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