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