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