2 * Copyright (c) 2003-2019 The DragonFly Project. All rights reserved.
3 * Copyright (c) 1991 Regents of the University of California.
6 * This code is derived from software contributed to Berkeley by
7 * The Mach Operating System project at Carnegie-Mellon University.
9 * This code is derived from software contributed to The DragonFly Project
10 * by Matthew Dillon <dillon@backplane.com>
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
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.
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
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 $
41 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
42 * All rights reserved.
44 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
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.
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.
56 * Carnegie Mellon requests users of this software to return to
58 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
59 * School of Computer Science
60 * Carnegie Mellon University
61 * Pittsburgh PA 15213-3890
63 * any improvements or extensions that they make and grant Carnegie the
64 * rights to redistribute these changes.
67 * Resident memory management module. The module manipulates 'VM pages'.
68 * A VM page is the core building block for memory management.
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/malloc.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>
83 #include <vm/vm_param.h>
85 #include <vm/vm_kern.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>
95 #include <machine/inttypes.h>
96 #include <machine/md_var.h>
97 #include <machine/specialreg.h>
98 #include <machine/bus_dma.h>
100 #include <vm/vm_page2.h>
101 #include <sys/spinlock2.h>
103 struct vm_page_hash_elm {
110 * SET - Minimum required set associative size, must be a power of 2. We
111 * want this to match or exceed the set-associativeness of the cpu,
112 * up to a reasonable limit (we will use 16).
114 __read_mostly static int set_assoc_mask = 16 - 1;
116 static void vm_page_queue_init(void);
117 static void vm_page_free_wakeup(void);
118 static vm_page_t vm_page_select_cache(u_short pg_color);
119 static vm_page_t _vm_page_list_find2(int basequeue, int index, int *lastp);
120 static void _vm_page_deactivate_locked(vm_page_t m, int athead);
121 static void vm_numa_add_topology_mem(cpu_node_t *cpup, int physid, long bytes);
124 * Array of tailq lists
126 struct vpgqueues vm_page_queues[PQ_COUNT];
128 static volatile int vm_pages_waiting;
129 static struct alist vm_contig_alist;
130 static struct almeta vm_contig_ameta[ALIST_RECORDS_65536];
131 static struct spinlock vm_contig_spin = SPINLOCK_INITIALIZER(&vm_contig_spin, "vm_contig_spin");
133 static struct vm_page_hash_elm *vm_page_hash;
134 __read_mostly static int vm_page_hash_size;
136 static u_long vm_dma_reserved = 0;
137 TUNABLE_ULONG("vm.dma_reserved", &vm_dma_reserved);
138 SYSCTL_ULONG(_vm, OID_AUTO, dma_reserved, CTLFLAG_RD, &vm_dma_reserved, 0,
139 "Memory reserved for DMA");
140 SYSCTL_UINT(_vm, OID_AUTO, dma_free_pages, CTLFLAG_RD,
141 &vm_contig_alist.bl_free, 0, "Memory reserved for DMA");
143 static int vm_contig_verbose = 0;
144 TUNABLE_INT("vm.contig_verbose", &vm_contig_verbose);
146 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
147 vm_pindex_t, pindex);
150 vm_page_queue_init(void)
154 for (i = 0; i < PQ_L2_SIZE; i++)
155 vm_page_queues[PQ_FREE+i].cnt_offset =
156 offsetof(struct vmstats, v_free_count);
157 for (i = 0; i < PQ_L2_SIZE; i++)
158 vm_page_queues[PQ_CACHE+i].cnt_offset =
159 offsetof(struct vmstats, v_cache_count);
160 for (i = 0; i < PQ_L2_SIZE; i++)
161 vm_page_queues[PQ_INACTIVE+i].cnt_offset =
162 offsetof(struct vmstats, v_inactive_count);
163 for (i = 0; i < PQ_L2_SIZE; i++)
164 vm_page_queues[PQ_ACTIVE+i].cnt_offset =
165 offsetof(struct vmstats, v_active_count);
166 for (i = 0; i < PQ_L2_SIZE; i++)
167 vm_page_queues[PQ_HOLD+i].cnt_offset =
168 offsetof(struct vmstats, v_active_count);
169 /* PQ_NONE has no queue */
171 for (i = 0; i < PQ_COUNT; i++) {
172 vm_page_queues[i].lastq = -1;
173 TAILQ_INIT(&vm_page_queues[i].pl);
174 spin_init(&vm_page_queues[i].spin, "vm_page_queue_init");
179 * note: place in initialized data section? Is this necessary?
181 vm_pindex_t first_page = 0;
182 vm_pindex_t vm_page_array_size = 0;
183 vm_page_t vm_page_array = NULL;
184 vm_paddr_t vm_low_phys_reserved;
189 * Sets the page size, perhaps based upon the memory size.
190 * Must be called before any use of page-size dependent functions.
193 vm_set_page_size(void)
195 if (vmstats.v_page_size == 0)
196 vmstats.v_page_size = PAGE_SIZE;
197 if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
198 panic("vm_set_page_size: page size not a power of two");
204 * Add a new page to the freelist for use by the system. New pages
205 * are added to both the head and tail of the associated free page
206 * queue in a bottom-up fashion, so both zero'd and non-zero'd page
207 * requests pull 'recent' adds (higher physical addresses) first.
209 * Beware that the page zeroing daemon will also be running soon after
210 * boot, moving pages from the head to the tail of the PQ_FREE queues.
212 * Must be called in a critical section.
215 vm_add_new_page(vm_paddr_t pa)
217 struct vpgqueues *vpq;
220 m = PHYS_TO_VM_PAGE(pa);
223 m->pat_mode = PAT_WRITE_BACK;
224 m->pc = (pa >> PAGE_SHIFT);
227 * Twist for cpu localization in addition to page coloring, so
228 * different cpus selecting by m->queue get different page colors.
230 m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE);
231 m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE));
235 * Reserve a certain number of contiguous low memory pages for
236 * contigmalloc() to use.
238 if (pa < vm_low_phys_reserved) {
239 atomic_add_long(&vmstats.v_page_count, 1);
240 atomic_add_long(&vmstats.v_dma_pages, 1);
243 atomic_add_long(&vmstats.v_wire_count, 1);
244 alist_free(&vm_contig_alist, pa >> PAGE_SHIFT, 1);
251 m->queue = m->pc + PQ_FREE;
252 KKASSERT(m->dirty == 0);
254 atomic_add_long(&vmstats.v_page_count, 1);
255 atomic_add_long(&vmstats.v_free_count, 1);
256 vpq = &vm_page_queues[m->queue];
257 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
264 * Initializes the resident memory module.
266 * Preallocates memory for critical VM structures and arrays prior to
267 * kernel_map becoming available.
269 * Memory is allocated from (virtual2_start, virtual2_end) if available,
270 * otherwise memory is allocated from (virtual_start, virtual_end).
272 * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
273 * large enough to hold vm_page_array & other structures for machines with
274 * large amounts of ram, so we want to use virtual2* when available.
277 vm_page_startup(void)
279 vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
282 vm_paddr_t page_range;
288 vm_paddr_t biggestone, biggestsize;
295 vaddr = round_page(vaddr);
298 * Make sure ranges are page-aligned.
300 for (i = 0; phys_avail[i].phys_end; ++i) {
301 phys_avail[i].phys_beg = round_page64(phys_avail[i].phys_beg);
302 phys_avail[i].phys_end = trunc_page64(phys_avail[i].phys_end);
303 if (phys_avail[i].phys_end < phys_avail[i].phys_beg)
304 phys_avail[i].phys_end = phys_avail[i].phys_beg;
308 * Locate largest block
310 for (i = 0; phys_avail[i].phys_end; ++i) {
311 vm_paddr_t size = phys_avail[i].phys_end -
312 phys_avail[i].phys_beg;
314 if (size > biggestsize) {
320 --i; /* adjust to last entry for use down below */
322 end = phys_avail[biggestone].phys_end;
323 end = trunc_page(end);
326 * Initialize the queue headers for the free queue, the active queue
327 * and the inactive queue.
329 vm_page_queue_init();
331 #if !defined(_KERNEL_VIRTUAL)
333 * VKERNELs don't support minidumps and as such don't need
336 * Allocate a bitmap to indicate that a random physical page
337 * needs to be included in a minidump.
339 * The amd64 port needs this to indicate which direct map pages
340 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
342 * However, x86 still needs this workspace internally within the
343 * minidump code. In theory, they are not needed on x86, but are
344 * included should the sf_buf code decide to use them.
346 page_range = phys_avail[i].phys_end / PAGE_SIZE;
347 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
348 end -= vm_page_dump_size;
349 vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
350 VM_PROT_READ | VM_PROT_WRITE);
351 bzero((void *)vm_page_dump, vm_page_dump_size);
354 * Compute the number of pages of memory that will be available for
355 * use (taking into account the overhead of a page structure per
358 first_page = phys_avail[0].phys_beg / PAGE_SIZE;
359 page_range = phys_avail[i].phys_end / PAGE_SIZE - first_page;
360 npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
362 #ifndef _KERNEL_VIRTUAL
364 * (only applies to real kernels)
366 * Reserve a large amount of low memory for potential 32-bit DMA
367 * space allocations. Once device initialization is complete we
368 * release most of it, but keep (vm_dma_reserved) memory reserved
369 * for later use. Typically for X / graphics. Through trial and
370 * error we find that GPUs usually requires ~60-100MB or so.
372 * By default, 128M is left in reserve on machines with 2G+ of ram.
374 vm_low_phys_reserved = (vm_paddr_t)65536 << PAGE_SHIFT;
375 if (vm_low_phys_reserved > total / 4)
376 vm_low_phys_reserved = total / 4;
377 if (vm_dma_reserved == 0) {
378 vm_dma_reserved = 128 * 1024 * 1024; /* 128MB */
379 if (vm_dma_reserved > total / 16)
380 vm_dma_reserved = total / 16;
383 alist_init(&vm_contig_alist, 65536, vm_contig_ameta,
384 ALIST_RECORDS_65536);
387 * Initialize the mem entry structures now, and put them in the free
390 if (bootverbose && ctob(physmem) >= 400LL*1024*1024*1024)
391 kprintf("initializing vm_page_array ");
392 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
393 mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE);
394 vm_page_array = (vm_page_t)mapped;
396 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
398 * since pmap_map on amd64 returns stuff out of a direct-map region,
399 * we have to manually add these pages to the minidump tracking so
400 * that they can be dumped, including the vm_page_array.
403 pa < phys_avail[biggestone].phys_end;
410 * Clear all of the page structures, run basic initialization so
411 * PHYS_TO_VM_PAGE() operates properly even on pages not in the
414 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
415 vm_page_array_size = page_range;
416 if (bootverbose && ctob(physmem) >= 400LL*1024*1024*1024)
417 kprintf("size = 0x%zx\n", vm_page_array_size);
419 m = &vm_page_array[0];
420 pa = ptoa(first_page);
421 for (i = 0; i < page_range; ++i) {
422 spin_init(&m->spin, "vm_page");
429 * Construct the free queue(s) in ascending order (by physical
430 * address) so that the first 16MB of physical memory is allocated
431 * last rather than first. On large-memory machines, this avoids
432 * the exhaustion of low physical memory before isa_dma_init has run.
434 vmstats.v_page_count = 0;
435 vmstats.v_free_count = 0;
436 for (i = 0; phys_avail[i].phys_end && npages > 0; ++i) {
437 pa = phys_avail[i].phys_beg;
441 last_pa = phys_avail[i].phys_end;
442 while (pa < last_pa && npages-- > 0) {
448 virtual2_start = vaddr;
450 virtual_start = vaddr;
451 mycpu->gd_vmstats = vmstats;
455 * (called from early boot only)
457 * Reorganize VM pages based on numa data. May be called as many times as
458 * necessary. Will reorganize the vm_page_t page color and related queue(s)
459 * to allow vm_page_alloc() to choose pages based on socket affinity.
461 * NOTE: This function is only called while we are still in UP mode, so
462 * we only need a critical section to protect the queues (which
463 * saves a lot of time, there are likely a ton of pages).
466 vm_numa_organize(vm_paddr_t ran_beg, vm_paddr_t bytes, int physid)
471 struct vpgqueues *vpq;
479 * Check if no physical information, or there was only one socket
480 * (so don't waste time doing nothing!).
482 if (cpu_topology_phys_ids <= 1 ||
483 cpu_topology_core_ids == 0) {
488 * Setup for our iteration. Note that ACPI may iterate CPU
489 * sockets starting at 0 or 1 or some other number. The
490 * cpu_topology code mod's it against the socket count.
492 ran_end = ran_beg + bytes;
494 socket_mod = PQ_L2_SIZE / cpu_topology_phys_ids;
495 socket_value = (physid % cpu_topology_phys_ids) * socket_mod;
496 mend = &vm_page_array[vm_page_array_size];
501 * Adjust cpu_topology's phys_mem parameter
504 vm_numa_add_topology_mem(root_cpu_node, physid, (long)bytes);
507 * Adjust vm_page->pc and requeue all affected pages. The
508 * allocator will then be able to localize memory allocations
511 for (i = 0; phys_avail[i].phys_end; ++i) {
512 scan_beg = phys_avail[i].phys_beg;
513 scan_end = phys_avail[i].phys_end;
514 if (scan_end <= ran_beg)
516 if (scan_beg >= ran_end)
518 if (scan_beg < ran_beg)
520 if (scan_end > ran_end)
522 if (atop(scan_end) > first_page + vm_page_array_size)
523 scan_end = ptoa(first_page + vm_page_array_size);
525 m = PHYS_TO_VM_PAGE(scan_beg);
526 while (scan_beg < scan_end) {
528 if (m->queue != PQ_NONE) {
529 vpq = &vm_page_queues[m->queue];
530 TAILQ_REMOVE(&vpq->pl, m, pageq);
532 /* queue doesn't change, no need to adj cnt */
535 m->pc += socket_value;
538 vpq = &vm_page_queues[m->queue];
539 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
541 /* queue doesn't change, no need to adj cnt */
544 m->pc += socket_value;
547 scan_beg += PAGE_SIZE;
556 * (called from early boot only)
558 * Don't allow the NUMA organization to leave vm_page_queues[] nodes
559 * completely empty for a logical cpu. Doing so would force allocations
560 * on that cpu to always borrow from a nearby cpu, create unnecessary
561 * contention, and cause vm_page_alloc() to iterate more queues and run more
564 * This situation can occur when memory sticks are not entirely populated,
565 * populated at different densities, or in naturally assymetric systems
566 * such as the 2990WX. There could very well be many vm_page_queues[]
567 * entries with *NO* pages assigned to them.
569 * Fixing this up ensures that each logical CPU has roughly the same
570 * sized memory pool, and more importantly ensures that logical CPUs
571 * do not wind up with an empty memory pool.
573 * At them moment we just iterate the other queues and borrow pages,
574 * moving them into the queues for cpus with severe deficits even though
575 * the memory might not be local to those cpus. I am not doing this in
576 * a 'smart' way, its effectively UMA style (sorta, since its page-by-page
577 * whereas real UMA typically exchanges address bits 8-10 with high address
578 * bits). But it works extremely well and gives us fairly good deterministic
579 * results on the cpu cores associated with these secondary nodes.
582 vm_numa_organize_finalize(void)
584 struct vpgqueues *vpq;
595 * Machines might not use an exact power of 2 for phys_ids,
596 * core_ids, ht_ids, etc. This can slightly reduce the actual
597 * range of indices in vm_page_queues[] that are nominally used.
599 if (cpu_topology_ht_ids) {
600 scale_lim = PQ_L2_SIZE / cpu_topology_phys_ids;
601 scale_lim = scale_lim / cpu_topology_core_ids;
602 scale_lim = scale_lim / cpu_topology_ht_ids;
603 scale_lim = scale_lim * cpu_topology_ht_ids;
604 scale_lim = scale_lim * cpu_topology_core_ids;
605 scale_lim = scale_lim * cpu_topology_phys_ids;
607 scale_lim = PQ_L2_SIZE;
611 * Calculate an average, set hysteresis for balancing from
612 * 10% below the average to the average.
615 for (i = 0; i < scale_lim; ++i) {
616 lcnt_hi += vm_page_queues[i].lcnt;
618 lcnt_hi /= scale_lim;
619 lcnt_lo = lcnt_hi - lcnt_hi / 10;
621 kprintf("vm_page: avg %ld pages per queue, %d queues\n",
625 for (i = 0; i < scale_lim; ++i) {
626 vpq = &vm_page_queues[PQ_FREE + i];
627 while (vpq->lcnt < lcnt_lo) {
628 struct vpgqueues *vptmp;
630 iter = (iter + 1) & PQ_L2_MASK;
631 vptmp = &vm_page_queues[PQ_FREE + iter];
632 if (vptmp->lcnt < lcnt_hi)
634 m = TAILQ_FIRST(&vptmp->pl);
635 KKASSERT(m->queue == PQ_FREE + iter);
636 TAILQ_REMOVE(&vptmp->pl, m, pageq);
638 /* queue doesn't change, no need to adj cnt */
642 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
651 vm_numa_add_topology_mem(cpu_node_t *cpup, int physid, long bytes)
658 cpup->phys_mem += bytes;
662 * All members should have the same chipid, so we only need
663 * to pull out one member.
665 if (CPUMASK_TESTNZERO(cpup->members)) {
666 cpuid = BSFCPUMASK(cpup->members);
668 get_chip_ID_from_APICID(CPUID_TO_APICID(cpuid))) {
669 cpup->phys_mem += bytes;
676 * Just inherit from the parent node
678 cpup->phys_mem = cpup->parent_node->phys_mem;
681 for (i = 0; i < MAXCPU && cpup->child_node[i]; ++i)
682 vm_numa_add_topology_mem(cpup->child_node[i], physid, bytes);
686 * We tended to reserve a ton of memory for contigmalloc(). Now that most
687 * drivers have initialized we want to return most the remaining free
688 * reserve back to the VM page queues so they can be used for normal
691 * We leave vm_dma_reserved bytes worth of free pages in the reserve pool.
694 vm_page_startup_finish(void *dummy __unused)
702 struct vm_page_hash_elm *mp;
706 * Set the set_assoc_mask based on the fitted number of CPUs.
707 * This is a mask, so we subject 1.
709 * w/PQ_L2_SIZE = 1024:
711 * Don't let the associativity drop below 8. So if we have
712 * 256 CPUs, two hyper-threads will wind up sharing. The
713 * maximum is PQ_L2_SIZE.
715 mask = PQ_L2_SIZE / ncpus_fit - 1;
716 if (mask < 7) /* minimum is 8-way w/256 CPU threads */
719 set_assoc_mask = mask;
722 * Return part of the initial reserve back to the system
724 spin_lock(&vm_contig_spin);
726 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
727 if (bfree <= vm_dma_reserved / PAGE_SIZE)
733 * Figure out how much of the initial reserve we have to
734 * free in order to reach our target.
736 bfree -= vm_dma_reserved / PAGE_SIZE;
738 blk += count - bfree;
743 * Calculate the nearest power of 2 <= count.
745 for (xcount = 1; xcount <= count; xcount <<= 1)
748 blk += count - xcount;
752 * Allocate the pages from the alist, then free them to
753 * the normal VM page queues.
755 * Pages allocated from the alist are wired. We have to
756 * busy, unwire, and free them. We must also adjust
757 * vm_low_phys_reserved before freeing any pages to prevent
760 rblk = alist_alloc(&vm_contig_alist, blk, count);
762 kprintf("vm_page_startup_finish: Unable to return "
763 "dma space @0x%08x/%d -> 0x%08x\n",
767 atomic_add_long(&vmstats.v_dma_pages, -(long)count);
768 spin_unlock(&vm_contig_spin);
770 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
771 vm_low_phys_reserved = VM_PAGE_TO_PHYS(m);
773 vm_page_busy_wait(m, FALSE, "cpgfr");
774 vm_page_unwire(m, 0);
779 spin_lock(&vm_contig_spin);
781 spin_unlock(&vm_contig_spin);
784 * Print out how much DMA space drivers have already allocated and
785 * how much is left over.
787 kprintf("DMA space used: %jdk, remaining available: %jdk\n",
788 (intmax_t)(vmstats.v_dma_pages - vm_contig_alist.bl_free) *
790 (intmax_t)vm_contig_alist.bl_free * (PAGE_SIZE / 1024));
795 vm_page_hash_size = 4096;
796 while (vm_page_hash_size < (vm_page_array_size / 16))
797 vm_page_hash_size <<= 1;
798 if (vm_page_hash_size > 1024*1024)
799 vm_page_hash_size = 1024*1024;
802 * hash table for vm_page_lookup_quick()
804 mp = (void *)kmem_alloc3(&kernel_map,
805 vm_page_hash_size * sizeof(*vm_page_hash),
806 VM_SUBSYS_VMPGHASH, KM_CPU(0));
807 bzero(mp, vm_page_hash_size * sizeof(*mp));
811 SYSINIT(vm_pgend, SI_SUB_PROC0_POST, SI_ORDER_ANY,
812 vm_page_startup_finish, NULL);
816 * Scan comparison function for Red-Black tree scans. An inclusive
817 * (start,end) is expected. Other fields are not used.
820 rb_vm_page_scancmp(struct vm_page *p, void *data)
822 struct rb_vm_page_scan_info *info = data;
824 if (p->pindex < info->start_pindex)
826 if (p->pindex > info->end_pindex)
832 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
834 if (p1->pindex < p2->pindex)
836 if (p1->pindex > p2->pindex)
842 vm_page_init(vm_page_t m)
844 /* do nothing for now. Called from pmap_page_init() */
848 * Each page queue has its own spin lock, which is fairly optimal for
849 * allocating and freeing pages at least.
851 * The caller must hold the vm_page_spin_lock() before locking a vm_page's
852 * queue spinlock via this function. Also note that m->queue cannot change
853 * unless both the page and queue are locked.
857 _vm_page_queue_spin_lock(vm_page_t m)
862 if (queue != PQ_NONE) {
863 spin_lock(&vm_page_queues[queue].spin);
864 KKASSERT(queue == m->queue);
870 _vm_page_queue_spin_unlock(vm_page_t m)
876 if (queue != PQ_NONE)
877 spin_unlock(&vm_page_queues[queue].spin);
882 _vm_page_queues_spin_lock(u_short queue)
885 if (queue != PQ_NONE)
886 spin_lock(&vm_page_queues[queue].spin);
892 _vm_page_queues_spin_unlock(u_short queue)
895 if (queue != PQ_NONE)
896 spin_unlock(&vm_page_queues[queue].spin);
900 vm_page_queue_spin_lock(vm_page_t m)
902 _vm_page_queue_spin_lock(m);
906 vm_page_queues_spin_lock(u_short queue)
908 _vm_page_queues_spin_lock(queue);
912 vm_page_queue_spin_unlock(vm_page_t m)
914 _vm_page_queue_spin_unlock(m);
918 vm_page_queues_spin_unlock(u_short queue)
920 _vm_page_queues_spin_unlock(queue);
924 * This locks the specified vm_page and its queue in the proper order
925 * (page first, then queue). The queue may change so the caller must
930 _vm_page_and_queue_spin_lock(vm_page_t m)
932 vm_page_spin_lock(m);
933 _vm_page_queue_spin_lock(m);
938 _vm_page_and_queue_spin_unlock(vm_page_t m)
940 _vm_page_queues_spin_unlock(m->queue);
941 vm_page_spin_unlock(m);
945 vm_page_and_queue_spin_unlock(vm_page_t m)
947 _vm_page_and_queue_spin_unlock(m);
951 vm_page_and_queue_spin_lock(vm_page_t m)
953 _vm_page_and_queue_spin_lock(m);
957 * Helper function removes vm_page from its current queue.
958 * Returns the base queue the page used to be on.
960 * The vm_page and the queue must be spinlocked.
961 * This function will unlock the queue but leave the page spinlocked.
963 static __inline u_short
964 _vm_page_rem_queue_spinlocked(vm_page_t m)
966 struct vpgqueues *pq;
972 if (queue != PQ_NONE) {
973 pq = &vm_page_queues[queue];
974 TAILQ_REMOVE(&pq->pl, m, pageq);
977 * Adjust our pcpu stats. In order for the nominal low-memory
978 * algorithms to work properly we don't let any pcpu stat get
979 * too negative before we force it to be rolled-up into the
980 * global stats. Otherwise our pageout and vm_wait tests
983 * The idea here is to reduce unnecessary SMP cache
984 * mastership changes in the global vmstats, which can be
985 * particularly bad in multi-socket systems.
987 cnt = (long *)((char *)&mycpu->gd_vmstats_adj + pq->cnt_offset);
988 atomic_add_long(cnt, -1);
989 if (*cnt < -VMMETER_SLOP_COUNT) {
990 u_long copy = atomic_swap_long(cnt, 0);
991 cnt = (long *)((char *)&vmstats + pq->cnt_offset);
992 atomic_add_long(cnt, copy);
993 cnt = (long *)((char *)&mycpu->gd_vmstats +
995 atomic_add_long(cnt, copy);
1001 vm_page_queues_spin_unlock(oqueue); /* intended */
1007 * Helper function places the vm_page on the specified queue. Generally
1008 * speaking only PQ_FREE pages are placed at the head, to allow them to
1009 * be allocated sooner rather than later on the assumption that they
1012 * The vm_page must be spinlocked.
1013 * The vm_page must NOT be FICTITIOUS (that would be a disaster)
1014 * This function will return with both the page and the queue locked.
1016 static __inline void
1017 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
1019 struct vpgqueues *pq;
1022 KKASSERT(m->queue == PQ_NONE && (m->flags & PG_FICTITIOUS) == 0);
1024 if (queue != PQ_NONE) {
1025 vm_page_queues_spin_lock(queue);
1026 pq = &vm_page_queues[queue];
1030 * Adjust our pcpu stats. If a system entity really needs
1031 * to incorporate the count it will call vmstats_rollup()
1032 * to roll it all up into the global vmstats strufture.
1034 cnt = (long *)((char *)&mycpu->gd_vmstats_adj + pq->cnt_offset);
1035 atomic_add_long(cnt, 1);
1038 * PQ_FREE is always handled LIFO style to try to provide
1039 * cache-hot pages to programs.
1042 if (queue - m->pc == PQ_FREE) {
1043 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1044 } else if (athead) {
1045 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
1047 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
1049 /* leave the queue spinlocked */
1054 * Wait until page is no longer BUSY. If also_m_busy is TRUE we wait
1055 * until the page is no longer BUSY or SBUSY (busy_count field is 0).
1057 * Returns TRUE if it had to sleep, FALSE if we did not. Only one sleep
1058 * call will be made before returning.
1060 * This function does NOT busy the page and on return the page is not
1061 * guaranteed to be available.
1064 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
1066 u_int32_t busy_count;
1069 busy_count = m->busy_count;
1072 if ((busy_count & PBUSY_LOCKED) == 0 &&
1073 (also_m_busy == 0 || (busy_count & PBUSY_MASK) == 0)) {
1076 tsleep_interlock(m, 0);
1077 if (atomic_cmpset_int(&m->busy_count, busy_count,
1078 busy_count | PBUSY_WANTED)) {
1079 atomic_set_int(&m->flags, PG_REFERENCED);
1080 tsleep(m, PINTERLOCKED, msg, 0);
1087 * This calculates and returns a page color given an optional VM object and
1088 * either a pindex or an iterator. We attempt to return a cpu-localized
1089 * pg_color that is still roughly 16-way set-associative. The CPU topology
1090 * is used if it was probed.
1092 * The caller may use the returned value to index into e.g. PQ_FREE when
1093 * allocating a page in order to nominally obtain pages that are hopefully
1094 * already localized to the requesting cpu. This function is not able to
1095 * provide any sort of guarantee of this, but does its best to improve
1096 * hardware cache management performance.
1098 * WARNING! The caller must mask the returned value with PQ_L2_MASK.
1101 vm_get_pg_color(int cpuid, vm_object_t object, vm_pindex_t pindex)
1104 int object_pg_color;
1107 * WARNING! cpu_topology_core_ids might not be a power of two.
1108 * We also shouldn't make assumptions about
1109 * cpu_topology_phys_ids either.
1111 * WARNING! ncpus might not be known at this time (during early
1112 * boot), and might be set to 1.
1114 * General format: [phys_id][core_id][cpuid][set-associativity]
1115 * (but uses modulo, so not necessarily precise bit masks)
1117 object_pg_color = object ? object->pg_color : 0;
1119 if (cpu_topology_ht_ids) {
1128 * Translate cpuid to socket, core, and hyperthread id.
1130 phys_id = get_cpu_phys_id(cpuid);
1131 core_id = get_cpu_core_id(cpuid);
1132 ht_id = get_cpu_ht_id(cpuid);
1135 * Calculate pg_color for our array index.
1137 * physcale - socket multiplier.
1138 * grpscale - core multiplier (cores per socket)
1139 * cpu* - cpus per core
1141 * WARNING! In early boot, ncpus has not yet been
1142 * initialized and may be set to (1).
1144 * WARNING! physcale must match the organization that
1145 * vm_numa_organize() creates to ensure that
1146 * we properly localize allocations to the
1149 physcale = PQ_L2_SIZE / cpu_topology_phys_ids;
1150 grpscale = physcale / cpu_topology_core_ids;
1151 cpuscale = grpscale / cpu_topology_ht_ids;
1153 pg_color = phys_id * physcale;
1154 pg_color += core_id * grpscale;
1155 pg_color += ht_id * cpuscale;
1156 pg_color += (pindex + object_pg_color) % cpuscale;
1160 pg_color += (pindex + object_pg_color) % grpsize;
1165 /* 3->9, 4->8, 5->10, 6->12, 7->14 */
1170 pg_color += (pindex + object_pg_color) % grpsize;
1175 * Unknown topology, distribute things evenly.
1177 * WARNING! In early boot, ncpus has not yet been
1178 * initialized and may be set to (1).
1182 cpuscale = PQ_L2_SIZE / ncpus;
1184 pg_color = cpuid * cpuscale;
1185 pg_color += (pindex + object_pg_color) % cpuscale;
1187 return (pg_color & PQ_L2_MASK);
1191 * Wait until BUSY can be set, then set it. If also_m_busy is TRUE we
1192 * also wait for m->busy_count to become 0 before setting PBUSY_LOCKED.
1195 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
1196 int also_m_busy, const char *msg
1199 u_int32_t busy_count;
1202 busy_count = m->busy_count;
1204 if (busy_count & PBUSY_LOCKED) {
1205 tsleep_interlock(m, 0);
1206 if (atomic_cmpset_int(&m->busy_count, busy_count,
1207 busy_count | PBUSY_WANTED)) {
1208 atomic_set_int(&m->flags, PG_REFERENCED);
1209 tsleep(m, PINTERLOCKED, msg, 0);
1211 } else if (also_m_busy && busy_count) {
1212 tsleep_interlock(m, 0);
1213 if (atomic_cmpset_int(&m->busy_count, busy_count,
1214 busy_count | PBUSY_WANTED)) {
1215 atomic_set_int(&m->flags, PG_REFERENCED);
1216 tsleep(m, PINTERLOCKED, msg, 0);
1219 if (atomic_cmpset_int(&m->busy_count, busy_count,
1220 busy_count | PBUSY_LOCKED)) {
1221 #ifdef VM_PAGE_DEBUG
1222 m->busy_func = func;
1223 m->busy_line = lineno;
1232 * Attempt to set BUSY. If also_m_busy is TRUE we only succeed if
1233 * m->busy_count is also 0.
1235 * Returns non-zero on failure.
1238 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
1241 u_int32_t busy_count;
1244 busy_count = m->busy_count;
1246 if (busy_count & PBUSY_LOCKED)
1248 if (also_m_busy && (busy_count & PBUSY_MASK) != 0)
1250 if (atomic_cmpset_int(&m->busy_count, busy_count,
1251 busy_count | PBUSY_LOCKED)) {
1252 #ifdef VM_PAGE_DEBUG
1253 m->busy_func = func;
1254 m->busy_line = lineno;
1262 * Clear the BUSY flag and return non-zero to indicate to the caller
1263 * that a wakeup() should be performed.
1269 _vm_page_wakeup(vm_page_t m)
1271 u_int32_t busy_count;
1273 busy_count = m->busy_count;
1276 if (atomic_fcmpset_int(&m->busy_count, &busy_count,
1278 ~(PBUSY_LOCKED | PBUSY_WANTED))) {
1279 return((int)(busy_count & PBUSY_WANTED));
1286 * Clear the BUSY flag and wakeup anyone waiting for the page. This
1287 * is typically the last call you make on a page before moving onto
1291 vm_page_wakeup(vm_page_t m)
1293 KASSERT(m->busy_count & PBUSY_LOCKED,
1294 ("vm_page_wakeup: page not busy!!!"));
1295 if (_vm_page_wakeup(m))
1300 * Hold a page, preventing reuse. This is typically only called on pages
1301 * in a known state (either held busy, special, or interlocked in some
1302 * manner). Holding a page does not ensure that it remains valid, it only
1303 * prevents reuse. The page must not already be on the FREE queue or in
1304 * any danger of being moved to the FREE queue concurrent with this call.
1306 * Other parts of the system can still disassociate the page from its object
1307 * and attempt to free it, or perform read or write I/O on it and/or otherwise
1308 * manipulate the page, but if the page is held the VM system will leave the
1309 * page and its data intact and not cycle it through the FREE queue until
1310 * the last hold has been released.
1312 * (see vm_page_wire() if you want to prevent the page from being
1313 * disassociated from its object too).
1316 vm_page_hold(vm_page_t m)
1318 atomic_add_int(&m->hold_count, 1);
1319 KKASSERT(m->queue - m->pc != PQ_FREE);
1323 * The opposite of vm_page_hold(). If the page is on the HOLD queue
1324 * it was freed while held and must be moved back to the FREE queue.
1326 * To avoid racing against vm_page_free*() we must re-test conditions
1327 * after obtaining the spin-lock. The initial test can also race a
1328 * vm_page_free*() that is in the middle of moving a page to PQ_HOLD,
1329 * leaving the page on PQ_HOLD with hold_count == 0. Rather than
1330 * throw a spin-lock in the critical path, we rely on the pageout
1331 * daemon to clean-up these loose ends.
1333 * More critically, the 'easy movement' between queues without busying
1334 * a vm_page is only allowed for PQ_FREE<->PQ_HOLD.
1337 vm_page_unhold(vm_page_t m)
1339 KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1340 ("vm_page_unhold: pg %p illegal hold_count (%d) or "
1341 "on FREE queue (%d)",
1342 m, m->hold_count, m->queue - m->pc));
1344 if (atomic_fetchadd_int(&m->hold_count, -1) == 1 &&
1345 m->queue - m->pc == PQ_HOLD) {
1346 vm_page_spin_lock(m);
1347 if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1348 _vm_page_queue_spin_lock(m);
1349 _vm_page_rem_queue_spinlocked(m);
1350 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
1351 _vm_page_queue_spin_unlock(m);
1353 vm_page_spin_unlock(m);
1358 * Create a fictitious page with the specified physical address and
1359 * memory attribute. The memory attribute is the only the machine-
1360 * dependent aspect of a fictitious page that must be initialized.
1363 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1365 if ((m->flags & PG_FICTITIOUS) != 0) {
1367 * The page's memattr might have changed since the
1368 * previous initialization. Update the pmap to the
1373 m->phys_addr = paddr;
1375 /* Fictitious pages don't use "segind". */
1376 /* Fictitious pages don't use "order" or "pool". */
1377 m->flags = PG_FICTITIOUS | PG_UNMANAGED;
1378 m->busy_count = PBUSY_LOCKED;
1380 spin_init(&m->spin, "fake_page");
1383 pmap_page_set_memattr(m, memattr);
1387 * Inserts the given vm_page into the object and object list.
1389 * The pagetables are not updated but will presumably fault the page
1390 * in if necessary, or if a kernel page the caller will at some point
1391 * enter the page into the kernel's pmap. We are not allowed to block
1392 * here so we *can't* do this anyway.
1394 * This routine may not block.
1395 * This routine must be called with the vm_object held.
1396 * This routine must be called with a critical section held.
1398 * This routine returns TRUE if the page was inserted into the object
1399 * successfully, and FALSE if the page already exists in the object.
1402 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1404 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1405 if (m->object != NULL)
1406 panic("vm_page_insert: already inserted");
1408 atomic_add_int(&object->generation, 1);
1411 * Associate the VM page with an (object, offset).
1413 * The vm_page spin lock is required for interactions with the pmap.
1415 vm_page_spin_lock(m);
1418 if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1421 vm_page_spin_unlock(m);
1424 ++object->resident_page_count;
1425 ++mycpu->gd_vmtotal.t_rm;
1426 vm_page_spin_unlock(m);
1429 * Since we are inserting a new and possibly dirty page,
1430 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1432 if ((m->valid & m->dirty) ||
1433 (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1434 vm_object_set_writeable_dirty(object);
1437 * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1439 swap_pager_page_inserted(m);
1444 * Removes the given vm_page_t from the (object,index) table
1446 * The page must be BUSY and will remain BUSY on return.
1447 * No other requirements.
1449 * NOTE: FreeBSD side effect was to unbusy the page on return. We leave
1452 * NOTE: Caller is responsible for any pmap disposition prior to the
1453 * rename (as the pmap code will not be able to find the entries
1454 * once the object has been disassociated). The caller may choose
1455 * to leave the pmap association intact if this routine is being
1456 * called as part of a rename between shadowed objects.
1458 * This routine may not block.
1461 vm_page_remove(vm_page_t m)
1465 if (m->object == NULL) {
1469 if ((m->busy_count & PBUSY_LOCKED) == 0)
1470 panic("vm_page_remove: page not busy");
1474 vm_object_hold(object);
1477 * Remove the page from the object and update the object.
1479 * The vm_page spin lock is required for interactions with the pmap.
1481 vm_page_spin_lock(m);
1482 vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1483 --object->resident_page_count;
1484 --mycpu->gd_vmtotal.t_rm;
1486 atomic_add_int(&object->generation, 1);
1487 vm_page_spin_unlock(m);
1489 vm_object_drop(object);
1493 * Calculate the hash position for the vm_page hash heuristic.
1495 * Mask by ~3 to offer 4-way set-assoc
1498 struct vm_page_hash_elm *
1499 vm_page_hash_hash(vm_object_t object, vm_pindex_t pindex)
1503 hi = ((object->pg_color << 8) ^ (uintptr_t)object) + (pindex << 2);
1504 hi &= vm_page_hash_size - 1;
1506 return (&vm_page_hash[hi]);
1510 * Heuristical page lookup that does not require any locks. Returns
1511 * a soft-busied page on success, NULL on failure.
1513 * Caller must lookup the page the slow way if NULL is returned.
1516 vm_page_hash_get(vm_object_t object, vm_pindex_t pindex)
1518 struct vm_page_hash_elm *mp;
1522 if (vm_page_hash == NULL)
1524 mp = vm_page_hash_hash(object, pindex);
1525 for (i = 0; i < 4; ++i) {
1530 if (m->object != object || m->pindex != pindex)
1532 if (vm_page_sbusy_try(m))
1534 if (m->object == object && m->pindex == pindex) {
1535 mp[i].ticks = ticks;
1538 vm_page_sbusy_drop(m);
1544 * Enter page onto vm_page_hash[]. This is a heuristic, SMP collisions
1549 vm_page_hash_enter(vm_page_t m)
1551 struct vm_page_hash_elm *mp;
1552 struct vm_page_hash_elm *best;
1556 m > &vm_page_array[0] &&
1557 m < &vm_page_array[vm_page_array_size]) {
1558 mp = vm_page_hash_hash(m->object, m->pindex);
1560 for (i = 0; i < 4; ++i) {
1562 mp[i].ticks = ticks;
1567 * The best choice is the oldest entry
1569 if ((ticks - best->ticks) < (ticks - mp[i].ticks) ||
1570 (int)(ticks - mp[i].ticks) < 0) {
1575 best->ticks = ticks;
1580 * Locate and return the page at (object, pindex), or NULL if the
1581 * page could not be found.
1583 * The caller must hold the vm_object token.
1586 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1591 * Search the hash table for this object/offset pair
1593 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1594 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1596 KKASSERT(m->object == object && m->pindex == pindex);
1597 vm_page_hash_enter(m);
1603 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1605 int also_m_busy, const char *msg
1608 u_int32_t busy_count;
1611 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1612 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1614 KKASSERT(m->object == object && m->pindex == pindex);
1615 busy_count = m->busy_count;
1617 if (busy_count & PBUSY_LOCKED) {
1618 tsleep_interlock(m, 0);
1619 if (atomic_cmpset_int(&m->busy_count, busy_count,
1620 busy_count | PBUSY_WANTED)) {
1621 atomic_set_int(&m->flags, PG_REFERENCED);
1622 tsleep(m, PINTERLOCKED, msg, 0);
1623 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1626 } else if (also_m_busy && busy_count) {
1627 tsleep_interlock(m, 0);
1628 if (atomic_cmpset_int(&m->busy_count, busy_count,
1629 busy_count | PBUSY_WANTED)) {
1630 atomic_set_int(&m->flags, PG_REFERENCED);
1631 tsleep(m, PINTERLOCKED, msg, 0);
1632 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1635 } else if (atomic_cmpset_int(&m->busy_count, busy_count,
1636 busy_count | PBUSY_LOCKED)) {
1637 #ifdef VM_PAGE_DEBUG
1638 m->busy_func = func;
1639 m->busy_line = lineno;
1641 vm_page_hash_enter(m);
1649 * Attempt to lookup and busy a page.
1651 * Returns NULL if the page could not be found
1653 * Returns a vm_page and error == TRUE if the page exists but could not
1656 * Returns a vm_page and error == FALSE on success.
1659 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1661 int also_m_busy, int *errorp
1664 u_int32_t busy_count;
1667 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1668 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1671 KKASSERT(m->object == object && m->pindex == pindex);
1672 busy_count = m->busy_count;
1674 if (busy_count & PBUSY_LOCKED) {
1678 if (also_m_busy && busy_count) {
1682 if (atomic_cmpset_int(&m->busy_count, busy_count,
1683 busy_count | PBUSY_LOCKED)) {
1684 #ifdef VM_PAGE_DEBUG
1685 m->busy_func = func;
1686 m->busy_line = lineno;
1688 vm_page_hash_enter(m);
1696 * Returns a page that is only soft-busied for use by the caller in
1697 * a read-only fashion. Returns NULL if the page could not be found,
1698 * the soft busy could not be obtained, or the page data is invalid.
1701 vm_page_lookup_sbusy_try(struct vm_object *object, vm_pindex_t pindex,
1702 int pgoff, int pgbytes)
1706 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1707 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1709 if ((m->valid != VM_PAGE_BITS_ALL &&
1710 !vm_page_is_valid(m, pgoff, pgbytes)) ||
1711 (m->flags & PG_FICTITIOUS)) {
1713 } else if (vm_page_sbusy_try(m)) {
1715 } else if ((m->valid != VM_PAGE_BITS_ALL &&
1716 !vm_page_is_valid(m, pgoff, pgbytes)) ||
1717 (m->flags & PG_FICTITIOUS)) {
1718 vm_page_sbusy_drop(m);
1721 vm_page_hash_enter(m);
1728 * Caller must hold the related vm_object
1731 vm_page_next(vm_page_t m)
1735 next = vm_page_rb_tree_RB_NEXT(m);
1736 if (next && next->pindex != m->pindex + 1)
1744 * Move the given vm_page from its current object to the specified
1745 * target object/offset. The page must be busy and will remain so
1748 * new_object must be held.
1749 * This routine might block. XXX ?
1751 * NOTE: Swap associated with the page must be invalidated by the move. We
1752 * have to do this for several reasons: (1) we aren't freeing the
1753 * page, (2) we are dirtying the page, (3) the VM system is probably
1754 * moving the page from object A to B, and will then later move
1755 * the backing store from A to B and we can't have a conflict.
1757 * NOTE: We *always* dirty the page. It is necessary both for the
1758 * fact that we moved it, and because we may be invalidating
1759 * swap. If the page is on the cache, we have to deactivate it
1760 * or vm_page_dirty() will panic. Dirty pages are not allowed
1763 * NOTE: Caller is responsible for any pmap disposition prior to the
1764 * rename (as the pmap code will not be able to find the entries
1765 * once the object has been disassociated or changed). Nominally
1766 * the caller is moving a page between shadowed objects and so the
1767 * pmap association is retained without having to remove the page
1771 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1773 KKASSERT(m->busy_count & PBUSY_LOCKED);
1774 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1776 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1779 if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1780 panic("vm_page_rename: target exists (%p,%"PRIu64")",
1781 new_object, new_pindex);
1783 if (m->queue - m->pc == PQ_CACHE)
1784 vm_page_deactivate(m);
1789 * vm_page_unqueue() without any wakeup. This routine is used when a page
1790 * is to remain BUSYied by the caller.
1792 * This routine may not block.
1795 vm_page_unqueue_nowakeup(vm_page_t m)
1797 vm_page_and_queue_spin_lock(m);
1798 (void)_vm_page_rem_queue_spinlocked(m);
1799 vm_page_spin_unlock(m);
1803 * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1806 * This routine may not block.
1809 vm_page_unqueue(vm_page_t m)
1813 vm_page_and_queue_spin_lock(m);
1814 queue = _vm_page_rem_queue_spinlocked(m);
1815 if (queue == PQ_FREE || queue == PQ_CACHE) {
1816 vm_page_spin_unlock(m);
1817 pagedaemon_wakeup();
1819 vm_page_spin_unlock(m);
1824 * vm_page_list_find()
1826 * Find a page on the specified queue with color optimization.
1828 * The page coloring optimization attempts to locate a page that does
1829 * not overload other nearby pages in the object in the cpu's L1 or L2
1830 * caches. We need this optimization because cpu caches tend to be
1831 * physical caches, while object spaces tend to be virtual.
1833 * The page coloring optimization also, very importantly, tries to localize
1834 * memory to cpus and physical sockets.
1836 * Each PQ_FREE and PQ_CACHE color queue has its own spinlock and the
1837 * algorithm is adjusted to localize allocations on a per-core basis.
1838 * This is done by 'twisting' the colors.
1840 * The page is returned spinlocked and removed from its queue (it will
1841 * be on PQ_NONE), or NULL. The page is not BUSY'd. The caller
1842 * is responsible for dealing with the busy-page case (usually by
1843 * deactivating the page and looping).
1845 * NOTE: This routine is carefully inlined. A non-inlined version
1846 * is available for outside callers but the only critical path is
1847 * from within this source file.
1849 * NOTE: This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1850 * represent stable storage, allowing us to order our locks vm_page
1851 * first, then queue.
1855 _vm_page_list_find(int basequeue, int index)
1857 struct vpgqueues *pq;
1860 index &= PQ_L2_MASK;
1861 pq = &vm_page_queues[basequeue + index];
1864 * Try this cpu's colored queue first. Test for a page unlocked,
1865 * then lock the queue and locate a page. Note that the lock order
1866 * is reversed, but we do not want to dwadle on the page spinlock
1867 * anyway as it is held significantly longer than the queue spinlock.
1869 if (TAILQ_FIRST(&pq->pl)) {
1870 spin_lock(&pq->spin);
1871 TAILQ_FOREACH(m, &pq->pl, pageq) {
1872 if (spin_trylock(&m->spin) == 0)
1874 KKASSERT(m->queue == basequeue + index);
1875 _vm_page_rem_queue_spinlocked(m);
1879 spin_unlock(&pq->spin);
1883 * If we are unable to get a page, do a more involved NUMA-aware
1884 * search. However, to avoid re-searching empty queues over and
1885 * over again skip to pq->last if appropriate.
1890 m = _vm_page_list_find2(basequeue, index, &pq->lastq);
1896 * If we could not find the page in the desired queue try to find it in
1897 * a nearby (NUMA-aware) queue.
1900 _vm_page_list_find2(int basequeue, int index, int *lastp)
1902 struct vpgqueues *pq;
1904 int pqmask = set_assoc_mask >> 1;
1909 index &= PQ_L2_MASK;
1910 pq = &vm_page_queues[basequeue];
1913 * Run local sets of 16, 32, 64, 128, up to the entire queue if all
1914 * else fails (PQ_L2_MASK).
1916 * pqmask is a mask, 15, 31, 63, etc.
1918 * Test each queue unlocked first, then lock the queue and locate
1919 * a page. Note that the lock order is reversed, but we do not want
1920 * to dwadle on the page spinlock anyway as it is held significantly
1921 * longer than the queue spinlock.
1924 pqmask = (pqmask << 1) | 1;
1925 for (i = pqstart; i <= pqmask; ++i) {
1926 pqi = (index & ~pqmask) | ((index + i) & pqmask);
1927 if (TAILQ_FIRST(&pq[pqi].pl)) {
1928 spin_lock(&pq[pqi].spin);
1929 TAILQ_FOREACH(m, &pq[pqi].pl, pageq) {
1930 if (spin_trylock(&m->spin) == 0)
1932 KKASSERT(m->queue == basequeue + pqi);
1933 _vm_page_rem_queue_spinlocked(m);
1936 * If we had to wander too far, set
1937 * *lastp to skip past empty queues.
1940 *lastp = pqi & PQ_L2_MASK;
1943 spin_unlock(&pq[pqi].spin);
1947 } while (pqmask != PQ_L2_MASK);
1953 * Returns a vm_page candidate for allocation. The page is not busied so
1954 * it can move around. The caller must busy the page (and typically
1955 * deactivate it if it cannot be busied!)
1957 * Returns a spinlocked vm_page that has been removed from its queue.
1960 vm_page_list_find(int basequeue, int index)
1962 return(_vm_page_list_find(basequeue, index));
1966 * Find a page on the cache queue with color optimization, remove it
1967 * from the queue, and busy it. The returned page will not be spinlocked.
1969 * A candidate failure will be deactivated. Candidates can fail due to
1970 * being busied by someone else, in which case they will be deactivated.
1972 * This routine may not block.
1976 vm_page_select_cache(u_short pg_color)
1981 m = _vm_page_list_find(PQ_CACHE, pg_color);
1985 * (m) has been removed from its queue and spinlocked
1987 if (vm_page_busy_try(m, TRUE)) {
1988 _vm_page_deactivate_locked(m, 0);
1989 vm_page_spin_unlock(m);
1992 * We successfully busied the page
1994 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) == 0 &&
1995 m->hold_count == 0 &&
1996 m->wire_count == 0 &&
1997 (m->dirty & m->valid) == 0) {
1998 vm_page_spin_unlock(m);
1999 pagedaemon_wakeup();
2004 * The page cannot be recycled, deactivate it.
2006 _vm_page_deactivate_locked(m, 0);
2007 if (_vm_page_wakeup(m)) {
2008 vm_page_spin_unlock(m);
2011 vm_page_spin_unlock(m);
2019 * Find a free page. We attempt to inline the nominal case and fall back
2020 * to _vm_page_select_free() otherwise. A busied page is removed from
2021 * the queue and returned.
2023 * This routine may not block.
2025 static __inline vm_page_t
2026 vm_page_select_free(u_short pg_color)
2031 m = _vm_page_list_find(PQ_FREE, pg_color);
2034 if (vm_page_busy_try(m, TRUE)) {
2036 * Various mechanisms such as a pmap_collect can
2037 * result in a busy page on the free queue. We
2038 * have to move the page out of the way so we can
2039 * retry the allocation. If the other thread is not
2040 * allocating the page then m->valid will remain 0 and
2041 * the pageout daemon will free the page later on.
2043 * Since we could not busy the page, however, we
2044 * cannot make assumptions as to whether the page
2045 * will be allocated by the other thread or not,
2046 * so all we can do is deactivate it to move it out
2047 * of the way. In particular, if the other thread
2048 * wires the page it may wind up on the inactive
2049 * queue and the pageout daemon will have to deal
2050 * with that case too.
2052 _vm_page_deactivate_locked(m, 0);
2053 vm_page_spin_unlock(m);
2056 * Theoretically if we are able to busy the page
2057 * atomic with the queue removal (using the vm_page
2058 * lock) nobody else should have been able to mess
2059 * with the page before us.
2061 * Assert the page state. Note that even though
2062 * wiring doesn't adjust queues, a page on the free
2063 * queue should never be wired at this point.
2065 KKASSERT((m->flags & (PG_UNMANAGED |
2066 PG_NEED_COMMIT)) == 0);
2067 KASSERT(m->hold_count == 0,
2068 ("m->hold_count is not zero "
2069 "pg %p q=%d flags=%08x hold=%d wire=%d",
2070 m, m->queue, m->flags,
2071 m->hold_count, m->wire_count));
2072 KKASSERT(m->wire_count == 0);
2073 vm_page_spin_unlock(m);
2074 pagedaemon_wakeup();
2076 /* return busied and removed page */
2086 * Allocate and return a memory cell associated with this VM object/offset
2087 * pair. If object is NULL an unassociated page will be allocated.
2089 * The returned page will be busied and removed from its queues. This
2090 * routine can block and may return NULL if a race occurs and the page
2091 * is found to already exist at the specified (object, pindex).
2093 * VM_ALLOC_NORMAL allow use of cache pages, nominal free drain
2094 * VM_ALLOC_QUICK like normal but cannot use cache
2095 * VM_ALLOC_SYSTEM greater free drain
2096 * VM_ALLOC_INTERRUPT allow free list to be completely drained
2097 * VM_ALLOC_ZERO advisory request for pre-zero'd page only
2098 * VM_ALLOC_FORCE_ZERO advisory request for pre-zero'd page only
2099 * VM_ALLOC_NULL_OK ok to return NULL on insertion collision
2100 * (see vm_page_grab())
2101 * VM_ALLOC_USE_GD ok to use per-gd cache
2103 * VM_ALLOC_CPU(n) allocate using specified cpu localization
2105 * The object must be held if not NULL
2106 * This routine may not block
2108 * Additional special handling is required when called from an interrupt
2109 * (VM_ALLOC_INTERRUPT). We are not allowed to mess with the page cache
2113 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
2123 * Special per-cpu free VM page cache. The pages are pre-busied
2124 * and pre-zerod for us.
2126 if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
2128 if (gd->gd_vmpg_count) {
2129 m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
2141 * CPU localization algorithm. Break the page queues up by physical
2142 * id and core id (note that two cpu threads will have the same core
2143 * id, and core_id != gd_cpuid).
2145 * This is nowhere near perfect, for example the last pindex in a
2146 * subgroup will overflow into the next cpu or package. But this
2147 * should get us good page reuse locality in heavy mixed loads.
2149 * (may be executed before the APs are started, so other GDs might
2152 if (page_req & VM_ALLOC_CPU_SPEC)
2153 cpuid_local = VM_ALLOC_GETCPU(page_req);
2155 cpuid_local = mycpu->gd_cpuid;
2157 pg_color = vm_get_pg_color(cpuid_local, object, pindex);
2160 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
2161 VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2164 * Certain system threads (pageout daemon, buf_daemon's) are
2165 * allowed to eat deeper into the free page list.
2167 if (curthread->td_flags & TDF_SYSTHREAD)
2168 page_req |= VM_ALLOC_SYSTEM;
2171 * Impose various limitations. Note that the v_free_reserved test
2172 * must match the opposite of vm_page_count_target() to avoid
2173 * livelocks, be careful.
2177 if (gd->gd_vmstats.v_free_count >= gd->gd_vmstats.v_free_reserved ||
2178 ((page_req & VM_ALLOC_INTERRUPT) &&
2179 gd->gd_vmstats.v_free_count > 0) ||
2180 ((page_req & VM_ALLOC_SYSTEM) &&
2181 gd->gd_vmstats.v_cache_count == 0 &&
2182 gd->gd_vmstats.v_free_count >
2183 gd->gd_vmstats.v_interrupt_free_min)
2186 * The free queue has sufficient free pages to take one out.
2188 m = vm_page_select_free(pg_color);
2189 } else if (page_req & VM_ALLOC_NORMAL) {
2191 * Allocatable from the cache (non-interrupt only). On
2192 * success, we must free the page and try again, thus
2193 * ensuring that vmstats.v_*_free_min counters are replenished.
2196 if (curthread->td_preempted) {
2197 kprintf("vm_page_alloc(): warning, attempt to allocate"
2198 " cache page from preempting interrupt\n");
2201 m = vm_page_select_cache(pg_color);
2204 m = vm_page_select_cache(pg_color);
2207 * On success move the page into the free queue and loop.
2209 * Only do this if we can safely acquire the vm_object lock,
2210 * because this is effectively a random page and the caller
2211 * might be holding the lock shared, we don't want to
2215 KASSERT(m->dirty == 0,
2216 ("Found dirty cache page %p", m));
2217 if ((obj = m->object) != NULL) {
2218 if (vm_object_hold_try(obj)) {
2219 vm_page_protect(m, VM_PROT_NONE);
2221 /* m->object NULL here */
2222 vm_object_drop(obj);
2224 vm_page_deactivate(m);
2228 vm_page_protect(m, VM_PROT_NONE);
2235 * On failure return NULL
2237 atomic_add_int(&vm_pageout_deficit, 1);
2238 pagedaemon_wakeup();
2242 * No pages available, wakeup the pageout daemon and give up.
2244 atomic_add_int(&vm_pageout_deficit, 1);
2245 pagedaemon_wakeup();
2250 * v_free_count can race so loop if we don't find the expected
2259 * Good page found. The page has already been busied for us and
2260 * removed from its queues.
2262 KASSERT(m->dirty == 0,
2263 ("vm_page_alloc: free/cache page %p was dirty", m));
2264 KKASSERT(m->queue == PQ_NONE);
2270 * Initialize the structure, inheriting some flags but clearing
2271 * all the rest. The page has already been busied for us.
2273 vm_page_flag_clear(m, ~PG_KEEP_NEWPAGE_MASK);
2275 KKASSERT(m->wire_count == 0);
2276 KKASSERT((m->busy_count & PBUSY_MASK) == 0);
2281 * Caller must be holding the object lock (asserted by
2282 * vm_page_insert()).
2284 * NOTE: Inserting a page here does not insert it into any pmaps
2285 * (which could cause us to block allocating memory).
2287 * NOTE: If no object an unassociated page is allocated, m->pindex
2288 * can be used by the caller for any purpose.
2291 if (vm_page_insert(m, object, pindex) == FALSE) {
2293 if ((page_req & VM_ALLOC_NULL_OK) == 0)
2294 panic("PAGE RACE %p[%ld]/%p",
2295 object, (long)pindex, m);
2303 * Don't wakeup too often - wakeup the pageout daemon when
2304 * we would be nearly out of memory.
2306 pagedaemon_wakeup();
2309 * A BUSY page is returned.
2315 * Returns number of pages available in our DMA memory reserve
2316 * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
2319 vm_contig_avail_pages(void)
2324 spin_lock(&vm_contig_spin);
2325 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
2326 spin_unlock(&vm_contig_spin);
2332 * Attempt to allocate contiguous physical memory with the specified
2336 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
2337 unsigned long alignment, unsigned long boundary,
2338 unsigned long size, vm_memattr_t memattr)
2344 static vm_pindex_t contig_rover;
2347 alignment >>= PAGE_SHIFT;
2350 boundary >>= PAGE_SHIFT;
2353 size = (size + PAGE_MASK) >> PAGE_SHIFT;
2357 * Disabled temporarily until we find a solution for DRM (a flag
2358 * to always use the free space reserve, for performance).
2360 if (high == BUS_SPACE_MAXADDR && alignment <= PAGE_SIZE &&
2361 boundary <= PAGE_SIZE && size == 1 &&
2362 memattr == VM_MEMATTR_DEFAULT) {
2364 * Any page will work, use vm_page_alloc()
2365 * (e.g. when used from kmem_alloc_attr())
2367 m = vm_page_alloc(NULL, (contig_rover++) & 0x7FFFFFFF,
2368 VM_ALLOC_NORMAL | VM_ALLOC_SYSTEM |
2369 VM_ALLOC_INTERRUPT);
2370 m->valid = VM_PAGE_BITS_ALL;
2377 * Use the low-memory dma reserve
2379 spin_lock(&vm_contig_spin);
2380 blk = alist_alloc(&vm_contig_alist, 0, size);
2381 if (blk == ALIST_BLOCK_NONE) {
2382 spin_unlock(&vm_contig_spin);
2384 kprintf("vm_page_alloc_contig: %ldk nospace\n",
2385 (size << PAGE_SHIFT) / 1024);
2390 if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
2391 alist_free(&vm_contig_alist, blk, size);
2392 spin_unlock(&vm_contig_spin);
2394 kprintf("vm_page_alloc_contig: %ldk high "
2396 (size << PAGE_SHIFT) / 1024,
2401 spin_unlock(&vm_contig_spin);
2402 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
2404 if (vm_contig_verbose) {
2405 kprintf("vm_page_alloc_contig: %016jx/%ldk "
2406 "(%016jx-%016jx al=%lu bo=%lu pgs=%lu attr=%d\n",
2407 (intmax_t)m->phys_addr,
2408 (size << PAGE_SHIFT) / 1024,
2409 low, high, alignment, boundary, size, memattr);
2411 if (memattr != VM_MEMATTR_DEFAULT) {
2412 for (i = 0;i < size; i++)
2413 pmap_page_set_memattr(&m[i], memattr);
2419 * Free contiguously allocated pages. The pages will be wired but not busy.
2420 * When freeing to the alist we leave them wired and not busy.
2423 vm_page_free_contig(vm_page_t m, unsigned long size)
2425 vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2426 vm_pindex_t start = pa >> PAGE_SHIFT;
2427 vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2429 if (vm_contig_verbose) {
2430 kprintf("vm_page_free_contig: %016jx/%ldk\n",
2431 (intmax_t)pa, size / 1024);
2433 if (pa < vm_low_phys_reserved) {
2434 KKASSERT(pa + size <= vm_low_phys_reserved);
2435 spin_lock(&vm_contig_spin);
2436 alist_free(&vm_contig_alist, start, pages);
2437 spin_unlock(&vm_contig_spin);
2440 vm_page_busy_wait(m, FALSE, "cpgfr");
2441 vm_page_unwire(m, 0);
2452 * Wait for sufficient free memory for nominal heavy memory use kernel
2455 * WARNING! Be sure never to call this in any vm_pageout code path, which
2456 * will trivially deadlock the system.
2459 vm_wait_nominal(void)
2461 while (vm_page_count_min(0))
2466 * Test if vm_wait_nominal() would block.
2469 vm_test_nominal(void)
2471 if (vm_page_count_min(0))
2477 * Block until free pages are available for allocation, called in various
2478 * places before memory allocations.
2480 * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2481 * more generous then that.
2487 * never wait forever
2491 lwkt_gettoken(&vm_token);
2493 if (curthread == pagethread ||
2494 curthread == emergpager) {
2496 * The pageout daemon itself needs pages, this is bad.
2498 if (vm_page_count_min(0)) {
2499 vm_pageout_pages_needed = 1;
2500 tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2504 * Wakeup the pageout daemon if necessary and wait.
2506 * Do not wait indefinitely for the target to be reached,
2507 * as load might prevent it from being reached any time soon.
2508 * But wait a little to try to slow down page allocations
2509 * and to give more important threads (the pagedaemon)
2510 * allocation priority.
2512 if (vm_page_count_target()) {
2513 if (vm_pages_needed == 0) {
2514 vm_pages_needed = 1;
2515 wakeup(&vm_pages_needed);
2517 ++vm_pages_waiting; /* SMP race ok */
2518 tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2521 lwkt_reltoken(&vm_token);
2525 * Block until free pages are available for allocation
2527 * Called only from vm_fault so that processes page faulting can be
2531 vm_wait_pfault(void)
2534 * Wakeup the pageout daemon if necessary and wait.
2536 * Do not wait indefinitely for the target to be reached,
2537 * as load might prevent it from being reached any time soon.
2538 * But wait a little to try to slow down page allocations
2539 * and to give more important threads (the pagedaemon)
2540 * allocation priority.
2542 if (vm_page_count_min(0)) {
2543 lwkt_gettoken(&vm_token);
2544 while (vm_page_count_severe()) {
2545 if (vm_page_count_target()) {
2548 if (vm_pages_needed == 0) {
2549 vm_pages_needed = 1;
2550 wakeup(&vm_pages_needed);
2552 ++vm_pages_waiting; /* SMP race ok */
2553 tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2556 * Do not stay stuck in the loop if the system is trying
2557 * to kill the process.
2560 if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2564 lwkt_reltoken(&vm_token);
2569 * Put the specified page on the active list (if appropriate). Ensure
2570 * that act_count is at least ACT_INIT but do not otherwise mess with it.
2572 * The caller should be holding the page busied ? XXX
2573 * This routine may not block.
2576 vm_page_activate(vm_page_t m)
2580 vm_page_spin_lock(m);
2581 if (m->queue - m->pc != PQ_ACTIVE && !(m->flags & PG_FICTITIOUS)) {
2582 _vm_page_queue_spin_lock(m);
2583 oqueue = _vm_page_rem_queue_spinlocked(m);
2584 /* page is left spinlocked, queue is unlocked */
2586 if (oqueue == PQ_CACHE)
2587 mycpu->gd_cnt.v_reactivated++;
2588 if ((m->flags & PG_UNMANAGED) == 0) {
2589 if (m->act_count < ACT_INIT)
2590 m->act_count = ACT_INIT;
2591 _vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2593 _vm_page_and_queue_spin_unlock(m);
2594 if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2595 pagedaemon_wakeup();
2597 if (m->act_count < ACT_INIT)
2598 m->act_count = ACT_INIT;
2599 vm_page_spin_unlock(m);
2604 vm_page_soft_activate(vm_page_t m)
2606 if (m->queue - m->pc == PQ_ACTIVE || (m->flags & PG_FICTITIOUS)) {
2607 if (m->act_count < ACT_INIT)
2608 m->act_count = ACT_INIT;
2610 vm_page_activate(m);
2615 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2616 * routine is called when a page has been added to the cache or free
2619 * This routine may not block.
2621 static __inline void
2622 vm_page_free_wakeup(void)
2624 globaldata_t gd = mycpu;
2627 * If the pageout daemon itself needs pages, then tell it that
2628 * there are some free.
2630 if (vm_pageout_pages_needed &&
2631 gd->gd_vmstats.v_cache_count + gd->gd_vmstats.v_free_count >=
2632 gd->gd_vmstats.v_pageout_free_min
2634 vm_pageout_pages_needed = 0;
2635 wakeup(&vm_pageout_pages_needed);
2639 * Wakeup processes that are waiting on memory.
2641 * Generally speaking we want to wakeup stuck processes as soon as
2642 * possible. !vm_page_count_min(0) is the absolute minimum point
2643 * where we can do this. Wait a bit longer to reduce degenerate
2644 * re-blocking (vm_page_free_hysteresis). The target check is just
2645 * to make sure the min-check w/hysteresis does not exceed the
2648 if (vm_pages_waiting) {
2649 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2650 !vm_page_count_target()) {
2651 vm_pages_waiting = 0;
2652 wakeup(&vmstats.v_free_count);
2653 ++mycpu->gd_cnt.v_ppwakeups;
2656 if (!vm_page_count_target()) {
2658 * Plenty of pages are free, wakeup everyone.
2660 vm_pages_waiting = 0;
2661 wakeup(&vmstats.v_free_count);
2662 ++mycpu->gd_cnt.v_ppwakeups;
2663 } else if (!vm_page_count_min(0)) {
2665 * Some pages are free, wakeup someone.
2667 int wcount = vm_pages_waiting;
2670 vm_pages_waiting = wcount;
2671 wakeup_one(&vmstats.v_free_count);
2672 ++mycpu->gd_cnt.v_ppwakeups;
2679 * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2680 * it from its VM object.
2682 * The vm_page must be BUSY on entry. BUSY will be released on
2683 * return (the page will have been freed).
2686 vm_page_free_toq(vm_page_t m)
2688 mycpu->gd_cnt.v_tfree++;
2689 if (m->flags & (PG_MAPPED | PG_WRITEABLE))
2690 pmap_mapped_sync(m);
2691 KKASSERT((m->flags & PG_MAPPED) == 0);
2692 KKASSERT(m->busy_count & PBUSY_LOCKED);
2694 if ((m->busy_count & PBUSY_MASK) || ((m->queue - m->pc) == PQ_FREE)) {
2695 kprintf("vm_page_free: pindex(%lu), busy %08x, "
2697 (u_long)m->pindex, m->busy_count, m->hold_count);
2698 if ((m->queue - m->pc) == PQ_FREE)
2699 panic("vm_page_free: freeing free page");
2701 panic("vm_page_free: freeing busy page");
2705 * Remove from object, spinlock the page and its queues and
2706 * remove from any queue. No queue spinlock will be held
2707 * after this section (because the page was removed from any
2713 * No further management of fictitious pages occurs beyond object
2714 * and queue removal.
2716 if ((m->flags & PG_FICTITIOUS) != 0) {
2717 KKASSERT(m->queue == PQ_NONE);
2721 vm_page_and_queue_spin_lock(m);
2722 _vm_page_rem_queue_spinlocked(m);
2727 if (m->wire_count != 0) {
2728 if (m->wire_count > 1) {
2730 "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2731 m->wire_count, (long)m->pindex);
2733 panic("vm_page_free: freeing wired page");
2737 * Clear the UNMANAGED flag when freeing an unmanaged page.
2738 * Clear the NEED_COMMIT flag
2740 if (m->flags & PG_UNMANAGED)
2741 vm_page_flag_clear(m, PG_UNMANAGED);
2742 if (m->flags & PG_NEED_COMMIT)
2743 vm_page_flag_clear(m, PG_NEED_COMMIT);
2745 if (m->hold_count != 0) {
2746 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2748 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 1);
2752 * This sequence allows us to clear BUSY while still holding
2753 * its spin lock, which reduces contention vs allocators. We
2754 * must not leave the queue locked or _vm_page_wakeup() may
2757 _vm_page_queue_spin_unlock(m);
2758 if (_vm_page_wakeup(m)) {
2759 vm_page_spin_unlock(m);
2762 vm_page_spin_unlock(m);
2764 vm_page_free_wakeup();
2768 * vm_page_unmanage()
2770 * Prevent PV management from being done on the page. The page is
2771 * also removed from the paging queues, and as a consequence of no longer
2772 * being managed the pageout daemon will not touch it (since there is no
2773 * way to locate the pte mappings for the page). madvise() calls that
2774 * mess with the pmap will also no longer operate on the page.
2776 * Beyond that the page is still reasonably 'normal'. Freeing the page
2777 * will clear the flag.
2779 * This routine is used by OBJT_PHYS objects - objects using unswappable
2780 * physical memory as backing store rather then swap-backed memory and
2781 * will eventually be extended to support 4MB unmanaged physical
2784 * Caller must be holding the page busy.
2787 vm_page_unmanage(vm_page_t m)
2789 KKASSERT(m->busy_count & PBUSY_LOCKED);
2790 if ((m->flags & PG_UNMANAGED) == 0) {
2793 vm_page_flag_set(m, PG_UNMANAGED);
2797 * Mark this page as wired down by yet another map. We do not adjust the
2798 * queue the page is on, it will be checked for wiring as-needed.
2800 * Caller must be holding the page busy.
2803 vm_page_wire(vm_page_t m)
2806 * Only bump the wire statistics if the page is not already wired,
2807 * and only unqueue the page if it is on some queue (if it is unmanaged
2808 * it is already off the queues). Don't do anything with fictitious
2809 * pages because they are always wired.
2811 KKASSERT(m->busy_count & PBUSY_LOCKED);
2812 if ((m->flags & PG_FICTITIOUS) == 0) {
2813 if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2814 atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count, 1);
2816 KASSERT(m->wire_count != 0,
2817 ("vm_page_wire: wire_count overflow m=%p", m));
2822 * Release one wiring of this page, potentially enabling it to be paged again.
2824 * Note that wired pages are no longer unconditionally removed from the
2825 * paging queues, so the page may already be on a queue. Move the page
2826 * to the desired queue if necessary.
2828 * Many pages placed on the inactive queue should actually go
2829 * into the cache, but it is difficult to figure out which. What
2830 * we do instead, if the inactive target is well met, is to put
2831 * clean pages at the head of the inactive queue instead of the tail.
2832 * This will cause them to be moved to the cache more quickly and
2833 * if not actively re-referenced, freed more quickly. If we just
2834 * stick these pages at the end of the inactive queue, heavy filesystem
2835 * meta-data accesses can cause an unnecessary paging load on memory bound
2836 * processes. This optimization causes one-time-use metadata to be
2837 * reused more quickly.
2839 * Pages marked PG_NEED_COMMIT are always activated and never placed on
2840 * the inactive queue. This helps the pageout daemon determine memory
2841 * pressure and act on out-of-memory situations more quickly.
2843 * BUT, if we are in a low-memory situation we have no choice but to
2844 * put clean pages on the cache queue.
2846 * A number of routines use vm_page_unwire() to guarantee that the page
2847 * will go into either the inactive or active queues, and will NEVER
2848 * be placed in the cache - for example, just after dirtying a page.
2849 * dirty pages in the cache are not allowed.
2851 * This routine may not block.
2854 vm_page_unwire(vm_page_t m, int activate)
2856 KKASSERT(m->busy_count & PBUSY_LOCKED);
2857 if (m->flags & PG_FICTITIOUS) {
2859 } else if ((int)m->wire_count <= 0) {
2860 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2862 if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2863 atomic_add_long(&mycpu->gd_vmstats_adj.v_wire_count,-1);
2864 if (m->flags & PG_UNMANAGED) {
2866 } else if (activate || (m->flags & PG_NEED_COMMIT)) {
2867 vm_page_activate(m);
2869 vm_page_deactivate(m);
2876 * Move the specified page to the inactive queue.
2878 * Normally athead is 0 resulting in LRU operation. athead is set
2879 * to 1 if we want this page to be 'as if it were placed in the cache',
2880 * except without unmapping it from the process address space.
2882 * vm_page's spinlock must be held on entry and will remain held on return.
2883 * This routine may not block. The caller does not have to hold the page
2884 * busied but should have some sort of interlock on its validity.
2887 _vm_page_deactivate_locked(vm_page_t m, int athead)
2892 * Ignore if already inactive.
2894 if (m->queue - m->pc == PQ_INACTIVE || (m->flags & PG_FICTITIOUS))
2896 _vm_page_queue_spin_lock(m);
2897 oqueue = _vm_page_rem_queue_spinlocked(m);
2899 if ((m->flags & PG_UNMANAGED) == 0) {
2900 if (oqueue == PQ_CACHE)
2901 mycpu->gd_cnt.v_reactivated++;
2902 vm_page_flag_clear(m, PG_WINATCFLS);
2903 _vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2906 &vm_page_queues[PQ_INACTIVE + m->pc].adds, 1);
2909 /* NOTE: PQ_NONE if condition not taken */
2910 _vm_page_queue_spin_unlock(m);
2911 /* leaves vm_page spinlocked */
2915 * Attempt to deactivate a page.
2920 vm_page_deactivate(vm_page_t m)
2922 vm_page_spin_lock(m);
2923 _vm_page_deactivate_locked(m, 0);
2924 vm_page_spin_unlock(m);
2928 vm_page_deactivate_locked(vm_page_t m)
2930 _vm_page_deactivate_locked(m, 0);
2934 * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
2936 * This function returns non-zero if it successfully moved the page to
2939 * This function unconditionally unbusies the page on return.
2942 vm_page_try_to_cache(vm_page_t m)
2945 * Shortcut if we obviously cannot move the page, or if the
2946 * page is already on the cache queue, or it is ficitious.
2948 if (m->dirty || m->hold_count || m->wire_count ||
2949 m->queue - m->pc == PQ_CACHE ||
2950 (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT | PG_FICTITIOUS))) {
2956 * Page busied by us and no longer spinlocked. Dirty pages cannot
2957 * be moved to the cache.
2959 vm_page_test_dirty(m);
2960 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2969 * Attempt to free the page. If we cannot free it, we do nothing.
2970 * 1 is returned on success, 0 on failure.
2972 * Caller provides an unlocked/non-busied page.
2976 vm_page_try_to_free(vm_page_t m)
2978 if (vm_page_busy_try(m, TRUE))
2982 * The page can be in any state, including already being on the free
2983 * queue. Check to see if it really can be freed.
2985 if (m->dirty || /* can't free if it is dirty */
2986 m->hold_count || /* or held (XXX may be wrong) */
2987 m->wire_count || /* or wired */
2988 (m->flags & (PG_UNMANAGED | /* or unmanaged */
2989 PG_NEED_COMMIT | /* or needs a commit */
2990 PG_FICTITIOUS)) || /* or is fictitious */
2991 m->queue - m->pc == PQ_FREE || /* already on PQ_FREE */
2992 m->queue - m->pc == PQ_HOLD) { /* already on PQ_HOLD */
2998 * We can probably free the page.
3000 * Page busied by us and no longer spinlocked. Dirty pages will
3001 * not be freed by this function. We have to re-test the
3002 * dirty bit after cleaning out the pmaps.
3004 vm_page_test_dirty(m);
3005 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3009 vm_page_protect(m, VM_PROT_NONE);
3010 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3021 * Put the specified page onto the page cache queue (if appropriate).
3023 * The page must be busy, and this routine will release the busy and
3024 * possibly even free the page.
3027 vm_page_cache(vm_page_t m)
3030 * Not suitable for the cache
3032 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT | PG_FICTITIOUS)) ||
3033 (m->busy_count & PBUSY_MASK) ||
3034 m->wire_count || m->hold_count) {
3040 * Already in the cache (and thus not mapped)
3042 if ((m->queue - m->pc) == PQ_CACHE) {
3043 if (m->flags & (PG_MAPPED | PG_WRITEABLE))
3044 pmap_mapped_sync(m);
3045 KKASSERT((m->flags & PG_MAPPED) == 0);
3052 * REMOVED - it is possible for dirty to get set at any time as
3053 * long as the page is still mapped and writeable.
3055 * Caller is required to test m->dirty, but note that the act of
3056 * removing the page from its maps can cause it to become dirty
3057 * on an SMP system due to another cpu running in usermode.
3060 panic("vm_page_cache: caching a dirty page, pindex: %ld",
3066 * Remove all pmaps and indicate that the page is not
3067 * writeable or mapped. Our vm_page_protect() call may
3068 * have blocked (especially w/ VM_PROT_NONE), so recheck
3071 vm_page_protect(m, VM_PROT_NONE);
3072 pmap_mapped_sync(m);
3073 if ((m->flags & (PG_UNMANAGED | PG_MAPPED)) ||
3074 (m->busy_count & PBUSY_MASK) ||
3075 m->wire_count || m->hold_count) {
3077 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
3078 vm_page_deactivate(m);
3081 _vm_page_and_queue_spin_lock(m);
3082 _vm_page_rem_queue_spinlocked(m);
3083 _vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
3084 _vm_page_and_queue_spin_unlock(m);
3086 vm_page_free_wakeup();
3091 * vm_page_dontneed()
3093 * Cache, deactivate, or do nothing as appropriate. This routine
3094 * is typically used by madvise() MADV_DONTNEED.
3096 * Generally speaking we want to move the page into the cache so
3097 * it gets reused quickly. However, this can result in a silly syndrome
3098 * due to the page recycling too quickly. Small objects will not be
3099 * fully cached. On the otherhand, if we move the page to the inactive
3100 * queue we wind up with a problem whereby very large objects
3101 * unnecessarily blow away our inactive and cache queues.
3103 * The solution is to move the pages based on a fixed weighting. We
3104 * either leave them alone, deactivate them, or move them to the cache,
3105 * where moving them to the cache has the highest weighting.
3106 * By forcing some pages into other queues we eventually force the
3107 * system to balance the queues, potentially recovering other unrelated
3108 * space from active. The idea is to not force this to happen too
3111 * The page must be busied.
3114 vm_page_dontneed(vm_page_t m)
3116 static int dnweight;
3123 * occassionally leave the page alone
3125 if ((dnw & 0x01F0) == 0 ||
3126 m->queue - m->pc == PQ_INACTIVE ||
3127 m->queue - m->pc == PQ_CACHE
3129 if (m->act_count >= ACT_INIT)
3135 * If vm_page_dontneed() is inactivating a page, it must clear
3136 * the referenced flag; otherwise the pagedaemon will see references
3137 * on the page in the inactive queue and reactivate it. Until the
3138 * page can move to the cache queue, madvise's job is not done.
3140 vm_page_flag_clear(m, PG_REFERENCED);
3141 pmap_clear_reference(m);
3144 vm_page_test_dirty(m);
3146 if (m->dirty || (dnw & 0x0070) == 0) {
3148 * Deactivate the page 3 times out of 32.
3153 * Cache the page 28 times out of every 32. Note that
3154 * the page is deactivated instead of cached, but placed
3155 * at the head of the queue instead of the tail.
3159 vm_page_spin_lock(m);
3160 _vm_page_deactivate_locked(m, head);
3161 vm_page_spin_unlock(m);
3165 * These routines manipulate the 'soft busy' count for a page. A soft busy
3166 * is almost like a hard BUSY except that it allows certain compatible
3167 * operations to occur on the page while it is busy. For example, a page
3168 * undergoing a write can still be mapped read-only.
3170 * We also use soft-busy to quickly pmap_enter shared read-only pages
3171 * without having to hold the page locked.
3173 * The soft-busy count can be > 1 in situations where multiple threads
3174 * are pmap_enter()ing the same page simultaneously, or when two buffer
3175 * cache buffers overlap the same page.
3177 * The caller must hold the page BUSY when making these two calls.
3180 vm_page_io_start(vm_page_t m)
3184 ocount = atomic_fetchadd_int(&m->busy_count, 1);
3185 KKASSERT(ocount & PBUSY_LOCKED);
3189 vm_page_io_finish(vm_page_t m)
3193 ocount = atomic_fetchadd_int(&m->busy_count, -1);
3194 KKASSERT(ocount & PBUSY_MASK);
3196 if (((ocount - 1) & (PBUSY_LOCKED | PBUSY_MASK)) == 0)
3202 * Attempt to soft-busy a page. The page must not be PBUSY_LOCKED.
3204 * We can't use fetchadd here because we might race a hard-busy and the
3205 * page freeing code asserts on a non-zero soft-busy count (even if only
3208 * Returns 0 on success, non-zero on failure.
3211 vm_page_sbusy_try(vm_page_t m)
3216 ocount = m->busy_count;
3218 if (ocount & PBUSY_LOCKED)
3220 if (atomic_cmpset_int(&m->busy_count, ocount, ocount + 1))
3225 if (m->busy_count & PBUSY_LOCKED)
3227 ocount = atomic_fetchadd_int(&m->busy_count, 1);
3228 if (ocount & PBUSY_LOCKED) {
3229 vm_page_sbusy_drop(m);
3237 * Indicate that a clean VM page requires a filesystem commit and cannot
3238 * be reused. Used by tmpfs.
3241 vm_page_need_commit(vm_page_t m)
3243 vm_page_flag_set(m, PG_NEED_COMMIT);
3244 vm_object_set_writeable_dirty(m->object);
3248 vm_page_clear_commit(vm_page_t m)
3250 vm_page_flag_clear(m, PG_NEED_COMMIT);
3254 * Grab a page, blocking if it is busy and allocating a page if necessary.
3255 * A busy page is returned or NULL. The page may or may not be valid and
3256 * might not be on a queue (the caller is responsible for the disposition of
3259 * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
3260 * page will be zero'd and marked valid.
3262 * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
3263 * valid even if it already exists.
3265 * If VM_ALLOC_RETRY is specified this routine will never return NULL. Also
3266 * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
3267 * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
3269 * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
3270 * always returned if we had blocked.
3272 * This routine may not be called from an interrupt.
3274 * No other requirements.
3277 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
3283 KKASSERT(allocflags &
3284 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
3285 vm_object_hold_shared(object);
3287 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
3289 vm_page_sleep_busy(m, TRUE, "pgrbwt");
3290 if ((allocflags & VM_ALLOC_RETRY) == 0) {
3295 } else if (m == NULL) {
3297 vm_object_upgrade(object);
3300 if (allocflags & VM_ALLOC_RETRY)
3301 allocflags |= VM_ALLOC_NULL_OK;
3302 m = vm_page_alloc(object, pindex,
3303 allocflags & ~VM_ALLOC_RETRY);
3307 if ((allocflags & VM_ALLOC_RETRY) == 0)
3316 * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
3318 * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
3319 * valid even if already valid.
3321 * NOTE! We have removed all of the PG_ZERO optimizations and also
3322 * removed the idle zeroing code. These optimizations actually
3323 * slow things down on modern cpus because the zerod area is
3324 * likely uncached, placing a memory-access burden on the
3325 * accesors taking the fault.
3327 * By always zeroing the page in-line with the fault, no
3328 * dynamic ram reads are needed and the caches are hot, ready
3329 * for userland to access the memory.
3331 if (m->valid == 0) {
3332 if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
3333 pmap_zero_page(VM_PAGE_TO_PHYS(m));
3334 m->valid = VM_PAGE_BITS_ALL;
3336 } else if (allocflags & VM_ALLOC_FORCE_ZERO) {
3337 pmap_zero_page(VM_PAGE_TO_PHYS(m));
3338 m->valid = VM_PAGE_BITS_ALL;
3341 vm_object_drop(object);
3346 * Mapping function for valid bits or for dirty bits in
3347 * a page. May not block.
3349 * Inputs are required to range within a page.
3355 vm_page_bits(int base, int size)
3361 base + size <= PAGE_SIZE,
3362 ("vm_page_bits: illegal base/size %d/%d", base, size)
3365 if (size == 0) /* handle degenerate case */
3368 first_bit = base >> DEV_BSHIFT;
3369 last_bit = (base + size - 1) >> DEV_BSHIFT;
3371 return ((2 << last_bit) - (1 << first_bit));
3375 * Sets portions of a page valid and clean. The arguments are expected
3376 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
3377 * of any partial chunks touched by the range. The invalid portion of
3378 * such chunks will be zero'd.
3380 * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
3381 * align base to DEV_BSIZE so as not to mark clean a partially
3382 * truncated device block. Otherwise the dirty page status might be
3385 * This routine may not block.
3387 * (base + size) must be less then or equal to PAGE_SIZE.
3390 _vm_page_zero_valid(vm_page_t m, int base, int size)
3395 if (size == 0) /* handle degenerate case */
3399 * If the base is not DEV_BSIZE aligned and the valid
3400 * bit is clear, we have to zero out a portion of the
3404 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
3405 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
3407 pmap_zero_page_area(
3415 * If the ending offset is not DEV_BSIZE aligned and the
3416 * valid bit is clear, we have to zero out a portion of
3420 endoff = base + size;
3422 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3423 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
3425 pmap_zero_page_area(
3428 DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
3434 * Set valid, clear dirty bits. If validating the entire
3435 * page we can safely clear the pmap modify bit. We also
3436 * use this opportunity to clear the PG_NOSYNC flag. If a process
3437 * takes a write fault on a MAP_NOSYNC memory area the flag will
3440 * We set valid bits inclusive of any overlap, but we can only
3441 * clear dirty bits for DEV_BSIZE chunks that are fully within
3444 * Page must be busied?
3445 * No other requirements.
3448 vm_page_set_valid(vm_page_t m, int base, int size)
3450 _vm_page_zero_valid(m, base, size);
3451 m->valid |= vm_page_bits(base, size);
3456 * Set valid bits and clear dirty bits.
3458 * Page must be busied by caller.
3460 * NOTE: This function does not clear the pmap modified bit.
3461 * Also note that e.g. NFS may use a byte-granular base
3464 * No other requirements.
3467 vm_page_set_validclean(vm_page_t m, int base, int size)
3471 _vm_page_zero_valid(m, base, size);
3472 pagebits = vm_page_bits(base, size);
3473 m->valid |= pagebits;
3474 m->dirty &= ~pagebits;
3475 if (base == 0 && size == PAGE_SIZE) {
3476 /*pmap_clear_modify(m);*/
3477 vm_page_flag_clear(m, PG_NOSYNC);
3482 * Set valid & dirty. Used by buwrite()
3484 * Page must be busied by caller.
3487 vm_page_set_validdirty(vm_page_t m, int base, int size)
3491 pagebits = vm_page_bits(base, size);
3492 m->valid |= pagebits;
3493 m->dirty |= pagebits;
3495 vm_object_set_writeable_dirty(m->object);
3501 * NOTE: This function does not clear the pmap modified bit.
3502 * Also note that e.g. NFS may use a byte-granular base
3505 * Page must be busied?
3506 * No other requirements.
3509 vm_page_clear_dirty(vm_page_t m, int base, int size)
3511 m->dirty &= ~vm_page_bits(base, size);
3512 if (base == 0 && size == PAGE_SIZE) {
3513 /*pmap_clear_modify(m);*/
3514 vm_page_flag_clear(m, PG_NOSYNC);
3519 * Make the page all-dirty.
3521 * Also make sure the related object and vnode reflect the fact that the
3522 * object may now contain a dirty page.
3524 * Page must be busied?
3525 * No other requirements.
3528 vm_page_dirty(vm_page_t m)
3531 int pqtype = m->queue - m->pc;
3533 KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3534 ("vm_page_dirty: page in free/cache queue!"));
3535 if (m->dirty != VM_PAGE_BITS_ALL) {
3536 m->dirty = VM_PAGE_BITS_ALL;
3538 vm_object_set_writeable_dirty(m->object);
3543 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3544 * valid and dirty bits for the effected areas are cleared.
3546 * Page must be busied?
3548 * No other requirements.
3551 vm_page_set_invalid(vm_page_t m, int base, int size)
3555 bits = vm_page_bits(base, size);
3558 atomic_add_int(&m->object->generation, 1);
3562 * The kernel assumes that the invalid portions of a page contain
3563 * garbage, but such pages can be mapped into memory by user code.
3564 * When this occurs, we must zero out the non-valid portions of the
3565 * page so user code sees what it expects.
3567 * Pages are most often semi-valid when the end of a file is mapped
3568 * into memory and the file's size is not page aligned.
3570 * Page must be busied?
3571 * No other requirements.
3574 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3580 * Scan the valid bits looking for invalid sections that
3581 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
3582 * valid bit may be set ) have already been zerod by
3583 * vm_page_set_validclean().
3585 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3586 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3587 (m->valid & (1 << i))
3590 pmap_zero_page_area(
3593 (i - b) << DEV_BSHIFT
3601 * setvalid is TRUE when we can safely set the zero'd areas
3602 * as being valid. We can do this if there are no cache consistency
3603 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3606 m->valid = VM_PAGE_BITS_ALL;
3610 * Is a (partial) page valid? Note that the case where size == 0
3611 * will return FALSE in the degenerate case where the page is entirely
3612 * invalid, and TRUE otherwise.
3615 * No other requirements.
3618 vm_page_is_valid(vm_page_t m, int base, int size)
3620 int bits = vm_page_bits(base, size);
3622 if (m->valid && ((m->valid & bits) == bits))
3629 * Update dirty bits from pmap/mmu. May not block.
3631 * Caller must hold the page busy
3633 * WARNING! Unless the page has been unmapped, this function only
3634 * provides a likely dirty status.
3637 vm_page_test_dirty(vm_page_t m)
3639 if (m->dirty != VM_PAGE_BITS_ALL && pmap_is_modified(m)) {
3644 #include "opt_ddb.h"
3646 #include <ddb/ddb.h>
3648 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3650 db_printf("vmstats.v_free_count: %ld\n", vmstats.v_free_count);
3651 db_printf("vmstats.v_cache_count: %ld\n", vmstats.v_cache_count);
3652 db_printf("vmstats.v_inactive_count: %ld\n", vmstats.v_inactive_count);
3653 db_printf("vmstats.v_active_count: %ld\n", vmstats.v_active_count);
3654 db_printf("vmstats.v_wire_count: %ld\n", vmstats.v_wire_count);
3655 db_printf("vmstats.v_free_reserved: %ld\n", vmstats.v_free_reserved);
3656 db_printf("vmstats.v_free_min: %ld\n", vmstats.v_free_min);
3657 db_printf("vmstats.v_free_target: %ld\n", vmstats.v_free_target);
3658 db_printf("vmstats.v_cache_min: %ld\n", vmstats.v_cache_min);
3659 db_printf("vmstats.v_inactive_target: %ld\n",
3660 vmstats.v_inactive_target);
3663 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3666 db_printf("PQ_FREE:");
3667 for (i = 0; i < PQ_L2_SIZE; i++) {
3668 db_printf(" %ld", vm_page_queues[PQ_FREE + i].lcnt);
3672 db_printf("PQ_CACHE:");
3673 for(i = 0; i < PQ_L2_SIZE; i++) {
3674 db_printf(" %ld", vm_page_queues[PQ_CACHE + i].lcnt);
3678 db_printf("PQ_ACTIVE:");
3679 for(i = 0; i < PQ_L2_SIZE; i++) {
3680 db_printf(" %ld", vm_page_queues[PQ_ACTIVE + i].lcnt);
3684 db_printf("PQ_INACTIVE:");
3685 for(i = 0; i < PQ_L2_SIZE; i++) {
3686 db_printf(" %ld", vm_page_queues[PQ_INACTIVE + i].lcnt);