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