xref: /dragonfly/sys/vm/vm_page.c (revision 8eff4093)
1 /*
2  * Copyright (c) 1991 Regents of the University of California.
3  * All rights reserved.
4  * Copyright (c) 2003-2011 The DragonFly Project.  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  * This code is derived from software contributed to The DragonFly Project
10  * by Matthew Dillon <dillon@backplane.com>
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	from: @(#)vm_page.c	7.4 (Berkeley) 5/7/91
37  * $FreeBSD: src/sys/vm/vm_page.c,v 1.147.2.18 2002/03/10 05:03:19 alc Exp $
38  */
39 
40 /*
41  * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42  * All rights reserved.
43  *
44  * Authors: Avadis Tevanian, Jr., Michael Wayne Young
45  *
46  * Permission to use, copy, modify and distribute this software and
47  * its documentation is hereby granted, provided that both the copyright
48  * notice and this permission notice appear in all copies of the
49  * software, derivative works or modified versions, and any portions
50  * thereof, and that both notices appear in supporting documentation.
51  *
52  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
53  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
54  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
55  *
56  * Carnegie Mellon requests users of this software to return to
57  *
58  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
59  *  School of Computer Science
60  *  Carnegie Mellon University
61  *  Pittsburgh PA 15213-3890
62  *
63  * any improvements or extensions that they make and grant Carnegie the
64  * rights to redistribute these changes.
65  */
66 /*
67  * Resident memory management module.  The module manipulates 'VM pages'.
68  * A VM page is the core building block for memory management.
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.h>
74 #include <sys/proc.h>
75 #include <sys/vmmeter.h>
76 #include <sys/vnode.h>
77 #include <sys/kernel.h>
78 #include <sys/alist.h>
79 #include <sys/sysctl.h>
80 #include <sys/cpu_topology.h>
81 
82 #include <vm/vm.h>
83 #include <vm/vm_param.h>
84 #include <sys/lock.h>
85 #include <vm/vm_kern.h>
86 #include <vm/pmap.h>
87 #include <vm/vm_map.h>
88 #include <vm/vm_object.h>
89 #include <vm/vm_page.h>
90 #include <vm/vm_pageout.h>
91 #include <vm/vm_pager.h>
92 #include <vm/vm_extern.h>
93 #include <vm/swap_pager.h>
94 
95 #include <machine/inttypes.h>
96 #include <machine/md_var.h>
97 #include <machine/specialreg.h>
98 #include <machine/bus_dma.h>
99 
100 #include <vm/vm_page2.h>
101 #include <sys/spinlock2.h>
102 
103 /*
104  * SET - Minimum required set associative size, must be a power of 2.  We
105  *	 want this to match or exceed the set-associativeness of the cpu.
106  *
107  * GRP - A larger set that allows bleed-over into the domains of other
108  *	 nearby cpus.  Also must be a power of 2.  Used by the page zeroing
109  *	 code to smooth things out a bit.
110  */
111 #define PQ_SET_ASSOC		16
112 #define PQ_SET_ASSOC_MASK	(PQ_SET_ASSOC - 1)
113 
114 #define PQ_GRP_ASSOC		(PQ_SET_ASSOC * 2)
115 #define PQ_GRP_ASSOC_MASK	(PQ_GRP_ASSOC - 1)
116 
117 static void vm_page_queue_init(void);
118 static void vm_page_free_wakeup(void);
119 static vm_page_t vm_page_select_cache(u_short pg_color);
120 static vm_page_t _vm_page_list_find2(int basequeue, int index);
121 static void _vm_page_deactivate_locked(vm_page_t m, int athead);
122 
123 /*
124  * Array of tailq lists
125  */
126 __cachealign struct vpgqueues vm_page_queues[PQ_COUNT];
127 
128 static volatile int vm_pages_waiting;
129 static struct alist vm_contig_alist;
130 static struct almeta vm_contig_ameta[ALIST_RECORDS_65536];
131 static struct spinlock vm_contig_spin = SPINLOCK_INITIALIZER(&vm_contig_spin, "vm_contig_spin");
132 
133 static u_long vm_dma_reserved = 0;
134 TUNABLE_ULONG("vm.dma_reserved", &vm_dma_reserved);
135 SYSCTL_ULONG(_vm, OID_AUTO, dma_reserved, CTLFLAG_RD, &vm_dma_reserved, 0,
136 	    "Memory reserved for DMA");
137 SYSCTL_UINT(_vm, OID_AUTO, dma_free_pages, CTLFLAG_RD,
138 	    &vm_contig_alist.bl_free, 0, "Memory reserved for DMA");
139 
140 static int vm_contig_verbose = 0;
141 TUNABLE_INT("vm.contig_verbose", &vm_contig_verbose);
142 
143 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
144 	     vm_pindex_t, pindex);
145 
146 static void
147 vm_page_queue_init(void)
148 {
149 	int i;
150 
151 	for (i = 0; i < PQ_L2_SIZE; i++)
152 		vm_page_queues[PQ_FREE+i].cnt_offset =
153 			offsetof(struct vmstats, v_free_count);
154 	for (i = 0; i < PQ_L2_SIZE; i++)
155 		vm_page_queues[PQ_CACHE+i].cnt_offset =
156 			offsetof(struct vmstats, v_cache_count);
157 	for (i = 0; i < PQ_L2_SIZE; i++)
158 		vm_page_queues[PQ_INACTIVE+i].cnt_offset =
159 			offsetof(struct vmstats, v_inactive_count);
160 	for (i = 0; i < PQ_L2_SIZE; i++)
161 		vm_page_queues[PQ_ACTIVE+i].cnt_offset =
162 			offsetof(struct vmstats, v_active_count);
163 	for (i = 0; i < PQ_L2_SIZE; i++)
164 		vm_page_queues[PQ_HOLD+i].cnt_offset =
165 			offsetof(struct vmstats, v_active_count);
166 	/* PQ_NONE has no queue */
167 
168 	for (i = 0; i < PQ_COUNT; i++) {
169 		TAILQ_INIT(&vm_page_queues[i].pl);
170 		spin_init(&vm_page_queues[i].spin, "vm_page_queue_init");
171 	}
172 }
173 
174 /*
175  * note: place in initialized data section?  Is this necessary?
176  */
177 vm_pindex_t first_page = 0;
178 vm_pindex_t vm_page_array_size = 0;
179 vm_page_t vm_page_array = NULL;
180 vm_paddr_t vm_low_phys_reserved;
181 
182 /*
183  * (low level boot)
184  *
185  * Sets the page size, perhaps based upon the memory size.
186  * Must be called before any use of page-size dependent functions.
187  */
188 void
189 vm_set_page_size(void)
190 {
191 	if (vmstats.v_page_size == 0)
192 		vmstats.v_page_size = PAGE_SIZE;
193 	if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
194 		panic("vm_set_page_size: page size not a power of two");
195 }
196 
197 /*
198  * (low level boot)
199  *
200  * Add a new page to the freelist for use by the system.  New pages
201  * are added to both the head and tail of the associated free page
202  * queue in a bottom-up fashion, so both zero'd and non-zero'd page
203  * requests pull 'recent' adds (higher physical addresses) first.
204  *
205  * Beware that the page zeroing daemon will also be running soon after
206  * boot, moving pages from the head to the tail of the PQ_FREE queues.
207  *
208  * Must be called in a critical section.
209  */
210 static void
211 vm_add_new_page(vm_paddr_t pa)
212 {
213 	struct vpgqueues *vpq;
214 	vm_page_t m;
215 
216 	m = PHYS_TO_VM_PAGE(pa);
217 	m->phys_addr = pa;
218 	m->flags = 0;
219 	m->pat_mode = PAT_WRITE_BACK;
220 	m->pc = (pa >> PAGE_SHIFT);
221 
222 	/*
223 	 * Twist for cpu localization in addition to page coloring, so
224 	 * different cpus selecting by m->queue get different page colors.
225 	 */
226 	m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE);
227 	m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE));
228 	m->pc &= PQ_L2_MASK;
229 
230 	/*
231 	 * Reserve a certain number of contiguous low memory pages for
232 	 * contigmalloc() to use.
233 	 */
234 	if (pa < vm_low_phys_reserved) {
235 		atomic_add_long(&vmstats.v_page_count, 1);
236 		atomic_add_long(&vmstats.v_dma_pages, 1);
237 		m->queue = PQ_NONE;
238 		m->wire_count = 1;
239 		atomic_add_long(&vmstats.v_wire_count, 1);
240 		alist_free(&vm_contig_alist, pa >> PAGE_SHIFT, 1);
241 		return;
242 	}
243 
244 	/*
245 	 * General page
246 	 */
247 	m->queue = m->pc + PQ_FREE;
248 	KKASSERT(m->dirty == 0);
249 
250 	atomic_add_long(&vmstats.v_page_count, 1);
251 	atomic_add_long(&vmstats.v_free_count, 1);
252 	vpq = &vm_page_queues[m->queue];
253 	TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
254 	++vpq->lcnt;
255 }
256 
257 /*
258  * (low level boot)
259  *
260  * Initializes the resident memory module.
261  *
262  * Preallocates memory for critical VM structures and arrays prior to
263  * kernel_map becoming available.
264  *
265  * Memory is allocated from (virtual2_start, virtual2_end) if available,
266  * otherwise memory is allocated from (virtual_start, virtual_end).
267  *
268  * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
269  * large enough to hold vm_page_array & other structures for machines with
270  * large amounts of ram, so we want to use virtual2* when available.
271  */
272 void
273 vm_page_startup(void)
274 {
275 	vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
276 	vm_offset_t mapped;
277 	vm_pindex_t npages;
278 	vm_paddr_t page_range;
279 	vm_paddr_t new_end;
280 	int i;
281 	vm_paddr_t pa;
282 	vm_paddr_t last_pa;
283 	vm_paddr_t end;
284 	vm_paddr_t biggestone, biggestsize;
285 	vm_paddr_t total;
286 	vm_page_t m;
287 
288 	total = 0;
289 	biggestsize = 0;
290 	biggestone = 0;
291 	vaddr = round_page(vaddr);
292 
293 	/*
294 	 * Make sure ranges are page-aligned.
295 	 */
296 	for (i = 0; phys_avail[i].phys_end; ++i) {
297 		phys_avail[i].phys_beg = round_page64(phys_avail[i].phys_beg);
298 		phys_avail[i].phys_end = trunc_page64(phys_avail[i].phys_end);
299 		if (phys_avail[i].phys_end < phys_avail[i].phys_beg)
300 			phys_avail[i].phys_end = phys_avail[i].phys_beg;
301 	}
302 
303 	/*
304 	 * Locate largest block
305 	 */
306 	for (i = 0; phys_avail[i].phys_end; ++i) {
307 		vm_paddr_t size = phys_avail[i].phys_end -
308 				  phys_avail[i].phys_beg;
309 
310 		if (size > biggestsize) {
311 			biggestone = i;
312 			biggestsize = size;
313 		}
314 		total += size;
315 	}
316 	--i;	/* adjust to last entry for use down below */
317 
318 	end = phys_avail[biggestone].phys_end;
319 	end = trunc_page(end);
320 
321 	/*
322 	 * Initialize the queue headers for the free queue, the active queue
323 	 * and the inactive queue.
324 	 */
325 	vm_page_queue_init();
326 
327 #if !defined(_KERNEL_VIRTUAL)
328 	/*
329 	 * VKERNELs don't support minidumps and as such don't need
330 	 * vm_page_dump
331 	 *
332 	 * Allocate a bitmap to indicate that a random physical page
333 	 * needs to be included in a minidump.
334 	 *
335 	 * The amd64 port needs this to indicate which direct map pages
336 	 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
337 	 *
338 	 * However, x86 still needs this workspace internally within the
339 	 * minidump code.  In theory, they are not needed on x86, but are
340 	 * included should the sf_buf code decide to use them.
341 	 */
342 	page_range = phys_avail[i].phys_end / PAGE_SIZE;
343 	vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
344 	end -= vm_page_dump_size;
345 	vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
346 					VM_PROT_READ | VM_PROT_WRITE);
347 	bzero((void *)vm_page_dump, vm_page_dump_size);
348 #endif
349 	/*
350 	 * Compute the number of pages of memory that will be available for
351 	 * use (taking into account the overhead of a page structure per
352 	 * page).
353 	 */
354 	first_page = phys_avail[0].phys_beg / PAGE_SIZE;
355 	page_range = phys_avail[i].phys_end / PAGE_SIZE - first_page;
356 	npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
357 
358 #ifndef _KERNEL_VIRTUAL
359 	/*
360 	 * (only applies to real kernels)
361 	 *
362 	 * Reserve a large amount of low memory for potential 32-bit DMA
363 	 * space allocations.  Once device initialization is complete we
364 	 * release most of it, but keep (vm_dma_reserved) memory reserved
365 	 * for later use.  Typically for X / graphics.  Through trial and
366 	 * error we find that GPUs usually requires ~60-100MB or so.
367 	 *
368 	 * By default, 128M is left in reserve on machines with 2G+ of ram.
369 	 */
370 	vm_low_phys_reserved = (vm_paddr_t)65536 << PAGE_SHIFT;
371 	if (vm_low_phys_reserved > total / 4)
372 		vm_low_phys_reserved = total / 4;
373 	if (vm_dma_reserved == 0) {
374 		vm_dma_reserved = 128 * 1024 * 1024;	/* 128MB */
375 		if (vm_dma_reserved > total / 16)
376 			vm_dma_reserved = total / 16;
377 	}
378 #endif
379 	alist_init(&vm_contig_alist, 65536, vm_contig_ameta,
380 		   ALIST_RECORDS_65536);
381 
382 	/*
383 	 * Initialize the mem entry structures now, and put them in the free
384 	 * queue.
385 	 */
386 	new_end = trunc_page(end - page_range * sizeof(struct vm_page));
387 	mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE);
388 	vm_page_array = (vm_page_t)mapped;
389 
390 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
391 	/*
392 	 * since pmap_map on amd64 returns stuff out of a direct-map region,
393 	 * we have to manually add these pages to the minidump tracking so
394 	 * that they can be dumped, including the vm_page_array.
395 	 */
396 	for (pa = new_end;
397 	     pa < phys_avail[biggestone].phys_end;
398 	     pa += PAGE_SIZE) {
399 		dump_add_page(pa);
400 	}
401 #endif
402 
403 	/*
404 	 * Clear all of the page structures, run basic initialization so
405 	 * PHYS_TO_VM_PAGE() operates properly even on pages not in the
406 	 * map.
407 	 */
408 	bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
409 	vm_page_array_size = page_range;
410 
411 	m = &vm_page_array[0];
412 	pa = ptoa(first_page);
413 	for (i = 0; i < page_range; ++i) {
414 		spin_init(&m->spin, "vm_page");
415 		m->phys_addr = pa;
416 		pa += PAGE_SIZE;
417 		++m;
418 	}
419 
420 	/*
421 	 * Construct the free queue(s) in ascending order (by physical
422 	 * address) so that the first 16MB of physical memory is allocated
423 	 * last rather than first.  On large-memory machines, this avoids
424 	 * the exhaustion of low physical memory before isa_dma_init has run.
425 	 */
426 	vmstats.v_page_count = 0;
427 	vmstats.v_free_count = 0;
428 	for (i = 0; phys_avail[i].phys_end && npages > 0; ++i) {
429 		pa = phys_avail[i].phys_beg;
430 		if (i == biggestone)
431 			last_pa = new_end;
432 		else
433 			last_pa = phys_avail[i].phys_end;
434 		while (pa < last_pa && npages-- > 0) {
435 			vm_add_new_page(pa);
436 			pa += PAGE_SIZE;
437 		}
438 	}
439 	if (virtual2_start)
440 		virtual2_start = vaddr;
441 	else
442 		virtual_start = vaddr;
443 	mycpu->gd_vmstats = vmstats;
444 }
445 
446 /*
447  * Reorganize VM pages based on numa data.  May be called as many times as
448  * necessary.  Will reorganize the vm_page_t page color and related queue(s)
449  * to allow vm_page_alloc() to choose pages based on socket affinity.
450  *
451  * NOTE: This function is only called while we are still in UP mode, so
452  *	 we only need a critical section to protect the queues (which
453  *	 saves a lot of time, there are likely a ton of pages).
454  */
455 void
456 vm_numa_organize(vm_paddr_t ran_beg, vm_paddr_t bytes, int physid)
457 {
458 	vm_paddr_t scan_beg;
459 	vm_paddr_t scan_end;
460 	vm_paddr_t ran_end;
461 	struct vpgqueues *vpq;
462 	vm_page_t m;
463 	vm_page_t mend;
464 	int i;
465 	int socket_mod;
466 	int socket_value;
467 
468 	/*
469 	 * Check if no physical information, or there was only one socket
470 	 * (so don't waste time doing nothing!).
471 	 */
472 	if (cpu_topology_phys_ids <= 1 ||
473 	    cpu_topology_core_ids == 0) {
474 		return;
475 	}
476 
477 	/*
478 	 * Setup for our iteration.  Note that ACPI may iterate CPU
479 	 * sockets starting at 0 or 1 or some other number.  The
480 	 * cpu_topology code mod's it against the socket count.
481 	 */
482 	ran_end = ran_beg + bytes;
483 	physid %= cpu_topology_phys_ids;
484 
485 	socket_mod = PQ_L2_SIZE / cpu_topology_phys_ids;
486 	socket_value = physid * socket_mod;
487 	mend = &vm_page_array[vm_page_array_size];
488 
489 	crit_enter();
490 
491 	/*
492 	 * Adjust vm_page->pc and requeue all affected pages.  The
493 	 * allocator will then be able to localize memory allocations
494 	 * to some degree.
495 	 */
496 	for (i = 0; phys_avail[i].phys_end; ++i) {
497 		scan_beg = phys_avail[i].phys_beg;
498 		scan_end = phys_avail[i].phys_end;
499 		if (scan_end <= ran_beg)
500 			continue;
501 		if (scan_beg >= ran_end)
502 			continue;
503 		if (scan_beg < ran_beg)
504 			scan_beg = ran_beg;
505 		if (scan_end > ran_end)
506 			scan_end = ran_end;
507 		if (atop(scan_end) > first_page + vm_page_array_size)
508 			scan_end = ptoa(first_page + vm_page_array_size);
509 
510 		m = PHYS_TO_VM_PAGE(scan_beg);
511 		while (scan_beg < scan_end) {
512 			KKASSERT(m < mend);
513 			if (m->queue != PQ_NONE) {
514 				vpq = &vm_page_queues[m->queue];
515 				TAILQ_REMOVE(&vpq->pl, m, pageq);
516 				--vpq->lcnt;
517 				/* queue doesn't change, no need to adj cnt */
518 				m->queue -= m->pc;
519 				m->pc %= socket_mod;
520 				m->pc += socket_value;
521 				m->pc &= PQ_L2_MASK;
522 				m->queue += m->pc;
523 				vpq = &vm_page_queues[m->queue];
524 				TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
525 				++vpq->lcnt;
526 				/* queue doesn't change, no need to adj cnt */
527 			} else {
528 				m->pc %= socket_mod;
529 				m->pc += socket_value;
530 				m->pc &= PQ_L2_MASK;
531 			}
532 			scan_beg += PAGE_SIZE;
533 			++m;
534 		}
535 	}
536 	crit_exit();
537 }
538 
539 /*
540  * We tended to reserve a ton of memory for contigmalloc().  Now that most
541  * drivers have initialized we want to return most the remaining free
542  * reserve back to the VM page queues so they can be used for normal
543  * allocations.
544  *
545  * We leave vm_dma_reserved bytes worth of free pages in the reserve pool.
546  */
547 static void
548 vm_page_startup_finish(void *dummy __unused)
549 {
550 	alist_blk_t blk;
551 	alist_blk_t rblk;
552 	alist_blk_t count;
553 	alist_blk_t xcount;
554 	alist_blk_t bfree;
555 	vm_page_t m;
556 
557 	spin_lock(&vm_contig_spin);
558 	for (;;) {
559 		bfree = alist_free_info(&vm_contig_alist, &blk, &count);
560 		if (bfree <= vm_dma_reserved / PAGE_SIZE)
561 			break;
562 		if (count == 0)
563 			break;
564 
565 		/*
566 		 * Figure out how much of the initial reserve we have to
567 		 * free in order to reach our target.
568 		 */
569 		bfree -= vm_dma_reserved / PAGE_SIZE;
570 		if (count > bfree) {
571 			blk += count - bfree;
572 			count = bfree;
573 		}
574 
575 		/*
576 		 * Calculate the nearest power of 2 <= count.
577 		 */
578 		for (xcount = 1; xcount <= count; xcount <<= 1)
579 			;
580 		xcount >>= 1;
581 		blk += count - xcount;
582 		count = xcount;
583 
584 		/*
585 		 * Allocate the pages from the alist, then free them to
586 		 * the normal VM page queues.
587 		 *
588 		 * Pages allocated from the alist are wired.  We have to
589 		 * busy, unwire, and free them.  We must also adjust
590 		 * vm_low_phys_reserved before freeing any pages to prevent
591 		 * confusion.
592 		 */
593 		rblk = alist_alloc(&vm_contig_alist, blk, count);
594 		if (rblk != blk) {
595 			kprintf("vm_page_startup_finish: Unable to return "
596 				"dma space @0x%08x/%d -> 0x%08x\n",
597 				blk, count, rblk);
598 			break;
599 		}
600 		atomic_add_long(&vmstats.v_dma_pages, -(long)count);
601 		spin_unlock(&vm_contig_spin);
602 
603 		m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
604 		vm_low_phys_reserved = VM_PAGE_TO_PHYS(m);
605 		while (count) {
606 			vm_page_busy_wait(m, FALSE, "cpgfr");
607 			vm_page_unwire(m, 0);
608 			vm_page_free(m);
609 			--count;
610 			++m;
611 		}
612 		spin_lock(&vm_contig_spin);
613 	}
614 	spin_unlock(&vm_contig_spin);
615 
616 	/*
617 	 * Print out how much DMA space drivers have already allocated and
618 	 * how much is left over.
619 	 */
620 	kprintf("DMA space used: %jdk, remaining available: %jdk\n",
621 		(intmax_t)(vmstats.v_dma_pages - vm_contig_alist.bl_free) *
622 		(PAGE_SIZE / 1024),
623 		(intmax_t)vm_contig_alist.bl_free * (PAGE_SIZE / 1024));
624 }
625 SYSINIT(vm_pgend, SI_SUB_PROC0_POST, SI_ORDER_ANY,
626 	vm_page_startup_finish, NULL);
627 
628 
629 /*
630  * Scan comparison function for Red-Black tree scans.  An inclusive
631  * (start,end) is expected.  Other fields are not used.
632  */
633 int
634 rb_vm_page_scancmp(struct vm_page *p, void *data)
635 {
636 	struct rb_vm_page_scan_info *info = data;
637 
638 	if (p->pindex < info->start_pindex)
639 		return(-1);
640 	if (p->pindex > info->end_pindex)
641 		return(1);
642 	return(0);
643 }
644 
645 int
646 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
647 {
648 	if (p1->pindex < p2->pindex)
649 		return(-1);
650 	if (p1->pindex > p2->pindex)
651 		return(1);
652 	return(0);
653 }
654 
655 void
656 vm_page_init(vm_page_t m)
657 {
658 	/* do nothing for now.  Called from pmap_page_init() */
659 }
660 
661 /*
662  * Each page queue has its own spin lock, which is fairly optimal for
663  * allocating and freeing pages at least.
664  *
665  * The caller must hold the vm_page_spin_lock() before locking a vm_page's
666  * queue spinlock via this function.  Also note that m->queue cannot change
667  * unless both the page and queue are locked.
668  */
669 static __inline
670 void
671 _vm_page_queue_spin_lock(vm_page_t m)
672 {
673 	u_short queue;
674 
675 	queue = m->queue;
676 	if (queue != PQ_NONE) {
677 		spin_lock(&vm_page_queues[queue].spin);
678 		KKASSERT(queue == m->queue);
679 	}
680 }
681 
682 static __inline
683 void
684 _vm_page_queue_spin_unlock(vm_page_t m)
685 {
686 	u_short queue;
687 
688 	queue = m->queue;
689 	cpu_ccfence();
690 	if (queue != PQ_NONE)
691 		spin_unlock(&vm_page_queues[queue].spin);
692 }
693 
694 static __inline
695 void
696 _vm_page_queues_spin_lock(u_short queue)
697 {
698 	cpu_ccfence();
699 	if (queue != PQ_NONE)
700 		spin_lock(&vm_page_queues[queue].spin);
701 }
702 
703 
704 static __inline
705 void
706 _vm_page_queues_spin_unlock(u_short queue)
707 {
708 	cpu_ccfence();
709 	if (queue != PQ_NONE)
710 		spin_unlock(&vm_page_queues[queue].spin);
711 }
712 
713 void
714 vm_page_queue_spin_lock(vm_page_t m)
715 {
716 	_vm_page_queue_spin_lock(m);
717 }
718 
719 void
720 vm_page_queues_spin_lock(u_short queue)
721 {
722 	_vm_page_queues_spin_lock(queue);
723 }
724 
725 void
726 vm_page_queue_spin_unlock(vm_page_t m)
727 {
728 	_vm_page_queue_spin_unlock(m);
729 }
730 
731 void
732 vm_page_queues_spin_unlock(u_short queue)
733 {
734 	_vm_page_queues_spin_unlock(queue);
735 }
736 
737 /*
738  * This locks the specified vm_page and its queue in the proper order
739  * (page first, then queue).  The queue may change so the caller must
740  * recheck on return.
741  */
742 static __inline
743 void
744 _vm_page_and_queue_spin_lock(vm_page_t m)
745 {
746 	vm_page_spin_lock(m);
747 	_vm_page_queue_spin_lock(m);
748 }
749 
750 static __inline
751 void
752 _vm_page_and_queue_spin_unlock(vm_page_t m)
753 {
754 	_vm_page_queues_spin_unlock(m->queue);
755 	vm_page_spin_unlock(m);
756 }
757 
758 void
759 vm_page_and_queue_spin_unlock(vm_page_t m)
760 {
761 	_vm_page_and_queue_spin_unlock(m);
762 }
763 
764 void
765 vm_page_and_queue_spin_lock(vm_page_t m)
766 {
767 	_vm_page_and_queue_spin_lock(m);
768 }
769 
770 /*
771  * Helper function removes vm_page from its current queue.
772  * Returns the base queue the page used to be on.
773  *
774  * The vm_page and the queue must be spinlocked.
775  * This function will unlock the queue but leave the page spinlocked.
776  */
777 static __inline u_short
778 _vm_page_rem_queue_spinlocked(vm_page_t m)
779 {
780 	struct vpgqueues *pq;
781 	u_short queue;
782 	u_short oqueue;
783 	long *cnt;
784 
785 	queue = m->queue;
786 	if (queue != PQ_NONE) {
787 		pq = &vm_page_queues[queue];
788 		TAILQ_REMOVE(&pq->pl, m, pageq);
789 
790 		/*
791 		 * Adjust our pcpu stats.  In order for the nominal low-memory
792 		 * algorithms to work properly we don't let any pcpu stat get
793 		 * too negative before we force it to be rolled-up into the
794 		 * global stats.  Otherwise our pageout and vm_wait tests
795 		 * will fail badly.
796 		 *
797 		 * The idea here is to reduce unnecessary SMP cache
798 		 * mastership changes in the global vmstats, which can be
799 		 * particularly bad in multi-socket systems.
800 		 */
801 		cnt = (long *)((char *)&mycpu->gd_vmstats_adj + pq->cnt_offset);
802 		atomic_add_long(cnt, -1);
803 		if (*cnt < -VMMETER_SLOP_COUNT) {
804 			u_long copy = atomic_swap_long(cnt, 0);
805 			cnt = (long *)((char *)&vmstats + pq->cnt_offset);
806 			atomic_add_long(cnt, copy);
807 			cnt = (long *)((char *)&mycpu->gd_vmstats +
808 				      pq->cnt_offset);
809 			atomic_add_long(cnt, copy);
810 		}
811 		pq->lcnt--;
812 		m->queue = PQ_NONE;
813 		oqueue = queue;
814 		queue -= m->pc;
815 		vm_page_queues_spin_unlock(oqueue);	/* intended */
816 	}
817 	return queue;
818 }
819 
820 /*
821  * Helper function places the vm_page on the specified queue.  Generally
822  * speaking only PQ_FREE pages are placed at the head, to allow them to
823  * be allocated sooner rather than later on the assumption that they
824  * are cache-hot.
825  *
826  * The vm_page must be spinlocked.
827  * This function will return with both the page and the queue locked.
828  */
829 static __inline void
830 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
831 {
832 	struct vpgqueues *pq;
833 	u_long *cnt;
834 
835 	KKASSERT(m->queue == PQ_NONE);
836 
837 	if (queue != PQ_NONE) {
838 		vm_page_queues_spin_lock(queue);
839 		pq = &vm_page_queues[queue];
840 		++pq->lcnt;
841 
842 		/*
843 		 * Adjust our pcpu stats.  If a system entity really needs
844 		 * to incorporate the count it will call vmstats_rollup()
845 		 * to roll it all up into the global vmstats strufture.
846 		 */
847 		cnt = (long *)((char *)&mycpu->gd_vmstats_adj + pq->cnt_offset);
848 		atomic_add_long(cnt, 1);
849 
850 		/*
851 		 * PQ_FREE is always handled LIFO style to try to provide
852 		 * cache-hot pages to programs.
853 		 */
854 		m->queue = queue;
855 		if (queue - m->pc == PQ_FREE) {
856 			TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
857 		} else if (athead) {
858 			TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
859 		} else {
860 			TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
861 		}
862 		/* leave the queue spinlocked */
863 	}
864 }
865 
866 /*
867  * Wait until page is no longer BUSY.  If also_m_busy is TRUE we wait
868  * until the page is no longer BUSY or SBUSY (busy_count field is 0).
869  *
870  * Returns TRUE if it had to sleep, FALSE if we did not.  Only one sleep
871  * call will be made before returning.
872  *
873  * This function does NOT busy the page and on return the page is not
874  * guaranteed to be available.
875  */
876 void
877 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
878 {
879 	u_int32_t busy_count;
880 
881 	for (;;) {
882 		busy_count = m->busy_count;
883 		cpu_ccfence();
884 
885 		if ((busy_count & PBUSY_LOCKED) == 0 &&
886 		    (also_m_busy == 0 || (busy_count & PBUSY_MASK) == 0)) {
887 			break;
888 		}
889 		tsleep_interlock(m, 0);
890 		if (atomic_cmpset_int(&m->busy_count, busy_count,
891 				      busy_count | PBUSY_WANTED)) {
892 			atomic_set_int(&m->flags, PG_REFERENCED);
893 			tsleep(m, PINTERLOCKED, msg, 0);
894 			break;
895 		}
896 	}
897 }
898 
899 /*
900  * This calculates and returns a page color given an optional VM object and
901  * either a pindex or an iterator.  We attempt to return a cpu-localized
902  * pg_color that is still roughly 16-way set-associative.  The CPU topology
903  * is used if it was probed.
904  *
905  * The caller may use the returned value to index into e.g. PQ_FREE when
906  * allocating a page in order to nominally obtain pages that are hopefully
907  * already localized to the requesting cpu.  This function is not able to
908  * provide any sort of guarantee of this, but does its best to improve
909  * hardware cache management performance.
910  *
911  * WARNING! The caller must mask the returned value with PQ_L2_MASK.
912  */
913 u_short
914 vm_get_pg_color(int cpuid, vm_object_t object, vm_pindex_t pindex)
915 {
916 	u_short pg_color;
917 	int phys_id;
918 	int core_id;
919 	int object_pg_color;
920 
921 	phys_id = get_cpu_phys_id(cpuid);
922 	core_id = get_cpu_core_id(cpuid);
923 	object_pg_color = object ? object->pg_color : 0;
924 
925 	if (cpu_topology_phys_ids && cpu_topology_core_ids) {
926 		int grpsize;
927 
928 		/*
929 		 * Break us down by socket and cpu
930 		 */
931 		pg_color = phys_id * PQ_L2_SIZE / cpu_topology_phys_ids;
932 		pg_color += core_id * PQ_L2_SIZE /
933 			    (cpu_topology_core_ids * cpu_topology_phys_ids);
934 
935 		/*
936 		 * Calculate remaining component for object/queue color
937 		 */
938 		grpsize = PQ_L2_SIZE / (cpu_topology_core_ids *
939 					cpu_topology_phys_ids);
940 		if (grpsize >= 8) {
941 			pg_color += (pindex + object_pg_color) % grpsize;
942 		} else {
943 			if (grpsize <= 2) {
944 				grpsize = 8;
945 			} else {
946 				/* 3->9, 4->8, 5->10, 6->12, 7->14 */
947 				grpsize += grpsize;
948 				if (grpsize < 8)
949 					grpsize += grpsize;
950 			}
951 			pg_color += (pindex + object_pg_color) % grpsize;
952 		}
953 	} else {
954 		/*
955 		 * Unknown topology, distribute things evenly.
956 		 */
957 		pg_color = cpuid * PQ_L2_SIZE / ncpus;
958 		pg_color += pindex + object_pg_color;
959 	}
960 	return (pg_color & PQ_L2_MASK);
961 }
962 
963 /*
964  * Wait until BUSY can be set, then set it.  If also_m_busy is TRUE we
965  * also wait for m->busy_count to become 0 before setting PBUSY_LOCKED.
966  */
967 void
968 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
969 				     int also_m_busy, const char *msg
970 				     VM_PAGE_DEBUG_ARGS)
971 {
972 	u_int32_t busy_count;
973 
974 	for (;;) {
975 		busy_count = m->busy_count;
976 		cpu_ccfence();
977 		if (busy_count & PBUSY_LOCKED) {
978 			tsleep_interlock(m, 0);
979 			if (atomic_cmpset_int(&m->busy_count, busy_count,
980 					  busy_count | PBUSY_WANTED)) {
981 				atomic_set_int(&m->flags, PG_REFERENCED);
982 				tsleep(m, PINTERLOCKED, msg, 0);
983 			}
984 		} else if (also_m_busy && busy_count) {
985 			tsleep_interlock(m, 0);
986 			if (atomic_cmpset_int(&m->busy_count, busy_count,
987 					  busy_count | PBUSY_WANTED)) {
988 				atomic_set_int(&m->flags, PG_REFERENCED);
989 				tsleep(m, PINTERLOCKED, msg, 0);
990 			}
991 		} else {
992 			if (atomic_cmpset_int(&m->busy_count, busy_count,
993 					      busy_count | PBUSY_LOCKED)) {
994 #ifdef VM_PAGE_DEBUG
995 				m->busy_func = func;
996 				m->busy_line = lineno;
997 #endif
998 				break;
999 			}
1000 		}
1001 	}
1002 }
1003 
1004 /*
1005  * Attempt to set BUSY.  If also_m_busy is TRUE we only succeed if
1006  * m->busy_count is also 0.
1007  *
1008  * Returns non-zero on failure.
1009  */
1010 int
1011 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
1012 				    VM_PAGE_DEBUG_ARGS)
1013 {
1014 	u_int32_t busy_count;
1015 
1016 	for (;;) {
1017 		busy_count = m->busy_count;
1018 		cpu_ccfence();
1019 		if (busy_count & PBUSY_LOCKED)
1020 			return TRUE;
1021 		if (also_m_busy && (busy_count & PBUSY_MASK) != 0)
1022 			return TRUE;
1023 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1024 				      busy_count | PBUSY_LOCKED)) {
1025 #ifdef VM_PAGE_DEBUG
1026 				m->busy_func = func;
1027 				m->busy_line = lineno;
1028 #endif
1029 			return FALSE;
1030 		}
1031 	}
1032 }
1033 
1034 /*
1035  * Clear the BUSY flag and return non-zero to indicate to the caller
1036  * that a wakeup() should be performed.
1037  *
1038  * The vm_page must be spinlocked and will remain spinlocked on return.
1039  * The related queue must NOT be spinlocked (which could deadlock us).
1040  *
1041  * (inline version)
1042  */
1043 static __inline
1044 int
1045 _vm_page_wakeup(vm_page_t m)
1046 {
1047 	u_int32_t busy_count;
1048 
1049 	for (;;) {
1050 		busy_count = m->busy_count;
1051 		cpu_ccfence();
1052 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1053 				      busy_count &
1054 				      ~(PBUSY_LOCKED | PBUSY_WANTED))) {
1055 			break;
1056 		}
1057 	}
1058 	return((int)(busy_count & PBUSY_WANTED));
1059 }
1060 
1061 /*
1062  * Clear the BUSY flag and wakeup anyone waiting for the page.  This
1063  * is typically the last call you make on a page before moving onto
1064  * other things.
1065  */
1066 void
1067 vm_page_wakeup(vm_page_t m)
1068 {
1069         KASSERT(m->busy_count & PBUSY_LOCKED,
1070 		("vm_page_wakeup: page not busy!!!"));
1071 	vm_page_spin_lock(m);
1072 	if (_vm_page_wakeup(m)) {
1073 		vm_page_spin_unlock(m);
1074 		wakeup(m);
1075 	} else {
1076 		vm_page_spin_unlock(m);
1077 	}
1078 }
1079 
1080 /*
1081  * Holding a page keeps it from being reused.  Other parts of the system
1082  * can still disassociate the page from its current object and free it, or
1083  * perform read or write I/O on it and/or otherwise manipulate the page,
1084  * but if the page is held the VM system will leave the page and its data
1085  * intact and not reuse the page for other purposes until the last hold
1086  * reference is released.  (see vm_page_wire() if you want to prevent the
1087  * page from being disassociated from its object too).
1088  *
1089  * The caller must still validate the contents of the page and, if necessary,
1090  * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
1091  * before manipulating the page.
1092  *
1093  * XXX get vm_page_spin_lock() here and move FREE->HOLD if necessary
1094  */
1095 void
1096 vm_page_hold(vm_page_t m)
1097 {
1098 	vm_page_spin_lock(m);
1099 	atomic_add_int(&m->hold_count, 1);
1100 	if (m->queue - m->pc == PQ_FREE) {
1101 		_vm_page_queue_spin_lock(m);
1102 		_vm_page_rem_queue_spinlocked(m);
1103 		_vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
1104 		_vm_page_queue_spin_unlock(m);
1105 	}
1106 	vm_page_spin_unlock(m);
1107 }
1108 
1109 /*
1110  * The opposite of vm_page_hold().  If the page is on the HOLD queue
1111  * it was freed while held and must be moved back to the FREE queue.
1112  */
1113 void
1114 vm_page_unhold(vm_page_t m)
1115 {
1116 	KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1117 		("vm_page_unhold: pg %p illegal hold_count (%d) or on FREE queue (%d)",
1118 		 m, m->hold_count, m->queue - m->pc));
1119 	vm_page_spin_lock(m);
1120 	atomic_add_int(&m->hold_count, -1);
1121 	if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1122 		_vm_page_queue_spin_lock(m);
1123 		_vm_page_rem_queue_spinlocked(m);
1124 		_vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
1125 		_vm_page_queue_spin_unlock(m);
1126 	}
1127 	vm_page_spin_unlock(m);
1128 }
1129 
1130 /*
1131  *	vm_page_getfake:
1132  *
1133  *	Create a fictitious page with the specified physical address and
1134  *	memory attribute.  The memory attribute is the only the machine-
1135  *	dependent aspect of a fictitious page that must be initialized.
1136  */
1137 
1138 void
1139 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1140 {
1141 
1142 	if ((m->flags & PG_FICTITIOUS) != 0) {
1143 		/*
1144 		 * The page's memattr might have changed since the
1145 		 * previous initialization.  Update the pmap to the
1146 		 * new memattr.
1147 		 */
1148 		goto memattr;
1149 	}
1150 	m->phys_addr = paddr;
1151 	m->queue = PQ_NONE;
1152 	/* Fictitious pages don't use "segind". */
1153 	/* Fictitious pages don't use "order" or "pool". */
1154 	m->flags = PG_FICTITIOUS | PG_UNMANAGED;
1155 	m->busy_count = PBUSY_LOCKED;
1156 	m->wire_count = 1;
1157 	spin_init(&m->spin, "fake_page");
1158 	pmap_page_init(m);
1159 memattr:
1160 	pmap_page_set_memattr(m, memattr);
1161 }
1162 
1163 /*
1164  * Inserts the given vm_page into the object and object list.
1165  *
1166  * The pagetables are not updated but will presumably fault the page
1167  * in if necessary, or if a kernel page the caller will at some point
1168  * enter the page into the kernel's pmap.  We are not allowed to block
1169  * here so we *can't* do this anyway.
1170  *
1171  * This routine may not block.
1172  * This routine must be called with the vm_object held.
1173  * This routine must be called with a critical section held.
1174  *
1175  * This routine returns TRUE if the page was inserted into the object
1176  * successfully, and FALSE if the page already exists in the object.
1177  */
1178 int
1179 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1180 {
1181 	ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1182 	if (m->object != NULL)
1183 		panic("vm_page_insert: already inserted");
1184 
1185 	atomic_add_int(&object->generation, 1);
1186 
1187 	/*
1188 	 * Record the object/offset pair in this page and add the
1189 	 * pv_list_count of the page to the object.
1190 	 *
1191 	 * The vm_page spin lock is required for interactions with the pmap.
1192 	 */
1193 	vm_page_spin_lock(m);
1194 	m->object = object;
1195 	m->pindex = pindex;
1196 	if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1197 		m->object = NULL;
1198 		m->pindex = 0;
1199 		vm_page_spin_unlock(m);
1200 		return FALSE;
1201 	}
1202 	++object->resident_page_count;
1203 	++mycpu->gd_vmtotal.t_rm;
1204 	vm_page_spin_unlock(m);
1205 
1206 	/*
1207 	 * Since we are inserting a new and possibly dirty page,
1208 	 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1209 	 */
1210 	if ((m->valid & m->dirty) ||
1211 	    (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1212 		vm_object_set_writeable_dirty(object);
1213 
1214 	/*
1215 	 * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1216 	 */
1217 	swap_pager_page_inserted(m);
1218 	return TRUE;
1219 }
1220 
1221 /*
1222  * Removes the given vm_page_t from the (object,index) table
1223  *
1224  * The underlying pmap entry (if any) is NOT removed here.
1225  * This routine may not block.
1226  *
1227  * The page must be BUSY and will remain BUSY on return.
1228  * No other requirements.
1229  *
1230  * NOTE: FreeBSD side effect was to unbusy the page on return.  We leave
1231  *	 it busy.
1232  */
1233 void
1234 vm_page_remove(vm_page_t m)
1235 {
1236 	vm_object_t object;
1237 
1238 	if (m->object == NULL) {
1239 		return;
1240 	}
1241 
1242 	if ((m->busy_count & PBUSY_LOCKED) == 0)
1243 		panic("vm_page_remove: page not busy");
1244 
1245 	object = m->object;
1246 
1247 	vm_object_hold(object);
1248 
1249 	/*
1250 	 * Remove the page from the object and update the object.
1251 	 *
1252 	 * The vm_page spin lock is required for interactions with the pmap.
1253 	 */
1254 	vm_page_spin_lock(m);
1255 	vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1256 	--object->resident_page_count;
1257 	--mycpu->gd_vmtotal.t_rm;
1258 	m->object = NULL;
1259 	atomic_add_int(&object->generation, 1);
1260 	vm_page_spin_unlock(m);
1261 
1262 	vm_object_drop(object);
1263 }
1264 
1265 /*
1266  * Locate and return the page at (object, pindex), or NULL if the
1267  * page could not be found.
1268  *
1269  * The caller must hold the vm_object token.
1270  */
1271 vm_page_t
1272 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1273 {
1274 	vm_page_t m;
1275 
1276 	/*
1277 	 * Search the hash table for this object/offset pair
1278 	 */
1279 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1280 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1281 	KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
1282 	return(m);
1283 }
1284 
1285 vm_page_t
1286 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1287 					    vm_pindex_t pindex,
1288 					    int also_m_busy, const char *msg
1289 					    VM_PAGE_DEBUG_ARGS)
1290 {
1291 	u_int32_t busy_count;
1292 	vm_page_t m;
1293 
1294 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1295 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1296 	while (m) {
1297 		KKASSERT(m->object == object && m->pindex == pindex);
1298 		busy_count = m->busy_count;
1299 		cpu_ccfence();
1300 		if (busy_count & PBUSY_LOCKED) {
1301 			tsleep_interlock(m, 0);
1302 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1303 					  busy_count | PBUSY_WANTED)) {
1304 				atomic_set_int(&m->flags, PG_REFERENCED);
1305 				tsleep(m, PINTERLOCKED, msg, 0);
1306 				m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1307 							      pindex);
1308 			}
1309 		} else if (also_m_busy && busy_count) {
1310 			tsleep_interlock(m, 0);
1311 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1312 					  busy_count | PBUSY_WANTED)) {
1313 				atomic_set_int(&m->flags, PG_REFERENCED);
1314 				tsleep(m, PINTERLOCKED, msg, 0);
1315 				m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1316 							      pindex);
1317 			}
1318 		} else if (atomic_cmpset_int(&m->busy_count, busy_count,
1319 					     busy_count | PBUSY_LOCKED)) {
1320 #ifdef VM_PAGE_DEBUG
1321 			m->busy_func = func;
1322 			m->busy_line = lineno;
1323 #endif
1324 			break;
1325 		}
1326 	}
1327 	return m;
1328 }
1329 
1330 /*
1331  * Attempt to lookup and busy a page.
1332  *
1333  * Returns NULL if the page could not be found
1334  *
1335  * Returns a vm_page and error == TRUE if the page exists but could not
1336  * be busied.
1337  *
1338  * Returns a vm_page and error == FALSE on success.
1339  */
1340 vm_page_t
1341 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1342 					   vm_pindex_t pindex,
1343 					   int also_m_busy, int *errorp
1344 					   VM_PAGE_DEBUG_ARGS)
1345 {
1346 	u_int32_t busy_count;
1347 	vm_page_t m;
1348 
1349 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1350 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1351 	*errorp = FALSE;
1352 	while (m) {
1353 		KKASSERT(m->object == object && m->pindex == pindex);
1354 		busy_count = m->busy_count;
1355 		cpu_ccfence();
1356 		if (busy_count & PBUSY_LOCKED) {
1357 			*errorp = TRUE;
1358 			break;
1359 		}
1360 		if (also_m_busy && busy_count) {
1361 			*errorp = TRUE;
1362 			break;
1363 		}
1364 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1365 				      busy_count | PBUSY_LOCKED)) {
1366 #ifdef VM_PAGE_DEBUG
1367 			m->busy_func = func;
1368 			m->busy_line = lineno;
1369 #endif
1370 			break;
1371 		}
1372 	}
1373 	return m;
1374 }
1375 
1376 /*
1377  * Returns a page that is only soft-busied for use by the caller in
1378  * a read-only fashion.  Returns NULL if the page could not be found,
1379  * the soft busy could not be obtained, or the page data is invalid.
1380  */
1381 vm_page_t
1382 vm_page_lookup_sbusy_try(struct vm_object *object, vm_pindex_t pindex,
1383 			 int pgoff, int pgbytes)
1384 {
1385 	vm_page_t m;
1386 
1387 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1388 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1389 	if (m) {
1390 		if ((m->valid != VM_PAGE_BITS_ALL &&
1391 		     !vm_page_is_valid(m, pgoff, pgbytes)) ||
1392 		    (m->flags & PG_FICTITIOUS)) {
1393 			m = NULL;
1394 		} else if (vm_page_sbusy_try(m)) {
1395 			m = NULL;
1396 		} else if ((m->valid != VM_PAGE_BITS_ALL &&
1397 			    !vm_page_is_valid(m, pgoff, pgbytes)) ||
1398 			   (m->flags & PG_FICTITIOUS)) {
1399 			vm_page_sbusy_drop(m);
1400 			m = NULL;
1401 		}
1402 	}
1403 	return m;
1404 }
1405 
1406 /*
1407  * Caller must hold the related vm_object
1408  */
1409 vm_page_t
1410 vm_page_next(vm_page_t m)
1411 {
1412 	vm_page_t next;
1413 
1414 	next = vm_page_rb_tree_RB_NEXT(m);
1415 	if (next && next->pindex != m->pindex + 1)
1416 		next = NULL;
1417 	return (next);
1418 }
1419 
1420 /*
1421  * vm_page_rename()
1422  *
1423  * Move the given vm_page from its current object to the specified
1424  * target object/offset.  The page must be busy and will remain so
1425  * on return.
1426  *
1427  * new_object must be held.
1428  * This routine might block. XXX ?
1429  *
1430  * NOTE: Swap associated with the page must be invalidated by the move.  We
1431  *       have to do this for several reasons:  (1) we aren't freeing the
1432  *       page, (2) we are dirtying the page, (3) the VM system is probably
1433  *       moving the page from object A to B, and will then later move
1434  *       the backing store from A to B and we can't have a conflict.
1435  *
1436  * NOTE: We *always* dirty the page.  It is necessary both for the
1437  *       fact that we moved it, and because we may be invalidating
1438  *	 swap.  If the page is on the cache, we have to deactivate it
1439  *	 or vm_page_dirty() will panic.  Dirty pages are not allowed
1440  *	 on the cache.
1441  */
1442 void
1443 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1444 {
1445 	KKASSERT(m->busy_count & PBUSY_LOCKED);
1446 	ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1447 	if (m->object) {
1448 		ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1449 		vm_page_remove(m);
1450 	}
1451 	if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1452 		panic("vm_page_rename: target exists (%p,%"PRIu64")",
1453 		      new_object, new_pindex);
1454 	}
1455 	if (m->queue - m->pc == PQ_CACHE)
1456 		vm_page_deactivate(m);
1457 	vm_page_dirty(m);
1458 }
1459 
1460 /*
1461  * vm_page_unqueue() without any wakeup.  This routine is used when a page
1462  * is to remain BUSYied by the caller.
1463  *
1464  * This routine may not block.
1465  */
1466 void
1467 vm_page_unqueue_nowakeup(vm_page_t m)
1468 {
1469 	vm_page_and_queue_spin_lock(m);
1470 	(void)_vm_page_rem_queue_spinlocked(m);
1471 	vm_page_spin_unlock(m);
1472 }
1473 
1474 /*
1475  * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1476  * if necessary.
1477  *
1478  * This routine may not block.
1479  */
1480 void
1481 vm_page_unqueue(vm_page_t m)
1482 {
1483 	u_short queue;
1484 
1485 	vm_page_and_queue_spin_lock(m);
1486 	queue = _vm_page_rem_queue_spinlocked(m);
1487 	if (queue == PQ_FREE || queue == PQ_CACHE) {
1488 		vm_page_spin_unlock(m);
1489 		pagedaemon_wakeup();
1490 	} else {
1491 		vm_page_spin_unlock(m);
1492 	}
1493 }
1494 
1495 /*
1496  * vm_page_list_find()
1497  *
1498  * Find a page on the specified queue with color optimization.
1499  *
1500  * The page coloring optimization attempts to locate a page that does
1501  * not overload other nearby pages in the object in the cpu's L1 or L2
1502  * caches.  We need this optimization because cpu caches tend to be
1503  * physical caches, while object spaces tend to be virtual.
1504  *
1505  * The page coloring optimization also, very importantly, tries to localize
1506  * memory to cpus and physical sockets.
1507  *
1508  * On MP systems each PQ_FREE and PQ_CACHE color queue has its own spinlock
1509  * and the algorithm is adjusted to localize allocations on a per-core basis.
1510  * This is done by 'twisting' the colors.
1511  *
1512  * The page is returned spinlocked and removed from its queue (it will
1513  * be on PQ_NONE), or NULL. The page is not BUSY'd.  The caller
1514  * is responsible for dealing with the busy-page case (usually by
1515  * deactivating the page and looping).
1516  *
1517  * NOTE:  This routine is carefully inlined.  A non-inlined version
1518  *	  is available for outside callers but the only critical path is
1519  *	  from within this source file.
1520  *
1521  * NOTE:  This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1522  *	  represent stable storage, allowing us to order our locks vm_page
1523  *	  first, then queue.
1524  */
1525 static __inline
1526 vm_page_t
1527 _vm_page_list_find(int basequeue, int index)
1528 {
1529 	vm_page_t m;
1530 
1531 	for (;;) {
1532 		m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
1533 		if (m == NULL) {
1534 			m = _vm_page_list_find2(basequeue, index);
1535 			return(m);
1536 		}
1537 		vm_page_and_queue_spin_lock(m);
1538 		if (m->queue == basequeue + index) {
1539 			_vm_page_rem_queue_spinlocked(m);
1540 			/* vm_page_t spin held, no queue spin */
1541 			break;
1542 		}
1543 		vm_page_and_queue_spin_unlock(m);
1544 	}
1545 	return(m);
1546 }
1547 
1548 /*
1549  * If we could not find the page in the desired queue try to find it in
1550  * a nearby queue.
1551  */
1552 static vm_page_t
1553 _vm_page_list_find2(int basequeue, int index)
1554 {
1555 	struct vpgqueues *pq;
1556 	vm_page_t m = NULL;
1557 	int pqmask = PQ_SET_ASSOC_MASK >> 1;
1558 	int pqi;
1559 	int i;
1560 
1561 	index &= PQ_L2_MASK;
1562 	pq = &vm_page_queues[basequeue];
1563 
1564 	/*
1565 	 * Run local sets of 16, 32, 64, 128, and the whole queue if all
1566 	 * else fails (PQ_L2_MASK which is 255).
1567 	 */
1568 	do {
1569 		pqmask = (pqmask << 1) | 1;
1570 		for (i = 0; i <= pqmask; ++i) {
1571 			pqi = (index & ~pqmask) | ((index + i) & pqmask);
1572 			m = TAILQ_FIRST(&pq[pqi].pl);
1573 			if (m) {
1574 				_vm_page_and_queue_spin_lock(m);
1575 				if (m->queue == basequeue + pqi) {
1576 					_vm_page_rem_queue_spinlocked(m);
1577 					return(m);
1578 				}
1579 				_vm_page_and_queue_spin_unlock(m);
1580 				--i;
1581 				continue;
1582 			}
1583 		}
1584 	} while (pqmask != PQ_L2_MASK);
1585 
1586 	return(m);
1587 }
1588 
1589 /*
1590  * Returns a vm_page candidate for allocation.  The page is not busied so
1591  * it can move around.  The caller must busy the page (and typically
1592  * deactivate it if it cannot be busied!)
1593  *
1594  * Returns a spinlocked vm_page that has been removed from its queue.
1595  */
1596 vm_page_t
1597 vm_page_list_find(int basequeue, int index)
1598 {
1599 	return(_vm_page_list_find(basequeue, index));
1600 }
1601 
1602 /*
1603  * Find a page on the cache queue with color optimization, remove it
1604  * from the queue, and busy it.  The returned page will not be spinlocked.
1605  *
1606  * A candidate failure will be deactivated.  Candidates can fail due to
1607  * being busied by someone else, in which case they will be deactivated.
1608  *
1609  * This routine may not block.
1610  *
1611  */
1612 static vm_page_t
1613 vm_page_select_cache(u_short pg_color)
1614 {
1615 	vm_page_t m;
1616 
1617 	for (;;) {
1618 		m = _vm_page_list_find(PQ_CACHE, pg_color & PQ_L2_MASK);
1619 		if (m == NULL)
1620 			break;
1621 		/*
1622 		 * (m) has been removed from its queue and spinlocked
1623 		 */
1624 		if (vm_page_busy_try(m, TRUE)) {
1625 			_vm_page_deactivate_locked(m, 0);
1626 			vm_page_spin_unlock(m);
1627 		} else {
1628 			/*
1629 			 * We successfully busied the page
1630 			 */
1631 			if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) == 0 &&
1632 			    m->hold_count == 0 &&
1633 			    m->wire_count == 0 &&
1634 			    (m->dirty & m->valid) == 0) {
1635 				vm_page_spin_unlock(m);
1636 				pagedaemon_wakeup();
1637 				return(m);
1638 			}
1639 
1640 			/*
1641 			 * The page cannot be recycled, deactivate it.
1642 			 */
1643 			_vm_page_deactivate_locked(m, 0);
1644 			if (_vm_page_wakeup(m)) {
1645 				vm_page_spin_unlock(m);
1646 				wakeup(m);
1647 			} else {
1648 				vm_page_spin_unlock(m);
1649 			}
1650 		}
1651 	}
1652 	return (m);
1653 }
1654 
1655 /*
1656  * Find a free page.  We attempt to inline the nominal case and fall back
1657  * to _vm_page_select_free() otherwise.  A busied page is removed from
1658  * the queue and returned.
1659  *
1660  * This routine may not block.
1661  */
1662 static __inline vm_page_t
1663 vm_page_select_free(u_short pg_color)
1664 {
1665 	vm_page_t m;
1666 
1667 	for (;;) {
1668 		m = _vm_page_list_find(PQ_FREE, pg_color & PQ_L2_MASK);
1669 		if (m == NULL)
1670 			break;
1671 		if (vm_page_busy_try(m, TRUE)) {
1672 			/*
1673 			 * Various mechanisms such as a pmap_collect can
1674 			 * result in a busy page on the free queue.  We
1675 			 * have to move the page out of the way so we can
1676 			 * retry the allocation.  If the other thread is not
1677 			 * allocating the page then m->valid will remain 0 and
1678 			 * the pageout daemon will free the page later on.
1679 			 *
1680 			 * Since we could not busy the page, however, we
1681 			 * cannot make assumptions as to whether the page
1682 			 * will be allocated by the other thread or not,
1683 			 * so all we can do is deactivate it to move it out
1684 			 * of the way.  In particular, if the other thread
1685 			 * wires the page it may wind up on the inactive
1686 			 * queue and the pageout daemon will have to deal
1687 			 * with that case too.
1688 			 */
1689 			_vm_page_deactivate_locked(m, 0);
1690 			vm_page_spin_unlock(m);
1691 		} else {
1692 			/*
1693 			 * Theoretically if we are able to busy the page
1694 			 * atomic with the queue removal (using the vm_page
1695 			 * lock) nobody else should be able to mess with the
1696 			 * page before us.
1697 			 */
1698 			KKASSERT((m->flags & (PG_UNMANAGED |
1699 					      PG_NEED_COMMIT)) == 0);
1700 			KASSERT(m->hold_count == 0, ("m->hold_count is not zero "
1701 						     "pg %p q=%d flags=%08x hold=%d wire=%d",
1702 						     m, m->queue, m->flags, m->hold_count, m->wire_count));
1703 			KKASSERT(m->wire_count == 0);
1704 			vm_page_spin_unlock(m);
1705 			pagedaemon_wakeup();
1706 
1707 			/* return busied and removed page */
1708 			return(m);
1709 		}
1710 	}
1711 	return(m);
1712 }
1713 
1714 /*
1715  * vm_page_alloc()
1716  *
1717  * Allocate and return a memory cell associated with this VM object/offset
1718  * pair.  If object is NULL an unassociated page will be allocated.
1719  *
1720  * The returned page will be busied and removed from its queues.  This
1721  * routine can block and may return NULL if a race occurs and the page
1722  * is found to already exist at the specified (object, pindex).
1723  *
1724  *	VM_ALLOC_NORMAL		allow use of cache pages, nominal free drain
1725  *	VM_ALLOC_QUICK		like normal but cannot use cache
1726  *	VM_ALLOC_SYSTEM		greater free drain
1727  *	VM_ALLOC_INTERRUPT	allow free list to be completely drained
1728  *	VM_ALLOC_ZERO		advisory request for pre-zero'd page only
1729  *	VM_ALLOC_FORCE_ZERO	advisory request for pre-zero'd page only
1730  *	VM_ALLOC_NULL_OK	ok to return NULL on insertion collision
1731  *				(see vm_page_grab())
1732  *	VM_ALLOC_USE_GD		ok to use per-gd cache
1733  *
1734  *	VM_ALLOC_CPU(n)		allocate using specified cpu localization
1735  *
1736  * The object must be held if not NULL
1737  * This routine may not block
1738  *
1739  * Additional special handling is required when called from an interrupt
1740  * (VM_ALLOC_INTERRUPT).  We are not allowed to mess with the page cache
1741  * in this case.
1742  */
1743 vm_page_t
1744 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
1745 {
1746 	globaldata_t gd;
1747 	vm_object_t obj;
1748 	vm_page_t m;
1749 	u_short pg_color;
1750 	int cpuid_local;
1751 
1752 #if 0
1753 	/*
1754 	 * Special per-cpu free VM page cache.  The pages are pre-busied
1755 	 * and pre-zerod for us.
1756 	 */
1757 	if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
1758 		crit_enter_gd(gd);
1759 		if (gd->gd_vmpg_count) {
1760 			m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
1761 			crit_exit_gd(gd);
1762 			goto done;
1763                 }
1764 		crit_exit_gd(gd);
1765         }
1766 #endif
1767 	m = NULL;
1768 
1769 	/*
1770 	 * CPU LOCALIZATION
1771 	 *
1772 	 * CPU localization algorithm.  Break the page queues up by physical
1773 	 * id and core id (note that two cpu threads will have the same core
1774 	 * id, and core_id != gd_cpuid).
1775 	 *
1776 	 * This is nowhere near perfect, for example the last pindex in a
1777 	 * subgroup will overflow into the next cpu or package.  But this
1778 	 * should get us good page reuse locality in heavy mixed loads.
1779 	 *
1780 	 * (may be executed before the APs are started, so other GDs might
1781 	 *  not exist!)
1782 	 */
1783 	if (page_req & VM_ALLOC_CPU_SPEC)
1784 		cpuid_local = VM_ALLOC_GETCPU(page_req);
1785 	else
1786 		cpuid_local = mycpu->gd_cpuid;
1787 
1788 	pg_color = vm_get_pg_color(cpuid_local, object, pindex);
1789 
1790 	KKASSERT(page_req &
1791 		(VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
1792 		 VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1793 
1794 	/*
1795 	 * Certain system threads (pageout daemon, buf_daemon's) are
1796 	 * allowed to eat deeper into the free page list.
1797 	 */
1798 	if (curthread->td_flags & TDF_SYSTHREAD)
1799 		page_req |= VM_ALLOC_SYSTEM;
1800 
1801 	/*
1802 	 * Impose various limitations.  Note that the v_free_reserved test
1803 	 * must match the opposite of vm_page_count_target() to avoid
1804 	 * livelocks, be careful.
1805 	 */
1806 loop:
1807 	gd = mycpu;
1808 	if (gd->gd_vmstats.v_free_count >= gd->gd_vmstats.v_free_reserved ||
1809 	    ((page_req & VM_ALLOC_INTERRUPT) &&
1810 	     gd->gd_vmstats.v_free_count > 0) ||
1811 	    ((page_req & VM_ALLOC_SYSTEM) &&
1812 	     gd->gd_vmstats.v_cache_count == 0 &&
1813 		gd->gd_vmstats.v_free_count >
1814 		gd->gd_vmstats.v_interrupt_free_min)
1815 	) {
1816 		/*
1817 		 * The free queue has sufficient free pages to take one out.
1818 		 */
1819 		m = vm_page_select_free(pg_color);
1820 	} else if (page_req & VM_ALLOC_NORMAL) {
1821 		/*
1822 		 * Allocatable from the cache (non-interrupt only).  On
1823 		 * success, we must free the page and try again, thus
1824 		 * ensuring that vmstats.v_*_free_min counters are replenished.
1825 		 */
1826 #ifdef INVARIANTS
1827 		if (curthread->td_preempted) {
1828 			kprintf("vm_page_alloc(): warning, attempt to allocate"
1829 				" cache page from preempting interrupt\n");
1830 			m = NULL;
1831 		} else {
1832 			m = vm_page_select_cache(pg_color);
1833 		}
1834 #else
1835 		m = vm_page_select_cache(pg_color);
1836 #endif
1837 		/*
1838 		 * On success move the page into the free queue and loop.
1839 		 *
1840 		 * Only do this if we can safely acquire the vm_object lock,
1841 		 * because this is effectively a random page and the caller
1842 		 * might be holding the lock shared, we don't want to
1843 		 * deadlock.
1844 		 */
1845 		if (m != NULL) {
1846 			KASSERT(m->dirty == 0,
1847 				("Found dirty cache page %p", m));
1848 			if ((obj = m->object) != NULL) {
1849 				if (vm_object_hold_try(obj)) {
1850 					vm_page_protect(m, VM_PROT_NONE);
1851 					vm_page_free(m);
1852 					/* m->object NULL here */
1853 					vm_object_drop(obj);
1854 				} else {
1855 					vm_page_deactivate(m);
1856 					vm_page_wakeup(m);
1857 				}
1858 			} else {
1859 				vm_page_protect(m, VM_PROT_NONE);
1860 				vm_page_free(m);
1861 			}
1862 			goto loop;
1863 		}
1864 
1865 		/*
1866 		 * On failure return NULL
1867 		 */
1868 		atomic_add_int(&vm_pageout_deficit, 1);
1869 		pagedaemon_wakeup();
1870 		return (NULL);
1871 	} else {
1872 		/*
1873 		 * No pages available, wakeup the pageout daemon and give up.
1874 		 */
1875 		atomic_add_int(&vm_pageout_deficit, 1);
1876 		pagedaemon_wakeup();
1877 		return (NULL);
1878 	}
1879 
1880 	/*
1881 	 * v_free_count can race so loop if we don't find the expected
1882 	 * page.
1883 	 */
1884 	if (m == NULL) {
1885 		vmstats_rollup();
1886 		goto loop;
1887 	}
1888 
1889 	/*
1890 	 * Good page found.  The page has already been busied for us and
1891 	 * removed from its queues.
1892 	 */
1893 	KASSERT(m->dirty == 0,
1894 		("vm_page_alloc: free/cache page %p was dirty", m));
1895 	KKASSERT(m->queue == PQ_NONE);
1896 
1897 #if 0
1898 done:
1899 #endif
1900 	/*
1901 	 * Initialize the structure, inheriting some flags but clearing
1902 	 * all the rest.  The page has already been busied for us.
1903 	 */
1904 	vm_page_flag_clear(m, ~PG_KEEP_NEWPAGE_MASK);
1905 
1906 	KKASSERT(m->wire_count == 0);
1907 	KKASSERT((m->busy_count & PBUSY_MASK) == 0);
1908 	m->act_count = 0;
1909 	m->valid = 0;
1910 
1911 	/*
1912 	 * Caller must be holding the object lock (asserted by
1913 	 * vm_page_insert()).
1914 	 *
1915 	 * NOTE: Inserting a page here does not insert it into any pmaps
1916 	 *	 (which could cause us to block allocating memory).
1917 	 *
1918 	 * NOTE: If no object an unassociated page is allocated, m->pindex
1919 	 *	 can be used by the caller for any purpose.
1920 	 */
1921 	if (object) {
1922 		if (vm_page_insert(m, object, pindex) == FALSE) {
1923 			vm_page_free(m);
1924 			if ((page_req & VM_ALLOC_NULL_OK) == 0)
1925 				panic("PAGE RACE %p[%ld]/%p",
1926 				      object, (long)pindex, m);
1927 			m = NULL;
1928 		}
1929 	} else {
1930 		m->pindex = pindex;
1931 	}
1932 
1933 	/*
1934 	 * Don't wakeup too often - wakeup the pageout daemon when
1935 	 * we would be nearly out of memory.
1936 	 */
1937 	pagedaemon_wakeup();
1938 
1939 	/*
1940 	 * A BUSY page is returned.
1941 	 */
1942 	return (m);
1943 }
1944 
1945 /*
1946  * Returns number of pages available in our DMA memory reserve
1947  * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
1948  */
1949 vm_size_t
1950 vm_contig_avail_pages(void)
1951 {
1952 	alist_blk_t blk;
1953 	alist_blk_t count;
1954 	alist_blk_t bfree;
1955 	spin_lock(&vm_contig_spin);
1956 	bfree = alist_free_info(&vm_contig_alist, &blk, &count);
1957 	spin_unlock(&vm_contig_spin);
1958 
1959 	return bfree;
1960 }
1961 
1962 /*
1963  * Attempt to allocate contiguous physical memory with the specified
1964  * requirements.
1965  */
1966 vm_page_t
1967 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
1968 		     unsigned long alignment, unsigned long boundary,
1969 		     unsigned long size, vm_memattr_t memattr)
1970 {
1971 	alist_blk_t blk;
1972 	vm_page_t m;
1973 	vm_pindex_t i;
1974 #if 0
1975 	static vm_pindex_t contig_rover;
1976 #endif
1977 
1978 	alignment >>= PAGE_SHIFT;
1979 	if (alignment == 0)
1980 		alignment = 1;
1981 	boundary >>= PAGE_SHIFT;
1982 	if (boundary == 0)
1983 		boundary = 1;
1984 	size = (size + PAGE_MASK) >> PAGE_SHIFT;
1985 
1986 #if 0
1987 	/*
1988 	 * Disabled temporarily until we find a solution for DRM (a flag
1989 	 * to always use the free space reserve, for performance).
1990 	 */
1991 	if (high == BUS_SPACE_MAXADDR && alignment <= PAGE_SIZE &&
1992 	    boundary <= PAGE_SIZE && size == 1 &&
1993 	    memattr == VM_MEMATTR_DEFAULT) {
1994 		/*
1995 		 * Any page will work, use vm_page_alloc()
1996 		 * (e.g. when used from kmem_alloc_attr())
1997 		 */
1998 		m = vm_page_alloc(NULL, (contig_rover++) & 0x7FFFFFFF,
1999 				  VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2000 				  VM_ALLOC_INTERRUPT);
2001 		m->valid = VM_PAGE_BITS_ALL;
2002 		vm_page_wire(m);
2003 		vm_page_wakeup(m);
2004 	} else
2005 #endif
2006 	{
2007 		/*
2008 		 * Use the low-memory dma reserve
2009 		 */
2010 		spin_lock(&vm_contig_spin);
2011 		blk = alist_alloc(&vm_contig_alist, 0, size);
2012 		if (blk == ALIST_BLOCK_NONE) {
2013 			spin_unlock(&vm_contig_spin);
2014 			if (bootverbose) {
2015 				kprintf("vm_page_alloc_contig: %ldk nospace\n",
2016 					(size << PAGE_SHIFT) / 1024);
2017 				print_backtrace(5);
2018 			}
2019 			return(NULL);
2020 		}
2021 		if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
2022 			alist_free(&vm_contig_alist, blk, size);
2023 			spin_unlock(&vm_contig_spin);
2024 			if (bootverbose) {
2025 				kprintf("vm_page_alloc_contig: %ldk high "
2026 					"%016jx failed\n",
2027 					(size << PAGE_SHIFT) / 1024,
2028 					(intmax_t)high);
2029 			}
2030 			return(NULL);
2031 		}
2032 		spin_unlock(&vm_contig_spin);
2033 		m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
2034 	}
2035 	if (vm_contig_verbose) {
2036 		kprintf("vm_page_alloc_contig: %016jx/%ldk "
2037 			"(%016jx-%016jx al=%lu bo=%lu pgs=%lu attr=%d\n",
2038 			(intmax_t)m->phys_addr,
2039 			(size << PAGE_SHIFT) / 1024,
2040 			low, high, alignment, boundary, size, memattr);
2041 	}
2042 	if (memattr != VM_MEMATTR_DEFAULT) {
2043 		for (i = 0;i < size; i++)
2044 			pmap_page_set_memattr(&m[i], memattr);
2045 	}
2046 	return m;
2047 }
2048 
2049 /*
2050  * Free contiguously allocated pages.  The pages will be wired but not busy.
2051  * When freeing to the alist we leave them wired and not busy.
2052  */
2053 void
2054 vm_page_free_contig(vm_page_t m, unsigned long size)
2055 {
2056 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2057 	vm_pindex_t start = pa >> PAGE_SHIFT;
2058 	vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2059 
2060 	if (vm_contig_verbose) {
2061 		kprintf("vm_page_free_contig:  %016jx/%ldk\n",
2062 			(intmax_t)pa, size / 1024);
2063 	}
2064 	if (pa < vm_low_phys_reserved) {
2065 		KKASSERT(pa + size <= vm_low_phys_reserved);
2066 		spin_lock(&vm_contig_spin);
2067 		alist_free(&vm_contig_alist, start, pages);
2068 		spin_unlock(&vm_contig_spin);
2069 	} else {
2070 		while (pages) {
2071 			vm_page_busy_wait(m, FALSE, "cpgfr");
2072 			vm_page_unwire(m, 0);
2073 			vm_page_free(m);
2074 			--pages;
2075 			++m;
2076 		}
2077 
2078 	}
2079 }
2080 
2081 
2082 /*
2083  * Wait for sufficient free memory for nominal heavy memory use kernel
2084  * operations.
2085  *
2086  * WARNING!  Be sure never to call this in any vm_pageout code path, which
2087  *	     will trivially deadlock the system.
2088  */
2089 void
2090 vm_wait_nominal(void)
2091 {
2092 	while (vm_page_count_min(0))
2093 		vm_wait(0);
2094 }
2095 
2096 /*
2097  * Test if vm_wait_nominal() would block.
2098  */
2099 int
2100 vm_test_nominal(void)
2101 {
2102 	if (vm_page_count_min(0))
2103 		return(1);
2104 	return(0);
2105 }
2106 
2107 /*
2108  * Block until free pages are available for allocation, called in various
2109  * places before memory allocations.
2110  *
2111  * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2112  * more generous then that.
2113  */
2114 void
2115 vm_wait(int timo)
2116 {
2117 	/*
2118 	 * never wait forever
2119 	 */
2120 	if (timo == 0)
2121 		timo = hz;
2122 	lwkt_gettoken(&vm_token);
2123 
2124 	if (curthread == pagethread ||
2125 	    curthread == emergpager) {
2126 		/*
2127 		 * The pageout daemon itself needs pages, this is bad.
2128 		 */
2129 		if (vm_page_count_min(0)) {
2130 			vm_pageout_pages_needed = 1;
2131 			tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2132 		}
2133 	} else {
2134 		/*
2135 		 * Wakeup the pageout daemon if necessary and wait.
2136 		 *
2137 		 * Do not wait indefinitely for the target to be reached,
2138 		 * as load might prevent it from being reached any time soon.
2139 		 * But wait a little to try to slow down page allocations
2140 		 * and to give more important threads (the pagedaemon)
2141 		 * allocation priority.
2142 		 */
2143 		if (vm_page_count_target()) {
2144 			if (vm_pages_needed == 0) {
2145 				vm_pages_needed = 1;
2146 				wakeup(&vm_pages_needed);
2147 			}
2148 			++vm_pages_waiting;	/* SMP race ok */
2149 			tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2150 		}
2151 	}
2152 	lwkt_reltoken(&vm_token);
2153 }
2154 
2155 /*
2156  * Block until free pages are available for allocation
2157  *
2158  * Called only from vm_fault so that processes page faulting can be
2159  * easily tracked.
2160  */
2161 void
2162 vm_wait_pfault(void)
2163 {
2164 	/*
2165 	 * Wakeup the pageout daemon if necessary and wait.
2166 	 *
2167 	 * Do not wait indefinitely for the target to be reached,
2168 	 * as load might prevent it from being reached any time soon.
2169 	 * But wait a little to try to slow down page allocations
2170 	 * and to give more important threads (the pagedaemon)
2171 	 * allocation priority.
2172 	 */
2173 	if (vm_page_count_min(0)) {
2174 		lwkt_gettoken(&vm_token);
2175 		while (vm_page_count_severe()) {
2176 			if (vm_page_count_target()) {
2177 				thread_t td;
2178 
2179 				if (vm_pages_needed == 0) {
2180 					vm_pages_needed = 1;
2181 					wakeup(&vm_pages_needed);
2182 				}
2183 				++vm_pages_waiting;	/* SMP race ok */
2184 				tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2185 
2186 				/*
2187 				 * Do not stay stuck in the loop if the system is trying
2188 				 * to kill the process.
2189 				 */
2190 				td = curthread;
2191 				if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2192 					break;
2193 			}
2194 		}
2195 		lwkt_reltoken(&vm_token);
2196 	}
2197 }
2198 
2199 /*
2200  * Put the specified page on the active list (if appropriate).  Ensure
2201  * that act_count is at least ACT_INIT but do not otherwise mess with it.
2202  *
2203  * The caller should be holding the page busied ? XXX
2204  * This routine may not block.
2205  */
2206 void
2207 vm_page_activate(vm_page_t m)
2208 {
2209 	u_short oqueue;
2210 
2211 	vm_page_spin_lock(m);
2212 	if (m->queue - m->pc != PQ_ACTIVE) {
2213 		_vm_page_queue_spin_lock(m);
2214 		oqueue = _vm_page_rem_queue_spinlocked(m);
2215 		/* page is left spinlocked, queue is unlocked */
2216 
2217 		if (oqueue == PQ_CACHE)
2218 			mycpu->gd_cnt.v_reactivated++;
2219 		if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2220 			if (m->act_count < ACT_INIT)
2221 				m->act_count = ACT_INIT;
2222 			_vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2223 		}
2224 		_vm_page_and_queue_spin_unlock(m);
2225 		if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2226 			pagedaemon_wakeup();
2227 	} else {
2228 		if (m->act_count < ACT_INIT)
2229 			m->act_count = ACT_INIT;
2230 		vm_page_spin_unlock(m);
2231 	}
2232 }
2233 
2234 /*
2235  * Helper routine for vm_page_free_toq() and vm_page_cache().  This
2236  * routine is called when a page has been added to the cache or free
2237  * queues.
2238  *
2239  * This routine may not block.
2240  */
2241 static __inline void
2242 vm_page_free_wakeup(void)
2243 {
2244 	globaldata_t gd = mycpu;
2245 
2246 	/*
2247 	 * If the pageout daemon itself needs pages, then tell it that
2248 	 * there are some free.
2249 	 */
2250 	if (vm_pageout_pages_needed &&
2251 	    gd->gd_vmstats.v_cache_count + gd->gd_vmstats.v_free_count >=
2252 	    gd->gd_vmstats.v_pageout_free_min
2253 	) {
2254 		vm_pageout_pages_needed = 0;
2255 		wakeup(&vm_pageout_pages_needed);
2256 	}
2257 
2258 	/*
2259 	 * Wakeup processes that are waiting on memory.
2260 	 *
2261 	 * Generally speaking we want to wakeup stuck processes as soon as
2262 	 * possible.  !vm_page_count_min(0) is the absolute minimum point
2263 	 * where we can do this.  Wait a bit longer to reduce degenerate
2264 	 * re-blocking (vm_page_free_hysteresis).  The target check is just
2265 	 * to make sure the min-check w/hysteresis does not exceed the
2266 	 * normal target.
2267 	 */
2268 	if (vm_pages_waiting) {
2269 		if (!vm_page_count_min(vm_page_free_hysteresis) ||
2270 		    !vm_page_count_target()) {
2271 			vm_pages_waiting = 0;
2272 			wakeup(&vmstats.v_free_count);
2273 			++mycpu->gd_cnt.v_ppwakeups;
2274 		}
2275 #if 0
2276 		if (!vm_page_count_target()) {
2277 			/*
2278 			 * Plenty of pages are free, wakeup everyone.
2279 			 */
2280 			vm_pages_waiting = 0;
2281 			wakeup(&vmstats.v_free_count);
2282 			++mycpu->gd_cnt.v_ppwakeups;
2283 		} else if (!vm_page_count_min(0)) {
2284 			/*
2285 			 * Some pages are free, wakeup someone.
2286 			 */
2287 			int wcount = vm_pages_waiting;
2288 			if (wcount > 0)
2289 				--wcount;
2290 			vm_pages_waiting = wcount;
2291 			wakeup_one(&vmstats.v_free_count);
2292 			++mycpu->gd_cnt.v_ppwakeups;
2293 		}
2294 #endif
2295 	}
2296 }
2297 
2298 /*
2299  * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2300  * it from its VM object.
2301  *
2302  * The vm_page must be BUSY on entry.  BUSY will be released on
2303  * return (the page will have been freed).
2304  */
2305 void
2306 vm_page_free_toq(vm_page_t m)
2307 {
2308 	mycpu->gd_cnt.v_tfree++;
2309 	KKASSERT((m->flags & PG_MAPPED) == 0);
2310 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2311 
2312 	if ((m->busy_count & PBUSY_MASK) || ((m->queue - m->pc) == PQ_FREE)) {
2313 		kprintf("vm_page_free: pindex(%lu), busy %08x, "
2314 			"hold(%d)\n",
2315 			(u_long)m->pindex, m->busy_count, m->hold_count);
2316 		if ((m->queue - m->pc) == PQ_FREE)
2317 			panic("vm_page_free: freeing free page");
2318 		else
2319 			panic("vm_page_free: freeing busy page");
2320 	}
2321 
2322 	/*
2323 	 * Remove from object, spinlock the page and its queues and
2324 	 * remove from any queue.  No queue spinlock will be held
2325 	 * after this section (because the page was removed from any
2326 	 * queue).
2327 	 */
2328 	vm_page_remove(m);
2329 	vm_page_and_queue_spin_lock(m);
2330 	_vm_page_rem_queue_spinlocked(m);
2331 
2332 	/*
2333 	 * No further management of fictitious pages occurs beyond object
2334 	 * and queue removal.
2335 	 */
2336 	if ((m->flags & PG_FICTITIOUS) != 0) {
2337 		vm_page_spin_unlock(m);
2338 		vm_page_wakeup(m);
2339 		return;
2340 	}
2341 
2342 	m->valid = 0;
2343 	vm_page_undirty(m);
2344 
2345 	if (m->wire_count != 0) {
2346 		if (m->wire_count > 1) {
2347 		    panic(
2348 			"vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2349 			m->wire_count, (long)m->pindex);
2350 		}
2351 		panic("vm_page_free: freeing wired page");
2352 	}
2353 
2354 	/*
2355 	 * Clear the UNMANAGED flag when freeing an unmanaged page.
2356 	 * Clear the NEED_COMMIT flag
2357 	 */
2358 	if (m->flags & PG_UNMANAGED)
2359 		vm_page_flag_clear(m, PG_UNMANAGED);
2360 	if (m->flags & PG_NEED_COMMIT)
2361 		vm_page_flag_clear(m, PG_NEED_COMMIT);
2362 
2363 	if (m->hold_count != 0) {
2364 		_vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2365 	} else {
2366 		_vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
2367 	}
2368 
2369 	/*
2370 	 * This sequence allows us to clear BUSY while still holding
2371 	 * its spin lock, which reduces contention vs allocators.  We
2372 	 * must not leave the queue locked or _vm_page_wakeup() may
2373 	 * deadlock.
2374 	 */
2375 	_vm_page_queue_spin_unlock(m);
2376 	if (_vm_page_wakeup(m)) {
2377 		vm_page_spin_unlock(m);
2378 		wakeup(m);
2379 	} else {
2380 		vm_page_spin_unlock(m);
2381 	}
2382 	vm_page_free_wakeup();
2383 }
2384 
2385 /*
2386  * vm_page_unmanage()
2387  *
2388  * Prevent PV management from being done on the page.  The page is
2389  * removed from the paging queues as if it were wired, and as a
2390  * consequence of no longer being managed the pageout daemon will not
2391  * touch it (since there is no way to locate the pte mappings for the
2392  * page).  madvise() calls that mess with the pmap will also no longer
2393  * operate on the page.
2394  *
2395  * Beyond that the page is still reasonably 'normal'.  Freeing the page
2396  * will clear the flag.
2397  *
2398  * This routine is used by OBJT_PHYS objects - objects using unswappable
2399  * physical memory as backing store rather then swap-backed memory and
2400  * will eventually be extended to support 4MB unmanaged physical
2401  * mappings.
2402  *
2403  * Caller must be holding the page busy.
2404  */
2405 void
2406 vm_page_unmanage(vm_page_t m)
2407 {
2408 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2409 	if ((m->flags & PG_UNMANAGED) == 0) {
2410 		if (m->wire_count == 0)
2411 			vm_page_unqueue(m);
2412 	}
2413 	vm_page_flag_set(m, PG_UNMANAGED);
2414 }
2415 
2416 /*
2417  * Mark this page as wired down by yet another map, removing it from
2418  * paging queues as necessary.
2419  *
2420  * Caller must be holding the page busy.
2421  */
2422 void
2423 vm_page_wire(vm_page_t m)
2424 {
2425 	/*
2426 	 * Only bump the wire statistics if the page is not already wired,
2427 	 * and only unqueue the page if it is on some queue (if it is unmanaged
2428 	 * it is already off the queues).  Don't do anything with fictitious
2429 	 * pages because they are always wired.
2430 	 */
2431 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2432 	if ((m->flags & PG_FICTITIOUS) == 0) {
2433 		if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2434 			if ((m->flags & PG_UNMANAGED) == 0)
2435 				vm_page_unqueue(m);
2436 			atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count, 1);
2437 		}
2438 		KASSERT(m->wire_count != 0,
2439 			("vm_page_wire: wire_count overflow m=%p", m));
2440 	}
2441 }
2442 
2443 /*
2444  * Release one wiring of this page, potentially enabling it to be paged again.
2445  *
2446  * Many pages placed on the inactive queue should actually go
2447  * into the cache, but it is difficult to figure out which.  What
2448  * we do instead, if the inactive target is well met, is to put
2449  * clean pages at the head of the inactive queue instead of the tail.
2450  * This will cause them to be moved to the cache more quickly and
2451  * if not actively re-referenced, freed more quickly.  If we just
2452  * stick these pages at the end of the inactive queue, heavy filesystem
2453  * meta-data accesses can cause an unnecessary paging load on memory bound
2454  * processes.  This optimization causes one-time-use metadata to be
2455  * reused more quickly.
2456  *
2457  * Pages marked PG_NEED_COMMIT are always activated and never placed on
2458  * the inactive queue.  This helps the pageout daemon determine memory
2459  * pressure and act on out-of-memory situations more quickly.
2460  *
2461  * BUT, if we are in a low-memory situation we have no choice but to
2462  * put clean pages on the cache queue.
2463  *
2464  * A number of routines use vm_page_unwire() to guarantee that the page
2465  * will go into either the inactive or active queues, and will NEVER
2466  * be placed in the cache - for example, just after dirtying a page.
2467  * dirty pages in the cache are not allowed.
2468  *
2469  * This routine may not block.
2470  */
2471 void
2472 vm_page_unwire(vm_page_t m, int activate)
2473 {
2474 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2475 	if (m->flags & PG_FICTITIOUS) {
2476 		/* do nothing */
2477 	} else if (m->wire_count <= 0) {
2478 		panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2479 	} else {
2480 		if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2481 			atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count,-1);
2482 			if (m->flags & PG_UNMANAGED) {
2483 				;
2484 			} else if (activate || (m->flags & PG_NEED_COMMIT)) {
2485 				vm_page_spin_lock(m);
2486 				_vm_page_add_queue_spinlocked(m,
2487 							PQ_ACTIVE + m->pc, 0);
2488 				_vm_page_and_queue_spin_unlock(m);
2489 			} else {
2490 				vm_page_spin_lock(m);
2491 				vm_page_flag_clear(m, PG_WINATCFLS);
2492 				_vm_page_add_queue_spinlocked(m,
2493 							PQ_INACTIVE + m->pc, 0);
2494 				++vm_swapcache_inactive_heuristic;
2495 				_vm_page_and_queue_spin_unlock(m);
2496 			}
2497 		}
2498 	}
2499 }
2500 
2501 /*
2502  * Move the specified page to the inactive queue.  If the page has
2503  * any associated swap, the swap is deallocated.
2504  *
2505  * Normally athead is 0 resulting in LRU operation.  athead is set
2506  * to 1 if we want this page to be 'as if it were placed in the cache',
2507  * except without unmapping it from the process address space.
2508  *
2509  * vm_page's spinlock must be held on entry and will remain held on return.
2510  * This routine may not block.
2511  */
2512 static void
2513 _vm_page_deactivate_locked(vm_page_t m, int athead)
2514 {
2515 	u_short oqueue;
2516 
2517 	/*
2518 	 * Ignore if already inactive.
2519 	 */
2520 	if (m->queue - m->pc == PQ_INACTIVE)
2521 		return;
2522 	_vm_page_queue_spin_lock(m);
2523 	oqueue = _vm_page_rem_queue_spinlocked(m);
2524 
2525 	if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2526 		if (oqueue == PQ_CACHE)
2527 			mycpu->gd_cnt.v_reactivated++;
2528 		vm_page_flag_clear(m, PG_WINATCFLS);
2529 		_vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2530 		if (athead == 0)
2531 			++vm_swapcache_inactive_heuristic;
2532 	}
2533 	/* NOTE: PQ_NONE if condition not taken */
2534 	_vm_page_queue_spin_unlock(m);
2535 	/* leaves vm_page spinlocked */
2536 }
2537 
2538 /*
2539  * Attempt to deactivate a page.
2540  *
2541  * No requirements.
2542  */
2543 void
2544 vm_page_deactivate(vm_page_t m)
2545 {
2546 	vm_page_spin_lock(m);
2547 	_vm_page_deactivate_locked(m, 0);
2548 	vm_page_spin_unlock(m);
2549 }
2550 
2551 void
2552 vm_page_deactivate_locked(vm_page_t m)
2553 {
2554 	_vm_page_deactivate_locked(m, 0);
2555 }
2556 
2557 /*
2558  * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
2559  *
2560  * This function returns non-zero if it successfully moved the page to
2561  * PQ_CACHE.
2562  *
2563  * This function unconditionally unbusies the page on return.
2564  */
2565 int
2566 vm_page_try_to_cache(vm_page_t m)
2567 {
2568 	vm_page_spin_lock(m);
2569 	if (m->dirty || m->hold_count || m->wire_count ||
2570 	    (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT))) {
2571 		if (_vm_page_wakeup(m)) {
2572 			vm_page_spin_unlock(m);
2573 			wakeup(m);
2574 		} else {
2575 			vm_page_spin_unlock(m);
2576 		}
2577 		return(0);
2578 	}
2579 	vm_page_spin_unlock(m);
2580 
2581 	/*
2582 	 * Page busied by us and no longer spinlocked.  Dirty pages cannot
2583 	 * be moved to the cache.
2584 	 */
2585 	vm_page_test_dirty(m);
2586 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2587 		vm_page_wakeup(m);
2588 		return(0);
2589 	}
2590 	vm_page_cache(m);
2591 	return(1);
2592 }
2593 
2594 /*
2595  * Attempt to free the page.  If we cannot free it, we do nothing.
2596  * 1 is returned on success, 0 on failure.
2597  *
2598  * No requirements.
2599  */
2600 int
2601 vm_page_try_to_free(vm_page_t m)
2602 {
2603 	vm_page_spin_lock(m);
2604 	if (vm_page_busy_try(m, TRUE)) {
2605 		vm_page_spin_unlock(m);
2606 		return(0);
2607 	}
2608 
2609 	/*
2610 	 * The page can be in any state, including already being on the free
2611 	 * queue.  Check to see if it really can be freed.
2612 	 */
2613 	if (m->dirty ||				/* can't free if it is dirty */
2614 	    m->hold_count ||			/* or held (XXX may be wrong) */
2615 	    m->wire_count ||			/* or wired */
2616 	    (m->flags & (PG_UNMANAGED |		/* or unmanaged */
2617 			 PG_NEED_COMMIT)) ||	/* or needs a commit */
2618 	    m->queue - m->pc == PQ_FREE ||	/* already on PQ_FREE */
2619 	    m->queue - m->pc == PQ_HOLD) {	/* already on PQ_HOLD */
2620 		if (_vm_page_wakeup(m)) {
2621 			vm_page_spin_unlock(m);
2622 			wakeup(m);
2623 		} else {
2624 			vm_page_spin_unlock(m);
2625 		}
2626 		return(0);
2627 	}
2628 	vm_page_spin_unlock(m);
2629 
2630 	/*
2631 	 * We can probably free the page.
2632 	 *
2633 	 * Page busied by us and no longer spinlocked.  Dirty pages will
2634 	 * not be freed by this function.    We have to re-test the
2635 	 * dirty bit after cleaning out the pmaps.
2636 	 */
2637 	vm_page_test_dirty(m);
2638 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2639 		vm_page_wakeup(m);
2640 		return(0);
2641 	}
2642 	vm_page_protect(m, VM_PROT_NONE);
2643 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2644 		vm_page_wakeup(m);
2645 		return(0);
2646 	}
2647 	vm_page_free(m);
2648 	return(1);
2649 }
2650 
2651 /*
2652  * vm_page_cache
2653  *
2654  * Put the specified page onto the page cache queue (if appropriate).
2655  *
2656  * The page must be busy, and this routine will release the busy and
2657  * possibly even free the page.
2658  */
2659 void
2660 vm_page_cache(vm_page_t m)
2661 {
2662 	/*
2663 	 * Not suitable for the cache
2664 	 */
2665 	if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
2666 	    (m->busy_count & PBUSY_MASK) ||
2667 	    m->wire_count || m->hold_count) {
2668 		vm_page_wakeup(m);
2669 		return;
2670 	}
2671 
2672 	/*
2673 	 * Already in the cache (and thus not mapped)
2674 	 */
2675 	if ((m->queue - m->pc) == PQ_CACHE) {
2676 		KKASSERT((m->flags & PG_MAPPED) == 0);
2677 		vm_page_wakeup(m);
2678 		return;
2679 	}
2680 
2681 	/*
2682 	 * Caller is required to test m->dirty, but note that the act of
2683 	 * removing the page from its maps can cause it to become dirty
2684 	 * on an SMP system due to another cpu running in usermode.
2685 	 */
2686 	if (m->dirty) {
2687 		panic("vm_page_cache: caching a dirty page, pindex: %ld",
2688 			(long)m->pindex);
2689 	}
2690 
2691 	/*
2692 	 * Remove all pmaps and indicate that the page is not
2693 	 * writeable or mapped.  Our vm_page_protect() call may
2694 	 * have blocked (especially w/ VM_PROT_NONE), so recheck
2695 	 * everything.
2696 	 */
2697 	vm_page_protect(m, VM_PROT_NONE);
2698 	if ((m->flags & (PG_UNMANAGED | PG_MAPPED)) ||
2699 	    (m->busy_count & PBUSY_MASK) ||
2700 	    m->wire_count || m->hold_count) {
2701 		vm_page_wakeup(m);
2702 	} else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2703 		vm_page_deactivate(m);
2704 		vm_page_wakeup(m);
2705 	} else {
2706 		_vm_page_and_queue_spin_lock(m);
2707 		_vm_page_rem_queue_spinlocked(m);
2708 		_vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
2709 		_vm_page_queue_spin_unlock(m);
2710 		if (_vm_page_wakeup(m)) {
2711 			vm_page_spin_unlock(m);
2712 			wakeup(m);
2713 		} else {
2714 			vm_page_spin_unlock(m);
2715 		}
2716 		vm_page_free_wakeup();
2717 	}
2718 }
2719 
2720 /*
2721  * vm_page_dontneed()
2722  *
2723  * Cache, deactivate, or do nothing as appropriate.  This routine
2724  * is typically used by madvise() MADV_DONTNEED.
2725  *
2726  * Generally speaking we want to move the page into the cache so
2727  * it gets reused quickly.  However, this can result in a silly syndrome
2728  * due to the page recycling too quickly.  Small objects will not be
2729  * fully cached.  On the otherhand, if we move the page to the inactive
2730  * queue we wind up with a problem whereby very large objects
2731  * unnecessarily blow away our inactive and cache queues.
2732  *
2733  * The solution is to move the pages based on a fixed weighting.  We
2734  * either leave them alone, deactivate them, or move them to the cache,
2735  * where moving them to the cache has the highest weighting.
2736  * By forcing some pages into other queues we eventually force the
2737  * system to balance the queues, potentially recovering other unrelated
2738  * space from active.  The idea is to not force this to happen too
2739  * often.
2740  *
2741  * The page must be busied.
2742  */
2743 void
2744 vm_page_dontneed(vm_page_t m)
2745 {
2746 	static int dnweight;
2747 	int dnw;
2748 	int head;
2749 
2750 	dnw = ++dnweight;
2751 
2752 	/*
2753 	 * occassionally leave the page alone
2754 	 */
2755 	if ((dnw & 0x01F0) == 0 ||
2756 	    m->queue - m->pc == PQ_INACTIVE ||
2757 	    m->queue - m->pc == PQ_CACHE
2758 	) {
2759 		if (m->act_count >= ACT_INIT)
2760 			--m->act_count;
2761 		return;
2762 	}
2763 
2764 	/*
2765 	 * If vm_page_dontneed() is inactivating a page, it must clear
2766 	 * the referenced flag; otherwise the pagedaemon will see references
2767 	 * on the page in the inactive queue and reactivate it. Until the
2768 	 * page can move to the cache queue, madvise's job is not done.
2769 	 */
2770 	vm_page_flag_clear(m, PG_REFERENCED);
2771 	pmap_clear_reference(m);
2772 
2773 	if (m->dirty == 0)
2774 		vm_page_test_dirty(m);
2775 
2776 	if (m->dirty || (dnw & 0x0070) == 0) {
2777 		/*
2778 		 * Deactivate the page 3 times out of 32.
2779 		 */
2780 		head = 0;
2781 	} else {
2782 		/*
2783 		 * Cache the page 28 times out of every 32.  Note that
2784 		 * the page is deactivated instead of cached, but placed
2785 		 * at the head of the queue instead of the tail.
2786 		 */
2787 		head = 1;
2788 	}
2789 	vm_page_spin_lock(m);
2790 	_vm_page_deactivate_locked(m, head);
2791 	vm_page_spin_unlock(m);
2792 }
2793 
2794 /*
2795  * These routines manipulate the 'soft busy' count for a page.  A soft busy
2796  * is almost like a hard BUSY except that it allows certain compatible
2797  * operations to occur on the page while it is busy.  For example, a page
2798  * undergoing a write can still be mapped read-only.
2799  *
2800  * We also use soft-busy to quickly pmap_enter shared read-only pages
2801  * without having to hold the page locked.
2802  *
2803  * The soft-busy count can be > 1 in situations where multiple threads
2804  * are pmap_enter()ing the same page simultaneously, or when two buffer
2805  * cache buffers overlap the same page.
2806  *
2807  * The caller must hold the page BUSY when making these two calls.
2808  */
2809 void
2810 vm_page_io_start(vm_page_t m)
2811 {
2812 	uint32_t ocount;
2813 
2814 	ocount = atomic_fetchadd_int(&m->busy_count, 1);
2815 	KKASSERT(ocount & PBUSY_LOCKED);
2816 }
2817 
2818 void
2819 vm_page_io_finish(vm_page_t m)
2820 {
2821 	uint32_t ocount;
2822 
2823 	ocount = atomic_fetchadd_int(&m->busy_count, -1);
2824 	KKASSERT(ocount & PBUSY_MASK);
2825 #if 0
2826 	if (((ocount - 1) & (PBUSY_LOCKED | PBUSY_MASK)) == 0)
2827 		wakeup(m);
2828 #endif
2829 }
2830 
2831 /*
2832  * Attempt to soft-busy a page.  The page must not be PBUSY_LOCKED.
2833  *
2834  * Returns 0 on success, non-zero on failure.
2835  */
2836 int
2837 vm_page_sbusy_try(vm_page_t m)
2838 {
2839 	uint32_t ocount;
2840 
2841 	if (m->busy_count & PBUSY_LOCKED)
2842 		return 1;
2843 	ocount = atomic_fetchadd_int(&m->busy_count, 1);
2844 	if (ocount & PBUSY_LOCKED) {
2845 		vm_page_sbusy_drop(m);
2846 		return 1;
2847 	}
2848 	return 0;
2849 }
2850 
2851 /*
2852  * Indicate that a clean VM page requires a filesystem commit and cannot
2853  * be reused.  Used by tmpfs.
2854  */
2855 void
2856 vm_page_need_commit(vm_page_t m)
2857 {
2858 	vm_page_flag_set(m, PG_NEED_COMMIT);
2859 	vm_object_set_writeable_dirty(m->object);
2860 }
2861 
2862 void
2863 vm_page_clear_commit(vm_page_t m)
2864 {
2865 	vm_page_flag_clear(m, PG_NEED_COMMIT);
2866 }
2867 
2868 /*
2869  * Grab a page, blocking if it is busy and allocating a page if necessary.
2870  * A busy page is returned or NULL.  The page may or may not be valid and
2871  * might not be on a queue (the caller is responsible for the disposition of
2872  * the page).
2873  *
2874  * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
2875  * page will be zero'd and marked valid.
2876  *
2877  * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
2878  * valid even if it already exists.
2879  *
2880  * If VM_ALLOC_RETRY is specified this routine will never return NULL.  Also
2881  * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
2882  * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
2883  *
2884  * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
2885  * always returned if we had blocked.
2886  *
2887  * This routine may not be called from an interrupt.
2888  *
2889  * No other requirements.
2890  */
2891 vm_page_t
2892 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2893 {
2894 	vm_page_t m;
2895 	int error;
2896 	int shared = 1;
2897 
2898 	KKASSERT(allocflags &
2899 		(VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2900 	vm_object_hold_shared(object);
2901 	for (;;) {
2902 		m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2903 		if (error) {
2904 			vm_page_sleep_busy(m, TRUE, "pgrbwt");
2905 			if ((allocflags & VM_ALLOC_RETRY) == 0) {
2906 				m = NULL;
2907 				break;
2908 			}
2909 			/* retry */
2910 		} else if (m == NULL) {
2911 			if (shared) {
2912 				vm_object_upgrade(object);
2913 				shared = 0;
2914 			}
2915 			if (allocflags & VM_ALLOC_RETRY)
2916 				allocflags |= VM_ALLOC_NULL_OK;
2917 			m = vm_page_alloc(object, pindex,
2918 					  allocflags & ~VM_ALLOC_RETRY);
2919 			if (m)
2920 				break;
2921 			vm_wait(0);
2922 			if ((allocflags & VM_ALLOC_RETRY) == 0)
2923 				goto failed;
2924 		} else {
2925 			/* m found */
2926 			break;
2927 		}
2928 	}
2929 
2930 	/*
2931 	 * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
2932 	 *
2933 	 * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
2934 	 * valid even if already valid.
2935 	 *
2936 	 * NOTE!  We have removed all of the PG_ZERO optimizations and also
2937 	 *	  removed the idle zeroing code.  These optimizations actually
2938 	 *	  slow things down on modern cpus because the zerod area is
2939 	 *	  likely uncached, placing a memory-access burden on the
2940 	 *	  accesors taking the fault.
2941 	 *
2942 	 *	  By always zeroing the page in-line with the fault, no
2943 	 *	  dynamic ram reads are needed and the caches are hot, ready
2944 	 *	  for userland to access the memory.
2945 	 */
2946 	if (m->valid == 0) {
2947 		if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
2948 			pmap_zero_page(VM_PAGE_TO_PHYS(m));
2949 			m->valid = VM_PAGE_BITS_ALL;
2950 		}
2951 	} else if (allocflags & VM_ALLOC_FORCE_ZERO) {
2952 		pmap_zero_page(VM_PAGE_TO_PHYS(m));
2953 		m->valid = VM_PAGE_BITS_ALL;
2954 	}
2955 failed:
2956 	vm_object_drop(object);
2957 	return(m);
2958 }
2959 
2960 /*
2961  * Mapping function for valid bits or for dirty bits in
2962  * a page.  May not block.
2963  *
2964  * Inputs are required to range within a page.
2965  *
2966  * No requirements.
2967  * Non blocking.
2968  */
2969 int
2970 vm_page_bits(int base, int size)
2971 {
2972 	int first_bit;
2973 	int last_bit;
2974 
2975 	KASSERT(
2976 	    base + size <= PAGE_SIZE,
2977 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
2978 	);
2979 
2980 	if (size == 0)		/* handle degenerate case */
2981 		return(0);
2982 
2983 	first_bit = base >> DEV_BSHIFT;
2984 	last_bit = (base + size - 1) >> DEV_BSHIFT;
2985 
2986 	return ((2 << last_bit) - (1 << first_bit));
2987 }
2988 
2989 /*
2990  * Sets portions of a page valid and clean.  The arguments are expected
2991  * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2992  * of any partial chunks touched by the range.  The invalid portion of
2993  * such chunks will be zero'd.
2994  *
2995  * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
2996  *	 align base to DEV_BSIZE so as not to mark clean a partially
2997  *	 truncated device block.  Otherwise the dirty page status might be
2998  *	 lost.
2999  *
3000  * This routine may not block.
3001  *
3002  * (base + size) must be less then or equal to PAGE_SIZE.
3003  */
3004 static void
3005 _vm_page_zero_valid(vm_page_t m, int base, int size)
3006 {
3007 	int frag;
3008 	int endoff;
3009 
3010 	if (size == 0)	/* handle degenerate case */
3011 		return;
3012 
3013 	/*
3014 	 * If the base is not DEV_BSIZE aligned and the valid
3015 	 * bit is clear, we have to zero out a portion of the
3016 	 * first block.
3017 	 */
3018 
3019 	if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
3020 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
3021 	) {
3022 		pmap_zero_page_area(
3023 		    VM_PAGE_TO_PHYS(m),
3024 		    frag,
3025 		    base - frag
3026 		);
3027 	}
3028 
3029 	/*
3030 	 * If the ending offset is not DEV_BSIZE aligned and the
3031 	 * valid bit is clear, we have to zero out a portion of
3032 	 * the last block.
3033 	 */
3034 
3035 	endoff = base + size;
3036 
3037 	if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3038 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
3039 	) {
3040 		pmap_zero_page_area(
3041 		    VM_PAGE_TO_PHYS(m),
3042 		    endoff,
3043 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
3044 		);
3045 	}
3046 }
3047 
3048 /*
3049  * Set valid, clear dirty bits.  If validating the entire
3050  * page we can safely clear the pmap modify bit.  We also
3051  * use this opportunity to clear the PG_NOSYNC flag.  If a process
3052  * takes a write fault on a MAP_NOSYNC memory area the flag will
3053  * be set again.
3054  *
3055  * We set valid bits inclusive of any overlap, but we can only
3056  * clear dirty bits for DEV_BSIZE chunks that are fully within
3057  * the range.
3058  *
3059  * Page must be busied?
3060  * No other requirements.
3061  */
3062 void
3063 vm_page_set_valid(vm_page_t m, int base, int size)
3064 {
3065 	_vm_page_zero_valid(m, base, size);
3066 	m->valid |= vm_page_bits(base, size);
3067 }
3068 
3069 
3070 /*
3071  * Set valid bits and clear dirty bits.
3072  *
3073  * Page must be busied by caller.
3074  *
3075  * NOTE: This function does not clear the pmap modified bit.
3076  *	 Also note that e.g. NFS may use a byte-granular base
3077  *	 and size.
3078  *
3079  * No other requirements.
3080  */
3081 void
3082 vm_page_set_validclean(vm_page_t m, int base, int size)
3083 {
3084 	int pagebits;
3085 
3086 	_vm_page_zero_valid(m, base, size);
3087 	pagebits = vm_page_bits(base, size);
3088 	m->valid |= pagebits;
3089 	m->dirty &= ~pagebits;
3090 	if (base == 0 && size == PAGE_SIZE) {
3091 		/*pmap_clear_modify(m);*/
3092 		vm_page_flag_clear(m, PG_NOSYNC);
3093 	}
3094 }
3095 
3096 /*
3097  * Set valid & dirty.  Used by buwrite()
3098  *
3099  * Page must be busied by caller.
3100  */
3101 void
3102 vm_page_set_validdirty(vm_page_t m, int base, int size)
3103 {
3104 	int pagebits;
3105 
3106 	pagebits = vm_page_bits(base, size);
3107 	m->valid |= pagebits;
3108 	m->dirty |= pagebits;
3109 	if (m->object)
3110 	       vm_object_set_writeable_dirty(m->object);
3111 }
3112 
3113 /*
3114  * Clear dirty bits.
3115  *
3116  * NOTE: This function does not clear the pmap modified bit.
3117  *	 Also note that e.g. NFS may use a byte-granular base
3118  *	 and size.
3119  *
3120  * Page must be busied?
3121  * No other requirements.
3122  */
3123 void
3124 vm_page_clear_dirty(vm_page_t m, int base, int size)
3125 {
3126 	m->dirty &= ~vm_page_bits(base, size);
3127 	if (base == 0 && size == PAGE_SIZE) {
3128 		/*pmap_clear_modify(m);*/
3129 		vm_page_flag_clear(m, PG_NOSYNC);
3130 	}
3131 }
3132 
3133 /*
3134  * Make the page all-dirty.
3135  *
3136  * Also make sure the related object and vnode reflect the fact that the
3137  * object may now contain a dirty page.
3138  *
3139  * Page must be busied?
3140  * No other requirements.
3141  */
3142 void
3143 vm_page_dirty(vm_page_t m)
3144 {
3145 #ifdef INVARIANTS
3146         int pqtype = m->queue - m->pc;
3147 #endif
3148         KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3149                 ("vm_page_dirty: page in free/cache queue!"));
3150 	if (m->dirty != VM_PAGE_BITS_ALL) {
3151 		m->dirty = VM_PAGE_BITS_ALL;
3152 		if (m->object)
3153 			vm_object_set_writeable_dirty(m->object);
3154 	}
3155 }
3156 
3157 /*
3158  * Invalidates DEV_BSIZE'd chunks within a page.  Both the
3159  * valid and dirty bits for the effected areas are cleared.
3160  *
3161  * Page must be busied?
3162  * Does not block.
3163  * No other requirements.
3164  */
3165 void
3166 vm_page_set_invalid(vm_page_t m, int base, int size)
3167 {
3168 	int bits;
3169 
3170 	bits = vm_page_bits(base, size);
3171 	m->valid &= ~bits;
3172 	m->dirty &= ~bits;
3173 	atomic_add_int(&m->object->generation, 1);
3174 }
3175 
3176 /*
3177  * The kernel assumes that the invalid portions of a page contain
3178  * garbage, but such pages can be mapped into memory by user code.
3179  * When this occurs, we must zero out the non-valid portions of the
3180  * page so user code sees what it expects.
3181  *
3182  * Pages are most often semi-valid when the end of a file is mapped
3183  * into memory and the file's size is not page aligned.
3184  *
3185  * Page must be busied?
3186  * No other requirements.
3187  */
3188 void
3189 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3190 {
3191 	int b;
3192 	int i;
3193 
3194 	/*
3195 	 * Scan the valid bits looking for invalid sections that
3196 	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
3197 	 * valid bit may be set ) have already been zerod by
3198 	 * vm_page_set_validclean().
3199 	 */
3200 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3201 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
3202 		    (m->valid & (1 << i))
3203 		) {
3204 			if (i > b) {
3205 				pmap_zero_page_area(
3206 				    VM_PAGE_TO_PHYS(m),
3207 				    b << DEV_BSHIFT,
3208 				    (i - b) << DEV_BSHIFT
3209 				);
3210 			}
3211 			b = i + 1;
3212 		}
3213 	}
3214 
3215 	/*
3216 	 * setvalid is TRUE when we can safely set the zero'd areas
3217 	 * as being valid.  We can do this if there are no cache consistency
3218 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3219 	 */
3220 	if (setvalid)
3221 		m->valid = VM_PAGE_BITS_ALL;
3222 }
3223 
3224 /*
3225  * Is a (partial) page valid?  Note that the case where size == 0
3226  * will return FALSE in the degenerate case where the page is entirely
3227  * invalid, and TRUE otherwise.
3228  *
3229  * Does not block.
3230  * No other requirements.
3231  */
3232 int
3233 vm_page_is_valid(vm_page_t m, int base, int size)
3234 {
3235 	int bits = vm_page_bits(base, size);
3236 
3237 	if (m->valid && ((m->valid & bits) == bits))
3238 		return 1;
3239 	else
3240 		return 0;
3241 }
3242 
3243 /*
3244  * update dirty bits from pmap/mmu.  May not block.
3245  *
3246  * Caller must hold the page busy
3247  */
3248 void
3249 vm_page_test_dirty(vm_page_t m)
3250 {
3251 	if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
3252 		vm_page_dirty(m);
3253 	}
3254 }
3255 
3256 #include "opt_ddb.h"
3257 #ifdef DDB
3258 #include <ddb/ddb.h>
3259 
3260 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3261 {
3262 	db_printf("vmstats.v_free_count: %ld\n", vmstats.v_free_count);
3263 	db_printf("vmstats.v_cache_count: %ld\n", vmstats.v_cache_count);
3264 	db_printf("vmstats.v_inactive_count: %ld\n", vmstats.v_inactive_count);
3265 	db_printf("vmstats.v_active_count: %ld\n", vmstats.v_active_count);
3266 	db_printf("vmstats.v_wire_count: %ld\n", vmstats.v_wire_count);
3267 	db_printf("vmstats.v_free_reserved: %ld\n", vmstats.v_free_reserved);
3268 	db_printf("vmstats.v_free_min: %ld\n", vmstats.v_free_min);
3269 	db_printf("vmstats.v_free_target: %ld\n", vmstats.v_free_target);
3270 	db_printf("vmstats.v_cache_min: %ld\n", vmstats.v_cache_min);
3271 	db_printf("vmstats.v_inactive_target: %ld\n",
3272 		  vmstats.v_inactive_target);
3273 }
3274 
3275 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3276 {
3277 	int i;
3278 	db_printf("PQ_FREE:");
3279 	for (i = 0; i < PQ_L2_SIZE; i++) {
3280 		db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
3281 	}
3282 	db_printf("\n");
3283 
3284 	db_printf("PQ_CACHE:");
3285 	for(i = 0; i < PQ_L2_SIZE; i++) {
3286 		db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
3287 	}
3288 	db_printf("\n");
3289 
3290 	db_printf("PQ_ACTIVE:");
3291 	for(i = 0; i < PQ_L2_SIZE; i++) {
3292 		db_printf(" %d", vm_page_queues[PQ_ACTIVE + i].lcnt);
3293 	}
3294 	db_printf("\n");
3295 
3296 	db_printf("PQ_INACTIVE:");
3297 	for(i = 0; i < PQ_L2_SIZE; i++) {
3298 		db_printf(" %d", vm_page_queues[PQ_INACTIVE + i].lcnt);
3299 	}
3300 	db_printf("\n");
3301 }
3302 #endif /* DDB */
3303