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