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