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