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