1 /*- 2 * Copyright (c) 1991 Regents of the University of California. 3 * All rights reserved. 4 * Copyright (c) 1994 John S. Dyson 5 * All rights reserved. 6 * Copyright (c) 1994 David Greenman 7 * All rights reserved. 8 * Copyright (c) 2005 Yahoo! Technologies Norway AS 9 * All rights reserved. 10 * 11 * This code is derived from software contributed to Berkeley by 12 * The Mach Operating System project at Carnegie-Mellon University. 13 * 14 * Redistribution and use in source and binary forms, with or without 15 * modification, are permitted provided that the following conditions 16 * are met: 17 * 1. Redistributions of source code must retain the above copyright 18 * notice, this list of conditions and the following disclaimer. 19 * 2. Redistributions in binary form must reproduce the above copyright 20 * notice, this list of conditions and the following disclaimer in the 21 * documentation and/or other materials provided with the distribution. 22 * 3. All advertising materials mentioning features or use of this software 23 * must display the following acknowledgement: 24 * This product includes software developed by the University of 25 * California, Berkeley and its contributors. 26 * 4. Neither the name of the University nor the names of its contributors 27 * may be used to endorse or promote products derived from this software 28 * without specific prior written permission. 29 * 30 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 31 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 32 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 33 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 34 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 35 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 36 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 38 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 39 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 40 * SUCH DAMAGE. 41 * 42 * from: @(#)vm_pageout.c 7.4 (Berkeley) 5/7/91 43 * 44 * 45 * Copyright (c) 1987, 1990 Carnegie-Mellon University. 46 * All rights reserved. 47 * 48 * Authors: Avadis Tevanian, Jr., Michael Wayne Young 49 * 50 * Permission to use, copy, modify and distribute this software and 51 * its documentation is hereby granted, provided that both the copyright 52 * notice and this permission notice appear in all copies of the 53 * software, derivative works or modified versions, and any portions 54 * thereof, and that both notices appear in supporting documentation. 55 * 56 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" 57 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND 58 * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. 59 * 60 * Carnegie Mellon requests users of this software to return to 61 * 62 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU 63 * School of Computer Science 64 * Carnegie Mellon University 65 * Pittsburgh PA 15213-3890 66 * 67 * any improvements or extensions that they make and grant Carnegie the 68 * rights to redistribute these changes. 69 */ 70 71 /* 72 * The proverbial page-out daemon. 73 */ 74 75 #include <sys/cdefs.h> 76 __FBSDID("$FreeBSD$"); 77 78 #include "opt_vm.h" 79 80 #include <sys/param.h> 81 #include <sys/systm.h> 82 #include <sys/kernel.h> 83 #include <sys/eventhandler.h> 84 #include <sys/lock.h> 85 #include <sys/mutex.h> 86 #include <sys/proc.h> 87 #include <sys/kthread.h> 88 #include <sys/ktr.h> 89 #include <sys/mount.h> 90 #include <sys/racct.h> 91 #include <sys/resourcevar.h> 92 #include <sys/sched.h> 93 #include <sys/sdt.h> 94 #include <sys/signalvar.h> 95 #include <sys/smp.h> 96 #include <sys/time.h> 97 #include <sys/vnode.h> 98 #include <sys/vmmeter.h> 99 #include <sys/rwlock.h> 100 #include <sys/sx.h> 101 #include <sys/sysctl.h> 102 103 #include <vm/vm.h> 104 #include <vm/vm_param.h> 105 #include <vm/vm_object.h> 106 #include <vm/vm_page.h> 107 #include <vm/vm_map.h> 108 #include <vm/vm_pageout.h> 109 #include <vm/vm_pager.h> 110 #include <vm/vm_phys.h> 111 #include <vm/swap_pager.h> 112 #include <vm/vm_extern.h> 113 #include <vm/uma.h> 114 115 /* 116 * System initialization 117 */ 118 119 /* the kernel process "vm_pageout"*/ 120 static void vm_pageout(void); 121 static void vm_pageout_init(void); 122 static int vm_pageout_clean(vm_page_t m, int *numpagedout); 123 static int vm_pageout_cluster(vm_page_t m); 124 static bool vm_pageout_scan(struct vm_domain *vmd, int pass); 125 static void vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage, 126 int starting_page_shortage); 127 128 SYSINIT(pagedaemon_init, SI_SUB_KTHREAD_PAGE, SI_ORDER_FIRST, vm_pageout_init, 129 NULL); 130 131 struct proc *pageproc; 132 133 static struct kproc_desc page_kp = { 134 "pagedaemon", 135 vm_pageout, 136 &pageproc 137 }; 138 SYSINIT(pagedaemon, SI_SUB_KTHREAD_PAGE, SI_ORDER_SECOND, kproc_start, 139 &page_kp); 140 141 SDT_PROVIDER_DEFINE(vm); 142 SDT_PROBE_DEFINE(vm, , , vm__lowmem_scan); 143 144 #if !defined(NO_SWAPPING) 145 /* the kernel process "vm_daemon"*/ 146 static void vm_daemon(void); 147 static struct proc *vmproc; 148 149 static struct kproc_desc vm_kp = { 150 "vmdaemon", 151 vm_daemon, 152 &vmproc 153 }; 154 SYSINIT(vmdaemon, SI_SUB_KTHREAD_VM, SI_ORDER_FIRST, kproc_start, &vm_kp); 155 #endif 156 157 /* Pagedaemon activity rates, in subdivisions of one second. */ 158 #define VM_LAUNDER_RATE 10 159 #define VM_INACT_SCAN_RATE 2 160 161 int vm_pageout_deficit; /* Estimated number of pages deficit */ 162 u_int vm_pageout_wakeup_thresh; 163 static int vm_pageout_oom_seq = 12; 164 bool vm_pageout_wanted; /* Event on which pageout daemon sleeps */ 165 bool vm_pages_needed; /* Are threads waiting for free pages? */ 166 167 /* Pending request for dirty page laundering. */ 168 static enum { 169 VM_LAUNDRY_IDLE, 170 VM_LAUNDRY_BACKGROUND, 171 VM_LAUNDRY_SHORTFALL 172 } vm_laundry_request = VM_LAUNDRY_IDLE; 173 174 #if !defined(NO_SWAPPING) 175 static int vm_pageout_req_swapout; /* XXX */ 176 static int vm_daemon_needed; 177 static struct mtx vm_daemon_mtx; 178 /* Allow for use by vm_pageout before vm_daemon is initialized. */ 179 MTX_SYSINIT(vm_daemon, &vm_daemon_mtx, "vm daemon", MTX_DEF); 180 #endif 181 static int vm_pageout_update_period; 182 static int disable_swap_pageouts; 183 static int lowmem_period = 10; 184 static time_t lowmem_uptime; 185 static int swapdev_enabled; 186 187 #if defined(NO_SWAPPING) 188 static int vm_swap_enabled = 0; 189 static int vm_swap_idle_enabled = 0; 190 #else 191 static int vm_swap_enabled = 1; 192 static int vm_swap_idle_enabled = 0; 193 #endif 194 195 static int vm_panic_on_oom = 0; 196 197 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom, 198 CTLFLAG_RWTUN, &vm_panic_on_oom, 0, 199 "panic on out of memory instead of killing the largest process"); 200 201 SYSCTL_INT(_vm, OID_AUTO, pageout_wakeup_thresh, 202 CTLFLAG_RW, &vm_pageout_wakeup_thresh, 0, 203 "free page threshold for waking up the pageout daemon"); 204 205 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period, 206 CTLFLAG_RW, &vm_pageout_update_period, 0, 207 "Maximum active LRU update period"); 208 209 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RW, &lowmem_period, 0, 210 "Low memory callback period"); 211 212 #if defined(NO_SWAPPING) 213 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, 214 CTLFLAG_RD, &vm_swap_enabled, 0, "Enable entire process swapout"); 215 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, 216 CTLFLAG_RD, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria"); 217 #else 218 SYSCTL_INT(_vm, VM_SWAPPING_ENABLED, swap_enabled, 219 CTLFLAG_RW, &vm_swap_enabled, 0, "Enable entire process swapout"); 220 SYSCTL_INT(_vm, OID_AUTO, swap_idle_enabled, 221 CTLFLAG_RW, &vm_swap_idle_enabled, 0, "Allow swapout on idle criteria"); 222 #endif 223 224 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts, 225 CTLFLAG_RW, &disable_swap_pageouts, 0, "Disallow swapout of dirty pages"); 226 227 static int pageout_lock_miss; 228 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss, 229 CTLFLAG_RD, &pageout_lock_miss, 0, "vget() lock misses during pageout"); 230 231 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq, 232 CTLFLAG_RW, &vm_pageout_oom_seq, 0, 233 "back-to-back calls to oom detector to start OOM"); 234 235 static int act_scan_laundry_weight = 3; 236 SYSCTL_INT(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RW, 237 &act_scan_laundry_weight, 0, 238 "weight given to clean vs. dirty pages in active queue scans"); 239 240 static u_int vm_background_launder_target; 241 SYSCTL_UINT(_vm, OID_AUTO, background_launder_target, CTLFLAG_RW, 242 &vm_background_launder_target, 0, 243 "background laundering target, in pages"); 244 245 static u_int vm_background_launder_rate = 4096; 246 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RW, 247 &vm_background_launder_rate, 0, 248 "background laundering rate, in kilobytes per second"); 249 250 static u_int vm_background_launder_max = 20 * 1024; 251 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RW, 252 &vm_background_launder_max, 0, "background laundering cap, in kilobytes"); 253 254 int vm_pageout_page_count = 32; 255 256 int vm_page_max_wired; /* XXX max # of wired pages system-wide */ 257 SYSCTL_INT(_vm, OID_AUTO, max_wired, 258 CTLFLAG_RW, &vm_page_max_wired, 0, "System-wide limit to wired page count"); 259 260 static u_int isqrt(u_int num); 261 static boolean_t vm_pageout_fallback_object_lock(vm_page_t, vm_page_t *); 262 static int vm_pageout_launder(struct vm_domain *vmd, int launder, 263 bool in_shortfall); 264 static void vm_pageout_laundry_worker(void *arg); 265 #if !defined(NO_SWAPPING) 266 static void vm_pageout_map_deactivate_pages(vm_map_t, long); 267 static void vm_pageout_object_deactivate_pages(pmap_t, vm_object_t, long); 268 static void vm_req_vmdaemon(int req); 269 #endif 270 static boolean_t vm_pageout_page_lock(vm_page_t, vm_page_t *); 271 272 /* 273 * Initialize a dummy page for marking the caller's place in the specified 274 * paging queue. In principle, this function only needs to set the flag 275 * PG_MARKER. Nonetheless, it write busies and initializes the hold count 276 * to one as safety precautions. 277 */ 278 static void 279 vm_pageout_init_marker(vm_page_t marker, u_short queue) 280 { 281 282 bzero(marker, sizeof(*marker)); 283 marker->flags = PG_MARKER; 284 marker->busy_lock = VPB_SINGLE_EXCLUSIVER; 285 marker->queue = queue; 286 marker->hold_count = 1; 287 } 288 289 /* 290 * vm_pageout_fallback_object_lock: 291 * 292 * Lock vm object currently associated with `m'. VM_OBJECT_TRYWLOCK is 293 * known to have failed and page queue must be either PQ_ACTIVE or 294 * PQ_INACTIVE. To avoid lock order violation, unlock the page queue 295 * while locking the vm object. Use marker page to detect page queue 296 * changes and maintain notion of next page on page queue. Return 297 * TRUE if no changes were detected, FALSE otherwise. vm object is 298 * locked on return. 299 * 300 * This function depends on both the lock portion of struct vm_object 301 * and normal struct vm_page being type stable. 302 */ 303 static boolean_t 304 vm_pageout_fallback_object_lock(vm_page_t m, vm_page_t *next) 305 { 306 struct vm_page marker; 307 struct vm_pagequeue *pq; 308 boolean_t unchanged; 309 u_short queue; 310 vm_object_t object; 311 312 queue = m->queue; 313 vm_pageout_init_marker(&marker, queue); 314 pq = vm_page_pagequeue(m); 315 object = m->object; 316 317 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q); 318 vm_pagequeue_unlock(pq); 319 vm_page_unlock(m); 320 VM_OBJECT_WLOCK(object); 321 vm_page_lock(m); 322 vm_pagequeue_lock(pq); 323 324 /* 325 * The page's object might have changed, and/or the page might 326 * have moved from its original position in the queue. If the 327 * page's object has changed, then the caller should abandon 328 * processing the page because the wrong object lock was 329 * acquired. Use the marker's plinks.q, not the page's, to 330 * determine if the page has been moved. The state of the 331 * page's plinks.q can be indeterminate; whereas, the marker's 332 * plinks.q must be valid. 333 */ 334 *next = TAILQ_NEXT(&marker, plinks.q); 335 unchanged = m->object == object && 336 m == TAILQ_PREV(&marker, pglist, plinks.q); 337 KASSERT(!unchanged || m->queue == queue, 338 ("page %p queue %d %d", m, queue, m->queue)); 339 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q); 340 return (unchanged); 341 } 342 343 /* 344 * Lock the page while holding the page queue lock. Use marker page 345 * to detect page queue changes and maintain notion of next page on 346 * page queue. Return TRUE if no changes were detected, FALSE 347 * otherwise. The page is locked on return. The page queue lock might 348 * be dropped and reacquired. 349 * 350 * This function depends on normal struct vm_page being type stable. 351 */ 352 static boolean_t 353 vm_pageout_page_lock(vm_page_t m, vm_page_t *next) 354 { 355 struct vm_page marker; 356 struct vm_pagequeue *pq; 357 boolean_t unchanged; 358 u_short queue; 359 360 vm_page_lock_assert(m, MA_NOTOWNED); 361 if (vm_page_trylock(m)) 362 return (TRUE); 363 364 queue = m->queue; 365 vm_pageout_init_marker(&marker, queue); 366 pq = vm_page_pagequeue(m); 367 368 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &marker, plinks.q); 369 vm_pagequeue_unlock(pq); 370 vm_page_lock(m); 371 vm_pagequeue_lock(pq); 372 373 /* Page queue might have changed. */ 374 *next = TAILQ_NEXT(&marker, plinks.q); 375 unchanged = m == TAILQ_PREV(&marker, pglist, plinks.q); 376 KASSERT(!unchanged || m->queue == queue, 377 ("page %p queue %d %d", m, queue, m->queue)); 378 TAILQ_REMOVE(&pq->pq_pl, &marker, plinks.q); 379 return (unchanged); 380 } 381 382 /* 383 * Scan for pages at adjacent offsets within the given page's object that are 384 * eligible for laundering, form a cluster of these pages and the given page, 385 * and launder that cluster. 386 */ 387 static int 388 vm_pageout_cluster(vm_page_t m) 389 { 390 vm_object_t object; 391 vm_page_t mc[2 * vm_pageout_page_count], p, pb, ps; 392 vm_pindex_t pindex; 393 int ib, is, page_base, pageout_count; 394 395 vm_page_assert_locked(m); 396 object = m->object; 397 VM_OBJECT_ASSERT_WLOCKED(object); 398 pindex = m->pindex; 399 400 /* 401 * We can't clean the page if it is busy or held. 402 */ 403 vm_page_assert_unbusied(m); 404 KASSERT(m->hold_count == 0, ("page %p is held", m)); 405 vm_page_unlock(m); 406 407 mc[vm_pageout_page_count] = pb = ps = m; 408 pageout_count = 1; 409 page_base = vm_pageout_page_count; 410 ib = 1; 411 is = 1; 412 413 /* 414 * We can cluster only if the page is not clean, busy, or held, and 415 * the page is in the laundry queue. 416 * 417 * During heavy mmap/modification loads the pageout 418 * daemon can really fragment the underlying file 419 * due to flushing pages out of order and not trying to 420 * align the clusters (which leaves sporadic out-of-order 421 * holes). To solve this problem we do the reverse scan 422 * first and attempt to align our cluster, then do a 423 * forward scan if room remains. 424 */ 425 more: 426 while (ib != 0 && pageout_count < vm_pageout_page_count) { 427 if (ib > pindex) { 428 ib = 0; 429 break; 430 } 431 if ((p = vm_page_prev(pb)) == NULL || vm_page_busied(p)) { 432 ib = 0; 433 break; 434 } 435 vm_page_test_dirty(p); 436 if (p->dirty == 0) { 437 ib = 0; 438 break; 439 } 440 vm_page_lock(p); 441 if (!vm_page_in_laundry(p) || 442 p->hold_count != 0) { /* may be undergoing I/O */ 443 vm_page_unlock(p); 444 ib = 0; 445 break; 446 } 447 vm_page_unlock(p); 448 mc[--page_base] = pb = p; 449 ++pageout_count; 450 ++ib; 451 452 /* 453 * We are at an alignment boundary. Stop here, and switch 454 * directions. Do not clear ib. 455 */ 456 if ((pindex - (ib - 1)) % vm_pageout_page_count == 0) 457 break; 458 } 459 while (pageout_count < vm_pageout_page_count && 460 pindex + is < object->size) { 461 if ((p = vm_page_next(ps)) == NULL || vm_page_busied(p)) 462 break; 463 vm_page_test_dirty(p); 464 if (p->dirty == 0) 465 break; 466 vm_page_lock(p); 467 if (!vm_page_in_laundry(p) || 468 p->hold_count != 0) { /* may be undergoing I/O */ 469 vm_page_unlock(p); 470 break; 471 } 472 vm_page_unlock(p); 473 mc[page_base + pageout_count] = ps = p; 474 ++pageout_count; 475 ++is; 476 } 477 478 /* 479 * If we exhausted our forward scan, continue with the reverse scan 480 * when possible, even past an alignment boundary. This catches 481 * boundary conditions. 482 */ 483 if (ib != 0 && pageout_count < vm_pageout_page_count) 484 goto more; 485 486 return (vm_pageout_flush(&mc[page_base], pageout_count, 487 VM_PAGER_PUT_NOREUSE, 0, NULL, NULL)); 488 } 489 490 /* 491 * vm_pageout_flush() - launder the given pages 492 * 493 * The given pages are laundered. Note that we setup for the start of 494 * I/O ( i.e. busy the page ), mark it read-only, and bump the object 495 * reference count all in here rather then in the parent. If we want 496 * the parent to do more sophisticated things we may have to change 497 * the ordering. 498 * 499 * Returned runlen is the count of pages between mreq and first 500 * page after mreq with status VM_PAGER_AGAIN. 501 * *eio is set to TRUE if pager returned VM_PAGER_ERROR or VM_PAGER_FAIL 502 * for any page in runlen set. 503 */ 504 int 505 vm_pageout_flush(vm_page_t *mc, int count, int flags, int mreq, int *prunlen, 506 boolean_t *eio) 507 { 508 vm_object_t object = mc[0]->object; 509 int pageout_status[count]; 510 int numpagedout = 0; 511 int i, runlen; 512 513 VM_OBJECT_ASSERT_WLOCKED(object); 514 515 /* 516 * Initiate I/O. Bump the vm_page_t->busy counter and 517 * mark the pages read-only. 518 * 519 * We do not have to fixup the clean/dirty bits here... we can 520 * allow the pager to do it after the I/O completes. 521 * 522 * NOTE! mc[i]->dirty may be partial or fragmented due to an 523 * edge case with file fragments. 524 */ 525 for (i = 0; i < count; i++) { 526 KASSERT(mc[i]->valid == VM_PAGE_BITS_ALL, 527 ("vm_pageout_flush: partially invalid page %p index %d/%d", 528 mc[i], i, count)); 529 vm_page_sbusy(mc[i]); 530 pmap_remove_write(mc[i]); 531 } 532 vm_object_pip_add(object, count); 533 534 vm_pager_put_pages(object, mc, count, flags, pageout_status); 535 536 runlen = count - mreq; 537 if (eio != NULL) 538 *eio = FALSE; 539 for (i = 0; i < count; i++) { 540 vm_page_t mt = mc[i]; 541 542 KASSERT(pageout_status[i] == VM_PAGER_PEND || 543 !pmap_page_is_write_mapped(mt), 544 ("vm_pageout_flush: page %p is not write protected", mt)); 545 switch (pageout_status[i]) { 546 case VM_PAGER_OK: 547 vm_page_lock(mt); 548 if (vm_page_in_laundry(mt)) 549 vm_page_deactivate_noreuse(mt); 550 vm_page_unlock(mt); 551 /* FALLTHROUGH */ 552 case VM_PAGER_PEND: 553 numpagedout++; 554 break; 555 case VM_PAGER_BAD: 556 /* 557 * The page is outside the object's range. We pretend 558 * that the page out worked and clean the page, so the 559 * changes will be lost if the page is reclaimed by 560 * the page daemon. 561 */ 562 vm_page_undirty(mt); 563 vm_page_lock(mt); 564 if (vm_page_in_laundry(mt)) 565 vm_page_deactivate_noreuse(mt); 566 vm_page_unlock(mt); 567 break; 568 case VM_PAGER_ERROR: 569 case VM_PAGER_FAIL: 570 /* 571 * If the page couldn't be paged out to swap because the 572 * pager wasn't able to find space, place the page in 573 * the PQ_UNSWAPPABLE holding queue. This is an 574 * optimization that prevents the page daemon from 575 * wasting CPU cycles on pages that cannot be reclaimed 576 * becase no swap device is configured. 577 * 578 * Otherwise, reactivate the page so that it doesn't 579 * clog the laundry and inactive queues. (We will try 580 * paging it out again later.) 581 */ 582 vm_page_lock(mt); 583 if (object->type == OBJT_SWAP && 584 pageout_status[i] == VM_PAGER_FAIL) { 585 vm_page_unswappable(mt); 586 numpagedout++; 587 } else 588 vm_page_activate(mt); 589 vm_page_unlock(mt); 590 if (eio != NULL && i >= mreq && i - mreq < runlen) 591 *eio = TRUE; 592 break; 593 case VM_PAGER_AGAIN: 594 if (i >= mreq && i - mreq < runlen) 595 runlen = i - mreq; 596 break; 597 } 598 599 /* 600 * If the operation is still going, leave the page busy to 601 * block all other accesses. Also, leave the paging in 602 * progress indicator set so that we don't attempt an object 603 * collapse. 604 */ 605 if (pageout_status[i] != VM_PAGER_PEND) { 606 vm_object_pip_wakeup(object); 607 vm_page_sunbusy(mt); 608 } 609 } 610 if (prunlen != NULL) 611 *prunlen = runlen; 612 return (numpagedout); 613 } 614 615 static void 616 vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused) 617 { 618 619 atomic_store_rel_int(&swapdev_enabled, 1); 620 } 621 622 static void 623 vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused) 624 { 625 626 if (swap_pager_nswapdev() == 1) 627 atomic_store_rel_int(&swapdev_enabled, 0); 628 } 629 630 #if !defined(NO_SWAPPING) 631 /* 632 * vm_pageout_object_deactivate_pages 633 * 634 * Deactivate enough pages to satisfy the inactive target 635 * requirements. 636 * 637 * The object and map must be locked. 638 */ 639 static void 640 vm_pageout_object_deactivate_pages(pmap_t pmap, vm_object_t first_object, 641 long desired) 642 { 643 vm_object_t backing_object, object; 644 vm_page_t p; 645 int act_delta, remove_mode; 646 647 VM_OBJECT_ASSERT_LOCKED(first_object); 648 if ((first_object->flags & OBJ_FICTITIOUS) != 0) 649 return; 650 for (object = first_object;; object = backing_object) { 651 if (pmap_resident_count(pmap) <= desired) 652 goto unlock_return; 653 VM_OBJECT_ASSERT_LOCKED(object); 654 if ((object->flags & OBJ_UNMANAGED) != 0 || 655 object->paging_in_progress != 0) 656 goto unlock_return; 657 658 remove_mode = 0; 659 if (object->shadow_count > 1) 660 remove_mode = 1; 661 /* 662 * Scan the object's entire memory queue. 663 */ 664 TAILQ_FOREACH(p, &object->memq, listq) { 665 if (pmap_resident_count(pmap) <= desired) 666 goto unlock_return; 667 if (vm_page_busied(p)) 668 continue; 669 VM_CNT_INC(v_pdpages); 670 vm_page_lock(p); 671 if (p->wire_count != 0 || p->hold_count != 0 || 672 !pmap_page_exists_quick(pmap, p)) { 673 vm_page_unlock(p); 674 continue; 675 } 676 act_delta = pmap_ts_referenced(p); 677 if ((p->aflags & PGA_REFERENCED) != 0) { 678 if (act_delta == 0) 679 act_delta = 1; 680 vm_page_aflag_clear(p, PGA_REFERENCED); 681 } 682 if (!vm_page_active(p) && act_delta != 0) { 683 vm_page_activate(p); 684 p->act_count += act_delta; 685 } else if (vm_page_active(p)) { 686 if (act_delta == 0) { 687 p->act_count -= min(p->act_count, 688 ACT_DECLINE); 689 if (!remove_mode && p->act_count == 0) { 690 pmap_remove_all(p); 691 vm_page_deactivate(p); 692 } else 693 vm_page_requeue(p); 694 } else { 695 vm_page_activate(p); 696 if (p->act_count < ACT_MAX - 697 ACT_ADVANCE) 698 p->act_count += ACT_ADVANCE; 699 vm_page_requeue(p); 700 } 701 } else if (vm_page_inactive(p)) 702 pmap_remove_all(p); 703 vm_page_unlock(p); 704 } 705 if ((backing_object = object->backing_object) == NULL) 706 goto unlock_return; 707 VM_OBJECT_RLOCK(backing_object); 708 if (object != first_object) 709 VM_OBJECT_RUNLOCK(object); 710 } 711 unlock_return: 712 if (object != first_object) 713 VM_OBJECT_RUNLOCK(object); 714 } 715 716 /* 717 * deactivate some number of pages in a map, try to do it fairly, but 718 * that is really hard to do. 719 */ 720 static void 721 vm_pageout_map_deactivate_pages(map, desired) 722 vm_map_t map; 723 long desired; 724 { 725 vm_map_entry_t tmpe; 726 vm_object_t obj, bigobj; 727 int nothingwired; 728 729 if (!vm_map_trylock(map)) 730 return; 731 732 bigobj = NULL; 733 nothingwired = TRUE; 734 735 /* 736 * first, search out the biggest object, and try to free pages from 737 * that. 738 */ 739 tmpe = map->header.next; 740 while (tmpe != &map->header) { 741 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) { 742 obj = tmpe->object.vm_object; 743 if (obj != NULL && VM_OBJECT_TRYRLOCK(obj)) { 744 if (obj->shadow_count <= 1 && 745 (bigobj == NULL || 746 bigobj->resident_page_count < obj->resident_page_count)) { 747 if (bigobj != NULL) 748 VM_OBJECT_RUNLOCK(bigobj); 749 bigobj = obj; 750 } else 751 VM_OBJECT_RUNLOCK(obj); 752 } 753 } 754 if (tmpe->wired_count > 0) 755 nothingwired = FALSE; 756 tmpe = tmpe->next; 757 } 758 759 if (bigobj != NULL) { 760 vm_pageout_object_deactivate_pages(map->pmap, bigobj, desired); 761 VM_OBJECT_RUNLOCK(bigobj); 762 } 763 /* 764 * Next, hunt around for other pages to deactivate. We actually 765 * do this search sort of wrong -- .text first is not the best idea. 766 */ 767 tmpe = map->header.next; 768 while (tmpe != &map->header) { 769 if (pmap_resident_count(vm_map_pmap(map)) <= desired) 770 break; 771 if ((tmpe->eflags & MAP_ENTRY_IS_SUB_MAP) == 0) { 772 obj = tmpe->object.vm_object; 773 if (obj != NULL) { 774 VM_OBJECT_RLOCK(obj); 775 vm_pageout_object_deactivate_pages(map->pmap, obj, desired); 776 VM_OBJECT_RUNLOCK(obj); 777 } 778 } 779 tmpe = tmpe->next; 780 } 781 782 /* 783 * Remove all mappings if a process is swapped out, this will free page 784 * table pages. 785 */ 786 if (desired == 0 && nothingwired) { 787 pmap_remove(vm_map_pmap(map), vm_map_min(map), 788 vm_map_max(map)); 789 } 790 791 vm_map_unlock(map); 792 } 793 #endif /* !defined(NO_SWAPPING) */ 794 795 /* 796 * Attempt to acquire all of the necessary locks to launder a page and 797 * then call through the clustering layer to PUTPAGES. Wait a short 798 * time for a vnode lock. 799 * 800 * Requires the page and object lock on entry, releases both before return. 801 * Returns 0 on success and an errno otherwise. 802 */ 803 static int 804 vm_pageout_clean(vm_page_t m, int *numpagedout) 805 { 806 struct vnode *vp; 807 struct mount *mp; 808 vm_object_t object; 809 vm_pindex_t pindex; 810 int error, lockmode; 811 812 vm_page_assert_locked(m); 813 object = m->object; 814 VM_OBJECT_ASSERT_WLOCKED(object); 815 error = 0; 816 vp = NULL; 817 mp = NULL; 818 819 /* 820 * The object is already known NOT to be dead. It 821 * is possible for the vget() to block the whole 822 * pageout daemon, but the new low-memory handling 823 * code should prevent it. 824 * 825 * We can't wait forever for the vnode lock, we might 826 * deadlock due to a vn_read() getting stuck in 827 * vm_wait while holding this vnode. We skip the 828 * vnode if we can't get it in a reasonable amount 829 * of time. 830 */ 831 if (object->type == OBJT_VNODE) { 832 vm_page_unlock(m); 833 vp = object->handle; 834 if (vp->v_type == VREG && 835 vn_start_write(vp, &mp, V_NOWAIT) != 0) { 836 mp = NULL; 837 error = EDEADLK; 838 goto unlock_all; 839 } 840 KASSERT(mp != NULL, 841 ("vp %p with NULL v_mount", vp)); 842 vm_object_reference_locked(object); 843 pindex = m->pindex; 844 VM_OBJECT_WUNLOCK(object); 845 lockmode = MNT_SHARED_WRITES(vp->v_mount) ? 846 LK_SHARED : LK_EXCLUSIVE; 847 if (vget(vp, lockmode | LK_TIMELOCK, curthread)) { 848 vp = NULL; 849 error = EDEADLK; 850 goto unlock_mp; 851 } 852 VM_OBJECT_WLOCK(object); 853 vm_page_lock(m); 854 /* 855 * While the object and page were unlocked, the page 856 * may have been: 857 * (1) moved to a different queue, 858 * (2) reallocated to a different object, 859 * (3) reallocated to a different offset, or 860 * (4) cleaned. 861 */ 862 if (!vm_page_in_laundry(m) || m->object != object || 863 m->pindex != pindex || m->dirty == 0) { 864 vm_page_unlock(m); 865 error = ENXIO; 866 goto unlock_all; 867 } 868 869 /* 870 * The page may have been busied or held while the object 871 * and page locks were released. 872 */ 873 if (vm_page_busied(m) || m->hold_count != 0) { 874 vm_page_unlock(m); 875 error = EBUSY; 876 goto unlock_all; 877 } 878 } 879 880 /* 881 * If a page is dirty, then it is either being washed 882 * (but not yet cleaned) or it is still in the 883 * laundry. If it is still in the laundry, then we 884 * start the cleaning operation. 885 */ 886 if ((*numpagedout = vm_pageout_cluster(m)) == 0) 887 error = EIO; 888 889 unlock_all: 890 VM_OBJECT_WUNLOCK(object); 891 892 unlock_mp: 893 vm_page_lock_assert(m, MA_NOTOWNED); 894 if (mp != NULL) { 895 if (vp != NULL) 896 vput(vp); 897 vm_object_deallocate(object); 898 vn_finished_write(mp); 899 } 900 901 return (error); 902 } 903 904 /* 905 * Attempt to launder the specified number of pages. 906 * 907 * Returns the number of pages successfully laundered. 908 */ 909 static int 910 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall) 911 { 912 struct vm_pagequeue *pq; 913 vm_object_t object; 914 vm_page_t m, next; 915 int act_delta, error, maxscan, numpagedout, starting_target; 916 int vnodes_skipped; 917 bool pageout_ok, queue_locked; 918 919 starting_target = launder; 920 vnodes_skipped = 0; 921 922 /* 923 * Scan the laundry queues for pages eligible to be laundered. We stop 924 * once the target number of dirty pages have been laundered, or once 925 * we've reached the end of the queue. A single iteration of this loop 926 * may cause more than one page to be laundered because of clustering. 927 * 928 * maxscan ensures that we don't re-examine requeued pages. Any 929 * additional pages written as part of a cluster are subtracted from 930 * maxscan since they must be taken from the laundry queue. 931 * 932 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no 933 * swap devices are configured. 934 */ 935 if (atomic_load_acq_int(&swapdev_enabled)) 936 pq = &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]; 937 else 938 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY]; 939 940 scan: 941 vm_pagequeue_lock(pq); 942 maxscan = pq->pq_cnt; 943 queue_locked = true; 944 for (m = TAILQ_FIRST(&pq->pq_pl); 945 m != NULL && maxscan-- > 0 && launder > 0; 946 m = next) { 947 vm_pagequeue_assert_locked(pq); 948 KASSERT(queue_locked, ("unlocked laundry queue")); 949 KASSERT(vm_page_in_laundry(m), 950 ("page %p has an inconsistent queue", m)); 951 next = TAILQ_NEXT(m, plinks.q); 952 if ((m->flags & PG_MARKER) != 0) 953 continue; 954 KASSERT((m->flags & PG_FICTITIOUS) == 0, 955 ("PG_FICTITIOUS page %p cannot be in laundry queue", m)); 956 KASSERT((m->oflags & VPO_UNMANAGED) == 0, 957 ("VPO_UNMANAGED page %p cannot be in laundry queue", m)); 958 if (!vm_pageout_page_lock(m, &next) || m->hold_count != 0) { 959 vm_page_unlock(m); 960 continue; 961 } 962 object = m->object; 963 if ((!VM_OBJECT_TRYWLOCK(object) && 964 (!vm_pageout_fallback_object_lock(m, &next) || 965 m->hold_count != 0)) || vm_page_busied(m)) { 966 VM_OBJECT_WUNLOCK(object); 967 vm_page_unlock(m); 968 continue; 969 } 970 971 /* 972 * Unlock the laundry queue, invalidating the 'next' pointer. 973 * Use a marker to remember our place in the laundry queue. 974 */ 975 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_laundry_marker, 976 plinks.q); 977 vm_pagequeue_unlock(pq); 978 queue_locked = false; 979 980 /* 981 * Invalid pages can be easily freed. They cannot be 982 * mapped; vm_page_free() asserts this. 983 */ 984 if (m->valid == 0) 985 goto free_page; 986 987 /* 988 * If the page has been referenced and the object is not dead, 989 * reactivate or requeue the page depending on whether the 990 * object is mapped. 991 */ 992 if ((m->aflags & PGA_REFERENCED) != 0) { 993 vm_page_aflag_clear(m, PGA_REFERENCED); 994 act_delta = 1; 995 } else 996 act_delta = 0; 997 if (object->ref_count != 0) 998 act_delta += pmap_ts_referenced(m); 999 else { 1000 KASSERT(!pmap_page_is_mapped(m), 1001 ("page %p is mapped", m)); 1002 } 1003 if (act_delta != 0) { 1004 if (object->ref_count != 0) { 1005 VM_CNT_INC(v_reactivated); 1006 vm_page_activate(m); 1007 1008 /* 1009 * Increase the activation count if the page 1010 * was referenced while in the laundry queue. 1011 * This makes it less likely that the page will 1012 * be returned prematurely to the inactive 1013 * queue. 1014 */ 1015 m->act_count += act_delta + ACT_ADVANCE; 1016 1017 /* 1018 * If this was a background laundering, count 1019 * activated pages towards our target. The 1020 * purpose of background laundering is to ensure 1021 * that pages are eventually cycled through the 1022 * laundry queue, and an activation is a valid 1023 * way out. 1024 */ 1025 if (!in_shortfall) 1026 launder--; 1027 goto drop_page; 1028 } else if ((object->flags & OBJ_DEAD) == 0) 1029 goto requeue_page; 1030 } 1031 1032 /* 1033 * If the page appears to be clean at the machine-independent 1034 * layer, then remove all of its mappings from the pmap in 1035 * anticipation of freeing it. If, however, any of the page's 1036 * mappings allow write access, then the page may still be 1037 * modified until the last of those mappings are removed. 1038 */ 1039 if (object->ref_count != 0) { 1040 vm_page_test_dirty(m); 1041 if (m->dirty == 0) 1042 pmap_remove_all(m); 1043 } 1044 1045 /* 1046 * Clean pages are freed, and dirty pages are paged out unless 1047 * they belong to a dead object. Requeueing dirty pages from 1048 * dead objects is pointless, as they are being paged out and 1049 * freed by the thread that destroyed the object. 1050 */ 1051 if (m->dirty == 0) { 1052 free_page: 1053 vm_page_free(m); 1054 VM_CNT_INC(v_dfree); 1055 } else if ((object->flags & OBJ_DEAD) == 0) { 1056 if (object->type != OBJT_SWAP && 1057 object->type != OBJT_DEFAULT) 1058 pageout_ok = true; 1059 else if (disable_swap_pageouts) 1060 pageout_ok = false; 1061 else 1062 pageout_ok = true; 1063 if (!pageout_ok) { 1064 requeue_page: 1065 vm_pagequeue_lock(pq); 1066 queue_locked = true; 1067 vm_page_requeue_locked(m); 1068 goto drop_page; 1069 } 1070 1071 /* 1072 * Form a cluster with adjacent, dirty pages from the 1073 * same object, and page out that entire cluster. 1074 * 1075 * The adjacent, dirty pages must also be in the 1076 * laundry. However, their mappings are not checked 1077 * for new references. Consequently, a recently 1078 * referenced page may be paged out. However, that 1079 * page will not be prematurely reclaimed. After page 1080 * out, the page will be placed in the inactive queue, 1081 * where any new references will be detected and the 1082 * page reactivated. 1083 */ 1084 error = vm_pageout_clean(m, &numpagedout); 1085 if (error == 0) { 1086 launder -= numpagedout; 1087 maxscan -= numpagedout - 1; 1088 } else if (error == EDEADLK) { 1089 pageout_lock_miss++; 1090 vnodes_skipped++; 1091 } 1092 goto relock_queue; 1093 } 1094 drop_page: 1095 vm_page_unlock(m); 1096 VM_OBJECT_WUNLOCK(object); 1097 relock_queue: 1098 if (!queue_locked) { 1099 vm_pagequeue_lock(pq); 1100 queue_locked = true; 1101 } 1102 next = TAILQ_NEXT(&vmd->vmd_laundry_marker, plinks.q); 1103 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_laundry_marker, plinks.q); 1104 } 1105 vm_pagequeue_unlock(pq); 1106 1107 if (launder > 0 && pq == &vmd->vmd_pagequeues[PQ_UNSWAPPABLE]) { 1108 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY]; 1109 goto scan; 1110 } 1111 1112 /* 1113 * Wakeup the sync daemon if we skipped a vnode in a writeable object 1114 * and we didn't launder enough pages. 1115 */ 1116 if (vnodes_skipped > 0 && launder > 0) 1117 (void)speedup_syncer(); 1118 1119 return (starting_target - launder); 1120 } 1121 1122 /* 1123 * Compute the integer square root. 1124 */ 1125 static u_int 1126 isqrt(u_int num) 1127 { 1128 u_int bit, root, tmp; 1129 1130 bit = 1u << ((NBBY * sizeof(u_int)) - 2); 1131 while (bit > num) 1132 bit >>= 2; 1133 root = 0; 1134 while (bit != 0) { 1135 tmp = root + bit; 1136 root >>= 1; 1137 if (num >= tmp) { 1138 num -= tmp; 1139 root += bit; 1140 } 1141 bit >>= 2; 1142 } 1143 return (root); 1144 } 1145 1146 /* 1147 * Perform the work of the laundry thread: periodically wake up and determine 1148 * whether any pages need to be laundered. If so, determine the number of pages 1149 * that need to be laundered, and launder them. 1150 */ 1151 static void 1152 vm_pageout_laundry_worker(void *arg) 1153 { 1154 struct vm_domain *domain; 1155 struct vm_pagequeue *pq; 1156 uint64_t nclean, ndirty; 1157 u_int last_launder, wakeups; 1158 int domidx, last_target, launder, shortfall, shortfall_cycle, target; 1159 bool in_shortfall; 1160 1161 domidx = (uintptr_t)arg; 1162 domain = &vm_dom[domidx]; 1163 pq = &domain->vmd_pagequeues[PQ_LAUNDRY]; 1164 KASSERT(domain->vmd_segs != 0, ("domain without segments")); 1165 vm_pageout_init_marker(&domain->vmd_laundry_marker, PQ_LAUNDRY); 1166 1167 shortfall = 0; 1168 in_shortfall = false; 1169 shortfall_cycle = 0; 1170 target = 0; 1171 last_launder = 0; 1172 1173 /* 1174 * Calls to these handlers are serialized by the swap syscall lock. 1175 */ 1176 (void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, domain, 1177 EVENTHANDLER_PRI_ANY); 1178 (void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, domain, 1179 EVENTHANDLER_PRI_ANY); 1180 1181 /* 1182 * The pageout laundry worker is never done, so loop forever. 1183 */ 1184 for (;;) { 1185 KASSERT(target >= 0, ("negative target %d", target)); 1186 KASSERT(shortfall_cycle >= 0, 1187 ("negative cycle %d", shortfall_cycle)); 1188 launder = 0; 1189 wakeups = VM_CNT_FETCH(v_pdwakeups); 1190 1191 /* 1192 * First determine whether we need to launder pages to meet a 1193 * shortage of free pages. 1194 */ 1195 if (shortfall > 0) { 1196 in_shortfall = true; 1197 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE; 1198 target = shortfall; 1199 } else if (!in_shortfall) 1200 goto trybackground; 1201 else if (shortfall_cycle == 0 || vm_laundry_target() <= 0) { 1202 /* 1203 * We recently entered shortfall and began laundering 1204 * pages. If we have completed that laundering run 1205 * (and we are no longer in shortfall) or we have met 1206 * our laundry target through other activity, then we 1207 * can stop laundering pages. 1208 */ 1209 in_shortfall = false; 1210 target = 0; 1211 goto trybackground; 1212 } 1213 last_launder = wakeups; 1214 launder = target / shortfall_cycle--; 1215 goto dolaundry; 1216 1217 /* 1218 * There's no immediate need to launder any pages; see if we 1219 * meet the conditions to perform background laundering: 1220 * 1221 * 1. The ratio of dirty to clean inactive pages exceeds the 1222 * background laundering threshold and the pagedaemon has 1223 * been woken up to reclaim pages since our last 1224 * laundering, or 1225 * 2. we haven't yet reached the target of the current 1226 * background laundering run. 1227 * 1228 * The background laundering threshold is not a constant. 1229 * Instead, it is a slowly growing function of the number of 1230 * page daemon wakeups since the last laundering. Thus, as the 1231 * ratio of dirty to clean inactive pages grows, the amount of 1232 * memory pressure required to trigger laundering decreases. 1233 */ 1234 trybackground: 1235 nclean = vm_cnt.v_inactive_count + vm_cnt.v_free_count; 1236 ndirty = vm_cnt.v_laundry_count; 1237 if (target == 0 && wakeups != last_launder && 1238 ndirty * isqrt(wakeups - last_launder) >= nclean) { 1239 target = vm_background_launder_target; 1240 } 1241 1242 /* 1243 * We have a non-zero background laundering target. If we've 1244 * laundered up to our maximum without observing a page daemon 1245 * wakeup, just stop. This is a safety belt that ensures we 1246 * don't launder an excessive amount if memory pressure is low 1247 * and the ratio of dirty to clean pages is large. Otherwise, 1248 * proceed at the background laundering rate. 1249 */ 1250 if (target > 0) { 1251 if (wakeups != last_launder) { 1252 last_launder = wakeups; 1253 last_target = target; 1254 } else if (last_target - target >= 1255 vm_background_launder_max * PAGE_SIZE / 1024) { 1256 target = 0; 1257 } 1258 launder = vm_background_launder_rate * PAGE_SIZE / 1024; 1259 launder /= VM_LAUNDER_RATE; 1260 if (launder > target) 1261 launder = target; 1262 } 1263 1264 dolaundry: 1265 if (launder > 0) { 1266 /* 1267 * Because of I/O clustering, the number of laundered 1268 * pages could exceed "target" by the maximum size of 1269 * a cluster minus one. 1270 */ 1271 target -= min(vm_pageout_launder(domain, launder, 1272 in_shortfall), target); 1273 pause("laundp", hz / VM_LAUNDER_RATE); 1274 } 1275 1276 /* 1277 * If we're not currently laundering pages and the page daemon 1278 * hasn't posted a new request, sleep until the page daemon 1279 * kicks us. 1280 */ 1281 vm_pagequeue_lock(pq); 1282 if (target == 0 && vm_laundry_request == VM_LAUNDRY_IDLE) 1283 (void)mtx_sleep(&vm_laundry_request, 1284 vm_pagequeue_lockptr(pq), PVM, "launds", 0); 1285 1286 /* 1287 * If the pagedaemon has indicated that it's in shortfall, start 1288 * a shortfall laundering unless we're already in the middle of 1289 * one. This may preempt a background laundering. 1290 */ 1291 if (vm_laundry_request == VM_LAUNDRY_SHORTFALL && 1292 (!in_shortfall || shortfall_cycle == 0)) { 1293 shortfall = vm_laundry_target() + vm_pageout_deficit; 1294 target = 0; 1295 } else 1296 shortfall = 0; 1297 1298 if (target == 0) 1299 vm_laundry_request = VM_LAUNDRY_IDLE; 1300 vm_pagequeue_unlock(pq); 1301 } 1302 } 1303 1304 /* 1305 * vm_pageout_scan does the dirty work for the pageout daemon. 1306 * 1307 * pass == 0: Update active LRU/deactivate pages 1308 * pass >= 1: Free inactive pages 1309 * 1310 * Returns true if pass was zero or enough pages were freed by the inactive 1311 * queue scan to meet the target. 1312 */ 1313 static bool 1314 vm_pageout_scan(struct vm_domain *vmd, int pass) 1315 { 1316 vm_page_t m, next; 1317 struct vm_pagequeue *pq; 1318 vm_object_t object; 1319 long min_scan; 1320 int act_delta, addl_page_shortage, deficit, inactq_shortage, maxscan; 1321 int page_shortage, scan_tick, scanned, starting_page_shortage; 1322 boolean_t queue_locked; 1323 1324 /* 1325 * If we need to reclaim memory ask kernel caches to return 1326 * some. We rate limit to avoid thrashing. 1327 */ 1328 if (vmd == &vm_dom[0] && pass > 0 && 1329 (time_uptime - lowmem_uptime) >= lowmem_period) { 1330 /* 1331 * Decrease registered cache sizes. 1332 */ 1333 SDT_PROBE0(vm, , , vm__lowmem_scan); 1334 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES); 1335 /* 1336 * We do this explicitly after the caches have been 1337 * drained above. 1338 */ 1339 uma_reclaim(); 1340 lowmem_uptime = time_uptime; 1341 } 1342 1343 /* 1344 * The addl_page_shortage is the number of temporarily 1345 * stuck pages in the inactive queue. In other words, the 1346 * number of pages from the inactive count that should be 1347 * discounted in setting the target for the active queue scan. 1348 */ 1349 addl_page_shortage = 0; 1350 1351 /* 1352 * Calculate the number of pages that we want to free. This number 1353 * can be negative if many pages are freed between the wakeup call to 1354 * the page daemon and this calculation. 1355 */ 1356 if (pass > 0) { 1357 deficit = atomic_readandclear_int(&vm_pageout_deficit); 1358 page_shortage = vm_paging_target() + deficit; 1359 } else 1360 page_shortage = deficit = 0; 1361 starting_page_shortage = page_shortage; 1362 1363 /* 1364 * Start scanning the inactive queue for pages that we can free. The 1365 * scan will stop when we reach the target or we have scanned the 1366 * entire queue. (Note that m->act_count is not used to make 1367 * decisions for the inactive queue, only for the active queue.) 1368 */ 1369 pq = &vmd->vmd_pagequeues[PQ_INACTIVE]; 1370 maxscan = pq->pq_cnt; 1371 vm_pagequeue_lock(pq); 1372 queue_locked = TRUE; 1373 for (m = TAILQ_FIRST(&pq->pq_pl); 1374 m != NULL && maxscan-- > 0 && page_shortage > 0; 1375 m = next) { 1376 vm_pagequeue_assert_locked(pq); 1377 KASSERT(queue_locked, ("unlocked inactive queue")); 1378 KASSERT(vm_page_inactive(m), ("Inactive queue %p", m)); 1379 1380 VM_CNT_INC(v_pdpages); 1381 next = TAILQ_NEXT(m, plinks.q); 1382 1383 /* 1384 * skip marker pages 1385 */ 1386 if (m->flags & PG_MARKER) 1387 continue; 1388 1389 KASSERT((m->flags & PG_FICTITIOUS) == 0, 1390 ("Fictitious page %p cannot be in inactive queue", m)); 1391 KASSERT((m->oflags & VPO_UNMANAGED) == 0, 1392 ("Unmanaged page %p cannot be in inactive queue", m)); 1393 1394 /* 1395 * The page or object lock acquisitions fail if the 1396 * page was removed from the queue or moved to a 1397 * different position within the queue. In either 1398 * case, addl_page_shortage should not be incremented. 1399 */ 1400 if (!vm_pageout_page_lock(m, &next)) 1401 goto unlock_page; 1402 else if (m->hold_count != 0) { 1403 /* 1404 * Held pages are essentially stuck in the 1405 * queue. So, they ought to be discounted 1406 * from the inactive count. See the 1407 * calculation of inactq_shortage before the 1408 * loop over the active queue below. 1409 */ 1410 addl_page_shortage++; 1411 goto unlock_page; 1412 } 1413 object = m->object; 1414 if (!VM_OBJECT_TRYWLOCK(object)) { 1415 if (!vm_pageout_fallback_object_lock(m, &next)) 1416 goto unlock_object; 1417 else if (m->hold_count != 0) { 1418 addl_page_shortage++; 1419 goto unlock_object; 1420 } 1421 } 1422 if (vm_page_busied(m)) { 1423 /* 1424 * Don't mess with busy pages. Leave them at 1425 * the front of the queue. Most likely, they 1426 * are being paged out and will leave the 1427 * queue shortly after the scan finishes. So, 1428 * they ought to be discounted from the 1429 * inactive count. 1430 */ 1431 addl_page_shortage++; 1432 unlock_object: 1433 VM_OBJECT_WUNLOCK(object); 1434 unlock_page: 1435 vm_page_unlock(m); 1436 continue; 1437 } 1438 KASSERT(m->hold_count == 0, ("Held page %p", m)); 1439 1440 /* 1441 * Dequeue the inactive page and unlock the inactive page 1442 * queue, invalidating the 'next' pointer. Dequeueing the 1443 * page here avoids a later reacquisition (and release) of 1444 * the inactive page queue lock when vm_page_activate(), 1445 * vm_page_free(), or vm_page_launder() is called. Use a 1446 * marker to remember our place in the inactive queue. 1447 */ 1448 TAILQ_INSERT_AFTER(&pq->pq_pl, m, &vmd->vmd_marker, plinks.q); 1449 vm_page_dequeue_locked(m); 1450 vm_pagequeue_unlock(pq); 1451 queue_locked = FALSE; 1452 1453 /* 1454 * Invalid pages can be easily freed. They cannot be 1455 * mapped, vm_page_free() asserts this. 1456 */ 1457 if (m->valid == 0) 1458 goto free_page; 1459 1460 /* 1461 * If the page has been referenced and the object is not dead, 1462 * reactivate or requeue the page depending on whether the 1463 * object is mapped. 1464 */ 1465 if ((m->aflags & PGA_REFERENCED) != 0) { 1466 vm_page_aflag_clear(m, PGA_REFERENCED); 1467 act_delta = 1; 1468 } else 1469 act_delta = 0; 1470 if (object->ref_count != 0) { 1471 act_delta += pmap_ts_referenced(m); 1472 } else { 1473 KASSERT(!pmap_page_is_mapped(m), 1474 ("vm_pageout_scan: page %p is mapped", m)); 1475 } 1476 if (act_delta != 0) { 1477 if (object->ref_count != 0) { 1478 VM_CNT_INC(v_reactivated); 1479 vm_page_activate(m); 1480 1481 /* 1482 * Increase the activation count if the page 1483 * was referenced while in the inactive queue. 1484 * This makes it less likely that the page will 1485 * be returned prematurely to the inactive 1486 * queue. 1487 */ 1488 m->act_count += act_delta + ACT_ADVANCE; 1489 goto drop_page; 1490 } else if ((object->flags & OBJ_DEAD) == 0) { 1491 vm_pagequeue_lock(pq); 1492 queue_locked = TRUE; 1493 m->queue = PQ_INACTIVE; 1494 TAILQ_INSERT_TAIL(&pq->pq_pl, m, plinks.q); 1495 vm_pagequeue_cnt_inc(pq); 1496 goto drop_page; 1497 } 1498 } 1499 1500 /* 1501 * If the page appears to be clean at the machine-independent 1502 * layer, then remove all of its mappings from the pmap in 1503 * anticipation of freeing it. If, however, any of the page's 1504 * mappings allow write access, then the page may still be 1505 * modified until the last of those mappings are removed. 1506 */ 1507 if (object->ref_count != 0) { 1508 vm_page_test_dirty(m); 1509 if (m->dirty == 0) 1510 pmap_remove_all(m); 1511 } 1512 1513 /* 1514 * Clean pages can be freed, but dirty pages must be sent back 1515 * to the laundry, unless they belong to a dead object. 1516 * Requeueing dirty pages from dead objects is pointless, as 1517 * they are being paged out and freed by the thread that 1518 * destroyed the object. 1519 */ 1520 if (m->dirty == 0) { 1521 free_page: 1522 vm_page_free(m); 1523 VM_CNT_INC(v_dfree); 1524 --page_shortage; 1525 } else if ((object->flags & OBJ_DEAD) == 0) 1526 vm_page_launder(m); 1527 drop_page: 1528 vm_page_unlock(m); 1529 VM_OBJECT_WUNLOCK(object); 1530 if (!queue_locked) { 1531 vm_pagequeue_lock(pq); 1532 queue_locked = TRUE; 1533 } 1534 next = TAILQ_NEXT(&vmd->vmd_marker, plinks.q); 1535 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_marker, plinks.q); 1536 } 1537 vm_pagequeue_unlock(pq); 1538 1539 /* 1540 * Wake up the laundry thread so that it can perform any needed 1541 * laundering. If we didn't meet our target, we're in shortfall and 1542 * need to launder more aggressively. If PQ_LAUNDRY is empty and no 1543 * swap devices are configured, the laundry thread has no work to do, so 1544 * don't bother waking it up. 1545 */ 1546 if (vm_laundry_request == VM_LAUNDRY_IDLE && 1547 starting_page_shortage > 0) { 1548 pq = &vm_dom[0].vmd_pagequeues[PQ_LAUNDRY]; 1549 vm_pagequeue_lock(pq); 1550 if (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled)) { 1551 if (page_shortage > 0) { 1552 vm_laundry_request = VM_LAUNDRY_SHORTFALL; 1553 VM_CNT_INC(v_pdshortfalls); 1554 } else if (vm_laundry_request != VM_LAUNDRY_SHORTFALL) 1555 vm_laundry_request = VM_LAUNDRY_BACKGROUND; 1556 wakeup(&vm_laundry_request); 1557 } 1558 vm_pagequeue_unlock(pq); 1559 } 1560 1561 #if !defined(NO_SWAPPING) 1562 /* 1563 * Wakeup the swapout daemon if we didn't free the targeted number of 1564 * pages. 1565 */ 1566 if (vm_swap_enabled && page_shortage > 0) 1567 vm_req_vmdaemon(VM_SWAP_NORMAL); 1568 #endif 1569 1570 /* 1571 * If the inactive queue scan fails repeatedly to meet its 1572 * target, kill the largest process. 1573 */ 1574 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage); 1575 1576 /* 1577 * Compute the number of pages we want to try to move from the 1578 * active queue to either the inactive or laundry queue. 1579 * 1580 * When scanning active pages, we make clean pages count more heavily 1581 * towards the page shortage than dirty pages. This is because dirty 1582 * pages must be laundered before they can be reused and thus have less 1583 * utility when attempting to quickly alleviate a shortage. However, 1584 * this weighting also causes the scan to deactivate dirty pages more 1585 * more aggressively, improving the effectiveness of clustering and 1586 * ensuring that they can eventually be reused. 1587 */ 1588 inactq_shortage = vm_cnt.v_inactive_target - (vm_cnt.v_inactive_count + 1589 vm_cnt.v_laundry_count / act_scan_laundry_weight) + 1590 vm_paging_target() + deficit + addl_page_shortage; 1591 page_shortage *= act_scan_laundry_weight; 1592 1593 pq = &vmd->vmd_pagequeues[PQ_ACTIVE]; 1594 vm_pagequeue_lock(pq); 1595 maxscan = pq->pq_cnt; 1596 1597 /* 1598 * If we're just idle polling attempt to visit every 1599 * active page within 'update_period' seconds. 1600 */ 1601 scan_tick = ticks; 1602 if (vm_pageout_update_period != 0) { 1603 min_scan = pq->pq_cnt; 1604 min_scan *= scan_tick - vmd->vmd_last_active_scan; 1605 min_scan /= hz * vm_pageout_update_period; 1606 } else 1607 min_scan = 0; 1608 if (min_scan > 0 || (inactq_shortage > 0 && maxscan > 0)) 1609 vmd->vmd_last_active_scan = scan_tick; 1610 1611 /* 1612 * Scan the active queue for pages that can be deactivated. Update 1613 * the per-page activity counter and use it to identify deactivation 1614 * candidates. Held pages may be deactivated. 1615 */ 1616 for (m = TAILQ_FIRST(&pq->pq_pl), scanned = 0; m != NULL && (scanned < 1617 min_scan || (inactq_shortage > 0 && scanned < maxscan)); m = next, 1618 scanned++) { 1619 KASSERT(m->queue == PQ_ACTIVE, 1620 ("vm_pageout_scan: page %p isn't active", m)); 1621 next = TAILQ_NEXT(m, plinks.q); 1622 if ((m->flags & PG_MARKER) != 0) 1623 continue; 1624 KASSERT((m->flags & PG_FICTITIOUS) == 0, 1625 ("Fictitious page %p cannot be in active queue", m)); 1626 KASSERT((m->oflags & VPO_UNMANAGED) == 0, 1627 ("Unmanaged page %p cannot be in active queue", m)); 1628 if (!vm_pageout_page_lock(m, &next)) { 1629 vm_page_unlock(m); 1630 continue; 1631 } 1632 1633 /* 1634 * The count for page daemon pages is updated after checking 1635 * the page for eligibility. 1636 */ 1637 VM_CNT_INC(v_pdpages); 1638 1639 /* 1640 * Check to see "how much" the page has been used. 1641 */ 1642 if ((m->aflags & PGA_REFERENCED) != 0) { 1643 vm_page_aflag_clear(m, PGA_REFERENCED); 1644 act_delta = 1; 1645 } else 1646 act_delta = 0; 1647 1648 /* 1649 * Perform an unsynchronized object ref count check. While 1650 * the page lock ensures that the page is not reallocated to 1651 * another object, in particular, one with unmanaged mappings 1652 * that cannot support pmap_ts_referenced(), two races are, 1653 * nonetheless, possible: 1654 * 1) The count was transitioning to zero, but we saw a non- 1655 * zero value. pmap_ts_referenced() will return zero 1656 * because the page is not mapped. 1657 * 2) The count was transitioning to one, but we saw zero. 1658 * This race delays the detection of a new reference. At 1659 * worst, we will deactivate and reactivate the page. 1660 */ 1661 if (m->object->ref_count != 0) 1662 act_delta += pmap_ts_referenced(m); 1663 1664 /* 1665 * Advance or decay the act_count based on recent usage. 1666 */ 1667 if (act_delta != 0) { 1668 m->act_count += ACT_ADVANCE + act_delta; 1669 if (m->act_count > ACT_MAX) 1670 m->act_count = ACT_MAX; 1671 } else 1672 m->act_count -= min(m->act_count, ACT_DECLINE); 1673 1674 /* 1675 * Move this page to the tail of the active, inactive or laundry 1676 * queue depending on usage. 1677 */ 1678 if (m->act_count == 0) { 1679 /* Dequeue to avoid later lock recursion. */ 1680 vm_page_dequeue_locked(m); 1681 1682 /* 1683 * When not short for inactive pages, let dirty pages go 1684 * through the inactive queue before moving to the 1685 * laundry queues. This gives them some extra time to 1686 * be reactivated, potentially avoiding an expensive 1687 * pageout. During a page shortage, the inactive queue 1688 * is necessarily small, so we may move dirty pages 1689 * directly to the laundry queue. 1690 */ 1691 if (inactq_shortage <= 0) 1692 vm_page_deactivate(m); 1693 else { 1694 /* 1695 * Calling vm_page_test_dirty() here would 1696 * require acquisition of the object's write 1697 * lock. However, during a page shortage, 1698 * directing dirty pages into the laundry 1699 * queue is only an optimization and not a 1700 * requirement. Therefore, we simply rely on 1701 * the opportunistic updates to the page's 1702 * dirty field by the pmap. 1703 */ 1704 if (m->dirty == 0) { 1705 vm_page_deactivate(m); 1706 inactq_shortage -= 1707 act_scan_laundry_weight; 1708 } else { 1709 vm_page_launder(m); 1710 inactq_shortage--; 1711 } 1712 } 1713 } else 1714 vm_page_requeue_locked(m); 1715 vm_page_unlock(m); 1716 } 1717 vm_pagequeue_unlock(pq); 1718 #if !defined(NO_SWAPPING) 1719 /* 1720 * Idle process swapout -- run once per second when we are reclaiming 1721 * pages. 1722 */ 1723 if (vm_swap_idle_enabled && pass > 0) { 1724 static long lsec; 1725 if (time_second != lsec) { 1726 vm_req_vmdaemon(VM_SWAP_IDLE); 1727 lsec = time_second; 1728 } 1729 } 1730 #endif 1731 return (page_shortage <= 0); 1732 } 1733 1734 static int vm_pageout_oom_vote; 1735 1736 /* 1737 * The pagedaemon threads randlomly select one to perform the 1738 * OOM. Trying to kill processes before all pagedaemons 1739 * failed to reach free target is premature. 1740 */ 1741 static void 1742 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage, 1743 int starting_page_shortage) 1744 { 1745 int old_vote; 1746 1747 if (starting_page_shortage <= 0 || starting_page_shortage != 1748 page_shortage) 1749 vmd->vmd_oom_seq = 0; 1750 else 1751 vmd->vmd_oom_seq++; 1752 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) { 1753 if (vmd->vmd_oom) { 1754 vmd->vmd_oom = FALSE; 1755 atomic_subtract_int(&vm_pageout_oom_vote, 1); 1756 } 1757 return; 1758 } 1759 1760 /* 1761 * Do not follow the call sequence until OOM condition is 1762 * cleared. 1763 */ 1764 vmd->vmd_oom_seq = 0; 1765 1766 if (vmd->vmd_oom) 1767 return; 1768 1769 vmd->vmd_oom = TRUE; 1770 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1); 1771 if (old_vote != vm_ndomains - 1) 1772 return; 1773 1774 /* 1775 * The current pagedaemon thread is the last in the quorum to 1776 * start OOM. Initiate the selection and signaling of the 1777 * victim. 1778 */ 1779 vm_pageout_oom(VM_OOM_MEM); 1780 1781 /* 1782 * After one round of OOM terror, recall our vote. On the 1783 * next pass, current pagedaemon would vote again if the low 1784 * memory condition is still there, due to vmd_oom being 1785 * false. 1786 */ 1787 vmd->vmd_oom = FALSE; 1788 atomic_subtract_int(&vm_pageout_oom_vote, 1); 1789 } 1790 1791 /* 1792 * The OOM killer is the page daemon's action of last resort when 1793 * memory allocation requests have been stalled for a prolonged period 1794 * of time because it cannot reclaim memory. This function computes 1795 * the approximate number of physical pages that could be reclaimed if 1796 * the specified address space is destroyed. 1797 * 1798 * Private, anonymous memory owned by the address space is the 1799 * principal resource that we expect to recover after an OOM kill. 1800 * Since the physical pages mapped by the address space's COW entries 1801 * are typically shared pages, they are unlikely to be released and so 1802 * they are not counted. 1803 * 1804 * To get to the point where the page daemon runs the OOM killer, its 1805 * efforts to write-back vnode-backed pages may have stalled. This 1806 * could be caused by a memory allocation deadlock in the write path 1807 * that might be resolved by an OOM kill. Therefore, physical pages 1808 * belonging to vnode-backed objects are counted, because they might 1809 * be freed without being written out first if the address space holds 1810 * the last reference to an unlinked vnode. 1811 * 1812 * Similarly, physical pages belonging to OBJT_PHYS objects are 1813 * counted because the address space might hold the last reference to 1814 * the object. 1815 */ 1816 static long 1817 vm_pageout_oom_pagecount(struct vmspace *vmspace) 1818 { 1819 vm_map_t map; 1820 vm_map_entry_t entry; 1821 vm_object_t obj; 1822 long res; 1823 1824 map = &vmspace->vm_map; 1825 KASSERT(!map->system_map, ("system map")); 1826 sx_assert(&map->lock, SA_LOCKED); 1827 res = 0; 1828 for (entry = map->header.next; entry != &map->header; 1829 entry = entry->next) { 1830 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) 1831 continue; 1832 obj = entry->object.vm_object; 1833 if (obj == NULL) 1834 continue; 1835 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 && 1836 obj->ref_count != 1) 1837 continue; 1838 switch (obj->type) { 1839 case OBJT_DEFAULT: 1840 case OBJT_SWAP: 1841 case OBJT_PHYS: 1842 case OBJT_VNODE: 1843 res += obj->resident_page_count; 1844 break; 1845 } 1846 } 1847 return (res); 1848 } 1849 1850 void 1851 vm_pageout_oom(int shortage) 1852 { 1853 struct proc *p, *bigproc; 1854 vm_offset_t size, bigsize; 1855 struct thread *td; 1856 struct vmspace *vm; 1857 bool breakout; 1858 1859 /* 1860 * We keep the process bigproc locked once we find it to keep anyone 1861 * from messing with it; however, there is a possibility of 1862 * deadlock if process B is bigproc and one of its child processes 1863 * attempts to propagate a signal to B while we are waiting for A's 1864 * lock while walking this list. To avoid this, we don't block on 1865 * the process lock but just skip a process if it is already locked. 1866 */ 1867 bigproc = NULL; 1868 bigsize = 0; 1869 sx_slock(&allproc_lock); 1870 FOREACH_PROC_IN_SYSTEM(p) { 1871 PROC_LOCK(p); 1872 1873 /* 1874 * If this is a system, protected or killed process, skip it. 1875 */ 1876 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC | 1877 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 || 1878 p->p_pid == 1 || P_KILLED(p) || 1879 (p->p_pid < 48 && swap_pager_avail != 0)) { 1880 PROC_UNLOCK(p); 1881 continue; 1882 } 1883 /* 1884 * If the process is in a non-running type state, 1885 * don't touch it. Check all the threads individually. 1886 */ 1887 breakout = false; 1888 FOREACH_THREAD_IN_PROC(p, td) { 1889 thread_lock(td); 1890 if (!TD_ON_RUNQ(td) && 1891 !TD_IS_RUNNING(td) && 1892 !TD_IS_SLEEPING(td) && 1893 !TD_IS_SUSPENDED(td) && 1894 !TD_IS_SWAPPED(td)) { 1895 thread_unlock(td); 1896 breakout = true; 1897 break; 1898 } 1899 thread_unlock(td); 1900 } 1901 if (breakout) { 1902 PROC_UNLOCK(p); 1903 continue; 1904 } 1905 /* 1906 * get the process size 1907 */ 1908 vm = vmspace_acquire_ref(p); 1909 if (vm == NULL) { 1910 PROC_UNLOCK(p); 1911 continue; 1912 } 1913 _PHOLD_LITE(p); 1914 PROC_UNLOCK(p); 1915 sx_sunlock(&allproc_lock); 1916 if (!vm_map_trylock_read(&vm->vm_map)) { 1917 vmspace_free(vm); 1918 sx_slock(&allproc_lock); 1919 PRELE(p); 1920 continue; 1921 } 1922 size = vmspace_swap_count(vm); 1923 if (shortage == VM_OOM_MEM) 1924 size += vm_pageout_oom_pagecount(vm); 1925 vm_map_unlock_read(&vm->vm_map); 1926 vmspace_free(vm); 1927 sx_slock(&allproc_lock); 1928 1929 /* 1930 * If this process is bigger than the biggest one, 1931 * remember it. 1932 */ 1933 if (size > bigsize) { 1934 if (bigproc != NULL) 1935 PRELE(bigproc); 1936 bigproc = p; 1937 bigsize = size; 1938 } else { 1939 PRELE(p); 1940 } 1941 } 1942 sx_sunlock(&allproc_lock); 1943 if (bigproc != NULL) { 1944 if (vm_panic_on_oom != 0) 1945 panic("out of swap space"); 1946 PROC_LOCK(bigproc); 1947 killproc(bigproc, "out of swap space"); 1948 sched_nice(bigproc, PRIO_MIN); 1949 _PRELE(bigproc); 1950 PROC_UNLOCK(bigproc); 1951 wakeup(&vm_cnt.v_free_count); 1952 } 1953 } 1954 1955 static void 1956 vm_pageout_worker(void *arg) 1957 { 1958 struct vm_domain *domain; 1959 int domidx, pass; 1960 bool target_met; 1961 1962 domidx = (uintptr_t)arg; 1963 domain = &vm_dom[domidx]; 1964 pass = 0; 1965 target_met = true; 1966 1967 /* 1968 * XXXKIB It could be useful to bind pageout daemon threads to 1969 * the cores belonging to the domain, from which vm_page_array 1970 * is allocated. 1971 */ 1972 1973 KASSERT(domain->vmd_segs != 0, ("domain without segments")); 1974 domain->vmd_last_active_scan = ticks; 1975 vm_pageout_init_marker(&domain->vmd_marker, PQ_INACTIVE); 1976 vm_pageout_init_marker(&domain->vmd_inacthead, PQ_INACTIVE); 1977 TAILQ_INSERT_HEAD(&domain->vmd_pagequeues[PQ_INACTIVE].pq_pl, 1978 &domain->vmd_inacthead, plinks.q); 1979 1980 /* 1981 * The pageout daemon worker is never done, so loop forever. 1982 */ 1983 while (TRUE) { 1984 mtx_lock(&vm_page_queue_free_mtx); 1985 1986 /* 1987 * Generally, after a level >= 1 scan, if there are enough 1988 * free pages to wakeup the waiters, then they are already 1989 * awake. A call to vm_page_free() during the scan awakened 1990 * them. However, in the following case, this wakeup serves 1991 * to bound the amount of time that a thread might wait. 1992 * Suppose a thread's call to vm_page_alloc() fails, but 1993 * before that thread calls VM_WAIT, enough pages are freed by 1994 * other threads to alleviate the free page shortage. The 1995 * thread will, nonetheless, wait until another page is freed 1996 * or this wakeup is performed. 1997 */ 1998 if (vm_pages_needed && !vm_page_count_min()) { 1999 vm_pages_needed = false; 2000 wakeup(&vm_cnt.v_free_count); 2001 } 2002 2003 /* 2004 * Do not clear vm_pageout_wanted until we reach our free page 2005 * target. Otherwise, we may be awakened over and over again, 2006 * wasting CPU time. 2007 */ 2008 if (vm_pageout_wanted && target_met) 2009 vm_pageout_wanted = false; 2010 2011 /* 2012 * Might the page daemon receive a wakeup call? 2013 */ 2014 if (vm_pageout_wanted) { 2015 /* 2016 * No. Either vm_pageout_wanted was set by another 2017 * thread during the previous scan, which must have 2018 * been a level 0 scan, or vm_pageout_wanted was 2019 * already set and the scan failed to free enough 2020 * pages. If we haven't yet performed a level >= 1 2021 * (page reclamation) scan, then increase the level 2022 * and scan again now. Otherwise, sleep a bit and 2023 * try again later. 2024 */ 2025 mtx_unlock(&vm_page_queue_free_mtx); 2026 if (pass >= 1) 2027 pause("psleep", hz / VM_INACT_SCAN_RATE); 2028 pass++; 2029 } else { 2030 /* 2031 * Yes. Sleep until pages need to be reclaimed or 2032 * have their reference stats updated. 2033 */ 2034 if (mtx_sleep(&vm_pageout_wanted, 2035 &vm_page_queue_free_mtx, PDROP | PVM, "psleep", 2036 hz) == 0) { 2037 VM_CNT_INC(v_pdwakeups); 2038 pass = 1; 2039 } else 2040 pass = 0; 2041 } 2042 2043 target_met = vm_pageout_scan(domain, pass); 2044 } 2045 } 2046 2047 /* 2048 * vm_pageout_init initialises basic pageout daemon settings. 2049 */ 2050 static void 2051 vm_pageout_init(void) 2052 { 2053 /* 2054 * Initialize some paging parameters. 2055 */ 2056 vm_cnt.v_interrupt_free_min = 2; 2057 if (vm_cnt.v_page_count < 2000) 2058 vm_pageout_page_count = 8; 2059 2060 /* 2061 * v_free_reserved needs to include enough for the largest 2062 * swap pager structures plus enough for any pv_entry structs 2063 * when paging. 2064 */ 2065 if (vm_cnt.v_page_count > 1024) 2066 vm_cnt.v_free_min = 4 + (vm_cnt.v_page_count - 1024) / 200; 2067 else 2068 vm_cnt.v_free_min = 4; 2069 vm_cnt.v_pageout_free_min = (2*MAXBSIZE)/PAGE_SIZE + 2070 vm_cnt.v_interrupt_free_min; 2071 vm_cnt.v_free_reserved = vm_pageout_page_count + 2072 vm_cnt.v_pageout_free_min + (vm_cnt.v_page_count / 768); 2073 vm_cnt.v_free_severe = vm_cnt.v_free_min / 2; 2074 vm_cnt.v_free_target = 4 * vm_cnt.v_free_min + vm_cnt.v_free_reserved; 2075 vm_cnt.v_free_min += vm_cnt.v_free_reserved; 2076 vm_cnt.v_free_severe += vm_cnt.v_free_reserved; 2077 vm_cnt.v_inactive_target = (3 * vm_cnt.v_free_target) / 2; 2078 if (vm_cnt.v_inactive_target > vm_cnt.v_free_count / 3) 2079 vm_cnt.v_inactive_target = vm_cnt.v_free_count / 3; 2080 2081 /* 2082 * Set the default wakeup threshold to be 10% above the minimum 2083 * page limit. This keeps the steady state out of shortfall. 2084 */ 2085 vm_pageout_wakeup_thresh = (vm_cnt.v_free_min / 10) * 11; 2086 2087 /* 2088 * Set interval in seconds for active scan. We want to visit each 2089 * page at least once every ten minutes. This is to prevent worst 2090 * case paging behaviors with stale active LRU. 2091 */ 2092 if (vm_pageout_update_period == 0) 2093 vm_pageout_update_period = 600; 2094 2095 /* XXX does not really belong here */ 2096 if (vm_page_max_wired == 0) 2097 vm_page_max_wired = vm_cnt.v_free_count / 3; 2098 2099 /* 2100 * Target amount of memory to move out of the laundry queue during a 2101 * background laundering. This is proportional to the amount of system 2102 * memory. 2103 */ 2104 vm_background_launder_target = (vm_cnt.v_free_target - 2105 vm_cnt.v_free_min) / 10; 2106 } 2107 2108 /* 2109 * vm_pageout is the high level pageout daemon. 2110 */ 2111 static void 2112 vm_pageout(void) 2113 { 2114 int error; 2115 #ifdef VM_NUMA_ALLOC 2116 int i; 2117 #endif 2118 2119 swap_pager_swap_init(); 2120 error = kthread_add(vm_pageout_laundry_worker, NULL, curproc, NULL, 2121 0, 0, "laundry: dom0"); 2122 if (error != 0) 2123 panic("starting laundry for domain 0, error %d", error); 2124 #ifdef VM_NUMA_ALLOC 2125 for (i = 1; i < vm_ndomains; i++) { 2126 error = kthread_add(vm_pageout_worker, (void *)(uintptr_t)i, 2127 curproc, NULL, 0, 0, "dom%d", i); 2128 if (error != 0) { 2129 panic("starting pageout for domain %d, error %d\n", 2130 i, error); 2131 } 2132 } 2133 #endif 2134 error = kthread_add(uma_reclaim_worker, NULL, curproc, NULL, 2135 0, 0, "uma"); 2136 if (error != 0) 2137 panic("starting uma_reclaim helper, error %d\n", error); 2138 vm_pageout_worker((void *)(uintptr_t)0); 2139 } 2140 2141 /* 2142 * Unless the free page queue lock is held by the caller, this function 2143 * should be regarded as advisory. Specifically, the caller should 2144 * not msleep() on &vm_cnt.v_free_count following this function unless 2145 * the free page queue lock is held until the msleep() is performed. 2146 */ 2147 void 2148 pagedaemon_wakeup(void) 2149 { 2150 2151 if (!vm_pageout_wanted && curthread->td_proc != pageproc) { 2152 vm_pageout_wanted = true; 2153 wakeup(&vm_pageout_wanted); 2154 } 2155 } 2156 2157 #if !defined(NO_SWAPPING) 2158 static void 2159 vm_req_vmdaemon(int req) 2160 { 2161 static int lastrun = 0; 2162 2163 mtx_lock(&vm_daemon_mtx); 2164 vm_pageout_req_swapout |= req; 2165 if ((ticks > (lastrun + hz)) || (ticks < lastrun)) { 2166 wakeup(&vm_daemon_needed); 2167 lastrun = ticks; 2168 } 2169 mtx_unlock(&vm_daemon_mtx); 2170 } 2171 2172 static void 2173 vm_daemon(void) 2174 { 2175 struct rlimit rsslim; 2176 struct proc *p; 2177 struct thread *td; 2178 struct vmspace *vm; 2179 int breakout, swapout_flags, tryagain, attempts; 2180 #ifdef RACCT 2181 uint64_t rsize, ravailable; 2182 #endif 2183 2184 while (TRUE) { 2185 mtx_lock(&vm_daemon_mtx); 2186 msleep(&vm_daemon_needed, &vm_daemon_mtx, PPAUSE, "psleep", 2187 #ifdef RACCT 2188 racct_enable ? hz : 0 2189 #else 2190 0 2191 #endif 2192 ); 2193 swapout_flags = vm_pageout_req_swapout; 2194 vm_pageout_req_swapout = 0; 2195 mtx_unlock(&vm_daemon_mtx); 2196 if (swapout_flags) 2197 swapout_procs(swapout_flags); 2198 2199 /* 2200 * scan the processes for exceeding their rlimits or if 2201 * process is swapped out -- deactivate pages 2202 */ 2203 tryagain = 0; 2204 attempts = 0; 2205 again: 2206 attempts++; 2207 sx_slock(&allproc_lock); 2208 FOREACH_PROC_IN_SYSTEM(p) { 2209 vm_pindex_t limit, size; 2210 2211 /* 2212 * if this is a system process or if we have already 2213 * looked at this process, skip it. 2214 */ 2215 PROC_LOCK(p); 2216 if (p->p_state != PRS_NORMAL || 2217 p->p_flag & (P_INEXEC | P_SYSTEM | P_WEXIT)) { 2218 PROC_UNLOCK(p); 2219 continue; 2220 } 2221 /* 2222 * if the process is in a non-running type state, 2223 * don't touch it. 2224 */ 2225 breakout = 0; 2226 FOREACH_THREAD_IN_PROC(p, td) { 2227 thread_lock(td); 2228 if (!TD_ON_RUNQ(td) && 2229 !TD_IS_RUNNING(td) && 2230 !TD_IS_SLEEPING(td) && 2231 !TD_IS_SUSPENDED(td)) { 2232 thread_unlock(td); 2233 breakout = 1; 2234 break; 2235 } 2236 thread_unlock(td); 2237 } 2238 if (breakout) { 2239 PROC_UNLOCK(p); 2240 continue; 2241 } 2242 /* 2243 * get a limit 2244 */ 2245 lim_rlimit_proc(p, RLIMIT_RSS, &rsslim); 2246 limit = OFF_TO_IDX( 2247 qmin(rsslim.rlim_cur, rsslim.rlim_max)); 2248 2249 /* 2250 * let processes that are swapped out really be 2251 * swapped out set the limit to nothing (will force a 2252 * swap-out.) 2253 */ 2254 if ((p->p_flag & P_INMEM) == 0) 2255 limit = 0; /* XXX */ 2256 vm = vmspace_acquire_ref(p); 2257 _PHOLD_LITE(p); 2258 PROC_UNLOCK(p); 2259 if (vm == NULL) { 2260 PRELE(p); 2261 continue; 2262 } 2263 sx_sunlock(&allproc_lock); 2264 2265 size = vmspace_resident_count(vm); 2266 if (size >= limit) { 2267 vm_pageout_map_deactivate_pages( 2268 &vm->vm_map, limit); 2269 size = vmspace_resident_count(vm); 2270 } 2271 #ifdef RACCT 2272 if (racct_enable) { 2273 rsize = IDX_TO_OFF(size); 2274 PROC_LOCK(p); 2275 if (p->p_state == PRS_NORMAL) 2276 racct_set(p, RACCT_RSS, rsize); 2277 ravailable = racct_get_available(p, RACCT_RSS); 2278 PROC_UNLOCK(p); 2279 if (rsize > ravailable) { 2280 /* 2281 * Don't be overly aggressive; this 2282 * might be an innocent process, 2283 * and the limit could've been exceeded 2284 * by some memory hog. Don't try 2285 * to deactivate more than 1/4th 2286 * of process' resident set size. 2287 */ 2288 if (attempts <= 8) { 2289 if (ravailable < rsize - 2290 (rsize / 4)) { 2291 ravailable = rsize - 2292 (rsize / 4); 2293 } 2294 } 2295 vm_pageout_map_deactivate_pages( 2296 &vm->vm_map, 2297 OFF_TO_IDX(ravailable)); 2298 /* Update RSS usage after paging out. */ 2299 size = vmspace_resident_count(vm); 2300 rsize = IDX_TO_OFF(size); 2301 PROC_LOCK(p); 2302 if (p->p_state == PRS_NORMAL) 2303 racct_set(p, RACCT_RSS, rsize); 2304 PROC_UNLOCK(p); 2305 if (rsize > ravailable) 2306 tryagain = 1; 2307 } 2308 } 2309 #endif 2310 vmspace_free(vm); 2311 sx_slock(&allproc_lock); 2312 PRELE(p); 2313 } 2314 sx_sunlock(&allproc_lock); 2315 if (tryagain != 0 && attempts <= 10) 2316 goto again; 2317 } 2318 } 2319 #endif /* !defined(NO_SWAPPING) */ 2320