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