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