1 /*- 2 * SPDX-License-Identifier: (BSD-4-Clause AND MIT-CMU) 3 * 4 * Copyright (c) 1991 Regents of the University of California. 5 * All rights reserved. 6 * Copyright (c) 1994 John S. Dyson 7 * All rights reserved. 8 * Copyright (c) 1994 David Greenman 9 * All rights reserved. 10 * Copyright (c) 2005 Yahoo! Technologies Norway AS 11 * All rights reserved. 12 * 13 * This code is derived from software contributed to Berkeley by 14 * The Mach Operating System project at Carnegie-Mellon University. 15 * 16 * Redistribution and use in source and binary forms, with or without 17 * modification, are permitted provided that the following conditions 18 * are met: 19 * 1. Redistributions of source code must retain the above copyright 20 * notice, this list of conditions and the following disclaimer. 21 * 2. Redistributions in binary form must reproduce the above copyright 22 * notice, this list of conditions and the following disclaimer in the 23 * documentation and/or other materials provided with the distribution. 24 * 3. All advertising materials mentioning features or use of this software 25 * must display the following acknowledgement: 26 * This product includes software developed by the University of 27 * California, Berkeley and its contributors. 28 * 4. Neither the name of the University nor the names of its contributors 29 * may be used to endorse or promote products derived from this software 30 * without specific prior written permission. 31 * 32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 35 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 42 * SUCH DAMAGE. 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 #include "opt_vm.h" 77 78 #include <sys/param.h> 79 #include <sys/systm.h> 80 #include <sys/kernel.h> 81 #include <sys/blockcount.h> 82 #include <sys/eventhandler.h> 83 #include <sys/lock.h> 84 #include <sys/mutex.h> 85 #include <sys/proc.h> 86 #include <sys/kthread.h> 87 #include <sys/ktr.h> 88 #include <sys/mount.h> 89 #include <sys/racct.h> 90 #include <sys/resourcevar.h> 91 #include <sys/sched.h> 92 #include <sys/sdt.h> 93 #include <sys/signalvar.h> 94 #include <sys/smp.h> 95 #include <sys/time.h> 96 #include <sys/vnode.h> 97 #include <sys/vmmeter.h> 98 #include <sys/rwlock.h> 99 #include <sys/sx.h> 100 #include <sys/sysctl.h> 101 102 #include <vm/vm.h> 103 #include <vm/vm_param.h> 104 #include <vm/vm_object.h> 105 #include <vm/vm_page.h> 106 #include <vm/vm_map.h> 107 #include <vm/vm_pageout.h> 108 #include <vm/vm_pager.h> 109 #include <vm/vm_phys.h> 110 #include <vm/vm_pagequeue.h> 111 #include <vm/vm_radix.h> 112 #include <vm/swap_pager.h> 113 #include <vm/vm_extern.h> 114 #include <vm/uma.h> 115 116 /* 117 * System initialization 118 */ 119 120 /* the kernel process "vm_pageout"*/ 121 static void vm_pageout(void); 122 static void vm_pageout_init(void); 123 static int vm_pageout_clean(vm_page_t m, int *numpagedout); 124 static int vm_pageout_cluster(vm_page_t m); 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 /* Pagedaemon activity rates, in subdivisions of one second. */ 145 #define VM_LAUNDER_RATE 10 146 #define VM_INACT_SCAN_RATE 10 147 148 static int swapdev_enabled; 149 int vm_pageout_page_count = 32; 150 151 static int vm_panic_on_oom = 0; 152 SYSCTL_INT(_vm, OID_AUTO, panic_on_oom, 153 CTLFLAG_RWTUN, &vm_panic_on_oom, 0, 154 "Panic on the given number of out-of-memory errors instead of " 155 "killing the largest process"); 156 157 static int vm_pageout_update_period; 158 SYSCTL_INT(_vm, OID_AUTO, pageout_update_period, 159 CTLFLAG_RWTUN, &vm_pageout_update_period, 0, 160 "Maximum active LRU update period"); 161 162 static int pageout_cpus_per_thread = 16; 163 SYSCTL_INT(_vm, OID_AUTO, pageout_cpus_per_thread, CTLFLAG_RDTUN, 164 &pageout_cpus_per_thread, 0, 165 "Number of CPUs per pagedaemon worker thread"); 166 167 static int lowmem_period = 10; 168 SYSCTL_INT(_vm, OID_AUTO, lowmem_period, CTLFLAG_RWTUN, &lowmem_period, 0, 169 "Low memory callback period"); 170 171 static int disable_swap_pageouts; 172 SYSCTL_INT(_vm, OID_AUTO, disable_swapspace_pageouts, 173 CTLFLAG_RWTUN, &disable_swap_pageouts, 0, 174 "Disallow swapout of dirty pages"); 175 176 static int pageout_lock_miss; 177 SYSCTL_INT(_vm, OID_AUTO, pageout_lock_miss, 178 CTLFLAG_RD, &pageout_lock_miss, 0, 179 "vget() lock misses during pageout"); 180 181 static int vm_pageout_oom_seq = 12; 182 SYSCTL_INT(_vm, OID_AUTO, pageout_oom_seq, 183 CTLFLAG_RWTUN, &vm_pageout_oom_seq, 0, 184 "back-to-back calls to oom detector to start OOM"); 185 186 static int act_scan_laundry_weight = 3; 187 188 static int 189 sysctl_act_scan_laundry_weight(SYSCTL_HANDLER_ARGS) 190 { 191 int error, newval; 192 193 newval = act_scan_laundry_weight; 194 error = sysctl_handle_int(oidp, &newval, 0, req); 195 if (error || req->newptr == NULL) 196 return (error); 197 if (newval < 1) 198 return (EINVAL); 199 act_scan_laundry_weight = newval; 200 return (0); 201 } 202 SYSCTL_PROC(_vm, OID_AUTO, act_scan_laundry_weight, CTLFLAG_RWTUN | CTLTYPE_INT, 203 &act_scan_laundry_weight, 0, sysctl_act_scan_laundry_weight, "I", 204 "weight given to clean vs. dirty pages in active queue scans"); 205 206 static u_int vm_background_launder_rate = 4096; 207 SYSCTL_UINT(_vm, OID_AUTO, background_launder_rate, CTLFLAG_RWTUN, 208 &vm_background_launder_rate, 0, 209 "background laundering rate, in kilobytes per second"); 210 211 static u_int vm_background_launder_max = 20 * 1024; 212 SYSCTL_UINT(_vm, OID_AUTO, background_launder_max, CTLFLAG_RWTUN, 213 &vm_background_launder_max, 0, 214 "background laundering cap, in kilobytes"); 215 216 u_long vm_page_max_user_wired; 217 SYSCTL_ULONG(_vm, OID_AUTO, max_user_wired, CTLFLAG_RW, 218 &vm_page_max_user_wired, 0, 219 "system-wide limit to user-wired page count"); 220 221 static u_int isqrt(u_int num); 222 static int vm_pageout_launder(struct vm_domain *vmd, int launder, 223 bool in_shortfall); 224 static void vm_pageout_laundry_worker(void *arg); 225 226 struct scan_state { 227 struct vm_batchqueue bq; 228 struct vm_pagequeue *pq; 229 vm_page_t marker; 230 int maxscan; 231 int scanned; 232 }; 233 234 static void 235 vm_pageout_init_scan(struct scan_state *ss, struct vm_pagequeue *pq, 236 vm_page_t marker, vm_page_t after, int maxscan) 237 { 238 239 vm_pagequeue_assert_locked(pq); 240 KASSERT((marker->a.flags & PGA_ENQUEUED) == 0, 241 ("marker %p already enqueued", marker)); 242 243 if (after == NULL) 244 TAILQ_INSERT_HEAD(&pq->pq_pl, marker, plinks.q); 245 else 246 TAILQ_INSERT_AFTER(&pq->pq_pl, after, marker, plinks.q); 247 vm_page_aflag_set(marker, PGA_ENQUEUED); 248 249 vm_batchqueue_init(&ss->bq); 250 ss->pq = pq; 251 ss->marker = marker; 252 ss->maxscan = maxscan; 253 ss->scanned = 0; 254 vm_pagequeue_unlock(pq); 255 } 256 257 static void 258 vm_pageout_end_scan(struct scan_state *ss) 259 { 260 struct vm_pagequeue *pq; 261 262 pq = ss->pq; 263 vm_pagequeue_assert_locked(pq); 264 KASSERT((ss->marker->a.flags & PGA_ENQUEUED) != 0, 265 ("marker %p not enqueued", ss->marker)); 266 267 TAILQ_REMOVE(&pq->pq_pl, ss->marker, plinks.q); 268 vm_page_aflag_clear(ss->marker, PGA_ENQUEUED); 269 pq->pq_pdpages += ss->scanned; 270 } 271 272 /* 273 * Add a small number of queued pages to a batch queue for later processing 274 * without the corresponding queue lock held. The caller must have enqueued a 275 * marker page at the desired start point for the scan. Pages will be 276 * physically dequeued if the caller so requests. Otherwise, the returned 277 * batch may contain marker pages, and it is up to the caller to handle them. 278 * 279 * When processing the batch queue, vm_pageout_defer() must be used to 280 * determine whether the page has been logically dequeued since the batch was 281 * collected. 282 */ 283 static __always_inline void 284 vm_pageout_collect_batch(struct scan_state *ss, const bool dequeue) 285 { 286 struct vm_pagequeue *pq; 287 vm_page_t m, marker, n; 288 289 marker = ss->marker; 290 pq = ss->pq; 291 292 KASSERT((marker->a.flags & PGA_ENQUEUED) != 0, 293 ("marker %p not enqueued", ss->marker)); 294 295 vm_pagequeue_lock(pq); 296 for (m = TAILQ_NEXT(marker, plinks.q); m != NULL && 297 ss->scanned < ss->maxscan && ss->bq.bq_cnt < VM_BATCHQUEUE_SIZE; 298 m = n, ss->scanned++) { 299 n = TAILQ_NEXT(m, plinks.q); 300 if ((m->flags & PG_MARKER) == 0) { 301 KASSERT((m->a.flags & PGA_ENQUEUED) != 0, 302 ("page %p not enqueued", m)); 303 KASSERT((m->flags & PG_FICTITIOUS) == 0, 304 ("Fictitious page %p cannot be in page queue", m)); 305 KASSERT((m->oflags & VPO_UNMANAGED) == 0, 306 ("Unmanaged page %p cannot be in page queue", m)); 307 } else if (dequeue) 308 continue; 309 310 (void)vm_batchqueue_insert(&ss->bq, m); 311 if (dequeue) { 312 TAILQ_REMOVE(&pq->pq_pl, m, plinks.q); 313 vm_page_aflag_clear(m, PGA_ENQUEUED); 314 } 315 } 316 TAILQ_REMOVE(&pq->pq_pl, marker, plinks.q); 317 if (__predict_true(m != NULL)) 318 TAILQ_INSERT_BEFORE(m, marker, plinks.q); 319 else 320 TAILQ_INSERT_TAIL(&pq->pq_pl, marker, plinks.q); 321 if (dequeue) 322 vm_pagequeue_cnt_add(pq, -ss->bq.bq_cnt); 323 vm_pagequeue_unlock(pq); 324 } 325 326 /* 327 * Return the next page to be scanned, or NULL if the scan is complete. 328 */ 329 static __always_inline vm_page_t 330 vm_pageout_next(struct scan_state *ss, const bool dequeue) 331 { 332 333 if (ss->bq.bq_cnt == 0) 334 vm_pageout_collect_batch(ss, dequeue); 335 return (vm_batchqueue_pop(&ss->bq)); 336 } 337 338 /* 339 * Determine whether processing of a page should be deferred and ensure that any 340 * outstanding queue operations are processed. 341 */ 342 static __always_inline bool 343 vm_pageout_defer(vm_page_t m, const uint8_t queue, const bool enqueued) 344 { 345 vm_page_astate_t as; 346 347 as = vm_page_astate_load(m); 348 if (__predict_false(as.queue != queue || 349 ((as.flags & PGA_ENQUEUED) != 0) != enqueued)) 350 return (true); 351 if ((as.flags & PGA_QUEUE_OP_MASK) != 0) { 352 vm_page_pqbatch_submit(m, queue); 353 return (true); 354 } 355 return (false); 356 } 357 358 /* 359 * We can cluster only if the page is not clean, busy, or held, and the page is 360 * in the laundry queue. 361 */ 362 static bool 363 vm_pageout_flushable(vm_page_t m) 364 { 365 if (vm_page_tryxbusy(m) == 0) 366 return (false); 367 if (!vm_page_wired(m)) { 368 vm_page_test_dirty(m); 369 if (m->dirty != 0 && vm_page_in_laundry(m) && 370 vm_page_try_remove_write(m)) 371 return (true); 372 } 373 vm_page_xunbusy(m); 374 return (false); 375 } 376 377 /* 378 * Scan for pages at adjacent offsets within the given page's object that are 379 * eligible for laundering, form a cluster of these pages and the given page, 380 * and launder that cluster. 381 */ 382 static int 383 vm_pageout_cluster(vm_page_t m) 384 { 385 struct pctrie_iter pages; 386 vm_page_t mc[2 * vm_pageout_page_count - 1]; 387 int alignment, page_base, pageout_count; 388 389 VM_OBJECT_ASSERT_WLOCKED(m->object); 390 391 vm_page_assert_xbusied(m); 392 393 vm_page_iter_init(&pages, m->object); 394 alignment = m->pindex % vm_pageout_page_count; 395 page_base = nitems(mc) / 2; 396 pageout_count = 1; 397 mc[page_base] = m; 398 399 /* 400 * During heavy mmap/modification loads the pageout 401 * daemon can really fragment the underlying file 402 * due to flushing pages out of order and not trying to 403 * align the clusters (which leaves sporadic out-of-order 404 * holes). To solve this problem we do the reverse scan 405 * first and attempt to align our cluster, then do a 406 * forward scan if room remains. 407 * 408 * If we are at an alignment boundary, stop here, and switch directions. 409 */ 410 if (alignment > 0) { 411 pages.index = mc[page_base]->pindex; 412 do { 413 m = vm_radix_iter_prev(&pages); 414 if (m == NULL || !vm_pageout_flushable(m)) 415 break; 416 mc[--page_base] = m; 417 } while (pageout_count++ < alignment); 418 } 419 if (pageout_count < vm_pageout_page_count) { 420 pages.index = mc[page_base + pageout_count - 1]->pindex; 421 do { 422 m = vm_radix_iter_next(&pages); 423 if (m == NULL || !vm_pageout_flushable(m)) 424 break; 425 mc[page_base + pageout_count] = m; 426 } while (++pageout_count < vm_pageout_page_count); 427 } 428 if (pageout_count < vm_pageout_page_count && 429 alignment == nitems(mc) / 2 - page_base) { 430 /* Resume the reverse scan. */ 431 pages.index = mc[page_base]->pindex; 432 do { 433 m = vm_radix_iter_prev(&pages); 434 if (m == NULL || !vm_pageout_flushable(m)) 435 break; 436 mc[--page_base] = m; 437 } while (++pageout_count < vm_pageout_page_count); 438 } 439 440 return (vm_pageout_flush(&mc[page_base], pageout_count, 441 VM_PAGER_PUT_NOREUSE, NULL)); 442 } 443 444 /* 445 * vm_pageout_flush() - launder the given pages 446 * 447 * The given pages are laundered. Note that we setup for the start of 448 * I/O ( i.e. busy the page ), mark it read-only, and bump the object 449 * reference count all in here rather then in the parent. If we want 450 * the parent to do more sophisticated things we may have to change 451 * the ordering. 452 * 453 * If eio is not NULL, returns the count of pages between 0 and first page 454 * with status VM_PAGER_AGAIN. *eio is set to true if pager returned 455 * VM_PAGER_ERROR or VM_PAGER_FAIL for any page in that set. 456 * 457 * Otherwise, returns the number of paged-out pages. 458 */ 459 int 460 vm_pageout_flush(vm_page_t *mc, int count, int flags, bool *eio) 461 { 462 vm_object_t object = mc[0]->object; 463 int pageout_status[count]; 464 int numpagedout = 0; 465 int i, runlen; 466 467 VM_OBJECT_ASSERT_WLOCKED(object); 468 469 /* 470 * Initiate I/O. Mark the pages shared busy and verify that they're 471 * valid and read-only. 472 * 473 * We do not have to fixup the clean/dirty bits here... we can 474 * allow the pager to do it after the I/O completes. 475 * 476 * NOTE! mc[i]->dirty may be partial or fragmented due to an 477 * edge case with file fragments. 478 */ 479 for (i = 0; i < count; i++) { 480 KASSERT(vm_page_all_valid(mc[i]), 481 ("vm_pageout_flush: partially invalid page %p index %d/%d", 482 mc[i], i, count)); 483 KASSERT((mc[i]->a.flags & PGA_WRITEABLE) == 0, 484 ("vm_pageout_flush: writeable page %p", mc[i])); 485 vm_page_busy_downgrade(mc[i]); 486 } 487 vm_object_pip_add(object, count); 488 489 vm_pager_put_pages(object, mc, count, flags, pageout_status); 490 491 runlen = count; 492 if (eio != NULL) 493 *eio = false; 494 for (i = 0; i < count; i++) { 495 vm_page_t mt = mc[i]; 496 497 KASSERT(pageout_status[i] == VM_PAGER_PEND || 498 !pmap_page_is_write_mapped(mt), 499 ("vm_pageout_flush: page %p is not write protected", mt)); 500 switch (pageout_status[i]) { 501 case VM_PAGER_OK: 502 /* 503 * The page may have moved since laundering started, in 504 * which case it should be left alone. 505 */ 506 if (vm_page_in_laundry(mt)) 507 vm_page_deactivate_noreuse(mt); 508 /* FALLTHROUGH */ 509 case VM_PAGER_PEND: 510 numpagedout++; 511 break; 512 case VM_PAGER_BAD: 513 /* 514 * The page is outside the object's range. We pretend 515 * that the page out worked and clean the page, so the 516 * changes will be lost if the page is reclaimed by 517 * the page daemon. 518 */ 519 vm_page_undirty(mt); 520 if (vm_page_in_laundry(mt)) 521 vm_page_deactivate_noreuse(mt); 522 break; 523 case VM_PAGER_ERROR: 524 case VM_PAGER_FAIL: 525 /* 526 * If the page couldn't be paged out to swap because the 527 * pager wasn't able to find space, place the page in 528 * the PQ_UNSWAPPABLE holding queue. This is an 529 * optimization that prevents the page daemon from 530 * wasting CPU cycles on pages that cannot be reclaimed 531 * because no swap device is configured. 532 * 533 * Otherwise, reactivate the page so that it doesn't 534 * clog the laundry and inactive queues. (We will try 535 * paging it out again later.) 536 */ 537 if ((object->flags & OBJ_SWAP) != 0 && 538 pageout_status[i] == VM_PAGER_FAIL) { 539 vm_page_unswappable(mt); 540 numpagedout++; 541 } else 542 vm_page_activate(mt); 543 if (eio != NULL) 544 *eio = true; 545 break; 546 case VM_PAGER_AGAIN: 547 if (runlen == count) 548 runlen = i; 549 break; 550 } 551 552 /* 553 * If the operation is still going, leave the page busy to 554 * block all other accesses. Also, leave the paging in 555 * progress indicator set so that we don't attempt an object 556 * collapse. 557 */ 558 if (pageout_status[i] != VM_PAGER_PEND) { 559 vm_object_pip_wakeup(object); 560 vm_page_sunbusy(mt); 561 } 562 } 563 if (eio != NULL) 564 return (runlen); 565 return (numpagedout); 566 } 567 568 static void 569 vm_pageout_swapon(void *arg __unused, struct swdevt *sp __unused) 570 { 571 572 atomic_store_rel_int(&swapdev_enabled, 1); 573 } 574 575 static void 576 vm_pageout_swapoff(void *arg __unused, struct swdevt *sp __unused) 577 { 578 579 if (swap_pager_nswapdev() == 1) 580 atomic_store_rel_int(&swapdev_enabled, 0); 581 } 582 583 /* 584 * Attempt to acquire all of the necessary locks to launder a page and 585 * then call through the clustering layer to PUTPAGES. Wait a short 586 * time for a vnode lock. 587 * 588 * Requires the page and object lock on entry, releases both before return. 589 * Returns 0 on success and an errno otherwise. 590 */ 591 static int 592 vm_pageout_clean(vm_page_t m, int *numpagedout) 593 { 594 struct vnode *vp; 595 struct mount *mp; 596 vm_object_t object; 597 vm_pindex_t pindex; 598 int error; 599 600 object = m->object; 601 VM_OBJECT_ASSERT_WLOCKED(object); 602 error = 0; 603 vp = NULL; 604 mp = NULL; 605 606 /* 607 * The object is already known NOT to be dead. It 608 * is possible for the vget() to block the whole 609 * pageout daemon, but the new low-memory handling 610 * code should prevent it. 611 * 612 * We can't wait forever for the vnode lock, we might 613 * deadlock due to a vn_read() getting stuck in 614 * vm_wait while holding this vnode. We skip the 615 * vnode if we can't get it in a reasonable amount 616 * of time. 617 */ 618 if (object->type == OBJT_VNODE) { 619 vm_page_xunbusy(m); 620 vp = object->handle; 621 if (vp->v_type == VREG && 622 vn_start_write(vp, &mp, V_NOWAIT) != 0) { 623 mp = NULL; 624 error = EDEADLK; 625 goto unlock_all; 626 } 627 KASSERT(mp != NULL, 628 ("vp %p with NULL v_mount", vp)); 629 vm_object_reference_locked(object); 630 pindex = m->pindex; 631 VM_OBJECT_WUNLOCK(object); 632 if (vget(vp, vn_lktype_write(NULL, vp) | LK_TIMELOCK) != 0) { 633 vp = NULL; 634 error = EDEADLK; 635 goto unlock_mp; 636 } 637 VM_OBJECT_WLOCK(object); 638 639 /* 640 * Ensure that the object and vnode were not disassociated 641 * while locks were dropped. 642 */ 643 if (vp->v_object != object) { 644 error = ENOENT; 645 goto unlock_all; 646 } 647 648 /* 649 * While the object was unlocked, the page may have been: 650 * (1) moved to a different queue, 651 * (2) reallocated to a different object, 652 * (3) reallocated to a different offset, or 653 * (4) cleaned. 654 */ 655 if (!vm_page_in_laundry(m) || m->object != object || 656 m->pindex != pindex || m->dirty == 0) { 657 error = ENXIO; 658 goto unlock_all; 659 } 660 661 /* 662 * The page may have been busied while the object lock was 663 * released. 664 */ 665 if (vm_page_tryxbusy(m) == 0) { 666 error = EBUSY; 667 goto unlock_all; 668 } 669 } 670 671 /* 672 * Remove all writeable mappings, failing if the page is wired. 673 */ 674 if (!vm_page_try_remove_write(m)) { 675 vm_page_xunbusy(m); 676 error = EBUSY; 677 goto unlock_all; 678 } 679 680 /* 681 * If a page is dirty, then it is either being washed 682 * (but not yet cleaned) or it is still in the 683 * laundry. If it is still in the laundry, then we 684 * start the cleaning operation. 685 */ 686 if ((*numpagedout = vm_pageout_cluster(m)) == 0) 687 error = EIO; 688 689 unlock_all: 690 VM_OBJECT_WUNLOCK(object); 691 692 unlock_mp: 693 if (mp != NULL) { 694 if (vp != NULL) 695 vput(vp); 696 vm_object_deallocate(object); 697 vn_finished_write(mp); 698 } 699 700 return (error); 701 } 702 703 /* 704 * Attempt to launder the specified number of pages. 705 * 706 * Returns the number of pages successfully laundered. 707 */ 708 static int 709 vm_pageout_launder(struct vm_domain *vmd, int launder, bool in_shortfall) 710 { 711 struct scan_state ss; 712 struct vm_pagequeue *pq; 713 vm_object_t object; 714 vm_page_t m, marker; 715 vm_page_astate_t new, old; 716 int act_delta, error, numpagedout, queue, refs, starting_target; 717 int vnodes_skipped; 718 bool pageout_ok; 719 720 object = NULL; 721 starting_target = launder; 722 vnodes_skipped = 0; 723 724 /* 725 * Scan the laundry queues for pages eligible to be laundered. We stop 726 * once the target number of dirty pages have been laundered, or once 727 * we've reached the end of the queue. A single iteration of this loop 728 * may cause more than one page to be laundered because of clustering. 729 * 730 * As an optimization, we avoid laundering from PQ_UNSWAPPABLE when no 731 * swap devices are configured. 732 */ 733 if (atomic_load_acq_int(&swapdev_enabled)) 734 queue = PQ_UNSWAPPABLE; 735 else 736 queue = PQ_LAUNDRY; 737 738 scan: 739 marker = &vmd->vmd_markers[queue]; 740 pq = &vmd->vmd_pagequeues[queue]; 741 vm_pagequeue_lock(pq); 742 vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt); 743 while (launder > 0 && (m = vm_pageout_next(&ss, false)) != NULL) { 744 if (__predict_false((m->flags & PG_MARKER) != 0)) 745 continue; 746 747 /* 748 * Don't touch a page that was removed from the queue after the 749 * page queue lock was released. Otherwise, ensure that any 750 * pending queue operations, such as dequeues for wired pages, 751 * are handled. 752 */ 753 if (vm_pageout_defer(m, queue, true)) 754 continue; 755 756 /* 757 * Lock the page's object. 758 */ 759 if (object == NULL || object != m->object) { 760 if (object != NULL) 761 VM_OBJECT_WUNLOCK(object); 762 object = atomic_load_ptr(&m->object); 763 if (__predict_false(object == NULL)) 764 /* The page is being freed by another thread. */ 765 continue; 766 767 /* Depends on type-stability. */ 768 VM_OBJECT_WLOCK(object); 769 if (__predict_false(m->object != object)) { 770 VM_OBJECT_WUNLOCK(object); 771 object = NULL; 772 continue; 773 } 774 } 775 776 if (vm_page_tryxbusy(m) == 0) 777 continue; 778 779 /* 780 * Check for wirings now that we hold the object lock and have 781 * exclusively busied the page. If the page is mapped, it may 782 * still be wired by pmap lookups. The call to 783 * vm_page_try_remove_all() below atomically checks for such 784 * wirings and removes mappings. If the page is unmapped, the 785 * wire count is guaranteed not to increase after this check. 786 */ 787 if (__predict_false(vm_page_wired(m))) 788 goto skip_page; 789 790 /* 791 * Invalid pages can be easily freed. They cannot be 792 * mapped; vm_page_free() asserts this. 793 */ 794 if (vm_page_none_valid(m)) 795 goto free_page; 796 797 refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0; 798 799 for (old = vm_page_astate_load(m);;) { 800 /* 801 * Check to see if the page has been removed from the 802 * queue since the first such check. Leave it alone if 803 * so, discarding any references collected by 804 * pmap_ts_referenced(). 805 */ 806 if (__predict_false(_vm_page_queue(old) == PQ_NONE)) 807 goto skip_page; 808 809 new = old; 810 act_delta = refs; 811 if ((old.flags & PGA_REFERENCED) != 0) { 812 new.flags &= ~PGA_REFERENCED; 813 act_delta++; 814 } 815 if (act_delta == 0) { 816 ; 817 } else if (object->ref_count != 0) { 818 /* 819 * Increase the activation count if the page was 820 * referenced while in the laundry queue. This 821 * makes it less likely that the page will be 822 * returned prematurely to the laundry queue. 823 */ 824 new.act_count += ACT_ADVANCE + 825 act_delta; 826 if (new.act_count > ACT_MAX) 827 new.act_count = ACT_MAX; 828 829 new.flags &= ~PGA_QUEUE_OP_MASK; 830 new.flags |= PGA_REQUEUE; 831 new.queue = PQ_ACTIVE; 832 if (!vm_page_pqstate_commit(m, &old, new)) 833 continue; 834 835 /* 836 * If this was a background laundering, count 837 * activated pages towards our target. The 838 * purpose of background laundering is to ensure 839 * that pages are eventually cycled through the 840 * laundry queue, and an activation is a valid 841 * way out. 842 */ 843 if (!in_shortfall) 844 launder--; 845 VM_CNT_INC(v_reactivated); 846 goto skip_page; 847 } else if ((object->flags & OBJ_DEAD) == 0) { 848 new.flags |= PGA_REQUEUE; 849 if (!vm_page_pqstate_commit(m, &old, new)) 850 continue; 851 goto skip_page; 852 } 853 break; 854 } 855 856 /* 857 * If the page appears to be clean at the machine-independent 858 * layer, then remove all of its mappings from the pmap in 859 * anticipation of freeing it. If, however, any of the page's 860 * mappings allow write access, then the page may still be 861 * modified until the last of those mappings are removed. 862 */ 863 if (object->ref_count != 0) { 864 vm_page_test_dirty(m); 865 if (m->dirty == 0 && !vm_page_try_remove_all(m)) 866 goto skip_page; 867 } 868 869 /* 870 * Clean pages are freed, and dirty pages are paged out unless 871 * they belong to a dead object. Requeueing dirty pages from 872 * dead objects is pointless, as they are being paged out and 873 * freed by the thread that destroyed the object. 874 */ 875 if (m->dirty == 0) { 876 free_page: 877 /* 878 * Now we are guaranteed that no other threads are 879 * manipulating the page, check for a last-second 880 * reference. 881 */ 882 if (vm_pageout_defer(m, queue, true)) 883 goto skip_page; 884 vm_page_free(m); 885 VM_CNT_INC(v_dfree); 886 } else if ((object->flags & OBJ_DEAD) == 0) { 887 if ((object->flags & OBJ_SWAP) != 0) 888 pageout_ok = disable_swap_pageouts == 0; 889 else 890 pageout_ok = true; 891 if (!pageout_ok) { 892 vm_page_launder(m); 893 goto skip_page; 894 } 895 896 /* 897 * Form a cluster with adjacent, dirty pages from the 898 * same object, and page out that entire cluster. 899 * 900 * The adjacent, dirty pages must also be in the 901 * laundry. However, their mappings are not checked 902 * for new references. Consequently, a recently 903 * referenced page may be paged out. However, that 904 * page will not be prematurely reclaimed. After page 905 * out, the page will be placed in the inactive queue, 906 * where any new references will be detected and the 907 * page reactivated. 908 */ 909 error = vm_pageout_clean(m, &numpagedout); 910 if (error == 0) { 911 launder -= numpagedout; 912 ss.scanned += numpagedout; 913 } else if (error == EDEADLK) { 914 pageout_lock_miss++; 915 vnodes_skipped++; 916 } 917 object = NULL; 918 } else { 919 skip_page: 920 vm_page_xunbusy(m); 921 } 922 } 923 if (object != NULL) { 924 VM_OBJECT_WUNLOCK(object); 925 object = NULL; 926 } 927 vm_pagequeue_lock(pq); 928 vm_pageout_end_scan(&ss); 929 vm_pagequeue_unlock(pq); 930 931 if (launder > 0 && queue == PQ_UNSWAPPABLE) { 932 queue = PQ_LAUNDRY; 933 goto scan; 934 } 935 936 /* 937 * Wakeup the sync daemon if we skipped a vnode in a writeable object 938 * and we didn't launder enough pages. 939 */ 940 if (vnodes_skipped > 0 && launder > 0) 941 (void)speedup_syncer(); 942 943 return (starting_target - launder); 944 } 945 946 /* 947 * Compute the integer square root. 948 */ 949 static u_int 950 isqrt(u_int num) 951 { 952 u_int bit, root, tmp; 953 954 bit = num != 0 ? (1u << ((fls(num) - 1) & ~1)) : 0; 955 root = 0; 956 while (bit != 0) { 957 tmp = root + bit; 958 root >>= 1; 959 if (num >= tmp) { 960 num -= tmp; 961 root += bit; 962 } 963 bit >>= 2; 964 } 965 return (root); 966 } 967 968 /* 969 * Perform the work of the laundry thread: periodically wake up and determine 970 * whether any pages need to be laundered. If so, determine the number of pages 971 * that need to be laundered, and launder them. 972 */ 973 static void 974 vm_pageout_laundry_worker(void *arg) 975 { 976 struct vm_domain *vmd; 977 struct vm_pagequeue *pq; 978 uint64_t nclean, ndirty, nfreed; 979 int domain, last_target, launder, shortfall, shortfall_cycle, target; 980 bool in_shortfall; 981 982 domain = (uintptr_t)arg; 983 vmd = VM_DOMAIN(domain); 984 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY]; 985 KASSERT(vmd->vmd_segs != 0, ("domain without segments")); 986 987 shortfall = 0; 988 in_shortfall = false; 989 shortfall_cycle = 0; 990 last_target = target = 0; 991 nfreed = 0; 992 993 /* 994 * Calls to these handlers are serialized by the swap syscall lock. 995 */ 996 (void)EVENTHANDLER_REGISTER(swapon, vm_pageout_swapon, vmd, 997 EVENTHANDLER_PRI_ANY); 998 (void)EVENTHANDLER_REGISTER(swapoff, vm_pageout_swapoff, vmd, 999 EVENTHANDLER_PRI_ANY); 1000 1001 /* 1002 * The pageout laundry worker is never done, so loop forever. 1003 */ 1004 for (;;) { 1005 KASSERT(target >= 0, ("negative target %d", target)); 1006 KASSERT(shortfall_cycle >= 0, 1007 ("negative cycle %d", shortfall_cycle)); 1008 launder = 0; 1009 1010 /* 1011 * First determine whether we need to launder pages to meet a 1012 * shortage of free pages. 1013 */ 1014 if (shortfall > 0) { 1015 in_shortfall = true; 1016 shortfall_cycle = VM_LAUNDER_RATE / VM_INACT_SCAN_RATE; 1017 target = shortfall; 1018 } else if (!in_shortfall) 1019 goto trybackground; 1020 else if (shortfall_cycle == 0 || vm_laundry_target(vmd) <= 0) { 1021 /* 1022 * We recently entered shortfall and began laundering 1023 * pages. If we have completed that laundering run 1024 * (and we are no longer in shortfall) or we have met 1025 * our laundry target through other activity, then we 1026 * can stop laundering pages. 1027 */ 1028 in_shortfall = false; 1029 target = 0; 1030 goto trybackground; 1031 } 1032 launder = target / shortfall_cycle--; 1033 goto dolaundry; 1034 1035 /* 1036 * There's no immediate need to launder any pages; see if we 1037 * meet the conditions to perform background laundering: 1038 * 1039 * 1. The ratio of dirty to clean inactive pages exceeds the 1040 * background laundering threshold, or 1041 * 2. we haven't yet reached the target of the current 1042 * background laundering run. 1043 * 1044 * The background laundering threshold is not a constant. 1045 * Instead, it is a slowly growing function of the number of 1046 * clean pages freed by the page daemon since the last 1047 * background laundering. Thus, as the ratio of dirty to 1048 * clean inactive pages grows, the amount of memory pressure 1049 * required to trigger laundering decreases. We ensure 1050 * that the threshold is non-zero after an inactive queue 1051 * scan, even if that scan failed to free a single clean page. 1052 */ 1053 trybackground: 1054 nclean = vmd->vmd_free_count + 1055 vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt; 1056 ndirty = vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt; 1057 if (target == 0 && ndirty * isqrt(howmany(nfreed + 1, 1058 vmd->vmd_free_target - vmd->vmd_free_min)) >= nclean) { 1059 target = vmd->vmd_background_launder_target; 1060 } 1061 1062 /* 1063 * We have a non-zero background laundering target. If we've 1064 * laundered up to our maximum without observing a page daemon 1065 * request, just stop. This is a safety belt that ensures we 1066 * don't launder an excessive amount if memory pressure is low 1067 * and the ratio of dirty to clean pages is large. Otherwise, 1068 * proceed at the background laundering rate. 1069 */ 1070 if (target > 0) { 1071 if (nfreed > 0) { 1072 nfreed = 0; 1073 last_target = target; 1074 } else if (last_target - target >= 1075 vm_background_launder_max * PAGE_SIZE / 1024) { 1076 target = 0; 1077 } 1078 launder = vm_background_launder_rate * PAGE_SIZE / 1024; 1079 launder /= VM_LAUNDER_RATE; 1080 if (launder > target) 1081 launder = target; 1082 } 1083 1084 dolaundry: 1085 if (launder > 0) { 1086 /* 1087 * Because of I/O clustering, the number of laundered 1088 * pages could exceed "target" by the maximum size of 1089 * a cluster minus one. 1090 */ 1091 target -= min(vm_pageout_launder(vmd, launder, 1092 in_shortfall), target); 1093 pause("laundp", hz / VM_LAUNDER_RATE); 1094 } 1095 1096 /* 1097 * If we're not currently laundering pages and the page daemon 1098 * hasn't posted a new request, sleep until the page daemon 1099 * kicks us. 1100 */ 1101 vm_pagequeue_lock(pq); 1102 if (target == 0 && vmd->vmd_laundry_request == VM_LAUNDRY_IDLE) 1103 (void)mtx_sleep(&vmd->vmd_laundry_request, 1104 vm_pagequeue_lockptr(pq), PVM, "launds", 0); 1105 1106 /* 1107 * If the pagedaemon has indicated that it's in shortfall, start 1108 * a shortfall laundering unless we're already in the middle of 1109 * one. This may preempt a background laundering. 1110 */ 1111 if (vmd->vmd_laundry_request == VM_LAUNDRY_SHORTFALL && 1112 (!in_shortfall || shortfall_cycle == 0)) { 1113 shortfall = vm_laundry_target(vmd) + 1114 vmd->vmd_pageout_deficit; 1115 target = 0; 1116 } else 1117 shortfall = 0; 1118 1119 if (target == 0) 1120 vmd->vmd_laundry_request = VM_LAUNDRY_IDLE; 1121 nfreed += vmd->vmd_clean_pages_freed; 1122 vmd->vmd_clean_pages_freed = 0; 1123 vm_pagequeue_unlock(pq); 1124 } 1125 } 1126 1127 /* 1128 * Compute the number of pages we want to try to move from the 1129 * active queue to either the inactive or laundry queue. 1130 * 1131 * When scanning active pages during a shortage, we make clean pages 1132 * count more heavily towards the page shortage than dirty pages. 1133 * This is because dirty pages must be laundered before they can be 1134 * reused and thus have less utility when attempting to quickly 1135 * alleviate a free page shortage. However, this weighting also 1136 * causes the scan to deactivate dirty pages more aggressively, 1137 * improving the effectiveness of clustering. 1138 */ 1139 static int 1140 vm_pageout_active_target(struct vm_domain *vmd) 1141 { 1142 int shortage; 1143 1144 shortage = vmd->vmd_inactive_target + vm_paging_target(vmd) - 1145 (vmd->vmd_pagequeues[PQ_INACTIVE].pq_cnt + 1146 vmd->vmd_pagequeues[PQ_LAUNDRY].pq_cnt / act_scan_laundry_weight); 1147 shortage *= act_scan_laundry_weight; 1148 return (shortage); 1149 } 1150 1151 /* 1152 * Scan the active queue. If there is no shortage of inactive pages, scan a 1153 * small portion of the queue in order to maintain quasi-LRU. 1154 */ 1155 static void 1156 vm_pageout_scan_active(struct vm_domain *vmd, int page_shortage) 1157 { 1158 struct scan_state ss; 1159 vm_object_t object; 1160 vm_page_t m, marker; 1161 struct vm_pagequeue *pq; 1162 vm_page_astate_t old, new; 1163 long min_scan; 1164 int act_delta, max_scan, ps_delta, refs, scan_tick; 1165 uint8_t nqueue; 1166 1167 marker = &vmd->vmd_markers[PQ_ACTIVE]; 1168 pq = &vmd->vmd_pagequeues[PQ_ACTIVE]; 1169 vm_pagequeue_lock(pq); 1170 1171 /* 1172 * If we're just idle polling attempt to visit every 1173 * active page within 'update_period' seconds. 1174 */ 1175 scan_tick = ticks; 1176 if (vm_pageout_update_period != 0) { 1177 min_scan = pq->pq_cnt; 1178 min_scan *= scan_tick - vmd->vmd_last_active_scan; 1179 min_scan /= hz * vm_pageout_update_period; 1180 } else 1181 min_scan = 0; 1182 if (min_scan > 0 || (page_shortage > 0 && pq->pq_cnt > 0)) 1183 vmd->vmd_last_active_scan = scan_tick; 1184 1185 /* 1186 * Scan the active queue for pages that can be deactivated. Update 1187 * the per-page activity counter and use it to identify deactivation 1188 * candidates. Held pages may be deactivated. 1189 * 1190 * To avoid requeuing each page that remains in the active queue, we 1191 * implement the CLOCK algorithm. To keep the implementation of the 1192 * enqueue operation consistent for all page queues, we use two hands, 1193 * represented by marker pages. Scans begin at the first hand, which 1194 * precedes the second hand in the queue. When the two hands meet, 1195 * they are moved back to the head and tail of the queue, respectively, 1196 * and scanning resumes. 1197 */ 1198 max_scan = page_shortage > 0 ? pq->pq_cnt : min_scan; 1199 act_scan: 1200 vm_pageout_init_scan(&ss, pq, marker, &vmd->vmd_clock[0], max_scan); 1201 while ((m = vm_pageout_next(&ss, false)) != NULL) { 1202 if (__predict_false(m == &vmd->vmd_clock[1])) { 1203 vm_pagequeue_lock(pq); 1204 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q); 1205 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[1], plinks.q); 1206 TAILQ_INSERT_HEAD(&pq->pq_pl, &vmd->vmd_clock[0], 1207 plinks.q); 1208 TAILQ_INSERT_TAIL(&pq->pq_pl, &vmd->vmd_clock[1], 1209 plinks.q); 1210 max_scan -= ss.scanned; 1211 vm_pageout_end_scan(&ss); 1212 goto act_scan; 1213 } 1214 if (__predict_false((m->flags & PG_MARKER) != 0)) 1215 continue; 1216 1217 /* 1218 * Don't touch a page that was removed from the queue after the 1219 * page queue lock was released. Otherwise, ensure that any 1220 * pending queue operations, such as dequeues for wired pages, 1221 * are handled. 1222 */ 1223 if (vm_pageout_defer(m, PQ_ACTIVE, true)) 1224 continue; 1225 1226 /* 1227 * A page's object pointer may be set to NULL before 1228 * the object lock is acquired. 1229 */ 1230 object = atomic_load_ptr(&m->object); 1231 if (__predict_false(object == NULL)) 1232 /* 1233 * The page has been removed from its object. 1234 */ 1235 continue; 1236 1237 /* Deferred free of swap space. */ 1238 if ((m->a.flags & PGA_SWAP_FREE) != 0 && 1239 VM_OBJECT_TRYWLOCK(object)) { 1240 if (m->object == object) 1241 vm_pager_page_unswapped(m); 1242 VM_OBJECT_WUNLOCK(object); 1243 } 1244 1245 /* 1246 * Check to see "how much" the page has been used. 1247 * 1248 * Test PGA_REFERENCED after calling pmap_ts_referenced() so 1249 * that a reference from a concurrently destroyed mapping is 1250 * observed here and now. 1251 * 1252 * Perform an unsynchronized object ref count check. While 1253 * the page lock ensures that the page is not reallocated to 1254 * another object, in particular, one with unmanaged mappings 1255 * that cannot support pmap_ts_referenced(), two races are, 1256 * nonetheless, possible: 1257 * 1) The count was transitioning to zero, but we saw a non- 1258 * zero value. pmap_ts_referenced() will return zero 1259 * because the page is not mapped. 1260 * 2) The count was transitioning to one, but we saw zero. 1261 * This race delays the detection of a new reference. At 1262 * worst, we will deactivate and reactivate the page. 1263 */ 1264 refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0; 1265 1266 old = vm_page_astate_load(m); 1267 do { 1268 /* 1269 * Check to see if the page has been removed from the 1270 * queue since the first such check. Leave it alone if 1271 * so, discarding any references collected by 1272 * pmap_ts_referenced(). 1273 */ 1274 if (__predict_false(_vm_page_queue(old) == PQ_NONE)) { 1275 ps_delta = 0; 1276 break; 1277 } 1278 1279 /* 1280 * Advance or decay the act_count based on recent usage. 1281 */ 1282 new = old; 1283 act_delta = refs; 1284 if ((old.flags & PGA_REFERENCED) != 0) { 1285 new.flags &= ~PGA_REFERENCED; 1286 act_delta++; 1287 } 1288 if (act_delta != 0) { 1289 new.act_count += ACT_ADVANCE + act_delta; 1290 if (new.act_count > ACT_MAX) 1291 new.act_count = ACT_MAX; 1292 } else { 1293 new.act_count -= min(new.act_count, 1294 ACT_DECLINE); 1295 } 1296 1297 if (new.act_count > 0) { 1298 /* 1299 * Adjust the activation count and keep the page 1300 * in the active queue. The count might be left 1301 * unchanged if it is saturated. The page may 1302 * have been moved to a different queue since we 1303 * started the scan, in which case we move it 1304 * back. 1305 */ 1306 ps_delta = 0; 1307 if (old.queue != PQ_ACTIVE) { 1308 new.flags &= ~PGA_QUEUE_OP_MASK; 1309 new.flags |= PGA_REQUEUE; 1310 new.queue = PQ_ACTIVE; 1311 } 1312 } else { 1313 /* 1314 * When not short for inactive pages, let dirty 1315 * pages go through the inactive queue before 1316 * moving to the laundry queue. This gives them 1317 * some extra time to be reactivated, 1318 * potentially avoiding an expensive pageout. 1319 * However, during a page shortage, the inactive 1320 * queue is necessarily small, and so dirty 1321 * pages would only spend a trivial amount of 1322 * time in the inactive queue. Therefore, we 1323 * might as well place them directly in the 1324 * laundry queue to reduce queuing overhead. 1325 * 1326 * Calling vm_page_test_dirty() here would 1327 * require acquisition of the object's write 1328 * lock. However, during a page shortage, 1329 * directing dirty pages into the laundry queue 1330 * is only an optimization and not a 1331 * requirement. Therefore, we simply rely on 1332 * the opportunistic updates to the page's dirty 1333 * field by the pmap. 1334 */ 1335 if (page_shortage <= 0) { 1336 nqueue = PQ_INACTIVE; 1337 ps_delta = 0; 1338 } else if (m->dirty == 0) { 1339 nqueue = PQ_INACTIVE; 1340 ps_delta = act_scan_laundry_weight; 1341 } else { 1342 nqueue = PQ_LAUNDRY; 1343 ps_delta = 1; 1344 } 1345 1346 new.flags &= ~PGA_QUEUE_OP_MASK; 1347 new.flags |= PGA_REQUEUE; 1348 new.queue = nqueue; 1349 } 1350 } while (!vm_page_pqstate_commit(m, &old, new)); 1351 1352 page_shortage -= ps_delta; 1353 } 1354 vm_pagequeue_lock(pq); 1355 TAILQ_REMOVE(&pq->pq_pl, &vmd->vmd_clock[0], plinks.q); 1356 TAILQ_INSERT_AFTER(&pq->pq_pl, marker, &vmd->vmd_clock[0], plinks.q); 1357 vm_pageout_end_scan(&ss); 1358 vm_pagequeue_unlock(pq); 1359 } 1360 1361 static int 1362 vm_pageout_reinsert_inactive_page(struct vm_pagequeue *pq, vm_page_t marker, 1363 vm_page_t m) 1364 { 1365 vm_page_astate_t as; 1366 1367 vm_pagequeue_assert_locked(pq); 1368 1369 as = vm_page_astate_load(m); 1370 if (as.queue != PQ_INACTIVE || (as.flags & PGA_ENQUEUED) != 0) 1371 return (0); 1372 vm_page_aflag_set(m, PGA_ENQUEUED); 1373 TAILQ_INSERT_BEFORE(marker, m, plinks.q); 1374 return (1); 1375 } 1376 1377 /* 1378 * Re-add stuck pages to the inactive queue. We will examine them again 1379 * during the next scan. If the queue state of a page has changed since 1380 * it was physically removed from the page queue in 1381 * vm_pageout_collect_batch(), don't do anything with that page. 1382 */ 1383 static void 1384 vm_pageout_reinsert_inactive(struct scan_state *ss, struct vm_batchqueue *bq, 1385 vm_page_t m) 1386 { 1387 struct vm_pagequeue *pq; 1388 vm_page_t marker; 1389 int delta; 1390 1391 delta = 0; 1392 marker = ss->marker; 1393 pq = ss->pq; 1394 1395 if (m != NULL) { 1396 if (vm_batchqueue_insert(bq, m) != 0) 1397 return; 1398 vm_pagequeue_lock(pq); 1399 delta += vm_pageout_reinsert_inactive_page(pq, marker, m); 1400 } else 1401 vm_pagequeue_lock(pq); 1402 while ((m = vm_batchqueue_pop(bq)) != NULL) 1403 delta += vm_pageout_reinsert_inactive_page(pq, marker, m); 1404 vm_pagequeue_cnt_add(pq, delta); 1405 vm_pagequeue_unlock(pq); 1406 vm_batchqueue_init(bq); 1407 } 1408 1409 static void 1410 vm_pageout_scan_inactive(struct vm_domain *vmd, int page_shortage) 1411 { 1412 struct timeval start, end; 1413 struct scan_state ss; 1414 struct vm_batchqueue rq; 1415 struct vm_page marker_page; 1416 vm_page_t m, marker; 1417 struct vm_pagequeue *pq; 1418 vm_object_t object; 1419 vm_page_astate_t old, new; 1420 int act_delta, addl_page_shortage, starting_page_shortage, refs; 1421 1422 object = NULL; 1423 vm_batchqueue_init(&rq); 1424 getmicrouptime(&start); 1425 1426 /* 1427 * The addl_page_shortage is an estimate of the number of temporarily 1428 * stuck pages in the inactive queue. In other words, the 1429 * number of pages from the inactive count that should be 1430 * discounted in setting the target for the active queue scan. 1431 */ 1432 addl_page_shortage = 0; 1433 1434 /* 1435 * Start scanning the inactive queue for pages that we can free. The 1436 * scan will stop when we reach the target or we have scanned the 1437 * entire queue. (Note that m->a.act_count is not used to make 1438 * decisions for the inactive queue, only for the active queue.) 1439 */ 1440 starting_page_shortage = page_shortage; 1441 marker = &marker_page; 1442 vm_page_init_marker(marker, PQ_INACTIVE, 0); 1443 pq = &vmd->vmd_pagequeues[PQ_INACTIVE]; 1444 vm_pagequeue_lock(pq); 1445 vm_pageout_init_scan(&ss, pq, marker, NULL, pq->pq_cnt); 1446 while (page_shortage > 0) { 1447 /* 1448 * If we need to refill the scan batch queue, release any 1449 * optimistically held object lock. This gives someone else a 1450 * chance to grab the lock, and also avoids holding it while we 1451 * do unrelated work. 1452 */ 1453 if (object != NULL && vm_batchqueue_empty(&ss.bq)) { 1454 VM_OBJECT_WUNLOCK(object); 1455 object = NULL; 1456 } 1457 1458 m = vm_pageout_next(&ss, true); 1459 if (m == NULL) 1460 break; 1461 KASSERT((m->flags & PG_MARKER) == 0, 1462 ("marker page %p was dequeued", m)); 1463 1464 /* 1465 * Don't touch a page that was removed from the queue after the 1466 * page queue lock was released. Otherwise, ensure that any 1467 * pending queue operations, such as dequeues for wired pages, 1468 * are handled. 1469 */ 1470 if (vm_pageout_defer(m, PQ_INACTIVE, false)) 1471 continue; 1472 1473 /* 1474 * Lock the page's object. 1475 */ 1476 if (object == NULL || object != m->object) { 1477 if (object != NULL) 1478 VM_OBJECT_WUNLOCK(object); 1479 object = atomic_load_ptr(&m->object); 1480 if (__predict_false(object == NULL)) 1481 /* The page is being freed by another thread. */ 1482 continue; 1483 1484 /* Depends on type-stability. */ 1485 VM_OBJECT_WLOCK(object); 1486 if (__predict_false(m->object != object)) { 1487 VM_OBJECT_WUNLOCK(object); 1488 object = NULL; 1489 goto reinsert; 1490 } 1491 } 1492 1493 if (vm_page_tryxbusy(m) == 0) { 1494 /* 1495 * Don't mess with busy pages. Leave them at 1496 * the front of the queue. Most likely, they 1497 * are being paged out and will leave the 1498 * queue shortly after the scan finishes. So, 1499 * they ought to be discounted from the 1500 * inactive count. 1501 */ 1502 addl_page_shortage++; 1503 goto reinsert; 1504 } 1505 1506 /* Deferred free of swap space. */ 1507 if ((m->a.flags & PGA_SWAP_FREE) != 0) 1508 vm_pager_page_unswapped(m); 1509 1510 /* 1511 * Check for wirings now that we hold the object lock and have 1512 * exclusively busied the page. If the page is mapped, it may 1513 * still be wired by pmap lookups. The call to 1514 * vm_page_try_remove_all() below atomically checks for such 1515 * wirings and removes mappings. If the page is unmapped, the 1516 * wire count is guaranteed not to increase after this check. 1517 */ 1518 if (__predict_false(vm_page_wired(m))) 1519 goto skip_page; 1520 1521 /* 1522 * Invalid pages can be easily freed. They cannot be 1523 * mapped, vm_page_free() asserts this. 1524 */ 1525 if (vm_page_none_valid(m)) 1526 goto free_page; 1527 1528 refs = object->ref_count != 0 ? pmap_ts_referenced(m) : 0; 1529 1530 for (old = vm_page_astate_load(m);;) { 1531 /* 1532 * Check to see if the page has been removed from the 1533 * queue since the first such check. Leave it alone if 1534 * so, discarding any references collected by 1535 * pmap_ts_referenced(). 1536 */ 1537 if (__predict_false(_vm_page_queue(old) == PQ_NONE)) 1538 goto skip_page; 1539 1540 new = old; 1541 act_delta = refs; 1542 if ((old.flags & PGA_REFERENCED) != 0) { 1543 new.flags &= ~PGA_REFERENCED; 1544 act_delta++; 1545 } 1546 if (act_delta == 0) { 1547 ; 1548 } else if (object->ref_count != 0) { 1549 /* 1550 * Increase the activation count if the 1551 * page was referenced while in the 1552 * inactive queue. This makes it less 1553 * likely that the page will be returned 1554 * prematurely to the inactive queue. 1555 */ 1556 new.act_count += ACT_ADVANCE + 1557 act_delta; 1558 if (new.act_count > ACT_MAX) 1559 new.act_count = ACT_MAX; 1560 1561 new.flags &= ~PGA_QUEUE_OP_MASK; 1562 new.flags |= PGA_REQUEUE; 1563 new.queue = PQ_ACTIVE; 1564 if (!vm_page_pqstate_commit(m, &old, new)) 1565 continue; 1566 1567 VM_CNT_INC(v_reactivated); 1568 goto skip_page; 1569 } else if ((object->flags & OBJ_DEAD) == 0) { 1570 new.queue = PQ_INACTIVE; 1571 new.flags |= PGA_REQUEUE; 1572 if (!vm_page_pqstate_commit(m, &old, new)) 1573 continue; 1574 goto skip_page; 1575 } 1576 break; 1577 } 1578 1579 /* 1580 * If the page appears to be clean at the machine-independent 1581 * layer, then remove all of its mappings from the pmap in 1582 * anticipation of freeing it. If, however, any of the page's 1583 * mappings allow write access, then the page may still be 1584 * modified until the last of those mappings are removed. 1585 */ 1586 if (object->ref_count != 0) { 1587 vm_page_test_dirty(m); 1588 if (m->dirty == 0 && !vm_page_try_remove_all(m)) 1589 goto skip_page; 1590 } 1591 1592 /* 1593 * Clean pages can be freed, but dirty pages must be sent back 1594 * to the laundry, unless they belong to a dead object. 1595 * Requeueing dirty pages from dead objects is pointless, as 1596 * they are being paged out and freed by the thread that 1597 * destroyed the object. 1598 */ 1599 if (m->dirty == 0) { 1600 free_page: 1601 /* 1602 * Now we are guaranteed that no other threads are 1603 * manipulating the page, check for a last-second 1604 * reference that would save it from doom. 1605 */ 1606 if (vm_pageout_defer(m, PQ_INACTIVE, false)) 1607 goto skip_page; 1608 1609 /* 1610 * Because we dequeued the page and have already checked 1611 * for pending dequeue and enqueue requests, we can 1612 * safely disassociate the page from the inactive queue 1613 * without holding the queue lock. 1614 */ 1615 m->a.queue = PQ_NONE; 1616 vm_page_free(m); 1617 page_shortage--; 1618 continue; 1619 } 1620 if ((object->flags & OBJ_DEAD) == 0) 1621 vm_page_launder(m); 1622 skip_page: 1623 vm_page_xunbusy(m); 1624 continue; 1625 reinsert: 1626 vm_pageout_reinsert_inactive(&ss, &rq, m); 1627 } 1628 if (object != NULL) 1629 VM_OBJECT_WUNLOCK(object); 1630 vm_pageout_reinsert_inactive(&ss, &rq, NULL); 1631 vm_pageout_reinsert_inactive(&ss, &ss.bq, NULL); 1632 vm_pagequeue_lock(pq); 1633 vm_pageout_end_scan(&ss); 1634 vm_pagequeue_unlock(pq); 1635 1636 /* 1637 * Record the remaining shortage and the progress and rate it was made. 1638 */ 1639 atomic_add_int(&vmd->vmd_addl_shortage, addl_page_shortage); 1640 getmicrouptime(&end); 1641 timevalsub(&end, &start); 1642 atomic_add_int(&vmd->vmd_inactive_us, 1643 end.tv_sec * 1000000 + end.tv_usec); 1644 atomic_add_int(&vmd->vmd_inactive_freed, 1645 starting_page_shortage - page_shortage); 1646 } 1647 1648 /* 1649 * Dispatch a number of inactive threads according to load and collect the 1650 * results to present a coherent view of paging activity on this domain. 1651 */ 1652 static int 1653 vm_pageout_inactive_dispatch(struct vm_domain *vmd, int shortage) 1654 { 1655 u_int freed, pps, slop, threads, us; 1656 1657 vmd->vmd_inactive_shortage = shortage; 1658 slop = 0; 1659 1660 /* 1661 * If we have more work than we can do in a quarter of our interval, we 1662 * fire off multiple threads to process it. 1663 */ 1664 if ((threads = vmd->vmd_inactive_threads) > 1 && 1665 vmd->vmd_helper_threads_enabled && 1666 vmd->vmd_inactive_pps != 0 && 1667 shortage > vmd->vmd_inactive_pps / VM_INACT_SCAN_RATE / 4) { 1668 vmd->vmd_inactive_shortage /= threads; 1669 slop = shortage % threads; 1670 vm_domain_pageout_lock(vmd); 1671 blockcount_acquire(&vmd->vmd_inactive_starting, threads - 1); 1672 blockcount_acquire(&vmd->vmd_inactive_running, threads - 1); 1673 wakeup(&vmd->vmd_inactive_shortage); 1674 vm_domain_pageout_unlock(vmd); 1675 } 1676 1677 /* Run the local thread scan. */ 1678 vm_pageout_scan_inactive(vmd, vmd->vmd_inactive_shortage + slop); 1679 1680 /* 1681 * Block until helper threads report results and then accumulate 1682 * totals. 1683 */ 1684 blockcount_wait(&vmd->vmd_inactive_running, NULL, "vmpoid", PVM); 1685 freed = atomic_readandclear_int(&vmd->vmd_inactive_freed); 1686 VM_CNT_ADD(v_dfree, freed); 1687 1688 /* 1689 * Calculate the per-thread paging rate with an exponential decay of 1690 * prior results. Careful to avoid integer rounding errors with large 1691 * us values. 1692 */ 1693 us = max(atomic_readandclear_int(&vmd->vmd_inactive_us), 1); 1694 if (us > 1000000) 1695 /* Keep rounding to tenths */ 1696 pps = (freed * 10) / ((us * 10) / 1000000); 1697 else 1698 pps = (1000000 / us) * freed; 1699 vmd->vmd_inactive_pps = (vmd->vmd_inactive_pps / 2) + (pps / 2); 1700 1701 return (shortage - freed); 1702 } 1703 1704 /* 1705 * Attempt to reclaim the requested number of pages from the inactive queue. 1706 * Returns true if the shortage was addressed. 1707 */ 1708 static int 1709 vm_pageout_inactive(struct vm_domain *vmd, int shortage, int *addl_shortage) 1710 { 1711 struct vm_pagequeue *pq; 1712 u_int addl_page_shortage, deficit, page_shortage; 1713 u_int starting_page_shortage; 1714 1715 /* 1716 * vmd_pageout_deficit counts the number of pages requested in 1717 * allocations that failed because of a free page shortage. We assume 1718 * that the allocations will be reattempted and thus include the deficit 1719 * in our scan target. 1720 */ 1721 deficit = atomic_readandclear_int(&vmd->vmd_pageout_deficit); 1722 starting_page_shortage = shortage + deficit; 1723 1724 /* 1725 * Run the inactive scan on as many threads as is necessary. 1726 */ 1727 page_shortage = vm_pageout_inactive_dispatch(vmd, starting_page_shortage); 1728 addl_page_shortage = atomic_readandclear_int(&vmd->vmd_addl_shortage); 1729 1730 /* 1731 * Wake up the laundry thread so that it can perform any needed 1732 * laundering. If we didn't meet our target, we're in shortfall and 1733 * need to launder more aggressively. If PQ_LAUNDRY is empty and no 1734 * swap devices are configured, the laundry thread has no work to do, so 1735 * don't bother waking it up. 1736 * 1737 * The laundry thread uses the number of inactive queue scans elapsed 1738 * since the last laundering to determine whether to launder again, so 1739 * keep count. 1740 */ 1741 if (starting_page_shortage > 0) { 1742 pq = &vmd->vmd_pagequeues[PQ_LAUNDRY]; 1743 vm_pagequeue_lock(pq); 1744 if (vmd->vmd_laundry_request == VM_LAUNDRY_IDLE && 1745 (pq->pq_cnt > 0 || atomic_load_acq_int(&swapdev_enabled))) { 1746 if (page_shortage > 0) { 1747 vmd->vmd_laundry_request = VM_LAUNDRY_SHORTFALL; 1748 VM_CNT_INC(v_pdshortfalls); 1749 } else if (vmd->vmd_laundry_request != 1750 VM_LAUNDRY_SHORTFALL) 1751 vmd->vmd_laundry_request = 1752 VM_LAUNDRY_BACKGROUND; 1753 wakeup(&vmd->vmd_laundry_request); 1754 } 1755 vmd->vmd_clean_pages_freed += 1756 starting_page_shortage - page_shortage; 1757 vm_pagequeue_unlock(pq); 1758 } 1759 1760 /* 1761 * If the inactive queue scan fails repeatedly to meet its 1762 * target, kill the largest process. 1763 */ 1764 vm_pageout_mightbe_oom(vmd, page_shortage, starting_page_shortage); 1765 1766 /* 1767 * See the description of addl_page_shortage above. 1768 */ 1769 *addl_shortage = addl_page_shortage + deficit; 1770 1771 return (page_shortage <= 0); 1772 } 1773 1774 static int vm_pageout_oom_vote; 1775 1776 /* 1777 * The pagedaemon threads randlomly select one to perform the 1778 * OOM. Trying to kill processes before all pagedaemons 1779 * failed to reach free target is premature. 1780 */ 1781 static void 1782 vm_pageout_mightbe_oom(struct vm_domain *vmd, int page_shortage, 1783 int starting_page_shortage) 1784 { 1785 int old_vote; 1786 1787 /* 1788 * Do not trigger an OOM kill if the page daemon is able to make 1789 * progress, or if there is no instantaneous shortage. The latter case 1790 * can happen if the PID controller is still reacting to an acute 1791 * shortage, and the inactive queue is full of dirty pages. 1792 */ 1793 if (starting_page_shortage <= 0 || starting_page_shortage != 1794 page_shortage || !vm_paging_needed(vmd, vmd->vmd_free_count)) 1795 vmd->vmd_oom_seq = 0; 1796 else 1797 vmd->vmd_oom_seq++; 1798 if (vmd->vmd_oom_seq < vm_pageout_oom_seq) { 1799 if (vmd->vmd_oom) { 1800 vmd->vmd_oom = false; 1801 atomic_subtract_int(&vm_pageout_oom_vote, 1); 1802 } 1803 return; 1804 } 1805 1806 /* 1807 * Do not follow the call sequence until OOM condition is 1808 * cleared. 1809 */ 1810 vmd->vmd_oom_seq = 0; 1811 1812 if (vmd->vmd_oom) 1813 return; 1814 1815 vmd->vmd_oom = true; 1816 old_vote = atomic_fetchadd_int(&vm_pageout_oom_vote, 1); 1817 if (old_vote != vm_ndomains - 1) 1818 return; 1819 1820 /* 1821 * The current pagedaemon thread is the last in the quorum to 1822 * start OOM. Initiate the selection and signaling of the 1823 * victim. 1824 */ 1825 vm_pageout_oom(VM_OOM_MEM); 1826 1827 /* 1828 * After one round of OOM terror, recall our vote. On the 1829 * next pass, current pagedaemon would vote again if the low 1830 * memory condition is still there, due to vmd_oom being 1831 * false. 1832 */ 1833 vmd->vmd_oom = false; 1834 atomic_subtract_int(&vm_pageout_oom_vote, 1); 1835 } 1836 1837 /* 1838 * The OOM killer is the page daemon's action of last resort when 1839 * memory allocation requests have been stalled for a prolonged period 1840 * of time because it cannot reclaim memory. This function computes 1841 * the approximate number of physical pages that could be reclaimed if 1842 * the specified address space is destroyed. 1843 * 1844 * Private, anonymous memory owned by the address space is the 1845 * principal resource that we expect to recover after an OOM kill. 1846 * Since the physical pages mapped by the address space's COW entries 1847 * are typically shared pages, they are unlikely to be released and so 1848 * they are not counted. 1849 * 1850 * To get to the point where the page daemon runs the OOM killer, its 1851 * efforts to write-back vnode-backed pages may have stalled. This 1852 * could be caused by a memory allocation deadlock in the write path 1853 * that might be resolved by an OOM kill. Therefore, physical pages 1854 * belonging to vnode-backed objects are counted, because they might 1855 * be freed without being written out first if the address space holds 1856 * the last reference to an unlinked vnode. 1857 * 1858 * Similarly, physical pages belonging to OBJT_PHYS objects are 1859 * counted because the address space might hold the last reference to 1860 * the object. 1861 */ 1862 static long 1863 vm_pageout_oom_pagecount(struct vmspace *vmspace) 1864 { 1865 vm_map_t map; 1866 vm_map_entry_t entry; 1867 vm_object_t obj; 1868 long res; 1869 1870 map = &vmspace->vm_map; 1871 KASSERT(!vm_map_is_system(map), ("system map")); 1872 sx_assert(&map->lock, SA_LOCKED); 1873 res = 0; 1874 VM_MAP_ENTRY_FOREACH(entry, map) { 1875 if ((entry->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) 1876 continue; 1877 obj = entry->object.vm_object; 1878 if (obj == NULL) 1879 continue; 1880 if ((entry->eflags & MAP_ENTRY_NEEDS_COPY) != 0 && 1881 obj->ref_count != 1) 1882 continue; 1883 if (obj->type == OBJT_PHYS || obj->type == OBJT_VNODE || 1884 (obj->flags & OBJ_SWAP) != 0) 1885 res += obj->resident_page_count; 1886 } 1887 return (res); 1888 } 1889 1890 static int vm_oom_ratelim_last; 1891 static int vm_oom_pf_secs = 10; 1892 SYSCTL_INT(_vm, OID_AUTO, oom_pf_secs, CTLFLAG_RWTUN, &vm_oom_pf_secs, 0, 1893 ""); 1894 static struct mtx vm_oom_ratelim_mtx; 1895 1896 void 1897 vm_pageout_oom(int shortage) 1898 { 1899 const char *reason; 1900 struct proc *p, *bigproc; 1901 vm_offset_t size, bigsize; 1902 struct thread *td; 1903 struct vmspace *vm; 1904 int now; 1905 bool breakout; 1906 1907 /* 1908 * For OOM requests originating from vm_fault(), there is a high 1909 * chance that a single large process faults simultaneously in 1910 * several threads. Also, on an active system running many 1911 * processes of middle-size, like buildworld, all of them 1912 * could fault almost simultaneously as well. 1913 * 1914 * To avoid killing too many processes, rate-limit OOMs 1915 * initiated by vm_fault() time-outs on the waits for free 1916 * pages. 1917 */ 1918 mtx_lock(&vm_oom_ratelim_mtx); 1919 now = ticks; 1920 if (shortage == VM_OOM_MEM_PF && 1921 (u_int)(now - vm_oom_ratelim_last) < hz * vm_oom_pf_secs) { 1922 mtx_unlock(&vm_oom_ratelim_mtx); 1923 return; 1924 } 1925 vm_oom_ratelim_last = now; 1926 mtx_unlock(&vm_oom_ratelim_mtx); 1927 1928 /* 1929 * We keep the process bigproc locked once we find it to keep anyone 1930 * from messing with it; however, there is a possibility of 1931 * deadlock if process B is bigproc and one of its child processes 1932 * attempts to propagate a signal to B while we are waiting for A's 1933 * lock while walking this list. To avoid this, we don't block on 1934 * the process lock but just skip a process if it is already locked. 1935 */ 1936 bigproc = NULL; 1937 bigsize = 0; 1938 sx_slock(&allproc_lock); 1939 FOREACH_PROC_IN_SYSTEM(p) { 1940 PROC_LOCK(p); 1941 1942 /* 1943 * If this is a system, protected or killed process, skip it. 1944 */ 1945 if (p->p_state != PRS_NORMAL || (p->p_flag & (P_INEXEC | 1946 P_PROTECTED | P_SYSTEM | P_WEXIT)) != 0 || 1947 p->p_pid == 1 || P_KILLED(p) || 1948 (p->p_pid < 48 && swap_pager_avail != 0)) { 1949 PROC_UNLOCK(p); 1950 continue; 1951 } 1952 /* 1953 * If the process is in a non-running type state, 1954 * don't touch it. Check all the threads individually. 1955 */ 1956 breakout = false; 1957 FOREACH_THREAD_IN_PROC(p, td) { 1958 thread_lock(td); 1959 if (!TD_ON_RUNQ(td) && 1960 !TD_IS_RUNNING(td) && 1961 !TD_IS_SLEEPING(td) && 1962 !TD_IS_SUSPENDED(td)) { 1963 thread_unlock(td); 1964 breakout = true; 1965 break; 1966 } 1967 thread_unlock(td); 1968 } 1969 if (breakout) { 1970 PROC_UNLOCK(p); 1971 continue; 1972 } 1973 /* 1974 * get the process size 1975 */ 1976 vm = vmspace_acquire_ref(p); 1977 if (vm == NULL) { 1978 PROC_UNLOCK(p); 1979 continue; 1980 } 1981 _PHOLD(p); 1982 PROC_UNLOCK(p); 1983 sx_sunlock(&allproc_lock); 1984 if (!vm_map_trylock_read(&vm->vm_map)) { 1985 vmspace_free(vm); 1986 sx_slock(&allproc_lock); 1987 PRELE(p); 1988 continue; 1989 } 1990 size = vmspace_swap_count(vm); 1991 if (shortage == VM_OOM_MEM || shortage == VM_OOM_MEM_PF) 1992 size += vm_pageout_oom_pagecount(vm); 1993 vm_map_unlock_read(&vm->vm_map); 1994 vmspace_free(vm); 1995 sx_slock(&allproc_lock); 1996 1997 /* 1998 * If this process is bigger than the biggest one, 1999 * remember it. 2000 */ 2001 if (size > bigsize) { 2002 if (bigproc != NULL) 2003 PRELE(bigproc); 2004 bigproc = p; 2005 bigsize = size; 2006 } else { 2007 PRELE(p); 2008 } 2009 } 2010 sx_sunlock(&allproc_lock); 2011 2012 if (bigproc != NULL) { 2013 switch (shortage) { 2014 case VM_OOM_MEM: 2015 reason = "failed to reclaim memory"; 2016 break; 2017 case VM_OOM_MEM_PF: 2018 reason = "a thread waited too long to allocate a page"; 2019 break; 2020 case VM_OOM_SWAPZ: 2021 reason = "out of swap space"; 2022 break; 2023 default: 2024 panic("unknown OOM reason %d", shortage); 2025 } 2026 if (vm_panic_on_oom != 0 && --vm_panic_on_oom == 0) 2027 panic("%s", reason); 2028 PROC_LOCK(bigproc); 2029 killproc(bigproc, reason); 2030 sched_nice(bigproc, PRIO_MIN); 2031 _PRELE(bigproc); 2032 PROC_UNLOCK(bigproc); 2033 } 2034 } 2035 2036 /* 2037 * Signal a free page shortage to subsystems that have registered an event 2038 * handler. Reclaim memory from UMA in the event of a severe shortage. 2039 * Return true if the free page count should be re-evaluated. 2040 */ 2041 static bool 2042 vm_pageout_lowmem(void) 2043 { 2044 static int lowmem_ticks = 0; 2045 int last; 2046 bool ret; 2047 2048 ret = false; 2049 2050 last = atomic_load_int(&lowmem_ticks); 2051 while ((u_int)(ticks - last) / hz >= lowmem_period) { 2052 if (atomic_fcmpset_int(&lowmem_ticks, &last, ticks) == 0) 2053 continue; 2054 2055 /* 2056 * Decrease registered cache sizes. 2057 */ 2058 SDT_PROBE0(vm, , , vm__lowmem_scan); 2059 EVENTHANDLER_INVOKE(vm_lowmem, VM_LOW_PAGES); 2060 2061 /* 2062 * We do this explicitly after the caches have been 2063 * drained above. 2064 */ 2065 uma_reclaim(UMA_RECLAIM_TRIM); 2066 ret = true; 2067 break; 2068 } 2069 2070 /* 2071 * Kick off an asynchronous reclaim of cached memory if one of the 2072 * page daemons is failing to keep up with demand. Use the "severe" 2073 * threshold instead of "min" to ensure that we do not blow away the 2074 * caches if a subset of the NUMA domains are depleted by kernel memory 2075 * allocations; the domainset iterators automatically skip domains 2076 * below the "min" threshold on the first pass. 2077 * 2078 * UMA reclaim worker has its own rate-limiting mechanism, so don't 2079 * worry about kicking it too often. 2080 */ 2081 if (vm_page_count_severe()) 2082 uma_reclaim_wakeup(); 2083 2084 return (ret); 2085 } 2086 2087 static void 2088 vm_pageout_worker(void *arg) 2089 { 2090 struct vm_domain *vmd; 2091 u_int ofree; 2092 int addl_shortage, domain, shortage; 2093 bool target_met; 2094 2095 domain = (uintptr_t)arg; 2096 vmd = VM_DOMAIN(domain); 2097 shortage = 0; 2098 target_met = true; 2099 2100 /* 2101 * XXXKIB It could be useful to bind pageout daemon threads to 2102 * the cores belonging to the domain, from which vm_page_array 2103 * is allocated. 2104 */ 2105 2106 KASSERT(vmd->vmd_segs != 0, ("domain without segments")); 2107 vmd->vmd_last_active_scan = ticks; 2108 2109 /* 2110 * The pageout daemon worker is never done, so loop forever. 2111 */ 2112 while (TRUE) { 2113 vm_domain_pageout_lock(vmd); 2114 2115 /* 2116 * We need to clear wanted before we check the limits. This 2117 * prevents races with wakers who will check wanted after they 2118 * reach the limit. 2119 */ 2120 atomic_store_int(&vmd->vmd_pageout_wanted, 0); 2121 2122 /* 2123 * Might the page daemon need to run again? 2124 */ 2125 if (vm_paging_needed(vmd, vmd->vmd_free_count)) { 2126 /* 2127 * Yes. If the scan failed to produce enough free 2128 * pages, sleep uninterruptibly for some time in the 2129 * hope that the laundry thread will clean some pages. 2130 */ 2131 vm_domain_pageout_unlock(vmd); 2132 if (!target_met) 2133 pause("pwait", hz / VM_INACT_SCAN_RATE); 2134 } else { 2135 /* 2136 * No, sleep until the next wakeup or until pages 2137 * need to have their reference stats updated. 2138 */ 2139 if (mtx_sleep(&vmd->vmd_pageout_wanted, 2140 vm_domain_pageout_lockptr(vmd), PDROP | PVM, 2141 "psleep", hz / VM_INACT_SCAN_RATE) == 0) 2142 VM_CNT_INC(v_pdwakeups); 2143 } 2144 2145 /* Prevent spurious wakeups by ensuring that wanted is set. */ 2146 atomic_store_int(&vmd->vmd_pageout_wanted, 1); 2147 2148 /* 2149 * Use the controller to calculate how many pages to free in 2150 * this interval, and scan the inactive queue. If the lowmem 2151 * handlers appear to have freed up some pages, subtract the 2152 * difference from the inactive queue scan target. 2153 */ 2154 shortage = pidctrl_daemon(&vmd->vmd_pid, vmd->vmd_free_count); 2155 if (shortage > 0) { 2156 ofree = vmd->vmd_free_count; 2157 if (vm_pageout_lowmem() && vmd->vmd_free_count > ofree) 2158 shortage -= min(vmd->vmd_free_count - ofree, 2159 (u_int)shortage); 2160 target_met = vm_pageout_inactive(vmd, shortage, 2161 &addl_shortage); 2162 } else 2163 addl_shortage = 0; 2164 2165 /* 2166 * Scan the active queue. A positive value for shortage 2167 * indicates that we must aggressively deactivate pages to avoid 2168 * a shortfall. 2169 */ 2170 shortage = vm_pageout_active_target(vmd) + addl_shortage; 2171 vm_pageout_scan_active(vmd, shortage); 2172 } 2173 } 2174 2175 /* 2176 * vm_pageout_helper runs additional pageout daemons in times of high paging 2177 * activity. 2178 */ 2179 static void 2180 vm_pageout_helper(void *arg) 2181 { 2182 struct vm_domain *vmd; 2183 int domain; 2184 2185 domain = (uintptr_t)arg; 2186 vmd = VM_DOMAIN(domain); 2187 2188 vm_domain_pageout_lock(vmd); 2189 for (;;) { 2190 msleep(&vmd->vmd_inactive_shortage, 2191 vm_domain_pageout_lockptr(vmd), PVM, "psleep", 0); 2192 blockcount_release(&vmd->vmd_inactive_starting, 1); 2193 2194 vm_domain_pageout_unlock(vmd); 2195 vm_pageout_scan_inactive(vmd, vmd->vmd_inactive_shortage); 2196 vm_domain_pageout_lock(vmd); 2197 2198 /* 2199 * Release the running count while the pageout lock is held to 2200 * prevent wakeup races. 2201 */ 2202 blockcount_release(&vmd->vmd_inactive_running, 1); 2203 } 2204 } 2205 2206 static int 2207 get_pageout_threads_per_domain(const struct vm_domain *vmd) 2208 { 2209 unsigned total_pageout_threads, eligible_cpus, domain_cpus; 2210 2211 if (VM_DOMAIN_EMPTY(vmd->vmd_domain)) 2212 return (0); 2213 2214 /* 2215 * Semi-arbitrarily constrain pagedaemon threads to less than half the 2216 * total number of CPUs in the system as an upper limit. 2217 */ 2218 if (pageout_cpus_per_thread < 2) 2219 pageout_cpus_per_thread = 2; 2220 else if (pageout_cpus_per_thread > mp_ncpus) 2221 pageout_cpus_per_thread = mp_ncpus; 2222 2223 total_pageout_threads = howmany(mp_ncpus, pageout_cpus_per_thread); 2224 domain_cpus = CPU_COUNT(&cpuset_domain[vmd->vmd_domain]); 2225 2226 /* Pagedaemons are not run in empty domains. */ 2227 eligible_cpus = mp_ncpus; 2228 for (unsigned i = 0; i < vm_ndomains; i++) 2229 if (VM_DOMAIN_EMPTY(i)) 2230 eligible_cpus -= CPU_COUNT(&cpuset_domain[i]); 2231 2232 /* 2233 * Assign a portion of the total pageout threads to this domain 2234 * corresponding to the fraction of pagedaemon-eligible CPUs in the 2235 * domain. In asymmetric NUMA systems, domains with more CPUs may be 2236 * allocated more threads than domains with fewer CPUs. 2237 */ 2238 return (howmany(total_pageout_threads * domain_cpus, eligible_cpus)); 2239 } 2240 2241 /* 2242 * Initialize basic pageout daemon settings. See the comment above the 2243 * definition of vm_domain for some explanation of how these thresholds are 2244 * used. 2245 */ 2246 static void 2247 vm_pageout_init_domain(int domain) 2248 { 2249 struct vm_domain *vmd; 2250 struct sysctl_oid *oid; 2251 2252 vmd = VM_DOMAIN(domain); 2253 vmd->vmd_interrupt_free_min = 2; 2254 2255 /* 2256 * v_free_reserved needs to include enough for the largest 2257 * swap pager structures plus enough for any pv_entry structs 2258 * when paging. 2259 */ 2260 vmd->vmd_pageout_free_min = 2 * MAXBSIZE / PAGE_SIZE + 2261 vmd->vmd_interrupt_free_min; 2262 vmd->vmd_free_reserved = vm_pageout_page_count + 2263 vmd->vmd_pageout_free_min + vmd->vmd_page_count / 768; 2264 vmd->vmd_free_min = vmd->vmd_page_count / 200; 2265 vmd->vmd_free_severe = vmd->vmd_free_min / 2; 2266 vmd->vmd_free_target = 4 * vmd->vmd_free_min + vmd->vmd_free_reserved; 2267 vmd->vmd_free_min += vmd->vmd_free_reserved; 2268 vmd->vmd_free_severe += vmd->vmd_free_reserved; 2269 vmd->vmd_inactive_target = (3 * vmd->vmd_free_target) / 2; 2270 if (vmd->vmd_inactive_target > vmd->vmd_free_count / 3) 2271 vmd->vmd_inactive_target = vmd->vmd_free_count / 3; 2272 2273 /* 2274 * Set the default wakeup threshold to be 10% below the paging 2275 * target. This keeps the steady state out of shortfall. 2276 */ 2277 vmd->vmd_pageout_wakeup_thresh = (vmd->vmd_free_target / 10) * 9; 2278 2279 /* 2280 * Target amount of memory to move out of the laundry queue during a 2281 * background laundering. This is proportional to the amount of system 2282 * memory. 2283 */ 2284 vmd->vmd_background_launder_target = (vmd->vmd_free_target - 2285 vmd->vmd_free_min) / 10; 2286 2287 /* Initialize the pageout daemon pid controller. */ 2288 pidctrl_init(&vmd->vmd_pid, hz / VM_INACT_SCAN_RATE, 2289 vmd->vmd_free_target, PIDCTRL_BOUND, 2290 PIDCTRL_KPD, PIDCTRL_KID, PIDCTRL_KDD); 2291 oid = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO, 2292 "pidctrl", CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, ""); 2293 pidctrl_init_sysctl(&vmd->vmd_pid, SYSCTL_CHILDREN(oid)); 2294 2295 vmd->vmd_inactive_threads = get_pageout_threads_per_domain(vmd); 2296 SYSCTL_ADD_BOOL(NULL, SYSCTL_CHILDREN(vmd->vmd_oid), OID_AUTO, 2297 "pageout_helper_threads_enabled", CTLFLAG_RWTUN, 2298 &vmd->vmd_helper_threads_enabled, 0, 2299 "Enable multi-threaded inactive queue scanning"); 2300 } 2301 2302 static void 2303 vm_pageout_init(void) 2304 { 2305 u_long freecount; 2306 int i; 2307 2308 /* 2309 * Initialize some paging parameters. 2310 */ 2311 freecount = 0; 2312 for (i = 0; i < vm_ndomains; i++) { 2313 struct vm_domain *vmd; 2314 2315 vm_pageout_init_domain(i); 2316 vmd = VM_DOMAIN(i); 2317 vm_cnt.v_free_reserved += vmd->vmd_free_reserved; 2318 vm_cnt.v_free_target += vmd->vmd_free_target; 2319 vm_cnt.v_free_min += vmd->vmd_free_min; 2320 vm_cnt.v_inactive_target += vmd->vmd_inactive_target; 2321 vm_cnt.v_pageout_free_min += vmd->vmd_pageout_free_min; 2322 vm_cnt.v_interrupt_free_min += vmd->vmd_interrupt_free_min; 2323 vm_cnt.v_free_severe += vmd->vmd_free_severe; 2324 freecount += vmd->vmd_free_count; 2325 } 2326 2327 /* 2328 * Set interval in seconds for active scan. We want to visit each 2329 * page at least once every ten minutes. This is to prevent worst 2330 * case paging behaviors with stale active LRU. 2331 */ 2332 if (vm_pageout_update_period == 0) 2333 vm_pageout_update_period = 600; 2334 2335 /* 2336 * Set the maximum number of user-wired virtual pages. Historically the 2337 * main source of such pages was mlock(2) and mlockall(2). Hypervisors 2338 * may also request user-wired memory. 2339 */ 2340 if (vm_page_max_user_wired == 0) 2341 vm_page_max_user_wired = 4 * freecount / 5; 2342 } 2343 2344 /* 2345 * vm_pageout is the high level pageout daemon. 2346 */ 2347 static void 2348 vm_pageout(void) 2349 { 2350 struct proc *p; 2351 struct thread *td; 2352 int error, first, i, j, pageout_threads; 2353 2354 p = curproc; 2355 td = curthread; 2356 2357 mtx_init(&vm_oom_ratelim_mtx, "vmoomr", NULL, MTX_DEF); 2358 swap_pager_swap_init(); 2359 for (first = -1, i = 0; i < vm_ndomains; i++) { 2360 if (VM_DOMAIN_EMPTY(i)) { 2361 if (bootverbose) 2362 printf("domain %d empty; skipping pageout\n", 2363 i); 2364 continue; 2365 } 2366 if (first == -1) 2367 first = i; 2368 else { 2369 error = kthread_add(vm_pageout_worker, 2370 (void *)(uintptr_t)i, p, NULL, 0, 0, "dom%d", i); 2371 if (error != 0) 2372 panic("starting pageout for domain %d: %d\n", 2373 i, error); 2374 } 2375 pageout_threads = VM_DOMAIN(i)->vmd_inactive_threads; 2376 for (j = 0; j < pageout_threads - 1; j++) { 2377 error = kthread_add(vm_pageout_helper, 2378 (void *)(uintptr_t)i, p, NULL, 0, 0, 2379 "dom%d helper%d", i, j); 2380 if (error != 0) 2381 panic("starting pageout helper %d for domain " 2382 "%d: %d\n", j, i, error); 2383 } 2384 error = kthread_add(vm_pageout_laundry_worker, 2385 (void *)(uintptr_t)i, p, NULL, 0, 0, "laundry: dom%d", i); 2386 if (error != 0) 2387 panic("starting laundry for domain %d: %d", i, error); 2388 } 2389 error = kthread_add(uma_reclaim_worker, NULL, p, NULL, 0, 0, "uma"); 2390 if (error != 0) 2391 panic("starting uma_reclaim helper, error %d\n", error); 2392 2393 snprintf(td->td_name, sizeof(td->td_name), "dom%d", first); 2394 vm_pageout_worker((void *)(uintptr_t)first); 2395 } 2396 2397 /* 2398 * Perform an advisory wakeup of the page daemon. 2399 */ 2400 void 2401 pagedaemon_wakeup(int domain) 2402 { 2403 struct vm_domain *vmd; 2404 2405 vmd = VM_DOMAIN(domain); 2406 vm_domain_pageout_assert_unlocked(vmd); 2407 if (curproc == pageproc) 2408 return; 2409 2410 if (atomic_fetchadd_int(&vmd->vmd_pageout_wanted, 1) == 0) { 2411 vm_domain_pageout_lock(vmd); 2412 atomic_store_int(&vmd->vmd_pageout_wanted, 1); 2413 wakeup(&vmd->vmd_pageout_wanted); 2414 vm_domain_pageout_unlock(vmd); 2415 } 2416 } 2417