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