xref: /dragonfly/sys/vm/vm_page.c (revision 5e83d98b)
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_adj;
994 	long *cnt_gd;
995 
996 	queue = m->queue;
997 	if (queue != PQ_NONE) {
998 		pq = &vm_page_queues[queue];
999 		TAILQ_REMOVE(&pq->pl, m, pageq);
1000 
1001 		/*
1002 		 * Primarily adjust our pcpu stats for rollup, which is
1003 		 * (mycpu->gd_vmstats_adj + offset).  This is normally
1004 		 * synchronized on every hardclock().
1005 		 *
1006 		 * However, in order for the nominal low-memory algorithms
1007 		 * to work properly if the unsynchronized adjustment gets
1008 		 * too negative and might trigger the pageout daemon, we
1009 		 * immediately synchronize with the global structure.
1010 		 *
1011 		 * The idea here is to reduce unnecessary SMP cache mastership
1012 		 * changes in the global vmstats, which can be particularly
1013 		 * bad in multi-socket systems.
1014 		 *
1015 		 * WARNING! In systems with low amounts of memory the
1016 		 *	    vm_paging_needed(-1024 * ncpus) test could
1017 		 *	    wind up testing a value above the paging target,
1018 		 *	    meaning it would almost always return TRUE.  In
1019 		 *	    that situation we synchronize every time the
1020 		 *	    cumulative adjustment falls below -1024.
1021 		 */
1022 		cnt_adj = (long *)((char *)&mycpu->gd_vmstats_adj +
1023 				   pq->cnt_offset);
1024 		cnt_gd = (long *)((char *)&mycpu->gd_vmstats +
1025 				   pq->cnt_offset);
1026 		atomic_add_long(cnt_adj, -1);
1027 		atomic_add_long(cnt_gd, -1);
1028 
1029 		if (*cnt_adj < -1024 && vm_paging_needed(-1024 * ncpus)) {
1030 			u_long copy = atomic_swap_long(cnt_adj, 0);
1031 			cnt_adj = (long *)((char *)&vmstats + pq->cnt_offset);
1032 			atomic_add_long(cnt_adj, copy);
1033 		}
1034 		pq->lcnt--;
1035 		m->queue = PQ_NONE;
1036 		oqueue = queue;
1037 		queue -= m->pc;
1038 		vm_page_queues_spin_unlock(oqueue);	/* intended */
1039 	}
1040 	return queue;
1041 }
1042 
1043 /*
1044  * Helper function places the vm_page on the specified queue.  Generally
1045  * speaking only PQ_FREE pages are placed at the head, to allow them to
1046  * be allocated sooner rather than later on the assumption that they
1047  * are cache-hot.
1048  *
1049  * The vm_page must be spinlocked.
1050  * The vm_page must NOT be FICTITIOUS (that would be a disaster)
1051  * This function will return with both the page and the queue locked.
1052  */
1053 static __inline void
1054 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
1055 {
1056 	struct vpgqueues *pq;
1057 	u_long *cnt_adj;
1058 	u_long *cnt_gd;
1059 
1060 	KKASSERT(m->queue == PQ_NONE &&
1061 		 (m->flags & (PG_FICTITIOUS | PG_UNQUEUED)) == 0);
1062 
1063 	if (queue != PQ_NONE) {
1064 		vm_page_queues_spin_lock(queue);
1065 		pq = &vm_page_queues[queue];
1066 		++pq->lcnt;
1067 
1068 		/*
1069 		 * Adjust our pcpu stats.  If a system entity really needs
1070 		 * to incorporate the count it will call vmstats_rollup()
1071 		 * to roll it all up into the global vmstats strufture.
1072 		 */
1073 		cnt_adj = (long *)((char *)&mycpu->gd_vmstats_adj +
1074 				   pq->cnt_offset);
1075 		cnt_gd = (long *)((char *)&mycpu->gd_vmstats +
1076 				   pq->cnt_offset);
1077 		atomic_add_long(cnt_adj, 1);
1078 		atomic_add_long(cnt_gd, 1);
1079 
1080 		/*
1081 		 * PQ_FREE is always handled LIFO style to try to provide
1082 		 * cache-hot pages to programs.
1083 		 */
1084 		m->queue = queue;
1085 		if (queue - m->pc == PQ_FREE) {
1086 			TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1087 		} else if (athead) {
1088 			TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1089 		} else {
1090 			TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1091 		}
1092 		/* leave the queue spinlocked */
1093 	}
1094 }
1095 
1096 /*
1097  * Wait until page is no longer BUSY.  If also_m_busy is TRUE we wait
1098  * until the page is no longer BUSY or SBUSY (busy_count field is 0).
1099  *
1100  * Returns TRUE if it had to sleep, FALSE if we did not.  Only one sleep
1101  * call will be made before returning.
1102  *
1103  * This function does NOT busy the page and on return the page is not
1104  * guaranteed to be available.
1105  */
1106 void
1107 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
1108 {
1109 	u_int32_t busy_count;
1110 
1111 	for (;;) {
1112 		busy_count = m->busy_count;
1113 		cpu_ccfence();
1114 
1115 		if ((busy_count & PBUSY_LOCKED) == 0 &&
1116 		    (also_m_busy == 0 || (busy_count & PBUSY_MASK) == 0)) {
1117 			break;
1118 		}
1119 		tsleep_interlock(m, 0);
1120 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1121 				      busy_count | PBUSY_WANTED)) {
1122 			atomic_set_int(&m->flags, PG_REFERENCED);
1123 			tsleep(m, PINTERLOCKED, msg, 0);
1124 			break;
1125 		}
1126 	}
1127 }
1128 
1129 /*
1130  * This calculates and returns a page color given an optional VM object and
1131  * either a pindex or an iterator.  We attempt to return a cpu-localized
1132  * pg_color that is still roughly 16-way set-associative.  The CPU topology
1133  * is used if it was probed.
1134  *
1135  * The caller may use the returned value to index into e.g. PQ_FREE when
1136  * allocating a page in order to nominally obtain pages that are hopefully
1137  * already localized to the requesting cpu.  This function is not able to
1138  * provide any sort of guarantee of this, but does its best to improve
1139  * hardware cache management performance.
1140  *
1141  * WARNING! The caller must mask the returned value with PQ_L2_MASK.
1142  */
1143 u_short
1144 vm_get_pg_color(int cpuid, vm_object_t object, vm_pindex_t pindex)
1145 {
1146 	u_short pg_color;
1147 	int object_pg_color;
1148 
1149 	/*
1150 	 * WARNING! cpu_topology_core_ids might not be a power of two.
1151 	 *	    We also shouldn't make assumptions about
1152 	 *	    cpu_topology_phys_ids either.
1153 	 *
1154 	 * WARNING! ncpus might not be known at this time (during early
1155 	 *	    boot), and might be set to 1.
1156 	 *
1157 	 * General format: [phys_id][core_id][cpuid][set-associativity]
1158 	 * (but uses modulo, so not necessarily precise bit masks)
1159 	 */
1160 	object_pg_color = object ? object->pg_color : 0;
1161 
1162 	if (cpu_topology_ht_ids) {
1163 		int phys_id;
1164 		int core_id;
1165 		int ht_id;
1166 		int physcale;
1167 		int grpscale;
1168 		int cpuscale;
1169 
1170 		/*
1171 		 * Translate cpuid to socket, core, and hyperthread id.
1172 		 */
1173 		phys_id = get_cpu_phys_id(cpuid);
1174 		core_id = get_cpu_core_id(cpuid);
1175 		ht_id = get_cpu_ht_id(cpuid);
1176 
1177 		/*
1178 		 * Calculate pg_color for our array index.
1179 		 *
1180 		 * physcale - socket multiplier.
1181 		 * grpscale - core multiplier (cores per socket)
1182 		 * cpu*	    - cpus per core
1183 		 *
1184 		 * WARNING! In early boot, ncpus has not yet been
1185 		 *	    initialized and may be set to (1).
1186 		 *
1187 		 * WARNING! physcale must match the organization that
1188 		 *	    vm_numa_organize() creates to ensure that
1189 		 *	    we properly localize allocations to the
1190 		 *	    requested cpuid.
1191 		 */
1192 		physcale = PQ_L2_SIZE / cpu_topology_phys_ids;
1193 		grpscale = physcale / cpu_topology_core_ids;
1194 		cpuscale = grpscale / cpu_topology_ht_ids;
1195 
1196 		pg_color = phys_id * physcale;
1197 		pg_color += core_id * grpscale;
1198 		pg_color += ht_id * cpuscale;
1199 		pg_color += (pindex + object_pg_color) % cpuscale;
1200 
1201 #if 0
1202 		if (grpsize >= 8) {
1203 			pg_color += (pindex + object_pg_color) % grpsize;
1204 		} else {
1205 			if (grpsize <= 2) {
1206 				grpsize = 8;
1207 			} else {
1208 				/* 3->9, 4->8, 5->10, 6->12, 7->14 */
1209 				grpsize += grpsize;
1210 				if (grpsize < 8)
1211 					grpsize += grpsize;
1212 			}
1213 			pg_color += (pindex + object_pg_color) % grpsize;
1214 		}
1215 #endif
1216 	} else {
1217 		/*
1218 		 * Unknown topology, distribute things evenly.
1219 		 *
1220 		 * WARNING! In early boot, ncpus has not yet been
1221 		 *	    initialized and may be set to (1).
1222 		 */
1223 		int cpuscale;
1224 
1225 		cpuscale = PQ_L2_SIZE / ncpus;
1226 
1227 		pg_color = cpuid * cpuscale;
1228 		pg_color += (pindex + object_pg_color) % cpuscale;
1229 	}
1230 	return (pg_color & PQ_L2_MASK);
1231 }
1232 
1233 /*
1234  * Wait until BUSY can be set, then set it.  If also_m_busy is TRUE we
1235  * also wait for m->busy_count to become 0 before setting PBUSY_LOCKED.
1236  */
1237 void
1238 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
1239 				     int also_m_busy, const char *msg
1240 				     VM_PAGE_DEBUG_ARGS)
1241 {
1242 	u_int32_t busy_count;
1243 
1244 	for (;;) {
1245 		busy_count = m->busy_count;
1246 		cpu_ccfence();
1247 		if (busy_count & PBUSY_LOCKED) {
1248 			tsleep_interlock(m, 0);
1249 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1250 					  busy_count | PBUSY_WANTED)) {
1251 				atomic_set_int(&m->flags, PG_REFERENCED);
1252 				tsleep(m, PINTERLOCKED, msg, 0);
1253 			}
1254 		} else if (also_m_busy && busy_count) {
1255 			tsleep_interlock(m, 0);
1256 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1257 					  busy_count | PBUSY_WANTED)) {
1258 				atomic_set_int(&m->flags, PG_REFERENCED);
1259 				tsleep(m, PINTERLOCKED, msg, 0);
1260 			}
1261 		} else {
1262 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1263 					      busy_count | PBUSY_LOCKED)) {
1264 #ifdef VM_PAGE_DEBUG
1265 				m->busy_func = func;
1266 				m->busy_line = lineno;
1267 #endif
1268 				break;
1269 			}
1270 		}
1271 	}
1272 }
1273 
1274 /*
1275  * Attempt to set BUSY.  If also_m_busy is TRUE we only succeed if
1276  * m->busy_count is also 0.
1277  *
1278  * Returns non-zero on failure.
1279  */
1280 int
1281 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
1282 				    VM_PAGE_DEBUG_ARGS)
1283 {
1284 	u_int32_t busy_count;
1285 
1286 	for (;;) {
1287 		busy_count = m->busy_count;
1288 		cpu_ccfence();
1289 		if (busy_count & PBUSY_LOCKED)
1290 			return TRUE;
1291 		if (also_m_busy && (busy_count & PBUSY_MASK) != 0)
1292 			return TRUE;
1293 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1294 				      busy_count | PBUSY_LOCKED)) {
1295 #ifdef VM_PAGE_DEBUG
1296 				m->busy_func = func;
1297 				m->busy_line = lineno;
1298 #endif
1299 			return FALSE;
1300 		}
1301 	}
1302 }
1303 
1304 /*
1305  * Clear the BUSY flag and return non-zero to indicate to the caller
1306  * that a wakeup() should be performed.
1307  *
1308  * (inline version)
1309  */
1310 static __inline
1311 int
1312 _vm_page_wakeup(vm_page_t m)
1313 {
1314 	u_int32_t busy_count;
1315 
1316 	busy_count = m->busy_count;
1317 	cpu_ccfence();
1318 	for (;;) {
1319 		if (atomic_fcmpset_int(&m->busy_count, &busy_count,
1320 				      busy_count &
1321 				      ~(PBUSY_LOCKED | PBUSY_WANTED))) {
1322 			return((int)(busy_count & PBUSY_WANTED));
1323 		}
1324 	}
1325 	/* not reached */
1326 }
1327 
1328 /*
1329  * Clear the BUSY flag and wakeup anyone waiting for the page.  This
1330  * is typically the last call you make on a page before moving onto
1331  * other things.
1332  */
1333 void
1334 vm_page_wakeup(vm_page_t m)
1335 {
1336         KASSERT(m->busy_count & PBUSY_LOCKED,
1337 		("vm_page_wakeup: page not busy!!!"));
1338 	if (_vm_page_wakeup(m))
1339 		wakeup(m);
1340 }
1341 
1342 /*
1343  * Hold a page, preventing reuse.  This is typically only called on pages
1344  * in a known state (either held busy, special, or interlocked in some
1345  * manner).  Holding a page does not ensure that it remains valid, it only
1346  * prevents reuse.  The page must not already be on the FREE queue or in
1347  * any danger of being moved to the FREE queue concurrent with this call.
1348  *
1349  * Other parts of the system can still disassociate the page from its object
1350  * and attempt to free it, or perform read or write I/O on it and/or otherwise
1351  * manipulate the page, but if the page is held the VM system will leave the
1352  * page and its data intact and not cycle it through the FREE queue until
1353  * the last hold has been released.
1354  *
1355  * (see vm_page_wire() if you want to prevent the page from being
1356  *  disassociated from its object too).
1357  */
1358 void
1359 vm_page_hold(vm_page_t m)
1360 {
1361 	atomic_add_int(&m->hold_count, 1);
1362 	KKASSERT(m->queue - m->pc != PQ_FREE);
1363 }
1364 
1365 /*
1366  * The opposite of vm_page_hold().  If the page is on the HOLD queue
1367  * it was freed while held and must be moved back to the FREE queue.
1368  *
1369  * To avoid racing against vm_page_free*() we must re-test conditions
1370  * after obtaining the spin-lock.  The initial test can also race a
1371  * vm_page_free*() that is in the middle of moving a page to PQ_HOLD,
1372  * leaving the page on PQ_HOLD with hold_count == 0.  Rather than
1373  * throw a spin-lock in the critical path, we rely on the pageout
1374  * daemon to clean-up these loose ends.
1375  *
1376  * More critically, the 'easy movement' between queues without busying
1377  * a vm_page is only allowed for PQ_FREE<->PQ_HOLD.
1378  */
1379 void
1380 vm_page_unhold(vm_page_t m)
1381 {
1382 	KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1383 		("vm_page_unhold: pg %p illegal hold_count (%d) or "
1384 		 "on FREE queue (%d)",
1385 		 m, m->hold_count, m->queue - m->pc));
1386 
1387 	if (atomic_fetchadd_int(&m->hold_count, -1) == 1 &&
1388 	    m->queue - m->pc == PQ_HOLD) {
1389 		vm_page_spin_lock(m);
1390 		if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1391 			_vm_page_queue_spin_lock(m);
1392 			_vm_page_rem_queue_spinlocked(m);
1393 			_vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
1394 			_vm_page_queue_spin_unlock(m);
1395 		}
1396 		vm_page_spin_unlock(m);
1397 	}
1398 }
1399 
1400 /*
1401  * Create a fictitious page with the specified physical address and
1402  * memory attribute.  The memory attribute is the only the machine-
1403  * dependent aspect of a fictitious page that must be initialized.
1404  */
1405 void
1406 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1407 {
1408 	/*
1409 	 * The page's memattr might have changed since the
1410 	 * previous initialization.  Update the pmap to the
1411 	 * new memattr.
1412 	 */
1413 	if ((m->flags & PG_FICTITIOUS) != 0)
1414 		goto memattr;
1415 	m->phys_addr = paddr;
1416 	m->queue = PQ_NONE;
1417 	/* Fictitious pages don't use "segind". */
1418 	/* Fictitious pages don't use "order" or "pool". */
1419 	m->flags = PG_FICTITIOUS | PG_UNQUEUED;
1420 	m->busy_count = PBUSY_LOCKED;
1421 	m->wire_count = 1;
1422 	spin_init(&m->spin, "fake_page");
1423 	pmap_page_init(m);
1424 memattr:
1425 	pmap_page_set_memattr(m, memattr);
1426 }
1427 
1428 /*
1429  * Inserts the given vm_page into the object and object list.
1430  *
1431  * The pagetables are not updated but will presumably fault the page
1432  * in if necessary, or if a kernel page the caller will at some point
1433  * enter the page into the kernel's pmap.  We are not allowed to block
1434  * here so we *can't* do this anyway.
1435  *
1436  * This routine may not block.
1437  * This routine must be called with the vm_object held.
1438  * This routine must be called with a critical section held.
1439  *
1440  * This routine returns TRUE if the page was inserted into the object
1441  * successfully, and FALSE if the page already exists in the object.
1442  */
1443 int
1444 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1445 {
1446 	ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1447 	if (m->object != NULL)
1448 		panic("vm_page_insert: already inserted");
1449 
1450 	atomic_add_int(&object->generation, 1);
1451 
1452 	/*
1453 	 * Associate the VM page with an (object, offset).
1454 	 *
1455 	 * The vm_page spin lock is required for interactions with the pmap.
1456 	 * XXX vm_page_spin_lock() might not be needed for this any more.
1457 	 */
1458 	vm_page_spin_lock(m);
1459 	m->object = object;
1460 	m->pindex = pindex;
1461 	if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1462 		m->object = NULL;
1463 		m->pindex = 0;
1464 		vm_page_spin_unlock(m);
1465 		return FALSE;
1466 	}
1467 	++object->resident_page_count;
1468 	++mycpu->gd_vmtotal.t_rm;
1469 	vm_page_spin_unlock(m);
1470 
1471 	/*
1472 	 * Since we are inserting a new and possibly dirty page,
1473 	 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1474 	 */
1475 	if ((m->valid & m->dirty) ||
1476 	    (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1477 		vm_object_set_writeable_dirty(object);
1478 
1479 	/*
1480 	 * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1481 	 */
1482 	swap_pager_page_inserted(m);
1483 	return TRUE;
1484 }
1485 
1486 /*
1487  * Removes the given vm_page_t from the (object,index) table
1488  *
1489  * The page must be BUSY and will remain BUSY on return.
1490  * No other requirements.
1491  *
1492  * NOTE: FreeBSD side effect was to unbusy the page on return.  We leave
1493  *	 it busy.
1494  *
1495  * NOTE: Caller is responsible for any pmap disposition prior to the
1496  *	 rename (as the pmap code will not be able to find the entries
1497  *	 once the object has been disassociated).  The caller may choose
1498  *	 to leave the pmap association intact if this routine is being
1499  *	 called as part of a rename between shadowed objects.
1500  *
1501  * This routine may not block.
1502  */
1503 void
1504 vm_page_remove(vm_page_t m)
1505 {
1506 	vm_object_t object;
1507 
1508 	if (m->object == NULL) {
1509 		return;
1510 	}
1511 
1512 	if ((m->busy_count & PBUSY_LOCKED) == 0)
1513 		panic("vm_page_remove: page not busy");
1514 
1515 	object = m->object;
1516 
1517 	vm_object_hold(object);
1518 
1519 	/*
1520 	 * Remove the page from the object and update the object.
1521 	 *
1522 	 * The vm_page spin lock is required for interactions with the pmap.
1523 	 * XXX vm_page_spin_lock() might not be needed for this any more.
1524 	 */
1525 	vm_page_spin_lock(m);
1526 	vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1527 	--object->resident_page_count;
1528 	--mycpu->gd_vmtotal.t_rm;
1529 	m->object = NULL;
1530 	atomic_add_int(&object->generation, 1);
1531 	vm_page_spin_unlock(m);
1532 
1533 	vm_object_drop(object);
1534 }
1535 
1536 /*
1537  * Calculate the hash position for the vm_page hash heuristic.
1538  *
1539  * Mask by ~3 to offer 4-way set-assoc
1540  */
1541 static __inline
1542 struct vm_page_hash_elm *
1543 vm_page_hash_hash(vm_object_t object, vm_pindex_t pindex)
1544 {
1545 	size_t hi;
1546 
1547 	/* mix it up */
1548 	hi = (intptr_t)object ^ object->pg_color ^ pindex;
1549 	hi += object->pg_color * pindex;
1550 	hi = hi ^ (hi >> 20);
1551 	hi &= vm_page_hash_size - 1;		/* bounds */
1552 	hi &= ~(VM_PAGE_HASH_SET - 1);		/* set-assoc */
1553 	return (&vm_page_hash[hi]);
1554 }
1555 
1556 /*
1557  * Heuristical page lookup that does not require any locks.  Returns
1558  * a soft-busied page on success, NULL on failure.
1559  *
1560  * Caller must lookup the page the slow way if NULL is returned.
1561  */
1562 vm_page_t
1563 vm_page_hash_get(vm_object_t object, vm_pindex_t pindex)
1564 {
1565 	struct vm_page_hash_elm *mp;
1566 	vm_page_t m;
1567 	int i;
1568 
1569 	if (vm_page_hash == NULL)
1570 		return NULL;
1571 	mp = vm_page_hash_hash(object, pindex);
1572 	for (i = 0; i < VM_PAGE_HASH_SET; ++i) {
1573 		m = mp[i].m;
1574 		cpu_ccfence();
1575 		if (m == NULL)
1576 			continue;
1577 		if (m->object != object || m->pindex != pindex)
1578 			continue;
1579 		if (vm_page_sbusy_try(m))
1580 			continue;
1581 		if (m->object == object && m->pindex == pindex) {
1582 			mp[i].ticks = ticks;
1583 			return m;
1584 		}
1585 		vm_page_sbusy_drop(m);
1586 	}
1587 	return NULL;
1588 }
1589 
1590 /*
1591  * Enter page onto vm_page_hash[].  This is a heuristic, SMP collisions
1592  * are allowed.
1593  */
1594 static __inline
1595 void
1596 vm_page_hash_enter(vm_page_t m)
1597 {
1598 	struct vm_page_hash_elm *mp;
1599 	struct vm_page_hash_elm *best;
1600 	int i;
1601 
1602 	/*
1603 	 * Only enter type-stable vm_pages with well-shared objects.
1604 	 */
1605 	if (vm_page_hash == NULL ||
1606 	    m < &vm_page_array[0] ||
1607 	    m >= &vm_page_array[vm_page_array_size])
1608 		return;
1609 	if (m->object == NULL)
1610 		return;
1611 #if 0
1612 	/*
1613 	 * Disabled at the moment, there are some degenerate conditions
1614 	 * with often-exec'd programs that get ignored.  In particular,
1615 	 * the kernel's elf loader does a vn_rdwr() on the first page of
1616 	 * a binary.
1617 	 */
1618 	if (m->object->ref_count <= 2 || (m->object->flags & OBJ_ONEMAPPING))
1619 		return;
1620 #endif
1621 	if (vm_page_hash_vnode_only && m->object->type != OBJT_VNODE)
1622 		return;
1623 
1624 	/*
1625 	 *
1626 	 */
1627 	mp = vm_page_hash_hash(m->object, m->pindex);
1628 	best = mp;
1629 	for (i = 0; i < VM_PAGE_HASH_SET; ++i) {
1630 		if (mp[i].m == m) {
1631 			mp[i].ticks = ticks;
1632 			return;
1633 		}
1634 
1635 		/*
1636 		 * The best choice is the oldest entry
1637 		 */
1638 		if ((ticks - best->ticks) < (ticks - mp[i].ticks) ||
1639 		    (int)(ticks - mp[i].ticks) < 0) {
1640 			best = &mp[i];
1641 		}
1642 	}
1643 	best->m = m;
1644 	best->ticks = ticks;
1645 }
1646 
1647 /*
1648  * Locate and return the page at (object, pindex), or NULL if the
1649  * page could not be found.
1650  *
1651  * The caller must hold the vm_object token.
1652  */
1653 vm_page_t
1654 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1655 {
1656 	vm_page_t m;
1657 
1658 	/*
1659 	 * Search the hash table for this object/offset pair
1660 	 */
1661 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1662 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1663 	if (m) {
1664 		KKASSERT(m->object == object && m->pindex == pindex);
1665 		vm_page_hash_enter(m);
1666 	}
1667 	return(m);
1668 }
1669 
1670 vm_page_t
1671 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1672 					    vm_pindex_t pindex,
1673 					    int also_m_busy, const char *msg
1674 					    VM_PAGE_DEBUG_ARGS)
1675 {
1676 	u_int32_t busy_count;
1677 	vm_page_t m;
1678 
1679 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1680 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1681 	while (m) {
1682 		KKASSERT(m->object == object && m->pindex == pindex);
1683 		busy_count = m->busy_count;
1684 		cpu_ccfence();
1685 		if (busy_count & PBUSY_LOCKED) {
1686 			tsleep_interlock(m, 0);
1687 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1688 					  busy_count | PBUSY_WANTED)) {
1689 				atomic_set_int(&m->flags, PG_REFERENCED);
1690 				tsleep(m, PINTERLOCKED, msg, 0);
1691 				m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1692 							      pindex);
1693 			}
1694 		} else if (also_m_busy && busy_count) {
1695 			tsleep_interlock(m, 0);
1696 			if (atomic_cmpset_int(&m->busy_count, busy_count,
1697 					  busy_count | PBUSY_WANTED)) {
1698 				atomic_set_int(&m->flags, PG_REFERENCED);
1699 				tsleep(m, PINTERLOCKED, msg, 0);
1700 				m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1701 							      pindex);
1702 			}
1703 		} else if (atomic_cmpset_int(&m->busy_count, busy_count,
1704 					     busy_count | PBUSY_LOCKED)) {
1705 #ifdef VM_PAGE_DEBUG
1706 			m->busy_func = func;
1707 			m->busy_line = lineno;
1708 #endif
1709 			vm_page_hash_enter(m);
1710 			break;
1711 		}
1712 	}
1713 	return m;
1714 }
1715 
1716 /*
1717  * Attempt to lookup and busy a page.
1718  *
1719  * Returns NULL if the page could not be found
1720  *
1721  * Returns a vm_page and error == TRUE if the page exists but could not
1722  * be busied.
1723  *
1724  * Returns a vm_page and error == FALSE on success.
1725  */
1726 vm_page_t
1727 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1728 					   vm_pindex_t pindex,
1729 					   int also_m_busy, int *errorp
1730 					   VM_PAGE_DEBUG_ARGS)
1731 {
1732 	u_int32_t busy_count;
1733 	vm_page_t m;
1734 
1735 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1736 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1737 	*errorp = FALSE;
1738 	while (m) {
1739 		KKASSERT(m->object == object && m->pindex == pindex);
1740 		busy_count = m->busy_count;
1741 		cpu_ccfence();
1742 		if (busy_count & PBUSY_LOCKED) {
1743 			*errorp = TRUE;
1744 			break;
1745 		}
1746 		if (also_m_busy && busy_count) {
1747 			*errorp = TRUE;
1748 			break;
1749 		}
1750 		if (atomic_cmpset_int(&m->busy_count, busy_count,
1751 				      busy_count | PBUSY_LOCKED)) {
1752 #ifdef VM_PAGE_DEBUG
1753 			m->busy_func = func;
1754 			m->busy_line = lineno;
1755 #endif
1756 			vm_page_hash_enter(m);
1757 			break;
1758 		}
1759 	}
1760 	return m;
1761 }
1762 
1763 /*
1764  * Returns a page that is only soft-busied for use by the caller in
1765  * a read-only fashion.  Returns NULL if the page could not be found,
1766  * the soft busy could not be obtained, or the page data is invalid.
1767  *
1768  * XXX Doesn't handle PG_FICTITIOUS pages at the moment, but there is
1769  *     no reason why we couldn't.
1770  */
1771 vm_page_t
1772 vm_page_lookup_sbusy_try(struct vm_object *object, vm_pindex_t pindex,
1773 			 int pgoff, int pgbytes)
1774 {
1775 	vm_page_t m;
1776 
1777 	ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1778 	m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1779 	if (m) {
1780 		if ((m->valid != VM_PAGE_BITS_ALL &&
1781 		     !vm_page_is_valid(m, pgoff, pgbytes)) ||
1782 		    (m->flags & PG_FICTITIOUS)) {
1783 			m = NULL;
1784 		} else if (vm_page_sbusy_try(m)) {
1785 			m = NULL;
1786 		} else if ((m->valid != VM_PAGE_BITS_ALL &&
1787 			    !vm_page_is_valid(m, pgoff, pgbytes)) ||
1788 			   (m->flags & PG_FICTITIOUS)) {
1789 			vm_page_sbusy_drop(m);
1790 			m = NULL;
1791 		} else {
1792 			vm_page_hash_enter(m);
1793 		}
1794 	}
1795 	return m;
1796 }
1797 
1798 /*
1799  * Caller must hold the related vm_object
1800  */
1801 vm_page_t
1802 vm_page_next(vm_page_t m)
1803 {
1804 	vm_page_t next;
1805 
1806 	next = vm_page_rb_tree_RB_NEXT(m);
1807 	if (next && next->pindex != m->pindex + 1)
1808 		next = NULL;
1809 	return (next);
1810 }
1811 
1812 /*
1813  * vm_page_rename()
1814  *
1815  * Move the given vm_page from its current object to the specified
1816  * target object/offset.  The page must be busy and will remain so
1817  * on return.
1818  *
1819  * new_object must be held.
1820  * This routine might block. XXX ?
1821  *
1822  * NOTE: Swap associated with the page must be invalidated by the move.  We
1823  *       have to do this for several reasons:  (1) we aren't freeing the
1824  *       page, (2) we are dirtying the page, (3) the VM system is probably
1825  *       moving the page from object A to B, and will then later move
1826  *       the backing store from A to B and we can't have a conflict.
1827  *
1828  * NOTE: We *always* dirty the page.  It is necessary both for the
1829  *       fact that we moved it, and because we may be invalidating
1830  *	 swap.  If the page is on the cache, we have to deactivate it
1831  *	 or vm_page_dirty() will panic.  Dirty pages are not allowed
1832  *	 on the cache.
1833  *
1834  * NOTE: Caller is responsible for any pmap disposition prior to the
1835  *	 rename (as the pmap code will not be able to find the entries
1836  *	 once the object has been disassociated or changed).  Nominally
1837  *	 the caller is moving a page between shadowed objects and so the
1838  *	 pmap association is retained without having to remove the page
1839  *	 from it.
1840  */
1841 void
1842 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1843 {
1844 	KKASSERT(m->busy_count & PBUSY_LOCKED);
1845 	ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1846 	if (m->object) {
1847 		ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1848 		vm_page_remove(m);
1849 	}
1850 	if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1851 		panic("vm_page_rename: target exists (%p,%"PRIu64")",
1852 		      new_object, new_pindex);
1853 	}
1854 	if (m->queue - m->pc == PQ_CACHE)
1855 		vm_page_deactivate(m);
1856 	vm_page_dirty(m);
1857 }
1858 
1859 /*
1860  * vm_page_unqueue() without any wakeup.  This routine is used when a page
1861  * is to remain BUSYied by the caller.
1862  *
1863  * This routine may not block.
1864  */
1865 void
1866 vm_page_unqueue_nowakeup(vm_page_t m)
1867 {
1868 	vm_page_and_queue_spin_lock(m);
1869 	(void)_vm_page_rem_queue_spinlocked(m);
1870 	vm_page_spin_unlock(m);
1871 }
1872 
1873 /*
1874  * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1875  * if necessary.
1876  *
1877  * This routine may not block.
1878  */
1879 void
1880 vm_page_unqueue(vm_page_t m)
1881 {
1882 	u_short queue;
1883 
1884 	vm_page_and_queue_spin_lock(m);
1885 	queue = _vm_page_rem_queue_spinlocked(m);
1886 	if (queue == PQ_FREE || queue == PQ_CACHE) {
1887 		vm_page_spin_unlock(m);
1888 		pagedaemon_wakeup();
1889 	} else {
1890 		vm_page_spin_unlock(m);
1891 	}
1892 }
1893 
1894 /*
1895  * vm_page_list_find()
1896  *
1897  * Find a page on the specified queue with color optimization.
1898  *
1899  * The page coloring optimization attempts to locate a page that does
1900  * not overload other nearby pages in the object in the cpu's L1 or L2
1901  * caches.  We need this optimization because cpu caches tend to be
1902  * physical caches, while object spaces tend to be virtual.
1903  *
1904  * The page coloring optimization also, very importantly, tries to localize
1905  * memory to cpus and physical sockets.
1906  *
1907  * Each PQ_FREE and PQ_CACHE color queue has its own spinlock and the
1908  * algorithm is adjusted to localize allocations on a per-core basis.
1909  * This is done by 'twisting' the colors.
1910  *
1911  * The page is returned spinlocked and removed from its queue (it will
1912  * be on PQ_NONE), or NULL. The page is not BUSY'd.  The caller
1913  * is responsible for dealing with the busy-page case (usually by
1914  * deactivating the page and looping).
1915  *
1916  * NOTE:  This routine is carefully inlined.  A non-inlined version
1917  *	  is available for outside callers but the only critical path is
1918  *	  from within this source file.
1919  *
1920  * NOTE:  This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1921  *	  represent stable storage, allowing us to order our locks vm_page
1922  *	  first, then queue.
1923  */
1924 static __inline
1925 vm_page_t
1926 _vm_page_list_find(int basequeue, int index)
1927 {
1928 	struct vpgqueues *pq;
1929 	vm_page_t m;
1930 
1931 	index &= PQ_L2_MASK;
1932 	pq = &vm_page_queues[basequeue + index];
1933 
1934 	/*
1935 	 * Try this cpu's colored queue first.  Test for a page unlocked,
1936 	 * then lock the queue and locate a page.  Note that the lock order
1937 	 * is reversed, but we do not want to dwadle on the page spinlock
1938 	 * anyway as it is held significantly longer than the queue spinlock.
1939 	 */
1940 	if (TAILQ_FIRST(&pq->pl)) {
1941 		spin_lock(&pq->spin);
1942 		TAILQ_FOREACH(m, &pq->pl, pageq) {
1943 			if (spin_trylock(&m->spin) == 0)
1944 				continue;
1945 			KKASSERT(m->queue == basequeue + index);
1946 			_vm_page_rem_queue_spinlocked(m);
1947 			pq->lastq = -1;
1948 			return(m);
1949 		}
1950 		spin_unlock(&pq->spin);
1951 	}
1952 
1953 	/*
1954 	 * If we are unable to get a page, do a more involved NUMA-aware
1955 	 * search.  However, to avoid re-searching empty queues over and
1956 	 * over again skip to pq->last if appropriate.
1957 	 */
1958 	if (pq->lastq >= 0)
1959 		index = pq->lastq;
1960 
1961 	m = _vm_page_list_find2(basequeue, index, &pq->lastq);
1962 
1963 	return(m);
1964 }
1965 
1966 /*
1967  * If we could not find the page in the desired queue try to find it in
1968  * a nearby (NUMA-aware) queue.
1969  */
1970 static vm_page_t
1971 _vm_page_list_find2(int basequeue, int index, int *lastp)
1972 {
1973 	struct vpgqueues *pq;
1974 	vm_page_t m = NULL;
1975 	int pqmask = set_assoc_mask >> 1;
1976 	int pqi;
1977 	int range;
1978 	int skip_start;
1979 	int skip_next;
1980 	int count;
1981 
1982 	index &= PQ_L2_MASK;
1983 	pq = &vm_page_queues[basequeue];
1984 	count = 0;
1985 	skip_start = -1;
1986 	skip_next = -1;
1987 
1988 	/*
1989 	 * Run local sets of 16, 32, 64, 128, up to the entire queue if all
1990 	 * else fails (PQ_L2_MASK).
1991 	 *
1992 	 * pqmask is a mask, 15, 31, 63, etc.
1993 	 *
1994 	 * Test each queue unlocked first, then lock the queue and locate
1995 	 * a page.  Note that the lock order is reversed, but we do not want
1996 	 * to dwadle on the page spinlock anyway as it is held significantly
1997 	 * longer than the queue spinlock.
1998 	 */
1999 	do {
2000 		pqmask = (pqmask << 1) | 1;
2001 
2002 		pqi = index;
2003 		range = pqmask + 1;
2004 
2005 		while (range > 0) {
2006 			if (pqi >= skip_start && pqi < skip_next) {
2007 				range -= skip_next - pqi;
2008 				pqi = (pqi & ~pqmask) | (skip_next & pqmask);
2009 			}
2010 			if (range > 0 && TAILQ_FIRST(&pq[pqi].pl)) {
2011 				spin_lock(&pq[pqi].spin);
2012 				TAILQ_FOREACH(m, &pq[pqi].pl, pageq) {
2013 					if (spin_trylock(&m->spin) == 0)
2014 						continue;
2015 					KKASSERT(m->queue == basequeue + pqi);
2016 					_vm_page_rem_queue_spinlocked(m);
2017 
2018 					/*
2019 					 * If we had to wander too far, set
2020 					 * *lastp to skip past empty queues.
2021 					 */
2022 					if (count >= 8)
2023 						*lastp = pqi & PQ_L2_MASK;
2024 					return(m);
2025 				}
2026 				spin_unlock(&pq[pqi].spin);
2027 			}
2028 			--range;
2029 			++count;
2030 			pqi = (pqi & ~pqmask) | ((pqi + 1) & pqmask);
2031 		}
2032 		skip_start = pqi & ~pqmask;
2033 		skip_next = (pqi | pqmask) + 1;
2034 	} while (pqmask != PQ_L2_MASK);
2035 
2036 	return(m);
2037 }
2038 
2039 /*
2040  * Returns a vm_page candidate for allocation.  The page is not busied so
2041  * it can move around.  The caller must busy the page (and typically
2042  * deactivate it if it cannot be busied!)
2043  *
2044  * Returns a spinlocked vm_page that has been removed from its queue.
2045  */
2046 vm_page_t
2047 vm_page_list_find(int basequeue, int index)
2048 {
2049 	return(_vm_page_list_find(basequeue, index));
2050 }
2051 
2052 /*
2053  * Find a page on the cache queue with color optimization, remove it
2054  * from the queue, and busy it.  The returned page will not be spinlocked.
2055  *
2056  * A candidate failure will be deactivated.  Candidates can fail due to
2057  * being busied by someone else, in which case they will be deactivated.
2058  *
2059  * This routine may not block.
2060  *
2061  */
2062 static vm_page_t
2063 vm_page_select_cache(u_short pg_color)
2064 {
2065 	vm_page_t m;
2066 
2067 	for (;;) {
2068 		m = _vm_page_list_find(PQ_CACHE, pg_color);
2069 		if (m == NULL)
2070 			break;
2071 		/*
2072 		 * (m) has been removed from its queue and spinlocked
2073 		 */
2074 		if (vm_page_busy_try(m, TRUE)) {
2075 			_vm_page_deactivate_locked(m, 0);
2076 			vm_page_spin_unlock(m);
2077 		} else {
2078 			/*
2079 			 * We successfully busied the page
2080 			 */
2081 			if ((m->flags & PG_NEED_COMMIT) == 0 &&
2082 			    m->hold_count == 0 &&
2083 			    m->wire_count == 0 &&
2084 			    (m->dirty & m->valid) == 0) {
2085 				vm_page_spin_unlock(m);
2086 				KKASSERT((m->flags & PG_UNQUEUED) == 0);
2087 				pagedaemon_wakeup();
2088 				return(m);
2089 			}
2090 
2091 			/*
2092 			 * The page cannot be recycled, deactivate it.
2093 			 */
2094 			_vm_page_deactivate_locked(m, 0);
2095 			if (_vm_page_wakeup(m)) {
2096 				vm_page_spin_unlock(m);
2097 				wakeup(m);
2098 			} else {
2099 				vm_page_spin_unlock(m);
2100 			}
2101 		}
2102 	}
2103 	return (m);
2104 }
2105 
2106 /*
2107  * Find a free page.  We attempt to inline the nominal case and fall back
2108  * to _vm_page_select_free() otherwise.  A busied page is removed from
2109  * the queue and returned.
2110  *
2111  * This routine may not block.
2112  */
2113 static __inline vm_page_t
2114 vm_page_select_free(u_short pg_color)
2115 {
2116 	vm_page_t m;
2117 
2118 	for (;;) {
2119 		m = _vm_page_list_find(PQ_FREE, pg_color);
2120 		if (m == NULL)
2121 			break;
2122 		if (vm_page_busy_try(m, TRUE)) {
2123 			/*
2124 			 * Various mechanisms such as a pmap_collect can
2125 			 * result in a busy page on the free queue.  We
2126 			 * have to move the page out of the way so we can
2127 			 * retry the allocation.  If the other thread is not
2128 			 * allocating the page then m->valid will remain 0 and
2129 			 * the pageout daemon will free the page later on.
2130 			 *
2131 			 * Since we could not busy the page, however, we
2132 			 * cannot make assumptions as to whether the page
2133 			 * will be allocated by the other thread or not,
2134 			 * so all we can do is deactivate it to move it out
2135 			 * of the way.  In particular, if the other thread
2136 			 * wires the page it may wind up on the inactive
2137 			 * queue and the pageout daemon will have to deal
2138 			 * with that case too.
2139 			 */
2140 			_vm_page_deactivate_locked(m, 0);
2141 			vm_page_spin_unlock(m);
2142 		} else {
2143 			/*
2144 			 * Theoretically if we are able to busy the page
2145 			 * atomic with the queue removal (using the vm_page
2146 			 * lock) nobody else should have been able to mess
2147 			 * with the page before us.
2148 			 *
2149 			 * Assert the page state.  Note that even though
2150 			 * wiring doesn't adjust queues, a page on the free
2151 			 * queue should never be wired at this point.
2152 			 */
2153 			KKASSERT((m->flags & (PG_UNQUEUED |
2154 					      PG_NEED_COMMIT)) == 0);
2155 			KASSERT(m->hold_count == 0,
2156 				("m->hold_count is not zero "
2157 				 "pg %p q=%d flags=%08x hold=%d wire=%d",
2158 				 m, m->queue, m->flags,
2159 				 m->hold_count, m->wire_count));
2160 			KKASSERT(m->wire_count == 0);
2161 			vm_page_spin_unlock(m);
2162 			pagedaemon_wakeup();
2163 
2164 			/* return busied and removed page */
2165 			return(m);
2166 		}
2167 	}
2168 	return(m);
2169 }
2170 
2171 /*
2172  * vm_page_alloc()
2173  *
2174  * Allocate and return a memory cell associated with this VM object/offset
2175  * pair.  If object is NULL an unassociated page will be allocated.
2176  *
2177  * The returned page will be busied and removed from its queues.  This
2178  * routine can block and may return NULL if a race occurs and the page
2179  * is found to already exist at the specified (object, pindex).
2180  *
2181  *	VM_ALLOC_NORMAL		allow use of cache pages, nominal free drain
2182  *	VM_ALLOC_QUICK		like normal but cannot use cache
2183  *	VM_ALLOC_SYSTEM		greater free drain
2184  *	VM_ALLOC_INTERRUPT	allow free list to be completely drained
2185  *	VM_ALLOC_ZERO		advisory request for pre-zero'd page only
2186  *	VM_ALLOC_FORCE_ZERO	advisory request for pre-zero'd page only
2187  *	VM_ALLOC_NULL_OK	ok to return NULL on insertion collision
2188  *				(see vm_page_grab())
2189  *	VM_ALLOC_USE_GD		ok to use per-gd cache
2190  *
2191  *	VM_ALLOC_CPU(n)		allocate using specified cpu localization
2192  *
2193  * The object must be held if not NULL
2194  * This routine may not block
2195  *
2196  * Additional special handling is required when called from an interrupt
2197  * (VM_ALLOC_INTERRUPT).  We are not allowed to mess with the page cache
2198  * in this case.
2199  */
2200 vm_page_t
2201 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
2202 {
2203 	globaldata_t gd;
2204 	vm_object_t obj;
2205 	vm_page_t m;
2206 	u_short pg_color;
2207 	int cpuid_local;
2208 
2209 #if 0
2210 	/*
2211 	 * Special per-cpu free VM page cache.  The pages are pre-busied
2212 	 * and pre-zerod for us.
2213 	 */
2214 	if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
2215 		crit_enter_gd(gd);
2216 		if (gd->gd_vmpg_count) {
2217 			m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
2218 			crit_exit_gd(gd);
2219 			goto done;
2220                 }
2221 		crit_exit_gd(gd);
2222         }
2223 #endif
2224 	m = NULL;
2225 
2226 	/*
2227 	 * CPU LOCALIZATION
2228 	 *
2229 	 * CPU localization algorithm.  Break the page queues up by physical
2230 	 * id and core id (note that two cpu threads will have the same core
2231 	 * id, and core_id != gd_cpuid).
2232 	 *
2233 	 * This is nowhere near perfect, for example the last pindex in a
2234 	 * subgroup will overflow into the next cpu or package.  But this
2235 	 * should get us good page reuse locality in heavy mixed loads.
2236 	 *
2237 	 * (may be executed before the APs are started, so other GDs might
2238 	 *  not exist!)
2239 	 */
2240 	if (page_req & VM_ALLOC_CPU_SPEC)
2241 		cpuid_local = VM_ALLOC_GETCPU(page_req);
2242 	else
2243 		cpuid_local = mycpu->gd_cpuid;
2244 
2245 	pg_color = vm_get_pg_color(cpuid_local, object, pindex);
2246 
2247 	KKASSERT(page_req &
2248 		(VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
2249 		 VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2250 
2251 	/*
2252 	 * Certain system threads (pageout daemon, buf_daemon's) are
2253 	 * allowed to eat deeper into the free page list.
2254 	 */
2255 	if (curthread->td_flags & TDF_SYSTHREAD)
2256 		page_req |= VM_ALLOC_SYSTEM;
2257 
2258 	/*
2259 	 * Impose various limitations.  Note that the v_free_reserved test
2260 	 * must match the opposite of vm_page_count_target() to avoid
2261 	 * livelocks, be careful.
2262 	 */
2263 loop:
2264 	gd = mycpu;
2265 	if (gd->gd_vmstats.v_free_count >= gd->gd_vmstats.v_free_reserved ||
2266 	    ((page_req & VM_ALLOC_INTERRUPT) &&
2267 	     gd->gd_vmstats.v_free_count > 0) ||
2268 	    ((page_req & VM_ALLOC_SYSTEM) &&
2269 	     gd->gd_vmstats.v_cache_count == 0 &&
2270 		gd->gd_vmstats.v_free_count >
2271 		gd->gd_vmstats.v_interrupt_free_min)
2272 	) {
2273 		/*
2274 		 * The free queue has sufficient free pages to take one out.
2275 		 */
2276 		m = vm_page_select_free(pg_color);
2277 	} else if (page_req & VM_ALLOC_NORMAL) {
2278 		/*
2279 		 * Allocatable from the cache (non-interrupt only).  On
2280 		 * success, we must free the page and try again, thus
2281 		 * ensuring that vmstats.v_*_free_min counters are replenished.
2282 		 */
2283 #ifdef INVARIANTS
2284 		if (curthread->td_preempted) {
2285 			kprintf("vm_page_alloc(): warning, attempt to allocate"
2286 				" cache page from preempting interrupt\n");
2287 			m = NULL;
2288 		} else {
2289 			m = vm_page_select_cache(pg_color);
2290 		}
2291 #else
2292 		m = vm_page_select_cache(pg_color);
2293 #endif
2294 		/*
2295 		 * On success move the page into the free queue and loop.
2296 		 *
2297 		 * Only do this if we can safely acquire the vm_object lock,
2298 		 * because this is effectively a random page and the caller
2299 		 * might be holding the lock shared, we don't want to
2300 		 * deadlock.
2301 		 */
2302 		if (m != NULL) {
2303 			KASSERT(m->dirty == 0,
2304 				("Found dirty cache page %p", m));
2305 			if ((obj = m->object) != NULL) {
2306 				if (vm_object_hold_try(obj)) {
2307 					vm_page_protect(m, VM_PROT_NONE);
2308 					vm_page_free(m);
2309 					/* m->object NULL here */
2310 					vm_object_drop(obj);
2311 				} else {
2312 					vm_page_deactivate(m);
2313 					vm_page_wakeup(m);
2314 				}
2315 			} else {
2316 				vm_page_protect(m, VM_PROT_NONE);
2317 				vm_page_free(m);
2318 			}
2319 			goto loop;
2320 		}
2321 
2322 		/*
2323 		 * On failure return NULL
2324 		 */
2325 		atomic_add_int(&vm_pageout_deficit, 1);
2326 		pagedaemon_wakeup();
2327 		return (NULL);
2328 	} else {
2329 		/*
2330 		 * No pages available, wakeup the pageout daemon and give up.
2331 		 */
2332 		atomic_add_int(&vm_pageout_deficit, 1);
2333 		pagedaemon_wakeup();
2334 		return (NULL);
2335 	}
2336 
2337 	/*
2338 	 * v_free_count can race so loop if we don't find the expected
2339 	 * page.
2340 	 */
2341 	if (m == NULL) {
2342 		vmstats_rollup();
2343 		goto loop;
2344 	}
2345 
2346 	/*
2347 	 * Good page found.  The page has already been busied for us and
2348 	 * removed from its queues.
2349 	 */
2350 	KASSERT(m->dirty == 0,
2351 		("vm_page_alloc: free/cache page %p was dirty", m));
2352 	KKASSERT(m->queue == PQ_NONE);
2353 
2354 #if 0
2355 done:
2356 #endif
2357 	/*
2358 	 * Initialize the structure, inheriting some flags but clearing
2359 	 * all the rest.  The page has already been busied for us.
2360 	 */
2361 	vm_page_flag_clear(m, ~PG_KEEP_NEWPAGE_MASK);
2362 
2363 	KKASSERT(m->wire_count == 0);
2364 	KKASSERT((m->busy_count & PBUSY_MASK) == 0);
2365 	m->act_count = 0;
2366 	m->valid = 0;
2367 
2368 	/*
2369 	 * Caller must be holding the object lock (asserted by
2370 	 * vm_page_insert()).
2371 	 *
2372 	 * NOTE: Inserting a page here does not insert it into any pmaps
2373 	 *	 (which could cause us to block allocating memory).
2374 	 *
2375 	 * NOTE: If no object an unassociated page is allocated, m->pindex
2376 	 *	 can be used by the caller for any purpose.
2377 	 */
2378 	if (object) {
2379 		if (vm_page_insert(m, object, pindex) == FALSE) {
2380 			vm_page_free(m);
2381 			if ((page_req & VM_ALLOC_NULL_OK) == 0)
2382 				panic("PAGE RACE %p[%ld]/%p",
2383 				      object, (long)pindex, m);
2384 			m = NULL;
2385 		}
2386 	} else {
2387 		m->pindex = pindex;
2388 	}
2389 
2390 	/*
2391 	 * Don't wakeup too often - wakeup the pageout daemon when
2392 	 * we would be nearly out of memory.
2393 	 */
2394 	pagedaemon_wakeup();
2395 
2396 	/*
2397 	 * A BUSY page is returned.
2398 	 */
2399 	return (m);
2400 }
2401 
2402 /*
2403  * Returns number of pages available in our DMA memory reserve
2404  * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
2405  */
2406 vm_size_t
2407 vm_contig_avail_pages(void)
2408 {
2409 	alist_blk_t blk;
2410 	alist_blk_t count;
2411 	alist_blk_t bfree;
2412 	spin_lock(&vm_contig_spin);
2413 	bfree = alist_free_info(&vm_contig_alist, &blk, &count);
2414 	spin_unlock(&vm_contig_spin);
2415 
2416 	return bfree;
2417 }
2418 
2419 /*
2420  * Attempt to allocate contiguous physical memory with the specified
2421  * requirements.
2422  */
2423 vm_page_t
2424 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
2425 		     unsigned long alignment, unsigned long boundary,
2426 		     unsigned long size, vm_memattr_t memattr)
2427 {
2428 	alist_blk_t blk;
2429 	vm_page_t m;
2430 	vm_pindex_t i;
2431 #if 0
2432 	static vm_pindex_t contig_rover;
2433 #endif
2434 
2435 	alignment >>= PAGE_SHIFT;
2436 	if (alignment == 0)
2437 		alignment = 1;
2438 	boundary >>= PAGE_SHIFT;
2439 	if (boundary == 0)
2440 		boundary = 1;
2441 	size = (size + PAGE_MASK) >> PAGE_SHIFT;
2442 
2443 #if 0
2444 	/*
2445 	 * Disabled temporarily until we find a solution for DRM (a flag
2446 	 * to always use the free space reserve, for performance).
2447 	 */
2448 	if (high == BUS_SPACE_MAXADDR && alignment <= PAGE_SIZE &&
2449 	    boundary <= PAGE_SIZE && size == 1 &&
2450 	    memattr == VM_MEMATTR_DEFAULT) {
2451 		/*
2452 		 * Any page will work, use vm_page_alloc()
2453 		 * (e.g. when used from kmem_alloc_attr())
2454 		 */
2455 		m = vm_page_alloc(NULL, (contig_rover++) & 0x7FFFFFFF,
2456 				  VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2457 				  VM_ALLOC_INTERRUPT);
2458 		m->valid = VM_PAGE_BITS_ALL;
2459 		vm_page_wire(m);
2460 		vm_page_wakeup(m);
2461 	} else
2462 #endif
2463 	{
2464 		/*
2465 		 * Use the low-memory dma reserve
2466 		 */
2467 		spin_lock(&vm_contig_spin);
2468 		blk = alist_alloc(&vm_contig_alist, 0, size);
2469 		if (blk == ALIST_BLOCK_NONE) {
2470 			spin_unlock(&vm_contig_spin);
2471 			if (bootverbose) {
2472 				kprintf("vm_page_alloc_contig: %ldk nospace\n",
2473 					(size << PAGE_SHIFT) / 1024);
2474 				print_backtrace(5);
2475 			}
2476 			return(NULL);
2477 		}
2478 		if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
2479 			alist_free(&vm_contig_alist, blk, size);
2480 			spin_unlock(&vm_contig_spin);
2481 			if (bootverbose) {
2482 				kprintf("vm_page_alloc_contig: %ldk high "
2483 					"%016jx failed\n",
2484 					(size << PAGE_SHIFT) / 1024,
2485 					(intmax_t)high);
2486 			}
2487 			return(NULL);
2488 		}
2489 		spin_unlock(&vm_contig_spin);
2490 
2491 		/*
2492 		 * Base vm_page_t of range
2493 		 */
2494 		m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
2495 	}
2496 	if (vm_contig_verbose) {
2497 		kprintf("vm_page_alloc_contig: %016jx/%ldk "
2498 			"(%016jx-%016jx al=%lu bo=%lu pgs=%lu attr=%d\n",
2499 			(intmax_t)m->phys_addr,
2500 			(size << PAGE_SHIFT) / 1024,
2501 			low, high, alignment, boundary, size, memattr);
2502 	}
2503 	if (memattr != VM_MEMATTR_DEFAULT) {
2504 		for (i = 0; i < size; ++i) {
2505 			KKASSERT(m[i].flags & PG_FICTITIOUS);
2506 			pmap_page_set_memattr(&m[i], memattr);
2507 		}
2508 	}
2509 	return m;
2510 }
2511 
2512 /*
2513  * Free contiguously allocated pages.  The pages will be wired but not busy.
2514  * When freeing to the alist we leave them wired and not busy.
2515  */
2516 void
2517 vm_page_free_contig(vm_page_t m, unsigned long size)
2518 {
2519 	vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2520 	vm_pindex_t start = pa >> PAGE_SHIFT;
2521 	vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2522 
2523 	if (vm_contig_verbose) {
2524 		kprintf("vm_page_free_contig:  %016jx/%ldk\n",
2525 			(intmax_t)pa, size / 1024);
2526 	}
2527 	if (pa < vm_low_phys_reserved) {
2528 		/*
2529 		 * Just assert check the first page for convenience.
2530 		 */
2531 		KKASSERT(m->wire_count == 1);
2532 		KKASSERT(m->flags & PG_FICTITIOUS);
2533 		KKASSERT(pa + size <= vm_low_phys_reserved);
2534 		spin_lock(&vm_contig_spin);
2535 		alist_free(&vm_contig_alist, start, pages);
2536 		spin_unlock(&vm_contig_spin);
2537 	} else {
2538 		while (pages) {
2539 			/* XXX FUTURE, maybe (pair with vm_pg_contig_alloc()) */
2540 			/*vm_page_flag_clear(m, PG_FICTITIOUS | PG_UNQUEUED);*/
2541 			vm_page_busy_wait(m, FALSE, "cpgfr");
2542 			vm_page_unwire(m, 0);
2543 			vm_page_free(m);
2544 			--pages;
2545 			++m;
2546 		}
2547 
2548 	}
2549 }
2550 
2551 
2552 /*
2553  * Wait for sufficient free memory for nominal heavy memory use kernel
2554  * operations.
2555  *
2556  * WARNING!  Be sure never to call this in any vm_pageout code path, which
2557  *	     will trivially deadlock the system.
2558  */
2559 void
2560 vm_wait_nominal(void)
2561 {
2562 	while (vm_page_count_min(0))
2563 		vm_wait(0);
2564 }
2565 
2566 /*
2567  * Test if vm_wait_nominal() would block.
2568  */
2569 int
2570 vm_test_nominal(void)
2571 {
2572 	if (vm_page_count_min(0))
2573 		return(1);
2574 	return(0);
2575 }
2576 
2577 /*
2578  * Block until free pages are available for allocation, called in various
2579  * places before memory allocations.
2580  *
2581  * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2582  * more generous then that.
2583  */
2584 void
2585 vm_wait(int timo)
2586 {
2587 	/*
2588 	 * never wait forever
2589 	 */
2590 	if (timo == 0)
2591 		timo = hz;
2592 	lwkt_gettoken(&vm_token);
2593 
2594 	if (curthread == pagethread ||
2595 	    curthread == emergpager) {
2596 		/*
2597 		 * The pageout daemon itself needs pages, this is bad.
2598 		 */
2599 		if (vm_page_count_min(0)) {
2600 			vm_pageout_pages_needed = 1;
2601 			tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2602 		}
2603 	} else {
2604 		/*
2605 		 * Wakeup the pageout daemon if necessary and wait.
2606 		 *
2607 		 * Do not wait indefinitely for the target to be reached,
2608 		 * as load might prevent it from being reached any time soon.
2609 		 * But wait a little to try to slow down page allocations
2610 		 * and to give more important threads (the pagedaemon)
2611 		 * allocation priority.
2612 		 */
2613 		if (vm_page_count_target()) {
2614 			if (vm_pages_needed == 0) {
2615 				vm_pages_needed = 1;
2616 				wakeup(&vm_pages_needed);
2617 			}
2618 			++vm_pages_waiting;	/* SMP race ok */
2619 			tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2620 		}
2621 	}
2622 	lwkt_reltoken(&vm_token);
2623 }
2624 
2625 /*
2626  * Block until free pages are available for allocation
2627  *
2628  * Called only from vm_fault so that processes page faulting can be
2629  * easily tracked.
2630  */
2631 void
2632 vm_wait_pfault(void)
2633 {
2634 	/*
2635 	 * Wakeup the pageout daemon if necessary and wait.
2636 	 *
2637 	 * Do not wait indefinitely for the target to be reached,
2638 	 * as load might prevent it from being reached any time soon.
2639 	 * But wait a little to try to slow down page allocations
2640 	 * and to give more important threads (the pagedaemon)
2641 	 * allocation priority.
2642 	 */
2643 	if (vm_page_count_min(0)) {
2644 		lwkt_gettoken(&vm_token);
2645 		while (vm_page_count_severe()) {
2646 			if (vm_page_count_target()) {
2647 				thread_t td;
2648 
2649 				if (vm_pages_needed == 0) {
2650 					vm_pages_needed = 1;
2651 					wakeup(&vm_pages_needed);
2652 				}
2653 				++vm_pages_waiting;	/* SMP race ok */
2654 				tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2655 
2656 				/*
2657 				 * Do not stay stuck in the loop if the system is trying
2658 				 * to kill the process.
2659 				 */
2660 				td = curthread;
2661 				if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2662 					break;
2663 			}
2664 		}
2665 		lwkt_reltoken(&vm_token);
2666 	}
2667 }
2668 
2669 /*
2670  * Put the specified page on the active list (if appropriate).  Ensure
2671  * that act_count is at least ACT_INIT but do not otherwise mess with it.
2672  *
2673  * The caller should be holding the page busied ? XXX
2674  * This routine may not block.
2675  *
2676  * It is ok if the page is wired (so buffer cache operations don't have
2677  * to mess with the page queues).
2678  */
2679 void
2680 vm_page_activate(vm_page_t m)
2681 {
2682 	u_short oqueue;
2683 
2684 	/*
2685 	 * If already active or inappropriate, just set act_count and
2686 	 * return.  We don't have to spin-lock the page.
2687 	 */
2688 	if (m->queue - m->pc == PQ_ACTIVE ||
2689 	    (m->flags & (PG_FICTITIOUS | PG_UNQUEUED))) {
2690 		if (m->act_count < ACT_INIT)
2691 			m->act_count = ACT_INIT;
2692 		return;
2693 	}
2694 
2695 	vm_page_spin_lock(m);
2696 	if (m->queue - m->pc != PQ_ACTIVE &&
2697 	    (m->flags & (PG_FICTITIOUS | PG_UNQUEUED)) == 0) {
2698 		_vm_page_queue_spin_lock(m);
2699 		oqueue = _vm_page_rem_queue_spinlocked(m);
2700 		/* page is left spinlocked, queue is unlocked */
2701 
2702 		if (oqueue == PQ_CACHE)
2703 			mycpu->gd_cnt.v_reactivated++;
2704 		if (m->act_count < ACT_INIT)
2705 			m->act_count = ACT_INIT;
2706 		_vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2707 		_vm_page_and_queue_spin_unlock(m);
2708 		if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2709 			pagedaemon_wakeup();
2710 	} else {
2711 		if (m->act_count < ACT_INIT)
2712 			m->act_count = ACT_INIT;
2713 		vm_page_spin_unlock(m);
2714 	}
2715 }
2716 
2717 void
2718 vm_page_soft_activate(vm_page_t m)
2719 {
2720 	if (m->queue - m->pc == PQ_ACTIVE ||
2721 	    (m->flags & (PG_FICTITIOUS | PG_UNQUEUED))) {
2722 		if (m->act_count < ACT_INIT)
2723 			m->act_count = ACT_INIT;
2724 	} else {
2725 		vm_page_activate(m);
2726 	}
2727 }
2728 
2729 /*
2730  * Helper routine for vm_page_free_toq() and vm_page_cache().  This
2731  * routine is called when a page has been added to the cache or free
2732  * queues.
2733  *
2734  * This routine may not block.
2735  */
2736 static __inline void
2737 vm_page_free_wakeup(void)
2738 {
2739 	globaldata_t gd = mycpu;
2740 
2741 	/*
2742 	 * If the pageout daemon itself needs pages, then tell it that
2743 	 * there are some free.
2744 	 */
2745 	if (vm_pageout_pages_needed &&
2746 	    gd->gd_vmstats.v_cache_count + gd->gd_vmstats.v_free_count >=
2747 	    gd->gd_vmstats.v_pageout_free_min
2748 	) {
2749 		vm_pageout_pages_needed = 0;
2750 		wakeup(&vm_pageout_pages_needed);
2751 	}
2752 
2753 	/*
2754 	 * Wakeup processes that are waiting on memory.
2755 	 *
2756 	 * Generally speaking we want to wakeup stuck processes as soon as
2757 	 * possible.  !vm_page_count_min(0) is the absolute minimum point
2758 	 * where we can do this.  Wait a bit longer to reduce degenerate
2759 	 * re-blocking (vm_page_free_hysteresis).  The target check is just
2760 	 * to make sure the min-check w/hysteresis does not exceed the
2761 	 * normal target.
2762 	 */
2763 	if (vm_pages_waiting) {
2764 		if (!vm_page_count_min(vm_page_free_hysteresis) ||
2765 		    !vm_page_count_target()) {
2766 			vm_pages_waiting = 0;
2767 			wakeup(&vmstats.v_free_count);
2768 			++mycpu->gd_cnt.v_ppwakeups;
2769 		}
2770 #if 0
2771 		if (!vm_page_count_target()) {
2772 			/*
2773 			 * Plenty of pages are free, wakeup everyone.
2774 			 */
2775 			vm_pages_waiting = 0;
2776 			wakeup(&vmstats.v_free_count);
2777 			++mycpu->gd_cnt.v_ppwakeups;
2778 		} else if (!vm_page_count_min(0)) {
2779 			/*
2780 			 * Some pages are free, wakeup someone.
2781 			 */
2782 			int wcount = vm_pages_waiting;
2783 			if (wcount > 0)
2784 				--wcount;
2785 			vm_pages_waiting = wcount;
2786 			wakeup_one(&vmstats.v_free_count);
2787 			++mycpu->gd_cnt.v_ppwakeups;
2788 		}
2789 #endif
2790 	}
2791 }
2792 
2793 /*
2794  * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2795  * it from its VM object.
2796  *
2797  * The vm_page must be BUSY on entry.  BUSY will be released on
2798  * return (the page will have been freed).
2799  */
2800 void
2801 vm_page_free_toq(vm_page_t m)
2802 {
2803 	mycpu->gd_cnt.v_tfree++;
2804 	if (m->flags & (PG_MAPPED | PG_WRITEABLE))
2805 		pmap_mapped_sync(m);
2806 	KKASSERT((m->flags & PG_MAPPED) == 0);
2807 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2808 
2809 	if ((m->busy_count & PBUSY_MASK) || ((m->queue - m->pc) == PQ_FREE)) {
2810 		kprintf("vm_page_free: pindex(%lu), busy %08x, "
2811 			"hold(%d)\n",
2812 			(u_long)m->pindex, m->busy_count, m->hold_count);
2813 		if ((m->queue - m->pc) == PQ_FREE)
2814 			panic("vm_page_free: freeing free page");
2815 		else
2816 			panic("vm_page_free: freeing busy page");
2817 	}
2818 
2819 	/*
2820 	 * Remove from object, spinlock the page and its queues and
2821 	 * remove from any queue.  No queue spinlock will be held
2822 	 * after this section (because the page was removed from any
2823 	 * queue).
2824 	 */
2825 	vm_page_remove(m);
2826 
2827 	/*
2828 	 * No further management of fictitious pages occurs beyond object
2829 	 * and queue removal.
2830 	 */
2831 	if ((m->flags & PG_FICTITIOUS) != 0) {
2832 		KKASSERT(m->queue == PQ_NONE);
2833 		vm_page_wakeup(m);
2834 		return;
2835 	}
2836 	vm_page_and_queue_spin_lock(m);
2837 	_vm_page_rem_queue_spinlocked(m);
2838 
2839 	m->valid = 0;
2840 	vm_page_undirty(m);
2841 
2842 	if (m->wire_count != 0) {
2843 		if (m->wire_count > 1) {
2844 		    panic(
2845 			"vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2846 			m->wire_count, (long)m->pindex);
2847 		}
2848 		panic("vm_page_free: freeing wired page");
2849 	}
2850 
2851 	if (!MD_PAGE_FREEABLE(m))
2852 		panic("vm_page_free: page %p is still mapped!", m);
2853 
2854 	/*
2855 	 * Clear the PG_NEED_COMMIT and the PG_UNQUEUED flags.  The
2856 	 * page returns to normal operation and will be placed in
2857 	 * the PQ_HOLD or PQ_FREE queue.
2858 	 */
2859 	vm_page_flag_clear(m, PG_NEED_COMMIT | PG_UNQUEUED);
2860 
2861 	if (m->hold_count != 0) {
2862 		_vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2863 	} else {
2864 		_vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
2865 	}
2866 
2867 	/*
2868 	 * This sequence allows us to clear BUSY while still holding
2869 	 * its spin lock, which reduces contention vs allocators.  We
2870 	 * must not leave the queue locked or _vm_page_wakeup() may
2871 	 * deadlock.
2872 	 */
2873 	_vm_page_queue_spin_unlock(m);
2874 	if (_vm_page_wakeup(m)) {
2875 		vm_page_spin_unlock(m);
2876 		wakeup(m);
2877 	} else {
2878 		vm_page_spin_unlock(m);
2879 	}
2880 	vm_page_free_wakeup();
2881 }
2882 
2883 /*
2884  * Mark this page as wired down by yet another map.  We do not adjust the
2885  * queue the page is on, it will be checked for wiring as-needed.
2886  *
2887  * This function has no effect on fictitious pages.
2888  *
2889  * Caller must be holding the page busy.
2890  */
2891 void
2892 vm_page_wire(vm_page_t m)
2893 {
2894 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2895 	if ((m->flags & PG_FICTITIOUS) == 0) {
2896 		if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2897 			atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count, 1);
2898 		}
2899 		KASSERT(m->wire_count != 0,
2900 			("vm_page_wire: wire_count overflow m=%p", m));
2901 	}
2902 }
2903 
2904 /*
2905  * Release one wiring of this page, potentially enabling it to be paged again.
2906  *
2907  * Note that wired pages are no longer unconditionally removed from the
2908  * paging queues, so the page may already be on a queue.  Move the page
2909  * to the desired queue if necessary.
2910  *
2911  * Many pages placed on the inactive queue should actually go
2912  * into the cache, but it is difficult to figure out which.  What
2913  * we do instead, if the inactive target is well met, is to put
2914  * clean pages at the head of the inactive queue instead of the tail.
2915  * This will cause them to be moved to the cache more quickly and
2916  * if not actively re-referenced, freed more quickly.  If we just
2917  * stick these pages at the end of the inactive queue, heavy filesystem
2918  * meta-data accesses can cause an unnecessary paging load on memory bound
2919  * processes.  This optimization causes one-time-use metadata to be
2920  * reused more quickly.
2921  *
2922  * Pages marked PG_NEED_COMMIT are always activated and never placed on
2923  * the inactive queue.  This helps the pageout daemon determine memory
2924  * pressure and act on out-of-memory situations more quickly.
2925  *
2926  * BUT, if we are in a low-memory situation we have no choice but to
2927  * put clean pages on the cache queue.
2928  *
2929  * A number of routines use vm_page_unwire() to guarantee that the page
2930  * will go into either the inactive or active queues, and will NEVER
2931  * be placed in the cache - for example, just after dirtying a page.
2932  * dirty pages in the cache are not allowed.
2933  *
2934  * PG_FICTITIOUS or PG_UNQUEUED pages are never moved to any queue, and
2935  * the wire_count will not be adjusted in any way for a PG_FICTITIOUS
2936  * page.
2937  *
2938  * This routine may not block.
2939  */
2940 void
2941 vm_page_unwire(vm_page_t m, int activate)
2942 {
2943 	KKASSERT(m->busy_count & PBUSY_LOCKED);
2944 	if (m->flags & PG_FICTITIOUS) {
2945 		/* do nothing */
2946 	} else if ((int)m->wire_count <= 0) {
2947 		panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2948 	} else {
2949 		if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2950 			atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count,-1);
2951 			if (m->flags & PG_UNQUEUED) {
2952 				;
2953 			} else if (activate || (m->flags & PG_NEED_COMMIT)) {
2954 				vm_page_activate(m);
2955 			} else {
2956 				vm_page_deactivate(m);
2957 			}
2958 		}
2959 	}
2960 }
2961 
2962 /*
2963  * Move the specified page to the inactive queue.
2964  *
2965  * Normally athead is 0 resulting in LRU operation.  athead is set
2966  * to 1 if we want this page to be 'as if it were placed in the cache',
2967  * except without unmapping it from the process address space.
2968  *
2969  * vm_page's spinlock must be held on entry and will remain held on return.
2970  * This routine may not block.  The caller does not have to hold the page
2971  * busied but should have some sort of interlock on its validity.
2972  *
2973  * It is ok if the page is wired (so buffer cache operations don't have
2974  * to mess with the page queues).
2975  */
2976 static void
2977 _vm_page_deactivate_locked(vm_page_t m, int athead)
2978 {
2979 	u_short oqueue;
2980 
2981 	/*
2982 	 * Ignore if already inactive.
2983 	 */
2984 	if (m->queue - m->pc == PQ_INACTIVE ||
2985 	    (m->flags & (PG_FICTITIOUS | PG_UNQUEUED))) {
2986 		return;
2987 	}
2988 
2989 	_vm_page_queue_spin_lock(m);
2990 	oqueue = _vm_page_rem_queue_spinlocked(m);
2991 
2992 	if ((m->flags & (PG_FICTITIOUS | PG_UNQUEUED)) == 0) {
2993 		if (oqueue == PQ_CACHE)
2994 			mycpu->gd_cnt.v_reactivated++;
2995 		vm_page_flag_clear(m, PG_WINATCFLS);
2996 		_vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2997 		if (athead == 0) {
2998 			atomic_add_long(
2999 				&vm_page_queues[PQ_INACTIVE + m->pc].adds, 1);
3000 		}
3001 	}
3002 	/* NOTE: PQ_NONE if condition not taken */
3003 	_vm_page_queue_spin_unlock(m);
3004 	/* leaves vm_page spinlocked */
3005 }
3006 
3007 /*
3008  * Attempt to deactivate a page.
3009  *
3010  * No requirements.  We can pre-filter before getting the spinlock.
3011  *
3012  * It is ok if the page is wired (so buffer cache operations don't have
3013  * to mess with the page queues).
3014  */
3015 void
3016 vm_page_deactivate(vm_page_t m)
3017 {
3018 	if (m->queue - m->pc != PQ_INACTIVE &&
3019 	    (m->flags & (PG_FICTITIOUS | PG_UNQUEUED)) == 0) {
3020 		vm_page_spin_lock(m);
3021 		_vm_page_deactivate_locked(m, 0);
3022 		vm_page_spin_unlock(m);
3023 	}
3024 }
3025 
3026 void
3027 vm_page_deactivate_locked(vm_page_t m)
3028 {
3029 	_vm_page_deactivate_locked(m, 0);
3030 }
3031 
3032 /*
3033  * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
3034  *
3035  * This function returns non-zero if it successfully moved the page to
3036  * PQ_CACHE.
3037  *
3038  * This function unconditionally unbusies the page on return.
3039  */
3040 int
3041 vm_page_try_to_cache(vm_page_t m)
3042 {
3043 	/*
3044 	 * Shortcut if we obviously cannot move the page, or if the
3045 	 * page is already on the cache queue, or it is ficitious.
3046 	 *
3047 	 * Never allow a wired page into the cache.
3048 	 */
3049 	if (m->dirty || m->hold_count || m->wire_count ||
3050 	    m->queue - m->pc == PQ_CACHE ||
3051 	    (m->flags & (PG_UNQUEUED | PG_NEED_COMMIT | PG_FICTITIOUS))) {
3052 		vm_page_wakeup(m);
3053 		return(0);
3054 	}
3055 
3056 	/*
3057 	 * Page busied by us and no longer spinlocked.  Dirty pages cannot
3058 	 * be moved to the cache.
3059 	 */
3060 	vm_page_test_dirty(m);
3061 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3062 		vm_page_wakeup(m);
3063 		return(0);
3064 	}
3065 	vm_page_cache(m);
3066 	return(1);
3067 }
3068 
3069 /*
3070  * Attempt to free the page.  If we cannot free it, we do nothing.
3071  * 1 is returned on success, 0 on failure.
3072  *
3073  * The page can be in any state, including already being on the free
3074  * queue.  Check to see if it really can be freed.  Note that we disallow
3075  * this ad-hoc operation if the page is flagged PG_UNQUEUED.
3076  *
3077  * Caller provides an unlocked/non-busied page.
3078  * No requirements.
3079  */
3080 int
3081 vm_page_try_to_free(vm_page_t m)
3082 {
3083 	if (vm_page_busy_try(m, TRUE))
3084 		return(0);
3085 
3086 	if (m->dirty ||				/* can't free if it is dirty */
3087 	    m->hold_count ||			/* or held (XXX may be wrong) */
3088 	    m->wire_count ||			/* or wired */
3089 	    (m->flags & (PG_UNQUEUED |		/* or unqueued */
3090 			 PG_NEED_COMMIT |	/* or needs a commit */
3091 			 PG_FICTITIOUS)) ||	/* or is fictitious */
3092 	    m->queue - m->pc == PQ_FREE ||	/* already on PQ_FREE */
3093 	    m->queue - m->pc == PQ_HOLD) {	/* already on PQ_HOLD */
3094 		vm_page_wakeup(m);
3095 		return(0);
3096 	}
3097 
3098 	/*
3099 	 * We can probably free the page.
3100 	 *
3101 	 * Page busied by us and no longer spinlocked.  Dirty pages will
3102 	 * not be freed by this function.    We have to re-test the
3103 	 * dirty bit after cleaning out the pmaps.
3104 	 */
3105 	vm_page_test_dirty(m);
3106 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3107 		vm_page_wakeup(m);
3108 		return(0);
3109 	}
3110 	vm_page_protect(m, VM_PROT_NONE);
3111 	if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3112 		vm_page_wakeup(m);
3113 		return(0);
3114 	}
3115 	vm_page_free(m);
3116 	return(1);
3117 }
3118 
3119 /*
3120  * vm_page_cache
3121  *
3122  * Put the specified page onto the page cache queue (if appropriate).
3123  *
3124  * The page must be busy, and this routine will release the busy and
3125  * possibly even free the page.
3126  */
3127 void
3128 vm_page_cache(vm_page_t m)
3129 {
3130 	/*
3131 	 * Not suitable for the cache
3132 	 */
3133 	if ((m->flags & (PG_UNQUEUED | PG_NEED_COMMIT | PG_FICTITIOUS)) ||
3134 	    (m->busy_count & PBUSY_MASK) ||
3135 	    m->wire_count || m->hold_count) {
3136 		vm_page_wakeup(m);
3137 		return;
3138 	}
3139 
3140 	/*
3141 	 * Already in the cache (and thus not mapped)
3142 	 */
3143 	if ((m->queue - m->pc) == PQ_CACHE) {
3144 		if (m->flags & (PG_MAPPED | PG_WRITEABLE))
3145 			pmap_mapped_sync(m);
3146 		KKASSERT((m->flags & PG_MAPPED) == 0);
3147 		vm_page_wakeup(m);
3148 		return;
3149 	}
3150 
3151 #if 0
3152 	/*
3153 	 * REMOVED - it is possible for dirty to get set at any time as
3154 	 *	     long as the page is still mapped and writeable.
3155 	 *
3156 	 * Caller is required to test m->dirty, but note that the act of
3157 	 * removing the page from its maps can cause it to become dirty
3158 	 * on an SMP system due to another cpu running in usermode.
3159 	 */
3160 	if (m->dirty) {
3161 		panic("vm_page_cache: caching a dirty page, pindex: %ld",
3162 			(long)m->pindex);
3163 	}
3164 #endif
3165 
3166 	/*
3167 	 * Remove all pmaps and indicate that the page is not
3168 	 * writeable or mapped.  Our vm_page_protect() call may
3169 	 * have blocked (especially w/ VM_PROT_NONE), so recheck
3170 	 * everything.
3171 	 */
3172 	vm_page_protect(m, VM_PROT_NONE);
3173 	pmap_mapped_sync(m);
3174 	if ((m->flags & (PG_UNQUEUED | PG_MAPPED)) ||
3175 	    (m->busy_count & PBUSY_MASK) ||
3176 	    m->wire_count || m->hold_count) {
3177 		vm_page_wakeup(m);
3178 	} else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3179 		vm_page_deactivate(m);
3180 		vm_page_wakeup(m);
3181 	} else {
3182 		_vm_page_and_queue_spin_lock(m);
3183 		_vm_page_rem_queue_spinlocked(m);
3184 		_vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
3185 		_vm_page_and_queue_spin_unlock(m);
3186 		vm_page_wakeup(m);
3187 		vm_page_free_wakeup();
3188 	}
3189 }
3190 
3191 /*
3192  * vm_page_dontneed()
3193  *
3194  * Cache, deactivate, or do nothing as appropriate.  This routine
3195  * is typically used by madvise() MADV_DONTNEED.
3196  *
3197  * Generally speaking we want to move the page into the cache so
3198  * it gets reused quickly.  However, this can result in a silly syndrome
3199  * due to the page recycling too quickly.  Small objects will not be
3200  * fully cached.  On the otherhand, if we move the page to the inactive
3201  * queue we wind up with a problem whereby very large objects
3202  * unnecessarily blow away our inactive and cache queues.
3203  *
3204  * The solution is to move the pages based on a fixed weighting.  We
3205  * either leave them alone, deactivate them, or move them to the cache,
3206  * where moving them to the cache has the highest weighting.
3207  * By forcing some pages into other queues we eventually force the
3208  * system to balance the queues, potentially recovering other unrelated
3209  * space from active.  The idea is to not force this to happen too
3210  * often.
3211  *
3212  * The page must be busied.
3213  */
3214 void
3215 vm_page_dontneed(vm_page_t m)
3216 {
3217 	static int dnweight;
3218 	int dnw;
3219 	int head;
3220 
3221 	dnw = ++dnweight;
3222 
3223 	/*
3224 	 * occassionally leave the page alone
3225 	 */
3226 	if ((dnw & 0x01F0) == 0 ||
3227 	    m->queue - m->pc == PQ_INACTIVE ||
3228 	    m->queue - m->pc == PQ_CACHE
3229 	) {
3230 		if (m->act_count >= ACT_INIT)
3231 			--m->act_count;
3232 		return;
3233 	}
3234 
3235 	/*
3236 	 * If vm_page_dontneed() is inactivating a page, it must clear
3237 	 * the referenced flag; otherwise the pagedaemon will see references
3238 	 * on the page in the inactive queue and reactivate it. Until the
3239 	 * page can move to the cache queue, madvise's job is not done.
3240 	 */
3241 	vm_page_flag_clear(m, PG_REFERENCED);
3242 	pmap_clear_reference(m);
3243 
3244 	if (m->dirty == 0)
3245 		vm_page_test_dirty(m);
3246 
3247 	if (m->dirty || (dnw & 0x0070) == 0) {
3248 		/*
3249 		 * Deactivate the page 3 times out of 32.
3250 		 */
3251 		head = 0;
3252 	} else {
3253 		/*
3254 		 * Cache the page 28 times out of every 32.  Note that
3255 		 * the page is deactivated instead of cached, but placed
3256 		 * at the head of the queue instead of the tail.
3257 		 */
3258 		head = 1;
3259 	}
3260 	vm_page_spin_lock(m);
3261 	_vm_page_deactivate_locked(m, head);
3262 	vm_page_spin_unlock(m);
3263 }
3264 
3265 /*
3266  * These routines manipulate the 'soft busy' count for a page.  A soft busy
3267  * is almost like a hard BUSY except that it allows certain compatible
3268  * operations to occur on the page while it is busy.  For example, a page
3269  * undergoing a write can still be mapped read-only.
3270  *
3271  * We also use soft-busy to quickly pmap_enter shared read-only pages
3272  * without having to hold the page locked.
3273  *
3274  * The soft-busy count can be > 1 in situations where multiple threads
3275  * are pmap_enter()ing the same page simultaneously, or when two buffer
3276  * cache buffers overlap the same page.
3277  *
3278  * The caller must hold the page BUSY when making these two calls.
3279  */
3280 void
3281 vm_page_io_start(vm_page_t m)
3282 {
3283 	uint32_t ocount;
3284 
3285 	ocount = atomic_fetchadd_int(&m->busy_count, 1);
3286 	KKASSERT(ocount & PBUSY_LOCKED);
3287 }
3288 
3289 void
3290 vm_page_io_finish(vm_page_t m)
3291 {
3292 	uint32_t ocount;
3293 
3294 	ocount = atomic_fetchadd_int(&m->busy_count, -1);
3295 	KKASSERT(ocount & PBUSY_MASK);
3296 #if 0
3297 	if (((ocount - 1) & (PBUSY_LOCKED | PBUSY_MASK)) == 0)
3298 		wakeup(m);
3299 #endif
3300 }
3301 
3302 /*
3303  * Attempt to soft-busy a page.  The page must not be PBUSY_LOCKED.
3304  *
3305  * We can't use fetchadd here because we might race a hard-busy and the
3306  * page freeing code asserts on a non-zero soft-busy count (even if only
3307  * temporary).
3308  *
3309  * Returns 0 on success, non-zero on failure.
3310  */
3311 int
3312 vm_page_sbusy_try(vm_page_t m)
3313 {
3314 	uint32_t ocount;
3315 
3316 	for (;;) {
3317 		ocount = m->busy_count;
3318 		cpu_ccfence();
3319 		if (ocount & PBUSY_LOCKED)
3320 			return 1;
3321 		if (atomic_cmpset_int(&m->busy_count, ocount, ocount + 1))
3322 			break;
3323 	}
3324 	return 0;
3325 #if 0
3326 	if (m->busy_count & PBUSY_LOCKED)
3327 		return 1;
3328 	ocount = atomic_fetchadd_int(&m->busy_count, 1);
3329 	if (ocount & PBUSY_LOCKED) {
3330 		vm_page_sbusy_drop(m);
3331 		return 1;
3332 	}
3333 	return 0;
3334 #endif
3335 }
3336 
3337 /*
3338  * Indicate that a clean VM page requires a filesystem commit and cannot
3339  * be reused.  Used by tmpfs.
3340  */
3341 void
3342 vm_page_need_commit(vm_page_t m)
3343 {
3344 	vm_page_flag_set(m, PG_NEED_COMMIT);
3345 	vm_object_set_writeable_dirty(m->object);
3346 }
3347 
3348 void
3349 vm_page_clear_commit(vm_page_t m)
3350 {
3351 	vm_page_flag_clear(m, PG_NEED_COMMIT);
3352 }
3353 
3354 /*
3355  * Grab a page, blocking if it is busy and allocating a page if necessary.
3356  * A busy page is returned or NULL.  The page may or may not be valid and
3357  * might not be on a queue (the caller is responsible for the disposition of
3358  * the page).
3359  *
3360  * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
3361  * page will be zero'd and marked valid.
3362  *
3363  * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
3364  * valid even if it already exists.
3365  *
3366  * If VM_ALLOC_RETRY is specified this routine will never return NULL.  Also
3367  * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
3368  * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
3369  *
3370  * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
3371  * always returned if we had blocked.
3372  *
3373  * This routine may not be called from an interrupt.
3374  *
3375  * No other requirements.
3376  */
3377 vm_page_t
3378 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3379 {
3380 	vm_page_t m;
3381 	int error;
3382 	int shared = 1;
3383 
3384 	KKASSERT(allocflags &
3385 		(VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
3386 	vm_object_hold_shared(object);
3387 	for (;;) {
3388 		m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3389 		if (error) {
3390 			vm_page_sleep_busy(m, TRUE, "pgrbwt");
3391 			if ((allocflags & VM_ALLOC_RETRY) == 0) {
3392 				m = NULL;
3393 				break;
3394 			}
3395 			/* retry */
3396 		} else if (m == NULL) {
3397 			if (shared) {
3398 				vm_object_upgrade(object);
3399 				shared = 0;
3400 			}
3401 			if (allocflags & VM_ALLOC_RETRY)
3402 				allocflags |= VM_ALLOC_NULL_OK;
3403 			m = vm_page_alloc(object, pindex,
3404 					  allocflags & ~VM_ALLOC_RETRY);
3405 			if (m)
3406 				break;
3407 			vm_wait(0);
3408 			if ((allocflags & VM_ALLOC_RETRY) == 0)
3409 				goto failed;
3410 		} else {
3411 			/* m found */
3412 			break;
3413 		}
3414 	}
3415 
3416 	/*
3417 	 * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
3418 	 *
3419 	 * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
3420 	 * valid even if already valid.
3421 	 *
3422 	 * NOTE!  We have removed all of the PG_ZERO optimizations and also
3423 	 *	  removed the idle zeroing code.  These optimizations actually
3424 	 *	  slow things down on modern cpus because the zerod area is
3425 	 *	  likely uncached, placing a memory-access burden on the
3426 	 *	  accesors taking the fault.
3427 	 *
3428 	 *	  By always zeroing the page in-line with the fault, no
3429 	 *	  dynamic ram reads are needed and the caches are hot, ready
3430 	 *	  for userland to access the memory.
3431 	 */
3432 	if (m->valid == 0) {
3433 		if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
3434 			pmap_zero_page(VM_PAGE_TO_PHYS(m));
3435 			m->valid = VM_PAGE_BITS_ALL;
3436 		}
3437 	} else if (allocflags & VM_ALLOC_FORCE_ZERO) {
3438 		pmap_zero_page(VM_PAGE_TO_PHYS(m));
3439 		m->valid = VM_PAGE_BITS_ALL;
3440 	}
3441 failed:
3442 	vm_object_drop(object);
3443 	return(m);
3444 }
3445 
3446 /*
3447  * Mapping function for valid bits or for dirty bits in
3448  * a page.  May not block.
3449  *
3450  * Inputs are required to range within a page.
3451  *
3452  * No requirements.
3453  * Non blocking.
3454  */
3455 int
3456 vm_page_bits(int base, int size)
3457 {
3458 	int first_bit;
3459 	int last_bit;
3460 
3461 	KASSERT(
3462 	    base + size <= PAGE_SIZE,
3463 	    ("vm_page_bits: illegal base/size %d/%d", base, size)
3464 	);
3465 
3466 	if (size == 0)		/* handle degenerate case */
3467 		return(0);
3468 
3469 	first_bit = base >> DEV_BSHIFT;
3470 	last_bit = (base + size - 1) >> DEV_BSHIFT;
3471 
3472 	return ((2 << last_bit) - (1 << first_bit));
3473 }
3474 
3475 /*
3476  * Sets portions of a page valid and clean.  The arguments are expected
3477  * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3478  * of any partial chunks touched by the range.  The invalid portion of
3479  * such chunks will be zero'd.
3480  *
3481  * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
3482  *	 align base to DEV_BSIZE so as not to mark clean a partially
3483  *	 truncated device block.  Otherwise the dirty page status might be
3484  *	 lost.
3485  *
3486  * This routine may not block.
3487  *
3488  * (base + size) must be less then or equal to PAGE_SIZE.
3489  */
3490 static void
3491 _vm_page_zero_valid(vm_page_t m, int base, int size)
3492 {
3493 	int frag;
3494 	int endoff;
3495 
3496 	if (size == 0)	/* handle degenerate case */
3497 		return;
3498 
3499 	/*
3500 	 * If the base is not DEV_BSIZE aligned and the valid
3501 	 * bit is clear, we have to zero out a portion of the
3502 	 * first block.
3503 	 */
3504 
3505 	if ((frag = rounddown2(base, DEV_BSIZE)) != base &&
3506 	    (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
3507 	) {
3508 		pmap_zero_page_area(
3509 		    VM_PAGE_TO_PHYS(m),
3510 		    frag,
3511 		    base - frag
3512 		);
3513 	}
3514 
3515 	/*
3516 	 * If the ending offset is not DEV_BSIZE aligned and the
3517 	 * valid bit is clear, we have to zero out a portion of
3518 	 * the last block.
3519 	 */
3520 
3521 	endoff = base + size;
3522 
3523 	if ((frag = rounddown2(endoff, DEV_BSIZE)) != endoff &&
3524 	    (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
3525 	) {
3526 		pmap_zero_page_area(
3527 		    VM_PAGE_TO_PHYS(m),
3528 		    endoff,
3529 		    DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
3530 		);
3531 	}
3532 }
3533 
3534 /*
3535  * Set valid, clear dirty bits.  If validating the entire
3536  * page we can safely clear the pmap modify bit.  We also
3537  * use this opportunity to clear the PG_NOSYNC flag.  If a process
3538  * takes a write fault on a MAP_NOSYNC memory area the flag will
3539  * be set again.
3540  *
3541  * We set valid bits inclusive of any overlap, but we can only
3542  * clear dirty bits for DEV_BSIZE chunks that are fully within
3543  * the range.
3544  *
3545  * Page must be busied?
3546  * No other requirements.
3547  */
3548 void
3549 vm_page_set_valid(vm_page_t m, int base, int size)
3550 {
3551 	_vm_page_zero_valid(m, base, size);
3552 	m->valid |= vm_page_bits(base, size);
3553 }
3554 
3555 
3556 /*
3557  * Set valid bits and clear dirty bits.
3558  *
3559  * Page must be busied by caller.
3560  *
3561  * NOTE: This function does not clear the pmap modified bit.
3562  *	 Also note that e.g. NFS may use a byte-granular base
3563  *	 and size.
3564  *
3565  * No other requirements.
3566  */
3567 void
3568 vm_page_set_validclean(vm_page_t m, int base, int size)
3569 {
3570 	int pagebits;
3571 
3572 	_vm_page_zero_valid(m, base, size);
3573 	pagebits = vm_page_bits(base, size);
3574 	m->valid |= pagebits;
3575 	m->dirty &= ~pagebits;
3576 	if (base == 0 && size == PAGE_SIZE) {
3577 		/*pmap_clear_modify(m);*/
3578 		vm_page_flag_clear(m, PG_NOSYNC);
3579 	}
3580 }
3581 
3582 /*
3583  * Set valid & dirty.  Used by buwrite()
3584  *
3585  * Page must be busied by caller.
3586  */
3587 void
3588 vm_page_set_validdirty(vm_page_t m, int base, int size)
3589 {
3590 	int pagebits;
3591 
3592 	pagebits = vm_page_bits(base, size);
3593 	m->valid |= pagebits;
3594 	m->dirty |= pagebits;
3595 	if (m->object)
3596 	       vm_object_set_writeable_dirty(m->object);
3597 }
3598 
3599 /*
3600  * Clear dirty bits.
3601  *
3602  * NOTE: This function does not clear the pmap modified bit.
3603  *	 Also note that e.g. NFS may use a byte-granular base
3604  *	 and size.
3605  *
3606  * Page must be busied?
3607  * No other requirements.
3608  */
3609 void
3610 vm_page_clear_dirty(vm_page_t m, int base, int size)
3611 {
3612 	m->dirty &= ~vm_page_bits(base, size);
3613 	if (base == 0 && size == PAGE_SIZE) {
3614 		/*pmap_clear_modify(m);*/
3615 		vm_page_flag_clear(m, PG_NOSYNC);
3616 	}
3617 }
3618 
3619 /*
3620  * Make the page all-dirty.
3621  *
3622  * Also make sure the related object and vnode reflect the fact that the
3623  * object may now contain a dirty page.
3624  *
3625  * Page must be busied?
3626  * No other requirements.
3627  */
3628 void
3629 vm_page_dirty(vm_page_t m)
3630 {
3631 #ifdef INVARIANTS
3632         int pqtype = m->queue - m->pc;
3633 #endif
3634         KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3635                 ("vm_page_dirty: page in free/cache queue!"));
3636 	if (m->dirty != VM_PAGE_BITS_ALL) {
3637 		m->dirty = VM_PAGE_BITS_ALL;
3638 		if (m->object)
3639 			vm_object_set_writeable_dirty(m->object);
3640 	}
3641 }
3642 
3643 /*
3644  * Invalidates DEV_BSIZE'd chunks within a page.  Both the
3645  * valid and dirty bits for the effected areas are cleared.
3646  *
3647  * Page must be busied?
3648  * Does not block.
3649  * No other requirements.
3650  */
3651 void
3652 vm_page_set_invalid(vm_page_t m, int base, int size)
3653 {
3654 	int bits;
3655 
3656 	bits = vm_page_bits(base, size);
3657 	m->valid &= ~bits;
3658 	m->dirty &= ~bits;
3659 	atomic_add_int(&m->object->generation, 1);
3660 }
3661 
3662 /*
3663  * The kernel assumes that the invalid portions of a page contain
3664  * garbage, but such pages can be mapped into memory by user code.
3665  * When this occurs, we must zero out the non-valid portions of the
3666  * page so user code sees what it expects.
3667  *
3668  * Pages are most often semi-valid when the end of a file is mapped
3669  * into memory and the file's size is not page aligned.
3670  *
3671  * Page must be busied?
3672  * No other requirements.
3673  */
3674 void
3675 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3676 {
3677 	int b;
3678 	int i;
3679 
3680 	/*
3681 	 * Scan the valid bits looking for invalid sections that
3682 	 * must be zerod.  Invalid sub-DEV_BSIZE'd areas ( where the
3683 	 * valid bit may be set ) have already been zerod by
3684 	 * vm_page_set_validclean().
3685 	 */
3686 	for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3687 		if (i == (PAGE_SIZE / DEV_BSIZE) ||
3688 		    (m->valid & (1 << i))
3689 		) {
3690 			if (i > b) {
3691 				pmap_zero_page_area(
3692 				    VM_PAGE_TO_PHYS(m),
3693 				    b << DEV_BSHIFT,
3694 				    (i - b) << DEV_BSHIFT
3695 				);
3696 			}
3697 			b = i + 1;
3698 		}
3699 	}
3700 
3701 	/*
3702 	 * setvalid is TRUE when we can safely set the zero'd areas
3703 	 * as being valid.  We can do this if there are no cache consistency
3704 	 * issues.  e.g. it is ok to do with UFS, but not ok to do with NFS.
3705 	 */
3706 	if (setvalid)
3707 		m->valid = VM_PAGE_BITS_ALL;
3708 }
3709 
3710 /*
3711  * Is a (partial) page valid?  Note that the case where size == 0
3712  * will return FALSE in the degenerate case where the page is entirely
3713  * invalid, and TRUE otherwise.
3714  *
3715  * Does not block.
3716  * No other requirements.
3717  */
3718 int
3719 vm_page_is_valid(vm_page_t m, int base, int size)
3720 {
3721 	int bits = vm_page_bits(base, size);
3722 
3723 	if (m->valid && ((m->valid & bits) == bits))
3724 		return 1;
3725 	else
3726 		return 0;
3727 }
3728 
3729 /*
3730  * Update dirty bits from pmap/mmu.  May not block.
3731  *
3732  * Caller must hold the page busy
3733  *
3734  * WARNING! Unless the page has been unmapped, this function only
3735  *	    provides a likely dirty status.
3736  */
3737 void
3738 vm_page_test_dirty(vm_page_t m)
3739 {
3740 	if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m)) {
3741 		vm_page_dirty(m);
3742 	}
3743 }
3744 
3745 #include "opt_ddb.h"
3746 #ifdef DDB
3747 #include <ddb/ddb.h>
3748 
3749 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3750 {
3751 	db_printf("vmstats.v_free_count: %ld\n", vmstats.v_free_count);
3752 	db_printf("vmstats.v_cache_count: %ld\n", vmstats.v_cache_count);
3753 	db_printf("vmstats.v_inactive_count: %ld\n", vmstats.v_inactive_count);
3754 	db_printf("vmstats.v_active_count: %ld\n", vmstats.v_active_count);
3755 	db_printf("vmstats.v_wire_count: %ld\n", vmstats.v_wire_count);
3756 	db_printf("vmstats.v_free_reserved: %ld\n", vmstats.v_free_reserved);
3757 	db_printf("vmstats.v_free_min: %ld\n", vmstats.v_free_min);
3758 	db_printf("vmstats.v_free_target: %ld\n", vmstats.v_free_target);
3759 	db_printf("vmstats.v_cache_min: %ld\n", vmstats.v_cache_min);
3760 	db_printf("vmstats.v_inactive_target: %ld\n",
3761 		  vmstats.v_inactive_target);
3762 }
3763 
3764 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3765 {
3766 	int i;
3767 	db_printf("PQ_FREE:");
3768 	for (i = 0; i < PQ_L2_SIZE; i++) {
3769 		db_printf(" %ld", vm_page_queues[PQ_FREE + i].lcnt);
3770 	}
3771 	db_printf("\n");
3772 
3773 	db_printf("PQ_CACHE:");
3774 	for(i = 0; i < PQ_L2_SIZE; i++) {
3775 		db_printf(" %ld", vm_page_queues[PQ_CACHE + i].lcnt);
3776 	}
3777 	db_printf("\n");
3778 
3779 	db_printf("PQ_ACTIVE:");
3780 	for(i = 0; i < PQ_L2_SIZE; i++) {
3781 		db_printf(" %ld", vm_page_queues[PQ_ACTIVE + i].lcnt);
3782 	}
3783 	db_printf("\n");
3784 
3785 	db_printf("PQ_INACTIVE:");
3786 	for(i = 0; i < PQ_L2_SIZE; i++) {
3787 		db_printf(" %ld", vm_page_queues[PQ_INACTIVE + i].lcnt);
3788 	}
3789 	db_printf("\n");
3790 }
3791 #endif /* DDB */
3792