kernel - Add NUMA awareness to vm_page_alloc() and related functions (2)
[dragonfly.git] / sys / vm / vm_page.c
blob006f913ac7adbd5ecaf98c952df2069d9a02491f
1 /*
2 * Copyright (c) 1991 Regents of the University of California.
3 * All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * The Mach Operating System project at Carnegie-Mellon University.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
32 * from: @(#)vm_page.c 7.4 (Berkeley) 5/7/91
33 * $FreeBSD: src/sys/vm/vm_page.c,v 1.147.2.18 2002/03/10 05:03:19 alc Exp $
37 * Copyright (c) 1987, 1990 Carnegie-Mellon University.
38 * All rights reserved.
40 * Authors: Avadis Tevanian, Jr., Michael Wayne Young
42 * Permission to use, copy, modify and distribute this software and
43 * its documentation is hereby granted, provided that both the copyright
44 * notice and this permission notice appear in all copies of the
45 * software, derivative works or modified versions, and any portions
46 * thereof, and that both notices appear in supporting documentation.
48 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
49 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
50 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
52 * Carnegie Mellon requests users of this software to return to
54 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
55 * School of Computer Science
56 * Carnegie Mellon University
57 * Pittsburgh PA 15213-3890
59 * any improvements or extensions that they make and grant Carnegie the
60 * rights to redistribute these changes.
63 * Resident memory management module. The module manipulates 'VM pages'.
64 * A VM page is the core building block for memory management.
67 #include <sys/param.h>
68 #include <sys/systm.h>
69 #include <sys/malloc.h>
70 #include <sys/proc.h>
71 #include <sys/vmmeter.h>
72 #include <sys/vnode.h>
73 #include <sys/kernel.h>
74 #include <sys/alist.h>
75 #include <sys/sysctl.h>
76 #include <sys/cpu_topology.h>
78 #include <vm/vm.h>
79 #include <vm/vm_param.h>
80 #include <sys/lock.h>
81 #include <vm/vm_kern.h>
82 #include <vm/pmap.h>
83 #include <vm/vm_map.h>
84 #include <vm/vm_object.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_pageout.h>
87 #include <vm/vm_pager.h>
88 #include <vm/vm_extern.h>
89 #include <vm/swap_pager.h>
91 #include <machine/inttypes.h>
92 #include <machine/md_var.h>
93 #include <machine/specialreg.h>
95 #include <vm/vm_page2.h>
96 #include <sys/spinlock2.h>
99 * Action hash for user umtx support.
101 #define VMACTION_HSIZE 256
102 #define VMACTION_HMASK (VMACTION_HSIZE - 1)
105 * SET - Minimum required set associative size, must be a power of 2. We
106 * want this to match or exceed the set-associativeness of the cpu.
108 * GRP - A larger set that allows bleed-over into the domains of other
109 * nearby cpus. Also must be a power of 2. Used by the page zeroing
110 * code to smooth things out a bit.
112 #define PQ_SET_ASSOC 16
113 #define PQ_SET_ASSOC_MASK (PQ_SET_ASSOC - 1)
115 #define PQ_GRP_ASSOC (PQ_SET_ASSOC * 2)
116 #define PQ_GRP_ASSOC_MASK (PQ_GRP_ASSOC - 1)
118 static void vm_page_queue_init(void);
119 static void vm_page_free_wakeup(void);
120 static vm_page_t vm_page_select_cache(u_short pg_color);
121 static vm_page_t _vm_page_list_find2(int basequeue, int index);
122 static void _vm_page_deactivate_locked(vm_page_t m, int athead);
125 * Array of tailq lists
127 __cachealign struct vpgqueues vm_page_queues[PQ_COUNT];
129 LIST_HEAD(vm_page_action_list, vm_page_action);
130 struct vm_page_action_list action_list[VMACTION_HSIZE];
131 static volatile int vm_pages_waiting;
133 static struct alist vm_contig_alist;
134 static struct almeta vm_contig_ameta[ALIST_RECORDS_65536];
135 static struct spinlock vm_contig_spin = SPINLOCK_INITIALIZER(&vm_contig_spin, "vm_contig_spin");
137 static u_long vm_dma_reserved = 0;
138 TUNABLE_ULONG("vm.dma_reserved", &vm_dma_reserved);
139 SYSCTL_ULONG(_vm, OID_AUTO, dma_reserved, CTLFLAG_RD, &vm_dma_reserved, 0,
140 "Memory reserved for DMA");
141 SYSCTL_UINT(_vm, OID_AUTO, dma_free_pages, CTLFLAG_RD,
142 &vm_contig_alist.bl_free, 0, "Memory reserved for DMA");
144 static int vm_contig_verbose = 0;
145 TUNABLE_INT("vm.contig_verbose", &vm_contig_verbose);
147 RB_GENERATE2(vm_page_rb_tree, vm_page, rb_entry, rb_vm_page_compare,
148 vm_pindex_t, pindex);
150 static void
151 vm_page_queue_init(void)
153 int i;
155 for (i = 0; i < PQ_L2_SIZE; i++)
156 vm_page_queues[PQ_FREE+i].cnt = &vmstats.v_free_count;
157 for (i = 0; i < PQ_L2_SIZE; i++)
158 vm_page_queues[PQ_CACHE+i].cnt = &vmstats.v_cache_count;
159 for (i = 0; i < PQ_L2_SIZE; i++)
160 vm_page_queues[PQ_INACTIVE+i].cnt = &vmstats.v_inactive_count;
161 for (i = 0; i < PQ_L2_SIZE; i++)
162 vm_page_queues[PQ_ACTIVE+i].cnt = &vmstats.v_active_count;
163 for (i = 0; i < PQ_L2_SIZE; i++)
164 vm_page_queues[PQ_HOLD+i].cnt = &vmstats.v_active_count;
165 /* PQ_NONE has no queue */
167 for (i = 0; i < PQ_COUNT; i++) {
168 TAILQ_INIT(&vm_page_queues[i].pl);
169 spin_init(&vm_page_queues[i].spin, "vm_page_queue_init");
172 for (i = 0; i < VMACTION_HSIZE; i++)
173 LIST_INIT(&action_list[i]);
177 * note: place in initialized data section? Is this necessary?
179 long first_page = 0;
180 int vm_page_array_size = 0;
181 vm_page_t vm_page_array = NULL;
182 vm_paddr_t vm_low_phys_reserved;
185 * (low level boot)
187 * Sets the page size, perhaps based upon the memory size.
188 * Must be called before any use of page-size dependent functions.
190 void
191 vm_set_page_size(void)
193 if (vmstats.v_page_size == 0)
194 vmstats.v_page_size = PAGE_SIZE;
195 if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
196 panic("vm_set_page_size: page size not a power of two");
200 * (low level boot)
202 * Add a new page to the freelist for use by the system. New pages
203 * are added to both the head and tail of the associated free page
204 * queue in a bottom-up fashion, so both zero'd and non-zero'd page
205 * requests pull 'recent' adds (higher physical addresses) first.
207 * Beware that the page zeroing daemon will also be running soon after
208 * boot, moving pages from the head to the tail of the PQ_FREE queues.
210 * Must be called in a critical section.
212 static void
213 vm_add_new_page(vm_paddr_t pa)
215 struct vpgqueues *vpq;
216 vm_page_t m;
218 m = PHYS_TO_VM_PAGE(pa);
219 m->phys_addr = pa;
220 m->flags = 0;
221 m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
222 m->pat_mode = PAT_WRITE_BACK;
225 * Twist for cpu localization in addition to page coloring, so
226 * different cpus selecting by m->queue get different page colors.
228 m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE) & PQ_L2_MASK;
229 m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE)) & PQ_L2_MASK;
232 * Reserve a certain number of contiguous low memory pages for
233 * contigmalloc() to use.
235 if (pa < vm_low_phys_reserved) {
236 atomic_add_int(&vmstats.v_page_count, 1);
237 atomic_add_int(&vmstats.v_dma_pages, 1);
238 m->queue = PQ_NONE;
239 m->wire_count = 1;
240 atomic_add_int(&vmstats.v_wire_count, 1);
241 alist_free(&vm_contig_alist, pa >> PAGE_SHIFT, 1);
242 return;
246 * General page
248 m->queue = m->pc + PQ_FREE;
249 KKASSERT(m->dirty == 0);
251 atomic_add_int(&vmstats.v_page_count, 1);
252 atomic_add_int(&vmstats.v_free_count, 1);
253 vpq = &vm_page_queues[m->queue];
254 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
255 ++vpq->lcnt;
259 * (low level boot)
261 * Initializes the resident memory module.
263 * Preallocates memory for critical VM structures and arrays prior to
264 * kernel_map becoming available.
266 * Memory is allocated from (virtual2_start, virtual2_end) if available,
267 * otherwise memory is allocated from (virtual_start, virtual_end).
269 * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
270 * large enough to hold vm_page_array & other structures for machines with
271 * large amounts of ram, so we want to use virtual2* when available.
273 void
274 vm_page_startup(void)
276 vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
277 vm_offset_t mapped;
278 vm_size_t npages;
279 vm_paddr_t page_range;
280 vm_paddr_t new_end;
281 int i;
282 vm_paddr_t pa;
283 vm_paddr_t last_pa;
284 vm_paddr_t end;
285 vm_paddr_t biggestone, biggestsize;
286 vm_paddr_t total;
288 total = 0;
289 biggestsize = 0;
290 biggestone = 0;
291 vaddr = round_page(vaddr);
294 * Make sure ranges are page-aligned.
296 for (i = 0; phys_avail[i].phys_end; ++i) {
297 phys_avail[i].phys_beg = round_page64(phys_avail[i].phys_beg);
298 phys_avail[i].phys_end = trunc_page64(phys_avail[i].phys_end);
299 if (phys_avail[i].phys_end < phys_avail[i].phys_beg)
300 phys_avail[i].phys_end = phys_avail[i].phys_beg;
304 * Locate largest block
306 for (i = 0; phys_avail[i].phys_end; ++i) {
307 vm_paddr_t size = phys_avail[i].phys_end -
308 phys_avail[i].phys_beg;
310 if (size > biggestsize) {
311 biggestone = i;
312 biggestsize = size;
314 total += size;
317 end = phys_avail[biggestone].phys_end;
318 end = trunc_page(end);
321 * Initialize the queue headers for the free queue, the active queue
322 * and the inactive queue.
324 vm_page_queue_init();
326 #if !defined(_KERNEL_VIRTUAL)
328 * VKERNELs don't support minidumps and as such don't need
329 * vm_page_dump
331 * Allocate a bitmap to indicate that a random physical page
332 * needs to be included in a minidump.
334 * The amd64 port needs this to indicate which direct map pages
335 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
337 * However, i386 still needs this workspace internally within the
338 * minidump code. In theory, they are not needed on i386, but are
339 * included should the sf_buf code decide to use them.
341 page_range = phys_avail[i-1].phys_end / PAGE_SIZE;
342 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
343 end -= vm_page_dump_size;
344 vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
345 VM_PROT_READ | VM_PROT_WRITE);
346 bzero((void *)vm_page_dump, vm_page_dump_size);
347 #endif
349 * Compute the number of pages of memory that will be available for
350 * use (taking into account the overhead of a page structure per
351 * page).
353 first_page = phys_avail[0].phys_beg / PAGE_SIZE;
354 page_range = phys_avail[i-1].phys_end / PAGE_SIZE - first_page;
355 npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
357 #ifndef _KERNEL_VIRTUAL
359 * (only applies to real kernels)
361 * Reserve a large amount of low memory for potential 32-bit DMA
362 * space allocations. Once device initialization is complete we
363 * release most of it, but keep (vm_dma_reserved) memory reserved
364 * for later use. Typically for X / graphics. Through trial and
365 * error we find that GPUs usually requires ~60-100MB or so.
367 * By default, 128M is left in reserve on machines with 2G+ of ram.
369 vm_low_phys_reserved = (vm_paddr_t)65536 << PAGE_SHIFT;
370 if (vm_low_phys_reserved > total / 4)
371 vm_low_phys_reserved = total / 4;
372 if (vm_dma_reserved == 0) {
373 vm_dma_reserved = 128 * 1024 * 1024; /* 128MB */
374 if (vm_dma_reserved > total / 16)
375 vm_dma_reserved = total / 16;
377 #endif
378 alist_init(&vm_contig_alist, 65536, vm_contig_ameta,
379 ALIST_RECORDS_65536);
382 * Initialize the mem entry structures now, and put them in the free
383 * queue.
385 new_end = trunc_page(end - page_range * sizeof(struct vm_page));
386 mapped = pmap_map(&vaddr, new_end, end, VM_PROT_READ | VM_PROT_WRITE);
387 vm_page_array = (vm_page_t)mapped;
389 #if defined(__x86_64__) && !defined(_KERNEL_VIRTUAL)
391 * since pmap_map on amd64 returns stuff out of a direct-map region,
392 * we have to manually add these pages to the minidump tracking so
393 * that they can be dumped, including the vm_page_array.
395 for (pa = new_end;
396 pa < phys_avail[biggestone].phys_end;
397 pa += PAGE_SIZE) {
398 dump_add_page(pa);
400 #endif
403 * Clear all of the page structures
405 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
406 vm_page_array_size = page_range;
409 * Construct the free queue(s) in ascending order (by physical
410 * address) so that the first 16MB of physical memory is allocated
411 * last rather than first. On large-memory machines, this avoids
412 * the exhaustion of low physical memory before isa_dmainit has run.
414 vmstats.v_page_count = 0;
415 vmstats.v_free_count = 0;
416 for (i = 0; phys_avail[i].phys_end && npages > 0; ++i) {
417 pa = phys_avail[i].phys_beg;
418 if (i == biggestone)
419 last_pa = new_end;
420 else
421 last_pa = phys_avail[i].phys_end;
422 while (pa < last_pa && npages-- > 0) {
423 vm_add_new_page(pa);
424 pa += PAGE_SIZE;
427 if (virtual2_start)
428 virtual2_start = vaddr;
429 else
430 virtual_start = vaddr;
434 * Reorganize VM pages based on numa data. May be called as many times as
435 * necessary. Will reorganize the vm_page_t page color and related queue(s)
436 * to allow vm_page_alloc() to choose pages based on socket affinity.
438 * NOTE: This function is only called while we are still in UP mode, so
439 * we only need a critical section to protect the queues (which
440 * saves a lot of time, there are likely a ton of pages).
442 void
443 vm_numa_organize(vm_paddr_t ran_beg, vm_paddr_t bytes, int physid)
445 vm_paddr_t scan_beg;
446 vm_paddr_t scan_end;
447 vm_paddr_t ran_end;
448 struct vpgqueues *vpq;
449 vm_page_t m;
450 vm_page_t mend;
451 int i;
452 int socket_mod;
453 int socket_value;
456 * Check if no physical information, or there was only one socket
457 * (so don't waste time doing nothing!).
459 if (cpu_topology_phys_ids <= 1 ||
460 cpu_topology_core_ids == 0) {
461 return;
465 * Setup for our iteration. Note that ACPI may iterate CPU
466 * sockets starting at 0 or 1 or some other number. The
467 * cpu_topology code mod's it against the socket count.
469 ran_end = ran_beg + bytes;
470 physid %= cpu_topology_phys_ids;
472 socket_mod = PQ_L2_SIZE / cpu_topology_phys_ids;
473 socket_value = physid * socket_mod;
474 mend = &vm_page_array[vm_page_array_size];
476 crit_enter();
479 * Adjust vm_page->pc and requeue all affected pages. The
480 * allocator will then be able to localize memory allocations
481 * to some degree.
483 for (i = 0; phys_avail[i].phys_end; ++i) {
484 scan_beg = phys_avail[i].phys_beg;
485 scan_end = phys_avail[i].phys_end;
486 if (scan_end <= ran_beg)
487 continue;
488 if (scan_beg >= ran_end)
489 continue;
490 if (scan_beg < ran_beg)
491 scan_beg = ran_beg;
492 if (scan_end > ran_end)
493 scan_end = ran_end;
494 if (atop(scan_end) > first_page + vm_page_array_size)
495 scan_end = ptoa(first_page + vm_page_array_size);
497 m = PHYS_TO_VM_PAGE(scan_beg);
498 while (scan_beg < scan_end) {
499 KKASSERT(m < mend);
500 if (m->queue != PQ_NONE) {
501 vpq = &vm_page_queues[m->queue];
502 TAILQ_REMOVE(&vpq->pl, m, pageq);
503 --vpq->lcnt;
504 /* queue doesn't change, no need to adj cnt */
505 /* atomic_add_int(vpq->cnt, -1); */
506 m->queue -= m->pc;
507 m->pc %= socket_mod;
508 m->pc += socket_value;
509 m->pc &= PQ_L2_MASK;
510 m->queue += m->pc;
511 vpq = &vm_page_queues[m->queue];
512 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
513 ++vpq->lcnt;
514 /* queue doesn't change, no need to adj cnt */
515 /* atomic_add_int(vpq->cnt, 1); */
516 } else {
517 m->pc %= socket_mod;
518 m->pc += socket_value;
519 m->pc &= PQ_L2_MASK;
521 scan_beg += PAGE_SIZE;
522 ++m;
525 crit_exit();
529 * We tended to reserve a ton of memory for contigmalloc(). Now that most
530 * drivers have initialized we want to return most the remaining free
531 * reserve back to the VM page queues so they can be used for normal
532 * allocations.
534 * We leave vm_dma_reserved bytes worth of free pages in the reserve pool.
536 static void
537 vm_page_startup_finish(void *dummy __unused)
539 alist_blk_t blk;
540 alist_blk_t rblk;
541 alist_blk_t count;
542 alist_blk_t xcount;
543 alist_blk_t bfree;
544 vm_page_t m;
546 spin_lock(&vm_contig_spin);
547 for (;;) {
548 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
549 if (bfree <= vm_dma_reserved / PAGE_SIZE)
550 break;
551 if (count == 0)
552 break;
555 * Figure out how much of the initial reserve we have to
556 * free in order to reach our target.
558 bfree -= vm_dma_reserved / PAGE_SIZE;
559 if (count > bfree) {
560 blk += count - bfree;
561 count = bfree;
565 * Calculate the nearest power of 2 <= count.
567 for (xcount = 1; xcount <= count; xcount <<= 1)
569 xcount >>= 1;
570 blk += count - xcount;
571 count = xcount;
574 * Allocate the pages from the alist, then free them to
575 * the normal VM page queues.
577 * Pages allocated from the alist are wired. We have to
578 * busy, unwire, and free them. We must also adjust
579 * vm_low_phys_reserved before freeing any pages to prevent
580 * confusion.
582 rblk = alist_alloc(&vm_contig_alist, blk, count);
583 if (rblk != blk) {
584 kprintf("vm_page_startup_finish: Unable to return "
585 "dma space @0x%08x/%d -> 0x%08x\n",
586 blk, count, rblk);
587 break;
589 atomic_add_int(&vmstats.v_dma_pages, -count);
590 spin_unlock(&vm_contig_spin);
592 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
593 vm_low_phys_reserved = VM_PAGE_TO_PHYS(m);
594 while (count) {
595 vm_page_busy_wait(m, FALSE, "cpgfr");
596 vm_page_unwire(m, 0);
597 vm_page_free(m);
598 --count;
599 ++m;
601 spin_lock(&vm_contig_spin);
603 spin_unlock(&vm_contig_spin);
606 * Print out how much DMA space drivers have already allocated and
607 * how much is left over.
609 kprintf("DMA space used: %jdk, remaining available: %jdk\n",
610 (intmax_t)(vmstats.v_dma_pages - vm_contig_alist.bl_free) *
611 (PAGE_SIZE / 1024),
612 (intmax_t)vm_contig_alist.bl_free * (PAGE_SIZE / 1024));
614 SYSINIT(vm_pgend, SI_SUB_PROC0_POST, SI_ORDER_ANY,
615 vm_page_startup_finish, NULL);
619 * Scan comparison function for Red-Black tree scans. An inclusive
620 * (start,end) is expected. Other fields are not used.
623 rb_vm_page_scancmp(struct vm_page *p, void *data)
625 struct rb_vm_page_scan_info *info = data;
627 if (p->pindex < info->start_pindex)
628 return(-1);
629 if (p->pindex > info->end_pindex)
630 return(1);
631 return(0);
635 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
637 if (p1->pindex < p2->pindex)
638 return(-1);
639 if (p1->pindex > p2->pindex)
640 return(1);
641 return(0);
644 void
645 vm_page_init(vm_page_t m)
647 /* do nothing for now. Called from pmap_page_init() */
651 * Each page queue has its own spin lock, which is fairly optimal for
652 * allocating and freeing pages at least.
654 * The caller must hold the vm_page_spin_lock() before locking a vm_page's
655 * queue spinlock via this function. Also note that m->queue cannot change
656 * unless both the page and queue are locked.
658 static __inline
659 void
660 _vm_page_queue_spin_lock(vm_page_t m)
662 u_short queue;
664 queue = m->queue;
665 if (queue != PQ_NONE) {
666 spin_lock(&vm_page_queues[queue].spin);
667 KKASSERT(queue == m->queue);
671 static __inline
672 void
673 _vm_page_queue_spin_unlock(vm_page_t m)
675 u_short queue;
677 queue = m->queue;
678 cpu_ccfence();
679 if (queue != PQ_NONE)
680 spin_unlock(&vm_page_queues[queue].spin);
683 static __inline
684 void
685 _vm_page_queues_spin_lock(u_short queue)
687 cpu_ccfence();
688 if (queue != PQ_NONE)
689 spin_lock(&vm_page_queues[queue].spin);
693 static __inline
694 void
695 _vm_page_queues_spin_unlock(u_short queue)
697 cpu_ccfence();
698 if (queue != PQ_NONE)
699 spin_unlock(&vm_page_queues[queue].spin);
702 void
703 vm_page_queue_spin_lock(vm_page_t m)
705 _vm_page_queue_spin_lock(m);
708 void
709 vm_page_queues_spin_lock(u_short queue)
711 _vm_page_queues_spin_lock(queue);
714 void
715 vm_page_queue_spin_unlock(vm_page_t m)
717 _vm_page_queue_spin_unlock(m);
720 void
721 vm_page_queues_spin_unlock(u_short queue)
723 _vm_page_queues_spin_unlock(queue);
727 * This locks the specified vm_page and its queue in the proper order
728 * (page first, then queue). The queue may change so the caller must
729 * recheck on return.
731 static __inline
732 void
733 _vm_page_and_queue_spin_lock(vm_page_t m)
735 vm_page_spin_lock(m);
736 _vm_page_queue_spin_lock(m);
739 static __inline
740 void
741 _vm_page_and_queue_spin_unlock(vm_page_t m)
743 _vm_page_queues_spin_unlock(m->queue);
744 vm_page_spin_unlock(m);
747 void
748 vm_page_and_queue_spin_unlock(vm_page_t m)
750 _vm_page_and_queue_spin_unlock(m);
753 void
754 vm_page_and_queue_spin_lock(vm_page_t m)
756 _vm_page_and_queue_spin_lock(m);
760 * Helper function removes vm_page from its current queue.
761 * Returns the base queue the page used to be on.
763 * The vm_page and the queue must be spinlocked.
764 * This function will unlock the queue but leave the page spinlocked.
766 static __inline u_short
767 _vm_page_rem_queue_spinlocked(vm_page_t m)
769 struct vpgqueues *pq;
770 u_short queue;
771 u_short oqueue;
773 queue = m->queue;
774 if (queue != PQ_NONE) {
775 pq = &vm_page_queues[queue];
776 TAILQ_REMOVE(&pq->pl, m, pageq);
777 atomic_add_int(pq->cnt, -1);
778 pq->lcnt--;
779 m->queue = PQ_NONE;
780 oqueue = queue;
781 queue -= m->pc;
782 vm_page_queues_spin_unlock(oqueue); /* intended */
784 return queue;
788 * Helper function places the vm_page on the specified queue.
790 * The vm_page must be spinlocked.
791 * This function will return with both the page and the queue locked.
793 static __inline void
794 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
796 struct vpgqueues *pq;
798 KKASSERT(m->queue == PQ_NONE);
800 if (queue != PQ_NONE) {
801 vm_page_queues_spin_lock(queue);
802 pq = &vm_page_queues[queue];
803 ++pq->lcnt;
804 atomic_add_int(pq->cnt, 1);
805 m->queue = queue;
808 * PQ_FREE is always handled LIFO style to try to provide
809 * cache-hot pages to programs.
811 if (queue - m->pc == PQ_FREE) {
812 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
813 } else if (athead) {
814 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
815 } else {
816 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
818 /* leave the queue spinlocked */
823 * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
824 * m->busy is zero. Returns TRUE if it had to sleep, FALSE if we
825 * did not. Only one sleep call will be made before returning.
827 * This function does NOT busy the page and on return the page is not
828 * guaranteed to be available.
830 void
831 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
833 u_int32_t flags;
835 for (;;) {
836 flags = m->flags;
837 cpu_ccfence();
839 if ((flags & PG_BUSY) == 0 &&
840 (also_m_busy == 0 || (flags & PG_SBUSY) == 0)) {
841 break;
843 tsleep_interlock(m, 0);
844 if (atomic_cmpset_int(&m->flags, flags,
845 flags | PG_WANTED | PG_REFERENCED)) {
846 tsleep(m, PINTERLOCKED, msg, 0);
847 break;
853 * This calculates and returns a page color given an optional VM object and
854 * either a pindex or an iterator. We attempt to return a cpu-localized
855 * pg_color that is still roughly 16-way set-associative. The CPU topology
856 * is used if it was probed.
858 * The caller may use the returned value to index into e.g. PQ_FREE when
859 * allocating a page in order to nominally obtain pages that are hopefully
860 * already localized to the requesting cpu. This function is not able to
861 * provide any sort of guarantee of this, but does its best to improve
862 * hardware cache management performance.
864 * WARNING! The caller must mask the returned value with PQ_L2_MASK.
866 u_short
867 vm_get_pg_color(globaldata_t gd, vm_object_t object, vm_pindex_t pindex)
869 u_short pg_color;
870 int phys_id;
871 int core_id;
872 int object_pg_color;
874 phys_id = get_cpu_phys_id(gd->gd_cpuid);
875 core_id = get_cpu_core_id(gd->gd_cpuid);
876 object_pg_color = object ? object->pg_color : 0;
878 if (cpu_topology_phys_ids && cpu_topology_core_ids) {
879 int grpsize = PQ_L2_SIZE / cpu_topology_phys_ids;
881 if (grpsize / cpu_topology_core_ids >= PQ_SET_ASSOC) {
883 * Enough space for a full break-down.
885 pg_color = phys_id * grpsize;
886 pg_color += core_id * grpsize / cpu_topology_core_ids;
887 pg_color += (pindex + object_pg_color) %
888 (grpsize / cpu_topology_core_ids);
889 } else {
891 * Not enough space, split up by physical package,
892 * then split up by core id but only down to a
893 * 16-set. If all else fails, force a 16-set.
895 pg_color = phys_id * grpsize;
896 if (grpsize > 16) {
897 pg_color += 16 * (core_id % (grpsize / 16));
898 grpsize = 16;
899 } else {
900 grpsize = 16;
902 pg_color += (pindex + object_pg_color) %
903 grpsize;
905 } else {
907 * Unknown topology, distribute things evenly.
909 pg_color = gd->gd_cpuid * PQ_L2_SIZE / ncpus;
910 pg_color += pindex + object_pg_color;
912 return pg_color;
916 * Wait until PG_BUSY can be set, then set it. If also_m_busy is TRUE we
917 * also wait for m->busy to become 0 before setting PG_BUSY.
919 void
920 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
921 int also_m_busy, const char *msg
922 VM_PAGE_DEBUG_ARGS)
924 u_int32_t flags;
926 for (;;) {
927 flags = m->flags;
928 cpu_ccfence();
929 if (flags & PG_BUSY) {
930 tsleep_interlock(m, 0);
931 if (atomic_cmpset_int(&m->flags, flags,
932 flags | PG_WANTED | PG_REFERENCED)) {
933 tsleep(m, PINTERLOCKED, msg, 0);
935 } else if (also_m_busy && (flags & PG_SBUSY)) {
936 tsleep_interlock(m, 0);
937 if (atomic_cmpset_int(&m->flags, flags,
938 flags | PG_WANTED | PG_REFERENCED)) {
939 tsleep(m, PINTERLOCKED, msg, 0);
941 } else {
942 if (atomic_cmpset_int(&m->flags, flags,
943 flags | PG_BUSY)) {
944 #ifdef VM_PAGE_DEBUG
945 m->busy_func = func;
946 m->busy_line = lineno;
947 #endif
948 break;
955 * Attempt to set PG_BUSY. If also_m_busy is TRUE we only succeed if m->busy
956 * is also 0.
958 * Returns non-zero on failure.
961 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
962 VM_PAGE_DEBUG_ARGS)
964 u_int32_t flags;
966 for (;;) {
967 flags = m->flags;
968 cpu_ccfence();
969 if (flags & PG_BUSY)
970 return TRUE;
971 if (also_m_busy && (flags & PG_SBUSY))
972 return TRUE;
973 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
974 #ifdef VM_PAGE_DEBUG
975 m->busy_func = func;
976 m->busy_line = lineno;
977 #endif
978 return FALSE;
984 * Clear the PG_BUSY flag and return non-zero to indicate to the caller
985 * that a wakeup() should be performed.
987 * The vm_page must be spinlocked and will remain spinlocked on return.
988 * The related queue must NOT be spinlocked (which could deadlock us).
990 * (inline version)
992 static __inline
994 _vm_page_wakeup(vm_page_t m)
996 u_int32_t flags;
998 for (;;) {
999 flags = m->flags;
1000 cpu_ccfence();
1001 if (atomic_cmpset_int(&m->flags, flags,
1002 flags & ~(PG_BUSY | PG_WANTED))) {
1003 break;
1006 return(flags & PG_WANTED);
1010 * Clear the PG_BUSY flag and wakeup anyone waiting for the page. This
1011 * is typically the last call you make on a page before moving onto
1012 * other things.
1014 void
1015 vm_page_wakeup(vm_page_t m)
1017 KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
1018 vm_page_spin_lock(m);
1019 if (_vm_page_wakeup(m)) {
1020 vm_page_spin_unlock(m);
1021 wakeup(m);
1022 } else {
1023 vm_page_spin_unlock(m);
1028 * Holding a page keeps it from being reused. Other parts of the system
1029 * can still disassociate the page from its current object and free it, or
1030 * perform read or write I/O on it and/or otherwise manipulate the page,
1031 * but if the page is held the VM system will leave the page and its data
1032 * intact and not reuse the page for other purposes until the last hold
1033 * reference is released. (see vm_page_wire() if you want to prevent the
1034 * page from being disassociated from its object too).
1036 * The caller must still validate the contents of the page and, if necessary,
1037 * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
1038 * before manipulating the page.
1040 * XXX get vm_page_spin_lock() here and move FREE->HOLD if necessary
1042 void
1043 vm_page_hold(vm_page_t m)
1045 vm_page_spin_lock(m);
1046 atomic_add_int(&m->hold_count, 1);
1047 if (m->queue - m->pc == PQ_FREE) {
1048 _vm_page_queue_spin_lock(m);
1049 _vm_page_rem_queue_spinlocked(m);
1050 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
1051 _vm_page_queue_spin_unlock(m);
1053 vm_page_spin_unlock(m);
1057 * The opposite of vm_page_hold(). If the page is on the HOLD queue
1058 * it was freed while held and must be moved back to the FREE queue.
1060 void
1061 vm_page_unhold(vm_page_t m)
1063 KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1064 ("vm_page_unhold: pg %p illegal hold_count (%d) or on FREE queue (%d)",
1065 m, m->hold_count, m->queue - m->pc));
1066 vm_page_spin_lock(m);
1067 atomic_add_int(&m->hold_count, -1);
1068 if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1069 _vm_page_queue_spin_lock(m);
1070 _vm_page_rem_queue_spinlocked(m);
1071 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
1072 _vm_page_queue_spin_unlock(m);
1074 vm_page_spin_unlock(m);
1078 * vm_page_getfake:
1080 * Create a fictitious page with the specified physical address and
1081 * memory attribute. The memory attribute is the only the machine-
1082 * dependent aspect of a fictitious page that must be initialized.
1085 void
1086 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1089 if ((m->flags & PG_FICTITIOUS) != 0) {
1091 * The page's memattr might have changed since the
1092 * previous initialization. Update the pmap to the
1093 * new memattr.
1095 goto memattr;
1097 m->phys_addr = paddr;
1098 m->queue = PQ_NONE;
1099 /* Fictitious pages don't use "segind". */
1100 /* Fictitious pages don't use "order" or "pool". */
1101 m->flags = PG_FICTITIOUS | PG_UNMANAGED | PG_BUSY;
1102 m->wire_count = 1;
1103 pmap_page_init(m);
1104 memattr:
1105 pmap_page_set_memattr(m, memattr);
1109 * Inserts the given vm_page into the object and object list.
1111 * The pagetables are not updated but will presumably fault the page
1112 * in if necessary, or if a kernel page the caller will at some point
1113 * enter the page into the kernel's pmap. We are not allowed to block
1114 * here so we *can't* do this anyway.
1116 * This routine may not block.
1117 * This routine must be called with the vm_object held.
1118 * This routine must be called with a critical section held.
1120 * This routine returns TRUE if the page was inserted into the object
1121 * successfully, and FALSE if the page already exists in the object.
1124 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1126 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1127 if (m->object != NULL)
1128 panic("vm_page_insert: already inserted");
1130 object->generation++;
1133 * Record the object/offset pair in this page and add the
1134 * pv_list_count of the page to the object.
1136 * The vm_page spin lock is required for interactions with the pmap.
1138 vm_page_spin_lock(m);
1139 m->object = object;
1140 m->pindex = pindex;
1141 if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1142 m->object = NULL;
1143 m->pindex = 0;
1144 vm_page_spin_unlock(m);
1145 return FALSE;
1147 ++object->resident_page_count;
1148 ++mycpu->gd_vmtotal.t_rm;
1149 /* atomic_add_int(&object->agg_pv_list_count, m->md.pv_list_count); */
1150 vm_page_spin_unlock(m);
1153 * Since we are inserting a new and possibly dirty page,
1154 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1156 if ((m->valid & m->dirty) ||
1157 (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1158 vm_object_set_writeable_dirty(object);
1161 * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1163 swap_pager_page_inserted(m);
1164 return TRUE;
1168 * Removes the given vm_page_t from the (object,index) table
1170 * The underlying pmap entry (if any) is NOT removed here.
1171 * This routine may not block.
1173 * The page must be BUSY and will remain BUSY on return.
1174 * No other requirements.
1176 * NOTE: FreeBSD side effect was to unbusy the page on return. We leave
1177 * it busy.
1179 void
1180 vm_page_remove(vm_page_t m)
1182 vm_object_t object;
1184 if (m->object == NULL) {
1185 return;
1188 if ((m->flags & PG_BUSY) == 0)
1189 panic("vm_page_remove: page not busy");
1191 object = m->object;
1193 vm_object_hold(object);
1196 * Remove the page from the object and update the object.
1198 * The vm_page spin lock is required for interactions with the pmap.
1200 vm_page_spin_lock(m);
1201 vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1202 --object->resident_page_count;
1203 --mycpu->gd_vmtotal.t_rm;
1204 /* atomic_add_int(&object->agg_pv_list_count, -m->md.pv_list_count); */
1205 m->object = NULL;
1206 vm_page_spin_unlock(m);
1208 object->generation++;
1210 vm_object_drop(object);
1214 * Locate and return the page at (object, pindex), or NULL if the
1215 * page could not be found.
1217 * The caller must hold the vm_object token.
1219 vm_page_t
1220 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1222 vm_page_t m;
1225 * Search the hash table for this object/offset pair
1227 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1228 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1229 KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
1230 return(m);
1233 vm_page_t
1234 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1235 vm_pindex_t pindex,
1236 int also_m_busy, const char *msg
1237 VM_PAGE_DEBUG_ARGS)
1239 u_int32_t flags;
1240 vm_page_t m;
1242 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1243 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1244 while (m) {
1245 KKASSERT(m->object == object && m->pindex == pindex);
1246 flags = m->flags;
1247 cpu_ccfence();
1248 if (flags & PG_BUSY) {
1249 tsleep_interlock(m, 0);
1250 if (atomic_cmpset_int(&m->flags, flags,
1251 flags | PG_WANTED | PG_REFERENCED)) {
1252 tsleep(m, PINTERLOCKED, msg, 0);
1253 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1254 pindex);
1256 } else if (also_m_busy && (flags & PG_SBUSY)) {
1257 tsleep_interlock(m, 0);
1258 if (atomic_cmpset_int(&m->flags, flags,
1259 flags | PG_WANTED | PG_REFERENCED)) {
1260 tsleep(m, PINTERLOCKED, msg, 0);
1261 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1262 pindex);
1264 } else if (atomic_cmpset_int(&m->flags, flags,
1265 flags | PG_BUSY)) {
1266 #ifdef VM_PAGE_DEBUG
1267 m->busy_func = func;
1268 m->busy_line = lineno;
1269 #endif
1270 break;
1273 return m;
1277 * Attempt to lookup and busy a page.
1279 * Returns NULL if the page could not be found
1281 * Returns a vm_page and error == TRUE if the page exists but could not
1282 * be busied.
1284 * Returns a vm_page and error == FALSE on success.
1286 vm_page_t
1287 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1288 vm_pindex_t pindex,
1289 int also_m_busy, int *errorp
1290 VM_PAGE_DEBUG_ARGS)
1292 u_int32_t flags;
1293 vm_page_t m;
1295 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1296 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1297 *errorp = FALSE;
1298 while (m) {
1299 KKASSERT(m->object == object && m->pindex == pindex);
1300 flags = m->flags;
1301 cpu_ccfence();
1302 if (flags & PG_BUSY) {
1303 *errorp = TRUE;
1304 break;
1306 if (also_m_busy && (flags & PG_SBUSY)) {
1307 *errorp = TRUE;
1308 break;
1310 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
1311 #ifdef VM_PAGE_DEBUG
1312 m->busy_func = func;
1313 m->busy_line = lineno;
1314 #endif
1315 break;
1318 return m;
1322 * Attempt to repurpose the passed-in page. If the passed-in page cannot
1323 * be repurposed it will be released, *must_reenter will be set to 1, and
1324 * this function will fall-through to vm_page_lookup_busy_try().
1326 * The passed-in page must be wired and not busy. The returned page will
1327 * be busied and not wired.
1329 * A different page may be returned. The returned page will be busied and
1330 * not wired.
1332 * NULL can be returned. If so, the required page could not be busied.
1333 * The passed-in page will be unwired.
1335 vm_page_t
1336 vm_page_repurpose(struct vm_object *object, vm_pindex_t pindex,
1337 int also_m_busy, int *errorp, vm_page_t m,
1338 int *must_reenter, int *iswired)
1340 if (m) {
1342 * Do not mess with pages in a complex state, such as pages
1343 * which are mapped, as repurposing such pages can be more
1344 * expensive than simply allocatin a new one.
1346 * NOTE: Soft-busying can deadlock against putpages or I/O
1347 * so we only allow hard-busying here.
1349 KKASSERT(also_m_busy == FALSE);
1350 vm_page_busy_wait(m, also_m_busy, "biodep");
1352 if ((m->flags & (PG_UNMANAGED | PG_MAPPED |
1353 PG_FICTITIOUS | PG_SBUSY)) ||
1354 m->busy || m->wire_count != 1 || m->hold_count) {
1355 vm_page_unwire(m, 0);
1356 vm_page_wakeup(m);
1357 /* fall through to normal lookup */
1358 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
1359 vm_page_unwire(m, 0);
1360 vm_page_deactivate(m);
1361 vm_page_wakeup(m);
1362 /* fall through to normal lookup */
1363 } else {
1365 * We can safely repurpose the page. It should
1366 * already be unqueued.
1368 KKASSERT(m->queue == PQ_NONE && m->dirty == 0);
1369 vm_page_remove(m);
1370 m->valid = 0;
1371 m->act_count = 0;
1372 if (vm_page_insert(m, object, pindex)) {
1373 *errorp = 0;
1374 *iswired = 1;
1376 return m;
1378 vm_page_unwire(m, 0);
1379 vm_page_free(m);
1380 /* fall through to normal lookup */
1385 * Cannot repurpose page, attempt to locate the desired page. May
1386 * return NULL.
1388 *must_reenter = 1;
1389 *iswired = 0;
1390 m = vm_page_lookup_busy_try(object, pindex, also_m_busy, errorp);
1392 return m;
1396 * Caller must hold the related vm_object
1398 vm_page_t
1399 vm_page_next(vm_page_t m)
1401 vm_page_t next;
1403 next = vm_page_rb_tree_RB_NEXT(m);
1404 if (next && next->pindex != m->pindex + 1)
1405 next = NULL;
1406 return (next);
1410 * vm_page_rename()
1412 * Move the given vm_page from its current object to the specified
1413 * target object/offset. The page must be busy and will remain so
1414 * on return.
1416 * new_object must be held.
1417 * This routine might block. XXX ?
1419 * NOTE: Swap associated with the page must be invalidated by the move. We
1420 * have to do this for several reasons: (1) we aren't freeing the
1421 * page, (2) we are dirtying the page, (3) the VM system is probably
1422 * moving the page from object A to B, and will then later move
1423 * the backing store from A to B and we can't have a conflict.
1425 * NOTE: We *always* dirty the page. It is necessary both for the
1426 * fact that we moved it, and because we may be invalidating
1427 * swap. If the page is on the cache, we have to deactivate it
1428 * or vm_page_dirty() will panic. Dirty pages are not allowed
1429 * on the cache.
1431 void
1432 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1434 KKASSERT(m->flags & PG_BUSY);
1435 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1436 if (m->object) {
1437 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1438 vm_page_remove(m);
1440 if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1441 panic("vm_page_rename: target exists (%p,%"PRIu64")",
1442 new_object, new_pindex);
1444 if (m->queue - m->pc == PQ_CACHE)
1445 vm_page_deactivate(m);
1446 vm_page_dirty(m);
1450 * vm_page_unqueue() without any wakeup. This routine is used when a page
1451 * is to remain BUSYied by the caller.
1453 * This routine may not block.
1455 void
1456 vm_page_unqueue_nowakeup(vm_page_t m)
1458 vm_page_and_queue_spin_lock(m);
1459 (void)_vm_page_rem_queue_spinlocked(m);
1460 vm_page_spin_unlock(m);
1464 * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1465 * if necessary.
1467 * This routine may not block.
1469 void
1470 vm_page_unqueue(vm_page_t m)
1472 u_short queue;
1474 vm_page_and_queue_spin_lock(m);
1475 queue = _vm_page_rem_queue_spinlocked(m);
1476 if (queue == PQ_FREE || queue == PQ_CACHE) {
1477 vm_page_spin_unlock(m);
1478 pagedaemon_wakeup();
1479 } else {
1480 vm_page_spin_unlock(m);
1485 * vm_page_list_find()
1487 * Find a page on the specified queue with color optimization.
1489 * The page coloring optimization attempts to locate a page that does
1490 * not overload other nearby pages in the object in the cpu's L1 or L2
1491 * caches. We need this optimization because cpu caches tend to be
1492 * physical caches, while object spaces tend to be virtual.
1494 * The page coloring optimization also, very importantly, tries to localize
1495 * memory to cpus and physical sockets.
1497 * On MP systems each PQ_FREE and PQ_CACHE color queue has its own spinlock
1498 * and the algorithm is adjusted to localize allocations on a per-core basis.
1499 * This is done by 'twisting' the colors.
1501 * The page is returned spinlocked and removed from its queue (it will
1502 * be on PQ_NONE), or NULL. The page is not PG_BUSY'd. The caller
1503 * is responsible for dealing with the busy-page case (usually by
1504 * deactivating the page and looping).
1506 * NOTE: This routine is carefully inlined. A non-inlined version
1507 * is available for outside callers but the only critical path is
1508 * from within this source file.
1510 * NOTE: This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1511 * represent stable storage, allowing us to order our locks vm_page
1512 * first, then queue.
1514 static __inline
1515 vm_page_t
1516 _vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1518 vm_page_t m;
1520 for (;;) {
1521 if (prefer_zero) {
1522 m = TAILQ_LAST(&vm_page_queues[basequeue+index].pl,
1523 pglist);
1524 } else {
1525 m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
1527 if (m == NULL) {
1528 m = _vm_page_list_find2(basequeue, index);
1529 return(m);
1531 vm_page_and_queue_spin_lock(m);
1532 if (m->queue == basequeue + index) {
1533 _vm_page_rem_queue_spinlocked(m);
1534 /* vm_page_t spin held, no queue spin */
1535 break;
1537 vm_page_and_queue_spin_unlock(m);
1539 return(m);
1543 * If we could not find the page in the desired queue try to find it in
1544 * a nearby queue.
1546 static vm_page_t
1547 _vm_page_list_find2(int basequeue, int index)
1549 struct vpgqueues *pq;
1550 vm_page_t m = NULL;
1551 int pqmask = PQ_SET_ASSOC_MASK >> 1;
1552 int pqi;
1553 int i;
1555 index &= PQ_L2_MASK;
1556 pq = &vm_page_queues[basequeue];
1559 * Run local sets of 16, 32, 64, 128, and the whole queue if all
1560 * else fails (PQ_L2_MASK which is 255).
1562 do {
1563 pqmask = (pqmask << 1) | 1;
1564 for (i = 0; i <= pqmask; ++i) {
1565 pqi = (index & ~pqmask) | ((index + i) & pqmask);
1566 m = TAILQ_FIRST(&pq[pqi].pl);
1567 if (m) {
1568 _vm_page_and_queue_spin_lock(m);
1569 if (m->queue == basequeue + pqi) {
1570 _vm_page_rem_queue_spinlocked(m);
1571 return(m);
1573 _vm_page_and_queue_spin_unlock(m);
1574 --i;
1575 continue;
1578 } while (pqmask != PQ_L2_MASK);
1580 return(m);
1584 * Returns a vm_page candidate for allocation. The page is not busied so
1585 * it can move around. The caller must busy the page (and typically
1586 * deactivate it if it cannot be busied!)
1588 * Returns a spinlocked vm_page that has been removed from its queue.
1590 vm_page_t
1591 vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1593 return(_vm_page_list_find(basequeue, index, prefer_zero));
1597 * Find a page on the cache queue with color optimization, remove it
1598 * from the queue, and busy it. The returned page will not be spinlocked.
1600 * A candidate failure will be deactivated. Candidates can fail due to
1601 * being busied by someone else, in which case they will be deactivated.
1603 * This routine may not block.
1606 static vm_page_t
1607 vm_page_select_cache(u_short pg_color)
1609 vm_page_t m;
1611 for (;;) {
1612 m = _vm_page_list_find(PQ_CACHE, pg_color & PQ_L2_MASK, FALSE);
1613 if (m == NULL)
1614 break;
1616 * (m) has been removed from its queue and spinlocked
1618 if (vm_page_busy_try(m, TRUE)) {
1619 _vm_page_deactivate_locked(m, 0);
1620 vm_page_spin_unlock(m);
1621 } else {
1623 * We successfully busied the page
1625 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) == 0 &&
1626 m->hold_count == 0 &&
1627 m->wire_count == 0 &&
1628 (m->dirty & m->valid) == 0) {
1629 vm_page_spin_unlock(m);
1630 pagedaemon_wakeup();
1631 return(m);
1635 * The page cannot be recycled, deactivate it.
1637 _vm_page_deactivate_locked(m, 0);
1638 if (_vm_page_wakeup(m)) {
1639 vm_page_spin_unlock(m);
1640 wakeup(m);
1641 } else {
1642 vm_page_spin_unlock(m);
1646 return (m);
1650 * Find a free or zero page, with specified preference. We attempt to
1651 * inline the nominal case and fall back to _vm_page_select_free()
1652 * otherwise. A busied page is removed from the queue and returned.
1654 * This routine may not block.
1656 static __inline vm_page_t
1657 vm_page_select_free(u_short pg_color, boolean_t prefer_zero)
1659 vm_page_t m;
1661 for (;;) {
1662 m = _vm_page_list_find(PQ_FREE, pg_color & PQ_L2_MASK,
1663 prefer_zero);
1664 if (m == NULL)
1665 break;
1666 if (vm_page_busy_try(m, TRUE)) {
1668 * Various mechanisms such as a pmap_collect can
1669 * result in a busy page on the free queue. We
1670 * have to move the page out of the way so we can
1671 * retry the allocation. If the other thread is not
1672 * allocating the page then m->valid will remain 0 and
1673 * the pageout daemon will free the page later on.
1675 * Since we could not busy the page, however, we
1676 * cannot make assumptions as to whether the page
1677 * will be allocated by the other thread or not,
1678 * so all we can do is deactivate it to move it out
1679 * of the way. In particular, if the other thread
1680 * wires the page it may wind up on the inactive
1681 * queue and the pageout daemon will have to deal
1682 * with that case too.
1684 _vm_page_deactivate_locked(m, 0);
1685 vm_page_spin_unlock(m);
1686 } else {
1688 * Theoretically if we are able to busy the page
1689 * atomic with the queue removal (using the vm_page
1690 * lock) nobody else should be able to mess with the
1691 * page before us.
1693 KKASSERT((m->flags & (PG_UNMANAGED |
1694 PG_NEED_COMMIT)) == 0);
1695 KASSERT(m->hold_count == 0, ("m->hold_count is not zero "
1696 "pg %p q=%d flags=%08x hold=%d wire=%d",
1697 m, m->queue, m->flags, m->hold_count, m->wire_count));
1698 KKASSERT(m->wire_count == 0);
1699 vm_page_spin_unlock(m);
1700 pagedaemon_wakeup();
1702 /* return busied and removed page */
1703 return(m);
1706 return(m);
1710 * vm_page_alloc()
1712 * Allocate and return a memory cell associated with this VM object/offset
1713 * pair. If object is NULL an unassociated page will be allocated.
1715 * The returned page will be busied and removed from its queues. This
1716 * routine can block and may return NULL if a race occurs and the page
1717 * is found to already exist at the specified (object, pindex).
1719 * VM_ALLOC_NORMAL allow use of cache pages, nominal free drain
1720 * VM_ALLOC_QUICK like normal but cannot use cache
1721 * VM_ALLOC_SYSTEM greater free drain
1722 * VM_ALLOC_INTERRUPT allow free list to be completely drained
1723 * VM_ALLOC_ZERO advisory request for pre-zero'd page only
1724 * VM_ALLOC_FORCE_ZERO advisory request for pre-zero'd page only
1725 * VM_ALLOC_NULL_OK ok to return NULL on insertion collision
1726 * (see vm_page_grab())
1727 * VM_ALLOC_USE_GD ok to use per-gd cache
1729 * The object must be held if not NULL
1730 * This routine may not block
1732 * Additional special handling is required when called from an interrupt
1733 * (VM_ALLOC_INTERRUPT). We are not allowed to mess with the page cache
1734 * in this case.
1736 vm_page_t
1737 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
1739 globaldata_t gd = mycpu;
1740 vm_object_t obj;
1741 vm_page_t m;
1742 u_short pg_color;
1744 #if 0
1746 * Special per-cpu free VM page cache. The pages are pre-busied
1747 * and pre-zerod for us.
1749 if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
1750 crit_enter_gd(gd);
1751 if (gd->gd_vmpg_count) {
1752 m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
1753 crit_exit_gd(gd);
1754 goto done;
1756 crit_exit_gd(gd);
1758 #endif
1759 m = NULL;
1762 * CPU LOCALIZATION
1764 * CPU localization algorithm. Break the page queues up by physical
1765 * id and core id (note that two cpu threads will have the same core
1766 * id, and core_id != gd_cpuid).
1768 * This is nowhere near perfect, for example the last pindex in a
1769 * subgroup will overflow into the next cpu or package. But this
1770 * should get us good page reuse locality in heavy mixed loads.
1772 pg_color = vm_get_pg_color(gd, object, pindex);
1774 KKASSERT(page_req &
1775 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
1776 VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1779 * Certain system threads (pageout daemon, buf_daemon's) are
1780 * allowed to eat deeper into the free page list.
1782 if (curthread->td_flags & TDF_SYSTHREAD)
1783 page_req |= VM_ALLOC_SYSTEM;
1786 * Impose various limitations. Note that the v_free_reserved test
1787 * must match the opposite of vm_page_count_target() to avoid
1788 * livelocks, be careful.
1790 loop:
1791 if (vmstats.v_free_count >= vmstats.v_free_reserved ||
1792 ((page_req & VM_ALLOC_INTERRUPT) && vmstats.v_free_count > 0) ||
1793 ((page_req & VM_ALLOC_SYSTEM) && vmstats.v_cache_count == 0 &&
1794 vmstats.v_free_count > vmstats.v_interrupt_free_min)
1797 * The free queue has sufficient free pages to take one out.
1799 if (page_req & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO))
1800 m = vm_page_select_free(pg_color, TRUE);
1801 else
1802 m = vm_page_select_free(pg_color, FALSE);
1803 } else if (page_req & VM_ALLOC_NORMAL) {
1805 * Allocatable from the cache (non-interrupt only). On
1806 * success, we must free the page and try again, thus
1807 * ensuring that vmstats.v_*_free_min counters are replenished.
1809 #ifdef INVARIANTS
1810 if (curthread->td_preempted) {
1811 kprintf("vm_page_alloc(): warning, attempt to allocate"
1812 " cache page from preempting interrupt\n");
1813 m = NULL;
1814 } else {
1815 m = vm_page_select_cache(pg_color);
1817 #else
1818 m = vm_page_select_cache(pg_color);
1819 #endif
1821 * On success move the page into the free queue and loop.
1823 * Only do this if we can safely acquire the vm_object lock,
1824 * because this is effectively a random page and the caller
1825 * might be holding the lock shared, we don't want to
1826 * deadlock.
1828 if (m != NULL) {
1829 KASSERT(m->dirty == 0,
1830 ("Found dirty cache page %p", m));
1831 if ((obj = m->object) != NULL) {
1832 if (vm_object_hold_try(obj)) {
1833 vm_page_protect(m, VM_PROT_NONE);
1834 vm_page_free(m);
1835 /* m->object NULL here */
1836 vm_object_drop(obj);
1837 } else {
1838 vm_page_deactivate(m);
1839 vm_page_wakeup(m);
1841 } else {
1842 vm_page_protect(m, VM_PROT_NONE);
1843 vm_page_free(m);
1845 goto loop;
1849 * On failure return NULL
1851 #if defined(DIAGNOSTIC)
1852 if (vmstats.v_cache_count > 0)
1853 kprintf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", vmstats.v_cache_count);
1854 #endif
1855 atomic_add_int(&vm_pageout_deficit, 1);
1856 pagedaemon_wakeup();
1857 return (NULL);
1858 } else {
1860 * No pages available, wakeup the pageout daemon and give up.
1862 atomic_add_int(&vm_pageout_deficit, 1);
1863 pagedaemon_wakeup();
1864 return (NULL);
1868 * v_free_count can race so loop if we don't find the expected
1869 * page.
1871 if (m == NULL)
1872 goto loop;
1875 * Good page found. The page has already been busied for us and
1876 * removed from its queues.
1878 KASSERT(m->dirty == 0,
1879 ("vm_page_alloc: free/cache page %p was dirty", m));
1880 KKASSERT(m->queue == PQ_NONE);
1882 #if 0
1883 done:
1884 #endif
1886 * Initialize the structure, inheriting some flags but clearing
1887 * all the rest. The page has already been busied for us.
1889 vm_page_flag_clear(m, ~(PG_BUSY | PG_SBUSY));
1890 KKASSERT(m->wire_count == 0);
1891 KKASSERT(m->busy == 0);
1892 m->act_count = 0;
1893 m->valid = 0;
1896 * Caller must be holding the object lock (asserted by
1897 * vm_page_insert()).
1899 * NOTE: Inserting a page here does not insert it into any pmaps
1900 * (which could cause us to block allocating memory).
1902 * NOTE: If no object an unassociated page is allocated, m->pindex
1903 * can be used by the caller for any purpose.
1905 if (object) {
1906 if (vm_page_insert(m, object, pindex) == FALSE) {
1907 vm_page_free(m);
1908 if ((page_req & VM_ALLOC_NULL_OK) == 0)
1909 panic("PAGE RACE %p[%ld]/%p",
1910 object, (long)pindex, m);
1911 m = NULL;
1913 } else {
1914 m->pindex = pindex;
1918 * Don't wakeup too often - wakeup the pageout daemon when
1919 * we would be nearly out of memory.
1921 pagedaemon_wakeup();
1924 * A PG_BUSY page is returned.
1926 return (m);
1930 * Returns number of pages available in our DMA memory reserve
1931 * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
1933 vm_size_t
1934 vm_contig_avail_pages(void)
1936 alist_blk_t blk;
1937 alist_blk_t count;
1938 alist_blk_t bfree;
1939 spin_lock(&vm_contig_spin);
1940 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
1941 spin_unlock(&vm_contig_spin);
1943 return bfree;
1947 * Attempt to allocate contiguous physical memory with the specified
1948 * requirements.
1950 vm_page_t
1951 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
1952 unsigned long alignment, unsigned long boundary,
1953 unsigned long size, vm_memattr_t memattr)
1955 alist_blk_t blk;
1956 vm_page_t m;
1957 int i;
1959 alignment >>= PAGE_SHIFT;
1960 if (alignment == 0)
1961 alignment = 1;
1962 boundary >>= PAGE_SHIFT;
1963 if (boundary == 0)
1964 boundary = 1;
1965 size = (size + PAGE_MASK) >> PAGE_SHIFT;
1967 spin_lock(&vm_contig_spin);
1968 blk = alist_alloc(&vm_contig_alist, 0, size);
1969 if (blk == ALIST_BLOCK_NONE) {
1970 spin_unlock(&vm_contig_spin);
1971 if (bootverbose) {
1972 kprintf("vm_page_alloc_contig: %ldk nospace\n",
1973 (size + PAGE_MASK) * (PAGE_SIZE / 1024));
1975 return(NULL);
1977 if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
1978 alist_free(&vm_contig_alist, blk, size);
1979 spin_unlock(&vm_contig_spin);
1980 if (bootverbose) {
1981 kprintf("vm_page_alloc_contig: %ldk high "
1982 "%016jx failed\n",
1983 (size + PAGE_MASK) * (PAGE_SIZE / 1024),
1984 (intmax_t)high);
1986 return(NULL);
1988 spin_unlock(&vm_contig_spin);
1989 if (vm_contig_verbose) {
1990 kprintf("vm_page_alloc_contig: %016jx/%ldk\n",
1991 (intmax_t)(vm_paddr_t)blk << PAGE_SHIFT,
1992 (size + PAGE_MASK) * (PAGE_SIZE / 1024));
1995 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
1996 if (memattr != VM_MEMATTR_DEFAULT)
1997 for (i = 0;i < size;i++)
1998 pmap_page_set_memattr(&m[i], memattr);
1999 return m;
2003 * Free contiguously allocated pages. The pages will be wired but not busy.
2004 * When freeing to the alist we leave them wired and not busy.
2006 void
2007 vm_page_free_contig(vm_page_t m, unsigned long size)
2009 vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2010 vm_pindex_t start = pa >> PAGE_SHIFT;
2011 vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2013 if (vm_contig_verbose) {
2014 kprintf("vm_page_free_contig: %016jx/%ldk\n",
2015 (intmax_t)pa, size / 1024);
2017 if (pa < vm_low_phys_reserved) {
2018 KKASSERT(pa + size <= vm_low_phys_reserved);
2019 spin_lock(&vm_contig_spin);
2020 alist_free(&vm_contig_alist, start, pages);
2021 spin_unlock(&vm_contig_spin);
2022 } else {
2023 while (pages) {
2024 vm_page_busy_wait(m, FALSE, "cpgfr");
2025 vm_page_unwire(m, 0);
2026 vm_page_free(m);
2027 --pages;
2028 ++m;
2036 * Wait for sufficient free memory for nominal heavy memory use kernel
2037 * operations.
2039 * WARNING! Be sure never to call this in any vm_pageout code path, which
2040 * will trivially deadlock the system.
2042 void
2043 vm_wait_nominal(void)
2045 while (vm_page_count_min(0))
2046 vm_wait(0);
2050 * Test if vm_wait_nominal() would block.
2053 vm_test_nominal(void)
2055 if (vm_page_count_min(0))
2056 return(1);
2057 return(0);
2061 * Block until free pages are available for allocation, called in various
2062 * places before memory allocations.
2064 * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2065 * more generous then that.
2067 void
2068 vm_wait(int timo)
2071 * never wait forever
2073 if (timo == 0)
2074 timo = hz;
2075 lwkt_gettoken(&vm_token);
2077 if (curthread == pagethread) {
2079 * The pageout daemon itself needs pages, this is bad.
2081 if (vm_page_count_min(0)) {
2082 vm_pageout_pages_needed = 1;
2083 tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2085 } else {
2087 * Wakeup the pageout daemon if necessary and wait.
2089 * Do not wait indefinitely for the target to be reached,
2090 * as load might prevent it from being reached any time soon.
2091 * But wait a little to try to slow down page allocations
2092 * and to give more important threads (the pagedaemon)
2093 * allocation priority.
2095 if (vm_page_count_target()) {
2096 if (vm_pages_needed == 0) {
2097 vm_pages_needed = 1;
2098 wakeup(&vm_pages_needed);
2100 ++vm_pages_waiting; /* SMP race ok */
2101 tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2104 lwkt_reltoken(&vm_token);
2108 * Block until free pages are available for allocation
2110 * Called only from vm_fault so that processes page faulting can be
2111 * easily tracked.
2113 void
2114 vm_wait_pfault(void)
2117 * Wakeup the pageout daemon if necessary and wait.
2119 * Do not wait indefinitely for the target to be reached,
2120 * as load might prevent it from being reached any time soon.
2121 * But wait a little to try to slow down page allocations
2122 * and to give more important threads (the pagedaemon)
2123 * allocation priority.
2125 if (vm_page_count_min(0)) {
2126 lwkt_gettoken(&vm_token);
2127 while (vm_page_count_severe()) {
2128 if (vm_page_count_target()) {
2129 thread_t td;
2131 if (vm_pages_needed == 0) {
2132 vm_pages_needed = 1;
2133 wakeup(&vm_pages_needed);
2135 ++vm_pages_waiting; /* SMP race ok */
2136 tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2139 * Do not stay stuck in the loop if the system is trying
2140 * to kill the process.
2142 td = curthread;
2143 if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2144 break;
2147 lwkt_reltoken(&vm_token);
2152 * Put the specified page on the active list (if appropriate). Ensure
2153 * that act_count is at least ACT_INIT but do not otherwise mess with it.
2155 * The caller should be holding the page busied ? XXX
2156 * This routine may not block.
2158 void
2159 vm_page_activate(vm_page_t m)
2161 u_short oqueue;
2163 vm_page_spin_lock(m);
2164 if (m->queue - m->pc != PQ_ACTIVE) {
2165 _vm_page_queue_spin_lock(m);
2166 oqueue = _vm_page_rem_queue_spinlocked(m);
2167 /* page is left spinlocked, queue is unlocked */
2169 if (oqueue == PQ_CACHE)
2170 mycpu->gd_cnt.v_reactivated++;
2171 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2172 if (m->act_count < ACT_INIT)
2173 m->act_count = ACT_INIT;
2174 _vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2176 _vm_page_and_queue_spin_unlock(m);
2177 if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2178 pagedaemon_wakeup();
2179 } else {
2180 if (m->act_count < ACT_INIT)
2181 m->act_count = ACT_INIT;
2182 vm_page_spin_unlock(m);
2187 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2188 * routine is called when a page has been added to the cache or free
2189 * queues.
2191 * This routine may not block.
2193 static __inline void
2194 vm_page_free_wakeup(void)
2197 * If the pageout daemon itself needs pages, then tell it that
2198 * there are some free.
2200 if (vm_pageout_pages_needed &&
2201 vmstats.v_cache_count + vmstats.v_free_count >=
2202 vmstats.v_pageout_free_min
2204 vm_pageout_pages_needed = 0;
2205 wakeup(&vm_pageout_pages_needed);
2209 * Wakeup processes that are waiting on memory.
2211 * Generally speaking we want to wakeup stuck processes as soon as
2212 * possible. !vm_page_count_min(0) is the absolute minimum point
2213 * where we can do this. Wait a bit longer to reduce degenerate
2214 * re-blocking (vm_page_free_hysteresis). The target check is just
2215 * to make sure the min-check w/hysteresis does not exceed the
2216 * normal target.
2218 if (vm_pages_waiting) {
2219 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2220 !vm_page_count_target()) {
2221 vm_pages_waiting = 0;
2222 wakeup(&vmstats.v_free_count);
2223 ++mycpu->gd_cnt.v_ppwakeups;
2225 #if 0
2226 if (!vm_page_count_target()) {
2228 * Plenty of pages are free, wakeup everyone.
2230 vm_pages_waiting = 0;
2231 wakeup(&vmstats.v_free_count);
2232 ++mycpu->gd_cnt.v_ppwakeups;
2233 } else if (!vm_page_count_min(0)) {
2235 * Some pages are free, wakeup someone.
2237 int wcount = vm_pages_waiting;
2238 if (wcount > 0)
2239 --wcount;
2240 vm_pages_waiting = wcount;
2241 wakeup_one(&vmstats.v_free_count);
2242 ++mycpu->gd_cnt.v_ppwakeups;
2244 #endif
2249 * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2250 * it from its VM object.
2252 * The vm_page must be PG_BUSY on entry. PG_BUSY will be released on
2253 * return (the page will have been freed).
2255 void
2256 vm_page_free_toq(vm_page_t m)
2258 mycpu->gd_cnt.v_tfree++;
2259 KKASSERT((m->flags & PG_MAPPED) == 0);
2260 KKASSERT(m->flags & PG_BUSY);
2262 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
2263 kprintf("vm_page_free: pindex(%lu), busy(%d), "
2264 "PG_BUSY(%d), hold(%d)\n",
2265 (u_long)m->pindex, m->busy,
2266 ((m->flags & PG_BUSY) ? 1 : 0), m->hold_count);
2267 if ((m->queue - m->pc) == PQ_FREE)
2268 panic("vm_page_free: freeing free page");
2269 else
2270 panic("vm_page_free: freeing busy page");
2274 * Remove from object, spinlock the page and its queues and
2275 * remove from any queue. No queue spinlock will be held
2276 * after this section (because the page was removed from any
2277 * queue).
2279 vm_page_remove(m);
2280 vm_page_and_queue_spin_lock(m);
2281 _vm_page_rem_queue_spinlocked(m);
2284 * No further management of fictitious pages occurs beyond object
2285 * and queue removal.
2287 if ((m->flags & PG_FICTITIOUS) != 0) {
2288 vm_page_spin_unlock(m);
2289 vm_page_wakeup(m);
2290 return;
2293 m->valid = 0;
2294 vm_page_undirty(m);
2296 if (m->wire_count != 0) {
2297 if (m->wire_count > 1) {
2298 panic(
2299 "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2300 m->wire_count, (long)m->pindex);
2302 panic("vm_page_free: freeing wired page");
2306 * Clear the UNMANAGED flag when freeing an unmanaged page.
2307 * Clear the NEED_COMMIT flag
2309 if (m->flags & PG_UNMANAGED)
2310 vm_page_flag_clear(m, PG_UNMANAGED);
2311 if (m->flags & PG_NEED_COMMIT)
2312 vm_page_flag_clear(m, PG_NEED_COMMIT);
2314 if (m->hold_count != 0) {
2315 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2316 } else {
2317 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
2321 * This sequence allows us to clear PG_BUSY while still holding
2322 * its spin lock, which reduces contention vs allocators. We
2323 * must not leave the queue locked or _vm_page_wakeup() may
2324 * deadlock.
2326 _vm_page_queue_spin_unlock(m);
2327 if (_vm_page_wakeup(m)) {
2328 vm_page_spin_unlock(m);
2329 wakeup(m);
2330 } else {
2331 vm_page_spin_unlock(m);
2333 vm_page_free_wakeup();
2337 * vm_page_unmanage()
2339 * Prevent PV management from being done on the page. The page is
2340 * removed from the paging queues as if it were wired, and as a
2341 * consequence of no longer being managed the pageout daemon will not
2342 * touch it (since there is no way to locate the pte mappings for the
2343 * page). madvise() calls that mess with the pmap will also no longer
2344 * operate on the page.
2346 * Beyond that the page is still reasonably 'normal'. Freeing the page
2347 * will clear the flag.
2349 * This routine is used by OBJT_PHYS objects - objects using unswappable
2350 * physical memory as backing store rather then swap-backed memory and
2351 * will eventually be extended to support 4MB unmanaged physical
2352 * mappings.
2354 * Caller must be holding the page busy.
2356 void
2357 vm_page_unmanage(vm_page_t m)
2359 KKASSERT(m->flags & PG_BUSY);
2360 if ((m->flags & PG_UNMANAGED) == 0) {
2361 if (m->wire_count == 0)
2362 vm_page_unqueue(m);
2364 vm_page_flag_set(m, PG_UNMANAGED);
2368 * Mark this page as wired down by yet another map, removing it from
2369 * paging queues as necessary.
2371 * Caller must be holding the page busy.
2373 void
2374 vm_page_wire(vm_page_t m)
2377 * Only bump the wire statistics if the page is not already wired,
2378 * and only unqueue the page if it is on some queue (if it is unmanaged
2379 * it is already off the queues). Don't do anything with fictitious
2380 * pages because they are always wired.
2382 KKASSERT(m->flags & PG_BUSY);
2383 if ((m->flags & PG_FICTITIOUS) == 0) {
2384 if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2385 if ((m->flags & PG_UNMANAGED) == 0)
2386 vm_page_unqueue(m);
2387 atomic_add_int(&vmstats.v_wire_count, 1);
2389 KASSERT(m->wire_count != 0,
2390 ("vm_page_wire: wire_count overflow m=%p", m));
2395 * Release one wiring of this page, potentially enabling it to be paged again.
2397 * Many pages placed on the inactive queue should actually go
2398 * into the cache, but it is difficult to figure out which. What
2399 * we do instead, if the inactive target is well met, is to put
2400 * clean pages at the head of the inactive queue instead of the tail.
2401 * This will cause them to be moved to the cache more quickly and
2402 * if not actively re-referenced, freed more quickly. If we just
2403 * stick these pages at the end of the inactive queue, heavy filesystem
2404 * meta-data accesses can cause an unnecessary paging load on memory bound
2405 * processes. This optimization causes one-time-use metadata to be
2406 * reused more quickly.
2408 * Pages marked PG_NEED_COMMIT are always activated and never placed on
2409 * the inactive queue. This helps the pageout daemon determine memory
2410 * pressure and act on out-of-memory situations more quickly.
2412 * BUT, if we are in a low-memory situation we have no choice but to
2413 * put clean pages on the cache queue.
2415 * A number of routines use vm_page_unwire() to guarantee that the page
2416 * will go into either the inactive or active queues, and will NEVER
2417 * be placed in the cache - for example, just after dirtying a page.
2418 * dirty pages in the cache are not allowed.
2420 * This routine may not block.
2422 void
2423 vm_page_unwire(vm_page_t m, int activate)
2425 KKASSERT(m->flags & PG_BUSY);
2426 if (m->flags & PG_FICTITIOUS) {
2427 /* do nothing */
2428 } else if (m->wire_count <= 0) {
2429 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2430 } else {
2431 if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2432 atomic_add_int(&vmstats.v_wire_count, -1);
2433 if (m->flags & PG_UNMANAGED) {
2435 } else if (activate || (m->flags & PG_NEED_COMMIT)) {
2436 vm_page_spin_lock(m);
2437 _vm_page_add_queue_spinlocked(m,
2438 PQ_ACTIVE + m->pc, 0);
2439 _vm_page_and_queue_spin_unlock(m);
2440 } else {
2441 vm_page_spin_lock(m);
2442 vm_page_flag_clear(m, PG_WINATCFLS);
2443 _vm_page_add_queue_spinlocked(m,
2444 PQ_INACTIVE + m->pc, 0);
2445 ++vm_swapcache_inactive_heuristic;
2446 _vm_page_and_queue_spin_unlock(m);
2453 * Move the specified page to the inactive queue. If the page has
2454 * any associated swap, the swap is deallocated.
2456 * Normally athead is 0 resulting in LRU operation. athead is set
2457 * to 1 if we want this page to be 'as if it were placed in the cache',
2458 * except without unmapping it from the process address space.
2460 * vm_page's spinlock must be held on entry and will remain held on return.
2461 * This routine may not block.
2463 static void
2464 _vm_page_deactivate_locked(vm_page_t m, int athead)
2466 u_short oqueue;
2469 * Ignore if already inactive.
2471 if (m->queue - m->pc == PQ_INACTIVE)
2472 return;
2473 _vm_page_queue_spin_lock(m);
2474 oqueue = _vm_page_rem_queue_spinlocked(m);
2476 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2477 if (oqueue == PQ_CACHE)
2478 mycpu->gd_cnt.v_reactivated++;
2479 vm_page_flag_clear(m, PG_WINATCFLS);
2480 _vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2481 if (athead == 0)
2482 ++vm_swapcache_inactive_heuristic;
2484 /* NOTE: PQ_NONE if condition not taken */
2485 _vm_page_queue_spin_unlock(m);
2486 /* leaves vm_page spinlocked */
2490 * Attempt to deactivate a page.
2492 * No requirements.
2494 void
2495 vm_page_deactivate(vm_page_t m)
2497 vm_page_spin_lock(m);
2498 _vm_page_deactivate_locked(m, 0);
2499 vm_page_spin_unlock(m);
2502 void
2503 vm_page_deactivate_locked(vm_page_t m)
2505 _vm_page_deactivate_locked(m, 0);
2509 * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
2511 * This function returns non-zero if it successfully moved the page to
2512 * PQ_CACHE.
2514 * This function unconditionally unbusies the page on return.
2517 vm_page_try_to_cache(vm_page_t m)
2519 vm_page_spin_lock(m);
2520 if (m->dirty || m->hold_count || m->wire_count ||
2521 (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT))) {
2522 if (_vm_page_wakeup(m)) {
2523 vm_page_spin_unlock(m);
2524 wakeup(m);
2525 } else {
2526 vm_page_spin_unlock(m);
2528 return(0);
2530 vm_page_spin_unlock(m);
2533 * Page busied by us and no longer spinlocked. Dirty pages cannot
2534 * be moved to the cache.
2536 vm_page_test_dirty(m);
2537 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2538 vm_page_wakeup(m);
2539 return(0);
2541 vm_page_cache(m);
2542 return(1);
2546 * Attempt to free the page. If we cannot free it, we do nothing.
2547 * 1 is returned on success, 0 on failure.
2549 * No requirements.
2552 vm_page_try_to_free(vm_page_t m)
2554 vm_page_spin_lock(m);
2555 if (vm_page_busy_try(m, TRUE)) {
2556 vm_page_spin_unlock(m);
2557 return(0);
2561 * The page can be in any state, including already being on the free
2562 * queue. Check to see if it really can be freed.
2564 if (m->dirty || /* can't free if it is dirty */
2565 m->hold_count || /* or held (XXX may be wrong) */
2566 m->wire_count || /* or wired */
2567 (m->flags & (PG_UNMANAGED | /* or unmanaged */
2568 PG_NEED_COMMIT)) || /* or needs a commit */
2569 m->queue - m->pc == PQ_FREE || /* already on PQ_FREE */
2570 m->queue - m->pc == PQ_HOLD) { /* already on PQ_HOLD */
2571 if (_vm_page_wakeup(m)) {
2572 vm_page_spin_unlock(m);
2573 wakeup(m);
2574 } else {
2575 vm_page_spin_unlock(m);
2577 return(0);
2579 vm_page_spin_unlock(m);
2582 * We can probably free the page.
2584 * Page busied by us and no longer spinlocked. Dirty pages will
2585 * not be freed by this function. We have to re-test the
2586 * dirty bit after cleaning out the pmaps.
2588 vm_page_test_dirty(m);
2589 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2590 vm_page_wakeup(m);
2591 return(0);
2593 vm_page_protect(m, VM_PROT_NONE);
2594 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2595 vm_page_wakeup(m);
2596 return(0);
2598 vm_page_free(m);
2599 return(1);
2603 * vm_page_cache
2605 * Put the specified page onto the page cache queue (if appropriate).
2607 * The page must be busy, and this routine will release the busy and
2608 * possibly even free the page.
2610 void
2611 vm_page_cache(vm_page_t m)
2614 * Not suitable for the cache
2616 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
2617 m->busy || m->wire_count || m->hold_count) {
2618 vm_page_wakeup(m);
2619 return;
2623 * Already in the cache (and thus not mapped)
2625 if ((m->queue - m->pc) == PQ_CACHE) {
2626 KKASSERT((m->flags & PG_MAPPED) == 0);
2627 vm_page_wakeup(m);
2628 return;
2632 * Caller is required to test m->dirty, but note that the act of
2633 * removing the page from its maps can cause it to become dirty
2634 * on an SMP system due to another cpu running in usermode.
2636 if (m->dirty) {
2637 panic("vm_page_cache: caching a dirty page, pindex: %ld",
2638 (long)m->pindex);
2642 * Remove all pmaps and indicate that the page is not
2643 * writeable or mapped. Our vm_page_protect() call may
2644 * have blocked (especially w/ VM_PROT_NONE), so recheck
2645 * everything.
2647 vm_page_protect(m, VM_PROT_NONE);
2648 if ((m->flags & (PG_UNMANAGED | PG_MAPPED)) ||
2649 m->busy || m->wire_count || m->hold_count) {
2650 vm_page_wakeup(m);
2651 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2652 vm_page_deactivate(m);
2653 vm_page_wakeup(m);
2654 } else {
2655 _vm_page_and_queue_spin_lock(m);
2656 _vm_page_rem_queue_spinlocked(m);
2657 _vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
2658 _vm_page_queue_spin_unlock(m);
2659 if (_vm_page_wakeup(m)) {
2660 vm_page_spin_unlock(m);
2661 wakeup(m);
2662 } else {
2663 vm_page_spin_unlock(m);
2665 vm_page_free_wakeup();
2670 * vm_page_dontneed()
2672 * Cache, deactivate, or do nothing as appropriate. This routine
2673 * is typically used by madvise() MADV_DONTNEED.
2675 * Generally speaking we want to move the page into the cache so
2676 * it gets reused quickly. However, this can result in a silly syndrome
2677 * due to the page recycling too quickly. Small objects will not be
2678 * fully cached. On the otherhand, if we move the page to the inactive
2679 * queue we wind up with a problem whereby very large objects
2680 * unnecessarily blow away our inactive and cache queues.
2682 * The solution is to move the pages based on a fixed weighting. We
2683 * either leave them alone, deactivate them, or move them to the cache,
2684 * where moving them to the cache has the highest weighting.
2685 * By forcing some pages into other queues we eventually force the
2686 * system to balance the queues, potentially recovering other unrelated
2687 * space from active. The idea is to not force this to happen too
2688 * often.
2690 * The page must be busied.
2692 void
2693 vm_page_dontneed(vm_page_t m)
2695 static int dnweight;
2696 int dnw;
2697 int head;
2699 dnw = ++dnweight;
2702 * occassionally leave the page alone
2704 if ((dnw & 0x01F0) == 0 ||
2705 m->queue - m->pc == PQ_INACTIVE ||
2706 m->queue - m->pc == PQ_CACHE
2708 if (m->act_count >= ACT_INIT)
2709 --m->act_count;
2710 return;
2714 * If vm_page_dontneed() is inactivating a page, it must clear
2715 * the referenced flag; otherwise the pagedaemon will see references
2716 * on the page in the inactive queue and reactivate it. Until the
2717 * page can move to the cache queue, madvise's job is not done.
2719 vm_page_flag_clear(m, PG_REFERENCED);
2720 pmap_clear_reference(m);
2722 if (m->dirty == 0)
2723 vm_page_test_dirty(m);
2725 if (m->dirty || (dnw & 0x0070) == 0) {
2727 * Deactivate the page 3 times out of 32.
2729 head = 0;
2730 } else {
2732 * Cache the page 28 times out of every 32. Note that
2733 * the page is deactivated instead of cached, but placed
2734 * at the head of the queue instead of the tail.
2736 head = 1;
2738 vm_page_spin_lock(m);
2739 _vm_page_deactivate_locked(m, head);
2740 vm_page_spin_unlock(m);
2744 * These routines manipulate the 'soft busy' count for a page. A soft busy
2745 * is almost like PG_BUSY except that it allows certain compatible operations
2746 * to occur on the page while it is busy. For example, a page undergoing a
2747 * write can still be mapped read-only.
2749 * Because vm_pages can overlap buffers m->busy can be > 1. m->busy is only
2750 * adjusted while the vm_page is PG_BUSY so the flash will occur when the
2751 * busy bit is cleared.
2753 void
2754 vm_page_io_start(vm_page_t m)
2756 KASSERT(m->flags & PG_BUSY, ("vm_page_io_start: page not busy!!!"));
2757 atomic_add_char(&m->busy, 1);
2758 vm_page_flag_set(m, PG_SBUSY);
2761 void
2762 vm_page_io_finish(vm_page_t m)
2764 KASSERT(m->flags & PG_BUSY, ("vm_page_io_finish: page not busy!!!"));
2765 atomic_subtract_char(&m->busy, 1);
2766 if (m->busy == 0)
2767 vm_page_flag_clear(m, PG_SBUSY);
2771 * Indicate that a clean VM page requires a filesystem commit and cannot
2772 * be reused. Used by tmpfs.
2774 void
2775 vm_page_need_commit(vm_page_t m)
2777 vm_page_flag_set(m, PG_NEED_COMMIT);
2778 vm_object_set_writeable_dirty(m->object);
2781 void
2782 vm_page_clear_commit(vm_page_t m)
2784 vm_page_flag_clear(m, PG_NEED_COMMIT);
2788 * Grab a page, blocking if it is busy and allocating a page if necessary.
2789 * A busy page is returned or NULL. The page may or may not be valid and
2790 * might not be on a queue (the caller is responsible for the disposition of
2791 * the page).
2793 * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
2794 * page will be zero'd and marked valid.
2796 * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
2797 * valid even if it already exists.
2799 * If VM_ALLOC_RETRY is specified this routine will never return NULL. Also
2800 * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
2801 * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
2803 * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
2804 * always returned if we had blocked.
2806 * This routine may not be called from an interrupt.
2808 * No other requirements.
2810 vm_page_t
2811 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2813 vm_page_t m;
2814 int error;
2815 int shared = 1;
2817 KKASSERT(allocflags &
2818 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2819 vm_object_hold_shared(object);
2820 for (;;) {
2821 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2822 if (error) {
2823 vm_page_sleep_busy(m, TRUE, "pgrbwt");
2824 if ((allocflags & VM_ALLOC_RETRY) == 0) {
2825 m = NULL;
2826 break;
2828 /* retry */
2829 } else if (m == NULL) {
2830 if (shared) {
2831 vm_object_upgrade(object);
2832 shared = 0;
2834 if (allocflags & VM_ALLOC_RETRY)
2835 allocflags |= VM_ALLOC_NULL_OK;
2836 m = vm_page_alloc(object, pindex,
2837 allocflags & ~VM_ALLOC_RETRY);
2838 if (m)
2839 break;
2840 vm_wait(0);
2841 if ((allocflags & VM_ALLOC_RETRY) == 0)
2842 goto failed;
2843 } else {
2844 /* m found */
2845 break;
2850 * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
2852 * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
2853 * valid even if already valid.
2855 * NOTE! We have removed all of the PG_ZERO optimizations and also
2856 * removed the idle zeroing code. These optimizations actually
2857 * slow things down on modern cpus because the zerod area is
2858 * likely uncached, placing a memory-access burden on the
2859 * accesors taking the fault.
2861 * By always zeroing the page in-line with the fault, no
2862 * dynamic ram reads are needed and the caches are hot, ready
2863 * for userland to access the memory.
2865 if (m->valid == 0) {
2866 if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
2867 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2868 m->valid = VM_PAGE_BITS_ALL;
2870 } else if (allocflags & VM_ALLOC_FORCE_ZERO) {
2871 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2872 m->valid = VM_PAGE_BITS_ALL;
2874 failed:
2875 vm_object_drop(object);
2876 return(m);
2880 * Mapping function for valid bits or for dirty bits in
2881 * a page. May not block.
2883 * Inputs are required to range within a page.
2885 * No requirements.
2886 * Non blocking.
2889 vm_page_bits(int base, int size)
2891 int first_bit;
2892 int last_bit;
2894 KASSERT(
2895 base + size <= PAGE_SIZE,
2896 ("vm_page_bits: illegal base/size %d/%d", base, size)
2899 if (size == 0) /* handle degenerate case */
2900 return(0);
2902 first_bit = base >> DEV_BSHIFT;
2903 last_bit = (base + size - 1) >> DEV_BSHIFT;
2905 return ((2 << last_bit) - (1 << first_bit));
2909 * Sets portions of a page valid and clean. The arguments are expected
2910 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2911 * of any partial chunks touched by the range. The invalid portion of
2912 * such chunks will be zero'd.
2914 * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
2915 * align base to DEV_BSIZE so as not to mark clean a partially
2916 * truncated device block. Otherwise the dirty page status might be
2917 * lost.
2919 * This routine may not block.
2921 * (base + size) must be less then or equal to PAGE_SIZE.
2923 static void
2924 _vm_page_zero_valid(vm_page_t m, int base, int size)
2926 int frag;
2927 int endoff;
2929 if (size == 0) /* handle degenerate case */
2930 return;
2933 * If the base is not DEV_BSIZE aligned and the valid
2934 * bit is clear, we have to zero out a portion of the
2935 * first block.
2938 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2939 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
2941 pmap_zero_page_area(
2942 VM_PAGE_TO_PHYS(m),
2943 frag,
2944 base - frag
2949 * If the ending offset is not DEV_BSIZE aligned and the
2950 * valid bit is clear, we have to zero out a portion of
2951 * the last block.
2954 endoff = base + size;
2956 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
2957 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
2959 pmap_zero_page_area(
2960 VM_PAGE_TO_PHYS(m),
2961 endoff,
2962 DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
2968 * Set valid, clear dirty bits. If validating the entire
2969 * page we can safely clear the pmap modify bit. We also
2970 * use this opportunity to clear the PG_NOSYNC flag. If a process
2971 * takes a write fault on a MAP_NOSYNC memory area the flag will
2972 * be set again.
2974 * We set valid bits inclusive of any overlap, but we can only
2975 * clear dirty bits for DEV_BSIZE chunks that are fully within
2976 * the range.
2978 * Page must be busied?
2979 * No other requirements.
2981 void
2982 vm_page_set_valid(vm_page_t m, int base, int size)
2984 _vm_page_zero_valid(m, base, size);
2985 m->valid |= vm_page_bits(base, size);
2990 * Set valid bits and clear dirty bits.
2992 * NOTE: This function does not clear the pmap modified bit.
2993 * Also note that e.g. NFS may use a byte-granular base
2994 * and size.
2996 * WARNING: Page must be busied? But vfs_clean_one_page() will call
2997 * this without necessarily busying the page (via bdwrite()).
2998 * So for now vm_token must also be held.
3000 * No other requirements.
3002 void
3003 vm_page_set_validclean(vm_page_t m, int base, int size)
3005 int pagebits;
3007 _vm_page_zero_valid(m, base, size);
3008 pagebits = vm_page_bits(base, size);
3009 m->valid |= pagebits;
3010 m->dirty &= ~pagebits;
3011 if (base == 0 && size == PAGE_SIZE) {
3012 /*pmap_clear_modify(m);*/
3013 vm_page_flag_clear(m, PG_NOSYNC);
3018 * Set valid & dirty. Used by buwrite()
3020 * WARNING: Page must be busied? But vfs_dirty_one_page() will
3021 * call this function in buwrite() so for now vm_token must
3022 * be held.
3024 * No other requirements.
3026 void
3027 vm_page_set_validdirty(vm_page_t m, int base, int size)
3029 int pagebits;
3031 pagebits = vm_page_bits(base, size);
3032 m->valid |= pagebits;
3033 m->dirty |= pagebits;
3034 if (m->object)
3035 vm_object_set_writeable_dirty(m->object);
3039 * Clear dirty bits.
3041 * NOTE: This function does not clear the pmap modified bit.
3042 * Also note that e.g. NFS may use a byte-granular base
3043 * and size.
3045 * Page must be busied?
3046 * No other requirements.
3048 void
3049 vm_page_clear_dirty(vm_page_t m, int base, int size)
3051 m->dirty &= ~vm_page_bits(base, size);
3052 if (base == 0 && size == PAGE_SIZE) {
3053 /*pmap_clear_modify(m);*/
3054 vm_page_flag_clear(m, PG_NOSYNC);
3059 * Make the page all-dirty.
3061 * Also make sure the related object and vnode reflect the fact that the
3062 * object may now contain a dirty page.
3064 * Page must be busied?
3065 * No other requirements.
3067 void
3068 vm_page_dirty(vm_page_t m)
3070 #ifdef INVARIANTS
3071 int pqtype = m->queue - m->pc;
3072 #endif
3073 KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3074 ("vm_page_dirty: page in free/cache queue!"));
3075 if (m->dirty != VM_PAGE_BITS_ALL) {
3076 m->dirty = VM_PAGE_BITS_ALL;
3077 if (m->object)
3078 vm_object_set_writeable_dirty(m->object);
3083 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3084 * valid and dirty bits for the effected areas are cleared.
3086 * Page must be busied?
3087 * Does not block.
3088 * No other requirements.
3090 void
3091 vm_page_set_invalid(vm_page_t m, int base, int size)
3093 int bits;
3095 bits = vm_page_bits(base, size);
3096 m->valid &= ~bits;
3097 m->dirty &= ~bits;
3098 m->object->generation++;
3102 * The kernel assumes that the invalid portions of a page contain
3103 * garbage, but such pages can be mapped into memory by user code.
3104 * When this occurs, we must zero out the non-valid portions of the
3105 * page so user code sees what it expects.
3107 * Pages are most often semi-valid when the end of a file is mapped
3108 * into memory and the file's size is not page aligned.
3110 * Page must be busied?
3111 * No other requirements.
3113 void
3114 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3116 int b;
3117 int i;
3120 * Scan the valid bits looking for invalid sections that
3121 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
3122 * valid bit may be set ) have already been zerod by
3123 * vm_page_set_validclean().
3125 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3126 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3127 (m->valid & (1 << i))
3129 if (i > b) {
3130 pmap_zero_page_area(
3131 VM_PAGE_TO_PHYS(m),
3132 b << DEV_BSHIFT,
3133 (i - b) << DEV_BSHIFT
3136 b = i + 1;
3141 * setvalid is TRUE when we can safely set the zero'd areas
3142 * as being valid. We can do this if there are no cache consistency
3143 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3145 if (setvalid)
3146 m->valid = VM_PAGE_BITS_ALL;
3150 * Is a (partial) page valid? Note that the case where size == 0
3151 * will return FALSE in the degenerate case where the page is entirely
3152 * invalid, and TRUE otherwise.
3154 * Does not block.
3155 * No other requirements.
3158 vm_page_is_valid(vm_page_t m, int base, int size)
3160 int bits = vm_page_bits(base, size);
3162 if (m->valid && ((m->valid & bits) == bits))
3163 return 1;
3164 else
3165 return 0;
3169 * update dirty bits from pmap/mmu. May not block.
3171 * Caller must hold the page busy
3173 void
3174 vm_page_test_dirty(vm_page_t m)
3176 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
3177 vm_page_dirty(m);
3182 * Register an action, associating it with its vm_page
3184 void
3185 vm_page_register_action(vm_page_action_t action, vm_page_event_t event)
3187 struct vm_page_action_list *list;
3188 int hv;
3190 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3191 list = &action_list[hv];
3193 lwkt_gettoken(&vm_token);
3194 vm_page_flag_set(action->m, PG_ACTIONLIST);
3195 action->event = event;
3196 LIST_INSERT_HEAD(list, action, entry);
3197 lwkt_reltoken(&vm_token);
3201 * Unregister an action, disassociating it from its related vm_page
3203 void
3204 vm_page_unregister_action(vm_page_action_t action)
3206 struct vm_page_action_list *list;
3207 int hv;
3209 lwkt_gettoken(&vm_token);
3210 if (action->event != VMEVENT_NONE) {
3211 action->event = VMEVENT_NONE;
3212 LIST_REMOVE(action, entry);
3214 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3215 list = &action_list[hv];
3216 if (LIST_EMPTY(list))
3217 vm_page_flag_clear(action->m, PG_ACTIONLIST);
3219 lwkt_reltoken(&vm_token);
3223 * Issue an event on a VM page. Corresponding action structures are
3224 * removed from the page's list and called.
3226 * If the vm_page has no more pending action events we clear its
3227 * PG_ACTIONLIST flag.
3229 void
3230 vm_page_event_internal(vm_page_t m, vm_page_event_t event)
3232 struct vm_page_action_list *list;
3233 struct vm_page_action *scan;
3234 struct vm_page_action *next;
3235 int hv;
3236 int all;
3238 hv = (int)((intptr_t)m >> 8) & VMACTION_HMASK;
3239 list = &action_list[hv];
3240 all = 1;
3242 lwkt_gettoken(&vm_token);
3243 LIST_FOREACH_MUTABLE(scan, list, entry, next) {
3244 if (scan->m == m) {
3245 if (scan->event == event) {
3246 scan->event = VMEVENT_NONE;
3247 LIST_REMOVE(scan, entry);
3248 scan->func(m, scan);
3249 /* XXX */
3250 } else {
3251 all = 0;
3255 if (all)
3256 vm_page_flag_clear(m, PG_ACTIONLIST);
3257 lwkt_reltoken(&vm_token);
3260 #include "opt_ddb.h"
3261 #ifdef DDB
3262 #include <sys/kernel.h>
3264 #include <ddb/ddb.h>
3266 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3268 db_printf("vmstats.v_free_count: %d\n", vmstats.v_free_count);
3269 db_printf("vmstats.v_cache_count: %d\n", vmstats.v_cache_count);
3270 db_printf("vmstats.v_inactive_count: %d\n", vmstats.v_inactive_count);
3271 db_printf("vmstats.v_active_count: %d\n", vmstats.v_active_count);
3272 db_printf("vmstats.v_wire_count: %d\n", vmstats.v_wire_count);
3273 db_printf("vmstats.v_free_reserved: %d\n", vmstats.v_free_reserved);
3274 db_printf("vmstats.v_free_min: %d\n", vmstats.v_free_min);
3275 db_printf("vmstats.v_free_target: %d\n", vmstats.v_free_target);
3276 db_printf("vmstats.v_cache_min: %d\n", vmstats.v_cache_min);
3277 db_printf("vmstats.v_inactive_target: %d\n", vmstats.v_inactive_target);
3280 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3282 int i;
3283 db_printf("PQ_FREE:");
3284 for(i=0;i<PQ_L2_SIZE;i++) {
3285 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
3287 db_printf("\n");
3289 db_printf("PQ_CACHE:");
3290 for(i=0;i<PQ_L2_SIZE;i++) {
3291 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
3293 db_printf("\n");
3295 db_printf("PQ_ACTIVE:");
3296 for(i=0;i<PQ_L2_SIZE;i++) {
3297 db_printf(" %d", vm_page_queues[PQ_ACTIVE + i].lcnt);
3299 db_printf("\n");
3301 db_printf("PQ_INACTIVE:");
3302 for(i=0;i<PQ_L2_SIZE;i++) {
3303 db_printf(" %d", vm_page_queues[PQ_INACTIVE + i].lcnt);
3305 db_printf("\n");
3307 #endif /* DDB */