vm_page.c revision 320605
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/11/sys/vm/vm_page.c 320605 2017-07-03 16:40:05Z 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/linker.h>
95#include <sys/malloc.h>
96#include <sys/mman.h>
97#include <sys/msgbuf.h>
98#include <sys/mutex.h>
99#include <sys/proc.h>
100#include <sys/rwlock.h>
101#include <sys/sbuf.h>
102#include <sys/smp.h>
103#include <sys/sysctl.h>
104#include <sys/vmmeter.h>
105#include <sys/vnode.h>
106
107#include <vm/vm.h>
108#include <vm/pmap.h>
109#include <vm/vm_param.h>
110#include <vm/vm_kern.h>
111#include <vm/vm_object.h>
112#include <vm/vm_page.h>
113#include <vm/vm_pageout.h>
114#include <vm/vm_pager.h>
115#include <vm/vm_phys.h>
116#include <vm/vm_radix.h>
117#include <vm/vm_reserv.h>
118#include <vm/vm_extern.h>
119#include <vm/uma.h>
120#include <vm/uma_int.h>
121
122#include <machine/md_var.h>
123
124/*
125 *	Associated with page of user-allocatable memory is a
126 *	page structure.
127 */
128
129struct vm_domain vm_dom[MAXMEMDOM];
130struct mtx_padalign vm_page_queue_free_mtx;
131
132struct mtx_padalign pa_lock[PA_LOCK_COUNT];
133
134vm_page_t vm_page_array;
135long vm_page_array_size;
136long first_page;
137int vm_page_zero_count;
138
139static int boot_pages = UMA_BOOT_PAGES;
140SYSCTL_INT(_vm, OID_AUTO, boot_pages, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
141    &boot_pages, 0,
142    "number of pages allocated for bootstrapping the VM system");
143
144static int pa_tryrelock_restart;
145SYSCTL_INT(_vm, OID_AUTO, tryrelock_restart, CTLFLAG_RD,
146    &pa_tryrelock_restart, 0, "Number of tryrelock restarts");
147
148static TAILQ_HEAD(, vm_page) blacklist_head;
149static int sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS);
150SYSCTL_PROC(_vm, OID_AUTO, page_blacklist, CTLTYPE_STRING | CTLFLAG_RD |
151    CTLFLAG_MPSAFE, NULL, 0, sysctl_vm_page_blacklist, "A", "Blacklist pages");
152
153/* Is the page daemon waiting for free pages? */
154static int vm_pageout_pages_needed;
155
156static uma_zone_t fakepg_zone;
157
158static void vm_page_alloc_check(vm_page_t m);
159static void vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits);
160static void vm_page_enqueue(uint8_t queue, vm_page_t m);
161static void vm_page_free_wakeup(void);
162static void vm_page_init_fakepg(void *dummy);
163static int vm_page_insert_after(vm_page_t m, vm_object_t object,
164    vm_pindex_t pindex, vm_page_t mpred);
165static void vm_page_insert_radixdone(vm_page_t m, vm_object_t object,
166    vm_page_t mpred);
167static int vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
168    vm_paddr_t high);
169
170SYSINIT(vm_page, SI_SUB_VM, SI_ORDER_SECOND, vm_page_init_fakepg, NULL);
171
172static void
173vm_page_init_fakepg(void *dummy)
174{
175
176	fakepg_zone = uma_zcreate("fakepg", sizeof(struct vm_page), NULL, NULL,
177	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE | UMA_ZONE_VM);
178}
179
180/* Make sure that u_long is at least 64 bits when PAGE_SIZE is 32K. */
181#if PAGE_SIZE == 32768
182#ifdef CTASSERT
183CTASSERT(sizeof(u_long) >= 8);
184#endif
185#endif
186
187/*
188 * Try to acquire a physical address lock while a pmap is locked.  If we
189 * fail to trylock we unlock and lock the pmap directly and cache the
190 * locked pa in *locked.  The caller should then restart their loop in case
191 * the virtual to physical mapping has changed.
192 */
193int
194vm_page_pa_tryrelock(pmap_t pmap, vm_paddr_t pa, vm_paddr_t *locked)
195{
196	vm_paddr_t lockpa;
197
198	lockpa = *locked;
199	*locked = pa;
200	if (lockpa) {
201		PA_LOCK_ASSERT(lockpa, MA_OWNED);
202		if (PA_LOCKPTR(pa) == PA_LOCKPTR(lockpa))
203			return (0);
204		PA_UNLOCK(lockpa);
205	}
206	if (PA_TRYLOCK(pa))
207		return (0);
208	PMAP_UNLOCK(pmap);
209	atomic_add_int(&pa_tryrelock_restart, 1);
210	PA_LOCK(pa);
211	PMAP_LOCK(pmap);
212	return (EAGAIN);
213}
214
215/*
216 *	vm_set_page_size:
217 *
218 *	Sets the page size, perhaps based upon the memory
219 *	size.  Must be called before any use of page-size
220 *	dependent functions.
221 */
222void
223vm_set_page_size(void)
224{
225	if (vm_cnt.v_page_size == 0)
226		vm_cnt.v_page_size = PAGE_SIZE;
227	if (((vm_cnt.v_page_size - 1) & vm_cnt.v_page_size) != 0)
228		panic("vm_set_page_size: page size not a power of two");
229}
230
231/*
232 *	vm_page_blacklist_next:
233 *
234 *	Find the next entry in the provided string of blacklist
235 *	addresses.  Entries are separated by space, comma, or newline.
236 *	If an invalid integer is encountered then the rest of the
237 *	string is skipped.  Updates the list pointer to the next
238 *	character, or NULL if the string is exhausted or invalid.
239 */
240static vm_paddr_t
241vm_page_blacklist_next(char **list, char *end)
242{
243	vm_paddr_t bad;
244	char *cp, *pos;
245
246	if (list == NULL || *list == NULL)
247		return (0);
248	if (**list =='\0') {
249		*list = NULL;
250		return (0);
251	}
252
253	/*
254	 * If there's no end pointer then the buffer is coming from
255	 * the kenv and we know it's null-terminated.
256	 */
257	if (end == NULL)
258		end = *list + strlen(*list);
259
260	/* Ensure that strtoq() won't walk off the end */
261	if (*end != '\0') {
262		if (*end == '\n' || *end == ' ' || *end  == ',')
263			*end = '\0';
264		else {
265			printf("Blacklist not terminated, skipping\n");
266			*list = NULL;
267			return (0);
268		}
269	}
270
271	for (pos = *list; *pos != '\0'; pos = cp) {
272		bad = strtoq(pos, &cp, 0);
273		if (*cp == '\0' || *cp == ' ' || *cp == ',' || *cp == '\n') {
274			if (bad == 0) {
275				if (++cp < end)
276					continue;
277				else
278					break;
279			}
280		} else
281			break;
282		if (*cp == '\0' || ++cp >= end)
283			*list = NULL;
284		else
285			*list = cp;
286		return (trunc_page(bad));
287	}
288	printf("Garbage in RAM blacklist, skipping\n");
289	*list = NULL;
290	return (0);
291}
292
293/*
294 *	vm_page_blacklist_check:
295 *
296 *	Iterate through the provided string of blacklist addresses, pulling
297 *	each entry out of the physical allocator free list and putting it
298 *	onto a list for reporting via the vm.page_blacklist sysctl.
299 */
300static void
301vm_page_blacklist_check(char *list, char *end)
302{
303	vm_paddr_t pa;
304	vm_page_t m;
305	char *next;
306	int ret;
307
308	next = list;
309	while (next != NULL) {
310		if ((pa = vm_page_blacklist_next(&next, end)) == 0)
311			continue;
312		m = vm_phys_paddr_to_vm_page(pa);
313		if (m == NULL)
314			continue;
315		mtx_lock(&vm_page_queue_free_mtx);
316		ret = vm_phys_unfree_page(m);
317		mtx_unlock(&vm_page_queue_free_mtx);
318		if (ret == TRUE) {
319			TAILQ_INSERT_TAIL(&blacklist_head, m, listq);
320			if (bootverbose)
321				printf("Skipping page with pa 0x%jx\n",
322				    (uintmax_t)pa);
323		}
324	}
325}
326
327/*
328 *	vm_page_blacklist_load:
329 *
330 *	Search for a special module named "ram_blacklist".  It'll be a
331 *	plain text file provided by the user via the loader directive
332 *	of the same name.
333 */
334static void
335vm_page_blacklist_load(char **list, char **end)
336{
337	void *mod;
338	u_char *ptr;
339	u_int len;
340
341	mod = NULL;
342	ptr = NULL;
343
344	mod = preload_search_by_type("ram_blacklist");
345	if (mod != NULL) {
346		ptr = preload_fetch_addr(mod);
347		len = preload_fetch_size(mod);
348        }
349	*list = ptr;
350	if (ptr != NULL)
351		*end = ptr + len;
352	else
353		*end = NULL;
354	return;
355}
356
357static int
358sysctl_vm_page_blacklist(SYSCTL_HANDLER_ARGS)
359{
360	vm_page_t m;
361	struct sbuf sbuf;
362	int error, first;
363
364	first = 1;
365	error = sysctl_wire_old_buffer(req, 0);
366	if (error != 0)
367		return (error);
368	sbuf_new_for_sysctl(&sbuf, NULL, 128, req);
369	TAILQ_FOREACH(m, &blacklist_head, listq) {
370		sbuf_printf(&sbuf, "%s%#jx", first ? "" : ",",
371		    (uintmax_t)m->phys_addr);
372		first = 0;
373	}
374	error = sbuf_finish(&sbuf);
375	sbuf_delete(&sbuf);
376	return (error);
377}
378
379static void
380vm_page_domain_init(struct vm_domain *vmd)
381{
382	struct vm_pagequeue *pq;
383	int i;
384
385	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_name) =
386	    "vm inactive pagequeue";
387	*__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_INACTIVE].pq_vcnt) =
388	    &vm_cnt.v_inactive_count;
389	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_name) =
390	    "vm active pagequeue";
391	*__DECONST(u_int **, &vmd->vmd_pagequeues[PQ_ACTIVE].pq_vcnt) =
392	    &vm_cnt.v_active_count;
393	*__DECONST(char **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_name) =
394	    "vm laundry pagequeue";
395	*__DECONST(int **, &vmd->vmd_pagequeues[PQ_LAUNDRY].pq_vcnt) =
396	    &vm_cnt.v_laundry_count;
397	vmd->vmd_page_count = 0;
398	vmd->vmd_free_count = 0;
399	vmd->vmd_segs = 0;
400	vmd->vmd_oom = FALSE;
401	for (i = 0; i < PQ_COUNT; i++) {
402		pq = &vmd->vmd_pagequeues[i];
403		TAILQ_INIT(&pq->pq_pl);
404		mtx_init(&pq->pq_mutex, pq->pq_name, "vm pagequeue",
405		    MTX_DEF | MTX_DUPOK);
406	}
407}
408
409/*
410 *	vm_page_startup:
411 *
412 *	Initializes the resident memory module.  Allocates physical memory for
413 *	bootstrapping UMA and some data structures that are used to manage
414 *	physical pages.  Initializes these structures, and populates the free
415 *	page queues.
416 */
417vm_offset_t
418vm_page_startup(vm_offset_t vaddr)
419{
420	vm_offset_t mapped;
421	vm_paddr_t high_avail, low_avail, page_range, size;
422	vm_paddr_t new_end;
423	int i;
424	vm_paddr_t pa;
425	vm_paddr_t last_pa;
426	char *list, *listend;
427	vm_paddr_t end;
428	vm_paddr_t biggestsize;
429	int biggestone;
430	int pages_per_zone;
431
432	biggestsize = 0;
433	biggestone = 0;
434	vaddr = round_page(vaddr);
435
436	for (i = 0; phys_avail[i + 1]; i += 2) {
437		phys_avail[i] = round_page(phys_avail[i]);
438		phys_avail[i + 1] = trunc_page(phys_avail[i + 1]);
439	}
440	for (i = 0; phys_avail[i + 1]; i += 2) {
441		size = phys_avail[i + 1] - phys_avail[i];
442		if (size > biggestsize) {
443			biggestone = i;
444			biggestsize = size;
445		}
446	}
447
448	end = phys_avail[biggestone+1];
449
450	/*
451	 * Initialize the page and queue locks.
452	 */
453	mtx_init(&vm_page_queue_free_mtx, "vm page free queue", NULL, MTX_DEF);
454	for (i = 0; i < PA_LOCK_COUNT; i++)
455		mtx_init(&pa_lock[i], "vm page", NULL, MTX_DEF);
456	for (i = 0; i < vm_ndomains; i++)
457		vm_page_domain_init(&vm_dom[i]);
458
459	/*
460	 * Almost all of the pages needed for bootstrapping UMA are used
461	 * for zone structures, so if the number of CPUs results in those
462	 * structures taking more than one page each, we set aside more pages
463	 * in proportion to the zone structure size.
464	 */
465	pages_per_zone = howmany(sizeof(struct uma_zone) +
466	    sizeof(struct uma_cache) * (mp_maxid + 1), UMA_SLAB_SIZE);
467	if (pages_per_zone > 1) {
468		/* Reserve more pages so that we don't run out. */
469		boot_pages = UMA_BOOT_PAGES_ZONES * pages_per_zone;
470	}
471
472	/*
473	 * Allocate memory for use when boot strapping the kernel memory
474	 * allocator.
475	 *
476	 * CTFLAG_RDTUN doesn't work during the early boot process, so we must
477	 * manually fetch the value.
478	 */
479	TUNABLE_INT_FETCH("vm.boot_pages", &boot_pages);
480	new_end = end - (boot_pages * UMA_SLAB_SIZE);
481	new_end = trunc_page(new_end);
482	mapped = pmap_map(&vaddr, new_end, end,
483	    VM_PROT_READ | VM_PROT_WRITE);
484	bzero((void *)mapped, end - new_end);
485	uma_startup((void *)mapped, boot_pages);
486
487#if defined(__aarch64__) || defined(__amd64__) || defined(__arm__) || \
488    defined(__i386__) || defined(__mips__)
489	/*
490	 * Allocate a bitmap to indicate that a random physical page
491	 * needs to be included in a minidump.
492	 *
493	 * The amd64 port needs this to indicate which direct map pages
494	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
495	 *
496	 * However, i386 still needs this workspace internally within the
497	 * minidump code.  In theory, they are not needed on i386, but are
498	 * included should the sf_buf code decide to use them.
499	 */
500	last_pa = 0;
501	for (i = 0; dump_avail[i + 1] != 0; i += 2)
502		if (dump_avail[i + 1] > last_pa)
503			last_pa = dump_avail[i + 1];
504	page_range = last_pa / PAGE_SIZE;
505	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
506	new_end -= vm_page_dump_size;
507	vm_page_dump = (void *)(uintptr_t)pmap_map(&vaddr, new_end,
508	    new_end + vm_page_dump_size, VM_PROT_READ | VM_PROT_WRITE);
509	bzero((void *)vm_page_dump, vm_page_dump_size);
510#endif
511#if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
512	/*
513	 * Include the UMA bootstrap pages and vm_page_dump in a crash dump.
514	 * When pmap_map() uses the direct map, they are not automatically
515	 * included.
516	 */
517	for (pa = new_end; pa < end; pa += PAGE_SIZE)
518		dump_add_page(pa);
519#endif
520	phys_avail[biggestone + 1] = new_end;
521#ifdef __amd64__
522	/*
523	 * Request that the physical pages underlying the message buffer be
524	 * included in a crash dump.  Since the message buffer is accessed
525	 * through the direct map, they are not automatically included.
526	 */
527	pa = DMAP_TO_PHYS((vm_offset_t)msgbufp->msg_ptr);
528	last_pa = pa + round_page(msgbufsize);
529	while (pa < last_pa) {
530		dump_add_page(pa);
531		pa += PAGE_SIZE;
532	}
533#endif
534	/*
535	 * Compute the number of pages of memory that will be available for
536	 * use, taking into account the overhead of a page structure per page.
537	 * In other words, solve
538	 *	"available physical memory" - round_page(page_range *
539	 *	    sizeof(struct vm_page)) = page_range * PAGE_SIZE
540	 * for page_range.
541	 */
542	low_avail = phys_avail[0];
543	high_avail = phys_avail[1];
544	for (i = 0; i < vm_phys_nsegs; i++) {
545		if (vm_phys_segs[i].start < low_avail)
546			low_avail = vm_phys_segs[i].start;
547		if (vm_phys_segs[i].end > high_avail)
548			high_avail = vm_phys_segs[i].end;
549	}
550	/* Skip the first chunk.  It is already accounted for. */
551	for (i = 2; phys_avail[i + 1] != 0; i += 2) {
552		if (phys_avail[i] < low_avail)
553			low_avail = phys_avail[i];
554		if (phys_avail[i + 1] > high_avail)
555			high_avail = phys_avail[i + 1];
556	}
557	first_page = low_avail / PAGE_SIZE;
558#ifdef VM_PHYSSEG_SPARSE
559	size = 0;
560	for (i = 0; i < vm_phys_nsegs; i++)
561		size += vm_phys_segs[i].end - vm_phys_segs[i].start;
562	for (i = 0; phys_avail[i + 1] != 0; i += 2)
563		size += phys_avail[i + 1] - phys_avail[i];
564#elif defined(VM_PHYSSEG_DENSE)
565	size = high_avail - low_avail;
566#else
567#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
568#endif
569
570#ifdef VM_PHYSSEG_DENSE
571	/*
572	 * In the VM_PHYSSEG_DENSE case, the number of pages can account for
573	 * the overhead of a page structure per page only if vm_page_array is
574	 * allocated from the last physical memory chunk.  Otherwise, we must
575	 * allocate page structures representing the physical memory
576	 * underlying vm_page_array, even though they will not be used.
577	 */
578	if (new_end != high_avail)
579		page_range = size / PAGE_SIZE;
580	else
581#endif
582	{
583		page_range = size / (PAGE_SIZE + sizeof(struct vm_page));
584
585		/*
586		 * If the partial bytes remaining are large enough for
587		 * a page (PAGE_SIZE) without a corresponding
588		 * 'struct vm_page', then new_end will contain an
589		 * extra page after subtracting the length of the VM
590		 * page array.  Compensate by subtracting an extra
591		 * page from new_end.
592		 */
593		if (size % (PAGE_SIZE + sizeof(struct vm_page)) >= PAGE_SIZE) {
594			if (new_end == high_avail)
595				high_avail -= PAGE_SIZE;
596			new_end -= PAGE_SIZE;
597		}
598	}
599	end = new_end;
600
601	/*
602	 * Reserve an unmapped guard page to trap access to vm_page_array[-1].
603	 * However, because this page is allocated from KVM, out-of-bounds
604	 * accesses using the direct map will not be trapped.
605	 */
606	vaddr += PAGE_SIZE;
607
608	/*
609	 * Allocate physical memory for the page structures, and map it.
610	 */
611	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
612	mapped = pmap_map(&vaddr, new_end, end,
613	    VM_PROT_READ | VM_PROT_WRITE);
614	vm_page_array = (vm_page_t) mapped;
615#if VM_NRESERVLEVEL > 0
616	/*
617	 * Allocate physical memory for the reservation management system's
618	 * data structures, and map it.
619	 */
620	if (high_avail == end)
621		high_avail = new_end;
622	new_end = vm_reserv_startup(&vaddr, new_end, high_avail);
623#endif
624#if defined(__aarch64__) || defined(__amd64__) || defined(__mips__)
625	/*
626	 * Include vm_page_array and vm_reserv_array in a crash dump.
627	 */
628	for (pa = new_end; pa < end; pa += PAGE_SIZE)
629		dump_add_page(pa);
630#endif
631	phys_avail[biggestone + 1] = new_end;
632
633	/*
634	 * Add physical memory segments corresponding to the available
635	 * physical pages.
636	 */
637	for (i = 0; phys_avail[i + 1] != 0; i += 2)
638		vm_phys_add_seg(phys_avail[i], phys_avail[i + 1]);
639
640	/*
641	 * Clear all of the page structures
642	 */
643	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
644	for (i = 0; i < page_range; i++)
645		vm_page_array[i].order = VM_NFREEORDER;
646	vm_page_array_size = page_range;
647
648	/*
649	 * Initialize the physical memory allocator.
650	 */
651	vm_phys_init();
652
653	/*
654	 * Add every available physical page that is not blacklisted to
655	 * the free lists.
656	 */
657	vm_cnt.v_page_count = 0;
658	vm_cnt.v_free_count = 0;
659	for (i = 0; phys_avail[i + 1] != 0; i += 2) {
660		pa = phys_avail[i];
661		last_pa = phys_avail[i + 1];
662		while (pa < last_pa) {
663			vm_phys_add_page(pa);
664			pa += PAGE_SIZE;
665		}
666	}
667
668	TAILQ_INIT(&blacklist_head);
669	vm_page_blacklist_load(&list, &listend);
670	vm_page_blacklist_check(list, listend);
671
672	list = kern_getenv("vm.blacklist");
673	vm_page_blacklist_check(list, NULL);
674
675	freeenv(list);
676#if VM_NRESERVLEVEL > 0
677	/*
678	 * Initialize the reservation management system.
679	 */
680	vm_reserv_init();
681#endif
682	return (vaddr);
683}
684
685void
686vm_page_reference(vm_page_t m)
687{
688
689	vm_page_aflag_set(m, PGA_REFERENCED);
690}
691
692/*
693 *	vm_page_busy_downgrade:
694 *
695 *	Downgrade an exclusive busy page into a single shared busy page.
696 */
697void
698vm_page_busy_downgrade(vm_page_t m)
699{
700	u_int x;
701	bool locked;
702
703	vm_page_assert_xbusied(m);
704	locked = mtx_owned(vm_page_lockptr(m));
705
706	for (;;) {
707		x = m->busy_lock;
708		x &= VPB_BIT_WAITERS;
709		if (x != 0 && !locked)
710			vm_page_lock(m);
711		if (atomic_cmpset_rel_int(&m->busy_lock,
712		    VPB_SINGLE_EXCLUSIVER | x, VPB_SHARERS_WORD(1)))
713			break;
714		if (x != 0 && !locked)
715			vm_page_unlock(m);
716	}
717	if (x != 0) {
718		wakeup(m);
719		if (!locked)
720			vm_page_unlock(m);
721	}
722}
723
724/*
725 *	vm_page_sbusied:
726 *
727 *	Return a positive value if the page is shared busied, 0 otherwise.
728 */
729int
730vm_page_sbusied(vm_page_t m)
731{
732	u_int x;
733
734	x = m->busy_lock;
735	return ((x & VPB_BIT_SHARED) != 0 && x != VPB_UNBUSIED);
736}
737
738/*
739 *	vm_page_sunbusy:
740 *
741 *	Shared unbusy a page.
742 */
743void
744vm_page_sunbusy(vm_page_t m)
745{
746	u_int x;
747
748	vm_page_assert_sbusied(m);
749
750	for (;;) {
751		x = m->busy_lock;
752		if (VPB_SHARERS(x) > 1) {
753			if (atomic_cmpset_int(&m->busy_lock, x,
754			    x - VPB_ONE_SHARER))
755				break;
756			continue;
757		}
758		if ((x & VPB_BIT_WAITERS) == 0) {
759			KASSERT(x == VPB_SHARERS_WORD(1),
760			    ("vm_page_sunbusy: invalid lock state"));
761			if (atomic_cmpset_int(&m->busy_lock,
762			    VPB_SHARERS_WORD(1), VPB_UNBUSIED))
763				break;
764			continue;
765		}
766		KASSERT(x == (VPB_SHARERS_WORD(1) | VPB_BIT_WAITERS),
767		    ("vm_page_sunbusy: invalid lock state for waiters"));
768
769		vm_page_lock(m);
770		if (!atomic_cmpset_int(&m->busy_lock, x, VPB_UNBUSIED)) {
771			vm_page_unlock(m);
772			continue;
773		}
774		wakeup(m);
775		vm_page_unlock(m);
776		break;
777	}
778}
779
780/*
781 *	vm_page_busy_sleep:
782 *
783 *	Sleep and release the page lock, using the page pointer as wchan.
784 *	This is used to implement the hard-path of busying mechanism.
785 *
786 *	The given page must be locked.
787 *
788 *	If nonshared is true, sleep only if the page is xbusy.
789 */
790void
791vm_page_busy_sleep(vm_page_t m, const char *wmesg, bool nonshared)
792{
793	u_int x;
794
795	vm_page_assert_locked(m);
796
797	x = m->busy_lock;
798	if (x == VPB_UNBUSIED || (nonshared && (x & VPB_BIT_SHARED) != 0) ||
799	    ((x & VPB_BIT_WAITERS) == 0 &&
800	    !atomic_cmpset_int(&m->busy_lock, x, x | VPB_BIT_WAITERS))) {
801		vm_page_unlock(m);
802		return;
803	}
804	msleep(m, vm_page_lockptr(m), PVM | PDROP, wmesg, 0);
805}
806
807/*
808 *	vm_page_trysbusy:
809 *
810 *	Try to shared busy a page.
811 *	If the operation succeeds 1 is returned otherwise 0.
812 *	The operation never sleeps.
813 */
814int
815vm_page_trysbusy(vm_page_t m)
816{
817	u_int x;
818
819	for (;;) {
820		x = m->busy_lock;
821		if ((x & VPB_BIT_SHARED) == 0)
822			return (0);
823		if (atomic_cmpset_acq_int(&m->busy_lock, x, x + VPB_ONE_SHARER))
824			return (1);
825	}
826}
827
828static void
829vm_page_xunbusy_locked(vm_page_t m)
830{
831
832	vm_page_assert_xbusied(m);
833	vm_page_assert_locked(m);
834
835	atomic_store_rel_int(&m->busy_lock, VPB_UNBUSIED);
836	/* There is a waiter, do wakeup() instead of vm_page_flash(). */
837	wakeup(m);
838}
839
840void
841vm_page_xunbusy_maybelocked(vm_page_t m)
842{
843	bool lockacq;
844
845	vm_page_assert_xbusied(m);
846
847	/*
848	 * Fast path for unbusy.  If it succeeds, we know that there
849	 * are no waiters, so we do not need a wakeup.
850	 */
851	if (atomic_cmpset_rel_int(&m->busy_lock, VPB_SINGLE_EXCLUSIVER,
852	    VPB_UNBUSIED))
853		return;
854
855	lockacq = !mtx_owned(vm_page_lockptr(m));
856	if (lockacq)
857		vm_page_lock(m);
858	vm_page_xunbusy_locked(m);
859	if (lockacq)
860		vm_page_unlock(m);
861}
862
863/*
864 *	vm_page_xunbusy_hard:
865 *
866 *	Called after the first try the exclusive unbusy of a page failed.
867 *	It is assumed that the waiters bit is on.
868 */
869void
870vm_page_xunbusy_hard(vm_page_t m)
871{
872
873	vm_page_assert_xbusied(m);
874
875	vm_page_lock(m);
876	vm_page_xunbusy_locked(m);
877	vm_page_unlock(m);
878}
879
880/*
881 *	vm_page_flash:
882 *
883 *	Wakeup anyone waiting for the page.
884 *	The ownership bits do not change.
885 *
886 *	The given page must be locked.
887 */
888void
889vm_page_flash(vm_page_t m)
890{
891	u_int x;
892
893	vm_page_lock_assert(m, MA_OWNED);
894
895	for (;;) {
896		x = m->busy_lock;
897		if ((x & VPB_BIT_WAITERS) == 0)
898			return;
899		if (atomic_cmpset_int(&m->busy_lock, x,
900		    x & (~VPB_BIT_WAITERS)))
901			break;
902	}
903	wakeup(m);
904}
905
906/*
907 * Keep page from being freed by the page daemon
908 * much of the same effect as wiring, except much lower
909 * overhead and should be used only for *very* temporary
910 * holding ("wiring").
911 */
912void
913vm_page_hold(vm_page_t mem)
914{
915
916	vm_page_lock_assert(mem, MA_OWNED);
917        mem->hold_count++;
918}
919
920void
921vm_page_unhold(vm_page_t mem)
922{
923
924	vm_page_lock_assert(mem, MA_OWNED);
925	KASSERT(mem->hold_count >= 1, ("vm_page_unhold: hold count < 0!!!"));
926	--mem->hold_count;
927	if (mem->hold_count == 0 && (mem->flags & PG_UNHOLDFREE) != 0)
928		vm_page_free_toq(mem);
929}
930
931/*
932 *	vm_page_unhold_pages:
933 *
934 *	Unhold each of the pages that is referenced by the given array.
935 */
936void
937vm_page_unhold_pages(vm_page_t *ma, int count)
938{
939	struct mtx *mtx, *new_mtx;
940
941	mtx = NULL;
942	for (; count != 0; count--) {
943		/*
944		 * Avoid releasing and reacquiring the same page lock.
945		 */
946		new_mtx = vm_page_lockptr(*ma);
947		if (mtx != new_mtx) {
948			if (mtx != NULL)
949				mtx_unlock(mtx);
950			mtx = new_mtx;
951			mtx_lock(mtx);
952		}
953		vm_page_unhold(*ma);
954		ma++;
955	}
956	if (mtx != NULL)
957		mtx_unlock(mtx);
958}
959
960vm_page_t
961PHYS_TO_VM_PAGE(vm_paddr_t pa)
962{
963	vm_page_t m;
964
965#ifdef VM_PHYSSEG_SPARSE
966	m = vm_phys_paddr_to_vm_page(pa);
967	if (m == NULL)
968		m = vm_phys_fictitious_to_vm_page(pa);
969	return (m);
970#elif defined(VM_PHYSSEG_DENSE)
971	long pi;
972
973	pi = atop(pa);
974	if (pi >= first_page && (pi - first_page) < vm_page_array_size) {
975		m = &vm_page_array[pi - first_page];
976		return (m);
977	}
978	return (vm_phys_fictitious_to_vm_page(pa));
979#else
980#error "Either VM_PHYSSEG_DENSE or VM_PHYSSEG_SPARSE must be defined."
981#endif
982}
983
984/*
985 *	vm_page_getfake:
986 *
987 *	Create a fictitious page with the specified physical address and
988 *	memory attribute.  The memory attribute is the only the machine-
989 *	dependent aspect of a fictitious page that must be initialized.
990 */
991vm_page_t
992vm_page_getfake(vm_paddr_t paddr, vm_memattr_t memattr)
993{
994	vm_page_t m;
995
996	m = uma_zalloc(fakepg_zone, M_WAITOK | M_ZERO);
997	vm_page_initfake(m, paddr, memattr);
998	return (m);
999}
1000
1001void
1002vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1003{
1004
1005	if ((m->flags & PG_FICTITIOUS) != 0) {
1006		/*
1007		 * The page's memattr might have changed since the
1008		 * previous initialization.  Update the pmap to the
1009		 * new memattr.
1010		 */
1011		goto memattr;
1012	}
1013	m->phys_addr = paddr;
1014	m->queue = PQ_NONE;
1015	/* Fictitious pages don't use "segind". */
1016	m->flags = PG_FICTITIOUS;
1017	/* Fictitious pages don't use "order" or "pool". */
1018	m->oflags = VPO_UNMANAGED;
1019	m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1020	m->wire_count = 1;
1021	pmap_page_init(m);
1022memattr:
1023	pmap_page_set_memattr(m, memattr);
1024}
1025
1026/*
1027 *	vm_page_putfake:
1028 *
1029 *	Release a fictitious page.
1030 */
1031void
1032vm_page_putfake(vm_page_t m)
1033{
1034
1035	KASSERT((m->oflags & VPO_UNMANAGED) != 0, ("managed %p", m));
1036	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1037	    ("vm_page_putfake: bad page %p", m));
1038	uma_zfree(fakepg_zone, m);
1039}
1040
1041/*
1042 *	vm_page_updatefake:
1043 *
1044 *	Update the given fictitious page to the specified physical address and
1045 *	memory attribute.
1046 */
1047void
1048vm_page_updatefake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1049{
1050
1051	KASSERT((m->flags & PG_FICTITIOUS) != 0,
1052	    ("vm_page_updatefake: bad page %p", m));
1053	m->phys_addr = paddr;
1054	pmap_page_set_memattr(m, memattr);
1055}
1056
1057/*
1058 *	vm_page_free:
1059 *
1060 *	Free a page.
1061 */
1062void
1063vm_page_free(vm_page_t m)
1064{
1065
1066	m->flags &= ~PG_ZERO;
1067	vm_page_free_toq(m);
1068}
1069
1070/*
1071 *	vm_page_free_zero:
1072 *
1073 *	Free a page to the zerod-pages queue
1074 */
1075void
1076vm_page_free_zero(vm_page_t m)
1077{
1078
1079	m->flags |= PG_ZERO;
1080	vm_page_free_toq(m);
1081}
1082
1083/*
1084 * Unbusy and handle the page queueing for a page from a getpages request that
1085 * was optionally read ahead or behind.
1086 */
1087void
1088vm_page_readahead_finish(vm_page_t m)
1089{
1090
1091	/* We shouldn't put invalid pages on queues. */
1092	KASSERT(m->valid != 0, ("%s: %p is invalid", __func__, m));
1093
1094	/*
1095	 * Since the page is not the actually needed one, whether it should
1096	 * be activated or deactivated is not obvious.  Empirical results
1097	 * have shown that deactivating the page is usually the best choice,
1098	 * unless the page is wanted by another thread.
1099	 */
1100	vm_page_lock(m);
1101	if ((m->busy_lock & VPB_BIT_WAITERS) != 0)
1102		vm_page_activate(m);
1103	else
1104		vm_page_deactivate(m);
1105	vm_page_unlock(m);
1106	vm_page_xunbusy(m);
1107}
1108
1109/*
1110 *	vm_page_sleep_if_busy:
1111 *
1112 *	Sleep and release the page queues lock if the page is busied.
1113 *	Returns TRUE if the thread slept.
1114 *
1115 *	The given page must be unlocked and object containing it must
1116 *	be locked.
1117 */
1118int
1119vm_page_sleep_if_busy(vm_page_t m, const char *msg)
1120{
1121	vm_object_t obj;
1122
1123	vm_page_lock_assert(m, MA_NOTOWNED);
1124	VM_OBJECT_ASSERT_WLOCKED(m->object);
1125
1126	if (vm_page_busied(m)) {
1127		/*
1128		 * The page-specific object must be cached because page
1129		 * identity can change during the sleep, causing the
1130		 * re-lock of a different object.
1131		 * It is assumed that a reference to the object is already
1132		 * held by the callers.
1133		 */
1134		obj = m->object;
1135		vm_page_lock(m);
1136		VM_OBJECT_WUNLOCK(obj);
1137		vm_page_busy_sleep(m, msg, false);
1138		VM_OBJECT_WLOCK(obj);
1139		return (TRUE);
1140	}
1141	return (FALSE);
1142}
1143
1144/*
1145 *	vm_page_dirty_KBI:		[ internal use only ]
1146 *
1147 *	Set all bits in the page's dirty field.
1148 *
1149 *	The object containing the specified page must be locked if the
1150 *	call is made from the machine-independent layer.
1151 *
1152 *	See vm_page_clear_dirty_mask().
1153 *
1154 *	This function should only be called by vm_page_dirty().
1155 */
1156void
1157vm_page_dirty_KBI(vm_page_t m)
1158{
1159
1160	/* Refer to this operation by its public name. */
1161	KASSERT(m->valid == VM_PAGE_BITS_ALL,
1162	    ("vm_page_dirty: page is invalid!"));
1163	m->dirty = VM_PAGE_BITS_ALL;
1164}
1165
1166/*
1167 *	vm_page_insert:		[ internal use only ]
1168 *
1169 *	Inserts the given mem entry into the object and object list.
1170 *
1171 *	The object must be locked.
1172 */
1173int
1174vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1175{
1176	vm_page_t mpred;
1177
1178	VM_OBJECT_ASSERT_WLOCKED(object);
1179	mpred = vm_radix_lookup_le(&object->rtree, pindex);
1180	return (vm_page_insert_after(m, object, pindex, mpred));
1181}
1182
1183/*
1184 *	vm_page_insert_after:
1185 *
1186 *	Inserts the page "m" into the specified object at offset "pindex".
1187 *
1188 *	The page "mpred" must immediately precede the offset "pindex" within
1189 *	the specified object.
1190 *
1191 *	The object must be locked.
1192 */
1193static int
1194vm_page_insert_after(vm_page_t m, vm_object_t object, vm_pindex_t pindex,
1195    vm_page_t mpred)
1196{
1197	vm_page_t msucc;
1198
1199	VM_OBJECT_ASSERT_WLOCKED(object);
1200	KASSERT(m->object == NULL,
1201	    ("vm_page_insert_after: page already inserted"));
1202	if (mpred != NULL) {
1203		KASSERT(mpred->object == object,
1204		    ("vm_page_insert_after: object doesn't contain mpred"));
1205		KASSERT(mpred->pindex < pindex,
1206		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1207		msucc = TAILQ_NEXT(mpred, listq);
1208	} else
1209		msucc = TAILQ_FIRST(&object->memq);
1210	if (msucc != NULL)
1211		KASSERT(msucc->pindex > pindex,
1212		    ("vm_page_insert_after: msucc doesn't succeed pindex"));
1213
1214	/*
1215	 * Record the object/offset pair in this page
1216	 */
1217	m->object = object;
1218	m->pindex = pindex;
1219
1220	/*
1221	 * Now link into the object's ordered list of backed pages.
1222	 */
1223	if (vm_radix_insert(&object->rtree, m)) {
1224		m->object = NULL;
1225		m->pindex = 0;
1226		return (1);
1227	}
1228	vm_page_insert_radixdone(m, object, mpred);
1229	return (0);
1230}
1231
1232/*
1233 *	vm_page_insert_radixdone:
1234 *
1235 *	Complete page "m" insertion into the specified object after the
1236 *	radix trie hooking.
1237 *
1238 *	The page "mpred" must precede the offset "m->pindex" within the
1239 *	specified object.
1240 *
1241 *	The object must be locked.
1242 */
1243static void
1244vm_page_insert_radixdone(vm_page_t m, vm_object_t object, vm_page_t mpred)
1245{
1246
1247	VM_OBJECT_ASSERT_WLOCKED(object);
1248	KASSERT(object != NULL && m->object == object,
1249	    ("vm_page_insert_radixdone: page %p has inconsistent object", m));
1250	if (mpred != NULL) {
1251		KASSERT(mpred->object == object,
1252		    ("vm_page_insert_after: object doesn't contain mpred"));
1253		KASSERT(mpred->pindex < m->pindex,
1254		    ("vm_page_insert_after: mpred doesn't precede pindex"));
1255	}
1256
1257	if (mpred != NULL)
1258		TAILQ_INSERT_AFTER(&object->memq, mpred, m, listq);
1259	else
1260		TAILQ_INSERT_HEAD(&object->memq, m, listq);
1261
1262	/*
1263	 * Show that the object has one more resident page.
1264	 */
1265	object->resident_page_count++;
1266
1267	/*
1268	 * Hold the vnode until the last page is released.
1269	 */
1270	if (object->resident_page_count == 1 && object->type == OBJT_VNODE)
1271		vhold(object->handle);
1272
1273	/*
1274	 * Since we are inserting a new and possibly dirty page,
1275	 * update the object's OBJ_MIGHTBEDIRTY flag.
1276	 */
1277	if (pmap_page_is_write_mapped(m))
1278		vm_object_set_writeable_dirty(object);
1279}
1280
1281/*
1282 *	vm_page_remove:
1283 *
1284 *	Removes the specified page from its containing object, but does not
1285 *	invalidate any backing storage.
1286 *
1287 *	The object must be locked.  The page must be locked if it is managed.
1288 */
1289void
1290vm_page_remove(vm_page_t m)
1291{
1292	vm_object_t object;
1293	vm_page_t mrem;
1294
1295	if ((m->oflags & VPO_UNMANAGED) == 0)
1296		vm_page_assert_locked(m);
1297	if ((object = m->object) == NULL)
1298		return;
1299	VM_OBJECT_ASSERT_WLOCKED(object);
1300	if (vm_page_xbusied(m))
1301		vm_page_xunbusy_maybelocked(m);
1302	mrem = vm_radix_remove(&object->rtree, m->pindex);
1303	KASSERT(mrem == m, ("removed page %p, expected page %p", mrem, m));
1304
1305	/*
1306	 * Now remove from the object's list of backed pages.
1307	 */
1308	TAILQ_REMOVE(&object->memq, m, listq);
1309
1310	/*
1311	 * And show that the object has one fewer resident page.
1312	 */
1313	object->resident_page_count--;
1314
1315	/*
1316	 * The vnode may now be recycled.
1317	 */
1318	if (object->resident_page_count == 0 && object->type == OBJT_VNODE)
1319		vdrop(object->handle);
1320
1321	m->object = NULL;
1322}
1323
1324/*
1325 *	vm_page_lookup:
1326 *
1327 *	Returns the page associated with the object/offset
1328 *	pair specified; if none is found, NULL is returned.
1329 *
1330 *	The object must be locked.
1331 */
1332vm_page_t
1333vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1334{
1335
1336	VM_OBJECT_ASSERT_LOCKED(object);
1337	return (vm_radix_lookup(&object->rtree, pindex));
1338}
1339
1340/*
1341 *	vm_page_find_least:
1342 *
1343 *	Returns the page associated with the object with least pindex
1344 *	greater than or equal to the parameter pindex, or NULL.
1345 *
1346 *	The object must be locked.
1347 */
1348vm_page_t
1349vm_page_find_least(vm_object_t object, vm_pindex_t pindex)
1350{
1351	vm_page_t m;
1352
1353	VM_OBJECT_ASSERT_LOCKED(object);
1354	if ((m = TAILQ_FIRST(&object->memq)) != NULL && m->pindex < pindex)
1355		m = vm_radix_lookup_ge(&object->rtree, pindex);
1356	return (m);
1357}
1358
1359/*
1360 * Returns the given page's successor (by pindex) within the object if it is
1361 * resident; if none is found, NULL is returned.
1362 *
1363 * The object must be locked.
1364 */
1365vm_page_t
1366vm_page_next(vm_page_t m)
1367{
1368	vm_page_t next;
1369
1370	VM_OBJECT_ASSERT_LOCKED(m->object);
1371	if ((next = TAILQ_NEXT(m, listq)) != NULL) {
1372		MPASS(next->object == m->object);
1373		if (next->pindex != m->pindex + 1)
1374			next = NULL;
1375	}
1376	return (next);
1377}
1378
1379/*
1380 * Returns the given page's predecessor (by pindex) within the object if it is
1381 * resident; if none is found, NULL is returned.
1382 *
1383 * The object must be locked.
1384 */
1385vm_page_t
1386vm_page_prev(vm_page_t m)
1387{
1388	vm_page_t prev;
1389
1390	VM_OBJECT_ASSERT_LOCKED(m->object);
1391	if ((prev = TAILQ_PREV(m, pglist, listq)) != NULL) {
1392		MPASS(prev->object == m->object);
1393		if (prev->pindex != m->pindex - 1)
1394			prev = NULL;
1395	}
1396	return (prev);
1397}
1398
1399/*
1400 * Uses the page mnew as a replacement for an existing page at index
1401 * pindex which must be already present in the object.
1402 *
1403 * The existing page must not be on a paging queue.
1404 */
1405vm_page_t
1406vm_page_replace(vm_page_t mnew, vm_object_t object, vm_pindex_t pindex)
1407{
1408	vm_page_t mold;
1409
1410	VM_OBJECT_ASSERT_WLOCKED(object);
1411	KASSERT(mnew->object == NULL,
1412	    ("vm_page_replace: page already in object"));
1413
1414	/*
1415	 * This function mostly follows vm_page_insert() and
1416	 * vm_page_remove() without the radix, object count and vnode
1417	 * dance.  Double check such functions for more comments.
1418	 */
1419
1420	mnew->object = object;
1421	mnew->pindex = pindex;
1422	mold = vm_radix_replace(&object->rtree, mnew);
1423	KASSERT(mold->queue == PQ_NONE,
1424	    ("vm_page_replace: mold is on a paging queue"));
1425
1426	/* Keep the resident page list in sorted order. */
1427	TAILQ_INSERT_AFTER(&object->memq, mold, mnew, listq);
1428	TAILQ_REMOVE(&object->memq, mold, listq);
1429
1430	mold->object = NULL;
1431	vm_page_xunbusy_maybelocked(mold);
1432
1433	/*
1434	 * The object's resident_page_count does not change because we have
1435	 * swapped one page for another, but OBJ_MIGHTBEDIRTY.
1436	 */
1437	if (pmap_page_is_write_mapped(mnew))
1438		vm_object_set_writeable_dirty(object);
1439	return (mold);
1440}
1441
1442/*
1443 *	vm_page_rename:
1444 *
1445 *	Move the given memory entry from its
1446 *	current object to the specified target object/offset.
1447 *
1448 *	Note: swap associated with the page must be invalidated by the move.  We
1449 *	      have to do this for several reasons:  (1) we aren't freeing the
1450 *	      page, (2) we are dirtying the page, (3) the VM system is probably
1451 *	      moving the page from object A to B, and will then later move
1452 *	      the backing store from A to B and we can't have a conflict.
1453 *
1454 *	Note: we *always* dirty the page.  It is necessary both for the
1455 *	      fact that we moved it, and because we may be invalidating
1456 *	      swap.
1457 *
1458 *	The objects must be locked.
1459 */
1460int
1461vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1462{
1463	vm_page_t mpred;
1464	vm_pindex_t opidx;
1465
1466	VM_OBJECT_ASSERT_WLOCKED(new_object);
1467
1468	mpred = vm_radix_lookup_le(&new_object->rtree, new_pindex);
1469	KASSERT(mpred == NULL || mpred->pindex != new_pindex,
1470	    ("vm_page_rename: pindex already renamed"));
1471
1472	/*
1473	 * Create a custom version of vm_page_insert() which does not depend
1474	 * by m_prev and can cheat on the implementation aspects of the
1475	 * function.
1476	 */
1477	opidx = m->pindex;
1478	m->pindex = new_pindex;
1479	if (vm_radix_insert(&new_object->rtree, m)) {
1480		m->pindex = opidx;
1481		return (1);
1482	}
1483
1484	/*
1485	 * The operation cannot fail anymore.  The removal must happen before
1486	 * the listq iterator is tainted.
1487	 */
1488	m->pindex = opidx;
1489	vm_page_lock(m);
1490	vm_page_remove(m);
1491
1492	/* Return back to the new pindex to complete vm_page_insert(). */
1493	m->pindex = new_pindex;
1494	m->object = new_object;
1495	vm_page_unlock(m);
1496	vm_page_insert_radixdone(m, new_object, mpred);
1497	vm_page_dirty(m);
1498	return (0);
1499}
1500
1501/*
1502 *	vm_page_alloc:
1503 *
1504 *	Allocate and return a page that is associated with the specified
1505 *	object and offset pair.  By default, this page is exclusive busied.
1506 *
1507 *	The caller must always specify an allocation class.
1508 *
1509 *	allocation classes:
1510 *	VM_ALLOC_NORMAL		normal process request
1511 *	VM_ALLOC_SYSTEM		system *really* needs a page
1512 *	VM_ALLOC_INTERRUPT	interrupt time request
1513 *
1514 *	optional allocation flags:
1515 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1516 *				intends to allocate
1517 *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1518 *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1519 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1520 *				should not be exclusive busy
1521 *	VM_ALLOC_SBUSY		shared busy the allocated page
1522 *	VM_ALLOC_WIRED		wire the allocated page
1523 *	VM_ALLOC_ZERO		prefer a zeroed page
1524 *
1525 *	This routine may not sleep.
1526 */
1527vm_page_t
1528vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int req)
1529{
1530	vm_page_t m, mpred;
1531	int flags, req_class;
1532
1533	mpred = NULL;	/* XXX: pacify gcc */
1534	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1535	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1536	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1537	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1538	    ("vm_page_alloc: inconsistent object(%p)/req(%x)", object, req));
1539	if (object != NULL)
1540		VM_OBJECT_ASSERT_WLOCKED(object);
1541
1542	if (__predict_false((req & VM_ALLOC_IFCACHED) != 0))
1543		return (NULL);
1544
1545	req_class = req & VM_ALLOC_CLASS_MASK;
1546
1547	/*
1548	 * The page daemon is allowed to dig deeper into the free page list.
1549	 */
1550	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1551		req_class = VM_ALLOC_SYSTEM;
1552
1553	if (object != NULL) {
1554		mpred = vm_radix_lookup_le(&object->rtree, pindex);
1555		KASSERT(mpred == NULL || mpred->pindex != pindex,
1556		   ("vm_page_alloc: pindex already allocated"));
1557	}
1558
1559	/*
1560	 * Allocate a page if the number of free pages exceeds the minimum
1561	 * for the request class.
1562	 */
1563	mtx_lock(&vm_page_queue_free_mtx);
1564	if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1565	    (req_class == VM_ALLOC_SYSTEM &&
1566	    vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1567	    (req_class == VM_ALLOC_INTERRUPT &&
1568	    vm_cnt.v_free_count > 0)) {
1569		/*
1570		 * Can we allocate the page from a reservation?
1571		 */
1572#if VM_NRESERVLEVEL > 0
1573		if (object == NULL || (object->flags & (OBJ_COLORED |
1574		    OBJ_FICTITIOUS)) != OBJ_COLORED || (m =
1575		    vm_reserv_alloc_page(object, pindex, mpred)) == NULL)
1576#endif
1577		{
1578			/*
1579			 * If not, allocate it from the free page queues.
1580			 */
1581			m = vm_phys_alloc_pages(object != NULL ?
1582			    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT, 0);
1583#if VM_NRESERVLEVEL > 0
1584			if (m == NULL && vm_reserv_reclaim_inactive()) {
1585				m = vm_phys_alloc_pages(object != NULL ?
1586				    VM_FREEPOOL_DEFAULT : VM_FREEPOOL_DIRECT,
1587				    0);
1588			}
1589#endif
1590		}
1591	} else {
1592		/*
1593		 * Not allocatable, give up.
1594		 */
1595		mtx_unlock(&vm_page_queue_free_mtx);
1596		atomic_add_int(&vm_pageout_deficit,
1597		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1598		pagedaemon_wakeup();
1599		return (NULL);
1600	}
1601
1602	/*
1603	 *  At this point we had better have found a good page.
1604	 */
1605	KASSERT(m != NULL, ("vm_page_alloc: missing page"));
1606	vm_phys_freecnt_adj(m, -1);
1607	if ((m->flags & PG_ZERO) != 0)
1608		vm_page_zero_count--;
1609	mtx_unlock(&vm_page_queue_free_mtx);
1610	vm_page_alloc_check(m);
1611
1612	/*
1613	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1614	 */
1615	flags = 0;
1616	if ((req & VM_ALLOC_ZERO) != 0)
1617		flags = PG_ZERO;
1618	flags &= m->flags;
1619	if ((req & VM_ALLOC_NODUMP) != 0)
1620		flags |= PG_NODUMP;
1621	m->flags = flags;
1622	m->aflags = 0;
1623	m->oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1624	    VPO_UNMANAGED : 0;
1625	m->busy_lock = VPB_UNBUSIED;
1626	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1627		m->busy_lock = VPB_SINGLE_EXCLUSIVER;
1628	if ((req & VM_ALLOC_SBUSY) != 0)
1629		m->busy_lock = VPB_SHARERS_WORD(1);
1630	if (req & VM_ALLOC_WIRED) {
1631		/*
1632		 * The page lock is not required for wiring a page until that
1633		 * page is inserted into the object.
1634		 */
1635		atomic_add_int(&vm_cnt.v_wire_count, 1);
1636		m->wire_count = 1;
1637	}
1638	m->act_count = 0;
1639
1640	if (object != NULL) {
1641		if (vm_page_insert_after(m, object, pindex, mpred)) {
1642			pagedaemon_wakeup();
1643			if (req & VM_ALLOC_WIRED) {
1644				atomic_subtract_int(&vm_cnt.v_wire_count, 1);
1645				m->wire_count = 0;
1646			}
1647			KASSERT(m->object == NULL, ("page %p has object", m));
1648			m->oflags = VPO_UNMANAGED;
1649			m->busy_lock = VPB_UNBUSIED;
1650			/* Don't change PG_ZERO. */
1651			vm_page_free_toq(m);
1652			return (NULL);
1653		}
1654
1655		/* Ignore device objects; the pager sets "memattr" for them. */
1656		if (object->memattr != VM_MEMATTR_DEFAULT &&
1657		    (object->flags & OBJ_FICTITIOUS) == 0)
1658			pmap_page_set_memattr(m, object->memattr);
1659	} else
1660		m->pindex = pindex;
1661
1662	/*
1663	 * Don't wakeup too often - wakeup the pageout daemon when
1664	 * we would be nearly out of memory.
1665	 */
1666	if (vm_paging_needed())
1667		pagedaemon_wakeup();
1668
1669	return (m);
1670}
1671
1672/*
1673 *	vm_page_alloc_contig:
1674 *
1675 *	Allocate a contiguous set of physical pages of the given size "npages"
1676 *	from the free lists.  All of the physical pages must be at or above
1677 *	the given physical address "low" and below the given physical address
1678 *	"high".  The given value "alignment" determines the alignment of the
1679 *	first physical page in the set.  If the given value "boundary" is
1680 *	non-zero, then the set of physical pages cannot cross any physical
1681 *	address boundary that is a multiple of that value.  Both "alignment"
1682 *	and "boundary" must be a power of two.
1683 *
1684 *	If the specified memory attribute, "memattr", is VM_MEMATTR_DEFAULT,
1685 *	then the memory attribute setting for the physical pages is configured
1686 *	to the object's memory attribute setting.  Otherwise, the memory
1687 *	attribute setting for the physical pages is configured to "memattr",
1688 *	overriding the object's memory attribute setting.  However, if the
1689 *	object's memory attribute setting is not VM_MEMATTR_DEFAULT, then the
1690 *	memory attribute setting for the physical pages cannot be configured
1691 *	to VM_MEMATTR_DEFAULT.
1692 *
1693 *	The specified object may not contain fictitious pages.
1694 *
1695 *	The caller must always specify an allocation class.
1696 *
1697 *	allocation classes:
1698 *	VM_ALLOC_NORMAL		normal process request
1699 *	VM_ALLOC_SYSTEM		system *really* needs a page
1700 *	VM_ALLOC_INTERRUPT	interrupt time request
1701 *
1702 *	optional allocation flags:
1703 *	VM_ALLOC_NOBUSY		do not exclusive busy the page
1704 *	VM_ALLOC_NODUMP		do not include the page in a kernel core dump
1705 *	VM_ALLOC_NOOBJ		page is not associated with an object and
1706 *				should not be exclusive busy
1707 *	VM_ALLOC_SBUSY		shared busy the allocated page
1708 *	VM_ALLOC_WIRED		wire the allocated page
1709 *	VM_ALLOC_ZERO		prefer a zeroed page
1710 *
1711 *	This routine may not sleep.
1712 */
1713vm_page_t
1714vm_page_alloc_contig(vm_object_t object, vm_pindex_t pindex, int req,
1715    u_long npages, vm_paddr_t low, vm_paddr_t high, u_long alignment,
1716    vm_paddr_t boundary, vm_memattr_t memattr)
1717{
1718	vm_page_t m, m_ret, mpred;
1719	u_int busy_lock, flags, oflags;
1720	int req_class;
1721
1722	mpred = NULL;	/* XXX: pacify gcc */
1723	KASSERT((object != NULL) == ((req & VM_ALLOC_NOOBJ) == 0) &&
1724	    (object != NULL || (req & VM_ALLOC_SBUSY) == 0) &&
1725	    ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) !=
1726	    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)),
1727	    ("vm_page_alloc_contig: inconsistent object(%p)/req(%x)", object,
1728	    req));
1729	if (object != NULL) {
1730		VM_OBJECT_ASSERT_WLOCKED(object);
1731		KASSERT((object->flags & OBJ_FICTITIOUS) == 0,
1732		    ("vm_page_alloc_contig: object %p has fictitious pages",
1733		    object));
1734	}
1735	KASSERT(npages > 0, ("vm_page_alloc_contig: npages is zero"));
1736	req_class = req & VM_ALLOC_CLASS_MASK;
1737
1738	/*
1739	 * The page daemon is allowed to dig deeper into the free page list.
1740	 */
1741	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1742		req_class = VM_ALLOC_SYSTEM;
1743
1744	if (object != NULL) {
1745		mpred = vm_radix_lookup_le(&object->rtree, pindex);
1746		KASSERT(mpred == NULL || mpred->pindex != pindex,
1747		    ("vm_page_alloc_contig: pindex already allocated"));
1748	}
1749
1750	/*
1751	 * Can we allocate the pages without the number of free pages falling
1752	 * below the lower bound for the allocation class?
1753	 */
1754	mtx_lock(&vm_page_queue_free_mtx);
1755	if (vm_cnt.v_free_count >= npages + vm_cnt.v_free_reserved ||
1756	    (req_class == VM_ALLOC_SYSTEM &&
1757	    vm_cnt.v_free_count >= npages + vm_cnt.v_interrupt_free_min) ||
1758	    (req_class == VM_ALLOC_INTERRUPT &&
1759	    vm_cnt.v_free_count >= npages)) {
1760		/*
1761		 * Can we allocate the pages from a reservation?
1762		 */
1763#if VM_NRESERVLEVEL > 0
1764retry:
1765		if (object == NULL || (object->flags & OBJ_COLORED) == 0 ||
1766		    (m_ret = vm_reserv_alloc_contig(object, pindex, npages,
1767		    low, high, alignment, boundary, mpred)) == NULL)
1768#endif
1769			/*
1770			 * If not, allocate them from the free page queues.
1771			 */
1772			m_ret = vm_phys_alloc_contig(npages, low, high,
1773			    alignment, boundary);
1774	} else {
1775		mtx_unlock(&vm_page_queue_free_mtx);
1776		atomic_add_int(&vm_pageout_deficit, npages);
1777		pagedaemon_wakeup();
1778		return (NULL);
1779	}
1780	if (m_ret != NULL) {
1781		vm_phys_freecnt_adj(m_ret, -npages);
1782		for (m = m_ret; m < &m_ret[npages]; m++)
1783			if ((m->flags & PG_ZERO) != 0)
1784				vm_page_zero_count--;
1785	} else {
1786#if VM_NRESERVLEVEL > 0
1787		if (vm_reserv_reclaim_contig(npages, low, high, alignment,
1788		    boundary))
1789			goto retry;
1790#endif
1791	}
1792	mtx_unlock(&vm_page_queue_free_mtx);
1793	if (m_ret == NULL)
1794		return (NULL);
1795	for (m = m_ret; m < &m_ret[npages]; m++)
1796		vm_page_alloc_check(m);
1797
1798	/*
1799	 * Initialize the pages.  Only the PG_ZERO flag is inherited.
1800	 */
1801	flags = 0;
1802	if ((req & VM_ALLOC_ZERO) != 0)
1803		flags = PG_ZERO;
1804	if ((req & VM_ALLOC_NODUMP) != 0)
1805		flags |= PG_NODUMP;
1806	oflags = object == NULL || (object->flags & OBJ_UNMANAGED) != 0 ?
1807	    VPO_UNMANAGED : 0;
1808	busy_lock = VPB_UNBUSIED;
1809	if ((req & (VM_ALLOC_NOBUSY | VM_ALLOC_NOOBJ | VM_ALLOC_SBUSY)) == 0)
1810		busy_lock = VPB_SINGLE_EXCLUSIVER;
1811	if ((req & VM_ALLOC_SBUSY) != 0)
1812		busy_lock = VPB_SHARERS_WORD(1);
1813	if ((req & VM_ALLOC_WIRED) != 0)
1814		atomic_add_int(&vm_cnt.v_wire_count, npages);
1815	if (object != NULL) {
1816		if (object->memattr != VM_MEMATTR_DEFAULT &&
1817		    memattr == VM_MEMATTR_DEFAULT)
1818			memattr = object->memattr;
1819	}
1820	for (m = m_ret; m < &m_ret[npages]; m++) {
1821		m->aflags = 0;
1822		m->flags = (m->flags | PG_NODUMP) & flags;
1823		m->busy_lock = busy_lock;
1824		if ((req & VM_ALLOC_WIRED) != 0)
1825			m->wire_count = 1;
1826		m->act_count = 0;
1827		m->oflags = oflags;
1828		if (object != NULL) {
1829			if (vm_page_insert_after(m, object, pindex, mpred)) {
1830				pagedaemon_wakeup();
1831				if ((req & VM_ALLOC_WIRED) != 0)
1832					atomic_subtract_int(
1833					    &vm_cnt.v_wire_count, npages);
1834				KASSERT(m->object == NULL,
1835				    ("page %p has object", m));
1836				mpred = m;
1837				for (m = m_ret; m < &m_ret[npages]; m++) {
1838					if (m <= mpred &&
1839					    (req & VM_ALLOC_WIRED) != 0)
1840						m->wire_count = 0;
1841					m->oflags = VPO_UNMANAGED;
1842					m->busy_lock = VPB_UNBUSIED;
1843					/* Don't change PG_ZERO. */
1844					vm_page_free_toq(m);
1845				}
1846				return (NULL);
1847			}
1848			mpred = m;
1849		} else
1850			m->pindex = pindex;
1851		if (memattr != VM_MEMATTR_DEFAULT)
1852			pmap_page_set_memattr(m, memattr);
1853		pindex++;
1854	}
1855	if (vm_paging_needed())
1856		pagedaemon_wakeup();
1857	return (m_ret);
1858}
1859
1860/*
1861 * Check a page that has been freshly dequeued from a freelist.
1862 */
1863static void
1864vm_page_alloc_check(vm_page_t m)
1865{
1866
1867	KASSERT(m->object == NULL, ("page %p has object", m));
1868	KASSERT(m->queue == PQ_NONE,
1869	    ("page %p has unexpected queue %d", m, m->queue));
1870	KASSERT(m->wire_count == 0, ("page %p is wired", m));
1871	KASSERT(m->hold_count == 0, ("page %p is held", m));
1872	KASSERT(!vm_page_busied(m), ("page %p is busy", m));
1873	KASSERT(m->dirty == 0, ("page %p is dirty", m));
1874	KASSERT(pmap_page_get_memattr(m) == VM_MEMATTR_DEFAULT,
1875	    ("page %p has unexpected memattr %d",
1876	    m, pmap_page_get_memattr(m)));
1877	KASSERT(m->valid == 0, ("free page %p is valid", m));
1878}
1879
1880/*
1881 * 	vm_page_alloc_freelist:
1882 *
1883 *	Allocate a physical page from the specified free page list.
1884 *
1885 *	The caller must always specify an allocation class.
1886 *
1887 *	allocation classes:
1888 *	VM_ALLOC_NORMAL		normal process request
1889 *	VM_ALLOC_SYSTEM		system *really* needs a page
1890 *	VM_ALLOC_INTERRUPT	interrupt time request
1891 *
1892 *	optional allocation flags:
1893 *	VM_ALLOC_COUNT(number)	the number of additional pages that the caller
1894 *				intends to allocate
1895 *	VM_ALLOC_WIRED		wire the allocated page
1896 *	VM_ALLOC_ZERO		prefer a zeroed page
1897 *
1898 *	This routine may not sleep.
1899 */
1900vm_page_t
1901vm_page_alloc_freelist(int flind, int req)
1902{
1903	vm_page_t m;
1904	u_int flags;
1905	int req_class;
1906
1907	req_class = req & VM_ALLOC_CLASS_MASK;
1908
1909	/*
1910	 * The page daemon is allowed to dig deeper into the free page list.
1911	 */
1912	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
1913		req_class = VM_ALLOC_SYSTEM;
1914
1915	/*
1916	 * Do not allocate reserved pages unless the req has asked for it.
1917	 */
1918	mtx_lock(&vm_page_queue_free_mtx);
1919	if (vm_cnt.v_free_count > vm_cnt.v_free_reserved ||
1920	    (req_class == VM_ALLOC_SYSTEM &&
1921	    vm_cnt.v_free_count > vm_cnt.v_interrupt_free_min) ||
1922	    (req_class == VM_ALLOC_INTERRUPT &&
1923	    vm_cnt.v_free_count > 0))
1924		m = vm_phys_alloc_freelist_pages(flind, VM_FREEPOOL_DIRECT, 0);
1925	else {
1926		mtx_unlock(&vm_page_queue_free_mtx);
1927		atomic_add_int(&vm_pageout_deficit,
1928		    max((u_int)req >> VM_ALLOC_COUNT_SHIFT, 1));
1929		pagedaemon_wakeup();
1930		return (NULL);
1931	}
1932	if (m == NULL) {
1933		mtx_unlock(&vm_page_queue_free_mtx);
1934		return (NULL);
1935	}
1936	vm_phys_freecnt_adj(m, -1);
1937	if ((m->flags & PG_ZERO) != 0)
1938		vm_page_zero_count--;
1939	mtx_unlock(&vm_page_queue_free_mtx);
1940	vm_page_alloc_check(m);
1941
1942	/*
1943	 * Initialize the page.  Only the PG_ZERO flag is inherited.
1944	 */
1945	m->aflags = 0;
1946	flags = 0;
1947	if ((req & VM_ALLOC_ZERO) != 0)
1948		flags = PG_ZERO;
1949	m->flags &= flags;
1950	if ((req & VM_ALLOC_WIRED) != 0) {
1951		/*
1952		 * The page lock is not required for wiring a page that does
1953		 * not belong to an object.
1954		 */
1955		atomic_add_int(&vm_cnt.v_wire_count, 1);
1956		m->wire_count = 1;
1957	}
1958	/* Unmanaged pages don't use "act_count". */
1959	m->oflags = VPO_UNMANAGED;
1960	if (vm_paging_needed())
1961		pagedaemon_wakeup();
1962	return (m);
1963}
1964
1965#define	VPSC_ANY	0	/* No restrictions. */
1966#define	VPSC_NORESERV	1	/* Skip reservations; implies VPSC_NOSUPER. */
1967#define	VPSC_NOSUPER	2	/* Skip superpages. */
1968
1969/*
1970 *	vm_page_scan_contig:
1971 *
1972 *	Scan vm_page_array[] between the specified entries "m_start" and
1973 *	"m_end" for a run of contiguous physical pages that satisfy the
1974 *	specified conditions, and return the lowest page in the run.  The
1975 *	specified "alignment" determines the alignment of the lowest physical
1976 *	page in the run.  If the specified "boundary" is non-zero, then the
1977 *	run of physical pages cannot span a physical address that is a
1978 *	multiple of "boundary".
1979 *
1980 *	"m_end" is never dereferenced, so it need not point to a vm_page
1981 *	structure within vm_page_array[].
1982 *
1983 *	"npages" must be greater than zero.  "m_start" and "m_end" must not
1984 *	span a hole (or discontiguity) in the physical address space.  Both
1985 *	"alignment" and "boundary" must be a power of two.
1986 */
1987vm_page_t
1988vm_page_scan_contig(u_long npages, vm_page_t m_start, vm_page_t m_end,
1989    u_long alignment, vm_paddr_t boundary, int options)
1990{
1991	struct mtx *m_mtx, *new_mtx;
1992	vm_object_t object;
1993	vm_paddr_t pa;
1994	vm_page_t m, m_run;
1995#if VM_NRESERVLEVEL > 0
1996	int level;
1997#endif
1998	int m_inc, order, run_ext, run_len;
1999
2000	KASSERT(npages > 0, ("npages is 0"));
2001	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2002	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2003	m_run = NULL;
2004	run_len = 0;
2005	m_mtx = NULL;
2006	for (m = m_start; m < m_end && run_len < npages; m += m_inc) {
2007		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2008		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2009
2010		/*
2011		 * If the current page would be the start of a run, check its
2012		 * physical address against the end, alignment, and boundary
2013		 * conditions.  If it doesn't satisfy these conditions, either
2014		 * terminate the scan or advance to the next page that
2015		 * satisfies the failed condition.
2016		 */
2017		if (run_len == 0) {
2018			KASSERT(m_run == NULL, ("m_run != NULL"));
2019			if (m + npages > m_end)
2020				break;
2021			pa = VM_PAGE_TO_PHYS(m);
2022			if ((pa & (alignment - 1)) != 0) {
2023				m_inc = atop(roundup2(pa, alignment) - pa);
2024				continue;
2025			}
2026			if (rounddown2(pa ^ (pa + ptoa(npages) - 1),
2027			    boundary) != 0) {
2028				m_inc = atop(roundup2(pa, boundary) - pa);
2029				continue;
2030			}
2031		} else
2032			KASSERT(m_run != NULL, ("m_run == NULL"));
2033
2034		/*
2035		 * Avoid releasing and reacquiring the same page lock.
2036		 */
2037		new_mtx = vm_page_lockptr(m);
2038		if (m_mtx != new_mtx) {
2039			if (m_mtx != NULL)
2040				mtx_unlock(m_mtx);
2041			m_mtx = new_mtx;
2042			mtx_lock(m_mtx);
2043		}
2044		m_inc = 1;
2045retry:
2046		if (m->wire_count != 0 || m->hold_count != 0)
2047			run_ext = 0;
2048#if VM_NRESERVLEVEL > 0
2049		else if ((level = vm_reserv_level(m)) >= 0 &&
2050		    (options & VPSC_NORESERV) != 0) {
2051			run_ext = 0;
2052			/* Advance to the end of the reservation. */
2053			pa = VM_PAGE_TO_PHYS(m);
2054			m_inc = atop(roundup2(pa + 1, vm_reserv_size(level)) -
2055			    pa);
2056		}
2057#endif
2058		else if ((object = m->object) != NULL) {
2059			/*
2060			 * The page is considered eligible for relocation if
2061			 * and only if it could be laundered or reclaimed by
2062			 * the page daemon.
2063			 */
2064			if (!VM_OBJECT_TRYRLOCK(object)) {
2065				mtx_unlock(m_mtx);
2066				VM_OBJECT_RLOCK(object);
2067				mtx_lock(m_mtx);
2068				if (m->object != object) {
2069					/*
2070					 * The page may have been freed.
2071					 */
2072					VM_OBJECT_RUNLOCK(object);
2073					goto retry;
2074				} else if (m->wire_count != 0 ||
2075				    m->hold_count != 0) {
2076					run_ext = 0;
2077					goto unlock;
2078				}
2079			}
2080			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2081			    ("page %p is PG_UNHOLDFREE", m));
2082			/* Don't care: PG_NODUMP, PG_ZERO. */
2083			if (object->type != OBJT_DEFAULT &&
2084			    object->type != OBJT_SWAP &&
2085			    object->type != OBJT_VNODE) {
2086				run_ext = 0;
2087#if VM_NRESERVLEVEL > 0
2088			} else if ((options & VPSC_NOSUPER) != 0 &&
2089			    (level = vm_reserv_level_iffullpop(m)) >= 0) {
2090				run_ext = 0;
2091				/* Advance to the end of the superpage. */
2092				pa = VM_PAGE_TO_PHYS(m);
2093				m_inc = atop(roundup2(pa + 1,
2094				    vm_reserv_size(level)) - pa);
2095#endif
2096			} else if (object->memattr == VM_MEMATTR_DEFAULT &&
2097			    m->queue != PQ_NONE && !vm_page_busied(m)) {
2098				/*
2099				 * The page is allocated but eligible for
2100				 * relocation.  Extend the current run by one
2101				 * page.
2102				 */
2103				KASSERT(pmap_page_get_memattr(m) ==
2104				    VM_MEMATTR_DEFAULT,
2105				    ("page %p has an unexpected memattr", m));
2106				KASSERT((m->oflags & (VPO_SWAPINPROG |
2107				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2108				    ("page %p has unexpected oflags", m));
2109				/* Don't care: VPO_NOSYNC. */
2110				run_ext = 1;
2111			} else
2112				run_ext = 0;
2113unlock:
2114			VM_OBJECT_RUNLOCK(object);
2115#if VM_NRESERVLEVEL > 0
2116		} else if (level >= 0) {
2117			/*
2118			 * The page is reserved but not yet allocated.  In
2119			 * other words, it is still free.  Extend the current
2120			 * run by one page.
2121			 */
2122			run_ext = 1;
2123#endif
2124		} else if ((order = m->order) < VM_NFREEORDER) {
2125			/*
2126			 * The page is enqueued in the physical memory
2127			 * allocator's free page queues.  Moreover, it is the
2128			 * first page in a power-of-two-sized run of
2129			 * contiguous free pages.  Add these pages to the end
2130			 * of the current run, and jump ahead.
2131			 */
2132			run_ext = 1 << order;
2133			m_inc = 1 << order;
2134		} else {
2135			/*
2136			 * Skip the page for one of the following reasons: (1)
2137			 * It is enqueued in the physical memory allocator's
2138			 * free page queues.  However, it is not the first
2139			 * page in a run of contiguous free pages.  (This case
2140			 * rarely occurs because the scan is performed in
2141			 * ascending order.) (2) It is not reserved, and it is
2142			 * transitioning from free to allocated.  (Conversely,
2143			 * the transition from allocated to free for managed
2144			 * pages is blocked by the page lock.) (3) It is
2145			 * allocated but not contained by an object and not
2146			 * wired, e.g., allocated by Xen's balloon driver.
2147			 */
2148			run_ext = 0;
2149		}
2150
2151		/*
2152		 * Extend or reset the current run of pages.
2153		 */
2154		if (run_ext > 0) {
2155			if (run_len == 0)
2156				m_run = m;
2157			run_len += run_ext;
2158		} else {
2159			if (run_len > 0) {
2160				m_run = NULL;
2161				run_len = 0;
2162			}
2163		}
2164	}
2165	if (m_mtx != NULL)
2166		mtx_unlock(m_mtx);
2167	if (run_len >= npages)
2168		return (m_run);
2169	return (NULL);
2170}
2171
2172/*
2173 *	vm_page_reclaim_run:
2174 *
2175 *	Try to relocate each of the allocated virtual pages within the
2176 *	specified run of physical pages to a new physical address.  Free the
2177 *	physical pages underlying the relocated virtual pages.  A virtual page
2178 *	is relocatable if and only if it could be laundered or reclaimed by
2179 *	the page daemon.  Whenever possible, a virtual page is relocated to a
2180 *	physical address above "high".
2181 *
2182 *	Returns 0 if every physical page within the run was already free or
2183 *	just freed by a successful relocation.  Otherwise, returns a non-zero
2184 *	value indicating why the last attempt to relocate a virtual page was
2185 *	unsuccessful.
2186 *
2187 *	"req_class" must be an allocation class.
2188 */
2189static int
2190vm_page_reclaim_run(int req_class, u_long npages, vm_page_t m_run,
2191    vm_paddr_t high)
2192{
2193	struct mtx *m_mtx, *new_mtx;
2194	struct spglist free;
2195	vm_object_t object;
2196	vm_paddr_t pa;
2197	vm_page_t m, m_end, m_new;
2198	int error, order, req;
2199
2200	KASSERT((req_class & VM_ALLOC_CLASS_MASK) == req_class,
2201	    ("req_class is not an allocation class"));
2202	SLIST_INIT(&free);
2203	error = 0;
2204	m = m_run;
2205	m_end = m_run + npages;
2206	m_mtx = NULL;
2207	for (; error == 0 && m < m_end; m++) {
2208		KASSERT((m->flags & (PG_FICTITIOUS | PG_MARKER)) == 0,
2209		    ("page %p is PG_FICTITIOUS or PG_MARKER", m));
2210
2211		/*
2212		 * Avoid releasing and reacquiring the same page lock.
2213		 */
2214		new_mtx = vm_page_lockptr(m);
2215		if (m_mtx != new_mtx) {
2216			if (m_mtx != NULL)
2217				mtx_unlock(m_mtx);
2218			m_mtx = new_mtx;
2219			mtx_lock(m_mtx);
2220		}
2221retry:
2222		if (m->wire_count != 0 || m->hold_count != 0)
2223			error = EBUSY;
2224		else if ((object = m->object) != NULL) {
2225			/*
2226			 * The page is relocated if and only if it could be
2227			 * laundered or reclaimed by the page daemon.
2228			 */
2229			if (!VM_OBJECT_TRYWLOCK(object)) {
2230				mtx_unlock(m_mtx);
2231				VM_OBJECT_WLOCK(object);
2232				mtx_lock(m_mtx);
2233				if (m->object != object) {
2234					/*
2235					 * The page may have been freed.
2236					 */
2237					VM_OBJECT_WUNLOCK(object);
2238					goto retry;
2239				} else if (m->wire_count != 0 ||
2240				    m->hold_count != 0) {
2241					error = EBUSY;
2242					goto unlock;
2243				}
2244			}
2245			KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2246			    ("page %p is PG_UNHOLDFREE", m));
2247			/* Don't care: PG_NODUMP, PG_ZERO. */
2248			if (object->type != OBJT_DEFAULT &&
2249			    object->type != OBJT_SWAP &&
2250			    object->type != OBJT_VNODE)
2251				error = EINVAL;
2252			else if (object->memattr != VM_MEMATTR_DEFAULT)
2253				error = EINVAL;
2254			else if (m->queue != PQ_NONE && !vm_page_busied(m)) {
2255				KASSERT(pmap_page_get_memattr(m) ==
2256				    VM_MEMATTR_DEFAULT,
2257				    ("page %p has an unexpected memattr", m));
2258				KASSERT((m->oflags & (VPO_SWAPINPROG |
2259				    VPO_SWAPSLEEP | VPO_UNMANAGED)) == 0,
2260				    ("page %p has unexpected oflags", m));
2261				/* Don't care: VPO_NOSYNC. */
2262				if (m->valid != 0) {
2263					/*
2264					 * First, try to allocate a new page
2265					 * that is above "high".  Failing
2266					 * that, try to allocate a new page
2267					 * that is below "m_run".  Allocate
2268					 * the new page between the end of
2269					 * "m_run" and "high" only as a last
2270					 * resort.
2271					 */
2272					req = req_class | VM_ALLOC_NOOBJ;
2273					if ((m->flags & PG_NODUMP) != 0)
2274						req |= VM_ALLOC_NODUMP;
2275					if (trunc_page(high) !=
2276					    ~(vm_paddr_t)PAGE_MASK) {
2277						m_new = vm_page_alloc_contig(
2278						    NULL, 0, req, 1,
2279						    round_page(high),
2280						    ~(vm_paddr_t)0,
2281						    PAGE_SIZE, 0,
2282						    VM_MEMATTR_DEFAULT);
2283					} else
2284						m_new = NULL;
2285					if (m_new == NULL) {
2286						pa = VM_PAGE_TO_PHYS(m_run);
2287						m_new = vm_page_alloc_contig(
2288						    NULL, 0, req, 1,
2289						    0, pa - 1, PAGE_SIZE, 0,
2290						    VM_MEMATTR_DEFAULT);
2291					}
2292					if (m_new == NULL) {
2293						pa += ptoa(npages);
2294						m_new = vm_page_alloc_contig(
2295						    NULL, 0, req, 1,
2296						    pa, high, PAGE_SIZE, 0,
2297						    VM_MEMATTR_DEFAULT);
2298					}
2299					if (m_new == NULL) {
2300						error = ENOMEM;
2301						goto unlock;
2302					}
2303					KASSERT(m_new->wire_count == 0,
2304					    ("page %p is wired", m));
2305
2306					/*
2307					 * Replace "m" with the new page.  For
2308					 * vm_page_replace(), "m" must be busy
2309					 * and dequeued.  Finally, change "m"
2310					 * as if vm_page_free() was called.
2311					 */
2312					if (object->ref_count != 0)
2313						pmap_remove_all(m);
2314					m_new->aflags = m->aflags;
2315					KASSERT(m_new->oflags == VPO_UNMANAGED,
2316					    ("page %p is managed", m));
2317					m_new->oflags = m->oflags & VPO_NOSYNC;
2318					pmap_copy_page(m, m_new);
2319					m_new->valid = m->valid;
2320					m_new->dirty = m->dirty;
2321					m->flags &= ~PG_ZERO;
2322					vm_page_xbusy(m);
2323					vm_page_remque(m);
2324					vm_page_replace_checked(m_new, object,
2325					    m->pindex, m);
2326					m->valid = 0;
2327					vm_page_undirty(m);
2328
2329					/*
2330					 * The new page must be deactivated
2331					 * before the object is unlocked.
2332					 */
2333					new_mtx = vm_page_lockptr(m_new);
2334					if (m_mtx != new_mtx) {
2335						mtx_unlock(m_mtx);
2336						m_mtx = new_mtx;
2337						mtx_lock(m_mtx);
2338					}
2339					vm_page_deactivate(m_new);
2340				} else {
2341					m->flags &= ~PG_ZERO;
2342					vm_page_remque(m);
2343					vm_page_remove(m);
2344					KASSERT(m->dirty == 0,
2345					    ("page %p is dirty", m));
2346				}
2347				SLIST_INSERT_HEAD(&free, m, plinks.s.ss);
2348			} else
2349				error = EBUSY;
2350unlock:
2351			VM_OBJECT_WUNLOCK(object);
2352		} else {
2353			mtx_lock(&vm_page_queue_free_mtx);
2354			order = m->order;
2355			if (order < VM_NFREEORDER) {
2356				/*
2357				 * The page is enqueued in the physical memory
2358				 * allocator's free page queues.  Moreover, it
2359				 * is the first page in a power-of-two-sized
2360				 * run of contiguous free pages.  Jump ahead
2361				 * to the last page within that run, and
2362				 * continue from there.
2363				 */
2364				m += (1 << order) - 1;
2365			}
2366#if VM_NRESERVLEVEL > 0
2367			else if (vm_reserv_is_page_free(m))
2368				order = 0;
2369#endif
2370			mtx_unlock(&vm_page_queue_free_mtx);
2371			if (order == VM_NFREEORDER)
2372				error = EINVAL;
2373		}
2374	}
2375	if (m_mtx != NULL)
2376		mtx_unlock(m_mtx);
2377	if ((m = SLIST_FIRST(&free)) != NULL) {
2378		mtx_lock(&vm_page_queue_free_mtx);
2379		do {
2380			SLIST_REMOVE_HEAD(&free, plinks.s.ss);
2381			vm_phys_freecnt_adj(m, 1);
2382#if VM_NRESERVLEVEL > 0
2383			if (!vm_reserv_free_page(m))
2384#else
2385			if (true)
2386#endif
2387				vm_phys_free_pages(m, 0);
2388		} while ((m = SLIST_FIRST(&free)) != NULL);
2389		vm_page_zero_idle_wakeup();
2390		vm_page_free_wakeup();
2391		mtx_unlock(&vm_page_queue_free_mtx);
2392	}
2393	return (error);
2394}
2395
2396#define	NRUNS	16
2397
2398CTASSERT(powerof2(NRUNS));
2399
2400#define	RUN_INDEX(count)	((count) & (NRUNS - 1))
2401
2402#define	MIN_RECLAIM	8
2403
2404/*
2405 *	vm_page_reclaim_contig:
2406 *
2407 *	Reclaim allocated, contiguous physical memory satisfying the specified
2408 *	conditions by relocating the virtual pages using that physical memory.
2409 *	Returns true if reclamation is successful and false otherwise.  Since
2410 *	relocation requires the allocation of physical pages, reclamation may
2411 *	fail due to a shortage of free pages.  When reclamation fails, callers
2412 *	are expected to perform VM_WAIT before retrying a failed allocation
2413 *	operation, e.g., vm_page_alloc_contig().
2414 *
2415 *	The caller must always specify an allocation class through "req".
2416 *
2417 *	allocation classes:
2418 *	VM_ALLOC_NORMAL		normal process request
2419 *	VM_ALLOC_SYSTEM		system *really* needs a page
2420 *	VM_ALLOC_INTERRUPT	interrupt time request
2421 *
2422 *	The optional allocation flags are ignored.
2423 *
2424 *	"npages" must be greater than zero.  Both "alignment" and "boundary"
2425 *	must be a power of two.
2426 */
2427bool
2428vm_page_reclaim_contig(int req, u_long npages, vm_paddr_t low, vm_paddr_t high,
2429    u_long alignment, vm_paddr_t boundary)
2430{
2431	vm_paddr_t curr_low;
2432	vm_page_t m_run, m_runs[NRUNS];
2433	u_long count, reclaimed;
2434	int error, i, options, req_class;
2435
2436	KASSERT(npages > 0, ("npages is 0"));
2437	KASSERT(powerof2(alignment), ("alignment is not a power of 2"));
2438	KASSERT(powerof2(boundary), ("boundary is not a power of 2"));
2439	req_class = req & VM_ALLOC_CLASS_MASK;
2440
2441	/*
2442	 * The page daemon is allowed to dig deeper into the free page list.
2443	 */
2444	if (curproc == pageproc && req_class != VM_ALLOC_INTERRUPT)
2445		req_class = VM_ALLOC_SYSTEM;
2446
2447	/*
2448	 * Return if the number of free pages cannot satisfy the requested
2449	 * allocation.
2450	 */
2451	count = vm_cnt.v_free_count;
2452	if (count < npages + vm_cnt.v_free_reserved || (count < npages +
2453	    vm_cnt.v_interrupt_free_min && req_class == VM_ALLOC_SYSTEM) ||
2454	    (count < npages && req_class == VM_ALLOC_INTERRUPT))
2455		return (false);
2456
2457	/*
2458	 * Scan up to three times, relaxing the restrictions ("options") on
2459	 * the reclamation of reservations and superpages each time.
2460	 */
2461	for (options = VPSC_NORESERV;;) {
2462		/*
2463		 * Find the highest runs that satisfy the given constraints
2464		 * and restrictions, and record them in "m_runs".
2465		 */
2466		curr_low = low;
2467		count = 0;
2468		for (;;) {
2469			m_run = vm_phys_scan_contig(npages, curr_low, high,
2470			    alignment, boundary, options);
2471			if (m_run == NULL)
2472				break;
2473			curr_low = VM_PAGE_TO_PHYS(m_run) + ptoa(npages);
2474			m_runs[RUN_INDEX(count)] = m_run;
2475			count++;
2476		}
2477
2478		/*
2479		 * Reclaim the highest runs in LIFO (descending) order until
2480		 * the number of reclaimed pages, "reclaimed", is at least
2481		 * MIN_RECLAIM.  Reset "reclaimed" each time because each
2482		 * reclamation is idempotent, and runs will (likely) recur
2483		 * from one scan to the next as restrictions are relaxed.
2484		 */
2485		reclaimed = 0;
2486		for (i = 0; count > 0 && i < NRUNS; i++) {
2487			count--;
2488			m_run = m_runs[RUN_INDEX(count)];
2489			error = vm_page_reclaim_run(req_class, npages, m_run,
2490			    high);
2491			if (error == 0) {
2492				reclaimed += npages;
2493				if (reclaimed >= MIN_RECLAIM)
2494					return (true);
2495			}
2496		}
2497
2498		/*
2499		 * Either relax the restrictions on the next scan or return if
2500		 * the last scan had no restrictions.
2501		 */
2502		if (options == VPSC_NORESERV)
2503			options = VPSC_NOSUPER;
2504		else if (options == VPSC_NOSUPER)
2505			options = VPSC_ANY;
2506		else if (options == VPSC_ANY)
2507			return (reclaimed != 0);
2508	}
2509}
2510
2511/*
2512 *	vm_wait:	(also see VM_WAIT macro)
2513 *
2514 *	Sleep until free pages are available for allocation.
2515 *	- Called in various places before memory allocations.
2516 */
2517void
2518vm_wait(void)
2519{
2520
2521	mtx_lock(&vm_page_queue_free_mtx);
2522	if (curproc == pageproc) {
2523		vm_pageout_pages_needed = 1;
2524		msleep(&vm_pageout_pages_needed, &vm_page_queue_free_mtx,
2525		    PDROP | PSWP, "VMWait", 0);
2526	} else {
2527		if (__predict_false(pageproc == NULL))
2528			panic("vm_wait in early boot");
2529		if (!vm_pageout_wanted) {
2530			vm_pageout_wanted = true;
2531			wakeup(&vm_pageout_wanted);
2532		}
2533		vm_pages_needed = true;
2534		msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PVM,
2535		    "vmwait", 0);
2536	}
2537}
2538
2539/*
2540 *	vm_waitpfault:	(also see VM_WAITPFAULT macro)
2541 *
2542 *	Sleep until free pages are available for allocation.
2543 *	- Called only in vm_fault so that processes page faulting
2544 *	  can be easily tracked.
2545 *	- Sleeps at a lower priority than vm_wait() so that vm_wait()ing
2546 *	  processes will be able to grab memory first.  Do not change
2547 *	  this balance without careful testing first.
2548 */
2549void
2550vm_waitpfault(void)
2551{
2552
2553	mtx_lock(&vm_page_queue_free_mtx);
2554	if (!vm_pageout_wanted) {
2555		vm_pageout_wanted = true;
2556		wakeup(&vm_pageout_wanted);
2557	}
2558	vm_pages_needed = true;
2559	msleep(&vm_cnt.v_free_count, &vm_page_queue_free_mtx, PDROP | PUSER,
2560	    "pfault", 0);
2561}
2562
2563struct vm_pagequeue *
2564vm_page_pagequeue(vm_page_t m)
2565{
2566
2567	if (vm_page_in_laundry(m))
2568		return (&vm_dom[0].vmd_pagequeues[m->queue]);
2569	else
2570		return (&vm_phys_domain(m)->vmd_pagequeues[m->queue]);
2571}
2572
2573/*
2574 *	vm_page_dequeue:
2575 *
2576 *	Remove the given page from its current page queue.
2577 *
2578 *	The page must be locked.
2579 */
2580void
2581vm_page_dequeue(vm_page_t m)
2582{
2583	struct vm_pagequeue *pq;
2584
2585	vm_page_assert_locked(m);
2586	KASSERT(m->queue < PQ_COUNT, ("vm_page_dequeue: page %p is not queued",
2587	    m));
2588	pq = vm_page_pagequeue(m);
2589	vm_pagequeue_lock(pq);
2590	m->queue = PQ_NONE;
2591	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2592	vm_pagequeue_cnt_dec(pq);
2593	vm_pagequeue_unlock(pq);
2594}
2595
2596/*
2597 *	vm_page_dequeue_locked:
2598 *
2599 *	Remove the given page from its current page queue.
2600 *
2601 *	The page and page queue must be locked.
2602 */
2603void
2604vm_page_dequeue_locked(vm_page_t m)
2605{
2606	struct vm_pagequeue *pq;
2607
2608	vm_page_lock_assert(m, MA_OWNED);
2609	pq = vm_page_pagequeue(m);
2610	vm_pagequeue_assert_locked(pq);
2611	m->queue = PQ_NONE;
2612	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2613	vm_pagequeue_cnt_dec(pq);
2614}
2615
2616/*
2617 *	vm_page_enqueue:
2618 *
2619 *	Add the given page to the specified page queue.
2620 *
2621 *	The page must be locked.
2622 */
2623static void
2624vm_page_enqueue(uint8_t queue, vm_page_t m)
2625{
2626	struct vm_pagequeue *pq;
2627
2628	vm_page_lock_assert(m, MA_OWNED);
2629	KASSERT(queue < PQ_COUNT,
2630	    ("vm_page_enqueue: invalid queue %u request for page %p",
2631	    queue, m));
2632	if (queue == PQ_LAUNDRY)
2633		pq = &vm_dom[0].vmd_pagequeues[queue];
2634	else
2635		pq = &vm_phys_domain(m)->vmd_pagequeues[queue];
2636	vm_pagequeue_lock(pq);
2637	m->queue = queue;
2638	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2639	vm_pagequeue_cnt_inc(pq);
2640	vm_pagequeue_unlock(pq);
2641}
2642
2643/*
2644 *	vm_page_requeue:
2645 *
2646 *	Move the given page to the tail of its current page queue.
2647 *
2648 *	The page must be locked.
2649 */
2650void
2651vm_page_requeue(vm_page_t m)
2652{
2653	struct vm_pagequeue *pq;
2654
2655	vm_page_lock_assert(m, MA_OWNED);
2656	KASSERT(m->queue != PQ_NONE,
2657	    ("vm_page_requeue: page %p is not queued", m));
2658	pq = vm_page_pagequeue(m);
2659	vm_pagequeue_lock(pq);
2660	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2661	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2662	vm_pagequeue_unlock(pq);
2663}
2664
2665/*
2666 *	vm_page_requeue_locked:
2667 *
2668 *	Move the given page to the tail of its current page queue.
2669 *
2670 *	The page queue must be locked.
2671 */
2672void
2673vm_page_requeue_locked(vm_page_t m)
2674{
2675	struct vm_pagequeue *pq;
2676
2677	KASSERT(m->queue != PQ_NONE,
2678	    ("vm_page_requeue_locked: page %p is not queued", m));
2679	pq = vm_page_pagequeue(m);
2680	vm_pagequeue_assert_locked(pq);
2681	TAILQ_REMOVE(&pq->pq_pl, m, plinks.q);
2682	TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2683}
2684
2685/*
2686 *	vm_page_activate:
2687 *
2688 *	Put the specified page on the active list (if appropriate).
2689 *	Ensure that act_count is at least ACT_INIT but do not otherwise
2690 *	mess with it.
2691 *
2692 *	The page must be locked.
2693 */
2694void
2695vm_page_activate(vm_page_t m)
2696{
2697	int queue;
2698
2699	vm_page_lock_assert(m, MA_OWNED);
2700	if ((queue = m->queue) != PQ_ACTIVE) {
2701		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2702			if (m->act_count < ACT_INIT)
2703				m->act_count = ACT_INIT;
2704			if (queue != PQ_NONE)
2705				vm_page_dequeue(m);
2706			vm_page_enqueue(PQ_ACTIVE, m);
2707		} else
2708			KASSERT(queue == PQ_NONE,
2709			    ("vm_page_activate: wired page %p is queued", m));
2710	} else {
2711		if (m->act_count < ACT_INIT)
2712			m->act_count = ACT_INIT;
2713	}
2714}
2715
2716/*
2717 *	vm_page_free_wakeup:
2718 *
2719 *	Helper routine for vm_page_free_toq().  This routine is called
2720 *	when a page is added to the free queues.
2721 *
2722 *	The page queues must be locked.
2723 */
2724static inline void
2725vm_page_free_wakeup(void)
2726{
2727
2728	mtx_assert(&vm_page_queue_free_mtx, MA_OWNED);
2729	/*
2730	 * if pageout daemon needs pages, then tell it that there are
2731	 * some free.
2732	 */
2733	if (vm_pageout_pages_needed &&
2734	    vm_cnt.v_free_count >= vm_cnt.v_pageout_free_min) {
2735		wakeup(&vm_pageout_pages_needed);
2736		vm_pageout_pages_needed = 0;
2737	}
2738	/*
2739	 * wakeup processes that are waiting on memory if we hit a
2740	 * high water mark. And wakeup scheduler process if we have
2741	 * lots of memory. this process will swapin processes.
2742	 */
2743	if (vm_pages_needed && !vm_page_count_min()) {
2744		vm_pages_needed = false;
2745		wakeup(&vm_cnt.v_free_count);
2746	}
2747}
2748
2749/*
2750 *	vm_page_free_toq:
2751 *
2752 *	Returns the given page to the free list,
2753 *	disassociating it with any VM object.
2754 *
2755 *	The object must be locked.  The page must be locked if it is managed.
2756 */
2757void
2758vm_page_free_toq(vm_page_t m)
2759{
2760
2761	if ((m->oflags & VPO_UNMANAGED) == 0) {
2762		vm_page_lock_assert(m, MA_OWNED);
2763		KASSERT(!pmap_page_is_mapped(m),
2764		    ("vm_page_free_toq: freeing mapped page %p", m));
2765	} else
2766		KASSERT(m->queue == PQ_NONE,
2767		    ("vm_page_free_toq: unmanaged page %p is queued", m));
2768	PCPU_INC(cnt.v_tfree);
2769
2770	if (vm_page_sbusied(m))
2771		panic("vm_page_free: freeing busy page %p", m);
2772
2773	/*
2774	 * Unqueue, then remove page.  Note that we cannot destroy
2775	 * the page here because we do not want to call the pager's
2776	 * callback routine until after we've put the page on the
2777	 * appropriate free queue.
2778	 */
2779	vm_page_remque(m);
2780	vm_page_remove(m);
2781
2782	/*
2783	 * If fictitious remove object association and
2784	 * return, otherwise delay object association removal.
2785	 */
2786	if ((m->flags & PG_FICTITIOUS) != 0) {
2787		return;
2788	}
2789
2790	m->valid = 0;
2791	vm_page_undirty(m);
2792
2793	if (m->wire_count != 0)
2794		panic("vm_page_free: freeing wired page %p", m);
2795	if (m->hold_count != 0) {
2796		m->flags &= ~PG_ZERO;
2797		KASSERT((m->flags & PG_UNHOLDFREE) == 0,
2798		    ("vm_page_free: freeing PG_UNHOLDFREE page %p", m));
2799		m->flags |= PG_UNHOLDFREE;
2800	} else {
2801		/*
2802		 * Restore the default memory attribute to the page.
2803		 */
2804		if (pmap_page_get_memattr(m) != VM_MEMATTR_DEFAULT)
2805			pmap_page_set_memattr(m, VM_MEMATTR_DEFAULT);
2806
2807		/*
2808		 * Insert the page into the physical memory allocator's free
2809		 * page queues.
2810		 */
2811		mtx_lock(&vm_page_queue_free_mtx);
2812		vm_phys_freecnt_adj(m, 1);
2813#if VM_NRESERVLEVEL > 0
2814		if (!vm_reserv_free_page(m))
2815#else
2816		if (TRUE)
2817#endif
2818			vm_phys_free_pages(m, 0);
2819		if ((m->flags & PG_ZERO) != 0)
2820			++vm_page_zero_count;
2821		else
2822			vm_page_zero_idle_wakeup();
2823		vm_page_free_wakeup();
2824		mtx_unlock(&vm_page_queue_free_mtx);
2825	}
2826}
2827
2828/*
2829 *	vm_page_wire:
2830 *
2831 *	Mark this page as wired down by yet
2832 *	another map, removing it from paging queues
2833 *	as necessary.
2834 *
2835 *	If the page is fictitious, then its wire count must remain one.
2836 *
2837 *	The page must be locked.
2838 */
2839void
2840vm_page_wire(vm_page_t m)
2841{
2842
2843	/*
2844	 * Only bump the wire statistics if the page is not already wired,
2845	 * and only unqueue the page if it is on some queue (if it is unmanaged
2846	 * it is already off the queues).
2847	 */
2848	vm_page_lock_assert(m, MA_OWNED);
2849	if ((m->flags & PG_FICTITIOUS) != 0) {
2850		KASSERT(m->wire_count == 1,
2851		    ("vm_page_wire: fictitious page %p's wire count isn't one",
2852		    m));
2853		return;
2854	}
2855	if (m->wire_count == 0) {
2856		KASSERT((m->oflags & VPO_UNMANAGED) == 0 ||
2857		    m->queue == PQ_NONE,
2858		    ("vm_page_wire: unmanaged page %p is queued", m));
2859		vm_page_remque(m);
2860		atomic_add_int(&vm_cnt.v_wire_count, 1);
2861	}
2862	m->wire_count++;
2863	KASSERT(m->wire_count != 0, ("vm_page_wire: wire_count overflow m=%p", m));
2864}
2865
2866/*
2867 * vm_page_unwire:
2868 *
2869 * Release one wiring of the specified page, potentially allowing it to be
2870 * paged out.  Returns TRUE if the number of wirings transitions to zero and
2871 * FALSE otherwise.
2872 *
2873 * Only managed pages belonging to an object can be paged out.  If the number
2874 * of wirings transitions to zero and the page is eligible for page out, then
2875 * the page is added to the specified paging queue (unless PQ_NONE is
2876 * specified).
2877 *
2878 * If a page is fictitious, then its wire count must always be one.
2879 *
2880 * A managed page must be locked.
2881 */
2882boolean_t
2883vm_page_unwire(vm_page_t m, uint8_t queue)
2884{
2885
2886	KASSERT(queue < PQ_COUNT || queue == PQ_NONE,
2887	    ("vm_page_unwire: invalid queue %u request for page %p",
2888	    queue, m));
2889	if ((m->oflags & VPO_UNMANAGED) == 0)
2890		vm_page_assert_locked(m);
2891	if ((m->flags & PG_FICTITIOUS) != 0) {
2892		KASSERT(m->wire_count == 1,
2893	    ("vm_page_unwire: fictitious page %p's wire count isn't one", m));
2894		return (FALSE);
2895	}
2896	if (m->wire_count > 0) {
2897		m->wire_count--;
2898		if (m->wire_count == 0) {
2899			atomic_subtract_int(&vm_cnt.v_wire_count, 1);
2900			if ((m->oflags & VPO_UNMANAGED) == 0 &&
2901			    m->object != NULL && queue != PQ_NONE)
2902				vm_page_enqueue(queue, m);
2903			return (TRUE);
2904		} else
2905			return (FALSE);
2906	} else
2907		panic("vm_page_unwire: page %p's wire count is zero", m);
2908}
2909
2910/*
2911 * Move the specified page to the inactive queue.
2912 *
2913 * Normally, "noreuse" is FALSE, resulting in LRU ordering of the inactive
2914 * queue.  However, setting "noreuse" to TRUE will accelerate the specified
2915 * page's reclamation, but it will not unmap the page from any address space.
2916 * This is implemented by inserting the page near the head of the inactive
2917 * queue, using a marker page to guide FIFO insertion ordering.
2918 *
2919 * The page must be locked.
2920 */
2921static inline void
2922_vm_page_deactivate(vm_page_t m, boolean_t noreuse)
2923{
2924	struct vm_pagequeue *pq;
2925	int queue;
2926
2927	vm_page_assert_locked(m);
2928
2929	/*
2930	 * Ignore if the page is already inactive, unless it is unlikely to be
2931	 * reactivated.
2932	 */
2933	if ((queue = m->queue) == PQ_INACTIVE && !noreuse)
2934		return;
2935	if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2936		pq = &vm_phys_domain(m)->vmd_pagequeues[PQ_INACTIVE];
2937		/* Avoid multiple acquisitions of the inactive queue lock. */
2938		if (queue == PQ_INACTIVE) {
2939			vm_pagequeue_lock(pq);
2940			vm_page_dequeue_locked(m);
2941		} else {
2942			if (queue != PQ_NONE)
2943				vm_page_dequeue(m);
2944			vm_pagequeue_lock(pq);
2945		}
2946		m->queue = PQ_INACTIVE;
2947		if (noreuse)
2948			TAILQ_INSERT_BEFORE(&vm_phys_domain(m)->vmd_inacthead,
2949			    m, plinks.q);
2950		else
2951			TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q);
2952		vm_pagequeue_cnt_inc(pq);
2953		vm_pagequeue_unlock(pq);
2954	}
2955}
2956
2957/*
2958 * Move the specified page to the inactive queue.
2959 *
2960 * The page must be locked.
2961 */
2962void
2963vm_page_deactivate(vm_page_t m)
2964{
2965
2966	_vm_page_deactivate(m, FALSE);
2967}
2968
2969/*
2970 * Move the specified page to the inactive queue with the expectation
2971 * that it is unlikely to be reused.
2972 *
2973 * The page must be locked.
2974 */
2975void
2976vm_page_deactivate_noreuse(vm_page_t m)
2977{
2978
2979	_vm_page_deactivate(m, TRUE);
2980}
2981
2982/*
2983 * vm_page_launder
2984 *
2985 * 	Put a page in the laundry.
2986 */
2987void
2988vm_page_launder(vm_page_t m)
2989{
2990	int queue;
2991
2992	vm_page_assert_locked(m);
2993	if ((queue = m->queue) != PQ_LAUNDRY) {
2994		if (m->wire_count == 0 && (m->oflags & VPO_UNMANAGED) == 0) {
2995			if (queue != PQ_NONE)
2996				vm_page_dequeue(m);
2997			vm_page_enqueue(PQ_LAUNDRY, m);
2998		} else
2999			KASSERT(queue == PQ_NONE,
3000			    ("wired page %p is queued", m));
3001	}
3002}
3003
3004/*
3005 * vm_page_try_to_free()
3006 *
3007 *	Attempt to free the page.  If we cannot free it, we do nothing.
3008 *	1 is returned on success, 0 on failure.
3009 */
3010int
3011vm_page_try_to_free(vm_page_t m)
3012{
3013
3014	vm_page_lock_assert(m, MA_OWNED);
3015	if (m->object != NULL)
3016		VM_OBJECT_ASSERT_WLOCKED(m->object);
3017	if (m->dirty || m->hold_count || m->wire_count ||
3018	    (m->oflags & VPO_UNMANAGED) != 0 || vm_page_busied(m))
3019		return (0);
3020	pmap_remove_all(m);
3021	if (m->dirty)
3022		return (0);
3023	vm_page_free(m);
3024	return (1);
3025}
3026
3027/*
3028 * vm_page_advise
3029 *
3030 * 	Deactivate or do nothing, as appropriate.
3031 *
3032 *	The object and page must be locked.
3033 */
3034void
3035vm_page_advise(vm_page_t m, int advice)
3036{
3037
3038	vm_page_assert_locked(m);
3039	VM_OBJECT_ASSERT_WLOCKED(m->object);
3040	if (advice == MADV_FREE)
3041		/*
3042		 * Mark the page clean.  This will allow the page to be freed
3043		 * without first paging it out.  MADV_FREE pages are often
3044		 * quickly reused by malloc(3), so we do not do anything that
3045		 * would result in a page fault on a later access.
3046		 */
3047		vm_page_undirty(m);
3048	else if (advice != MADV_DONTNEED)
3049		return;
3050
3051	/*
3052	 * Clear any references to the page.  Otherwise, the page daemon will
3053	 * immediately reactivate the page.
3054	 */
3055	vm_page_aflag_clear(m, PGA_REFERENCED);
3056
3057	if (advice != MADV_FREE && m->dirty == 0 && pmap_is_modified(m))
3058		vm_page_dirty(m);
3059
3060	/*
3061	 * Place clean pages near the head of the inactive queue rather than
3062	 * the tail, thus defeating the queue's LRU operation and ensuring that
3063	 * the page will be reused quickly.  Dirty pages not already in the
3064	 * laundry are moved there.
3065	 */
3066	if (m->dirty == 0)
3067		vm_page_deactivate_noreuse(m);
3068	else
3069		vm_page_launder(m);
3070}
3071
3072/*
3073 * Grab a page, waiting until we are waken up due to the page
3074 * changing state.  We keep on waiting, if the page continues
3075 * to be in the object.  If the page doesn't exist, first allocate it
3076 * and then conditionally zero it.
3077 *
3078 * This routine may sleep.
3079 *
3080 * The object must be locked on entry.  The lock will, however, be released
3081 * and reacquired if the routine sleeps.
3082 */
3083vm_page_t
3084vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3085{
3086	vm_page_t m;
3087	int sleep;
3088
3089	VM_OBJECT_ASSERT_WLOCKED(object);
3090	KASSERT((allocflags & VM_ALLOC_SBUSY) == 0 ||
3091	    (allocflags & VM_ALLOC_IGN_SBUSY) != 0,
3092	    ("vm_page_grab: VM_ALLOC_SBUSY/VM_ALLOC_IGN_SBUSY mismatch"));
3093retrylookup:
3094	if ((m = vm_page_lookup(object, pindex)) != NULL) {
3095		sleep = (allocflags & VM_ALLOC_IGN_SBUSY) != 0 ?
3096		    vm_page_xbusied(m) : vm_page_busied(m);
3097		if (sleep) {
3098			if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3099				return (NULL);
3100			/*
3101			 * Reference the page before unlocking and
3102			 * sleeping so that the page daemon is less
3103			 * likely to reclaim it.
3104			 */
3105			vm_page_aflag_set(m, PGA_REFERENCED);
3106			vm_page_lock(m);
3107			VM_OBJECT_WUNLOCK(object);
3108			vm_page_busy_sleep(m, "pgrbwt", (allocflags &
3109			    VM_ALLOC_IGN_SBUSY) != 0);
3110			VM_OBJECT_WLOCK(object);
3111			goto retrylookup;
3112		} else {
3113			if ((allocflags & VM_ALLOC_WIRED) != 0) {
3114				vm_page_lock(m);
3115				vm_page_wire(m);
3116				vm_page_unlock(m);
3117			}
3118			if ((allocflags &
3119			    (VM_ALLOC_NOBUSY | VM_ALLOC_SBUSY)) == 0)
3120				vm_page_xbusy(m);
3121			if ((allocflags & VM_ALLOC_SBUSY) != 0)
3122				vm_page_sbusy(m);
3123			return (m);
3124		}
3125	}
3126	m = vm_page_alloc(object, pindex, allocflags);
3127	if (m == NULL) {
3128		if ((allocflags & VM_ALLOC_NOWAIT) != 0)
3129			return (NULL);
3130		VM_OBJECT_WUNLOCK(object);
3131		VM_WAIT;
3132		VM_OBJECT_WLOCK(object);
3133		goto retrylookup;
3134	}
3135	if (allocflags & VM_ALLOC_ZERO && (m->flags & PG_ZERO) == 0)
3136		pmap_zero_page(m);
3137	return (m);
3138}
3139
3140/*
3141 * Mapping function for valid or dirty bits in a page.
3142 *
3143 * Inputs are required to range within a page.
3144 */
3145vm_page_bits_t
3146vm_page_bits(int base, int size)
3147{
3148	int first_bit;
3149	int last_bit;
3150
3151	KASSERT(
3152	    base + size <= PAGE_SIZE,
3153	    ("vm_page_bits: illegal base/size %d/%d", base, size)
3154	);
3155
3156	if (size == 0)		/* handle degenerate case */
3157		return (0);
3158
3159	first_bit = base >> DEV_BSHIFT;
3160	last_bit = (base + size - 1) >> DEV_BSHIFT;
3161
3162	return (((vm_page_bits_t)2 << last_bit) -
3163	    ((vm_page_bits_t)1 << first_bit));
3164}
3165
3166/*
3167 *	vm_page_set_valid_range:
3168 *
3169 *	Sets portions of a page valid.  The arguments are expected
3170 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3171 *	of any partial chunks touched by the range.  The invalid portion of
3172 *	such chunks will be zeroed.
3173 *
3174 *	(base + size) must be less then or equal to PAGE_SIZE.
3175 */
3176void
3177vm_page_set_valid_range(vm_page_t m, int base, int size)
3178{
3179	int endoff, frag;
3180
3181	VM_OBJECT_ASSERT_WLOCKED(m->object);
3182	if (size == 0)	/* handle degenerate case */
3183		return;
3184
3185	/*
3186	 * If the base is not DEV_BSIZE aligned and the valid
3187	 * bit is clear, we have to zero out a portion of the
3188	 * first block.
3189	 */
3190	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3191	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0)
3192		pmap_zero_page_area(m, frag, base - frag);
3193
3194	/*
3195	 * If the ending offset is not DEV_BSIZE aligned and the
3196	 * valid bit is clear, we have to zero out a portion of
3197	 * the last block.
3198	 */
3199	endoff = base + size;
3200	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3201	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0)
3202		pmap_zero_page_area(m, endoff,
3203		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3204
3205	/*
3206	 * Assert that no previously invalid block that is now being validated
3207	 * is already dirty.
3208	 */
3209	KASSERT((~m->valid & vm_page_bits(base, size) & m->dirty) == 0,
3210	    ("vm_page_set_valid_range: page %p is dirty", m));
3211
3212	/*
3213	 * Set valid bits inclusive of any overlap.
3214	 */
3215	m->valid |= vm_page_bits(base, size);
3216}
3217
3218/*
3219 * Clear the given bits from the specified page's dirty field.
3220 */
3221static __inline void
3222vm_page_clear_dirty_mask(vm_page_t m, vm_page_bits_t pagebits)
3223{
3224	uintptr_t addr;
3225#if PAGE_SIZE < 16384
3226	int shift;
3227#endif
3228
3229	/*
3230	 * If the object is locked and the page is neither exclusive busy nor
3231	 * write mapped, then the page's dirty field cannot possibly be
3232	 * set by a concurrent pmap operation.
3233	 */
3234	VM_OBJECT_ASSERT_WLOCKED(m->object);
3235	if (!vm_page_xbusied(m) && !pmap_page_is_write_mapped(m))
3236		m->dirty &= ~pagebits;
3237	else {
3238		/*
3239		 * The pmap layer can call vm_page_dirty() without
3240		 * holding a distinguished lock.  The combination of
3241		 * the object's lock and an atomic operation suffice
3242		 * to guarantee consistency of the page dirty field.
3243		 *
3244		 * For PAGE_SIZE == 32768 case, compiler already
3245		 * properly aligns the dirty field, so no forcible
3246		 * alignment is needed. Only require existence of
3247		 * atomic_clear_64 when page size is 32768.
3248		 */
3249		addr = (uintptr_t)&m->dirty;
3250#if PAGE_SIZE == 32768
3251		atomic_clear_64((uint64_t *)addr, pagebits);
3252#elif PAGE_SIZE == 16384
3253		atomic_clear_32((uint32_t *)addr, pagebits);
3254#else		/* PAGE_SIZE <= 8192 */
3255		/*
3256		 * Use a trick to perform a 32-bit atomic on the
3257		 * containing aligned word, to not depend on the existence
3258		 * of atomic_clear_{8, 16}.
3259		 */
3260		shift = addr & (sizeof(uint32_t) - 1);
3261#if BYTE_ORDER == BIG_ENDIAN
3262		shift = (sizeof(uint32_t) - sizeof(m->dirty) - shift) * NBBY;
3263#else
3264		shift *= NBBY;
3265#endif
3266		addr &= ~(sizeof(uint32_t) - 1);
3267		atomic_clear_32((uint32_t *)addr, pagebits << shift);
3268#endif		/* PAGE_SIZE */
3269	}
3270}
3271
3272/*
3273 *	vm_page_set_validclean:
3274 *
3275 *	Sets portions of a page valid and clean.  The arguments are expected
3276 *	to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3277 *	of any partial chunks touched by the range.  The invalid portion of
3278 *	such chunks will be zero'd.
3279 *
3280 *	(base + size) must be less then or equal to PAGE_SIZE.
3281 */
3282void
3283vm_page_set_validclean(vm_page_t m, int base, int size)
3284{
3285	vm_page_bits_t oldvalid, pagebits;
3286	int endoff, frag;
3287
3288	VM_OBJECT_ASSERT_WLOCKED(m->object);
3289	if (size == 0)	/* handle degenerate case */
3290		return;
3291
3292	/*
3293	 * If the base is not DEV_BSIZE aligned and the valid
3294	 * bit is clear, we have to zero out a portion of the
3295	 * first block.
3296	 */
3297	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3298	    (m->valid & ((vm_page_bits_t)1 << (base >> DEV_BSHIFT))) == 0)
3299		pmap_zero_page_area(m, frag, base - frag);
3300
3301	/*
3302	 * If the ending offset is not DEV_BSIZE aligned and the
3303	 * valid bit is clear, we have to zero out a portion of
3304	 * the last block.
3305	 */
3306	endoff = base + size;
3307	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3308	    (m->valid & ((vm_page_bits_t)1 << (endoff >> DEV_BSHIFT))) == 0)
3309		pmap_zero_page_area(m, endoff,
3310		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1)));
3311
3312	/*
3313	 * Set valid, clear dirty bits.  If validating the entire
3314	 * page we can safely clear the pmap modify bit.  We also
3315	 * use this opportunity to clear the VPO_NOSYNC flag.  If a process
3316	 * takes a write fault on a MAP_NOSYNC memory area the flag will
3317	 * be set again.
3318	 *
3319	 * We set valid bits inclusive of any overlap, but we can only
3320	 * clear dirty bits for DEV_BSIZE chunks that are fully within
3321	 * the range.
3322	 */
3323	oldvalid = m->valid;
3324	pagebits = vm_page_bits(base, size);
3325	m->valid |= pagebits;
3326#if 0	/* NOT YET */
3327	if ((frag = base & (DEV_BSIZE - 1)) != 0) {
3328		frag = DEV_BSIZE - frag;
3329		base += frag;
3330		size -= frag;
3331		if (size < 0)
3332			size = 0;
3333	}
3334	pagebits = vm_page_bits(base, size & (DEV_BSIZE - 1));
3335#endif
3336	if (base == 0 && size == PAGE_SIZE) {
3337		/*
3338		 * The page can only be modified within the pmap if it is
3339		 * mapped, and it can only be mapped if it was previously
3340		 * fully valid.
3341		 */
3342		if (oldvalid == VM_PAGE_BITS_ALL)
3343			/*
3344			 * Perform the pmap_clear_modify() first.  Otherwise,
3345			 * a concurrent pmap operation, such as
3346			 * pmap_protect(), could clear a modification in the
3347			 * pmap and set the dirty field on the page before
3348			 * pmap_clear_modify() had begun and after the dirty
3349			 * field was cleared here.
3350			 */
3351			pmap_clear_modify(m);
3352		m->dirty = 0;
3353		m->oflags &= ~VPO_NOSYNC;
3354	} else if (oldvalid != VM_PAGE_BITS_ALL)
3355		m->dirty &= ~pagebits;
3356	else
3357		vm_page_clear_dirty_mask(m, pagebits);
3358}
3359
3360void
3361vm_page_clear_dirty(vm_page_t m, int base, int size)
3362{
3363
3364	vm_page_clear_dirty_mask(m, vm_page_bits(base, size));
3365}
3366
3367/*
3368 *	vm_page_set_invalid:
3369 *
3370 *	Invalidates DEV_BSIZE'd chunks within a page.  Both the
3371 *	valid and dirty bits for the effected areas are cleared.
3372 */
3373void
3374vm_page_set_invalid(vm_page_t m, int base, int size)
3375{
3376	vm_page_bits_t bits;
3377	vm_object_t object;
3378
3379	object = m->object;
3380	VM_OBJECT_ASSERT_WLOCKED(object);
3381	if (object->type == OBJT_VNODE && base == 0 && IDX_TO_OFF(m->pindex) +
3382	    size >= object->un_pager.vnp.vnp_size)
3383		bits = VM_PAGE_BITS_ALL;
3384	else
3385		bits = vm_page_bits(base, size);
3386	if (object->ref_count != 0 && m->valid == VM_PAGE_BITS_ALL &&
3387	    bits != 0)
3388		pmap_remove_all(m);
3389	KASSERT((bits == 0 && m->valid == VM_PAGE_BITS_ALL) ||
3390	    !pmap_page_is_mapped(m),
3391	    ("vm_page_set_invalid: page %p is mapped", m));
3392	m->valid &= ~bits;
3393	m->dirty &= ~bits;
3394}
3395
3396/*
3397 * vm_page_zero_invalid()
3398 *
3399 *	The kernel assumes that the invalid portions of a page contain
3400 *	garbage, but such pages can be mapped into memory by user code.
3401 *	When this occurs, we must zero out the non-valid portions of the
3402 *	page so user code sees what it expects.
3403 *
3404 *	Pages are most often semi-valid when the end of a file is mapped
3405 *	into memory and the file's size is not page aligned.
3406 */
3407void
3408vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3409{
3410	int b;
3411	int i;
3412
3413	VM_OBJECT_ASSERT_WLOCKED(m->object);
3414	/*
3415	 * Scan the valid bits looking for invalid sections that
3416	 * must be zeroed.  Invalid sub-DEV_BSIZE'd areas ( where the
3417	 * valid bit may be set ) have already been zeroed by
3418	 * vm_page_set_validclean().
3419	 */
3420	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3421		if (i == (PAGE_SIZE / DEV_BSIZE) ||
3422		    (m->valid & ((vm_page_bits_t)1 << i))) {
3423			if (i > b) {
3424				pmap_zero_page_area(m,
3425				    b << DEV_BSHIFT, (i - b) << DEV_BSHIFT);
3426			}
3427			b = i + 1;
3428		}
3429	}
3430
3431	/*
3432	 * setvalid is TRUE when we can safely set the zero'd areas
3433	 * as being valid.  We can do this if there are no cache consistancy
3434	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3435	 */
3436	if (setvalid)
3437		m->valid = VM_PAGE_BITS_ALL;
3438}
3439
3440/*
3441 *	vm_page_is_valid:
3442 *
3443 *	Is (partial) page valid?  Note that the case where size == 0
3444 *	will return FALSE in the degenerate case where the page is
3445 *	entirely invalid, and TRUE otherwise.
3446 */
3447int
3448vm_page_is_valid(vm_page_t m, int base, int size)
3449{
3450	vm_page_bits_t bits;
3451
3452	VM_OBJECT_ASSERT_LOCKED(m->object);
3453	bits = vm_page_bits(base, size);
3454	return (m->valid != 0 && (m->valid & bits) == bits);
3455}
3456
3457/*
3458 *	vm_page_ps_is_valid:
3459 *
3460 *	Returns TRUE if the entire (super)page is valid and FALSE otherwise.
3461 */
3462boolean_t
3463vm_page_ps_is_valid(vm_page_t m)
3464{
3465	int i, npages;
3466
3467	VM_OBJECT_ASSERT_LOCKED(m->object);
3468	npages = atop(pagesizes[m->psind]);
3469
3470	/*
3471	 * The physically contiguous pages that make up a superpage, i.e., a
3472	 * page with a page size index ("psind") greater than zero, will
3473	 * occupy adjacent entries in vm_page_array[].
3474	 */
3475	for (i = 0; i < npages; i++) {
3476		if (m[i].valid != VM_PAGE_BITS_ALL)
3477			return (FALSE);
3478	}
3479	return (TRUE);
3480}
3481
3482/*
3483 * Set the page's dirty bits if the page is modified.
3484 */
3485void
3486vm_page_test_dirty(vm_page_t m)
3487{
3488
3489	VM_OBJECT_ASSERT_WLOCKED(m->object);
3490	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m))
3491		vm_page_dirty(m);
3492}
3493
3494void
3495vm_page_lock_KBI(vm_page_t m, const char *file, int line)
3496{
3497
3498	mtx_lock_flags_(vm_page_lockptr(m), 0, file, line);
3499}
3500
3501void
3502vm_page_unlock_KBI(vm_page_t m, const char *file, int line)
3503{
3504
3505	mtx_unlock_flags_(vm_page_lockptr(m), 0, file, line);
3506}
3507
3508int
3509vm_page_trylock_KBI(vm_page_t m, const char *file, int line)
3510{
3511
3512	return (mtx_trylock_flags_(vm_page_lockptr(m), 0, file, line));
3513}
3514
3515#if defined(INVARIANTS) || defined(INVARIANT_SUPPORT)
3516void
3517vm_page_assert_locked_KBI(vm_page_t m, const char *file, int line)
3518{
3519
3520	vm_page_lock_assert_KBI(m, MA_OWNED, file, line);
3521}
3522
3523void
3524vm_page_lock_assert_KBI(vm_page_t m, int a, const char *file, int line)
3525{
3526
3527	mtx_assert_(vm_page_lockptr(m), a, file, line);
3528}
3529#endif
3530
3531#ifdef INVARIANTS
3532void
3533vm_page_object_lock_assert(vm_page_t m)
3534{
3535
3536	/*
3537	 * Certain of the page's fields may only be modified by the
3538	 * holder of the containing object's lock or the exclusive busy.
3539	 * holder.  Unfortunately, the holder of the write busy is
3540	 * not recorded, and thus cannot be checked here.
3541	 */
3542	if (m->object != NULL && !vm_page_xbusied(m))
3543		VM_OBJECT_ASSERT_WLOCKED(m->object);
3544}
3545
3546void
3547vm_page_assert_pga_writeable(vm_page_t m, uint8_t bits)
3548{
3549
3550	if ((bits & PGA_WRITEABLE) == 0)
3551		return;
3552
3553	/*
3554	 * The PGA_WRITEABLE flag can only be set if the page is
3555	 * managed, is exclusively busied or the object is locked.
3556	 * Currently, this flag is only set by pmap_enter().
3557	 */
3558	KASSERT((m->oflags & VPO_UNMANAGED) == 0,
3559	    ("PGA_WRITEABLE on unmanaged page"));
3560	if (!vm_page_xbusied(m))
3561		VM_OBJECT_ASSERT_LOCKED(m->object);
3562}
3563#endif
3564
3565#include "opt_ddb.h"
3566#ifdef DDB
3567#include <sys/kernel.h>
3568
3569#include <ddb/ddb.h>
3570
3571DB_SHOW_COMMAND(page, vm_page_print_page_info)
3572{
3573
3574	db_printf("vm_cnt.v_free_count: %d\n", vm_cnt.v_free_count);
3575	db_printf("vm_cnt.v_inactive_count: %d\n", vm_cnt.v_inactive_count);
3576	db_printf("vm_cnt.v_active_count: %d\n", vm_cnt.v_active_count);
3577	db_printf("vm_cnt.v_laundry_count: %d\n", vm_cnt.v_laundry_count);
3578	db_printf("vm_cnt.v_wire_count: %d\n", vm_cnt.v_wire_count);
3579	db_printf("vm_cnt.v_free_reserved: %d\n", vm_cnt.v_free_reserved);
3580	db_printf("vm_cnt.v_free_min: %d\n", vm_cnt.v_free_min);
3581	db_printf("vm_cnt.v_free_target: %d\n", vm_cnt.v_free_target);
3582	db_printf("vm_cnt.v_inactive_target: %d\n", vm_cnt.v_inactive_target);
3583}
3584
3585DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3586{
3587	int dom;
3588
3589	db_printf("pq_free %d\n", vm_cnt.v_free_count);
3590	for (dom = 0; dom < vm_ndomains; dom++) {
3591		db_printf(
3592	    "dom %d page_cnt %d free %d pq_act %d pq_inact %d pq_laund %d\n",
3593		    dom,
3594		    vm_dom[dom].vmd_page_count,
3595		    vm_dom[dom].vmd_free_count,
3596		    vm_dom[dom].vmd_pagequeues[PQ_ACTIVE].pq_cnt,
3597		    vm_dom[dom].vmd_pagequeues[PQ_INACTIVE].pq_cnt,
3598		    vm_dom[dom].vmd_pagequeues[PQ_LAUNDRY].pq_cnt);
3599	}
3600}
3601
3602DB_SHOW_COMMAND(pginfo, vm_page_print_pginfo)
3603{
3604	vm_page_t m;
3605	boolean_t phys;
3606
3607	if (!have_addr) {
3608		db_printf("show pginfo addr\n");
3609		return;
3610	}
3611
3612	phys = strchr(modif, 'p') != NULL;
3613	if (phys)
3614		m = PHYS_TO_VM_PAGE(addr);
3615	else
3616		m = (vm_page_t)addr;
3617	db_printf(
3618    "page %p obj %p pidx 0x%jx phys 0x%jx q %d hold %d wire %d\n"
3619    "  af 0x%x of 0x%x f 0x%x act %d busy %x valid 0x%x dirty 0x%x\n",
3620	    m, m->object, (uintmax_t)m->pindex, (uintmax_t)m->phys_addr,
3621	    m->queue, m->hold_count, m->wire_count, m->aflags, m->oflags,
3622	    m->flags, m->act_count, m->busy_lock, m->valid, m->dirty);
3623}
3624#endif /* DDB */
3625