1 /*- 2 * SPDX-License-Identifier: BSD-4-Clause 3 * 4 * Copyright (c) 1998 Matthew Dillon, 5 * Copyright (c) 1994 John S. Dyson 6 * Copyright (c) 1990 University of Utah. 7 * Copyright (c) 1982, 1986, 1989, 1993 8 * The Regents of the University of California. All rights reserved. 9 * 10 * This code is derived from software contributed to Berkeley by 11 * the Systems Programming Group of the University of Utah Computer 12 * Science Department. 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 * New Swap System 43 * Matthew Dillon 44 * 45 * Radix Bitmap 'blists'. 46 * 47 * - The new swapper uses the new radix bitmap code. This should scale 48 * to arbitrarily small or arbitrarily large swap spaces and an almost 49 * arbitrary degree of fragmentation. 50 * 51 * Features: 52 * 53 * - on the fly reallocation of swap during putpages. The new system 54 * does not try to keep previously allocated swap blocks for dirty 55 * pages. 56 * 57 * - on the fly deallocation of swap 58 * 59 * - No more garbage collection required. Unnecessarily allocated swap 60 * blocks only exist for dirty vm_page_t's now and these are already 61 * cycled (in a high-load system) by the pager. We also do on-the-fly 62 * removal of invalidated swap blocks when a page is destroyed 63 * or renamed. 64 * 65 * from: Utah $Hdr: swap_pager.c 1.4 91/04/30$ 66 */ 67 68 #include "opt_vm.h" 69 70 #define EXTERR_CATEGORY EXTERR_CAT_SWAP 71 #include <sys/param.h> 72 #include <sys/bio.h> 73 #include <sys/blist.h> 74 #include <sys/buf.h> 75 #include <sys/conf.h> 76 #include <sys/disk.h> 77 #include <sys/disklabel.h> 78 #include <sys/eventhandler.h> 79 #include <sys/exterrvar.h> 80 #include <sys/fcntl.h> 81 #include <sys/limits.h> 82 #include <sys/lock.h> 83 #include <sys/kernel.h> 84 #include <sys/mount.h> 85 #include <sys/namei.h> 86 #include <sys/malloc.h> 87 #include <sys/pctrie.h> 88 #include <sys/priv.h> 89 #include <sys/proc.h> 90 #include <sys/racct.h> 91 #include <sys/resource.h> 92 #include <sys/resourcevar.h> 93 #include <sys/rwlock.h> 94 #include <sys/sbuf.h> 95 #include <sys/sysctl.h> 96 #include <sys/sysproto.h> 97 #include <sys/systm.h> 98 #include <sys/sx.h> 99 #include <sys/unistd.h> 100 #include <sys/user.h> 101 #include <sys/vmmeter.h> 102 #include <sys/vnode.h> 103 104 #include <security/mac/mac_framework.h> 105 106 #include <vm/vm.h> 107 #include <vm/pmap.h> 108 #include <vm/vm_map.h> 109 #include <vm/vm_kern.h> 110 #include <vm/vm_object.h> 111 #include <vm/vm_page.h> 112 #include <vm/vm_pager.h> 113 #include <vm/vm_pageout.h> 114 #include <vm/vm_param.h> 115 #include <vm/vm_radix.h> 116 #include <vm/swap_pager.h> 117 #include <vm/vm_extern.h> 118 #include <vm/uma.h> 119 120 #include <geom/geom.h> 121 122 /* 123 * MAX_PAGEOUT_CLUSTER must be a power of 2 between 1 and 64. 124 * The 64-page limit is due to the radix code (kern/subr_blist.c). 125 */ 126 #ifndef MAX_PAGEOUT_CLUSTER 127 #define MAX_PAGEOUT_CLUSTER 32 128 #endif 129 130 #if !defined(SWB_NPAGES) 131 #define SWB_NPAGES MAX_PAGEOUT_CLUSTER 132 #endif 133 134 #define SWAP_META_PAGES PCTRIE_COUNT 135 136 /* 137 * A swblk structure maps each page index within a 138 * SWAP_META_PAGES-aligned and sized range to the address of an 139 * on-disk swap block (or SWAPBLK_NONE). The collection of these 140 * mappings for an entire vm object is implemented as a pc-trie. 141 */ 142 struct swblk { 143 vm_pindex_t p; 144 daddr_t d[SWAP_META_PAGES]; 145 }; 146 147 /* 148 * A page_range structure records the start address and length of a sequence of 149 * mapped page addresses. 150 */ 151 struct page_range { 152 daddr_t start; 153 daddr_t num; 154 }; 155 156 static MALLOC_DEFINE(M_VMPGDATA, "vm_pgdata", "swap pager private data"); 157 static struct mtx sw_dev_mtx; 158 static TAILQ_HEAD(, swdevt) swtailq = TAILQ_HEAD_INITIALIZER(swtailq); 159 static struct swdevt *swdevhd; /* Allocate from here next */ 160 static int nswapdev; /* Number of swap devices */ 161 int swap_pager_avail; 162 static struct sx swdev_syscall_lock; /* serialize swap(on|off) */ 163 164 static __exclusive_cache_line u_long swap_reserved; 165 static u_long swap_total; 166 static int sysctl_page_shift(SYSCTL_HANDLER_ARGS); 167 168 static SYSCTL_NODE(_vm_stats, OID_AUTO, swap, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 169 "VM swap stats"); 170 171 SYSCTL_PROC(_vm, OID_AUTO, swap_reserved, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, 172 &swap_reserved, 0, sysctl_page_shift, "QU", 173 "Amount of swap storage needed to back all allocated anonymous memory."); 174 SYSCTL_PROC(_vm, OID_AUTO, swap_total, CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, 175 &swap_total, 0, sysctl_page_shift, "QU", 176 "Total amount of available swap storage."); 177 178 int vm_overcommit __read_mostly = 0; 179 SYSCTL_INT(_vm, VM_OVERCOMMIT, overcommit, CTLFLAG_RW, &vm_overcommit, 0, 180 "Configure virtual memory overcommit behavior. See tuning(7) " 181 "for details."); 182 static unsigned long swzone; 183 SYSCTL_ULONG(_vm, OID_AUTO, swzone, CTLFLAG_RD, &swzone, 0, 184 "Actual size of swap metadata zone"); 185 static unsigned long swap_maxpages; 186 SYSCTL_ULONG(_vm, OID_AUTO, swap_maxpages, CTLFLAG_RD, &swap_maxpages, 0, 187 "Maximum amount of swap supported"); 188 189 static COUNTER_U64_DEFINE_EARLY(swap_free_deferred); 190 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_deferred, 191 CTLFLAG_RD, &swap_free_deferred, 192 "Number of pages that deferred freeing swap space"); 193 194 static COUNTER_U64_DEFINE_EARLY(swap_free_completed); 195 SYSCTL_COUNTER_U64(_vm_stats_swap, OID_AUTO, free_completed, 196 CTLFLAG_RD, &swap_free_completed, 197 "Number of deferred frees completed"); 198 199 static int 200 sysctl_page_shift(SYSCTL_HANDLER_ARGS) 201 { 202 uint64_t newval; 203 u_long value = *(u_long *)arg1; 204 205 newval = ((uint64_t)value) << PAGE_SHIFT; 206 return (sysctl_handle_64(oidp, &newval, 0, req)); 207 } 208 209 static bool 210 swap_reserve_by_cred_rlimit(u_long pincr, struct ucred *cred, int oc) 211 { 212 struct uidinfo *uip; 213 u_long prev; 214 215 uip = cred->cr_ruidinfo; 216 217 prev = atomic_fetchadd_long(&uip->ui_vmsize, pincr); 218 if ((oc & SWAP_RESERVE_RLIMIT_ON) != 0 && 219 prev + pincr > lim_cur(curthread, RLIMIT_SWAP) && 220 priv_check(curthread, PRIV_VM_SWAP_NORLIMIT) != 0) { 221 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pincr); 222 KASSERT(prev >= pincr, 223 ("negative vmsize for uid %d\n", uip->ui_uid)); 224 return (false); 225 } 226 return (true); 227 } 228 229 static void 230 swap_release_by_cred_rlimit(u_long pdecr, struct ucred *cred) 231 { 232 struct uidinfo *uip; 233 #ifdef INVARIANTS 234 u_long prev; 235 #endif 236 237 uip = cred->cr_ruidinfo; 238 239 #ifdef INVARIANTS 240 prev = atomic_fetchadd_long(&uip->ui_vmsize, -pdecr); 241 KASSERT(prev >= pdecr, 242 ("negative vmsize for uid %d\n", uip->ui_uid)); 243 #else 244 atomic_subtract_long(&uip->ui_vmsize, pdecr); 245 #endif 246 } 247 248 static void 249 swap_reserve_force_rlimit(u_long pincr, struct ucred *cred) 250 { 251 struct uidinfo *uip; 252 253 uip = cred->cr_ruidinfo; 254 atomic_add_long(&uip->ui_vmsize, pincr); 255 } 256 257 bool 258 swap_reserve(vm_ooffset_t incr) 259 { 260 261 return (swap_reserve_by_cred(incr, curthread->td_ucred)); 262 } 263 264 bool 265 swap_reserve_by_cred(vm_ooffset_t incr, struct ucred *cred) 266 { 267 u_long r, s, prev, pincr; 268 #ifdef RACCT 269 int error; 270 #endif 271 int oc; 272 static int curfail; 273 static struct timeval lastfail; 274 275 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", 276 __func__, (uintmax_t)incr)); 277 278 #ifdef RACCT 279 if (RACCT_ENABLED()) { 280 PROC_LOCK(curproc); 281 error = racct_add(curproc, RACCT_SWAP, incr); 282 PROC_UNLOCK(curproc); 283 if (error != 0) 284 return (false); 285 } 286 #endif 287 288 pincr = atop(incr); 289 prev = atomic_fetchadd_long(&swap_reserved, pincr); 290 r = prev + pincr; 291 s = swap_total; 292 oc = atomic_load_int(&vm_overcommit); 293 if (r > s && (oc & SWAP_RESERVE_ALLOW_NONWIRED) != 0) { 294 s += vm_cnt.v_page_count - vm_cnt.v_free_reserved - 295 vm_wire_count(); 296 } 297 if ((oc & SWAP_RESERVE_FORCE_ON) != 0 && r > s && 298 priv_check(curthread, PRIV_VM_SWAP_NOQUOTA) != 0) { 299 prev = atomic_fetchadd_long(&swap_reserved, -pincr); 300 KASSERT(prev >= pincr, 301 ("swap_reserved < incr on overcommit fail")); 302 goto out_error; 303 } 304 305 if (!swap_reserve_by_cred_rlimit(pincr, cred, oc)) { 306 prev = atomic_fetchadd_long(&swap_reserved, -pincr); 307 KASSERT(prev >= pincr, 308 ("swap_reserved < incr on overcommit fail")); 309 goto out_error; 310 } 311 312 return (true); 313 314 out_error: 315 if (ppsratecheck(&lastfail, &curfail, 1)) { 316 printf("uid %d, pid %d: swap reservation " 317 "for %jd bytes failed\n", 318 cred->cr_ruidinfo->ui_uid, curproc->p_pid, incr); 319 } 320 #ifdef RACCT 321 if (RACCT_ENABLED()) { 322 PROC_LOCK(curproc); 323 racct_sub(curproc, RACCT_SWAP, incr); 324 PROC_UNLOCK(curproc); 325 } 326 #endif 327 328 return (false); 329 } 330 331 void 332 swap_reserve_force(vm_ooffset_t incr) 333 { 334 u_long pincr; 335 336 KASSERT((incr & PAGE_MASK) == 0, ("%s: incr: %ju & PAGE_MASK", 337 __func__, (uintmax_t)incr)); 338 339 #ifdef RACCT 340 if (RACCT_ENABLED()) { 341 PROC_LOCK(curproc); 342 racct_add_force(curproc, RACCT_SWAP, incr); 343 PROC_UNLOCK(curproc); 344 } 345 #endif 346 pincr = atop(incr); 347 atomic_add_long(&swap_reserved, pincr); 348 swap_reserve_force_rlimit(pincr, curthread->td_ucred); 349 } 350 351 void 352 swap_release(vm_ooffset_t decr) 353 { 354 struct ucred *cred; 355 356 PROC_LOCK(curproc); 357 cred = curproc->p_ucred; 358 swap_release_by_cred(decr, cred); 359 PROC_UNLOCK(curproc); 360 } 361 362 void 363 swap_release_by_cred(vm_ooffset_t decr, struct ucred *cred) 364 { 365 u_long pdecr; 366 #ifdef INVARIANTS 367 u_long prev; 368 #endif 369 370 KASSERT((decr & PAGE_MASK) == 0, ("%s: decr: %ju & PAGE_MASK", 371 __func__, (uintmax_t)decr)); 372 373 pdecr = atop(decr); 374 #ifdef INVARIANTS 375 prev = atomic_fetchadd_long(&swap_reserved, -pdecr); 376 KASSERT(prev >= pdecr, ("swap_reserved < decr")); 377 #else 378 atomic_subtract_long(&swap_reserved, pdecr); 379 #endif 380 381 swap_release_by_cred_rlimit(pdecr, cred); 382 #ifdef RACCT 383 if (racct_enable) 384 racct_sub_cred(cred, RACCT_SWAP, decr); 385 #endif 386 } 387 388 static bool swap_pager_full = true; /* swap space exhaustion (task killing) */ 389 bool swap_pager_almost_full = true; /* swap space exhaustion (w/hysteresis) */ 390 static struct mtx swbuf_mtx; /* to sync nsw_wcount_async */ 391 static int nsw_wcount_async; /* limit async write buffers */ 392 static int nsw_wcount_async_max;/* assigned maximum */ 393 int nsw_cluster_max; /* maximum VOP I/O allowed */ 394 395 static int sysctl_swap_async_max(SYSCTL_HANDLER_ARGS); 396 SYSCTL_PROC(_vm, OID_AUTO, swap_async_max, CTLTYPE_INT | CTLFLAG_RW | 397 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_async_max, "I", 398 "Maximum running async swap ops"); 399 static int sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS); 400 SYSCTL_PROC(_vm, OID_AUTO, swap_fragmentation, CTLTYPE_STRING | CTLFLAG_RD | 401 CTLFLAG_MPSAFE, NULL, 0, sysctl_swap_fragmentation, "A", 402 "Swap Fragmentation Info"); 403 404 static struct sx sw_alloc_sx; 405 406 /* 407 * "named" and "unnamed" anon region objects. Try to reduce the overhead 408 * of searching a named list by hashing it just a little. 409 */ 410 411 #define NOBJLISTS 8 412 413 #define NOBJLIST(handle) \ 414 (&swap_pager_object_list[((int)(intptr_t)handle >> 4) & (NOBJLISTS-1)]) 415 416 static struct pagerlst swap_pager_object_list[NOBJLISTS]; 417 static uma_zone_t swwbuf_zone; 418 static uma_zone_t swrbuf_zone; 419 static uma_zone_t swblk_zone; 420 static uma_zone_t swpctrie_zone; 421 422 /* 423 * pagerops for OBJT_SWAP - "swap pager". Some ops are also global procedure 424 * calls hooked from other parts of the VM system and do not appear here. 425 * (see vm/swap_pager.h). 426 */ 427 static vm_object_t 428 swap_pager_alloc(void *handle, vm_ooffset_t size, 429 vm_prot_t prot, vm_ooffset_t offset, struct ucred *); 430 static void swap_pager_dealloc(vm_object_t object); 431 static int swap_pager_getpages(vm_object_t, vm_page_t *, int, int *, 432 int *); 433 static int swap_pager_getpages_async(vm_object_t, vm_page_t *, int, int *, 434 int *, pgo_getpages_iodone_t, void *); 435 static void swap_pager_putpages(vm_object_t, vm_page_t *, int, int, int *); 436 static boolean_t 437 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, int *after); 438 static void swap_pager_init(void); 439 static void swap_pager_unswapped(vm_page_t); 440 static void swap_pager_swapoff(struct swdevt *sp); 441 static void swap_pager_update_writecount(vm_object_t object, 442 vm_offset_t start, vm_offset_t end); 443 static void swap_pager_release_writecount(vm_object_t object, 444 vm_offset_t start, vm_offset_t end); 445 static void swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, 446 vm_size_t size); 447 448 const struct pagerops swappagerops = { 449 .pgo_kvme_type = KVME_TYPE_SWAP, 450 .pgo_init = swap_pager_init, /* early system initialization of pager */ 451 .pgo_alloc = swap_pager_alloc, /* allocate an OBJT_SWAP object */ 452 .pgo_dealloc = swap_pager_dealloc, /* deallocate an OBJT_SWAP object */ 453 .pgo_getpages = swap_pager_getpages, /* pagein */ 454 .pgo_getpages_async = swap_pager_getpages_async, /* pagein (async) */ 455 .pgo_putpages = swap_pager_putpages, /* pageout */ 456 .pgo_haspage = swap_pager_haspage, /* get backing store status for page */ 457 .pgo_pageunswapped = swap_pager_unswapped, /* remove swap related to page */ 458 .pgo_update_writecount = swap_pager_update_writecount, 459 .pgo_release_writecount = swap_pager_release_writecount, 460 .pgo_freespace = swap_pager_freespace_pgo, 461 }; 462 463 /* 464 * swap_*() routines are externally accessible. swp_*() routines are 465 * internal. 466 */ 467 static int nswap_lowat = 128; /* in pages, swap_pager_almost_full warn */ 468 static int nswap_hiwat = 512; /* in pages, swap_pager_almost_full warn */ 469 470 SYSCTL_INT(_vm, OID_AUTO, dmmax, CTLFLAG_RD, &nsw_cluster_max, 0, 471 "Maximum size of a swap block in pages"); 472 473 static void swp_sizecheck(void); 474 static void swp_pager_async_iodone(struct buf *bp); 475 static bool swp_pager_swblk_empty(struct swblk *sb, int start, int limit); 476 static void swp_pager_free_empty_swblk(vm_object_t, struct swblk *sb); 477 static int swapongeom(struct vnode *); 478 static int swaponvp(struct thread *, struct vnode *, u_long); 479 static int swapoff_one(struct swdevt *sp, struct ucred *cred, 480 u_int flags); 481 482 /* 483 * Swap bitmap functions 484 */ 485 static void swp_pager_freeswapspace(const struct page_range *range); 486 static daddr_t swp_pager_getswapspace(int *npages); 487 488 /* 489 * Metadata functions 490 */ 491 static daddr_t swp_pager_meta_build(struct pctrie_iter *, vm_object_t object, 492 vm_pindex_t, daddr_t, bool); 493 static void swp_pager_meta_free(vm_object_t, vm_pindex_t, vm_pindex_t, 494 vm_size_t *); 495 static void swp_pager_meta_transfer(vm_object_t src, vm_object_t dst, 496 vm_pindex_t pindex, vm_pindex_t count); 497 static void swp_pager_meta_free_all(vm_object_t); 498 static daddr_t swp_pager_meta_lookup(struct pctrie_iter *, vm_pindex_t); 499 500 static void 501 swp_pager_init_freerange(struct page_range *range) 502 { 503 range->start = SWAPBLK_NONE; 504 range->num = 0; 505 } 506 507 static void 508 swp_pager_update_freerange(struct page_range *range, daddr_t addr) 509 { 510 if (range->start + range->num == addr) { 511 range->num++; 512 } else { 513 swp_pager_freeswapspace(range); 514 range->start = addr; 515 range->num = 1; 516 } 517 } 518 519 static void * 520 swblk_trie_alloc(struct pctrie *ptree) 521 { 522 523 return (uma_zalloc(swpctrie_zone, M_NOWAIT | (curproc == pageproc ? 524 M_USE_RESERVE : 0))); 525 } 526 527 static void 528 swblk_trie_free(struct pctrie *ptree, void *node) 529 { 530 531 uma_zfree(swpctrie_zone, node); 532 } 533 534 static int 535 swblk_start(struct swblk *sb, vm_pindex_t pindex) 536 { 537 return (sb == NULL || sb->p >= pindex ? 538 0 : pindex % SWAP_META_PAGES); 539 } 540 541 PCTRIE_DEFINE(SWAP, swblk, p, swblk_trie_alloc, swblk_trie_free); 542 543 static struct swblk * 544 swblk_lookup(vm_object_t object, vm_pindex_t pindex) 545 { 546 return (SWAP_PCTRIE_LOOKUP(&object->un_pager.swp.swp_blks, 547 rounddown(pindex, SWAP_META_PAGES))); 548 } 549 550 static void 551 swblk_lookup_remove(vm_object_t object, struct swblk *sb) 552 { 553 SWAP_PCTRIE_REMOVE(&object->un_pager.swp.swp_blks, sb->p); 554 } 555 556 static bool 557 swblk_is_empty(vm_object_t object) 558 { 559 return (pctrie_is_empty(&object->un_pager.swp.swp_blks)); 560 } 561 562 static struct swblk * 563 swblk_iter_lookup_ge(struct pctrie_iter *blks, vm_pindex_t pindex) 564 { 565 return (SWAP_PCTRIE_ITER_LOOKUP_GE(blks, 566 rounddown(pindex, SWAP_META_PAGES))); 567 } 568 569 static void 570 swblk_iter_init_only(struct pctrie_iter *blks, vm_object_t object) 571 { 572 VM_OBJECT_ASSERT_LOCKED(object); 573 MPASS((object->flags & OBJ_SWAP) != 0); 574 pctrie_iter_init(blks, &object->un_pager.swp.swp_blks); 575 } 576 577 578 static struct swblk * 579 swblk_iter_init(struct pctrie_iter *blks, vm_object_t object, 580 vm_pindex_t pindex) 581 { 582 swblk_iter_init_only(blks, object); 583 return (swblk_iter_lookup_ge(blks, pindex)); 584 } 585 586 static struct swblk * 587 swblk_iter_reinit(struct pctrie_iter *blks, vm_object_t object, 588 vm_pindex_t pindex) 589 { 590 swblk_iter_init_only(blks, object); 591 return (SWAP_PCTRIE_ITER_LOOKUP(blks, 592 rounddown(pindex, SWAP_META_PAGES))); 593 } 594 595 static struct swblk * 596 swblk_iter_limit_init(struct pctrie_iter *blks, vm_object_t object, 597 vm_pindex_t pindex, vm_pindex_t limit) 598 { 599 VM_OBJECT_ASSERT_LOCKED(object); 600 MPASS((object->flags & OBJ_SWAP) != 0); 601 pctrie_iter_limit_init(blks, &object->un_pager.swp.swp_blks, limit); 602 return (swblk_iter_lookup_ge(blks, pindex)); 603 } 604 605 static struct swblk * 606 swblk_iter_next(struct pctrie_iter *blks) 607 { 608 return (SWAP_PCTRIE_ITER_JUMP_GE(blks, SWAP_META_PAGES)); 609 } 610 611 static struct swblk * 612 swblk_iter_lookup(struct pctrie_iter *blks, vm_pindex_t pindex) 613 { 614 return (SWAP_PCTRIE_ITER_LOOKUP(blks, 615 rounddown(pindex, SWAP_META_PAGES))); 616 } 617 618 static int 619 swblk_iter_insert(struct pctrie_iter *blks, struct swblk *sb) 620 { 621 return (SWAP_PCTRIE_ITER_INSERT(blks, sb)); 622 } 623 624 static void 625 swblk_iter_remove(struct pctrie_iter *blks) 626 { 627 SWAP_PCTRIE_ITER_REMOVE(blks); 628 } 629 630 /* 631 * SWP_SIZECHECK() - update swap_pager_full indication 632 * 633 * update the swap_pager_almost_full indication and warn when we are 634 * about to run out of swap space, using lowat/hiwat hysteresis. 635 * 636 * Clear swap_pager_full ( task killing ) indication when lowat is met. 637 * 638 * No restrictions on call 639 * This routine may not block. 640 */ 641 static void 642 swp_sizecheck(void) 643 { 644 645 if (swap_pager_avail < nswap_lowat) { 646 if (!swap_pager_almost_full) { 647 printf("swap_pager: out of swap space\n"); 648 swap_pager_almost_full = true; 649 } 650 } else { 651 swap_pager_full = false; 652 if (swap_pager_avail > nswap_hiwat) 653 swap_pager_almost_full = false; 654 } 655 } 656 657 /* 658 * SWAP_PAGER_INIT() - initialize the swap pager! 659 * 660 * Expected to be started from system init. NOTE: This code is run 661 * before much else so be careful what you depend on. Most of the VM 662 * system has yet to be initialized at this point. 663 */ 664 static void 665 swap_pager_init(void) 666 { 667 /* 668 * Initialize object lists 669 */ 670 int i; 671 672 for (i = 0; i < NOBJLISTS; ++i) 673 TAILQ_INIT(&swap_pager_object_list[i]); 674 mtx_init(&sw_dev_mtx, "swapdev", NULL, MTX_DEF); 675 sx_init(&sw_alloc_sx, "swspsx"); 676 sx_init(&swdev_syscall_lock, "swsysc"); 677 678 /* 679 * The nsw_cluster_max is constrained by the bp->b_pages[] 680 * array, which has maxphys / PAGE_SIZE entries, and our locally 681 * defined MAX_PAGEOUT_CLUSTER. Also be aware that swap ops are 682 * constrained by the swap device interleave stripe size. 683 * 684 * Initialized early so that GEOM_ELI can see it. 685 */ 686 nsw_cluster_max = min(maxphys / PAGE_SIZE, MAX_PAGEOUT_CLUSTER); 687 } 688 689 /* 690 * SWAP_PAGER_SWAP_INIT() - swap pager initialization from pageout process 691 * 692 * Expected to be started from pageout process once, prior to entering 693 * its main loop. 694 */ 695 void 696 swap_pager_swap_init(void) 697 { 698 unsigned long n, n2; 699 700 /* 701 * Number of in-transit swap bp operations. Don't 702 * exhaust the pbufs completely. Make sure we 703 * initialize workable values (0 will work for hysteresis 704 * but it isn't very efficient). 705 * 706 * Currently we hardwire nsw_wcount_async to 4. This limit is 707 * designed to prevent other I/O from having high latencies due to 708 * our pageout I/O. The value 4 works well for one or two active swap 709 * devices but is probably a little low if you have more. Even so, 710 * a higher value would probably generate only a limited improvement 711 * with three or four active swap devices since the system does not 712 * typically have to pageout at extreme bandwidths. We will want 713 * at least 2 per swap devices, and 4 is a pretty good value if you 714 * have one NFS swap device due to the command/ack latency over NFS. 715 * So it all works out pretty well. 716 * 717 * nsw_cluster_max is initialized in swap_pager_init(). 718 */ 719 720 nsw_wcount_async = 4; 721 nsw_wcount_async_max = nsw_wcount_async; 722 mtx_init(&swbuf_mtx, "async swbuf mutex", NULL, MTX_DEF); 723 724 swwbuf_zone = pbuf_zsecond_create("swwbuf", nswbuf / 4); 725 swrbuf_zone = pbuf_zsecond_create("swrbuf", nswbuf / 2); 726 727 /* 728 * Initialize our zone, taking the user's requested size or 729 * estimating the number we need based on the number of pages 730 * in the system. 731 */ 732 n = maxswzone != 0 ? maxswzone / sizeof(struct swblk) : 733 vm_cnt.v_page_count / 2; 734 swpctrie_zone = uma_zcreate("swpctrie", pctrie_node_size(), NULL, NULL, 735 pctrie_zone_init, NULL, UMA_ALIGN_PTR, 0); 736 swblk_zone = uma_zcreate("swblk", sizeof(struct swblk), NULL, NULL, 737 NULL, NULL, _Alignof(struct swblk) - 1, 0); 738 n2 = n; 739 do { 740 if (uma_zone_reserve_kva(swblk_zone, n)) 741 break; 742 /* 743 * if the allocation failed, try a zone two thirds the 744 * size of the previous attempt. 745 */ 746 n -= ((n + 2) / 3); 747 } while (n > 0); 748 749 /* 750 * Often uma_zone_reserve_kva() cannot reserve exactly the 751 * requested size. Account for the difference when 752 * calculating swap_maxpages. 753 */ 754 n = uma_zone_get_max(swblk_zone); 755 756 if (n < n2) 757 printf("Swap blk zone entries changed from %lu to %lu.\n", 758 n2, n); 759 /* absolute maximum we can handle assuming 100% efficiency */ 760 swap_maxpages = n * SWAP_META_PAGES; 761 swzone = n * sizeof(struct swblk); 762 if (!uma_zone_reserve_kva(swpctrie_zone, n)) 763 printf("Cannot reserve swap pctrie zone, " 764 "reduce kern.maxswzone.\n"); 765 } 766 767 bool 768 swap_pager_init_object(vm_object_t object, void *handle, struct ucred *cred, 769 vm_ooffset_t size, vm_ooffset_t offset) 770 { 771 if (cred != NULL) { 772 if (!swap_reserve_by_cred(size, cred)) 773 return (false); 774 crhold(cred); 775 } 776 777 object->un_pager.swp.writemappings = 0; 778 object->handle = handle; 779 if (cred != NULL) { 780 object->cred = cred; 781 object->charge = size; 782 } 783 return (true); 784 } 785 786 static vm_object_t 787 swap_pager_alloc_init(objtype_t otype, void *handle, struct ucred *cred, 788 vm_ooffset_t size, vm_ooffset_t offset) 789 { 790 vm_object_t object; 791 792 /* 793 * The un_pager.swp.swp_blks trie is initialized by 794 * vm_object_allocate() to ensure the correct order of 795 * visibility to other threads. 796 */ 797 object = vm_object_allocate(otype, OFF_TO_IDX(offset + 798 PAGE_MASK + size)); 799 800 if (!swap_pager_init_object(object, handle, cred, size, offset)) { 801 vm_object_deallocate(object); 802 return (NULL); 803 } 804 return (object); 805 } 806 807 /* 808 * SWAP_PAGER_ALLOC() - allocate a new OBJT_SWAP VM object and instantiate 809 * its metadata structures. 810 * 811 * This routine is called from the mmap and fork code to create a new 812 * OBJT_SWAP object. 813 * 814 * This routine must ensure that no live duplicate is created for 815 * the named object request, which is protected against by 816 * holding the sw_alloc_sx lock in case handle != NULL. 817 */ 818 static vm_object_t 819 swap_pager_alloc(void *handle, vm_ooffset_t size, vm_prot_t prot, 820 vm_ooffset_t offset, struct ucred *cred) 821 { 822 vm_object_t object; 823 824 if (handle != NULL) { 825 /* 826 * Reference existing named region or allocate new one. There 827 * should not be a race here against swp_pager_meta_build() 828 * as called from vm_page_remove() in regards to the lookup 829 * of the handle. 830 */ 831 sx_xlock(&sw_alloc_sx); 832 object = vm_pager_object_lookup(NOBJLIST(handle), handle); 833 if (object == NULL) { 834 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred, 835 size, offset); 836 if (object != NULL) { 837 TAILQ_INSERT_TAIL(NOBJLIST(object->handle), 838 object, pager_object_list); 839 } 840 } 841 sx_xunlock(&sw_alloc_sx); 842 } else { 843 object = swap_pager_alloc_init(OBJT_SWAP, handle, cred, 844 size, offset); 845 } 846 return (object); 847 } 848 849 /* 850 * SWAP_PAGER_DEALLOC() - remove swap metadata from object 851 * 852 * The swap backing for the object is destroyed. The code is 853 * designed such that we can reinstantiate it later, but this 854 * routine is typically called only when the entire object is 855 * about to be destroyed. 856 * 857 * The object must be locked. 858 */ 859 static void 860 swap_pager_dealloc(vm_object_t object) 861 { 862 863 VM_OBJECT_ASSERT_WLOCKED(object); 864 KASSERT((object->flags & OBJ_DEAD) != 0, ("dealloc of reachable obj")); 865 866 /* 867 * Remove from list right away so lookups will fail if we block for 868 * pageout completion. 869 */ 870 if ((object->flags & OBJ_ANON) == 0 && object->handle != NULL) { 871 VM_OBJECT_WUNLOCK(object); 872 sx_xlock(&sw_alloc_sx); 873 TAILQ_REMOVE(NOBJLIST(object->handle), object, 874 pager_object_list); 875 sx_xunlock(&sw_alloc_sx); 876 VM_OBJECT_WLOCK(object); 877 } 878 879 vm_object_pip_wait(object, "swpdea"); 880 881 /* 882 * Free all remaining metadata. We only bother to free it from 883 * the swap meta data. We do not attempt to free swapblk's still 884 * associated with vm_page_t's for this object. We do not care 885 * if paging is still in progress on some objects. 886 */ 887 swp_pager_meta_free_all(object); 888 object->handle = NULL; 889 object->type = OBJT_DEAD; 890 891 /* 892 * Release the allocation charge. 893 */ 894 if (object->cred != NULL) { 895 swap_release_by_cred(object->charge, object->cred); 896 object->charge = 0; 897 crfree(object->cred); 898 object->cred = NULL; 899 } 900 901 /* 902 * Hide the object from swap_pager_swapoff(). 903 */ 904 vm_object_clear_flag(object, OBJ_SWAP); 905 } 906 907 /************************************************************************ 908 * SWAP PAGER BITMAP ROUTINES * 909 ************************************************************************/ 910 911 /* 912 * SWP_PAGER_GETSWAPSPACE() - allocate raw swap space 913 * 914 * Allocate swap for up to the requested number of pages. The 915 * starting swap block number (a page index) is returned or 916 * SWAPBLK_NONE if the allocation failed. 917 * 918 * Also has the side effect of advising that somebody made a mistake 919 * when they configured swap and didn't configure enough. 920 * 921 * This routine may not sleep. 922 * 923 * We allocate in round-robin fashion from the configured devices. 924 */ 925 static daddr_t 926 swp_pager_getswapspace(int *io_npages) 927 { 928 daddr_t blk; 929 struct swdevt *sp; 930 int mpages, npages; 931 932 KASSERT(*io_npages >= 1, 933 ("%s: npages not positive", __func__)); 934 blk = SWAPBLK_NONE; 935 mpages = *io_npages; 936 npages = imin(BLIST_MAX_ALLOC, mpages); 937 mtx_lock(&sw_dev_mtx); 938 sp = swdevhd; 939 while (!TAILQ_EMPTY(&swtailq)) { 940 if (sp == NULL) 941 sp = TAILQ_FIRST(&swtailq); 942 if ((sp->sw_flags & SW_CLOSING) == 0) 943 blk = blist_alloc(sp->sw_blist, &npages, mpages); 944 if (blk != SWAPBLK_NONE) 945 break; 946 sp = TAILQ_NEXT(sp, sw_list); 947 if (swdevhd == sp) { 948 if (npages == 1) 949 break; 950 mpages = npages - 1; 951 npages >>= 1; 952 } 953 } 954 if (blk != SWAPBLK_NONE) { 955 *io_npages = npages; 956 blk += sp->sw_first; 957 sp->sw_used += npages; 958 swap_pager_avail -= npages; 959 swp_sizecheck(); 960 swdevhd = TAILQ_NEXT(sp, sw_list); 961 } else { 962 if (!swap_pager_full) { 963 printf("swp_pager_getswapspace(%d): failed\n", 964 *io_npages); 965 swap_pager_full = swap_pager_almost_full = true; 966 } 967 swdevhd = NULL; 968 } 969 mtx_unlock(&sw_dev_mtx); 970 return (blk); 971 } 972 973 static bool 974 swp_pager_isondev(daddr_t blk, struct swdevt *sp) 975 { 976 977 return (blk >= sp->sw_first && blk < sp->sw_end); 978 } 979 980 static void 981 swp_pager_strategy(struct buf *bp) 982 { 983 struct swdevt *sp; 984 985 mtx_lock(&sw_dev_mtx); 986 TAILQ_FOREACH(sp, &swtailq, sw_list) { 987 if (swp_pager_isondev(bp->b_blkno, sp)) { 988 mtx_unlock(&sw_dev_mtx); 989 if ((sp->sw_flags & SW_UNMAPPED) != 0 && 990 unmapped_buf_allowed) { 991 bp->b_data = unmapped_buf; 992 bp->b_offset = 0; 993 } else { 994 pmap_qenter((vm_offset_t)bp->b_data, 995 &bp->b_pages[0], bp->b_bcount / PAGE_SIZE); 996 } 997 sp->sw_strategy(bp, sp); 998 return; 999 } 1000 } 1001 panic("Swapdev not found"); 1002 } 1003 1004 /* 1005 * SWP_PAGER_FREESWAPSPACE() - free raw swap space 1006 * 1007 * This routine returns the specified swap blocks back to the bitmap. 1008 * 1009 * This routine may not sleep. 1010 */ 1011 static void 1012 swp_pager_freeswapspace(const struct page_range *range) 1013 { 1014 daddr_t blk, npages; 1015 struct swdevt *sp; 1016 1017 blk = range->start; 1018 npages = range->num; 1019 if (npages == 0) 1020 return; 1021 mtx_lock(&sw_dev_mtx); 1022 TAILQ_FOREACH(sp, &swtailq, sw_list) { 1023 if (swp_pager_isondev(blk, sp)) { 1024 sp->sw_used -= npages; 1025 /* 1026 * If we are attempting to stop swapping on 1027 * this device, we don't want to mark any 1028 * blocks free lest they be reused. 1029 */ 1030 if ((sp->sw_flags & SW_CLOSING) == 0) { 1031 blist_free(sp->sw_blist, blk - sp->sw_first, 1032 npages); 1033 swap_pager_avail += npages; 1034 swp_sizecheck(); 1035 } 1036 mtx_unlock(&sw_dev_mtx); 1037 return; 1038 } 1039 } 1040 panic("Swapdev not found"); 1041 } 1042 1043 /* 1044 * SYSCTL_SWAP_FRAGMENTATION() - produce raw swap space stats 1045 */ 1046 static int 1047 sysctl_swap_fragmentation(SYSCTL_HANDLER_ARGS) 1048 { 1049 struct sbuf sbuf; 1050 struct swdevt *sp; 1051 const char *devname; 1052 int error; 1053 1054 error = sysctl_wire_old_buffer(req, 0); 1055 if (error != 0) 1056 return (error); 1057 sbuf_new_for_sysctl(&sbuf, NULL, 128, req); 1058 mtx_lock(&sw_dev_mtx); 1059 TAILQ_FOREACH(sp, &swtailq, sw_list) { 1060 if (vn_isdisk(sp->sw_vp)) 1061 devname = devtoname(sp->sw_vp->v_rdev); 1062 else 1063 devname = "[file]"; 1064 sbuf_printf(&sbuf, "\nFree space on device %s:\n", devname); 1065 blist_stats(sp->sw_blist, &sbuf); 1066 } 1067 mtx_unlock(&sw_dev_mtx); 1068 error = sbuf_finish(&sbuf); 1069 sbuf_delete(&sbuf); 1070 return (error); 1071 } 1072 1073 /* 1074 * SWAP_PAGER_FREESPACE() - frees swap blocks associated with a page 1075 * range within an object. 1076 * 1077 * This routine removes swapblk assignments from swap metadata. 1078 * 1079 * The external callers of this routine typically have already destroyed 1080 * or renamed vm_page_t's associated with this range in the object so 1081 * we should be ok. 1082 * 1083 * The object must be locked. 1084 */ 1085 void 1086 swap_pager_freespace(vm_object_t object, vm_pindex_t start, vm_size_t size, 1087 vm_size_t *freed) 1088 { 1089 MPASS((object->flags & OBJ_SWAP) != 0); 1090 1091 swp_pager_meta_free(object, start, size, freed); 1092 } 1093 1094 static void 1095 swap_pager_freespace_pgo(vm_object_t object, vm_pindex_t start, vm_size_t size) 1096 { 1097 MPASS((object->flags & OBJ_SWAP) != 0); 1098 1099 swp_pager_meta_free(object, start, size, NULL); 1100 } 1101 1102 /* 1103 * SWAP_PAGER_RESERVE() - reserve swap blocks in object 1104 * 1105 * Assigns swap blocks to the specified range within the object. The 1106 * swap blocks are not zeroed. Any previous swap assignment is destroyed. 1107 * 1108 * Returns 0 on success, -1 on failure. 1109 */ 1110 int 1111 swap_pager_reserve(vm_object_t object, vm_pindex_t start, vm_pindex_t size) 1112 { 1113 struct pctrie_iter blks; 1114 struct page_range range; 1115 daddr_t addr, blk; 1116 vm_pindex_t i, j; 1117 int n; 1118 1119 swp_pager_init_freerange(&range); 1120 VM_OBJECT_WLOCK(object); 1121 swblk_iter_init_only(&blks, object); 1122 for (i = 0; i < size; i += n) { 1123 n = MIN(size - i, INT_MAX); 1124 blk = swp_pager_getswapspace(&n); 1125 if (blk == SWAPBLK_NONE) { 1126 swp_pager_meta_free(object, start, i, NULL); 1127 VM_OBJECT_WUNLOCK(object); 1128 return (-1); 1129 } 1130 for (j = 0; j < n; ++j) { 1131 addr = swp_pager_meta_build(&blks, object, 1132 start + i + j, blk + j, false); 1133 if (addr != SWAPBLK_NONE) 1134 swp_pager_update_freerange(&range, addr); 1135 } 1136 } 1137 swp_pager_freeswapspace(&range); 1138 VM_OBJECT_WUNLOCK(object); 1139 return (0); 1140 } 1141 1142 /* 1143 * SWAP_PAGER_COPY() - copy blocks from source pager to destination pager 1144 * and destroy the source. 1145 * 1146 * Copy any valid swapblks from the source to the destination. In 1147 * cases where both the source and destination have a valid swapblk, 1148 * we keep the destination's. 1149 * 1150 * This routine is allowed to sleep. It may sleep allocating metadata 1151 * indirectly through swp_pager_meta_build(). 1152 * 1153 * The source object contains no vm_page_t's (which is just as well) 1154 * 1155 * The source and destination objects must be locked. 1156 * Both object locks may temporarily be released. 1157 */ 1158 void 1159 swap_pager_copy(vm_object_t srcobject, vm_object_t dstobject, 1160 vm_pindex_t offset, int destroysource) 1161 { 1162 VM_OBJECT_ASSERT_WLOCKED(srcobject); 1163 VM_OBJECT_ASSERT_WLOCKED(dstobject); 1164 1165 /* 1166 * If destroysource is set, we remove the source object from the 1167 * swap_pager internal queue now. 1168 */ 1169 if (destroysource && (srcobject->flags & OBJ_ANON) == 0 && 1170 srcobject->handle != NULL) { 1171 VM_OBJECT_WUNLOCK(srcobject); 1172 VM_OBJECT_WUNLOCK(dstobject); 1173 sx_xlock(&sw_alloc_sx); 1174 TAILQ_REMOVE(NOBJLIST(srcobject->handle), srcobject, 1175 pager_object_list); 1176 sx_xunlock(&sw_alloc_sx); 1177 VM_OBJECT_WLOCK(dstobject); 1178 VM_OBJECT_WLOCK(srcobject); 1179 } 1180 1181 /* 1182 * Transfer source to destination. 1183 */ 1184 swp_pager_meta_transfer(srcobject, dstobject, offset, dstobject->size); 1185 1186 /* 1187 * Free left over swap blocks in source. 1188 */ 1189 if (destroysource) 1190 swp_pager_meta_free_all(srcobject); 1191 } 1192 1193 /* 1194 * SWP_PAGER_HASPAGE_ITER() - determine if we have good backing store for 1195 * the requested page, accessed with the given 1196 * iterator. 1197 * 1198 * We determine whether good backing store exists for the requested 1199 * page and return TRUE if it does, FALSE if it doesn't. 1200 * 1201 * If TRUE, we also try to determine how much valid, contiguous backing 1202 * store exists before and after the requested page. 1203 */ 1204 static boolean_t 1205 swp_pager_haspage_iter(vm_pindex_t pindex, int *before, int *after, 1206 struct pctrie_iter *blks) 1207 { 1208 daddr_t blk, blk0; 1209 int i; 1210 1211 /* 1212 * do we have good backing store at the requested index ? 1213 */ 1214 blk0 = swp_pager_meta_lookup(blks, pindex); 1215 if (blk0 == SWAPBLK_NONE) { 1216 if (before) 1217 *before = 0; 1218 if (after) 1219 *after = 0; 1220 return (FALSE); 1221 } 1222 1223 /* 1224 * find backwards-looking contiguous good backing store 1225 */ 1226 if (before != NULL) { 1227 for (i = 1; i < SWB_NPAGES; i++) { 1228 if (i > pindex) 1229 break; 1230 blk = swp_pager_meta_lookup(blks, pindex - i); 1231 if (blk != blk0 - i) 1232 break; 1233 } 1234 *before = i - 1; 1235 } 1236 1237 /* 1238 * find forward-looking contiguous good backing store 1239 */ 1240 if (after != NULL) { 1241 for (i = 1; i < SWB_NPAGES; i++) { 1242 blk = swp_pager_meta_lookup(blks, pindex + i); 1243 if (blk != blk0 + i) 1244 break; 1245 } 1246 *after = i - 1; 1247 } 1248 return (TRUE); 1249 } 1250 1251 /* 1252 * SWAP_PAGER_HASPAGE() - determine if we have good backing store for 1253 * the requested page, in the given object. 1254 * 1255 * We determine whether good backing store exists for the requested 1256 * page and return TRUE if it does, FALSE if it doesn't. 1257 * 1258 * If TRUE, we also try to determine how much valid, contiguous backing 1259 * store exists before and after the requested page. 1260 */ 1261 static boolean_t 1262 swap_pager_haspage(vm_object_t object, vm_pindex_t pindex, int *before, 1263 int *after) 1264 { 1265 struct pctrie_iter blks; 1266 1267 swblk_iter_init_only(&blks, object); 1268 return (swp_pager_haspage_iter(pindex, before, after, &blks)); 1269 } 1270 1271 static void 1272 swap_pager_unswapped_acct(vm_page_t m) 1273 { 1274 KASSERT((m->object->flags & OBJ_SWAP) != 0, 1275 ("Free object not swappable")); 1276 if ((m->a.flags & PGA_SWAP_FREE) != 0) 1277 counter_u64_add(swap_free_completed, 1); 1278 vm_page_aflag_clear(m, PGA_SWAP_FREE | PGA_SWAP_SPACE); 1279 1280 /* 1281 * The meta data only exists if the object is OBJT_SWAP 1282 * and even then might not be allocated yet. 1283 */ 1284 } 1285 1286 /* 1287 * SWAP_PAGER_PAGE_UNSWAPPED() - remove swap backing store related to page 1288 * 1289 * This removes any associated swap backing store, whether valid or 1290 * not, from the page. 1291 * 1292 * This routine is typically called when a page is made dirty, at 1293 * which point any associated swap can be freed. MADV_FREE also 1294 * calls us in a special-case situation 1295 * 1296 * NOTE!!! If the page is clean and the swap was valid, the caller 1297 * should make the page dirty before calling this routine. This routine 1298 * does NOT change the m->dirty status of the page. Also: MADV_FREE 1299 * depends on it. 1300 * 1301 * This routine may not sleep. 1302 * 1303 * The object containing the page may be locked. 1304 */ 1305 static void 1306 swap_pager_unswapped(vm_page_t m) 1307 { 1308 struct page_range range; 1309 struct swblk *sb; 1310 vm_object_t obj; 1311 1312 /* 1313 * Handle enqueing deferred frees first. If we do not have the 1314 * object lock we wait for the page daemon to clear the space. 1315 */ 1316 obj = m->object; 1317 if (!VM_OBJECT_WOWNED(obj)) { 1318 VM_PAGE_OBJECT_BUSY_ASSERT(m); 1319 /* 1320 * The caller is responsible for synchronization but we 1321 * will harmlessly handle races. This is typically provided 1322 * by only calling unswapped() when a page transitions from 1323 * clean to dirty. 1324 */ 1325 if ((m->a.flags & (PGA_SWAP_SPACE | PGA_SWAP_FREE)) == 1326 PGA_SWAP_SPACE) { 1327 vm_page_aflag_set(m, PGA_SWAP_FREE); 1328 counter_u64_add(swap_free_deferred, 1); 1329 } 1330 return; 1331 } 1332 swap_pager_unswapped_acct(m); 1333 1334 sb = swblk_lookup(m->object, m->pindex); 1335 if (sb == NULL) 1336 return; 1337 range.start = sb->d[m->pindex % SWAP_META_PAGES]; 1338 if (range.start == SWAPBLK_NONE) 1339 return; 1340 range.num = 1; 1341 swp_pager_freeswapspace(&range); 1342 sb->d[m->pindex % SWAP_META_PAGES] = SWAPBLK_NONE; 1343 swp_pager_free_empty_swblk(m->object, sb); 1344 } 1345 1346 /* 1347 * swap_pager_getpages_locked() - bring pages in from swap 1348 * 1349 * Attempt to page in the pages in array "ma" of length "count". The 1350 * caller may optionally specify that additional pages preceding and 1351 * succeeding the specified range be paged in. The number of such pages 1352 * is returned in the "a_rbehind" and "a_rahead" parameters, and they will 1353 * be in the inactive queue upon return. 1354 * 1355 * The pages in "ma" must be busied and will remain busied upon return. 1356 */ 1357 static int 1358 swap_pager_getpages_locked(struct pctrie_iter *blks, vm_object_t object, 1359 vm_page_t *ma, int count, int *a_rbehind, int *a_rahead, struct buf *bp) 1360 { 1361 vm_pindex_t pindex; 1362 int rahead, rbehind; 1363 1364 VM_OBJECT_ASSERT_WLOCKED(object); 1365 1366 KASSERT((object->flags & OBJ_SWAP) != 0, 1367 ("%s: object not swappable", __func__)); 1368 pindex = ma[0]->pindex; 1369 if (!swp_pager_haspage_iter(pindex, &rbehind, &rahead, blks)) { 1370 VM_OBJECT_WUNLOCK(object); 1371 uma_zfree(swrbuf_zone, bp); 1372 return (VM_PAGER_FAIL); 1373 } 1374 1375 KASSERT(count - 1 <= rahead, 1376 ("page count %d extends beyond swap block", count)); 1377 1378 /* 1379 * Do not transfer any pages other than those that are xbusied 1380 * when running during a split or collapse operation. This 1381 * prevents clustering from re-creating pages which are being 1382 * moved into another object. 1383 */ 1384 if ((object->flags & (OBJ_SPLIT | OBJ_DEAD)) != 0) { 1385 rahead = count - 1; 1386 rbehind = 0; 1387 } 1388 /* Clip readbehind/ahead ranges to exclude already resident pages. */ 1389 rbehind = a_rbehind != NULL ? imin(*a_rbehind, rbehind) : 0; 1390 rahead = a_rahead != NULL ? imin(*a_rahead, rahead - count + 1) : 0; 1391 /* Allocate pages. */ 1392 vm_object_prepare_buf_pages(object, bp->b_pages, count, &rbehind, 1393 &rahead, ma); 1394 bp->b_npages = rbehind + count + rahead; 1395 for (int i = 0; i < bp->b_npages; i++) 1396 bp->b_pages[i]->oflags |= VPO_SWAPINPROG; 1397 bp->b_blkno = swp_pager_meta_lookup(blks, pindex - rbehind); 1398 KASSERT(bp->b_blkno != SWAPBLK_NONE, 1399 ("no swap blocking containing %p(%jx)", object, (uintmax_t)pindex)); 1400 1401 vm_object_pip_add(object, bp->b_npages); 1402 VM_OBJECT_WUNLOCK(object); 1403 MPASS((bp->b_flags & B_MAXPHYS) != 0); 1404 1405 /* Report back actual behind/ahead read. */ 1406 if (a_rbehind != NULL) 1407 *a_rbehind = rbehind; 1408 if (a_rahead != NULL) 1409 *a_rahead = rahead; 1410 1411 bp->b_flags |= B_PAGING; 1412 bp->b_iocmd = BIO_READ; 1413 bp->b_iodone = swp_pager_async_iodone; 1414 bp->b_rcred = crhold(thread0.td_ucred); 1415 bp->b_wcred = crhold(thread0.td_ucred); 1416 bp->b_bufsize = bp->b_bcount = ptoa(bp->b_npages); 1417 bp->b_pgbefore = rbehind; 1418 bp->b_pgafter = rahead; 1419 1420 VM_CNT_INC(v_swapin); 1421 VM_CNT_ADD(v_swappgsin, bp->b_npages); 1422 1423 /* 1424 * perform the I/O. NOTE!!! bp cannot be considered valid after 1425 * this point because we automatically release it on completion. 1426 * Instead, we look at the one page we are interested in which we 1427 * still hold a lock on even through the I/O completion. 1428 * 1429 * The other pages in our ma[] array are also released on completion, 1430 * so we cannot assume they are valid anymore either. 1431 * 1432 * NOTE: b_blkno is destroyed by the call to swapdev_strategy 1433 */ 1434 BUF_KERNPROC(bp); 1435 swp_pager_strategy(bp); 1436 1437 /* 1438 * Wait for the pages we want to complete. VPO_SWAPINPROG is always 1439 * cleared on completion. If an I/O error occurs, SWAPBLK_NONE 1440 * is set in the metadata for each page in the request. 1441 */ 1442 VM_OBJECT_WLOCK(object); 1443 /* This could be implemented more efficiently with aflags */ 1444 while ((ma[0]->oflags & VPO_SWAPINPROG) != 0) { 1445 ma[0]->oflags |= VPO_SWAPSLEEP; 1446 VM_CNT_INC(v_intrans); 1447 if (VM_OBJECT_SLEEP(object, &object->handle, PSWP, 1448 "swread", hz * 20)) { 1449 printf( 1450 "swap_pager: indefinite wait buffer: bufobj: %p, blkno: %jd, size: %ld\n", 1451 bp->b_bufobj, (intmax_t)bp->b_blkno, bp->b_bcount); 1452 } 1453 } 1454 VM_OBJECT_WUNLOCK(object); 1455 1456 /* 1457 * If we had an unrecoverable read error pages will not be valid. 1458 */ 1459 for (int i = 0; i < count; i++) 1460 if (ma[i]->valid != VM_PAGE_BITS_ALL) 1461 return (VM_PAGER_ERROR); 1462 1463 return (VM_PAGER_OK); 1464 1465 /* 1466 * A final note: in a low swap situation, we cannot deallocate swap 1467 * and mark a page dirty here because the caller is likely to mark 1468 * the page clean when we return, causing the page to possibly revert 1469 * to all-zero's later. 1470 */ 1471 } 1472 1473 static int 1474 swap_pager_getpages(vm_object_t object, vm_page_t *ma, int count, 1475 int *rbehind, int *rahead) 1476 { 1477 struct buf *bp; 1478 struct pctrie_iter blks; 1479 1480 bp = uma_zalloc(swrbuf_zone, M_WAITOK); 1481 VM_OBJECT_WLOCK(object); 1482 swblk_iter_init_only(&blks, object); 1483 return (swap_pager_getpages_locked(&blks, object, ma, count, rbehind, 1484 rahead, bp)); 1485 } 1486 1487 /* 1488 * swap_pager_getpages_async(): 1489 * 1490 * Right now this is emulation of asynchronous operation on top of 1491 * swap_pager_getpages(). 1492 */ 1493 static int 1494 swap_pager_getpages_async(vm_object_t object, vm_page_t *ma, int count, 1495 int *rbehind, int *rahead, pgo_getpages_iodone_t iodone, void *arg) 1496 { 1497 int r, error; 1498 1499 r = swap_pager_getpages(object, ma, count, rbehind, rahead); 1500 switch (r) { 1501 case VM_PAGER_OK: 1502 error = 0; 1503 break; 1504 case VM_PAGER_ERROR: 1505 error = EIO; 1506 break; 1507 case VM_PAGER_FAIL: 1508 error = EINVAL; 1509 break; 1510 default: 1511 panic("unhandled swap_pager_getpages() error %d", r); 1512 } 1513 (iodone)(arg, ma, count, error); 1514 1515 return (r); 1516 } 1517 1518 /* 1519 * swap_pager_putpages: 1520 * 1521 * Assign swap (if necessary) and initiate I/O on the specified pages. 1522 * 1523 * In a low memory situation we may block in VOP_STRATEGY(), but the new 1524 * vm_page reservation system coupled with properly written VFS devices 1525 * should ensure that no low-memory deadlock occurs. This is an area 1526 * which needs work. 1527 * 1528 * The parent has N vm_object_pip_add() references prior to 1529 * calling us and will remove references for rtvals[] that are 1530 * not set to VM_PAGER_PEND. We need to remove the rest on I/O 1531 * completion. 1532 * 1533 * The parent has soft-busy'd the pages it passes us and will unbusy 1534 * those whose rtvals[] entry is not set to VM_PAGER_PEND on return. 1535 * We need to unbusy the rest on I/O completion. 1536 */ 1537 static void 1538 swap_pager_putpages(vm_object_t object, vm_page_t *ma, int count, 1539 int flags, int *rtvals) 1540 { 1541 struct pctrie_iter blks; 1542 struct page_range range; 1543 struct buf *bp; 1544 daddr_t addr, blk; 1545 vm_page_t mreq; 1546 int i, j, n; 1547 bool async; 1548 1549 KASSERT(count == 0 || ma[0]->object == object, 1550 ("%s: object mismatch %p/%p", 1551 __func__, object, ma[0]->object)); 1552 1553 VM_OBJECT_WUNLOCK(object); 1554 async = curproc == pageproc && (flags & VM_PAGER_PUT_SYNC) == 0; 1555 swp_pager_init_freerange(&range); 1556 1557 /* 1558 * Assign swap blocks and issue I/O. We reallocate swap on the fly. 1559 * The page is left dirty until the pageout operation completes 1560 * successfully. 1561 */ 1562 for (i = 0; i < count; i += n) { 1563 /* Maximum I/O size is limited by maximum swap block size. */ 1564 n = min(count - i, nsw_cluster_max); 1565 1566 if (async) { 1567 mtx_lock(&swbuf_mtx); 1568 while (nsw_wcount_async == 0) 1569 msleep(&nsw_wcount_async, &swbuf_mtx, PVM, 1570 "swbufa", 0); 1571 nsw_wcount_async--; 1572 mtx_unlock(&swbuf_mtx); 1573 } 1574 1575 /* Get a block of swap of size up to size n. */ 1576 blk = swp_pager_getswapspace(&n); 1577 if (blk == SWAPBLK_NONE) { 1578 mtx_lock(&swbuf_mtx); 1579 if (++nsw_wcount_async == 1) 1580 wakeup(&nsw_wcount_async); 1581 mtx_unlock(&swbuf_mtx); 1582 for (j = 0; j < n; ++j) 1583 rtvals[i + j] = VM_PAGER_FAIL; 1584 continue; 1585 } 1586 VM_OBJECT_WLOCK(object); 1587 swblk_iter_init_only(&blks, object); 1588 for (j = 0; j < n; ++j) { 1589 mreq = ma[i + j]; 1590 vm_page_aflag_clear(mreq, PGA_SWAP_FREE); 1591 KASSERT(mreq->object == object, 1592 ("%s: object mismatch %p/%p", 1593 __func__, mreq->object, object)); 1594 addr = swp_pager_meta_build(&blks, object, 1595 mreq->pindex, blk + j, false); 1596 if (addr != SWAPBLK_NONE) 1597 swp_pager_update_freerange(&range, addr); 1598 MPASS(mreq->dirty == VM_PAGE_BITS_ALL); 1599 mreq->oflags |= VPO_SWAPINPROG; 1600 } 1601 VM_OBJECT_WUNLOCK(object); 1602 1603 bp = uma_zalloc(swwbuf_zone, M_WAITOK); 1604 MPASS((bp->b_flags & B_MAXPHYS) != 0); 1605 if (async) 1606 bp->b_flags |= B_ASYNC; 1607 bp->b_flags |= B_PAGING; 1608 bp->b_iocmd = BIO_WRITE; 1609 1610 bp->b_rcred = crhold(thread0.td_ucred); 1611 bp->b_wcred = crhold(thread0.td_ucred); 1612 bp->b_bcount = PAGE_SIZE * n; 1613 bp->b_bufsize = PAGE_SIZE * n; 1614 bp->b_blkno = blk; 1615 for (j = 0; j < n; j++) 1616 bp->b_pages[j] = ma[i + j]; 1617 bp->b_npages = n; 1618 1619 /* 1620 * Must set dirty range for NFS to work. 1621 */ 1622 bp->b_dirtyoff = 0; 1623 bp->b_dirtyend = bp->b_bcount; 1624 1625 VM_CNT_INC(v_swapout); 1626 VM_CNT_ADD(v_swappgsout, bp->b_npages); 1627 1628 /* 1629 * We unconditionally set rtvals[] to VM_PAGER_PEND so that we 1630 * can call the async completion routine at the end of a 1631 * synchronous I/O operation. Otherwise, our caller would 1632 * perform duplicate unbusy and wakeup operations on the page 1633 * and object, respectively. 1634 */ 1635 for (j = 0; j < n; j++) 1636 rtvals[i + j] = VM_PAGER_PEND; 1637 1638 /* 1639 * asynchronous 1640 * 1641 * NOTE: b_blkno is destroyed by the call to swapdev_strategy. 1642 */ 1643 if (async) { 1644 bp->b_iodone = swp_pager_async_iodone; 1645 BUF_KERNPROC(bp); 1646 swp_pager_strategy(bp); 1647 continue; 1648 } 1649 1650 /* 1651 * synchronous 1652 * 1653 * NOTE: b_blkno is destroyed by the call to swapdev_strategy. 1654 */ 1655 bp->b_iodone = bdone; 1656 swp_pager_strategy(bp); 1657 1658 /* 1659 * Wait for the sync I/O to complete. 1660 */ 1661 bwait(bp, PVM, "swwrt"); 1662 1663 /* 1664 * Now that we are through with the bp, we can call the 1665 * normal async completion, which frees everything up. 1666 */ 1667 swp_pager_async_iodone(bp); 1668 } 1669 swp_pager_freeswapspace(&range); 1670 VM_OBJECT_WLOCK(object); 1671 } 1672 1673 /* 1674 * swp_pager_async_iodone: 1675 * 1676 * Completion routine for asynchronous reads and writes from/to swap. 1677 * Also called manually by synchronous code to finish up a bp. 1678 * 1679 * This routine may not sleep. 1680 */ 1681 static void 1682 swp_pager_async_iodone(struct buf *bp) 1683 { 1684 int i; 1685 vm_object_t object = NULL; 1686 1687 /* 1688 * Report error - unless we ran out of memory, in which case 1689 * we've already logged it in swapgeom_strategy(). 1690 */ 1691 if (bp->b_ioflags & BIO_ERROR && bp->b_error != ENOMEM) { 1692 printf( 1693 "swap_pager: I/O error - %s failed; blkno %ld," 1694 "size %ld, error %d\n", 1695 ((bp->b_iocmd == BIO_READ) ? "pagein" : "pageout"), 1696 (long)bp->b_blkno, 1697 (long)bp->b_bcount, 1698 bp->b_error 1699 ); 1700 } 1701 1702 /* 1703 * remove the mapping for kernel virtual 1704 */ 1705 if (buf_mapped(bp)) 1706 pmap_qremove((vm_offset_t)bp->b_data, bp->b_npages); 1707 else 1708 bp->b_data = bp->b_kvabase; 1709 1710 if (bp->b_npages) { 1711 object = bp->b_pages[0]->object; 1712 VM_OBJECT_WLOCK(object); 1713 } 1714 1715 /* 1716 * cleanup pages. If an error occurs writing to swap, we are in 1717 * very serious trouble. If it happens to be a disk error, though, 1718 * we may be able to recover by reassigning the swap later on. So 1719 * in this case we remove the m->swapblk assignment for the page 1720 * but do not free it in the rlist. The errornous block(s) are thus 1721 * never reallocated as swap. Redirty the page and continue. 1722 */ 1723 for (i = 0; i < bp->b_npages; ++i) { 1724 vm_page_t m = bp->b_pages[i]; 1725 1726 m->oflags &= ~VPO_SWAPINPROG; 1727 if (m->oflags & VPO_SWAPSLEEP) { 1728 m->oflags &= ~VPO_SWAPSLEEP; 1729 wakeup(&object->handle); 1730 } 1731 1732 /* We always have space after I/O, successful or not. */ 1733 vm_page_aflag_set(m, PGA_SWAP_SPACE); 1734 1735 if (bp->b_ioflags & BIO_ERROR) { 1736 /* 1737 * If an error occurs I'd love to throw the swapblk 1738 * away without freeing it back to swapspace, so it 1739 * can never be used again. But I can't from an 1740 * interrupt. 1741 */ 1742 if (bp->b_iocmd == BIO_READ) { 1743 /* 1744 * NOTE: for reads, m->dirty will probably 1745 * be overridden by the original caller of 1746 * getpages so don't play cute tricks here. 1747 */ 1748 vm_page_invalid(m); 1749 if (i < bp->b_pgbefore || 1750 i >= bp->b_npages - bp->b_pgafter) 1751 vm_page_free_invalid(m); 1752 } else { 1753 /* 1754 * If a write error occurs, reactivate page 1755 * so it doesn't clog the inactive list, 1756 * then finish the I/O. 1757 */ 1758 MPASS(m->dirty == VM_PAGE_BITS_ALL); 1759 1760 /* PQ_UNSWAPPABLE? */ 1761 vm_page_activate(m); 1762 vm_page_sunbusy(m); 1763 } 1764 } else if (bp->b_iocmd == BIO_READ) { 1765 /* 1766 * NOTE: for reads, m->dirty will probably be 1767 * overridden by the original caller of getpages so 1768 * we cannot set them in order to free the underlying 1769 * swap in a low-swap situation. I don't think we'd 1770 * want to do that anyway, but it was an optimization 1771 * that existed in the old swapper for a time before 1772 * it got ripped out due to precisely this problem. 1773 */ 1774 KASSERT(!pmap_page_is_mapped(m), 1775 ("swp_pager_async_iodone: page %p is mapped", m)); 1776 KASSERT(m->dirty == 0, 1777 ("swp_pager_async_iodone: page %p is dirty", m)); 1778 1779 vm_page_valid(m); 1780 if (i < bp->b_pgbefore || 1781 i >= bp->b_npages - bp->b_pgafter) 1782 vm_page_readahead_finish(m); 1783 } else { 1784 /* 1785 * For write success, clear the dirty 1786 * status, then finish the I/O ( which decrements the 1787 * busy count and possibly wakes waiter's up ). 1788 * A page is only written to swap after a period of 1789 * inactivity. Therefore, we do not expect it to be 1790 * reused. 1791 */ 1792 KASSERT(!pmap_page_is_write_mapped(m), 1793 ("swp_pager_async_iodone: page %p is not write" 1794 " protected", m)); 1795 vm_page_undirty(m); 1796 vm_page_deactivate_noreuse(m); 1797 vm_page_sunbusy(m); 1798 } 1799 } 1800 1801 /* 1802 * adjust pip. NOTE: the original parent may still have its own 1803 * pip refs on the object. 1804 */ 1805 if (object != NULL) { 1806 vm_object_pip_wakeupn(object, bp->b_npages); 1807 VM_OBJECT_WUNLOCK(object); 1808 } 1809 1810 /* 1811 * swapdev_strategy() manually sets b_vp and b_bufobj before calling 1812 * bstrategy(). Set them back to NULL now we're done with it, or we'll 1813 * trigger a KASSERT in relpbuf(). 1814 */ 1815 if (bp->b_vp) { 1816 bp->b_vp = NULL; 1817 bp->b_bufobj = NULL; 1818 } 1819 /* 1820 * release the physical I/O buffer 1821 */ 1822 if (bp->b_flags & B_ASYNC) { 1823 mtx_lock(&swbuf_mtx); 1824 if (++nsw_wcount_async == 1) 1825 wakeup(&nsw_wcount_async); 1826 mtx_unlock(&swbuf_mtx); 1827 } 1828 uma_zfree((bp->b_iocmd == BIO_READ) ? swrbuf_zone : swwbuf_zone, bp); 1829 } 1830 1831 int 1832 swap_pager_nswapdev(void) 1833 { 1834 1835 return (nswapdev); 1836 } 1837 1838 static void 1839 swp_pager_force_dirty(struct page_range *range, vm_page_t m, daddr_t *blk) 1840 { 1841 vm_page_dirty(m); 1842 swap_pager_unswapped_acct(m); 1843 swp_pager_update_freerange(range, *blk); 1844 *blk = SWAPBLK_NONE; 1845 vm_page_launder(m); 1846 } 1847 1848 u_long 1849 swap_pager_swapped_pages(vm_object_t object) 1850 { 1851 struct pctrie_iter blks; 1852 struct swblk *sb; 1853 u_long res; 1854 int i; 1855 1856 VM_OBJECT_ASSERT_LOCKED(object); 1857 1858 if (swblk_is_empty(object)) 1859 return (0); 1860 1861 res = 0; 1862 for (sb = swblk_iter_init(&blks, object, 0); sb != NULL; 1863 sb = swblk_iter_next(&blks)) { 1864 for (i = 0; i < SWAP_META_PAGES; i++) { 1865 if (sb->d[i] != SWAPBLK_NONE) 1866 res++; 1867 } 1868 } 1869 return (res); 1870 } 1871 1872 /* 1873 * swap_pager_swapoff_object: 1874 * 1875 * Page in all of the pages that have been paged out for an object 1876 * to a swap device. 1877 */ 1878 static void 1879 swap_pager_swapoff_object(struct swdevt *sp, vm_object_t object, 1880 struct buf **bp) 1881 { 1882 struct pctrie_iter blks, pages; 1883 struct page_range range; 1884 struct swblk *sb; 1885 vm_page_t m; 1886 int i, rahead, rv; 1887 bool sb_empty; 1888 1889 VM_OBJECT_ASSERT_WLOCKED(object); 1890 KASSERT((object->flags & OBJ_SWAP) != 0, 1891 ("%s: Object not swappable", __func__)); 1892 KASSERT((object->flags & OBJ_DEAD) == 0, 1893 ("%s: Object already dead", __func__)); 1894 KASSERT((sp->sw_flags & SW_CLOSING) != 0, 1895 ("%s: Device not blocking further allocations", __func__)); 1896 1897 vm_page_iter_init(&pages, object); 1898 swp_pager_init_freerange(&range); 1899 sb = swblk_iter_init(&blks, object, 0); 1900 while (sb != NULL) { 1901 sb_empty = true; 1902 for (i = 0; i < SWAP_META_PAGES; i++) { 1903 /* Skip an invalid block. */ 1904 if (sb->d[i] == SWAPBLK_NONE) 1905 continue; 1906 /* Skip a block not of this device. */ 1907 if (!swp_pager_isondev(sb->d[i], sp)) { 1908 sb_empty = false; 1909 continue; 1910 } 1911 1912 /* 1913 * Look for a page corresponding to this block. If the 1914 * found page has pending operations, sleep and restart 1915 * the scan. 1916 */ 1917 m = vm_radix_iter_lookup(&pages, blks.index + i); 1918 if (m != NULL && (m->oflags & VPO_SWAPINPROG) != 0) { 1919 m->oflags |= VPO_SWAPSLEEP; 1920 VM_OBJECT_SLEEP(object, &object->handle, PSWP, 1921 "swpoff", 0); 1922 break; 1923 } 1924 1925 /* 1926 * If the found page is valid, mark it dirty and free 1927 * the swap block. 1928 */ 1929 if (m != NULL && vm_page_all_valid(m)) { 1930 swp_pager_force_dirty(&range, m, &sb->d[i]); 1931 continue; 1932 } 1933 /* Is there a page we can acquire or allocate? */ 1934 if (m != NULL) { 1935 if (!vm_page_busy_acquire(m, VM_ALLOC_WAITFAIL)) 1936 break; 1937 } else { 1938 m = vm_page_alloc_iter(object, blks.index + i, 1939 VM_ALLOC_NORMAL | VM_ALLOC_WAITFAIL, 1940 &pages); 1941 if (m == NULL) 1942 break; 1943 } 1944 1945 /* Get the page from swap, and restart the scan. */ 1946 vm_object_pip_add(object, 1); 1947 rahead = SWAP_META_PAGES; 1948 rv = swap_pager_getpages_locked(&blks, object, &m, 1, 1949 NULL, &rahead, *bp); 1950 if (rv != VM_PAGER_OK) 1951 panic("%s: read from swap failed: %d", 1952 __func__, rv); 1953 *bp = uma_zalloc(swrbuf_zone, M_WAITOK); 1954 VM_OBJECT_WLOCK(object); 1955 vm_object_pip_wakeupn(object, 1); 1956 KASSERT(vm_page_all_valid(m), 1957 ("%s: Page %p not all valid", __func__, m)); 1958 vm_page_deactivate_noreuse(m); 1959 vm_page_xunbusy(m); 1960 break; 1961 } 1962 if (i < SWAP_META_PAGES) { 1963 /* 1964 * The object lock has been released and regained. 1965 * Perhaps the object is now dead. 1966 */ 1967 if ((object->flags & OBJ_DEAD) != 0) { 1968 /* 1969 * Make sure that pending writes finish before 1970 * returning. 1971 */ 1972 vm_object_pip_wait(object, "swpoff"); 1973 swp_pager_meta_free_all(object); 1974 break; 1975 } 1976 1977 /* 1978 * The swapblk could have been freed, so reset the pages 1979 * iterator and search again for the first swblk at or 1980 * after blks.index. 1981 */ 1982 pctrie_iter_reset(&pages); 1983 sb = swblk_iter_init(&blks, object, blks.index); 1984 continue; 1985 } 1986 if (sb_empty) { 1987 swblk_iter_remove(&blks); 1988 uma_zfree(swblk_zone, sb); 1989 } 1990 1991 /* 1992 * It is safe to advance to the next block. No allocations 1993 * before blk.index have happened, even with the lock released, 1994 * because allocations on this device are blocked. 1995 */ 1996 sb = swblk_iter_next(&blks); 1997 } 1998 swp_pager_freeswapspace(&range); 1999 } 2000 2001 /* 2002 * swap_pager_swapoff: 2003 * 2004 * Page in all of the pages that have been paged out to the 2005 * given device. The corresponding blocks in the bitmap must be 2006 * marked as allocated and the device must be flagged SW_CLOSING. 2007 * There may be no processes swapped out to the device. 2008 * 2009 * This routine may block. 2010 */ 2011 static void 2012 swap_pager_swapoff(struct swdevt *sp) 2013 { 2014 vm_object_t object; 2015 struct buf *bp; 2016 int retries; 2017 2018 sx_assert(&swdev_syscall_lock, SA_XLOCKED); 2019 2020 retries = 0; 2021 full_rescan: 2022 bp = uma_zalloc(swrbuf_zone, M_WAITOK); 2023 mtx_lock(&vm_object_list_mtx); 2024 TAILQ_FOREACH(object, &vm_object_list, object_list) { 2025 if ((object->flags & OBJ_SWAP) == 0) 2026 continue; 2027 mtx_unlock(&vm_object_list_mtx); 2028 /* Depends on type-stability. */ 2029 VM_OBJECT_WLOCK(object); 2030 2031 /* 2032 * Dead objects are eventually terminated on their own. 2033 */ 2034 if ((object->flags & OBJ_DEAD) != 0) 2035 goto next_obj; 2036 2037 /* 2038 * Sync with fences placed after pctrie 2039 * initialization. We must not access pctrie below 2040 * unless we checked that our object is swap and not 2041 * dead. 2042 */ 2043 atomic_thread_fence_acq(); 2044 if ((object->flags & OBJ_SWAP) == 0) 2045 goto next_obj; 2046 2047 swap_pager_swapoff_object(sp, object, &bp); 2048 next_obj: 2049 VM_OBJECT_WUNLOCK(object); 2050 mtx_lock(&vm_object_list_mtx); 2051 } 2052 mtx_unlock(&vm_object_list_mtx); 2053 uma_zfree(swrbuf_zone, bp); 2054 2055 if (sp->sw_used) { 2056 /* 2057 * Objects may be locked or paging to the device being 2058 * removed, so we will miss their pages and need to 2059 * make another pass. We have marked this device as 2060 * SW_CLOSING, so the activity should finish soon. 2061 */ 2062 retries++; 2063 if (retries > 100) { 2064 panic("swapoff: failed to locate %d swap blocks", 2065 sp->sw_used); 2066 } 2067 pause("swpoff", hz / 20); 2068 goto full_rescan; 2069 } 2070 EVENTHANDLER_INVOKE(swapoff, sp); 2071 } 2072 2073 /************************************************************************ 2074 * SWAP META DATA * 2075 ************************************************************************ 2076 * 2077 * These routines manipulate the swap metadata stored in the 2078 * OBJT_SWAP object. 2079 * 2080 * Swap metadata is implemented with a global hash and not directly 2081 * linked into the object. Instead the object simply contains 2082 * appropriate tracking counters. 2083 */ 2084 2085 /* 2086 * SWP_PAGER_SWBLK_EMPTY() - is a range of blocks free? 2087 */ 2088 static bool 2089 swp_pager_swblk_empty(struct swblk *sb, int start, int limit) 2090 { 2091 int i; 2092 2093 MPASS(0 <= start && start <= limit && limit <= SWAP_META_PAGES); 2094 for (i = start; i < limit; i++) { 2095 if (sb->d[i] != SWAPBLK_NONE) 2096 return (false); 2097 } 2098 return (true); 2099 } 2100 2101 /* 2102 * SWP_PAGER_FREE_EMPTY_SWBLK() - frees if a block is free 2103 * 2104 * Nothing is done if the block is still in use. 2105 */ 2106 static void 2107 swp_pager_free_empty_swblk(vm_object_t object, struct swblk *sb) 2108 { 2109 2110 if (swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) { 2111 swblk_lookup_remove(object, sb); 2112 uma_zfree(swblk_zone, sb); 2113 } 2114 } 2115 2116 /* 2117 * SWP_PAGER_META_BUILD() - add swap block to swap meta data for object 2118 * 2119 * Try to add the specified swapblk to the object's swap metadata. If 2120 * nowait_noreplace is set, add the specified swapblk only if there is no 2121 * previously assigned swapblk at pindex. If the swapblk is invalid, and 2122 * replaces a valid swapblk, empty swap metadata is freed. If memory 2123 * allocation fails, and nowait_noreplace is set, return the specified 2124 * swapblk immediately to indicate failure; otherwise, wait and retry until 2125 * memory allocation succeeds. Return the previously assigned swapblk, if 2126 * any. 2127 */ 2128 static daddr_t 2129 swp_pager_meta_build(struct pctrie_iter *blks, vm_object_t object, 2130 vm_pindex_t pindex, daddr_t swapblk, bool nowait_noreplace) 2131 { 2132 static volatile int swblk_zone_exhausted, swpctrie_zone_exhausted; 2133 struct swblk *sb, *sb1; 2134 vm_pindex_t modpi; 2135 daddr_t prev_swapblk; 2136 int error, i; 2137 2138 VM_OBJECT_ASSERT_WLOCKED(object); 2139 2140 sb = swblk_iter_lookup(blks, pindex); 2141 if (sb == NULL) { 2142 if (swapblk == SWAPBLK_NONE) 2143 return (SWAPBLK_NONE); 2144 for (;;) { 2145 sb = uma_zalloc(swblk_zone, M_NOWAIT | (curproc == 2146 pageproc ? M_USE_RESERVE : 0)); 2147 if (sb != NULL) { 2148 sb->p = rounddown(pindex, SWAP_META_PAGES); 2149 for (i = 0; i < SWAP_META_PAGES; i++) 2150 sb->d[i] = SWAPBLK_NONE; 2151 if (atomic_cmpset_int(&swblk_zone_exhausted, 2152 1, 0)) 2153 printf("swblk zone ok\n"); 2154 break; 2155 } 2156 if (nowait_noreplace) 2157 return (swapblk); 2158 VM_OBJECT_WUNLOCK(object); 2159 if (uma_zone_exhausted(swblk_zone)) { 2160 if (atomic_cmpset_int(&swblk_zone_exhausted, 2161 0, 1)) 2162 printf("swap blk zone exhausted, " 2163 "increase kern.maxswzone\n"); 2164 vm_pageout_oom(VM_OOM_SWAPZ); 2165 pause("swzonxb", 10); 2166 } else 2167 uma_zwait(swblk_zone); 2168 VM_OBJECT_WLOCK(object); 2169 sb = swblk_iter_reinit(blks, object, pindex); 2170 if (sb != NULL) 2171 /* 2172 * Somebody swapped out a nearby page, 2173 * allocating swblk at the pindex index, 2174 * while we dropped the object lock. 2175 */ 2176 goto allocated; 2177 } 2178 for (;;) { 2179 error = swblk_iter_insert(blks, sb); 2180 if (error == 0) { 2181 if (atomic_cmpset_int(&swpctrie_zone_exhausted, 2182 1, 0)) 2183 printf("swpctrie zone ok\n"); 2184 break; 2185 } 2186 if (nowait_noreplace) { 2187 uma_zfree(swblk_zone, sb); 2188 return (swapblk); 2189 } 2190 VM_OBJECT_WUNLOCK(object); 2191 if (uma_zone_exhausted(swpctrie_zone)) { 2192 if (atomic_cmpset_int(&swpctrie_zone_exhausted, 2193 0, 1)) 2194 printf("swap pctrie zone exhausted, " 2195 "increase kern.maxswzone\n"); 2196 vm_pageout_oom(VM_OOM_SWAPZ); 2197 pause("swzonxp", 10); 2198 } else 2199 uma_zwait(swpctrie_zone); 2200 VM_OBJECT_WLOCK(object); 2201 sb1 = swblk_iter_reinit(blks, object, pindex); 2202 if (sb1 != NULL) { 2203 uma_zfree(swblk_zone, sb); 2204 sb = sb1; 2205 goto allocated; 2206 } 2207 } 2208 } 2209 allocated: 2210 MPASS(sb->p == rounddown(pindex, SWAP_META_PAGES)); 2211 2212 modpi = pindex % SWAP_META_PAGES; 2213 /* Return prior contents of metadata. */ 2214 prev_swapblk = sb->d[modpi]; 2215 if (!nowait_noreplace || prev_swapblk == SWAPBLK_NONE) { 2216 /* Enter block into metadata. */ 2217 sb->d[modpi] = swapblk; 2218 2219 /* 2220 * Free the swblk if we end up with the empty page run. 2221 */ 2222 if (swapblk == SWAPBLK_NONE && 2223 swp_pager_swblk_empty(sb, 0, SWAP_META_PAGES)) { 2224 swblk_iter_remove(blks); 2225 uma_zfree(swblk_zone, sb); 2226 } 2227 } 2228 return (prev_swapblk); 2229 } 2230 2231 /* 2232 * SWP_PAGER_META_TRANSFER() - transfer a range of blocks in the srcobject's 2233 * swap metadata into dstobject. 2234 * 2235 * Blocks in src that correspond to holes in dst are transferred. Blocks 2236 * in src that correspond to blocks in dst are freed. 2237 */ 2238 static void 2239 swp_pager_meta_transfer(vm_object_t srcobject, vm_object_t dstobject, 2240 vm_pindex_t pindex, vm_pindex_t count) 2241 { 2242 struct pctrie_iter dstblks, srcblks; 2243 struct page_range range; 2244 struct swblk *sb; 2245 daddr_t blk, d[SWAP_META_PAGES]; 2246 vm_pindex_t last; 2247 int d_mask, i, limit, start; 2248 _Static_assert(8 * sizeof(d_mask) >= SWAP_META_PAGES, 2249 "d_mask not big enough"); 2250 2251 VM_OBJECT_ASSERT_WLOCKED(srcobject); 2252 VM_OBJECT_ASSERT_WLOCKED(dstobject); 2253 2254 if (count == 0 || swblk_is_empty(srcobject)) 2255 return; 2256 2257 swp_pager_init_freerange(&range); 2258 d_mask = 0; 2259 last = pindex + count; 2260 swblk_iter_init_only(&dstblks, dstobject); 2261 for (sb = swblk_iter_limit_init(&srcblks, srcobject, pindex, last), 2262 start = swblk_start(sb, pindex); 2263 sb != NULL; sb = swblk_iter_next(&srcblks), start = 0) { 2264 limit = MIN(last - srcblks.index, SWAP_META_PAGES); 2265 for (i = start; i < limit; i++) { 2266 if (sb->d[i] == SWAPBLK_NONE) 2267 continue; 2268 blk = swp_pager_meta_build(&dstblks, dstobject, 2269 srcblks.index + i - pindex, sb->d[i], true); 2270 if (blk == sb->d[i]) { 2271 /* 2272 * Failed memory allocation stopped transfer; 2273 * save this block for transfer with lock 2274 * released. 2275 */ 2276 d[i] = blk; 2277 d_mask |= 1 << i; 2278 } else if (blk != SWAPBLK_NONE) { 2279 /* Dst has a block at pindex, so free block. */ 2280 swp_pager_update_freerange(&range, sb->d[i]); 2281 } 2282 sb->d[i] = SWAPBLK_NONE; 2283 } 2284 if (swp_pager_swblk_empty(sb, 0, start) && 2285 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) { 2286 swblk_iter_remove(&srcblks); 2287 uma_zfree(swblk_zone, sb); 2288 } 2289 if (d_mask != 0) { 2290 /* Finish block transfer, with the lock released. */ 2291 VM_OBJECT_WUNLOCK(srcobject); 2292 do { 2293 i = ffs(d_mask) - 1; 2294 swp_pager_meta_build(&dstblks, dstobject, 2295 srcblks.index + i - pindex, d[i], false); 2296 d_mask &= ~(1 << i); 2297 } while (d_mask != 0); 2298 VM_OBJECT_WLOCK(srcobject); 2299 2300 /* 2301 * While the lock was not held, the iterator path could 2302 * have become stale, so discard it. 2303 */ 2304 pctrie_iter_reset(&srcblks); 2305 } 2306 } 2307 swp_pager_freeswapspace(&range); 2308 } 2309 2310 /* 2311 * SWP_PAGER_META_FREE() - free a range of blocks in the object's swap metadata 2312 * 2313 * Return freed swap blocks to the swap bitmap, and free emptied swblk 2314 * metadata. With 'freed' set, provide a count of freed blocks that were 2315 * not associated with valid resident pages. 2316 */ 2317 static void 2318 swp_pager_meta_free(vm_object_t object, vm_pindex_t pindex, vm_pindex_t count, 2319 vm_size_t *freed) 2320 { 2321 struct pctrie_iter blks, pages; 2322 struct page_range range; 2323 struct swblk *sb; 2324 vm_page_t m; 2325 vm_pindex_t last; 2326 vm_size_t fc; 2327 int i, limit, start; 2328 2329 VM_OBJECT_ASSERT_WLOCKED(object); 2330 2331 fc = 0; 2332 if (count == 0 || swblk_is_empty(object)) 2333 goto out; 2334 2335 swp_pager_init_freerange(&range); 2336 vm_page_iter_init(&pages, object); 2337 last = pindex + count; 2338 for (sb = swblk_iter_limit_init(&blks, object, pindex, last), 2339 start = swblk_start(sb, pindex); 2340 sb != NULL; sb = swblk_iter_next(&blks), start = 0) { 2341 limit = MIN(last - blks.index, SWAP_META_PAGES); 2342 for (i = start; i < limit; i++) { 2343 if (sb->d[i] == SWAPBLK_NONE) 2344 continue; 2345 swp_pager_update_freerange(&range, sb->d[i]); 2346 if (freed != NULL) { 2347 m = vm_radix_iter_lookup(&pages, blks.index + i); 2348 if (m == NULL || vm_page_none_valid(m)) 2349 fc++; 2350 } 2351 sb->d[i] = SWAPBLK_NONE; 2352 } 2353 if (swp_pager_swblk_empty(sb, 0, start) && 2354 swp_pager_swblk_empty(sb, limit, SWAP_META_PAGES)) { 2355 swblk_iter_remove(&blks); 2356 uma_zfree(swblk_zone, sb); 2357 } 2358 } 2359 swp_pager_freeswapspace(&range); 2360 out: 2361 if (freed != NULL) 2362 *freed = fc; 2363 } 2364 2365 static void 2366 swp_pager_meta_free_block(struct swblk *sb, void *rangev) 2367 { 2368 struct page_range *range = rangev; 2369 2370 for (int i = 0; i < SWAP_META_PAGES; i++) { 2371 if (sb->d[i] != SWAPBLK_NONE) 2372 swp_pager_update_freerange(range, sb->d[i]); 2373 } 2374 uma_zfree(swblk_zone, sb); 2375 } 2376 2377 /* 2378 * SWP_PAGER_META_FREE_ALL() - destroy all swap metadata associated with object 2379 * 2380 * This routine locates and destroys all swap metadata associated with 2381 * an object. 2382 */ 2383 static void 2384 swp_pager_meta_free_all(vm_object_t object) 2385 { 2386 struct page_range range; 2387 2388 VM_OBJECT_ASSERT_WLOCKED(object); 2389 2390 swp_pager_init_freerange(&range); 2391 SWAP_PCTRIE_RECLAIM_CALLBACK(&object->un_pager.swp.swp_blks, 2392 swp_pager_meta_free_block, &range); 2393 swp_pager_freeswapspace(&range); 2394 } 2395 2396 /* 2397 * SWP_PAGER_METACTL() - misc control of swap meta data. 2398 * 2399 * This routine is capable of looking up, or removing swapblk 2400 * assignments in the swap meta data. It returns the swapblk being 2401 * looked-up, popped, or SWAPBLK_NONE if the block was invalid. 2402 * 2403 * When acting on a busy resident page and paging is in progress, we 2404 * have to wait until paging is complete but otherwise can act on the 2405 * busy page. 2406 */ 2407 static daddr_t 2408 swp_pager_meta_lookup(struct pctrie_iter *blks, vm_pindex_t pindex) 2409 { 2410 struct swblk *sb; 2411 2412 sb = swblk_iter_lookup(blks, pindex); 2413 if (sb == NULL) 2414 return (SWAPBLK_NONE); 2415 return (sb->d[pindex % SWAP_META_PAGES]); 2416 } 2417 2418 /* 2419 * Returns the least page index which is greater than or equal to the parameter 2420 * pindex and for which there is a swap block allocated. Returns OBJ_MAX_SIZE 2421 * if are no allocated swap blocks for the object after the requested pindex. 2422 */ 2423 static vm_pindex_t 2424 swap_pager_iter_find_least(struct pctrie_iter *blks, vm_pindex_t pindex) 2425 { 2426 struct swblk *sb; 2427 int i; 2428 2429 if ((sb = swblk_iter_lookup_ge(blks, pindex)) == NULL) 2430 return (OBJ_MAX_SIZE); 2431 if (blks->index < pindex) { 2432 for (i = pindex % SWAP_META_PAGES; i < SWAP_META_PAGES; i++) { 2433 if (sb->d[i] != SWAPBLK_NONE) 2434 return (blks->index + i); 2435 } 2436 if ((sb = swblk_iter_next(blks)) == NULL) 2437 return (OBJ_MAX_SIZE); 2438 } 2439 for (i = 0; i < SWAP_META_PAGES; i++) { 2440 if (sb->d[i] != SWAPBLK_NONE) 2441 return (blks->index + i); 2442 } 2443 2444 /* 2445 * We get here if a swblk is present in the trie but it 2446 * doesn't map any blocks. 2447 */ 2448 MPASS(0); 2449 return (OBJ_MAX_SIZE); 2450 } 2451 2452 /* 2453 * Find the first index >= pindex that has either a valid page or a swap 2454 * block. 2455 */ 2456 vm_pindex_t 2457 swap_pager_seek_data(vm_object_t object, vm_pindex_t pindex) 2458 { 2459 struct pctrie_iter blks, pages; 2460 vm_page_t m; 2461 vm_pindex_t swap_index; 2462 2463 VM_OBJECT_ASSERT_RLOCKED(object); 2464 vm_page_iter_init(&pages, object); 2465 m = vm_radix_iter_lookup_ge(&pages, pindex); 2466 if (m != NULL && pages.index == pindex && vm_page_any_valid(m)) 2467 return (pages.index); 2468 swblk_iter_init_only(&blks, object); 2469 swap_index = swap_pager_iter_find_least(&blks, pindex); 2470 if (swap_index == pindex) 2471 return (swap_index); 2472 2473 /* 2474 * Find the first resident page after m, before swap_index. 2475 */ 2476 while (m != NULL && pages.index < swap_index) { 2477 if (vm_page_any_valid(m)) 2478 return (pages.index); 2479 m = vm_radix_iter_step(&pages); 2480 } 2481 if (swap_index == OBJ_MAX_SIZE) 2482 swap_index = object->size; 2483 return (swap_index); 2484 } 2485 2486 /* 2487 * Find the first index >= pindex that has neither a valid page nor a swap 2488 * block. 2489 */ 2490 vm_pindex_t 2491 swap_pager_seek_hole(vm_object_t object, vm_pindex_t pindex) 2492 { 2493 struct pctrie_iter blks, pages; 2494 struct swblk *sb; 2495 vm_page_t m; 2496 2497 VM_OBJECT_ASSERT_RLOCKED(object); 2498 vm_page_iter_init(&pages, object); 2499 swblk_iter_init_only(&blks, object); 2500 while (((m = vm_radix_iter_lookup(&pages, pindex)) != NULL && 2501 vm_page_any_valid(m)) || 2502 ((sb = swblk_iter_lookup(&blks, pindex)) != NULL && 2503 sb->d[pindex % SWAP_META_PAGES] != SWAPBLK_NONE)) 2504 pindex++; 2505 return (pindex); 2506 } 2507 2508 /* 2509 * Is every page in the backing object or swap shadowed in the parent, and 2510 * unbusy and valid in swap? 2511 */ 2512 bool 2513 swap_pager_scan_all_shadowed(vm_object_t object) 2514 { 2515 struct pctrie_iter backing_blks, backing_pages, blks, pages; 2516 vm_object_t backing_object; 2517 vm_page_t p, pp; 2518 vm_pindex_t backing_offset_index, new_pindex, pi, pi_ubound, ps, pv; 2519 2520 VM_OBJECT_ASSERT_WLOCKED(object); 2521 VM_OBJECT_ASSERT_WLOCKED(object->backing_object); 2522 2523 backing_object = object->backing_object; 2524 2525 if ((backing_object->flags & OBJ_ANON) == 0) 2526 return (false); 2527 2528 KASSERT((object->flags & OBJ_ANON) != 0, 2529 ("Shadow object is not anonymous")); 2530 backing_offset_index = OFF_TO_IDX(object->backing_object_offset); 2531 pi_ubound = MIN(backing_object->size, 2532 backing_offset_index + object->size); 2533 vm_page_iter_init(&pages, object); 2534 vm_page_iter_init(&backing_pages, backing_object); 2535 swblk_iter_init_only(&blks, object); 2536 swblk_iter_init_only(&backing_blks, backing_object); 2537 2538 /* 2539 * Only check pages inside the parent object's range and inside the 2540 * parent object's mapping of the backing object. 2541 */ 2542 pv = ps = pi = backing_offset_index - 1; 2543 for (;;) { 2544 if (pi == pv) { 2545 p = vm_radix_iter_lookup_ge(&backing_pages, pv + 1); 2546 pv = p != NULL ? p->pindex : backing_object->size; 2547 } 2548 if (pi == ps) 2549 ps = swap_pager_iter_find_least(&backing_blks, ps + 1); 2550 pi = MIN(pv, ps); 2551 if (pi >= pi_ubound) 2552 break; 2553 2554 if (pi == pv) { 2555 /* 2556 * If the backing object page is busy a grandparent or 2557 * older page may still be undergoing CoW. It is not 2558 * safe to collapse the backing object until it is 2559 * quiesced. 2560 */ 2561 if (vm_page_tryxbusy(p) == 0) 2562 return (false); 2563 2564 /* 2565 * We raced with the fault handler that left newly 2566 * allocated invalid page on the object queue and 2567 * retried. 2568 */ 2569 if (!vm_page_all_valid(p)) 2570 break; 2571 2572 /* 2573 * Busy of p disallows fault handler to validate parent 2574 * page (pp, below). 2575 */ 2576 } 2577 2578 /* 2579 * See if the parent has the page or if the parent's object 2580 * pager has the page. If the parent has the page but the page 2581 * is not valid, the parent's object pager must have the page. 2582 * 2583 * If this fails, the parent does not completely shadow the 2584 * object and we might as well give up now. 2585 */ 2586 new_pindex = pi - backing_offset_index; 2587 pp = vm_radix_iter_lookup(&pages, new_pindex); 2588 2589 /* 2590 * The valid check here is stable due to object lock being 2591 * required to clear valid and initiate paging. 2592 */ 2593 if ((pp == NULL || vm_page_none_valid(pp)) && 2594 !swp_pager_haspage_iter(new_pindex, NULL, NULL, &blks)) 2595 break; 2596 if (pi == pv) 2597 vm_page_xunbusy(p); 2598 } 2599 if (pi < pi_ubound) { 2600 if (pi == pv) 2601 vm_page_xunbusy(p); 2602 return (false); 2603 } 2604 return (true); 2605 } 2606 2607 /* 2608 * System call swapon(name) enables swapping on device name, 2609 * which must be in the swdevsw. Return EBUSY 2610 * if already swapping on this device. 2611 */ 2612 #ifndef _SYS_SYSPROTO_H_ 2613 struct swapon_args { 2614 char *name; 2615 }; 2616 #endif 2617 2618 int 2619 sys_swapon(struct thread *td, struct swapon_args *uap) 2620 { 2621 struct vattr attr; 2622 struct vnode *vp; 2623 struct nameidata nd; 2624 int error; 2625 2626 error = priv_check(td, PRIV_SWAPON); 2627 if (error) 2628 return (error); 2629 2630 sx_xlock(&swdev_syscall_lock); 2631 2632 /* 2633 * Swap metadata may not fit in the KVM if we have physical 2634 * memory of >1GB. 2635 */ 2636 if (swblk_zone == NULL) { 2637 error = ENOMEM; 2638 goto done; 2639 } 2640 2641 NDINIT(&nd, LOOKUP, ISOPEN | FOLLOW | LOCKLEAF | AUDITVNODE1, 2642 UIO_USERSPACE, uap->name); 2643 error = namei(&nd); 2644 if (error) 2645 goto done; 2646 2647 NDFREE_PNBUF(&nd); 2648 vp = nd.ni_vp; 2649 2650 if (vn_isdisk_error(vp, &error)) { 2651 error = swapongeom(vp); 2652 } else if (vp->v_type == VREG && 2653 (vp->v_mount->mnt_vfc->vfc_flags & VFCF_NETWORK) != 0 && 2654 (error = VOP_GETATTR(vp, &attr, td->td_ucred)) == 0) { 2655 /* 2656 * Allow direct swapping to NFS regular files in the same 2657 * way that nfs_mountroot() sets up diskless swapping. 2658 */ 2659 error = swaponvp(td, vp, attr.va_size / DEV_BSIZE); 2660 } 2661 2662 if (error != 0) 2663 vput(vp); 2664 else 2665 VOP_UNLOCK(vp); 2666 done: 2667 sx_xunlock(&swdev_syscall_lock); 2668 return (error); 2669 } 2670 2671 /* 2672 * Check that the total amount of swap currently configured does not 2673 * exceed half the theoretical maximum. If it does, print a warning 2674 * message. 2675 */ 2676 static void 2677 swapon_check_swzone(void) 2678 { 2679 2680 /* recommend using no more than half that amount */ 2681 if (swap_total > swap_maxpages / 2) { 2682 printf("warning: total configured swap (%lu pages) " 2683 "exceeds maximum recommended amount (%lu pages).\n", 2684 swap_total, swap_maxpages / 2); 2685 printf("warning: increase kern.maxswzone " 2686 "or reduce amount of swap.\n"); 2687 } 2688 } 2689 2690 static int 2691 swaponsomething(struct vnode *vp, void *id, u_long nblks, 2692 sw_strategy_t *strategy, sw_close_t *close, dev_t dev, int flags) 2693 { 2694 struct swdevt *sp, *tsp; 2695 daddr_t dvbase; 2696 2697 /* 2698 * nblks is in DEV_BSIZE'd chunks, convert to PAGE_SIZE'd chunks. 2699 * First chop nblks off to page-align it, then convert. 2700 * 2701 * sw->sw_nblks is in page-sized chunks now too. 2702 */ 2703 nblks &= ~(ctodb(1) - 1); 2704 nblks = dbtoc(nblks); 2705 if (nblks == 0) 2706 return (EXTERROR(EINVAL, "swap device too small")); 2707 2708 sp = malloc(sizeof *sp, M_VMPGDATA, M_WAITOK | M_ZERO); 2709 sp->sw_blist = blist_create(nblks, M_WAITOK); 2710 sp->sw_vp = vp; 2711 sp->sw_id = id; 2712 sp->sw_dev = dev; 2713 sp->sw_nblks = nblks; 2714 sp->sw_used = 0; 2715 sp->sw_strategy = strategy; 2716 sp->sw_close = close; 2717 sp->sw_flags = flags; 2718 2719 /* 2720 * Do not free the first blocks in order to avoid overwriting 2721 * any bsd label at the front of the partition 2722 */ 2723 blist_free(sp->sw_blist, howmany(BBSIZE, PAGE_SIZE), 2724 nblks - howmany(BBSIZE, PAGE_SIZE)); 2725 2726 dvbase = 0; 2727 mtx_lock(&sw_dev_mtx); 2728 TAILQ_FOREACH(tsp, &swtailq, sw_list) { 2729 if (tsp->sw_end >= dvbase) { 2730 /* 2731 * We put one uncovered page between the devices 2732 * in order to definitively prevent any cross-device 2733 * I/O requests 2734 */ 2735 dvbase = tsp->sw_end + 1; 2736 } 2737 } 2738 sp->sw_first = dvbase; 2739 sp->sw_end = dvbase + nblks; 2740 TAILQ_INSERT_TAIL(&swtailq, sp, sw_list); 2741 nswapdev++; 2742 swap_pager_avail += nblks - howmany(BBSIZE, PAGE_SIZE); 2743 swap_total += nblks; 2744 swapon_check_swzone(); 2745 swp_sizecheck(); 2746 mtx_unlock(&sw_dev_mtx); 2747 EVENTHANDLER_INVOKE(swapon, sp); 2748 2749 return (0); 2750 } 2751 2752 /* 2753 * SYSCALL: swapoff(devname) 2754 * 2755 * Disable swapping on the given device. 2756 * 2757 * XXX: Badly designed system call: it should use a device index 2758 * rather than filename as specification. We keep sw_vp around 2759 * only to make this work. 2760 */ 2761 static int 2762 kern_swapoff(struct thread *td, const char *name, enum uio_seg name_seg, 2763 u_int flags) 2764 { 2765 struct vnode *vp; 2766 struct nameidata nd; 2767 struct swdevt *sp; 2768 int error; 2769 2770 error = priv_check(td, PRIV_SWAPOFF); 2771 if (error != 0) 2772 return (error); 2773 if ((flags & ~(SWAPOFF_FORCE)) != 0) 2774 return (EINVAL); 2775 2776 sx_xlock(&swdev_syscall_lock); 2777 2778 NDINIT(&nd, LOOKUP, FOLLOW | AUDITVNODE1, name_seg, name); 2779 error = namei(&nd); 2780 if (error) 2781 goto done; 2782 NDFREE_PNBUF(&nd); 2783 vp = nd.ni_vp; 2784 2785 mtx_lock(&sw_dev_mtx); 2786 TAILQ_FOREACH(sp, &swtailq, sw_list) { 2787 if (sp->sw_vp == vp) 2788 break; 2789 } 2790 mtx_unlock(&sw_dev_mtx); 2791 if (sp == NULL) { 2792 error = EINVAL; 2793 goto done; 2794 } 2795 error = swapoff_one(sp, td->td_ucred, flags); 2796 done: 2797 sx_xunlock(&swdev_syscall_lock); 2798 return (error); 2799 } 2800 2801 2802 #ifdef COMPAT_FREEBSD13 2803 int 2804 freebsd13_swapoff(struct thread *td, struct freebsd13_swapoff_args *uap) 2805 { 2806 return (kern_swapoff(td, uap->name, UIO_USERSPACE, 0)); 2807 } 2808 #endif 2809 2810 int 2811 sys_swapoff(struct thread *td, struct swapoff_args *uap) 2812 { 2813 return (kern_swapoff(td, uap->name, UIO_USERSPACE, uap->flags)); 2814 } 2815 2816 static int 2817 swapoff_one(struct swdevt *sp, struct ucred *cred, u_int flags) 2818 { 2819 u_long nblks; 2820 #ifdef MAC 2821 int error; 2822 #endif 2823 2824 sx_assert(&swdev_syscall_lock, SA_XLOCKED); 2825 #ifdef MAC 2826 (void) vn_lock(sp->sw_vp, LK_EXCLUSIVE | LK_RETRY); 2827 error = mac_system_check_swapoff(cred, sp->sw_vp); 2828 (void) VOP_UNLOCK(sp->sw_vp); 2829 if (error != 0) 2830 return (error); 2831 #endif 2832 nblks = sp->sw_nblks; 2833 2834 /* 2835 * We can turn off this swap device safely only if the 2836 * available virtual memory in the system will fit the amount 2837 * of data we will have to page back in, plus an epsilon so 2838 * the system doesn't become critically low on swap space. 2839 * The vm_free_count() part does not account e.g. for clean 2840 * pages that can be immediately reclaimed without paging, so 2841 * this is a very rough estimation. 2842 * 2843 * On the other hand, not turning swap off on swapoff_all() 2844 * means that we can lose swap data when filesystems go away, 2845 * which is arguably worse. 2846 */ 2847 if ((flags & SWAPOFF_FORCE) == 0 && 2848 vm_free_count() + swap_pager_avail < nblks + nswap_lowat) 2849 return (ENOMEM); 2850 2851 /* 2852 * Prevent further allocations on this device. 2853 */ 2854 mtx_lock(&sw_dev_mtx); 2855 sp->sw_flags |= SW_CLOSING; 2856 swap_pager_avail -= blist_fill(sp->sw_blist, 0, nblks); 2857 swap_total -= nblks; 2858 mtx_unlock(&sw_dev_mtx); 2859 2860 /* 2861 * Page in the contents of the device and close it. 2862 */ 2863 swap_pager_swapoff(sp); 2864 2865 sp->sw_close(curthread, sp); 2866 mtx_lock(&sw_dev_mtx); 2867 sp->sw_id = NULL; 2868 TAILQ_REMOVE(&swtailq, sp, sw_list); 2869 nswapdev--; 2870 if (nswapdev == 0) 2871 swap_pager_full = swap_pager_almost_full = true; 2872 if (swdevhd == sp) 2873 swdevhd = NULL; 2874 mtx_unlock(&sw_dev_mtx); 2875 blist_destroy(sp->sw_blist); 2876 free(sp, M_VMPGDATA); 2877 return (0); 2878 } 2879 2880 void 2881 swapoff_all(void) 2882 { 2883 struct swdevt *sp, *spt; 2884 const char *devname; 2885 int error; 2886 2887 sx_xlock(&swdev_syscall_lock); 2888 2889 mtx_lock(&sw_dev_mtx); 2890 TAILQ_FOREACH_SAFE(sp, &swtailq, sw_list, spt) { 2891 mtx_unlock(&sw_dev_mtx); 2892 if (vn_isdisk(sp->sw_vp)) 2893 devname = devtoname(sp->sw_vp->v_rdev); 2894 else 2895 devname = "[file]"; 2896 error = swapoff_one(sp, thread0.td_ucred, SWAPOFF_FORCE); 2897 if (error != 0) { 2898 printf("Cannot remove swap device %s (error=%d), " 2899 "skipping.\n", devname, error); 2900 } else if (bootverbose) { 2901 printf("Swap device %s removed.\n", devname); 2902 } 2903 mtx_lock(&sw_dev_mtx); 2904 } 2905 mtx_unlock(&sw_dev_mtx); 2906 2907 sx_xunlock(&swdev_syscall_lock); 2908 } 2909 2910 void 2911 swap_pager_status(int *total, int *used) 2912 { 2913 2914 *total = swap_total; 2915 *used = swap_total - swap_pager_avail - 2916 nswapdev * howmany(BBSIZE, PAGE_SIZE); 2917 } 2918 2919 int 2920 swap_dev_info(int name, struct xswdev *xs, char *devname, size_t len) 2921 { 2922 struct swdevt *sp; 2923 const char *tmp_devname; 2924 int error, n; 2925 2926 n = 0; 2927 error = ENOENT; 2928 mtx_lock(&sw_dev_mtx); 2929 TAILQ_FOREACH(sp, &swtailq, sw_list) { 2930 if (n != name) { 2931 n++; 2932 continue; 2933 } 2934 xs->xsw_version = XSWDEV_VERSION; 2935 xs->xsw_dev = sp->sw_dev; 2936 xs->xsw_flags = sp->sw_flags; 2937 xs->xsw_nblks = sp->sw_nblks; 2938 xs->xsw_used = sp->sw_used; 2939 if (devname != NULL) { 2940 if (vn_isdisk(sp->sw_vp)) 2941 tmp_devname = devtoname(sp->sw_vp->v_rdev); 2942 else 2943 tmp_devname = "[file]"; 2944 strncpy(devname, tmp_devname, len); 2945 } 2946 error = 0; 2947 break; 2948 } 2949 mtx_unlock(&sw_dev_mtx); 2950 return (error); 2951 } 2952 2953 #if defined(COMPAT_FREEBSD11) 2954 #define XSWDEV_VERSION_11 1 2955 struct xswdev11 { 2956 u_int xsw_version; 2957 uint32_t xsw_dev; 2958 int xsw_flags; 2959 int xsw_nblks; 2960 int xsw_used; 2961 }; 2962 #endif 2963 2964 #if defined(__amd64__) && defined(COMPAT_FREEBSD32) 2965 struct xswdev32 { 2966 u_int xsw_version; 2967 u_int xsw_dev1, xsw_dev2; 2968 int xsw_flags; 2969 int xsw_nblks; 2970 int xsw_used; 2971 }; 2972 #endif 2973 2974 static int 2975 sysctl_vm_swap_info(SYSCTL_HANDLER_ARGS) 2976 { 2977 struct xswdev xs; 2978 #if defined(__amd64__) && defined(COMPAT_FREEBSD32) 2979 struct xswdev32 xs32; 2980 #endif 2981 #if defined(COMPAT_FREEBSD11) 2982 struct xswdev11 xs11; 2983 #endif 2984 int error; 2985 2986 if (arg2 != 1) /* name length */ 2987 return (EINVAL); 2988 2989 memset(&xs, 0, sizeof(xs)); 2990 error = swap_dev_info(*(int *)arg1, &xs, NULL, 0); 2991 if (error != 0) 2992 return (error); 2993 #if defined(__amd64__) && defined(COMPAT_FREEBSD32) 2994 if (req->oldlen == sizeof(xs32)) { 2995 memset(&xs32, 0, sizeof(xs32)); 2996 xs32.xsw_version = XSWDEV_VERSION; 2997 xs32.xsw_dev1 = xs.xsw_dev; 2998 xs32.xsw_dev2 = xs.xsw_dev >> 32; 2999 xs32.xsw_flags = xs.xsw_flags; 3000 xs32.xsw_nblks = xs.xsw_nblks; 3001 xs32.xsw_used = xs.xsw_used; 3002 error = SYSCTL_OUT(req, &xs32, sizeof(xs32)); 3003 return (error); 3004 } 3005 #endif 3006 #if defined(COMPAT_FREEBSD11) 3007 if (req->oldlen == sizeof(xs11)) { 3008 memset(&xs11, 0, sizeof(xs11)); 3009 xs11.xsw_version = XSWDEV_VERSION_11; 3010 xs11.xsw_dev = xs.xsw_dev; /* truncation */ 3011 xs11.xsw_flags = xs.xsw_flags; 3012 xs11.xsw_nblks = xs.xsw_nblks; 3013 xs11.xsw_used = xs.xsw_used; 3014 error = SYSCTL_OUT(req, &xs11, sizeof(xs11)); 3015 return (error); 3016 } 3017 #endif 3018 error = SYSCTL_OUT(req, &xs, sizeof(xs)); 3019 return (error); 3020 } 3021 3022 SYSCTL_INT(_vm, OID_AUTO, nswapdev, CTLFLAG_RD, &nswapdev, 0, 3023 "Number of swap devices"); 3024 SYSCTL_NODE(_vm, OID_AUTO, swap_info, CTLFLAG_RD | CTLFLAG_MPSAFE, 3025 sysctl_vm_swap_info, 3026 "Swap statistics by device"); 3027 3028 /* 3029 * Count the approximate swap usage in pages for a vmspace. The 3030 * shadowed or not yet copied on write swap blocks are not accounted. 3031 * The map must be locked. 3032 */ 3033 long 3034 vmspace_swap_count(struct vmspace *vmspace) 3035 { 3036 struct pctrie_iter blks; 3037 vm_map_t map; 3038 vm_map_entry_t cur; 3039 vm_object_t object; 3040 struct swblk *sb; 3041 vm_pindex_t e, pi; 3042 long count; 3043 int i, limit, start; 3044 3045 map = &vmspace->vm_map; 3046 count = 0; 3047 3048 VM_MAP_ENTRY_FOREACH(cur, map) { 3049 if ((cur->eflags & MAP_ENTRY_IS_SUB_MAP) != 0) 3050 continue; 3051 object = cur->object.vm_object; 3052 if (object == NULL || (object->flags & OBJ_SWAP) == 0) 3053 continue; 3054 VM_OBJECT_RLOCK(object); 3055 if ((object->flags & OBJ_SWAP) == 0) 3056 goto unlock; 3057 pi = OFF_TO_IDX(cur->offset); 3058 e = pi + OFF_TO_IDX(cur->end - cur->start); 3059 for (sb = swblk_iter_limit_init(&blks, object, pi, e), 3060 start = swblk_start(sb, pi); 3061 sb != NULL; sb = swblk_iter_next(&blks), start = 0) { 3062 limit = MIN(e - blks.index, SWAP_META_PAGES); 3063 for (i = start; i < limit; i++) { 3064 if (sb->d[i] != SWAPBLK_NONE) 3065 count++; 3066 } 3067 } 3068 unlock: 3069 VM_OBJECT_RUNLOCK(object); 3070 } 3071 return (count); 3072 } 3073 3074 /* 3075 * GEOM backend 3076 * 3077 * Swapping onto disk devices. 3078 * 3079 */ 3080 3081 static g_orphan_t swapgeom_orphan; 3082 3083 static struct g_class g_swap_class = { 3084 .name = "SWAP", 3085 .version = G_VERSION, 3086 .orphan = swapgeom_orphan, 3087 }; 3088 3089 DECLARE_GEOM_CLASS(g_swap_class, g_class); 3090 3091 static void 3092 swapgeom_close_ev(void *arg, int flags) 3093 { 3094 struct g_consumer *cp; 3095 3096 cp = arg; 3097 g_access(cp, -1, -1, 0); 3098 g_detach(cp); 3099 g_destroy_consumer(cp); 3100 } 3101 3102 /* 3103 * Add a reference to the g_consumer for an inflight transaction. 3104 */ 3105 static void 3106 swapgeom_acquire(struct g_consumer *cp) 3107 { 3108 3109 mtx_assert(&sw_dev_mtx, MA_OWNED); 3110 cp->index++; 3111 } 3112 3113 /* 3114 * Remove a reference from the g_consumer. Post a close event if all 3115 * references go away, since the function might be called from the 3116 * biodone context. 3117 */ 3118 static void 3119 swapgeom_release(struct g_consumer *cp, struct swdevt *sp) 3120 { 3121 3122 mtx_assert(&sw_dev_mtx, MA_OWNED); 3123 cp->index--; 3124 if (cp->index == 0) { 3125 if (g_post_event(swapgeom_close_ev, cp, M_NOWAIT, NULL) == 0) 3126 sp->sw_id = NULL; 3127 } 3128 } 3129 3130 static void 3131 swapgeom_done(struct bio *bp2) 3132 { 3133 struct swdevt *sp; 3134 struct buf *bp; 3135 struct g_consumer *cp; 3136 3137 bp = bp2->bio_caller2; 3138 cp = bp2->bio_from; 3139 bp->b_ioflags = bp2->bio_flags; 3140 if (bp2->bio_error) 3141 bp->b_ioflags |= BIO_ERROR; 3142 bp->b_resid = bp->b_bcount - bp2->bio_completed; 3143 bp->b_error = bp2->bio_error; 3144 bp->b_caller1 = NULL; 3145 bufdone(bp); 3146 sp = bp2->bio_caller1; 3147 mtx_lock(&sw_dev_mtx); 3148 swapgeom_release(cp, sp); 3149 mtx_unlock(&sw_dev_mtx); 3150 g_destroy_bio(bp2); 3151 } 3152 3153 static void 3154 swapgeom_strategy(struct buf *bp, struct swdevt *sp) 3155 { 3156 struct bio *bio; 3157 struct g_consumer *cp; 3158 3159 mtx_lock(&sw_dev_mtx); 3160 cp = sp->sw_id; 3161 if (cp == NULL) { 3162 mtx_unlock(&sw_dev_mtx); 3163 bp->b_error = ENXIO; 3164 bp->b_ioflags |= BIO_ERROR; 3165 bufdone(bp); 3166 return; 3167 } 3168 swapgeom_acquire(cp); 3169 mtx_unlock(&sw_dev_mtx); 3170 if (bp->b_iocmd == BIO_WRITE) 3171 bio = g_new_bio(); 3172 else 3173 bio = g_alloc_bio(); 3174 if (bio == NULL) { 3175 mtx_lock(&sw_dev_mtx); 3176 swapgeom_release(cp, sp); 3177 mtx_unlock(&sw_dev_mtx); 3178 bp->b_error = ENOMEM; 3179 bp->b_ioflags |= BIO_ERROR; 3180 printf("swap_pager: cannot allocate bio\n"); 3181 bufdone(bp); 3182 return; 3183 } 3184 3185 bp->b_caller1 = bio; 3186 bio->bio_caller1 = sp; 3187 bio->bio_caller2 = bp; 3188 bio->bio_cmd = bp->b_iocmd; 3189 bio->bio_offset = (bp->b_blkno - sp->sw_first) * PAGE_SIZE; 3190 bio->bio_length = bp->b_bcount; 3191 bio->bio_done = swapgeom_done; 3192 bio->bio_flags |= BIO_SWAP; 3193 if (!buf_mapped(bp)) { 3194 bio->bio_ma = bp->b_pages; 3195 bio->bio_data = unmapped_buf; 3196 bio->bio_ma_offset = (vm_offset_t)bp->b_offset & PAGE_MASK; 3197 bio->bio_ma_n = bp->b_npages; 3198 bio->bio_flags |= BIO_UNMAPPED; 3199 } else { 3200 bio->bio_data = bp->b_data; 3201 bio->bio_ma = NULL; 3202 } 3203 g_io_request(bio, cp); 3204 return; 3205 } 3206 3207 static void 3208 swapgeom_orphan(struct g_consumer *cp) 3209 { 3210 struct swdevt *sp; 3211 int destroy; 3212 3213 mtx_lock(&sw_dev_mtx); 3214 TAILQ_FOREACH(sp, &swtailq, sw_list) { 3215 if (sp->sw_id == cp) { 3216 sp->sw_flags |= SW_CLOSING; 3217 break; 3218 } 3219 } 3220 /* 3221 * Drop reference we were created with. Do directly since we're in a 3222 * special context where we don't have to queue the call to 3223 * swapgeom_close_ev(). 3224 */ 3225 cp->index--; 3226 destroy = ((sp != NULL) && (cp->index == 0)); 3227 if (destroy) 3228 sp->sw_id = NULL; 3229 mtx_unlock(&sw_dev_mtx); 3230 if (destroy) 3231 swapgeom_close_ev(cp, 0); 3232 } 3233 3234 static void 3235 swapgeom_close(struct thread *td, struct swdevt *sw) 3236 { 3237 struct g_consumer *cp; 3238 3239 mtx_lock(&sw_dev_mtx); 3240 cp = sw->sw_id; 3241 sw->sw_id = NULL; 3242 mtx_unlock(&sw_dev_mtx); 3243 3244 /* 3245 * swapgeom_close() may be called from the biodone context, 3246 * where we cannot perform topology changes. Delegate the 3247 * work to the events thread. 3248 */ 3249 if (cp != NULL) 3250 g_waitfor_event(swapgeom_close_ev, cp, M_WAITOK, NULL); 3251 } 3252 3253 static int 3254 swapongeom_locked(struct cdev *dev, struct vnode *vp) 3255 { 3256 struct g_provider *pp; 3257 struct g_consumer *cp; 3258 static struct g_geom *gp; 3259 struct swdevt *sp; 3260 u_long nblks; 3261 int error; 3262 3263 pp = g_dev_getprovider(dev); 3264 if (pp == NULL) 3265 return (ENODEV); 3266 mtx_lock(&sw_dev_mtx); 3267 TAILQ_FOREACH(sp, &swtailq, sw_list) { 3268 cp = sp->sw_id; 3269 if (cp != NULL && cp->provider == pp) { 3270 mtx_unlock(&sw_dev_mtx); 3271 return (EBUSY); 3272 } 3273 } 3274 mtx_unlock(&sw_dev_mtx); 3275 if (gp == NULL) 3276 gp = g_new_geomf(&g_swap_class, "swap"); 3277 cp = g_new_consumer(gp); 3278 cp->index = 1; /* Number of active I/Os, plus one for being active. */ 3279 cp->flags |= G_CF_DIRECT_SEND | G_CF_DIRECT_RECEIVE; 3280 g_attach(cp, pp); 3281 3282 /* 3283 * XXX: Every time you think you can improve the margin for 3284 * footshooting, somebody depends on the ability to do so: 3285 * savecore(8) wants to write to our swapdev so we cannot 3286 * set an exclusive count :-( 3287 */ 3288 error = g_access(cp, 1, 1, 0); 3289 3290 if (error == 0) { 3291 nblks = pp->mediasize / DEV_BSIZE; 3292 error = swaponsomething(vp, cp, nblks, swapgeom_strategy, 3293 swapgeom_close, dev2udev(dev), 3294 (pp->flags & G_PF_ACCEPT_UNMAPPED) != 0 ? SW_UNMAPPED : 0); 3295 if (error != 0) 3296 g_access(cp, -1, -1, 0); 3297 } 3298 if (error != 0) { 3299 g_detach(cp); 3300 g_destroy_consumer(cp); 3301 } 3302 return (error); 3303 } 3304 3305 static int 3306 swapongeom(struct vnode *vp) 3307 { 3308 int error; 3309 3310 ASSERT_VOP_ELOCKED(vp, "swapongeom"); 3311 if (vp->v_type != VCHR || VN_IS_DOOMED(vp)) { 3312 error = ENOENT; 3313 } else { 3314 g_topology_lock(); 3315 error = swapongeom_locked(vp->v_rdev, vp); 3316 g_topology_unlock(); 3317 } 3318 return (error); 3319 } 3320 3321 /* 3322 * VNODE backend 3323 * 3324 * This is used mainly for network filesystem (read: probably only tested 3325 * with NFS) swapfiles. 3326 * 3327 */ 3328 3329 static void 3330 swapdev_strategy(struct buf *bp, struct swdevt *sp) 3331 { 3332 struct vnode *vp2; 3333 3334 bp->b_blkno = ctodb(bp->b_blkno - sp->sw_first); 3335 3336 vp2 = sp->sw_id; 3337 vhold(vp2); 3338 if (bp->b_iocmd == BIO_WRITE) { 3339 vn_lock(vp2, LK_EXCLUSIVE | LK_RETRY); 3340 if (bp->b_bufobj) 3341 bufobj_wdrop(bp->b_bufobj); 3342 bufobj_wref(&vp2->v_bufobj); 3343 } else { 3344 vn_lock(vp2, LK_SHARED | LK_RETRY); 3345 } 3346 if (bp->b_bufobj != &vp2->v_bufobj) 3347 bp->b_bufobj = &vp2->v_bufobj; 3348 bp->b_vp = vp2; 3349 bp->b_iooffset = dbtob(bp->b_blkno); 3350 bstrategy(bp); 3351 VOP_UNLOCK(vp2); 3352 } 3353 3354 static void 3355 swapdev_close(struct thread *td, struct swdevt *sp) 3356 { 3357 struct vnode *vp; 3358 3359 vp = sp->sw_vp; 3360 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY); 3361 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td); 3362 vput(vp); 3363 } 3364 3365 static int 3366 swaponvp(struct thread *td, struct vnode *vp, u_long nblks) 3367 { 3368 struct swdevt *sp; 3369 int error; 3370 3371 ASSERT_VOP_ELOCKED(vp, "swaponvp"); 3372 if (nblks == 0) 3373 return (ENXIO); 3374 mtx_lock(&sw_dev_mtx); 3375 TAILQ_FOREACH(sp, &swtailq, sw_list) { 3376 if (sp->sw_id == vp) { 3377 mtx_unlock(&sw_dev_mtx); 3378 return (EBUSY); 3379 } 3380 } 3381 mtx_unlock(&sw_dev_mtx); 3382 3383 #ifdef MAC 3384 error = mac_system_check_swapon(td->td_ucred, vp); 3385 if (error == 0) 3386 #endif 3387 error = VOP_OPEN(vp, FREAD | FWRITE, td->td_ucred, td, NULL); 3388 if (error != 0) 3389 return (error); 3390 3391 error = swaponsomething(vp, vp, nblks, swapdev_strategy, swapdev_close, 3392 NODEV, 0); 3393 if (error != 0) 3394 VOP_CLOSE(vp, FREAD | FWRITE, td->td_ucred, td); 3395 return (error); 3396 } 3397 3398 static int 3399 sysctl_swap_async_max(SYSCTL_HANDLER_ARGS) 3400 { 3401 int error, new, n; 3402 3403 new = nsw_wcount_async_max; 3404 error = sysctl_handle_int(oidp, &new, 0, req); 3405 if (error != 0 || req->newptr == NULL) 3406 return (error); 3407 3408 if (new > nswbuf / 2 || new < 1) 3409 return (EINVAL); 3410 3411 mtx_lock(&swbuf_mtx); 3412 while (nsw_wcount_async_max != new) { 3413 /* 3414 * Adjust difference. If the current async count is too low, 3415 * we will need to sqeeze our update slowly in. Sleep with a 3416 * higher priority than getpbuf() to finish faster. 3417 */ 3418 n = new - nsw_wcount_async_max; 3419 if (nsw_wcount_async + n >= 0) { 3420 nsw_wcount_async += n; 3421 nsw_wcount_async_max += n; 3422 wakeup(&nsw_wcount_async); 3423 } else { 3424 nsw_wcount_async_max -= nsw_wcount_async; 3425 nsw_wcount_async = 0; 3426 msleep(&nsw_wcount_async, &swbuf_mtx, PSWP, 3427 "swpsysctl", 0); 3428 } 3429 } 3430 mtx_unlock(&swbuf_mtx); 3431 3432 return (0); 3433 } 3434 3435 static void 3436 swap_pager_update_writecount(vm_object_t object, vm_offset_t start, 3437 vm_offset_t end) 3438 { 3439 3440 VM_OBJECT_WLOCK(object); 3441 KASSERT((object->flags & OBJ_ANON) == 0, 3442 ("Splittable object with writecount")); 3443 object->un_pager.swp.writemappings += (vm_ooffset_t)end - start; 3444 VM_OBJECT_WUNLOCK(object); 3445 } 3446 3447 static void 3448 swap_pager_release_writecount(vm_object_t object, vm_offset_t start, 3449 vm_offset_t end) 3450 { 3451 3452 VM_OBJECT_WLOCK(object); 3453 KASSERT((object->flags & OBJ_ANON) == 0, 3454 ("Splittable object with writecount")); 3455 KASSERT(object->un_pager.swp.writemappings >= (vm_ooffset_t)end - start, 3456 ("swap obj %p writecount %jx dec %jx", object, 3457 (uintmax_t)object->un_pager.swp.writemappings, 3458 (uintmax_t)((vm_ooffset_t)end - start))); 3459 object->un_pager.swp.writemappings -= (vm_ooffset_t)end - start; 3460 VM_OBJECT_WUNLOCK(object); 3461 } 3462