kernel - Remove most global atomic ops for VM page statistics
[dragonfly.git] / sys / vm / vm_page.c
blob344089f52f7c365b30c84c592e11cd3c037e041c
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_offset =
157 offsetof(struct vmstats, v_free_count);
158 for (i = 0; i < PQ_L2_SIZE; i++)
159 vm_page_queues[PQ_CACHE+i].cnt_offset =
160 offsetof(struct vmstats, v_cache_count);
161 for (i = 0; i < PQ_L2_SIZE; i++)
162 vm_page_queues[PQ_INACTIVE+i].cnt_offset =
163 offsetof(struct vmstats, v_inactive_count);
164 for (i = 0; i < PQ_L2_SIZE; i++)
165 vm_page_queues[PQ_ACTIVE+i].cnt_offset =
166 offsetof(struct vmstats, v_active_count);
167 for (i = 0; i < PQ_L2_SIZE; i++)
168 vm_page_queues[PQ_HOLD+i].cnt_offset =
169 offsetof(struct vmstats, v_active_count);
170 /* PQ_NONE has no queue */
172 for (i = 0; i < PQ_COUNT; i++) {
173 TAILQ_INIT(&vm_page_queues[i].pl);
174 spin_init(&vm_page_queues[i].spin, "vm_page_queue_init");
177 for (i = 0; i < VMACTION_HSIZE; i++)
178 LIST_INIT(&action_list[i]);
182 * note: place in initialized data section? Is this necessary?
184 long first_page = 0;
185 int vm_page_array_size = 0;
186 vm_page_t vm_page_array = NULL;
187 vm_paddr_t vm_low_phys_reserved;
190 * (low level boot)
192 * Sets the page size, perhaps based upon the memory size.
193 * Must be called before any use of page-size dependent functions.
195 void
196 vm_set_page_size(void)
198 if (vmstats.v_page_size == 0)
199 vmstats.v_page_size = PAGE_SIZE;
200 if (((vmstats.v_page_size - 1) & vmstats.v_page_size) != 0)
201 panic("vm_set_page_size: page size not a power of two");
205 * (low level boot)
207 * Add a new page to the freelist for use by the system. New pages
208 * are added to both the head and tail of the associated free page
209 * queue in a bottom-up fashion, so both zero'd and non-zero'd page
210 * requests pull 'recent' adds (higher physical addresses) first.
212 * Beware that the page zeroing daemon will also be running soon after
213 * boot, moving pages from the head to the tail of the PQ_FREE queues.
215 * Must be called in a critical section.
217 static void
218 vm_add_new_page(vm_paddr_t pa)
220 struct vpgqueues *vpq;
221 vm_page_t m;
223 m = PHYS_TO_VM_PAGE(pa);
224 m->phys_addr = pa;
225 m->flags = 0;
226 m->pc = (pa >> PAGE_SHIFT) & PQ_L2_MASK;
227 m->pat_mode = PAT_WRITE_BACK;
230 * Twist for cpu localization in addition to page coloring, so
231 * different cpus selecting by m->queue get different page colors.
233 m->pc ^= ((pa >> PAGE_SHIFT) / PQ_L2_SIZE) & PQ_L2_MASK;
234 m->pc ^= ((pa >> PAGE_SHIFT) / (PQ_L2_SIZE * PQ_L2_SIZE)) & PQ_L2_MASK;
237 * Reserve a certain number of contiguous low memory pages for
238 * contigmalloc() to use.
240 if (pa < vm_low_phys_reserved) {
241 atomic_add_int(&vmstats.v_page_count, 1);
242 atomic_add_int(&vmstats.v_dma_pages, 1);
243 m->queue = PQ_NONE;
244 m->wire_count = 1;
245 atomic_add_int(&vmstats.v_wire_count, 1);
246 alist_free(&vm_contig_alist, pa >> PAGE_SHIFT, 1);
247 return;
251 * General page
253 m->queue = m->pc + PQ_FREE;
254 KKASSERT(m->dirty == 0);
256 atomic_add_int(&vmstats.v_page_count, 1);
257 atomic_add_int(&vmstats.v_free_count, 1);
258 vpq = &vm_page_queues[m->queue];
259 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
260 ++vpq->lcnt;
264 * (low level boot)
266 * Initializes the resident memory module.
268 * Preallocates memory for critical VM structures and arrays prior to
269 * kernel_map becoming available.
271 * Memory is allocated from (virtual2_start, virtual2_end) if available,
272 * otherwise memory is allocated from (virtual_start, virtual_end).
274 * On x86-64 (virtual_start, virtual_end) is only 2GB and may not be
275 * large enough to hold vm_page_array & other structures for machines with
276 * large amounts of ram, so we want to use virtual2* when available.
278 void
279 vm_page_startup(void)
281 vm_offset_t vaddr = virtual2_start ? virtual2_start : virtual_start;
282 vm_offset_t mapped;
283 vm_size_t npages;
284 vm_paddr_t page_range;
285 vm_paddr_t new_end;
286 int i;
287 vm_paddr_t pa;
288 vm_paddr_t last_pa;
289 vm_paddr_t end;
290 vm_paddr_t biggestone, biggestsize;
291 vm_paddr_t total;
292 vm_page_t m;
294 total = 0;
295 biggestsize = 0;
296 biggestone = 0;
297 vaddr = round_page(vaddr);
300 * Make sure ranges are page-aligned.
302 for (i = 0; phys_avail[i].phys_end; ++i) {
303 phys_avail[i].phys_beg = round_page64(phys_avail[i].phys_beg);
304 phys_avail[i].phys_end = trunc_page64(phys_avail[i].phys_end);
305 if (phys_avail[i].phys_end < phys_avail[i].phys_beg)
306 phys_avail[i].phys_end = phys_avail[i].phys_beg;
310 * Locate largest block
312 for (i = 0; phys_avail[i].phys_end; ++i) {
313 vm_paddr_t size = phys_avail[i].phys_end -
314 phys_avail[i].phys_beg;
316 if (size > biggestsize) {
317 biggestone = i;
318 biggestsize = size;
320 total += size;
322 --i; /* adjust to last entry for use down below */
324 end = phys_avail[biggestone].phys_end;
325 end = trunc_page(end);
328 * Initialize the queue headers for the free queue, the active queue
329 * and the inactive queue.
331 vm_page_queue_init();
333 #if !defined(_KERNEL_VIRTUAL)
335 * VKERNELs don't support minidumps and as such don't need
336 * vm_page_dump
338 * Allocate a bitmap to indicate that a random physical page
339 * needs to be included in a minidump.
341 * The amd64 port needs this to indicate which direct map pages
342 * need to be dumped, via calls to dump_add_page()/dump_drop_page().
344 * However, i386 still needs this workspace internally within the
345 * minidump code. In theory, they are not needed on i386, but are
346 * included should the sf_buf code decide to use them.
348 page_range = phys_avail[i].phys_end / PAGE_SIZE;
349 vm_page_dump_size = round_page(roundup2(page_range, NBBY) / NBBY);
350 end -= vm_page_dump_size;
351 vm_page_dump = (void *)pmap_map(&vaddr, end, end + vm_page_dump_size,
352 VM_PROT_READ | VM_PROT_WRITE);
353 bzero((void *)vm_page_dump, vm_page_dump_size);
354 #endif
356 * Compute the number of pages of memory that will be available for
357 * use (taking into account the overhead of a page structure per
358 * page).
360 first_page = phys_avail[0].phys_beg / PAGE_SIZE;
361 page_range = phys_avail[i].phys_end / PAGE_SIZE - first_page;
362 npages = (total - (page_range * sizeof(struct vm_page))) / PAGE_SIZE;
364 #ifndef _KERNEL_VIRTUAL
366 * (only applies to real kernels)
368 * Reserve a large amount of low memory for potential 32-bit DMA
369 * space allocations. Once device initialization is complete we
370 * release most of it, but keep (vm_dma_reserved) memory reserved
371 * for later use. Typically for X / graphics. Through trial and
372 * error we find that GPUs usually requires ~60-100MB or so.
374 * By default, 128M is left in reserve on machines with 2G+ of ram.
376 vm_low_phys_reserved = (vm_paddr_t)65536 << PAGE_SHIFT;
377 if (vm_low_phys_reserved > total / 4)
378 vm_low_phys_reserved = total / 4;
379 if (vm_dma_reserved == 0) {
380 vm_dma_reserved = 128 * 1024 * 1024; /* 128MB */
381 if (vm_dma_reserved > total / 16)
382 vm_dma_reserved = total / 16;
384 #endif
385 alist_init(&vm_contig_alist, 65536, vm_contig_ameta,
386 ALIST_RECORDS_65536);
389 * Initialize the mem entry structures now, and put them in the free
390 * queue.
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.
402 for (pa = new_end;
403 pa < phys_avail[biggestone].phys_end;
404 pa += PAGE_SIZE) {
405 dump_add_page(pa);
407 #endif
410 * Clear all of the page structures, run basic initialization so
411 * PHYS_TO_VM_PAGE() operates properly even on pages not in the
412 * map.
414 bzero((caddr_t) vm_page_array, page_range * sizeof(struct vm_page));
415 vm_page_array_size = page_range;
417 m = &vm_page_array[0];
418 pa = ptoa(first_page);
419 for (i = 0; i < page_range; ++i) {
420 spin_init(&m->spin, "vm_page");
421 m->phys_addr = pa;
422 pa += PAGE_SIZE;
423 ++m;
427 * Construct the free queue(s) in ascending order (by physical
428 * address) so that the first 16MB of physical memory is allocated
429 * last rather than first. On large-memory machines, this avoids
430 * the exhaustion of low physical memory before isa_dmainit has run.
432 vmstats.v_page_count = 0;
433 vmstats.v_free_count = 0;
434 for (i = 0; phys_avail[i].phys_end && npages > 0; ++i) {
435 pa = phys_avail[i].phys_beg;
436 if (i == biggestone)
437 last_pa = new_end;
438 else
439 last_pa = phys_avail[i].phys_end;
440 while (pa < last_pa && npages-- > 0) {
441 vm_add_new_page(pa);
442 pa += PAGE_SIZE;
445 if (virtual2_start)
446 virtual2_start = vaddr;
447 else
448 virtual_start = vaddr;
452 * Reorganize VM pages based on numa data. May be called as many times as
453 * necessary. Will reorganize the vm_page_t page color and related queue(s)
454 * to allow vm_page_alloc() to choose pages based on socket affinity.
456 * NOTE: This function is only called while we are still in UP mode, so
457 * we only need a critical section to protect the queues (which
458 * saves a lot of time, there are likely a ton of pages).
460 void
461 vm_numa_organize(vm_paddr_t ran_beg, vm_paddr_t bytes, int physid)
463 vm_paddr_t scan_beg;
464 vm_paddr_t scan_end;
465 vm_paddr_t ran_end;
466 struct vpgqueues *vpq;
467 vm_page_t m;
468 vm_page_t mend;
469 int i;
470 int socket_mod;
471 int socket_value;
474 * Check if no physical information, or there was only one socket
475 * (so don't waste time doing nothing!).
477 if (cpu_topology_phys_ids <= 1 ||
478 cpu_topology_core_ids == 0) {
479 return;
483 * Setup for our iteration. Note that ACPI may iterate CPU
484 * sockets starting at 0 or 1 or some other number. The
485 * cpu_topology code mod's it against the socket count.
487 ran_end = ran_beg + bytes;
488 physid %= cpu_topology_phys_ids;
490 socket_mod = PQ_L2_SIZE / cpu_topology_phys_ids;
491 socket_value = physid * socket_mod;
492 mend = &vm_page_array[vm_page_array_size];
494 crit_enter();
497 * Adjust vm_page->pc and requeue all affected pages. The
498 * allocator will then be able to localize memory allocations
499 * to some degree.
501 for (i = 0; phys_avail[i].phys_end; ++i) {
502 scan_beg = phys_avail[i].phys_beg;
503 scan_end = phys_avail[i].phys_end;
504 if (scan_end <= ran_beg)
505 continue;
506 if (scan_beg >= ran_end)
507 continue;
508 if (scan_beg < ran_beg)
509 scan_beg = ran_beg;
510 if (scan_end > ran_end)
511 scan_end = ran_end;
512 if (atop(scan_end) > first_page + vm_page_array_size)
513 scan_end = ptoa(first_page + vm_page_array_size);
515 m = PHYS_TO_VM_PAGE(scan_beg);
516 while (scan_beg < scan_end) {
517 KKASSERT(m < mend);
518 if (m->queue != PQ_NONE) {
519 vpq = &vm_page_queues[m->queue];
520 TAILQ_REMOVE(&vpq->pl, m, pageq);
521 --vpq->lcnt;
522 /* queue doesn't change, no need to adj cnt */
523 m->queue -= m->pc;
524 m->pc %= socket_mod;
525 m->pc += socket_value;
526 m->pc &= PQ_L2_MASK;
527 m->queue += m->pc;
528 vpq = &vm_page_queues[m->queue];
529 TAILQ_INSERT_HEAD(&vpq->pl, m, pageq);
530 ++vpq->lcnt;
531 /* queue doesn't change, no need to adj cnt */
532 } else {
533 m->pc %= socket_mod;
534 m->pc += socket_value;
535 m->pc &= PQ_L2_MASK;
537 scan_beg += PAGE_SIZE;
538 ++m;
541 crit_exit();
545 * We tended to reserve a ton of memory for contigmalloc(). Now that most
546 * drivers have initialized we want to return most the remaining free
547 * reserve back to the VM page queues so they can be used for normal
548 * allocations.
550 * We leave vm_dma_reserved bytes worth of free pages in the reserve pool.
552 static void
553 vm_page_startup_finish(void *dummy __unused)
555 alist_blk_t blk;
556 alist_blk_t rblk;
557 alist_blk_t count;
558 alist_blk_t xcount;
559 alist_blk_t bfree;
560 vm_page_t m;
562 spin_lock(&vm_contig_spin);
563 for (;;) {
564 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
565 if (bfree <= vm_dma_reserved / PAGE_SIZE)
566 break;
567 if (count == 0)
568 break;
571 * Figure out how much of the initial reserve we have to
572 * free in order to reach our target.
574 bfree -= vm_dma_reserved / PAGE_SIZE;
575 if (count > bfree) {
576 blk += count - bfree;
577 count = bfree;
581 * Calculate the nearest power of 2 <= count.
583 for (xcount = 1; xcount <= count; xcount <<= 1)
585 xcount >>= 1;
586 blk += count - xcount;
587 count = xcount;
590 * Allocate the pages from the alist, then free them to
591 * the normal VM page queues.
593 * Pages allocated from the alist are wired. We have to
594 * busy, unwire, and free them. We must also adjust
595 * vm_low_phys_reserved before freeing any pages to prevent
596 * confusion.
598 rblk = alist_alloc(&vm_contig_alist, blk, count);
599 if (rblk != blk) {
600 kprintf("vm_page_startup_finish: Unable to return "
601 "dma space @0x%08x/%d -> 0x%08x\n",
602 blk, count, rblk);
603 break;
605 atomic_add_int(&vmstats.v_dma_pages, -count);
606 spin_unlock(&vm_contig_spin);
608 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
609 vm_low_phys_reserved = VM_PAGE_TO_PHYS(m);
610 while (count) {
611 vm_page_busy_wait(m, FALSE, "cpgfr");
612 vm_page_unwire(m, 0);
613 vm_page_free(m);
614 --count;
615 ++m;
617 spin_lock(&vm_contig_spin);
619 spin_unlock(&vm_contig_spin);
622 * Print out how much DMA space drivers have already allocated and
623 * how much is left over.
625 kprintf("DMA space used: %jdk, remaining available: %jdk\n",
626 (intmax_t)(vmstats.v_dma_pages - vm_contig_alist.bl_free) *
627 (PAGE_SIZE / 1024),
628 (intmax_t)vm_contig_alist.bl_free * (PAGE_SIZE / 1024));
630 SYSINIT(vm_pgend, SI_SUB_PROC0_POST, SI_ORDER_ANY,
631 vm_page_startup_finish, NULL);
635 * Scan comparison function for Red-Black tree scans. An inclusive
636 * (start,end) is expected. Other fields are not used.
639 rb_vm_page_scancmp(struct vm_page *p, void *data)
641 struct rb_vm_page_scan_info *info = data;
643 if (p->pindex < info->start_pindex)
644 return(-1);
645 if (p->pindex > info->end_pindex)
646 return(1);
647 return(0);
651 rb_vm_page_compare(struct vm_page *p1, struct vm_page *p2)
653 if (p1->pindex < p2->pindex)
654 return(-1);
655 if (p1->pindex > p2->pindex)
656 return(1);
657 return(0);
660 void
661 vm_page_init(vm_page_t m)
663 /* do nothing for now. Called from pmap_page_init() */
667 * Each page queue has its own spin lock, which is fairly optimal for
668 * allocating and freeing pages at least.
670 * The caller must hold the vm_page_spin_lock() before locking a vm_page's
671 * queue spinlock via this function. Also note that m->queue cannot change
672 * unless both the page and queue are locked.
674 static __inline
675 void
676 _vm_page_queue_spin_lock(vm_page_t m)
678 u_short queue;
680 queue = m->queue;
681 if (queue != PQ_NONE) {
682 spin_lock(&vm_page_queues[queue].spin);
683 KKASSERT(queue == m->queue);
687 static __inline
688 void
689 _vm_page_queue_spin_unlock(vm_page_t m)
691 u_short queue;
693 queue = m->queue;
694 cpu_ccfence();
695 if (queue != PQ_NONE)
696 spin_unlock(&vm_page_queues[queue].spin);
699 static __inline
700 void
701 _vm_page_queues_spin_lock(u_short queue)
703 cpu_ccfence();
704 if (queue != PQ_NONE)
705 spin_lock(&vm_page_queues[queue].spin);
709 static __inline
710 void
711 _vm_page_queues_spin_unlock(u_short queue)
713 cpu_ccfence();
714 if (queue != PQ_NONE)
715 spin_unlock(&vm_page_queues[queue].spin);
718 void
719 vm_page_queue_spin_lock(vm_page_t m)
721 _vm_page_queue_spin_lock(m);
724 void
725 vm_page_queues_spin_lock(u_short queue)
727 _vm_page_queues_spin_lock(queue);
730 void
731 vm_page_queue_spin_unlock(vm_page_t m)
733 _vm_page_queue_spin_unlock(m);
736 void
737 vm_page_queues_spin_unlock(u_short queue)
739 _vm_page_queues_spin_unlock(queue);
743 * This locks the specified vm_page and its queue in the proper order
744 * (page first, then queue). The queue may change so the caller must
745 * recheck on return.
747 static __inline
748 void
749 _vm_page_and_queue_spin_lock(vm_page_t m)
751 vm_page_spin_lock(m);
752 _vm_page_queue_spin_lock(m);
755 static __inline
756 void
757 _vm_page_and_queue_spin_unlock(vm_page_t m)
759 _vm_page_queues_spin_unlock(m->queue);
760 vm_page_spin_unlock(m);
763 void
764 vm_page_and_queue_spin_unlock(vm_page_t m)
766 _vm_page_and_queue_spin_unlock(m);
769 void
770 vm_page_and_queue_spin_lock(vm_page_t m)
772 _vm_page_and_queue_spin_lock(m);
776 * Helper function removes vm_page from its current queue.
777 * Returns the base queue the page used to be on.
779 * The vm_page and the queue must be spinlocked.
780 * This function will unlock the queue but leave the page spinlocked.
782 static __inline u_short
783 _vm_page_rem_queue_spinlocked(vm_page_t m)
785 struct vpgqueues *pq;
786 u_short queue;
787 u_short oqueue;
788 int *cnt;
790 queue = m->queue;
791 if (queue != PQ_NONE) {
792 pq = &vm_page_queues[queue];
793 TAILQ_REMOVE(&pq->pl, m, pageq);
796 * Adjust our pcpu stats. In order for the nominal low-memory
797 * algorithms to work properly we don't let any pcpu stat get
798 * too negative before we force it to be rolled-up into the
799 * global stats. Otherwise our pageout and vm_wait tests
800 * will fail badly.
802 * The idea here is to reduce unnecessary SMP cache
803 * mastership changes in the global vmstats, which can be
804 * particularly bad in multi-socket systems.
806 cnt = (int *)((char *)&mycpu->gd_vmstats + pq->cnt_offset);
807 atomic_add_int(cnt, -1);
808 if (*cnt < -VMMETER_SLOP_COUNT) {
809 u_int copy = atomic_swap_int(cnt, 0);
810 cnt = (int *)((char *)&vmstats + pq->cnt_offset);
811 atomic_add_int(cnt, copy);
813 pq->lcnt--;
814 m->queue = PQ_NONE;
815 oqueue = queue;
816 queue -= m->pc;
817 vm_page_queues_spin_unlock(oqueue); /* intended */
819 return queue;
823 * Helper function places the vm_page on the specified queue.
825 * The vm_page must be spinlocked.
826 * This function will return with both the page and the queue locked.
828 static __inline void
829 _vm_page_add_queue_spinlocked(vm_page_t m, u_short queue, int athead)
831 struct vpgqueues *pq;
832 u_int *cnt;
834 KKASSERT(m->queue == PQ_NONE);
836 if (queue != PQ_NONE) {
837 vm_page_queues_spin_lock(queue);
838 pq = &vm_page_queues[queue];
839 ++pq->lcnt;
842 * Adjust our pcpu stats. If a system entity really needs
843 * to incorporate the count it will call vmstats_rollup()
844 * to roll it all up into the global vmstats strufture.
846 cnt = (int *)((char *)&mycpu->gd_vmstats + pq->cnt_offset);
847 atomic_add_int(cnt, 1);
850 * PQ_FREE is always handled LIFO style to try to provide
851 * cache-hot pages to programs.
853 m->queue = queue;
854 if (queue - m->pc == PQ_FREE) {
855 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
856 } else if (athead) {
857 TAILQ_INSERT_HEAD(&pq->pl, m, pageq);
858 } else {
859 TAILQ_INSERT_TAIL(&pq->pl, m, pageq);
861 /* leave the queue spinlocked */
866 * Wait until page is no longer PG_BUSY or (if also_m_busy is TRUE)
867 * m->busy is zero. Returns TRUE if it had to sleep, FALSE if we
868 * did not. Only one sleep call will be made before returning.
870 * This function does NOT busy the page and on return the page is not
871 * guaranteed to be available.
873 void
874 vm_page_sleep_busy(vm_page_t m, int also_m_busy, const char *msg)
876 u_int32_t flags;
878 for (;;) {
879 flags = m->flags;
880 cpu_ccfence();
882 if ((flags & PG_BUSY) == 0 &&
883 (also_m_busy == 0 || (flags & PG_SBUSY) == 0)) {
884 break;
886 tsleep_interlock(m, 0);
887 if (atomic_cmpset_int(&m->flags, flags,
888 flags | PG_WANTED | PG_REFERENCED)) {
889 tsleep(m, PINTERLOCKED, msg, 0);
890 break;
896 * This calculates and returns a page color given an optional VM object and
897 * either a pindex or an iterator. We attempt to return a cpu-localized
898 * pg_color that is still roughly 16-way set-associative. The CPU topology
899 * is used if it was probed.
901 * The caller may use the returned value to index into e.g. PQ_FREE when
902 * allocating a page in order to nominally obtain pages that are hopefully
903 * already localized to the requesting cpu. This function is not able to
904 * provide any sort of guarantee of this, but does its best to improve
905 * hardware cache management performance.
907 * WARNING! The caller must mask the returned value with PQ_L2_MASK.
909 u_short
910 vm_get_pg_color(int cpuid, vm_object_t object, vm_pindex_t pindex)
912 u_short pg_color;
913 int phys_id;
914 int core_id;
915 int object_pg_color;
917 phys_id = get_cpu_phys_id(cpuid);
918 core_id = get_cpu_core_id(cpuid);
919 object_pg_color = object ? object->pg_color : 0;
921 if (cpu_topology_phys_ids && cpu_topology_core_ids) {
922 int grpsize = PQ_L2_SIZE / cpu_topology_phys_ids;
924 if (grpsize / cpu_topology_core_ids >= PQ_SET_ASSOC) {
926 * Enough space for a full break-down.
928 pg_color = phys_id * grpsize;
929 pg_color += core_id * grpsize / cpu_topology_core_ids;
930 pg_color += (pindex + object_pg_color) %
931 (grpsize / cpu_topology_core_ids);
932 } else {
934 * Not enough space, split up by physical package,
935 * then split up by core id but only down to a
936 * 16-set. If all else fails, force a 16-set.
938 pg_color = phys_id * grpsize;
939 if (grpsize > 16) {
940 pg_color += 16 * (core_id % (grpsize / 16));
941 grpsize = 16;
942 } else {
943 grpsize = 16;
945 pg_color += (pindex + object_pg_color) %
946 grpsize;
948 } else {
950 * Unknown topology, distribute things evenly.
952 pg_color = cpuid * PQ_L2_SIZE / ncpus;
953 pg_color += pindex + object_pg_color;
955 return pg_color;
959 * Wait until PG_BUSY can be set, then set it. If also_m_busy is TRUE we
960 * also wait for m->busy to become 0 before setting PG_BUSY.
962 void
963 VM_PAGE_DEBUG_EXT(vm_page_busy_wait)(vm_page_t m,
964 int also_m_busy, const char *msg
965 VM_PAGE_DEBUG_ARGS)
967 u_int32_t flags;
969 for (;;) {
970 flags = m->flags;
971 cpu_ccfence();
972 if (flags & PG_BUSY) {
973 tsleep_interlock(m, 0);
974 if (atomic_cmpset_int(&m->flags, flags,
975 flags | PG_WANTED | PG_REFERENCED)) {
976 tsleep(m, PINTERLOCKED, msg, 0);
978 } else if (also_m_busy && (flags & PG_SBUSY)) {
979 tsleep_interlock(m, 0);
980 if (atomic_cmpset_int(&m->flags, flags,
981 flags | PG_WANTED | PG_REFERENCED)) {
982 tsleep(m, PINTERLOCKED, msg, 0);
984 } else {
985 if (atomic_cmpset_int(&m->flags, flags,
986 flags | PG_BUSY)) {
987 #ifdef VM_PAGE_DEBUG
988 m->busy_func = func;
989 m->busy_line = lineno;
990 #endif
991 break;
998 * Attempt to set PG_BUSY. If also_m_busy is TRUE we only succeed if m->busy
999 * is also 0.
1001 * Returns non-zero on failure.
1004 VM_PAGE_DEBUG_EXT(vm_page_busy_try)(vm_page_t m, int also_m_busy
1005 VM_PAGE_DEBUG_ARGS)
1007 u_int32_t flags;
1009 for (;;) {
1010 flags = m->flags;
1011 cpu_ccfence();
1012 if (flags & PG_BUSY)
1013 return TRUE;
1014 if (also_m_busy && (flags & PG_SBUSY))
1015 return TRUE;
1016 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
1017 #ifdef VM_PAGE_DEBUG
1018 m->busy_func = func;
1019 m->busy_line = lineno;
1020 #endif
1021 return FALSE;
1027 * Clear the PG_BUSY flag and return non-zero to indicate to the caller
1028 * that a wakeup() should be performed.
1030 * The vm_page must be spinlocked and will remain spinlocked on return.
1031 * The related queue must NOT be spinlocked (which could deadlock us).
1033 * (inline version)
1035 static __inline
1037 _vm_page_wakeup(vm_page_t m)
1039 u_int32_t flags;
1041 for (;;) {
1042 flags = m->flags;
1043 cpu_ccfence();
1044 if (atomic_cmpset_int(&m->flags, flags,
1045 flags & ~(PG_BUSY | PG_WANTED))) {
1046 break;
1049 return(flags & PG_WANTED);
1053 * Clear the PG_BUSY flag and wakeup anyone waiting for the page. This
1054 * is typically the last call you make on a page before moving onto
1055 * other things.
1057 void
1058 vm_page_wakeup(vm_page_t m)
1060 KASSERT(m->flags & PG_BUSY, ("vm_page_wakeup: page not busy!!!"));
1061 vm_page_spin_lock(m);
1062 if (_vm_page_wakeup(m)) {
1063 vm_page_spin_unlock(m);
1064 wakeup(m);
1065 } else {
1066 vm_page_spin_unlock(m);
1071 * Holding a page keeps it from being reused. Other parts of the system
1072 * can still disassociate the page from its current object and free it, or
1073 * perform read or write I/O on it and/or otherwise manipulate the page,
1074 * but if the page is held the VM system will leave the page and its data
1075 * intact and not reuse the page for other purposes until the last hold
1076 * reference is released. (see vm_page_wire() if you want to prevent the
1077 * page from being disassociated from its object too).
1079 * The caller must still validate the contents of the page and, if necessary,
1080 * wait for any pending I/O (e.g. vm_page_sleep_busy() loop) to complete
1081 * before manipulating the page.
1083 * XXX get vm_page_spin_lock() here and move FREE->HOLD if necessary
1085 void
1086 vm_page_hold(vm_page_t m)
1088 vm_page_spin_lock(m);
1089 atomic_add_int(&m->hold_count, 1);
1090 if (m->queue - m->pc == PQ_FREE) {
1091 _vm_page_queue_spin_lock(m);
1092 _vm_page_rem_queue_spinlocked(m);
1093 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
1094 _vm_page_queue_spin_unlock(m);
1096 vm_page_spin_unlock(m);
1100 * The opposite of vm_page_hold(). If the page is on the HOLD queue
1101 * it was freed while held and must be moved back to the FREE queue.
1103 void
1104 vm_page_unhold(vm_page_t m)
1106 KASSERT(m->hold_count > 0 && m->queue - m->pc != PQ_FREE,
1107 ("vm_page_unhold: pg %p illegal hold_count (%d) or on FREE queue (%d)",
1108 m, m->hold_count, m->queue - m->pc));
1109 vm_page_spin_lock(m);
1110 atomic_add_int(&m->hold_count, -1);
1111 if (m->hold_count == 0 && m->queue - m->pc == PQ_HOLD) {
1112 _vm_page_queue_spin_lock(m);
1113 _vm_page_rem_queue_spinlocked(m);
1114 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
1115 _vm_page_queue_spin_unlock(m);
1117 vm_page_spin_unlock(m);
1121 * vm_page_getfake:
1123 * Create a fictitious page with the specified physical address and
1124 * memory attribute. The memory attribute is the only the machine-
1125 * dependent aspect of a fictitious page that must be initialized.
1128 void
1129 vm_page_initfake(vm_page_t m, vm_paddr_t paddr, vm_memattr_t memattr)
1132 if ((m->flags & PG_FICTITIOUS) != 0) {
1134 * The page's memattr might have changed since the
1135 * previous initialization. Update the pmap to the
1136 * new memattr.
1138 goto memattr;
1140 m->phys_addr = paddr;
1141 m->queue = PQ_NONE;
1142 /* Fictitious pages don't use "segind". */
1143 /* Fictitious pages don't use "order" or "pool". */
1144 m->flags = PG_FICTITIOUS | PG_UNMANAGED | PG_BUSY;
1145 m->wire_count = 1;
1146 spin_init(&m->spin, "fake_page");
1147 pmap_page_init(m);
1148 memattr:
1149 pmap_page_set_memattr(m, memattr);
1153 * Inserts the given vm_page into the object and object list.
1155 * The pagetables are not updated but will presumably fault the page
1156 * in if necessary, or if a kernel page the caller will at some point
1157 * enter the page into the kernel's pmap. We are not allowed to block
1158 * here so we *can't* do this anyway.
1160 * This routine may not block.
1161 * This routine must be called with the vm_object held.
1162 * This routine must be called with a critical section held.
1164 * This routine returns TRUE if the page was inserted into the object
1165 * successfully, and FALSE if the page already exists in the object.
1168 vm_page_insert(vm_page_t m, vm_object_t object, vm_pindex_t pindex)
1170 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(object));
1171 if (m->object != NULL)
1172 panic("vm_page_insert: already inserted");
1174 object->generation++;
1177 * Record the object/offset pair in this page and add the
1178 * pv_list_count of the page to the object.
1180 * The vm_page spin lock is required for interactions with the pmap.
1182 vm_page_spin_lock(m);
1183 m->object = object;
1184 m->pindex = pindex;
1185 if (vm_page_rb_tree_RB_INSERT(&object->rb_memq, m)) {
1186 m->object = NULL;
1187 m->pindex = 0;
1188 vm_page_spin_unlock(m);
1189 return FALSE;
1191 ++object->resident_page_count;
1192 ++mycpu->gd_vmtotal.t_rm;
1193 /* atomic_add_int(&object->agg_pv_list_count, m->md.pv_list_count); */
1194 vm_page_spin_unlock(m);
1197 * Since we are inserting a new and possibly dirty page,
1198 * update the object's OBJ_WRITEABLE and OBJ_MIGHTBEDIRTY flags.
1200 if ((m->valid & m->dirty) ||
1201 (m->flags & (PG_WRITEABLE | PG_NEED_COMMIT)))
1202 vm_object_set_writeable_dirty(object);
1205 * Checks for a swap assignment and sets PG_SWAPPED if appropriate.
1207 swap_pager_page_inserted(m);
1208 return TRUE;
1212 * Removes the given vm_page_t from the (object,index) table
1214 * The underlying pmap entry (if any) is NOT removed here.
1215 * This routine may not block.
1217 * The page must be BUSY and will remain BUSY on return.
1218 * No other requirements.
1220 * NOTE: FreeBSD side effect was to unbusy the page on return. We leave
1221 * it busy.
1223 void
1224 vm_page_remove(vm_page_t m)
1226 vm_object_t object;
1228 if (m->object == NULL) {
1229 return;
1232 if ((m->flags & PG_BUSY) == 0)
1233 panic("vm_page_remove: page not busy");
1235 object = m->object;
1237 vm_object_hold(object);
1240 * Remove the page from the object and update the object.
1242 * The vm_page spin lock is required for interactions with the pmap.
1244 vm_page_spin_lock(m);
1245 vm_page_rb_tree_RB_REMOVE(&object->rb_memq, m);
1246 --object->resident_page_count;
1247 --mycpu->gd_vmtotal.t_rm;
1248 /* atomic_add_int(&object->agg_pv_list_count, -m->md.pv_list_count); */
1249 m->object = NULL;
1250 vm_page_spin_unlock(m);
1252 object->generation++;
1254 vm_object_drop(object);
1258 * Locate and return the page at (object, pindex), or NULL if the
1259 * page could not be found.
1261 * The caller must hold the vm_object token.
1263 vm_page_t
1264 vm_page_lookup(vm_object_t object, vm_pindex_t pindex)
1266 vm_page_t m;
1269 * Search the hash table for this object/offset pair
1271 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1272 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1273 KKASSERT(m == NULL || (m->object == object && m->pindex == pindex));
1274 return(m);
1277 vm_page_t
1278 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_wait)(struct vm_object *object,
1279 vm_pindex_t pindex,
1280 int also_m_busy, const char *msg
1281 VM_PAGE_DEBUG_ARGS)
1283 u_int32_t flags;
1284 vm_page_t m;
1286 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1287 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1288 while (m) {
1289 KKASSERT(m->object == object && m->pindex == pindex);
1290 flags = m->flags;
1291 cpu_ccfence();
1292 if (flags & PG_BUSY) {
1293 tsleep_interlock(m, 0);
1294 if (atomic_cmpset_int(&m->flags, flags,
1295 flags | PG_WANTED | PG_REFERENCED)) {
1296 tsleep(m, PINTERLOCKED, msg, 0);
1297 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1298 pindex);
1300 } else if (also_m_busy && (flags & PG_SBUSY)) {
1301 tsleep_interlock(m, 0);
1302 if (atomic_cmpset_int(&m->flags, flags,
1303 flags | PG_WANTED | PG_REFERENCED)) {
1304 tsleep(m, PINTERLOCKED, msg, 0);
1305 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq,
1306 pindex);
1308 } else if (atomic_cmpset_int(&m->flags, flags,
1309 flags | PG_BUSY)) {
1310 #ifdef VM_PAGE_DEBUG
1311 m->busy_func = func;
1312 m->busy_line = lineno;
1313 #endif
1314 break;
1317 return m;
1321 * Attempt to lookup and busy a page.
1323 * Returns NULL if the page could not be found
1325 * Returns a vm_page and error == TRUE if the page exists but could not
1326 * be busied.
1328 * Returns a vm_page and error == FALSE on success.
1330 vm_page_t
1331 VM_PAGE_DEBUG_EXT(vm_page_lookup_busy_try)(struct vm_object *object,
1332 vm_pindex_t pindex,
1333 int also_m_busy, int *errorp
1334 VM_PAGE_DEBUG_ARGS)
1336 u_int32_t flags;
1337 vm_page_t m;
1339 ASSERT_LWKT_TOKEN_HELD(vm_object_token(object));
1340 m = vm_page_rb_tree_RB_LOOKUP(&object->rb_memq, pindex);
1341 *errorp = FALSE;
1342 while (m) {
1343 KKASSERT(m->object == object && m->pindex == pindex);
1344 flags = m->flags;
1345 cpu_ccfence();
1346 if (flags & PG_BUSY) {
1347 *errorp = TRUE;
1348 break;
1350 if (also_m_busy && (flags & PG_SBUSY)) {
1351 *errorp = TRUE;
1352 break;
1354 if (atomic_cmpset_int(&m->flags, flags, flags | PG_BUSY)) {
1355 #ifdef VM_PAGE_DEBUG
1356 m->busy_func = func;
1357 m->busy_line = lineno;
1358 #endif
1359 break;
1362 return m;
1366 * Attempt to repurpose the passed-in page. If the passed-in page cannot
1367 * be repurposed it will be released, *must_reenter will be set to 1, and
1368 * this function will fall-through to vm_page_lookup_busy_try().
1370 * The passed-in page must be wired and not busy. The returned page will
1371 * be busied and not wired.
1373 * A different page may be returned. The returned page will be busied and
1374 * not wired.
1376 * NULL can be returned. If so, the required page could not be busied.
1377 * The passed-in page will be unwired.
1379 vm_page_t
1380 vm_page_repurpose(struct vm_object *object, vm_pindex_t pindex,
1381 int also_m_busy, int *errorp, vm_page_t m,
1382 int *must_reenter, int *iswired)
1384 if (m) {
1386 * Do not mess with pages in a complex state, such as pages
1387 * which are mapped, as repurposing such pages can be more
1388 * expensive than simply allocatin a new one.
1390 * NOTE: Soft-busying can deadlock against putpages or I/O
1391 * so we only allow hard-busying here.
1393 KKASSERT(also_m_busy == FALSE);
1394 vm_page_busy_wait(m, also_m_busy, "biodep");
1396 if ((m->flags & (PG_UNMANAGED | PG_MAPPED |
1397 PG_FICTITIOUS | PG_SBUSY)) ||
1398 m->busy || m->wire_count != 1 || m->hold_count) {
1399 vm_page_unwire(m, 0);
1400 vm_page_wakeup(m);
1401 /* fall through to normal lookup */
1402 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
1403 vm_page_unwire(m, 0);
1404 vm_page_deactivate(m);
1405 vm_page_wakeup(m);
1406 /* fall through to normal lookup */
1407 } else {
1409 * We can safely repurpose the page. It should
1410 * already be unqueued.
1412 KKASSERT(m->queue == PQ_NONE && m->dirty == 0);
1413 vm_page_remove(m);
1414 m->valid = 0;
1415 m->act_count = 0;
1416 if (vm_page_insert(m, object, pindex)) {
1417 *errorp = 0;
1418 *iswired = 1;
1420 return m;
1422 vm_page_unwire(m, 0);
1423 vm_page_free(m);
1424 /* fall through to normal lookup */
1429 * Cannot repurpose page, attempt to locate the desired page. May
1430 * return NULL.
1432 *must_reenter = 1;
1433 *iswired = 0;
1434 m = vm_page_lookup_busy_try(object, pindex, also_m_busy, errorp);
1436 return m;
1440 * Caller must hold the related vm_object
1442 vm_page_t
1443 vm_page_next(vm_page_t m)
1445 vm_page_t next;
1447 next = vm_page_rb_tree_RB_NEXT(m);
1448 if (next && next->pindex != m->pindex + 1)
1449 next = NULL;
1450 return (next);
1454 * vm_page_rename()
1456 * Move the given vm_page from its current object to the specified
1457 * target object/offset. The page must be busy and will remain so
1458 * on return.
1460 * new_object must be held.
1461 * This routine might block. XXX ?
1463 * NOTE: Swap associated with the page must be invalidated by the move. We
1464 * have to do this for several reasons: (1) we aren't freeing the
1465 * page, (2) we are dirtying the page, (3) the VM system is probably
1466 * moving the page from object A to B, and will then later move
1467 * the backing store from A to B and we can't have a conflict.
1469 * NOTE: We *always* dirty the page. It is necessary both for the
1470 * fact that we moved it, and because we may be invalidating
1471 * swap. If the page is on the cache, we have to deactivate it
1472 * or vm_page_dirty() will panic. Dirty pages are not allowed
1473 * on the cache.
1475 void
1476 vm_page_rename(vm_page_t m, vm_object_t new_object, vm_pindex_t new_pindex)
1478 KKASSERT(m->flags & PG_BUSY);
1479 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(new_object));
1480 if (m->object) {
1481 ASSERT_LWKT_TOKEN_HELD_EXCL(vm_object_token(m->object));
1482 vm_page_remove(m);
1484 if (vm_page_insert(m, new_object, new_pindex) == FALSE) {
1485 panic("vm_page_rename: target exists (%p,%"PRIu64")",
1486 new_object, new_pindex);
1488 if (m->queue - m->pc == PQ_CACHE)
1489 vm_page_deactivate(m);
1490 vm_page_dirty(m);
1494 * vm_page_unqueue() without any wakeup. This routine is used when a page
1495 * is to remain BUSYied by the caller.
1497 * This routine may not block.
1499 void
1500 vm_page_unqueue_nowakeup(vm_page_t m)
1502 vm_page_and_queue_spin_lock(m);
1503 (void)_vm_page_rem_queue_spinlocked(m);
1504 vm_page_spin_unlock(m);
1508 * vm_page_unqueue() - Remove a page from its queue, wakeup the pagedemon
1509 * if necessary.
1511 * This routine may not block.
1513 void
1514 vm_page_unqueue(vm_page_t m)
1516 u_short queue;
1518 vm_page_and_queue_spin_lock(m);
1519 queue = _vm_page_rem_queue_spinlocked(m);
1520 if (queue == PQ_FREE || queue == PQ_CACHE) {
1521 vm_page_spin_unlock(m);
1522 pagedaemon_wakeup();
1523 } else {
1524 vm_page_spin_unlock(m);
1529 * vm_page_list_find()
1531 * Find a page on the specified queue with color optimization.
1533 * The page coloring optimization attempts to locate a page that does
1534 * not overload other nearby pages in the object in the cpu's L1 or L2
1535 * caches. We need this optimization because cpu caches tend to be
1536 * physical caches, while object spaces tend to be virtual.
1538 * The page coloring optimization also, very importantly, tries to localize
1539 * memory to cpus and physical sockets.
1541 * On MP systems each PQ_FREE and PQ_CACHE color queue has its own spinlock
1542 * and the algorithm is adjusted to localize allocations on a per-core basis.
1543 * This is done by 'twisting' the colors.
1545 * The page is returned spinlocked and removed from its queue (it will
1546 * be on PQ_NONE), or NULL. The page is not PG_BUSY'd. The caller
1547 * is responsible for dealing with the busy-page case (usually by
1548 * deactivating the page and looping).
1550 * NOTE: This routine is carefully inlined. A non-inlined version
1551 * is available for outside callers but the only critical path is
1552 * from within this source file.
1554 * NOTE: This routine assumes that the vm_pages found in PQ_CACHE and PQ_FREE
1555 * represent stable storage, allowing us to order our locks vm_page
1556 * first, then queue.
1558 static __inline
1559 vm_page_t
1560 _vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1562 vm_page_t m;
1564 for (;;) {
1565 if (prefer_zero) {
1566 m = TAILQ_LAST(&vm_page_queues[basequeue+index].pl,
1567 pglist);
1568 } else {
1569 m = TAILQ_FIRST(&vm_page_queues[basequeue+index].pl);
1571 if (m == NULL) {
1572 m = _vm_page_list_find2(basequeue, index);
1573 return(m);
1575 vm_page_and_queue_spin_lock(m);
1576 if (m->queue == basequeue + index) {
1577 _vm_page_rem_queue_spinlocked(m);
1578 /* vm_page_t spin held, no queue spin */
1579 break;
1581 vm_page_and_queue_spin_unlock(m);
1583 return(m);
1587 * If we could not find the page in the desired queue try to find it in
1588 * a nearby queue.
1590 static vm_page_t
1591 _vm_page_list_find2(int basequeue, int index)
1593 struct vpgqueues *pq;
1594 vm_page_t m = NULL;
1595 int pqmask = PQ_SET_ASSOC_MASK >> 1;
1596 int pqi;
1597 int i;
1599 index &= PQ_L2_MASK;
1600 pq = &vm_page_queues[basequeue];
1603 * Run local sets of 16, 32, 64, 128, and the whole queue if all
1604 * else fails (PQ_L2_MASK which is 255).
1606 do {
1607 pqmask = (pqmask << 1) | 1;
1608 for (i = 0; i <= pqmask; ++i) {
1609 pqi = (index & ~pqmask) | ((index + i) & pqmask);
1610 m = TAILQ_FIRST(&pq[pqi].pl);
1611 if (m) {
1612 _vm_page_and_queue_spin_lock(m);
1613 if (m->queue == basequeue + pqi) {
1614 _vm_page_rem_queue_spinlocked(m);
1615 return(m);
1617 _vm_page_and_queue_spin_unlock(m);
1618 --i;
1619 continue;
1622 } while (pqmask != PQ_L2_MASK);
1624 return(m);
1628 * Returns a vm_page candidate for allocation. The page is not busied so
1629 * it can move around. The caller must busy the page (and typically
1630 * deactivate it if it cannot be busied!)
1632 * Returns a spinlocked vm_page that has been removed from its queue.
1634 vm_page_t
1635 vm_page_list_find(int basequeue, int index, boolean_t prefer_zero)
1637 return(_vm_page_list_find(basequeue, index, prefer_zero));
1641 * Find a page on the cache queue with color optimization, remove it
1642 * from the queue, and busy it. The returned page will not be spinlocked.
1644 * A candidate failure will be deactivated. Candidates can fail due to
1645 * being busied by someone else, in which case they will be deactivated.
1647 * This routine may not block.
1650 static vm_page_t
1651 vm_page_select_cache(u_short pg_color)
1653 vm_page_t m;
1655 for (;;) {
1656 m = _vm_page_list_find(PQ_CACHE, pg_color & PQ_L2_MASK, FALSE);
1657 if (m == NULL)
1658 break;
1660 * (m) has been removed from its queue and spinlocked
1662 if (vm_page_busy_try(m, TRUE)) {
1663 _vm_page_deactivate_locked(m, 0);
1664 vm_page_spin_unlock(m);
1665 } else {
1667 * We successfully busied the page
1669 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) == 0 &&
1670 m->hold_count == 0 &&
1671 m->wire_count == 0 &&
1672 (m->dirty & m->valid) == 0) {
1673 vm_page_spin_unlock(m);
1674 pagedaemon_wakeup();
1675 return(m);
1679 * The page cannot be recycled, deactivate it.
1681 _vm_page_deactivate_locked(m, 0);
1682 if (_vm_page_wakeup(m)) {
1683 vm_page_spin_unlock(m);
1684 wakeup(m);
1685 } else {
1686 vm_page_spin_unlock(m);
1690 return (m);
1694 * Find a free or zero page, with specified preference. We attempt to
1695 * inline the nominal case and fall back to _vm_page_select_free()
1696 * otherwise. A busied page is removed from the queue and returned.
1698 * This routine may not block.
1700 static __inline vm_page_t
1701 vm_page_select_free(u_short pg_color, boolean_t prefer_zero)
1703 vm_page_t m;
1705 for (;;) {
1706 m = _vm_page_list_find(PQ_FREE, pg_color & PQ_L2_MASK,
1707 prefer_zero);
1708 if (m == NULL)
1709 break;
1710 if (vm_page_busy_try(m, TRUE)) {
1712 * Various mechanisms such as a pmap_collect can
1713 * result in a busy page on the free queue. We
1714 * have to move the page out of the way so we can
1715 * retry the allocation. If the other thread is not
1716 * allocating the page then m->valid will remain 0 and
1717 * the pageout daemon will free the page later on.
1719 * Since we could not busy the page, however, we
1720 * cannot make assumptions as to whether the page
1721 * will be allocated by the other thread or not,
1722 * so all we can do is deactivate it to move it out
1723 * of the way. In particular, if the other thread
1724 * wires the page it may wind up on the inactive
1725 * queue and the pageout daemon will have to deal
1726 * with that case too.
1728 _vm_page_deactivate_locked(m, 0);
1729 vm_page_spin_unlock(m);
1730 } else {
1732 * Theoretically if we are able to busy the page
1733 * atomic with the queue removal (using the vm_page
1734 * lock) nobody else should be able to mess with the
1735 * page before us.
1737 KKASSERT((m->flags & (PG_UNMANAGED |
1738 PG_NEED_COMMIT)) == 0);
1739 KASSERT(m->hold_count == 0, ("m->hold_count is not zero "
1740 "pg %p q=%d flags=%08x hold=%d wire=%d",
1741 m, m->queue, m->flags, m->hold_count, m->wire_count));
1742 KKASSERT(m->wire_count == 0);
1743 vm_page_spin_unlock(m);
1744 pagedaemon_wakeup();
1746 /* return busied and removed page */
1747 return(m);
1750 return(m);
1754 * vm_page_alloc()
1756 * Allocate and return a memory cell associated with this VM object/offset
1757 * pair. If object is NULL an unassociated page will be allocated.
1759 * The returned page will be busied and removed from its queues. This
1760 * routine can block and may return NULL if a race occurs and the page
1761 * is found to already exist at the specified (object, pindex).
1763 * VM_ALLOC_NORMAL allow use of cache pages, nominal free drain
1764 * VM_ALLOC_QUICK like normal but cannot use cache
1765 * VM_ALLOC_SYSTEM greater free drain
1766 * VM_ALLOC_INTERRUPT allow free list to be completely drained
1767 * VM_ALLOC_ZERO advisory request for pre-zero'd page only
1768 * VM_ALLOC_FORCE_ZERO advisory request for pre-zero'd page only
1769 * VM_ALLOC_NULL_OK ok to return NULL on insertion collision
1770 * (see vm_page_grab())
1771 * VM_ALLOC_USE_GD ok to use per-gd cache
1773 * VM_ALLOC_CPU(n) allocate using specified cpu localization
1775 * The object must be held if not NULL
1776 * This routine may not block
1778 * Additional special handling is required when called from an interrupt
1779 * (VM_ALLOC_INTERRUPT). We are not allowed to mess with the page cache
1780 * in this case.
1782 vm_page_t
1783 vm_page_alloc(vm_object_t object, vm_pindex_t pindex, int page_req)
1785 vm_object_t obj;
1786 vm_page_t m;
1787 u_short pg_color;
1788 int cpuid_local;
1790 #if 0
1792 * Special per-cpu free VM page cache. The pages are pre-busied
1793 * and pre-zerod for us.
1795 if (gd->gd_vmpg_count && (page_req & VM_ALLOC_USE_GD)) {
1796 crit_enter_gd(gd);
1797 if (gd->gd_vmpg_count) {
1798 m = gd->gd_vmpg_array[--gd->gd_vmpg_count];
1799 crit_exit_gd(gd);
1800 goto done;
1802 crit_exit_gd(gd);
1804 #endif
1805 m = NULL;
1808 * CPU LOCALIZATION
1810 * CPU localization algorithm. Break the page queues up by physical
1811 * id and core id (note that two cpu threads will have the same core
1812 * id, and core_id != gd_cpuid).
1814 * This is nowhere near perfect, for example the last pindex in a
1815 * subgroup will overflow into the next cpu or package. But this
1816 * should get us good page reuse locality in heavy mixed loads.
1818 * (may be executed before the APs are started, so other GDs might
1819 * not exist!)
1821 if (page_req & VM_ALLOC_CPU_SPEC)
1822 cpuid_local = VM_ALLOC_GETCPU(page_req);
1823 else
1824 cpuid_local = mycpu->gd_cpuid;
1826 pg_color = vm_get_pg_color(cpuid_local, object, pindex);
1828 KKASSERT(page_req &
1829 (VM_ALLOC_NORMAL|VM_ALLOC_QUICK|
1830 VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
1833 * Certain system threads (pageout daemon, buf_daemon's) are
1834 * allowed to eat deeper into the free page list.
1836 if (curthread->td_flags & TDF_SYSTHREAD)
1837 page_req |= VM_ALLOC_SYSTEM;
1840 * Impose various limitations. Note that the v_free_reserved test
1841 * must match the opposite of vm_page_count_target() to avoid
1842 * livelocks, be careful.
1844 loop:
1845 if (vmstats.v_free_count >= vmstats.v_free_reserved ||
1846 ((page_req & VM_ALLOC_INTERRUPT) && vmstats.v_free_count > 0) ||
1847 ((page_req & VM_ALLOC_SYSTEM) && vmstats.v_cache_count == 0 &&
1848 vmstats.v_free_count > vmstats.v_interrupt_free_min)
1851 * The free queue has sufficient free pages to take one out.
1853 if (page_req & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO))
1854 m = vm_page_select_free(pg_color, TRUE);
1855 else
1856 m = vm_page_select_free(pg_color, FALSE);
1857 } else if (page_req & VM_ALLOC_NORMAL) {
1859 * Allocatable from the cache (non-interrupt only). On
1860 * success, we must free the page and try again, thus
1861 * ensuring that vmstats.v_*_free_min counters are replenished.
1863 #ifdef INVARIANTS
1864 if (curthread->td_preempted) {
1865 kprintf("vm_page_alloc(): warning, attempt to allocate"
1866 " cache page from preempting interrupt\n");
1867 m = NULL;
1868 } else {
1869 m = vm_page_select_cache(pg_color);
1871 #else
1872 m = vm_page_select_cache(pg_color);
1873 #endif
1875 * On success move the page into the free queue and loop.
1877 * Only do this if we can safely acquire the vm_object lock,
1878 * because this is effectively a random page and the caller
1879 * might be holding the lock shared, we don't want to
1880 * deadlock.
1882 if (m != NULL) {
1883 KASSERT(m->dirty == 0,
1884 ("Found dirty cache page %p", m));
1885 if ((obj = m->object) != NULL) {
1886 if (vm_object_hold_try(obj)) {
1887 vm_page_protect(m, VM_PROT_NONE);
1888 vm_page_free(m);
1889 /* m->object NULL here */
1890 vm_object_drop(obj);
1891 } else {
1892 vm_page_deactivate(m);
1893 vm_page_wakeup(m);
1895 } else {
1896 vm_page_protect(m, VM_PROT_NONE);
1897 vm_page_free(m);
1899 goto loop;
1903 * On failure return NULL
1905 #if defined(DIAGNOSTIC)
1906 if (vmstats.v_cache_count > 0)
1907 kprintf("vm_page_alloc(NORMAL): missing pages on cache queue: %d\n", vmstats.v_cache_count);
1908 #endif
1909 atomic_add_int(&vm_pageout_deficit, 1);
1910 pagedaemon_wakeup();
1911 return (NULL);
1912 } else {
1914 * No pages available, wakeup the pageout daemon and give up.
1916 atomic_add_int(&vm_pageout_deficit, 1);
1917 pagedaemon_wakeup();
1918 return (NULL);
1922 * v_free_count can race so loop if we don't find the expected
1923 * page.
1925 if (m == NULL)
1926 goto loop;
1929 * Good page found. The page has already been busied for us and
1930 * removed from its queues.
1932 KASSERT(m->dirty == 0,
1933 ("vm_page_alloc: free/cache page %p was dirty", m));
1934 KKASSERT(m->queue == PQ_NONE);
1936 #if 0
1937 done:
1938 #endif
1940 * Initialize the structure, inheriting some flags but clearing
1941 * all the rest. The page has already been busied for us.
1943 vm_page_flag_clear(m, ~(PG_BUSY | PG_SBUSY));
1944 KKASSERT(m->wire_count == 0);
1945 KKASSERT(m->busy == 0);
1946 m->act_count = 0;
1947 m->valid = 0;
1950 * Caller must be holding the object lock (asserted by
1951 * vm_page_insert()).
1953 * NOTE: Inserting a page here does not insert it into any pmaps
1954 * (which could cause us to block allocating memory).
1956 * NOTE: If no object an unassociated page is allocated, m->pindex
1957 * can be used by the caller for any purpose.
1959 if (object) {
1960 if (vm_page_insert(m, object, pindex) == FALSE) {
1961 vm_page_free(m);
1962 if ((page_req & VM_ALLOC_NULL_OK) == 0)
1963 panic("PAGE RACE %p[%ld]/%p",
1964 object, (long)pindex, m);
1965 m = NULL;
1967 } else {
1968 m->pindex = pindex;
1972 * Don't wakeup too often - wakeup the pageout daemon when
1973 * we would be nearly out of memory.
1975 pagedaemon_wakeup();
1978 * A PG_BUSY page is returned.
1980 return (m);
1984 * Returns number of pages available in our DMA memory reserve
1985 * (adjusted with vm.dma_reserved=<value>m in /boot/loader.conf)
1987 vm_size_t
1988 vm_contig_avail_pages(void)
1990 alist_blk_t blk;
1991 alist_blk_t count;
1992 alist_blk_t bfree;
1993 spin_lock(&vm_contig_spin);
1994 bfree = alist_free_info(&vm_contig_alist, &blk, &count);
1995 spin_unlock(&vm_contig_spin);
1997 return bfree;
2001 * Attempt to allocate contiguous physical memory with the specified
2002 * requirements.
2004 vm_page_t
2005 vm_page_alloc_contig(vm_paddr_t low, vm_paddr_t high,
2006 unsigned long alignment, unsigned long boundary,
2007 unsigned long size, vm_memattr_t memattr)
2009 alist_blk_t blk;
2010 vm_page_t m;
2011 int i;
2013 alignment >>= PAGE_SHIFT;
2014 if (alignment == 0)
2015 alignment = 1;
2016 boundary >>= PAGE_SHIFT;
2017 if (boundary == 0)
2018 boundary = 1;
2019 size = (size + PAGE_MASK) >> PAGE_SHIFT;
2021 spin_lock(&vm_contig_spin);
2022 blk = alist_alloc(&vm_contig_alist, 0, size);
2023 if (blk == ALIST_BLOCK_NONE) {
2024 spin_unlock(&vm_contig_spin);
2025 if (bootverbose) {
2026 kprintf("vm_page_alloc_contig: %ldk nospace\n",
2027 (size + PAGE_MASK) * (PAGE_SIZE / 1024));
2029 return(NULL);
2031 if (high && ((vm_paddr_t)(blk + size) << PAGE_SHIFT) > high) {
2032 alist_free(&vm_contig_alist, blk, size);
2033 spin_unlock(&vm_contig_spin);
2034 if (bootverbose) {
2035 kprintf("vm_page_alloc_contig: %ldk high "
2036 "%016jx failed\n",
2037 (size + PAGE_MASK) * (PAGE_SIZE / 1024),
2038 (intmax_t)high);
2040 return(NULL);
2042 spin_unlock(&vm_contig_spin);
2043 if (vm_contig_verbose) {
2044 kprintf("vm_page_alloc_contig: %016jx/%ldk\n",
2045 (intmax_t)(vm_paddr_t)blk << PAGE_SHIFT,
2046 (size + PAGE_MASK) * (PAGE_SIZE / 1024));
2049 m = PHYS_TO_VM_PAGE((vm_paddr_t)blk << PAGE_SHIFT);
2050 if (memattr != VM_MEMATTR_DEFAULT)
2051 for (i = 0;i < size;i++)
2052 pmap_page_set_memattr(&m[i], memattr);
2053 return m;
2057 * Free contiguously allocated pages. The pages will be wired but not busy.
2058 * When freeing to the alist we leave them wired and not busy.
2060 void
2061 vm_page_free_contig(vm_page_t m, unsigned long size)
2063 vm_paddr_t pa = VM_PAGE_TO_PHYS(m);
2064 vm_pindex_t start = pa >> PAGE_SHIFT;
2065 vm_pindex_t pages = (size + PAGE_MASK) >> PAGE_SHIFT;
2067 if (vm_contig_verbose) {
2068 kprintf("vm_page_free_contig: %016jx/%ldk\n",
2069 (intmax_t)pa, size / 1024);
2071 if (pa < vm_low_phys_reserved) {
2072 KKASSERT(pa + size <= vm_low_phys_reserved);
2073 spin_lock(&vm_contig_spin);
2074 alist_free(&vm_contig_alist, start, pages);
2075 spin_unlock(&vm_contig_spin);
2076 } else {
2077 while (pages) {
2078 vm_page_busy_wait(m, FALSE, "cpgfr");
2079 vm_page_unwire(m, 0);
2080 vm_page_free(m);
2081 --pages;
2082 ++m;
2090 * Wait for sufficient free memory for nominal heavy memory use kernel
2091 * operations.
2093 * WARNING! Be sure never to call this in any vm_pageout code path, which
2094 * will trivially deadlock the system.
2096 void
2097 vm_wait_nominal(void)
2099 while (vm_page_count_min(0))
2100 vm_wait(0);
2104 * Test if vm_wait_nominal() would block.
2107 vm_test_nominal(void)
2109 if (vm_page_count_min(0))
2110 return(1);
2111 return(0);
2115 * Block until free pages are available for allocation, called in various
2116 * places before memory allocations.
2118 * The caller may loop if vm_page_count_min() == FALSE so we cannot be
2119 * more generous then that.
2121 void
2122 vm_wait(int timo)
2125 * never wait forever
2127 if (timo == 0)
2128 timo = hz;
2129 lwkt_gettoken(&vm_token);
2131 if (curthread == pagethread) {
2133 * The pageout daemon itself needs pages, this is bad.
2135 if (vm_page_count_min(0)) {
2136 vm_pageout_pages_needed = 1;
2137 tsleep(&vm_pageout_pages_needed, 0, "VMWait", timo);
2139 } else {
2141 * Wakeup the pageout daemon if necessary and wait.
2143 * Do not wait indefinitely for the target to be reached,
2144 * as load might prevent it from being reached any time soon.
2145 * But wait a little to try to slow down page allocations
2146 * and to give more important threads (the pagedaemon)
2147 * allocation priority.
2149 if (vm_page_count_target()) {
2150 if (vm_pages_needed == 0) {
2151 vm_pages_needed = 1;
2152 wakeup(&vm_pages_needed);
2154 ++vm_pages_waiting; /* SMP race ok */
2155 tsleep(&vmstats.v_free_count, 0, "vmwait", timo);
2158 lwkt_reltoken(&vm_token);
2162 * Block until free pages are available for allocation
2164 * Called only from vm_fault so that processes page faulting can be
2165 * easily tracked.
2167 void
2168 vm_wait_pfault(void)
2171 * Wakeup the pageout daemon if necessary and wait.
2173 * Do not wait indefinitely for the target to be reached,
2174 * as load might prevent it from being reached any time soon.
2175 * But wait a little to try to slow down page allocations
2176 * and to give more important threads (the pagedaemon)
2177 * allocation priority.
2179 if (vm_page_count_min(0)) {
2180 lwkt_gettoken(&vm_token);
2181 while (vm_page_count_severe()) {
2182 if (vm_page_count_target()) {
2183 thread_t td;
2185 if (vm_pages_needed == 0) {
2186 vm_pages_needed = 1;
2187 wakeup(&vm_pages_needed);
2189 ++vm_pages_waiting; /* SMP race ok */
2190 tsleep(&vmstats.v_free_count, 0, "pfault", hz);
2193 * Do not stay stuck in the loop if the system is trying
2194 * to kill the process.
2196 td = curthread;
2197 if (td->td_proc && (td->td_proc->p_flags & P_LOWMEMKILL))
2198 break;
2201 lwkt_reltoken(&vm_token);
2206 * Put the specified page on the active list (if appropriate). Ensure
2207 * that act_count is at least ACT_INIT but do not otherwise mess with it.
2209 * The caller should be holding the page busied ? XXX
2210 * This routine may not block.
2212 void
2213 vm_page_activate(vm_page_t m)
2215 u_short oqueue;
2217 vm_page_spin_lock(m);
2218 if (m->queue - m->pc != PQ_ACTIVE) {
2219 _vm_page_queue_spin_lock(m);
2220 oqueue = _vm_page_rem_queue_spinlocked(m);
2221 /* page is left spinlocked, queue is unlocked */
2223 if (oqueue == PQ_CACHE)
2224 mycpu->gd_cnt.v_reactivated++;
2225 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2226 if (m->act_count < ACT_INIT)
2227 m->act_count = ACT_INIT;
2228 _vm_page_add_queue_spinlocked(m, PQ_ACTIVE + m->pc, 0);
2230 _vm_page_and_queue_spin_unlock(m);
2231 if (oqueue == PQ_CACHE || oqueue == PQ_FREE)
2232 pagedaemon_wakeup();
2233 } else {
2234 if (m->act_count < ACT_INIT)
2235 m->act_count = ACT_INIT;
2236 vm_page_spin_unlock(m);
2241 * Helper routine for vm_page_free_toq() and vm_page_cache(). This
2242 * routine is called when a page has been added to the cache or free
2243 * queues.
2245 * This routine may not block.
2247 static __inline void
2248 vm_page_free_wakeup(void)
2251 * If the pageout daemon itself needs pages, then tell it that
2252 * there are some free.
2254 if (vm_pageout_pages_needed &&
2255 vmstats.v_cache_count + vmstats.v_free_count >=
2256 vmstats.v_pageout_free_min
2258 vm_pageout_pages_needed = 0;
2259 wakeup(&vm_pageout_pages_needed);
2263 * Wakeup processes that are waiting on memory.
2265 * Generally speaking we want to wakeup stuck processes as soon as
2266 * possible. !vm_page_count_min(0) is the absolute minimum point
2267 * where we can do this. Wait a bit longer to reduce degenerate
2268 * re-blocking (vm_page_free_hysteresis). The target check is just
2269 * to make sure the min-check w/hysteresis does not exceed the
2270 * normal target.
2272 if (vm_pages_waiting) {
2273 if (!vm_page_count_min(vm_page_free_hysteresis) ||
2274 !vm_page_count_target()) {
2275 vm_pages_waiting = 0;
2276 wakeup(&vmstats.v_free_count);
2277 ++mycpu->gd_cnt.v_ppwakeups;
2279 #if 0
2280 if (!vm_page_count_target()) {
2282 * Plenty of pages are free, wakeup everyone.
2284 vm_pages_waiting = 0;
2285 wakeup(&vmstats.v_free_count);
2286 ++mycpu->gd_cnt.v_ppwakeups;
2287 } else if (!vm_page_count_min(0)) {
2289 * Some pages are free, wakeup someone.
2291 int wcount = vm_pages_waiting;
2292 if (wcount > 0)
2293 --wcount;
2294 vm_pages_waiting = wcount;
2295 wakeup_one(&vmstats.v_free_count);
2296 ++mycpu->gd_cnt.v_ppwakeups;
2298 #endif
2303 * Returns the given page to the PQ_FREE or PQ_HOLD list and disassociates
2304 * it from its VM object.
2306 * The vm_page must be PG_BUSY on entry. PG_BUSY will be released on
2307 * return (the page will have been freed).
2309 void
2310 vm_page_free_toq(vm_page_t m)
2312 mycpu->gd_cnt.v_tfree++;
2313 KKASSERT((m->flags & PG_MAPPED) == 0);
2314 KKASSERT(m->flags & PG_BUSY);
2316 if (m->busy || ((m->queue - m->pc) == PQ_FREE)) {
2317 kprintf("vm_page_free: pindex(%lu), busy(%d), "
2318 "PG_BUSY(%d), hold(%d)\n",
2319 (u_long)m->pindex, m->busy,
2320 ((m->flags & PG_BUSY) ? 1 : 0), m->hold_count);
2321 if ((m->queue - m->pc) == PQ_FREE)
2322 panic("vm_page_free: freeing free page");
2323 else
2324 panic("vm_page_free: freeing busy page");
2328 * Remove from object, spinlock the page and its queues and
2329 * remove from any queue. No queue spinlock will be held
2330 * after this section (because the page was removed from any
2331 * queue).
2333 vm_page_remove(m);
2334 vm_page_and_queue_spin_lock(m);
2335 _vm_page_rem_queue_spinlocked(m);
2338 * No further management of fictitious pages occurs beyond object
2339 * and queue removal.
2341 if ((m->flags & PG_FICTITIOUS) != 0) {
2342 vm_page_spin_unlock(m);
2343 vm_page_wakeup(m);
2344 return;
2347 m->valid = 0;
2348 vm_page_undirty(m);
2350 if (m->wire_count != 0) {
2351 if (m->wire_count > 1) {
2352 panic(
2353 "vm_page_free: invalid wire count (%d), pindex: 0x%lx",
2354 m->wire_count, (long)m->pindex);
2356 panic("vm_page_free: freeing wired page");
2360 * Clear the UNMANAGED flag when freeing an unmanaged page.
2361 * Clear the NEED_COMMIT flag
2363 if (m->flags & PG_UNMANAGED)
2364 vm_page_flag_clear(m, PG_UNMANAGED);
2365 if (m->flags & PG_NEED_COMMIT)
2366 vm_page_flag_clear(m, PG_NEED_COMMIT);
2368 if (m->hold_count != 0) {
2369 _vm_page_add_queue_spinlocked(m, PQ_HOLD + m->pc, 0);
2370 } else {
2371 _vm_page_add_queue_spinlocked(m, PQ_FREE + m->pc, 0);
2375 * This sequence allows us to clear PG_BUSY while still holding
2376 * its spin lock, which reduces contention vs allocators. We
2377 * must not leave the queue locked or _vm_page_wakeup() may
2378 * deadlock.
2380 _vm_page_queue_spin_unlock(m);
2381 if (_vm_page_wakeup(m)) {
2382 vm_page_spin_unlock(m);
2383 wakeup(m);
2384 } else {
2385 vm_page_spin_unlock(m);
2387 vm_page_free_wakeup();
2391 * vm_page_unmanage()
2393 * Prevent PV management from being done on the page. The page is
2394 * removed from the paging queues as if it were wired, and as a
2395 * consequence of no longer being managed the pageout daemon will not
2396 * touch it (since there is no way to locate the pte mappings for the
2397 * page). madvise() calls that mess with the pmap will also no longer
2398 * operate on the page.
2400 * Beyond that the page is still reasonably 'normal'. Freeing the page
2401 * will clear the flag.
2403 * This routine is used by OBJT_PHYS objects - objects using unswappable
2404 * physical memory as backing store rather then swap-backed memory and
2405 * will eventually be extended to support 4MB unmanaged physical
2406 * mappings.
2408 * Caller must be holding the page busy.
2410 void
2411 vm_page_unmanage(vm_page_t m)
2413 KKASSERT(m->flags & PG_BUSY);
2414 if ((m->flags & PG_UNMANAGED) == 0) {
2415 if (m->wire_count == 0)
2416 vm_page_unqueue(m);
2418 vm_page_flag_set(m, PG_UNMANAGED);
2422 * Mark this page as wired down by yet another map, removing it from
2423 * paging queues as necessary.
2425 * Caller must be holding the page busy.
2427 void
2428 vm_page_wire(vm_page_t m)
2431 * Only bump the wire statistics if the page is not already wired,
2432 * and only unqueue the page if it is on some queue (if it is unmanaged
2433 * it is already off the queues). Don't do anything with fictitious
2434 * pages because they are always wired.
2436 KKASSERT(m->flags & PG_BUSY);
2437 if ((m->flags & PG_FICTITIOUS) == 0) {
2438 if (atomic_fetchadd_int(&m->wire_count, 1) == 0) {
2439 if ((m->flags & PG_UNMANAGED) == 0)
2440 vm_page_unqueue(m);
2441 atomic_add_int(&mycpu->gd_vmstats.v_wire_count, 1);
2443 KASSERT(m->wire_count != 0,
2444 ("vm_page_wire: wire_count overflow m=%p", m));
2449 * Release one wiring of this page, potentially enabling it to be paged again.
2451 * Many pages placed on the inactive queue should actually go
2452 * into the cache, but it is difficult to figure out which. What
2453 * we do instead, if the inactive target is well met, is to put
2454 * clean pages at the head of the inactive queue instead of the tail.
2455 * This will cause them to be moved to the cache more quickly and
2456 * if not actively re-referenced, freed more quickly. If we just
2457 * stick these pages at the end of the inactive queue, heavy filesystem
2458 * meta-data accesses can cause an unnecessary paging load on memory bound
2459 * processes. This optimization causes one-time-use metadata to be
2460 * reused more quickly.
2462 * Pages marked PG_NEED_COMMIT are always activated and never placed on
2463 * the inactive queue. This helps the pageout daemon determine memory
2464 * pressure and act on out-of-memory situations more quickly.
2466 * BUT, if we are in a low-memory situation we have no choice but to
2467 * put clean pages on the cache queue.
2469 * A number of routines use vm_page_unwire() to guarantee that the page
2470 * will go into either the inactive or active queues, and will NEVER
2471 * be placed in the cache - for example, just after dirtying a page.
2472 * dirty pages in the cache are not allowed.
2474 * This routine may not block.
2476 void
2477 vm_page_unwire(vm_page_t m, int activate)
2479 KKASSERT(m->flags & PG_BUSY);
2480 if (m->flags & PG_FICTITIOUS) {
2481 /* do nothing */
2482 } else if (m->wire_count <= 0) {
2483 panic("vm_page_unwire: invalid wire count: %d", m->wire_count);
2484 } else {
2485 if (atomic_fetchadd_int(&m->wire_count, -1) == 1) {
2486 atomic_add_int(&mycpu->gd_vmstats.v_wire_count, -1);
2487 if (m->flags & PG_UNMANAGED) {
2489 } else if (activate || (m->flags & PG_NEED_COMMIT)) {
2490 vm_page_spin_lock(m);
2491 _vm_page_add_queue_spinlocked(m,
2492 PQ_ACTIVE + m->pc, 0);
2493 _vm_page_and_queue_spin_unlock(m);
2494 } else {
2495 vm_page_spin_lock(m);
2496 vm_page_flag_clear(m, PG_WINATCFLS);
2497 _vm_page_add_queue_spinlocked(m,
2498 PQ_INACTIVE + m->pc, 0);
2499 ++vm_swapcache_inactive_heuristic;
2500 _vm_page_and_queue_spin_unlock(m);
2507 * Move the specified page to the inactive queue. If the page has
2508 * any associated swap, the swap is deallocated.
2510 * Normally athead is 0 resulting in LRU operation. athead is set
2511 * to 1 if we want this page to be 'as if it were placed in the cache',
2512 * except without unmapping it from the process address space.
2514 * vm_page's spinlock must be held on entry and will remain held on return.
2515 * This routine may not block.
2517 static void
2518 _vm_page_deactivate_locked(vm_page_t m, int athead)
2520 u_short oqueue;
2523 * Ignore if already inactive.
2525 if (m->queue - m->pc == PQ_INACTIVE)
2526 return;
2527 _vm_page_queue_spin_lock(m);
2528 oqueue = _vm_page_rem_queue_spinlocked(m);
2530 if (m->wire_count == 0 && (m->flags & PG_UNMANAGED) == 0) {
2531 if (oqueue == PQ_CACHE)
2532 mycpu->gd_cnt.v_reactivated++;
2533 vm_page_flag_clear(m, PG_WINATCFLS);
2534 _vm_page_add_queue_spinlocked(m, PQ_INACTIVE + m->pc, athead);
2535 if (athead == 0)
2536 ++vm_swapcache_inactive_heuristic;
2538 /* NOTE: PQ_NONE if condition not taken */
2539 _vm_page_queue_spin_unlock(m);
2540 /* leaves vm_page spinlocked */
2544 * Attempt to deactivate a page.
2546 * No requirements.
2548 void
2549 vm_page_deactivate(vm_page_t m)
2551 vm_page_spin_lock(m);
2552 _vm_page_deactivate_locked(m, 0);
2553 vm_page_spin_unlock(m);
2556 void
2557 vm_page_deactivate_locked(vm_page_t m)
2559 _vm_page_deactivate_locked(m, 0);
2563 * Attempt to move a busied page to PQ_CACHE, then unconditionally unbusy it.
2565 * This function returns non-zero if it successfully moved the page to
2566 * PQ_CACHE.
2568 * This function unconditionally unbusies the page on return.
2571 vm_page_try_to_cache(vm_page_t m)
2573 vm_page_spin_lock(m);
2574 if (m->dirty || m->hold_count || m->wire_count ||
2575 (m->flags & (PG_UNMANAGED | PG_NEED_COMMIT))) {
2576 if (_vm_page_wakeup(m)) {
2577 vm_page_spin_unlock(m);
2578 wakeup(m);
2579 } else {
2580 vm_page_spin_unlock(m);
2582 return(0);
2584 vm_page_spin_unlock(m);
2587 * Page busied by us and no longer spinlocked. Dirty pages cannot
2588 * be moved to the cache.
2590 vm_page_test_dirty(m);
2591 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2592 vm_page_wakeup(m);
2593 return(0);
2595 vm_page_cache(m);
2596 return(1);
2600 * Attempt to free the page. If we cannot free it, we do nothing.
2601 * 1 is returned on success, 0 on failure.
2603 * No requirements.
2606 vm_page_try_to_free(vm_page_t m)
2608 vm_page_spin_lock(m);
2609 if (vm_page_busy_try(m, TRUE)) {
2610 vm_page_spin_unlock(m);
2611 return(0);
2615 * The page can be in any state, including already being on the free
2616 * queue. Check to see if it really can be freed.
2618 if (m->dirty || /* can't free if it is dirty */
2619 m->hold_count || /* or held (XXX may be wrong) */
2620 m->wire_count || /* or wired */
2621 (m->flags & (PG_UNMANAGED | /* or unmanaged */
2622 PG_NEED_COMMIT)) || /* or needs a commit */
2623 m->queue - m->pc == PQ_FREE || /* already on PQ_FREE */
2624 m->queue - m->pc == PQ_HOLD) { /* already on PQ_HOLD */
2625 if (_vm_page_wakeup(m)) {
2626 vm_page_spin_unlock(m);
2627 wakeup(m);
2628 } else {
2629 vm_page_spin_unlock(m);
2631 return(0);
2633 vm_page_spin_unlock(m);
2636 * We can probably free the page.
2638 * Page busied by us and no longer spinlocked. Dirty pages will
2639 * not be freed by this function. We have to re-test the
2640 * dirty bit after cleaning out the pmaps.
2642 vm_page_test_dirty(m);
2643 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2644 vm_page_wakeup(m);
2645 return(0);
2647 vm_page_protect(m, VM_PROT_NONE);
2648 if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2649 vm_page_wakeup(m);
2650 return(0);
2652 vm_page_free(m);
2653 return(1);
2657 * vm_page_cache
2659 * Put the specified page onto the page cache queue (if appropriate).
2661 * The page must be busy, and this routine will release the busy and
2662 * possibly even free the page.
2664 void
2665 vm_page_cache(vm_page_t m)
2668 * Not suitable for the cache
2670 if ((m->flags & (PG_UNMANAGED | PG_NEED_COMMIT)) ||
2671 m->busy || m->wire_count || m->hold_count) {
2672 vm_page_wakeup(m);
2673 return;
2677 * Already in the cache (and thus not mapped)
2679 if ((m->queue - m->pc) == PQ_CACHE) {
2680 KKASSERT((m->flags & PG_MAPPED) == 0);
2681 vm_page_wakeup(m);
2682 return;
2686 * Caller is required to test m->dirty, but note that the act of
2687 * removing the page from its maps can cause it to become dirty
2688 * on an SMP system due to another cpu running in usermode.
2690 if (m->dirty) {
2691 panic("vm_page_cache: caching a dirty page, pindex: %ld",
2692 (long)m->pindex);
2696 * Remove all pmaps and indicate that the page is not
2697 * writeable or mapped. Our vm_page_protect() call may
2698 * have blocked (especially w/ VM_PROT_NONE), so recheck
2699 * everything.
2701 vm_page_protect(m, VM_PROT_NONE);
2702 if ((m->flags & (PG_UNMANAGED | PG_MAPPED)) ||
2703 m->busy || m->wire_count || m->hold_count) {
2704 vm_page_wakeup(m);
2705 } else if (m->dirty || (m->flags & PG_NEED_COMMIT)) {
2706 vm_page_deactivate(m);
2707 vm_page_wakeup(m);
2708 } else {
2709 _vm_page_and_queue_spin_lock(m);
2710 _vm_page_rem_queue_spinlocked(m);
2711 _vm_page_add_queue_spinlocked(m, PQ_CACHE + m->pc, 0);
2712 _vm_page_queue_spin_unlock(m);
2713 if (_vm_page_wakeup(m)) {
2714 vm_page_spin_unlock(m);
2715 wakeup(m);
2716 } else {
2717 vm_page_spin_unlock(m);
2719 vm_page_free_wakeup();
2724 * vm_page_dontneed()
2726 * Cache, deactivate, or do nothing as appropriate. This routine
2727 * is typically used by madvise() MADV_DONTNEED.
2729 * Generally speaking we want to move the page into the cache so
2730 * it gets reused quickly. However, this can result in a silly syndrome
2731 * due to the page recycling too quickly. Small objects will not be
2732 * fully cached. On the otherhand, if we move the page to the inactive
2733 * queue we wind up with a problem whereby very large objects
2734 * unnecessarily blow away our inactive and cache queues.
2736 * The solution is to move the pages based on a fixed weighting. We
2737 * either leave them alone, deactivate them, or move them to the cache,
2738 * where moving them to the cache has the highest weighting.
2739 * By forcing some pages into other queues we eventually force the
2740 * system to balance the queues, potentially recovering other unrelated
2741 * space from active. The idea is to not force this to happen too
2742 * often.
2744 * The page must be busied.
2746 void
2747 vm_page_dontneed(vm_page_t m)
2749 static int dnweight;
2750 int dnw;
2751 int head;
2753 dnw = ++dnweight;
2756 * occassionally leave the page alone
2758 if ((dnw & 0x01F0) == 0 ||
2759 m->queue - m->pc == PQ_INACTIVE ||
2760 m->queue - m->pc == PQ_CACHE
2762 if (m->act_count >= ACT_INIT)
2763 --m->act_count;
2764 return;
2768 * If vm_page_dontneed() is inactivating a page, it must clear
2769 * the referenced flag; otherwise the pagedaemon will see references
2770 * on the page in the inactive queue and reactivate it. Until the
2771 * page can move to the cache queue, madvise's job is not done.
2773 vm_page_flag_clear(m, PG_REFERENCED);
2774 pmap_clear_reference(m);
2776 if (m->dirty == 0)
2777 vm_page_test_dirty(m);
2779 if (m->dirty || (dnw & 0x0070) == 0) {
2781 * Deactivate the page 3 times out of 32.
2783 head = 0;
2784 } else {
2786 * Cache the page 28 times out of every 32. Note that
2787 * the page is deactivated instead of cached, but placed
2788 * at the head of the queue instead of the tail.
2790 head = 1;
2792 vm_page_spin_lock(m);
2793 _vm_page_deactivate_locked(m, head);
2794 vm_page_spin_unlock(m);
2798 * These routines manipulate the 'soft busy' count for a page. A soft busy
2799 * is almost like PG_BUSY except that it allows certain compatible operations
2800 * to occur on the page while it is busy. For example, a page undergoing a
2801 * write can still be mapped read-only.
2803 * Because vm_pages can overlap buffers m->busy can be > 1. m->busy is only
2804 * adjusted while the vm_page is PG_BUSY so the flash will occur when the
2805 * busy bit is cleared.
2807 void
2808 vm_page_io_start(vm_page_t m)
2810 KASSERT(m->flags & PG_BUSY, ("vm_page_io_start: page not busy!!!"));
2811 atomic_add_char(&m->busy, 1);
2812 vm_page_flag_set(m, PG_SBUSY);
2815 void
2816 vm_page_io_finish(vm_page_t m)
2818 KASSERT(m->flags & PG_BUSY, ("vm_page_io_finish: page not busy!!!"));
2819 atomic_subtract_char(&m->busy, 1);
2820 if (m->busy == 0)
2821 vm_page_flag_clear(m, PG_SBUSY);
2825 * Indicate that a clean VM page requires a filesystem commit and cannot
2826 * be reused. Used by tmpfs.
2828 void
2829 vm_page_need_commit(vm_page_t m)
2831 vm_page_flag_set(m, PG_NEED_COMMIT);
2832 vm_object_set_writeable_dirty(m->object);
2835 void
2836 vm_page_clear_commit(vm_page_t m)
2838 vm_page_flag_clear(m, PG_NEED_COMMIT);
2842 * Grab a page, blocking if it is busy and allocating a page if necessary.
2843 * A busy page is returned or NULL. The page may or may not be valid and
2844 * might not be on a queue (the caller is responsible for the disposition of
2845 * the page).
2847 * If VM_ALLOC_ZERO is specified and the grab must allocate a new page, the
2848 * page will be zero'd and marked valid.
2850 * If VM_ALLOC_FORCE_ZERO is specified the page will be zero'd and marked
2851 * valid even if it already exists.
2853 * If VM_ALLOC_RETRY is specified this routine will never return NULL. Also
2854 * note that VM_ALLOC_NORMAL must be specified if VM_ALLOC_RETRY is specified.
2855 * VM_ALLOC_NULL_OK is implied when VM_ALLOC_RETRY is specified.
2857 * This routine may block, but if VM_ALLOC_RETRY is not set then NULL is
2858 * always returned if we had blocked.
2860 * This routine may not be called from an interrupt.
2862 * No other requirements.
2864 vm_page_t
2865 vm_page_grab(vm_object_t object, vm_pindex_t pindex, int allocflags)
2867 vm_page_t m;
2868 int error;
2869 int shared = 1;
2871 KKASSERT(allocflags &
2872 (VM_ALLOC_NORMAL|VM_ALLOC_INTERRUPT|VM_ALLOC_SYSTEM));
2873 vm_object_hold_shared(object);
2874 for (;;) {
2875 m = vm_page_lookup_busy_try(object, pindex, TRUE, &error);
2876 if (error) {
2877 vm_page_sleep_busy(m, TRUE, "pgrbwt");
2878 if ((allocflags & VM_ALLOC_RETRY) == 0) {
2879 m = NULL;
2880 break;
2882 /* retry */
2883 } else if (m == NULL) {
2884 if (shared) {
2885 vm_object_upgrade(object);
2886 shared = 0;
2888 if (allocflags & VM_ALLOC_RETRY)
2889 allocflags |= VM_ALLOC_NULL_OK;
2890 m = vm_page_alloc(object, pindex,
2891 allocflags & ~VM_ALLOC_RETRY);
2892 if (m)
2893 break;
2894 vm_wait(0);
2895 if ((allocflags & VM_ALLOC_RETRY) == 0)
2896 goto failed;
2897 } else {
2898 /* m found */
2899 break;
2904 * If VM_ALLOC_ZERO an invalid page will be zero'd and set valid.
2906 * If VM_ALLOC_FORCE_ZERO the page is unconditionally zero'd and set
2907 * valid even if already valid.
2909 * NOTE! We have removed all of the PG_ZERO optimizations and also
2910 * removed the idle zeroing code. These optimizations actually
2911 * slow things down on modern cpus because the zerod area is
2912 * likely uncached, placing a memory-access burden on the
2913 * accesors taking the fault.
2915 * By always zeroing the page in-line with the fault, no
2916 * dynamic ram reads are needed and the caches are hot, ready
2917 * for userland to access the memory.
2919 if (m->valid == 0) {
2920 if (allocflags & (VM_ALLOC_ZERO | VM_ALLOC_FORCE_ZERO)) {
2921 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2922 m->valid = VM_PAGE_BITS_ALL;
2924 } else if (allocflags & VM_ALLOC_FORCE_ZERO) {
2925 pmap_zero_page(VM_PAGE_TO_PHYS(m));
2926 m->valid = VM_PAGE_BITS_ALL;
2928 failed:
2929 vm_object_drop(object);
2930 return(m);
2934 * Mapping function for valid bits or for dirty bits in
2935 * a page. May not block.
2937 * Inputs are required to range within a page.
2939 * No requirements.
2940 * Non blocking.
2943 vm_page_bits(int base, int size)
2945 int first_bit;
2946 int last_bit;
2948 KASSERT(
2949 base + size <= PAGE_SIZE,
2950 ("vm_page_bits: illegal base/size %d/%d", base, size)
2953 if (size == 0) /* handle degenerate case */
2954 return(0);
2956 first_bit = base >> DEV_BSHIFT;
2957 last_bit = (base + size - 1) >> DEV_BSHIFT;
2959 return ((2 << last_bit) - (1 << first_bit));
2963 * Sets portions of a page valid and clean. The arguments are expected
2964 * to be DEV_BSIZE aligned but if they aren't the bitmap is inclusive
2965 * of any partial chunks touched by the range. The invalid portion of
2966 * such chunks will be zero'd.
2968 * NOTE: When truncating a buffer vnode_pager_setsize() will automatically
2969 * align base to DEV_BSIZE so as not to mark clean a partially
2970 * truncated device block. Otherwise the dirty page status might be
2971 * lost.
2973 * This routine may not block.
2975 * (base + size) must be less then or equal to PAGE_SIZE.
2977 static void
2978 _vm_page_zero_valid(vm_page_t m, int base, int size)
2980 int frag;
2981 int endoff;
2983 if (size == 0) /* handle degenerate case */
2984 return;
2987 * If the base is not DEV_BSIZE aligned and the valid
2988 * bit is clear, we have to zero out a portion of the
2989 * first block.
2992 if ((frag = base & ~(DEV_BSIZE - 1)) != base &&
2993 (m->valid & (1 << (base >> DEV_BSHIFT))) == 0
2995 pmap_zero_page_area(
2996 VM_PAGE_TO_PHYS(m),
2997 frag,
2998 base - frag
3003 * If the ending offset is not DEV_BSIZE aligned and the
3004 * valid bit is clear, we have to zero out a portion of
3005 * the last block.
3008 endoff = base + size;
3010 if ((frag = endoff & ~(DEV_BSIZE - 1)) != endoff &&
3011 (m->valid & (1 << (endoff >> DEV_BSHIFT))) == 0
3013 pmap_zero_page_area(
3014 VM_PAGE_TO_PHYS(m),
3015 endoff,
3016 DEV_BSIZE - (endoff & (DEV_BSIZE - 1))
3022 * Set valid, clear dirty bits. If validating the entire
3023 * page we can safely clear the pmap modify bit. We also
3024 * use this opportunity to clear the PG_NOSYNC flag. If a process
3025 * takes a write fault on a MAP_NOSYNC memory area the flag will
3026 * be set again.
3028 * We set valid bits inclusive of any overlap, but we can only
3029 * clear dirty bits for DEV_BSIZE chunks that are fully within
3030 * the range.
3032 * Page must be busied?
3033 * No other requirements.
3035 void
3036 vm_page_set_valid(vm_page_t m, int base, int size)
3038 _vm_page_zero_valid(m, base, size);
3039 m->valid |= vm_page_bits(base, size);
3044 * Set valid bits and clear dirty bits.
3046 * NOTE: This function does not clear the pmap modified bit.
3047 * Also note that e.g. NFS may use a byte-granular base
3048 * and size.
3050 * WARNING: Page must be busied? But vfs_clean_one_page() will call
3051 * this without necessarily busying the page (via bdwrite()).
3052 * So for now vm_token must also be held.
3054 * No other requirements.
3056 void
3057 vm_page_set_validclean(vm_page_t m, int base, int size)
3059 int pagebits;
3061 _vm_page_zero_valid(m, base, size);
3062 pagebits = vm_page_bits(base, size);
3063 m->valid |= pagebits;
3064 m->dirty &= ~pagebits;
3065 if (base == 0 && size == PAGE_SIZE) {
3066 /*pmap_clear_modify(m);*/
3067 vm_page_flag_clear(m, PG_NOSYNC);
3072 * Set valid & dirty. Used by buwrite()
3074 * WARNING: Page must be busied? But vfs_dirty_one_page() will
3075 * call this function in buwrite() so for now vm_token must
3076 * be held.
3078 * No other requirements.
3080 void
3081 vm_page_set_validdirty(vm_page_t m, int base, int size)
3083 int pagebits;
3085 pagebits = vm_page_bits(base, size);
3086 m->valid |= pagebits;
3087 m->dirty |= pagebits;
3088 if (m->object)
3089 vm_object_set_writeable_dirty(m->object);
3093 * Clear dirty bits.
3095 * NOTE: This function does not clear the pmap modified bit.
3096 * Also note that e.g. NFS may use a byte-granular base
3097 * and size.
3099 * Page must be busied?
3100 * No other requirements.
3102 void
3103 vm_page_clear_dirty(vm_page_t m, int base, int size)
3105 m->dirty &= ~vm_page_bits(base, size);
3106 if (base == 0 && size == PAGE_SIZE) {
3107 /*pmap_clear_modify(m);*/
3108 vm_page_flag_clear(m, PG_NOSYNC);
3113 * Make the page all-dirty.
3115 * Also make sure the related object and vnode reflect the fact that the
3116 * object may now contain a dirty page.
3118 * Page must be busied?
3119 * No other requirements.
3121 void
3122 vm_page_dirty(vm_page_t m)
3124 #ifdef INVARIANTS
3125 int pqtype = m->queue - m->pc;
3126 #endif
3127 KASSERT(pqtype != PQ_CACHE && pqtype != PQ_FREE,
3128 ("vm_page_dirty: page in free/cache queue!"));
3129 if (m->dirty != VM_PAGE_BITS_ALL) {
3130 m->dirty = VM_PAGE_BITS_ALL;
3131 if (m->object)
3132 vm_object_set_writeable_dirty(m->object);
3137 * Invalidates DEV_BSIZE'd chunks within a page. Both the
3138 * valid and dirty bits for the effected areas are cleared.
3140 * Page must be busied?
3141 * Does not block.
3142 * No other requirements.
3144 void
3145 vm_page_set_invalid(vm_page_t m, int base, int size)
3147 int bits;
3149 bits = vm_page_bits(base, size);
3150 m->valid &= ~bits;
3151 m->dirty &= ~bits;
3152 m->object->generation++;
3156 * The kernel assumes that the invalid portions of a page contain
3157 * garbage, but such pages can be mapped into memory by user code.
3158 * When this occurs, we must zero out the non-valid portions of the
3159 * page so user code sees what it expects.
3161 * Pages are most often semi-valid when the end of a file is mapped
3162 * into memory and the file's size is not page aligned.
3164 * Page must be busied?
3165 * No other requirements.
3167 void
3168 vm_page_zero_invalid(vm_page_t m, boolean_t setvalid)
3170 int b;
3171 int i;
3174 * Scan the valid bits looking for invalid sections that
3175 * must be zerod. Invalid sub-DEV_BSIZE'd areas ( where the
3176 * valid bit may be set ) have already been zerod by
3177 * vm_page_set_validclean().
3179 for (b = i = 0; i <= PAGE_SIZE / DEV_BSIZE; ++i) {
3180 if (i == (PAGE_SIZE / DEV_BSIZE) ||
3181 (m->valid & (1 << i))
3183 if (i > b) {
3184 pmap_zero_page_area(
3185 VM_PAGE_TO_PHYS(m),
3186 b << DEV_BSHIFT,
3187 (i - b) << DEV_BSHIFT
3190 b = i + 1;
3195 * setvalid is TRUE when we can safely set the zero'd areas
3196 * as being valid. We can do this if there are no cache consistency
3197 * issues. e.g. it is ok to do with UFS, but not ok to do with NFS.
3199 if (setvalid)
3200 m->valid = VM_PAGE_BITS_ALL;
3204 * Is a (partial) page valid? Note that the case where size == 0
3205 * will return FALSE in the degenerate case where the page is entirely
3206 * invalid, and TRUE otherwise.
3208 * Does not block.
3209 * No other requirements.
3212 vm_page_is_valid(vm_page_t m, int base, int size)
3214 int bits = vm_page_bits(base, size);
3216 if (m->valid && ((m->valid & bits) == bits))
3217 return 1;
3218 else
3219 return 0;
3223 * update dirty bits from pmap/mmu. May not block.
3225 * Caller must hold the page busy
3227 void
3228 vm_page_test_dirty(vm_page_t m)
3230 if ((m->dirty != VM_PAGE_BITS_ALL) && pmap_is_modified(m)) {
3231 vm_page_dirty(m);
3236 * Register an action, associating it with its vm_page
3238 void
3239 vm_page_register_action(vm_page_action_t action, vm_page_event_t event)
3241 struct vm_page_action_list *list;
3242 int hv;
3244 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3245 list = &action_list[hv];
3247 lwkt_gettoken(&vm_token);
3248 vm_page_flag_set(action->m, PG_ACTIONLIST);
3249 action->event = event;
3250 LIST_INSERT_HEAD(list, action, entry);
3251 lwkt_reltoken(&vm_token);
3255 * Unregister an action, disassociating it from its related vm_page
3257 void
3258 vm_page_unregister_action(vm_page_action_t action)
3260 struct vm_page_action_list *list;
3261 int hv;
3263 lwkt_gettoken(&vm_token);
3264 if (action->event != VMEVENT_NONE) {
3265 action->event = VMEVENT_NONE;
3266 LIST_REMOVE(action, entry);
3268 hv = (int)((intptr_t)action->m >> 8) & VMACTION_HMASK;
3269 list = &action_list[hv];
3270 if (LIST_EMPTY(list))
3271 vm_page_flag_clear(action->m, PG_ACTIONLIST);
3273 lwkt_reltoken(&vm_token);
3277 * Issue an event on a VM page. Corresponding action structures are
3278 * removed from the page's list and called.
3280 * If the vm_page has no more pending action events we clear its
3281 * PG_ACTIONLIST flag.
3283 void
3284 vm_page_event_internal(vm_page_t m, vm_page_event_t event)
3286 struct vm_page_action_list *list;
3287 struct vm_page_action *scan;
3288 struct vm_page_action *next;
3289 int hv;
3290 int all;
3292 hv = (int)((intptr_t)m >> 8) & VMACTION_HMASK;
3293 list = &action_list[hv];
3294 all = 1;
3296 lwkt_gettoken(&vm_token);
3297 LIST_FOREACH_MUTABLE(scan, list, entry, next) {
3298 if (scan->m == m) {
3299 if (scan->event == event) {
3300 scan->event = VMEVENT_NONE;
3301 LIST_REMOVE(scan, entry);
3302 scan->func(m, scan);
3303 /* XXX */
3304 } else {
3305 all = 0;
3309 if (all)
3310 vm_page_flag_clear(m, PG_ACTIONLIST);
3311 lwkt_reltoken(&vm_token);
3314 #include "opt_ddb.h"
3315 #ifdef DDB
3316 #include <sys/kernel.h>
3318 #include <ddb/ddb.h>
3320 DB_SHOW_COMMAND(page, vm_page_print_page_info)
3322 db_printf("vmstats.v_free_count: %d\n", vmstats.v_free_count);
3323 db_printf("vmstats.v_cache_count: %d\n", vmstats.v_cache_count);
3324 db_printf("vmstats.v_inactive_count: %d\n", vmstats.v_inactive_count);
3325 db_printf("vmstats.v_active_count: %d\n", vmstats.v_active_count);
3326 db_printf("vmstats.v_wire_count: %d\n", vmstats.v_wire_count);
3327 db_printf("vmstats.v_free_reserved: %d\n", vmstats.v_free_reserved);
3328 db_printf("vmstats.v_free_min: %d\n", vmstats.v_free_min);
3329 db_printf("vmstats.v_free_target: %d\n", vmstats.v_free_target);
3330 db_printf("vmstats.v_cache_min: %d\n", vmstats.v_cache_min);
3331 db_printf("vmstats.v_inactive_target: %d\n", vmstats.v_inactive_target);
3334 DB_SHOW_COMMAND(pageq, vm_page_print_pageq_info)
3336 int i;
3337 db_printf("PQ_FREE:");
3338 for(i=0;i<PQ_L2_SIZE;i++) {
3339 db_printf(" %d", vm_page_queues[PQ_FREE + i].lcnt);
3341 db_printf("\n");
3343 db_printf("PQ_CACHE:");
3344 for(i=0;i<PQ_L2_SIZE;i++) {
3345 db_printf(" %d", vm_page_queues[PQ_CACHE + i].lcnt);
3347 db_printf("\n");
3349 db_printf("PQ_ACTIVE:");
3350 for(i=0;i<PQ_L2_SIZE;i++) {
3351 db_printf(" %d", vm_page_queues[PQ_ACTIVE + i].lcnt);
3353 db_printf("\n");
3355 db_printf("PQ_INACTIVE:");
3356 for(i=0;i<PQ_L2_SIZE;i++) {
3357 db_printf(" %d", vm_page_queues[PQ_INACTIVE + i].lcnt);
3359 db_printf("\n");
3361 #endif /* DDB */