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