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