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