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