1 /* $NetBSD: uvm_swap.c,v 1.197 2020/07/09 05:57:15 skrll Exp $ */ 2 3 /* 4 * Copyright (c) 1995, 1996, 1997, 2009 Matthew R. Green 5 * All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 26 * SUCH DAMAGE. 27 * 28 * from: NetBSD: vm_swap.c,v 1.52 1997/12/02 13:47:37 pk Exp 29 * from: Id: uvm_swap.c,v 1.1.2.42 1998/02/02 20:38:06 chuck Exp 30 */ 31 32 #include <sys/cdefs.h> 33 __KERNEL_RCSID(0, "$NetBSD: uvm_swap.c,v 1.197 2020/07/09 05:57:15 skrll Exp $"); 34 35 #include "opt_uvmhist.h" 36 #include "opt_compat_netbsd.h" 37 #include "opt_ddb.h" 38 39 #include <sys/param.h> 40 #include <sys/systm.h> 41 #include <sys/atomic.h> 42 #include <sys/buf.h> 43 #include <sys/bufq.h> 44 #include <sys/conf.h> 45 #include <sys/cprng.h> 46 #include <sys/proc.h> 47 #include <sys/namei.h> 48 #include <sys/disklabel.h> 49 #include <sys/errno.h> 50 #include <sys/kernel.h> 51 #include <sys/vnode.h> 52 #include <sys/file.h> 53 #include <sys/vmem.h> 54 #include <sys/blist.h> 55 #include <sys/mount.h> 56 #include <sys/pool.h> 57 #include <sys/kmem.h> 58 #include <sys/syscallargs.h> 59 #include <sys/swap.h> 60 #include <sys/kauth.h> 61 #include <sys/sysctl.h> 62 #include <sys/workqueue.h> 63 64 #include <uvm/uvm.h> 65 66 #include <miscfs/specfs/specdev.h> 67 68 #include <crypto/aes/aes.h> 69 70 /* 71 * uvm_swap.c: manage configuration and i/o to swap space. 72 */ 73 74 /* 75 * swap space is managed in the following way: 76 * 77 * each swap partition or file is described by a "swapdev" structure. 78 * each "swapdev" structure contains a "swapent" structure which contains 79 * information that is passed up to the user (via system calls). 80 * 81 * each swap partition is assigned a "priority" (int) which controls 82 * swap parition usage. 83 * 84 * the system maintains a global data structure describing all swap 85 * partitions/files. there is a sorted LIST of "swappri" structures 86 * which describe "swapdev"'s at that priority. this LIST is headed 87 * by the "swap_priority" global var. each "swappri" contains a 88 * TAILQ of "swapdev" structures at that priority. 89 * 90 * locking: 91 * - swap_syscall_lock (krwlock_t): this lock serializes the swapctl 92 * system call and prevents the swap priority list from changing 93 * while we are in the middle of a system call (e.g. SWAP_STATS). 94 * - uvm_swap_data_lock (kmutex_t): this lock protects all swap data 95 * structures including the priority list, the swapdev structures, 96 * and the swapmap arena. 97 * 98 * each swap device has the following info: 99 * - swap device in use (could be disabled, preventing future use) 100 * - swap enabled (allows new allocations on swap) 101 * - map info in /dev/drum 102 * - vnode pointer 103 * for swap files only: 104 * - block size 105 * - max byte count in buffer 106 * - buffer 107 * 108 * userland controls and configures swap with the swapctl(2) system call. 109 * the sys_swapctl performs the following operations: 110 * [1] SWAP_NSWAP: returns the number of swap devices currently configured 111 * [2] SWAP_STATS: given a pointer to an array of swapent structures 112 * (passed in via "arg") of a size passed in via "misc" ... we load 113 * the current swap config into the array. The actual work is done 114 * in the uvm_swap_stats() function. 115 * [3] SWAP_ON: given a pathname in arg (could be device or file) and a 116 * priority in "misc", start swapping on it. 117 * [4] SWAP_OFF: as SWAP_ON, but stops swapping to a device 118 * [5] SWAP_CTL: changes the priority of a swap device (new priority in 119 * "misc") 120 */ 121 122 /* 123 * swapdev: describes a single swap partition/file 124 * 125 * note the following should be true: 126 * swd_inuse <= swd_nblks [number of blocks in use is <= total blocks] 127 * swd_nblks <= swd_mapsize [because mapsize includes miniroot+disklabel] 128 */ 129 struct swapdev { 130 dev_t swd_dev; /* device id */ 131 int swd_flags; /* flags:inuse/enable/fake */ 132 int swd_priority; /* our priority */ 133 int swd_nblks; /* blocks in this device */ 134 char *swd_path; /* saved pathname of device */ 135 int swd_pathlen; /* length of pathname */ 136 int swd_npages; /* #pages we can use */ 137 int swd_npginuse; /* #pages in use */ 138 int swd_npgbad; /* #pages bad */ 139 int swd_drumoffset; /* page0 offset in drum */ 140 int swd_drumsize; /* #pages in drum */ 141 blist_t swd_blist; /* blist for this swapdev */ 142 struct vnode *swd_vp; /* backing vnode */ 143 TAILQ_ENTRY(swapdev) swd_next; /* priority tailq */ 144 145 int swd_bsize; /* blocksize (bytes) */ 146 int swd_maxactive; /* max active i/o reqs */ 147 struct bufq_state *swd_tab; /* buffer list */ 148 int swd_active; /* number of active buffers */ 149 150 volatile uint32_t *swd_encmap; /* bitmap of encrypted slots */ 151 struct aesenc swd_enckey; /* AES key expanded for enc */ 152 struct aesdec swd_deckey; /* AES key expanded for dec */ 153 bool swd_encinit; /* true if keys initialized */ 154 }; 155 156 /* 157 * swap device priority entry; the list is kept sorted on `spi_priority'. 158 */ 159 struct swappri { 160 int spi_priority; /* priority */ 161 TAILQ_HEAD(spi_swapdev, swapdev) spi_swapdev; 162 /* tailq of swapdevs at this priority */ 163 LIST_ENTRY(swappri) spi_swappri; /* global list of pri's */ 164 }; 165 166 /* 167 * The following two structures are used to keep track of data transfers 168 * on swap devices associated with regular files. 169 * NOTE: this code is more or less a copy of vnd.c; we use the same 170 * structure names here to ease porting.. 171 */ 172 struct vndxfer { 173 struct buf *vx_bp; /* Pointer to parent buffer */ 174 struct swapdev *vx_sdp; 175 int vx_error; 176 int vx_pending; /* # of pending aux buffers */ 177 int vx_flags; 178 #define VX_BUSY 1 179 #define VX_DEAD 2 180 }; 181 182 struct vndbuf { 183 struct buf vb_buf; 184 struct vndxfer *vb_xfer; 185 }; 186 187 /* 188 * We keep a of pool vndbuf's and vndxfer structures. 189 */ 190 static struct pool vndxfer_pool, vndbuf_pool; 191 192 /* 193 * local variables 194 */ 195 static vmem_t *swapmap; /* controls the mapping of /dev/drum */ 196 197 /* list of all active swap devices [by priority] */ 198 LIST_HEAD(swap_priority, swappri); 199 static struct swap_priority swap_priority; 200 201 /* locks */ 202 static kmutex_t uvm_swap_data_lock __cacheline_aligned; 203 static krwlock_t swap_syscall_lock; 204 205 /* workqueue and use counter for swap to regular files */ 206 static int sw_reg_count = 0; 207 static struct workqueue *sw_reg_workqueue; 208 209 /* tuneables */ 210 u_int uvm_swapisfull_factor = 99; 211 bool uvm_swap_encrypt = false; 212 213 /* 214 * prototypes 215 */ 216 static struct swapdev *swapdrum_getsdp(int); 217 218 static struct swapdev *swaplist_find(struct vnode *, bool); 219 static void swaplist_insert(struct swapdev *, 220 struct swappri *, int); 221 static void swaplist_trim(void); 222 223 static int swap_on(struct lwp *, struct swapdev *); 224 static int swap_off(struct lwp *, struct swapdev *); 225 226 static void sw_reg_strategy(struct swapdev *, struct buf *, int); 227 static void sw_reg_biodone(struct buf *); 228 static void sw_reg_iodone(struct work *wk, void *dummy); 229 static void sw_reg_start(struct swapdev *); 230 231 static int uvm_swap_io(struct vm_page **, int, int, int); 232 233 static void uvm_swap_genkey(struct swapdev *); 234 static void uvm_swap_encryptpage(struct swapdev *, void *, int); 235 static void uvm_swap_decryptpage(struct swapdev *, void *, int); 236 237 static size_t 238 encmap_size(size_t npages) 239 { 240 struct swapdev *sdp; 241 const size_t bytesperword = sizeof(sdp->swd_encmap[0]); 242 const size_t bitsperword = NBBY * bytesperword; 243 const size_t nbits = npages; /* one bit for each page */ 244 const size_t nwords = howmany(nbits, bitsperword); 245 const size_t nbytes = nwords * bytesperword; 246 247 return nbytes; 248 } 249 250 /* 251 * uvm_swap_init: init the swap system data structures and locks 252 * 253 * => called at boot time from init_main.c after the filesystems 254 * are brought up (which happens after uvm_init()) 255 */ 256 void 257 uvm_swap_init(void) 258 { 259 UVMHIST_FUNC(__func__); 260 261 UVMHIST_CALLED(pdhist); 262 /* 263 * first, init the swap list, its counter, and its lock. 264 * then get a handle on the vnode for /dev/drum by using 265 * the its dev_t number ("swapdev", from MD conf.c). 266 */ 267 268 LIST_INIT(&swap_priority); 269 uvmexp.nswapdev = 0; 270 rw_init(&swap_syscall_lock); 271 mutex_init(&uvm_swap_data_lock, MUTEX_DEFAULT, IPL_NONE); 272 273 if (bdevvp(swapdev, &swapdev_vp)) 274 panic("%s: can't get vnode for swap device", __func__); 275 if (vn_lock(swapdev_vp, LK_EXCLUSIVE | LK_RETRY)) 276 panic("%s: can't lock swap device", __func__); 277 if (VOP_OPEN(swapdev_vp, FREAD | FWRITE, NOCRED)) 278 panic("%s: can't open swap device", __func__); 279 VOP_UNLOCK(swapdev_vp); 280 281 /* 282 * create swap block resource map to map /dev/drum. the range 283 * from 1 to INT_MAX allows 2 gigablocks of swap space. note 284 * that block 0 is reserved (used to indicate an allocation 285 * failure, or no allocation). 286 */ 287 swapmap = vmem_create("swapmap", 1, INT_MAX - 1, 1, NULL, NULL, NULL, 0, 288 VM_NOSLEEP, IPL_NONE); 289 if (swapmap == 0) { 290 panic("%s: vmem_create failed", __func__); 291 } 292 293 pool_init(&vndxfer_pool, sizeof(struct vndxfer), 0, 0, 0, "swp vnx", 294 NULL, IPL_BIO); 295 pool_init(&vndbuf_pool, sizeof(struct vndbuf), 0, 0, 0, "swp vnd", 296 NULL, IPL_BIO); 297 298 UVMHIST_LOG(pdhist, "<- done", 0, 0, 0, 0); 299 } 300 301 /* 302 * swaplist functions: functions that operate on the list of swap 303 * devices on the system. 304 */ 305 306 /* 307 * swaplist_insert: insert swap device "sdp" into the global list 308 * 309 * => caller must hold both swap_syscall_lock and uvm_swap_data_lock 310 * => caller must provide a newly allocated swappri structure (we will 311 * FREE it if we don't need it... this it to prevent allocation 312 * blocking here while adding swap) 313 */ 314 static void 315 swaplist_insert(struct swapdev *sdp, struct swappri *newspp, int priority) 316 { 317 struct swappri *spp, *pspp; 318 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 319 320 KASSERT(rw_write_held(&swap_syscall_lock)); 321 KASSERT(mutex_owned(&uvm_swap_data_lock)); 322 323 /* 324 * find entry at or after which to insert the new device. 325 */ 326 pspp = NULL; 327 LIST_FOREACH(spp, &swap_priority, spi_swappri) { 328 if (priority <= spp->spi_priority) 329 break; 330 pspp = spp; 331 } 332 333 /* 334 * new priority? 335 */ 336 if (spp == NULL || spp->spi_priority != priority) { 337 spp = newspp; /* use newspp! */ 338 UVMHIST_LOG(pdhist, "created new swappri = %jd", 339 priority, 0, 0, 0); 340 341 spp->spi_priority = priority; 342 TAILQ_INIT(&spp->spi_swapdev); 343 344 if (pspp) 345 LIST_INSERT_AFTER(pspp, spp, spi_swappri); 346 else 347 LIST_INSERT_HEAD(&swap_priority, spp, spi_swappri); 348 } else { 349 /* we don't need a new priority structure, free it */ 350 kmem_free(newspp, sizeof(*newspp)); 351 } 352 353 /* 354 * priority found (or created). now insert on the priority's 355 * tailq list and bump the total number of swapdevs. 356 */ 357 sdp->swd_priority = priority; 358 TAILQ_INSERT_TAIL(&spp->spi_swapdev, sdp, swd_next); 359 uvmexp.nswapdev++; 360 } 361 362 /* 363 * swaplist_find: find and optionally remove a swap device from the 364 * global list. 365 * 366 * => caller must hold both swap_syscall_lock and uvm_swap_data_lock 367 * => we return the swapdev we found (and removed) 368 */ 369 static struct swapdev * 370 swaplist_find(struct vnode *vp, bool remove) 371 { 372 struct swapdev *sdp; 373 struct swappri *spp; 374 375 KASSERT(rw_lock_held(&swap_syscall_lock)); 376 KASSERT(remove ? rw_write_held(&swap_syscall_lock) : 1); 377 KASSERT(mutex_owned(&uvm_swap_data_lock)); 378 379 /* 380 * search the lists for the requested vp 381 */ 382 383 LIST_FOREACH(spp, &swap_priority, spi_swappri) { 384 TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) { 385 if (sdp->swd_vp == vp) { 386 if (remove) { 387 TAILQ_REMOVE(&spp->spi_swapdev, 388 sdp, swd_next); 389 uvmexp.nswapdev--; 390 } 391 return(sdp); 392 } 393 } 394 } 395 return (NULL); 396 } 397 398 /* 399 * swaplist_trim: scan priority list for empty priority entries and kill 400 * them. 401 * 402 * => caller must hold both swap_syscall_lock and uvm_swap_data_lock 403 */ 404 static void 405 swaplist_trim(void) 406 { 407 struct swappri *spp, *nextspp; 408 409 KASSERT(rw_write_held(&swap_syscall_lock)); 410 KASSERT(mutex_owned(&uvm_swap_data_lock)); 411 412 LIST_FOREACH_SAFE(spp, &swap_priority, spi_swappri, nextspp) { 413 if (!TAILQ_EMPTY(&spp->spi_swapdev)) 414 continue; 415 LIST_REMOVE(spp, spi_swappri); 416 kmem_free(spp, sizeof(*spp)); 417 } 418 } 419 420 /* 421 * swapdrum_getsdp: given a page offset in /dev/drum, convert it back 422 * to the "swapdev" that maps that section of the drum. 423 * 424 * => each swapdev takes one big contig chunk of the drum 425 * => caller must hold uvm_swap_data_lock 426 */ 427 static struct swapdev * 428 swapdrum_getsdp(int pgno) 429 { 430 struct swapdev *sdp; 431 struct swappri *spp; 432 433 KASSERT(mutex_owned(&uvm_swap_data_lock)); 434 435 LIST_FOREACH(spp, &swap_priority, spi_swappri) { 436 TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) { 437 if (sdp->swd_flags & SWF_FAKE) 438 continue; 439 if (pgno >= sdp->swd_drumoffset && 440 pgno < (sdp->swd_drumoffset + sdp->swd_drumsize)) { 441 return sdp; 442 } 443 } 444 } 445 return NULL; 446 } 447 448 /* 449 * swapdrum_sdp_is: true iff the swap device for pgno is sdp 450 * 451 * => for use in positive assertions only; result is not stable 452 */ 453 static bool __debugused 454 swapdrum_sdp_is(int pgno, struct swapdev *sdp) 455 { 456 bool result; 457 458 mutex_enter(&uvm_swap_data_lock); 459 result = swapdrum_getsdp(pgno) == sdp; 460 mutex_exit(&uvm_swap_data_lock); 461 462 return result; 463 } 464 465 void swapsys_lock(krw_t op) 466 { 467 rw_enter(&swap_syscall_lock, op); 468 } 469 470 void swapsys_unlock(void) 471 { 472 rw_exit(&swap_syscall_lock); 473 } 474 475 static void 476 swapent_cvt(struct swapent *se, const struct swapdev *sdp, int inuse) 477 { 478 se->se_dev = sdp->swd_dev; 479 se->se_flags = sdp->swd_flags; 480 se->se_nblks = sdp->swd_nblks; 481 se->se_inuse = inuse; 482 se->se_priority = sdp->swd_priority; 483 KASSERT(sdp->swd_pathlen < sizeof(se->se_path)); 484 strcpy(se->se_path, sdp->swd_path); 485 } 486 487 int (*uvm_swap_stats13)(const struct sys_swapctl_args *, register_t *) = 488 (void *)enosys; 489 int (*uvm_swap_stats50)(const struct sys_swapctl_args *, register_t *) = 490 (void *)enosys; 491 492 /* 493 * sys_swapctl: main entry point for swapctl(2) system call 494 * [with two helper functions: swap_on and swap_off] 495 */ 496 int 497 sys_swapctl(struct lwp *l, const struct sys_swapctl_args *uap, register_t *retval) 498 { 499 /* { 500 syscallarg(int) cmd; 501 syscallarg(void *) arg; 502 syscallarg(int) misc; 503 } */ 504 struct vnode *vp; 505 struct nameidata nd; 506 struct swappri *spp; 507 struct swapdev *sdp; 508 #define SWAP_PATH_MAX (PATH_MAX + 1) 509 char *userpath; 510 size_t len = 0; 511 int error; 512 int priority; 513 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 514 515 /* 516 * we handle the non-priv NSWAP and STATS request first. 517 * 518 * SWAP_NSWAP: return number of config'd swap devices 519 * [can also be obtained with uvmexp sysctl] 520 */ 521 if (SCARG(uap, cmd) == SWAP_NSWAP) { 522 const int nswapdev = uvmexp.nswapdev; 523 UVMHIST_LOG(pdhist, "<- done SWAP_NSWAP=%jd", nswapdev, 524 0, 0, 0); 525 *retval = nswapdev; 526 return 0; 527 } 528 529 userpath = kmem_alloc(SWAP_PATH_MAX, KM_SLEEP); 530 531 /* 532 * ensure serialized syscall access by grabbing the swap_syscall_lock 533 */ 534 rw_enter(&swap_syscall_lock, RW_WRITER); 535 536 /* 537 * SWAP_STATS: get stats on current # of configured swap devs 538 * 539 * note that the swap_priority list can't change as long 540 * as we are holding the swap_syscall_lock. we don't want 541 * to grab the uvm_swap_data_lock because we may fault&sleep during 542 * copyout() and we don't want to be holding that lock then! 543 */ 544 switch (SCARG(uap, cmd)) { 545 case SWAP_STATS13: 546 error = (*uvm_swap_stats13)(uap, retval); 547 goto out; 548 case SWAP_STATS50: 549 error = (*uvm_swap_stats50)(uap, retval); 550 goto out; 551 case SWAP_STATS: 552 error = uvm_swap_stats(SCARG(uap, arg), SCARG(uap, misc), 553 NULL, sizeof(struct swapent), retval); 554 UVMHIST_LOG(pdhist, "<- done SWAP_STATS", 0, 0, 0, 0); 555 goto out; 556 557 case SWAP_GETDUMPDEV: 558 error = copyout(&dumpdev, SCARG(uap, arg), sizeof(dumpdev)); 559 goto out; 560 default: 561 break; 562 } 563 564 /* 565 * all other requests require superuser privs. verify. 566 */ 567 if ((error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_SWAPCTL, 568 0, NULL, NULL, NULL))) 569 goto out; 570 571 if (SCARG(uap, cmd) == SWAP_DUMPOFF) { 572 /* drop the current dump device */ 573 dumpdev = NODEV; 574 dumpcdev = NODEV; 575 cpu_dumpconf(); 576 goto out; 577 } 578 579 /* 580 * at this point we expect a path name in arg. we will 581 * use namei() to gain a vnode reference (vref), and lock 582 * the vnode (VOP_LOCK). 583 * 584 * XXX: a NULL arg means use the root vnode pointer (e.g. for 585 * miniroot) 586 */ 587 if (SCARG(uap, arg) == NULL) { 588 vp = rootvp; /* miniroot */ 589 vref(vp); 590 if (vn_lock(vp, LK_EXCLUSIVE)) { 591 vrele(vp); 592 error = EBUSY; 593 goto out; 594 } 595 if (SCARG(uap, cmd) == SWAP_ON && 596 copystr("miniroot", userpath, SWAP_PATH_MAX, &len)) 597 panic("swapctl: miniroot copy failed"); 598 } else { 599 struct pathbuf *pb; 600 601 /* 602 * This used to allow copying in one extra byte 603 * (SWAP_PATH_MAX instead of PATH_MAX) for SWAP_ON. 604 * This was completely pointless because if anyone 605 * used that extra byte namei would fail with 606 * ENAMETOOLONG anyway, so I've removed the excess 607 * logic. - dholland 20100215 608 */ 609 610 error = pathbuf_copyin(SCARG(uap, arg), &pb); 611 if (error) { 612 goto out; 613 } 614 if (SCARG(uap, cmd) == SWAP_ON) { 615 /* get a copy of the string */ 616 pathbuf_copystring(pb, userpath, SWAP_PATH_MAX); 617 len = strlen(userpath) + 1; 618 } 619 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb); 620 if ((error = namei(&nd))) { 621 pathbuf_destroy(pb); 622 goto out; 623 } 624 vp = nd.ni_vp; 625 pathbuf_destroy(pb); 626 } 627 /* note: "vp" is referenced and locked */ 628 629 error = 0; /* assume no error */ 630 switch(SCARG(uap, cmd)) { 631 632 case SWAP_DUMPDEV: 633 if (vp->v_type != VBLK) { 634 error = ENOTBLK; 635 break; 636 } 637 if (bdevsw_lookup(vp->v_rdev)) { 638 dumpdev = vp->v_rdev; 639 dumpcdev = devsw_blk2chr(dumpdev); 640 } else 641 dumpdev = NODEV; 642 cpu_dumpconf(); 643 break; 644 645 case SWAP_CTL: 646 /* 647 * get new priority, remove old entry (if any) and then 648 * reinsert it in the correct place. finally, prune out 649 * any empty priority structures. 650 */ 651 priority = SCARG(uap, misc); 652 spp = kmem_alloc(sizeof(*spp), KM_SLEEP); 653 mutex_enter(&uvm_swap_data_lock); 654 if ((sdp = swaplist_find(vp, true)) == NULL) { 655 error = ENOENT; 656 } else { 657 swaplist_insert(sdp, spp, priority); 658 swaplist_trim(); 659 } 660 mutex_exit(&uvm_swap_data_lock); 661 if (error) 662 kmem_free(spp, sizeof(*spp)); 663 break; 664 665 case SWAP_ON: 666 667 /* 668 * check for duplicates. if none found, then insert a 669 * dummy entry on the list to prevent someone else from 670 * trying to enable this device while we are working on 671 * it. 672 */ 673 674 priority = SCARG(uap, misc); 675 sdp = kmem_zalloc(sizeof(*sdp), KM_SLEEP); 676 spp = kmem_alloc(sizeof(*spp), KM_SLEEP); 677 sdp->swd_flags = SWF_FAKE; 678 sdp->swd_vp = vp; 679 sdp->swd_dev = (vp->v_type == VBLK) ? vp->v_rdev : NODEV; 680 bufq_alloc(&sdp->swd_tab, "disksort", BUFQ_SORT_RAWBLOCK); 681 mutex_enter(&uvm_swap_data_lock); 682 if (swaplist_find(vp, false) != NULL) { 683 error = EBUSY; 684 mutex_exit(&uvm_swap_data_lock); 685 bufq_free(sdp->swd_tab); 686 kmem_free(sdp, sizeof(*sdp)); 687 kmem_free(spp, sizeof(*spp)); 688 break; 689 } 690 swaplist_insert(sdp, spp, priority); 691 mutex_exit(&uvm_swap_data_lock); 692 693 KASSERT(len > 0); 694 sdp->swd_pathlen = len; 695 sdp->swd_path = kmem_alloc(len, KM_SLEEP); 696 if (copystr(userpath, sdp->swd_path, len, 0) != 0) 697 panic("swapctl: copystr"); 698 699 /* 700 * we've now got a FAKE placeholder in the swap list. 701 * now attempt to enable swap on it. if we fail, undo 702 * what we've done and kill the fake entry we just inserted. 703 * if swap_on is a success, it will clear the SWF_FAKE flag 704 */ 705 706 if ((error = swap_on(l, sdp)) != 0) { 707 mutex_enter(&uvm_swap_data_lock); 708 (void) swaplist_find(vp, true); /* kill fake entry */ 709 swaplist_trim(); 710 mutex_exit(&uvm_swap_data_lock); 711 bufq_free(sdp->swd_tab); 712 kmem_free(sdp->swd_path, sdp->swd_pathlen); 713 kmem_free(sdp, sizeof(*sdp)); 714 break; 715 } 716 break; 717 718 case SWAP_OFF: 719 mutex_enter(&uvm_swap_data_lock); 720 if ((sdp = swaplist_find(vp, false)) == NULL) { 721 mutex_exit(&uvm_swap_data_lock); 722 error = ENXIO; 723 break; 724 } 725 726 /* 727 * If a device isn't in use or enabled, we 728 * can't stop swapping from it (again). 729 */ 730 if ((sdp->swd_flags & (SWF_INUSE|SWF_ENABLE)) == 0) { 731 mutex_exit(&uvm_swap_data_lock); 732 error = EBUSY; 733 break; 734 } 735 736 /* 737 * do the real work. 738 */ 739 error = swap_off(l, sdp); 740 break; 741 742 default: 743 error = EINVAL; 744 } 745 746 /* 747 * done! release the ref gained by namei() and unlock. 748 */ 749 vput(vp); 750 out: 751 rw_exit(&swap_syscall_lock); 752 kmem_free(userpath, SWAP_PATH_MAX); 753 754 UVMHIST_LOG(pdhist, "<- done! error=%jd", error, 0, 0, 0); 755 return (error); 756 } 757 758 /* 759 * uvm_swap_stats: implements swapctl(SWAP_STATS). The function is kept 760 * away from sys_swapctl() in order to allow COMPAT_* swapctl() 761 * emulation to use it directly without going through sys_swapctl(). 762 * The problem with using sys_swapctl() there is that it involves 763 * copying the swapent array to the stackgap, and this array's size 764 * is not known at build time. Hence it would not be possible to 765 * ensure it would fit in the stackgap in any case. 766 */ 767 int 768 uvm_swap_stats(char *ptr, int misc, 769 void (*f)(void *, const struct swapent *), size_t len, 770 register_t *retval) 771 { 772 struct swappri *spp; 773 struct swapdev *sdp; 774 struct swapent sep; 775 int count = 0; 776 int error; 777 778 KASSERT(len <= sizeof(sep)); 779 if (len == 0) 780 return ENOSYS; 781 782 if (misc < 0) 783 return EINVAL; 784 785 if (misc == 0 || uvmexp.nswapdev == 0) 786 return 0; 787 788 /* Make sure userland cannot exhaust kernel memory */ 789 if ((size_t)misc > (size_t)uvmexp.nswapdev) 790 misc = uvmexp.nswapdev; 791 792 KASSERT(rw_lock_held(&swap_syscall_lock)); 793 794 LIST_FOREACH(spp, &swap_priority, spi_swappri) { 795 TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) { 796 int inuse; 797 798 if (misc-- <= 0) 799 break; 800 801 inuse = btodb((uint64_t)sdp->swd_npginuse << 802 PAGE_SHIFT); 803 804 memset(&sep, 0, sizeof(sep)); 805 swapent_cvt(&sep, sdp, inuse); 806 if (f) 807 (*f)(&sep, &sep); 808 if ((error = copyout(&sep, ptr, len)) != 0) 809 return error; 810 ptr += len; 811 count++; 812 } 813 } 814 *retval = count; 815 return 0; 816 } 817 818 /* 819 * swap_on: attempt to enable a swapdev for swapping. note that the 820 * swapdev is already on the global list, but disabled (marked 821 * SWF_FAKE). 822 * 823 * => we avoid the start of the disk (to protect disk labels) 824 * => we also avoid the miniroot, if we are swapping to root. 825 * => caller should leave uvm_swap_data_lock unlocked, we may lock it 826 * if needed. 827 */ 828 static int 829 swap_on(struct lwp *l, struct swapdev *sdp) 830 { 831 struct vnode *vp; 832 int error, npages, nblocks, size; 833 long addr; 834 vmem_addr_t result; 835 struct vattr va; 836 dev_t dev; 837 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 838 839 /* 840 * we want to enable swapping on sdp. the swd_vp contains 841 * the vnode we want (locked and ref'd), and the swd_dev 842 * contains the dev_t of the file, if it a block device. 843 */ 844 845 vp = sdp->swd_vp; 846 dev = sdp->swd_dev; 847 848 /* 849 * open the swap file (mostly useful for block device files to 850 * let device driver know what is up). 851 * 852 * we skip the open/close for root on swap because the root 853 * has already been opened when root was mounted (mountroot). 854 */ 855 if (vp != rootvp) { 856 if ((error = VOP_OPEN(vp, FREAD|FWRITE, l->l_cred))) 857 return (error); 858 } 859 860 /* XXX this only works for block devices */ 861 UVMHIST_LOG(pdhist, " dev=%jd, major(dev)=%jd", dev, major(dev), 0, 0); 862 863 /* 864 * we now need to determine the size of the swap area. for 865 * block specials we can call the d_psize function. 866 * for normal files, we must stat [get attrs]. 867 * 868 * we put the result in nblks. 869 * for normal files, we also want the filesystem block size 870 * (which we get with statfs). 871 */ 872 switch (vp->v_type) { 873 case VBLK: 874 if ((nblocks = bdev_size(dev)) == -1) { 875 error = ENXIO; 876 goto bad; 877 } 878 break; 879 880 case VREG: 881 if ((error = VOP_GETATTR(vp, &va, l->l_cred))) 882 goto bad; 883 nblocks = (int)btodb(va.va_size); 884 sdp->swd_bsize = 1 << vp->v_mount->mnt_fs_bshift; 885 /* 886 * limit the max # of outstanding I/O requests we issue 887 * at any one time. take it easy on NFS servers. 888 */ 889 if (vp->v_tag == VT_NFS) 890 sdp->swd_maxactive = 2; /* XXX */ 891 else 892 sdp->swd_maxactive = 8; /* XXX */ 893 break; 894 895 default: 896 error = ENXIO; 897 goto bad; 898 } 899 900 /* 901 * save nblocks in a safe place and convert to pages. 902 */ 903 904 sdp->swd_nblks = nblocks; 905 npages = dbtob((uint64_t)nblocks) >> PAGE_SHIFT; 906 907 /* 908 * for block special files, we want to make sure that leave 909 * the disklabel and bootblocks alone, so we arrange to skip 910 * over them (arbitrarily choosing to skip PAGE_SIZE bytes). 911 * note that because of this the "size" can be less than the 912 * actual number of blocks on the device. 913 */ 914 if (vp->v_type == VBLK) { 915 /* we use pages 1 to (size - 1) [inclusive] */ 916 size = npages - 1; 917 addr = 1; 918 } else { 919 /* we use pages 0 to (size - 1) [inclusive] */ 920 size = npages; 921 addr = 0; 922 } 923 924 /* 925 * make sure we have enough blocks for a reasonable sized swap 926 * area. we want at least one page. 927 */ 928 929 if (size < 1) { 930 UVMHIST_LOG(pdhist, " size <= 1!!", 0, 0, 0, 0); 931 error = EINVAL; 932 goto bad; 933 } 934 935 UVMHIST_LOG(pdhist, " dev=%jx: size=%jd addr=%jd", dev, size, addr, 0); 936 937 /* 938 * now we need to allocate an extent to manage this swap device 939 */ 940 941 sdp->swd_blist = blist_create(npages); 942 /* mark all expect the `saved' region free. */ 943 blist_free(sdp->swd_blist, addr, size); 944 945 /* 946 * allocate space to for swap encryption state and mark the 947 * keys uninitialized so we generate them lazily 948 */ 949 sdp->swd_encmap = kmem_zalloc(encmap_size(npages), KM_SLEEP); 950 sdp->swd_encinit = false; 951 952 /* 953 * if the vnode we are swapping to is the root vnode 954 * (i.e. we are swapping to the miniroot) then we want 955 * to make sure we don't overwrite it. do a statfs to 956 * find its size and skip over it. 957 */ 958 if (vp == rootvp) { 959 struct mount *mp; 960 struct statvfs *sp; 961 int rootblocks, rootpages; 962 963 mp = rootvnode->v_mount; 964 sp = &mp->mnt_stat; 965 rootblocks = sp->f_blocks * btodb(sp->f_frsize); 966 /* 967 * XXX: sp->f_blocks isn't the total number of 968 * blocks in the filesystem, it's the number of 969 * data blocks. so, our rootblocks almost 970 * definitely underestimates the total size 971 * of the filesystem - how badly depends on the 972 * details of the filesystem type. there isn't 973 * an obvious way to deal with this cleanly 974 * and perfectly, so for now we just pad our 975 * rootblocks estimate with an extra 5 percent. 976 */ 977 rootblocks += (rootblocks >> 5) + 978 (rootblocks >> 6) + 979 (rootblocks >> 7); 980 rootpages = round_page(dbtob(rootblocks)) >> PAGE_SHIFT; 981 if (rootpages > size) 982 panic("swap_on: miniroot larger than swap?"); 983 984 if (rootpages != blist_fill(sdp->swd_blist, addr, rootpages)) { 985 panic("swap_on: unable to preserve miniroot"); 986 } 987 988 size -= rootpages; 989 printf("Preserved %d pages of miniroot ", rootpages); 990 printf("leaving %d pages of swap\n", size); 991 } 992 993 /* 994 * add a ref to vp to reflect usage as a swap device. 995 */ 996 vref(vp); 997 998 /* 999 * now add the new swapdev to the drum and enable. 1000 */ 1001 error = vmem_alloc(swapmap, npages, VM_BESTFIT | VM_SLEEP, &result); 1002 if (error != 0) 1003 panic("swapdrum_add"); 1004 /* 1005 * If this is the first regular swap create the workqueue. 1006 * => Protected by swap_syscall_lock. 1007 */ 1008 if (vp->v_type != VBLK) { 1009 if (sw_reg_count++ == 0) { 1010 KASSERT(sw_reg_workqueue == NULL); 1011 if (workqueue_create(&sw_reg_workqueue, "swapiod", 1012 sw_reg_iodone, NULL, PRIBIO, IPL_BIO, 0) != 0) 1013 panic("%s: workqueue_create failed", __func__); 1014 } 1015 } 1016 1017 sdp->swd_drumoffset = (int)result; 1018 sdp->swd_drumsize = npages; 1019 sdp->swd_npages = size; 1020 mutex_enter(&uvm_swap_data_lock); 1021 sdp->swd_flags &= ~SWF_FAKE; /* going live */ 1022 sdp->swd_flags |= (SWF_INUSE|SWF_ENABLE); 1023 uvmexp.swpages += size; 1024 uvmexp.swpgavail += size; 1025 mutex_exit(&uvm_swap_data_lock); 1026 return (0); 1027 1028 /* 1029 * failure: clean up and return error. 1030 */ 1031 1032 bad: 1033 if (sdp->swd_blist) { 1034 blist_destroy(sdp->swd_blist); 1035 } 1036 if (vp != rootvp) { 1037 (void)VOP_CLOSE(vp, FREAD|FWRITE, l->l_cred); 1038 } 1039 return (error); 1040 } 1041 1042 /* 1043 * swap_off: stop swapping on swapdev 1044 * 1045 * => swap data should be locked, we will unlock. 1046 */ 1047 static int 1048 swap_off(struct lwp *l, struct swapdev *sdp) 1049 { 1050 int npages = sdp->swd_npages; 1051 int error = 0; 1052 1053 UVMHIST_FUNC(__func__); 1054 UVMHIST_CALLARGS(pdhist, " dev=%jx, npages=%jd", sdp->swd_dev,npages, 0, 0); 1055 1056 KASSERT(rw_write_held(&swap_syscall_lock)); 1057 KASSERT(mutex_owned(&uvm_swap_data_lock)); 1058 1059 /* disable the swap area being removed */ 1060 sdp->swd_flags &= ~SWF_ENABLE; 1061 uvmexp.swpgavail -= npages; 1062 mutex_exit(&uvm_swap_data_lock); 1063 1064 /* 1065 * the idea is to find all the pages that are paged out to this 1066 * device, and page them all in. in uvm, swap-backed pageable 1067 * memory can take two forms: aobjs and anons. call the 1068 * swapoff hook for each subsystem to bring in pages. 1069 */ 1070 1071 if (uao_swap_off(sdp->swd_drumoffset, 1072 sdp->swd_drumoffset + sdp->swd_drumsize) || 1073 amap_swap_off(sdp->swd_drumoffset, 1074 sdp->swd_drumoffset + sdp->swd_drumsize)) { 1075 error = ENOMEM; 1076 } else if (sdp->swd_npginuse > sdp->swd_npgbad) { 1077 error = EBUSY; 1078 } 1079 1080 if (error) { 1081 mutex_enter(&uvm_swap_data_lock); 1082 sdp->swd_flags |= SWF_ENABLE; 1083 uvmexp.swpgavail += npages; 1084 mutex_exit(&uvm_swap_data_lock); 1085 1086 return error; 1087 } 1088 1089 /* 1090 * If this is the last regular swap destroy the workqueue. 1091 * => Protected by swap_syscall_lock. 1092 */ 1093 if (sdp->swd_vp->v_type != VBLK) { 1094 KASSERT(sw_reg_count > 0); 1095 KASSERT(sw_reg_workqueue != NULL); 1096 if (--sw_reg_count == 0) { 1097 workqueue_destroy(sw_reg_workqueue); 1098 sw_reg_workqueue = NULL; 1099 } 1100 } 1101 1102 /* 1103 * done with the vnode. 1104 * drop our ref on the vnode before calling VOP_CLOSE() 1105 * so that spec_close() can tell if this is the last close. 1106 */ 1107 vrele(sdp->swd_vp); 1108 if (sdp->swd_vp != rootvp) { 1109 (void) VOP_CLOSE(sdp->swd_vp, FREAD|FWRITE, l->l_cred); 1110 } 1111 1112 mutex_enter(&uvm_swap_data_lock); 1113 uvmexp.swpages -= npages; 1114 uvmexp.swpginuse -= sdp->swd_npgbad; 1115 1116 if (swaplist_find(sdp->swd_vp, true) == NULL) 1117 panic("%s: swapdev not in list", __func__); 1118 swaplist_trim(); 1119 mutex_exit(&uvm_swap_data_lock); 1120 1121 /* 1122 * free all resources! 1123 */ 1124 vmem_free(swapmap, sdp->swd_drumoffset, sdp->swd_drumsize); 1125 blist_destroy(sdp->swd_blist); 1126 bufq_free(sdp->swd_tab); 1127 kmem_free(__UNVOLATILE(sdp->swd_encmap), 1128 encmap_size(sdp->swd_drumsize)); 1129 explicit_memset(&sdp->swd_enckey, 0, sizeof sdp->swd_enckey); 1130 explicit_memset(&sdp->swd_deckey, 0, sizeof sdp->swd_deckey); 1131 kmem_free(sdp, sizeof(*sdp)); 1132 return (0); 1133 } 1134 1135 void 1136 uvm_swap_shutdown(struct lwp *l) 1137 { 1138 struct swapdev *sdp; 1139 struct swappri *spp; 1140 struct vnode *vp; 1141 int error; 1142 1143 printf("turning off swap..."); 1144 rw_enter(&swap_syscall_lock, RW_WRITER); 1145 mutex_enter(&uvm_swap_data_lock); 1146 again: 1147 LIST_FOREACH(spp, &swap_priority, spi_swappri) 1148 TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) { 1149 if (sdp->swd_flags & SWF_FAKE) 1150 continue; 1151 if ((sdp->swd_flags & (SWF_INUSE|SWF_ENABLE)) == 0) 1152 continue; 1153 #ifdef DEBUG 1154 printf("\nturning off swap on %s...", 1155 sdp->swd_path); 1156 #endif 1157 if (vn_lock(vp = sdp->swd_vp, LK_EXCLUSIVE)) { 1158 error = EBUSY; 1159 vp = NULL; 1160 } else 1161 error = 0; 1162 if (!error) { 1163 error = swap_off(l, sdp); 1164 mutex_enter(&uvm_swap_data_lock); 1165 } 1166 if (error) { 1167 printf("stopping swap on %s failed " 1168 "with error %d\n", sdp->swd_path, error); 1169 TAILQ_REMOVE(&spp->spi_swapdev, sdp, 1170 swd_next); 1171 uvmexp.nswapdev--; 1172 swaplist_trim(); 1173 if (vp) 1174 vput(vp); 1175 } 1176 goto again; 1177 } 1178 printf(" done\n"); 1179 mutex_exit(&uvm_swap_data_lock); 1180 rw_exit(&swap_syscall_lock); 1181 } 1182 1183 1184 /* 1185 * /dev/drum interface and i/o functions 1186 */ 1187 1188 /* 1189 * swstrategy: perform I/O on the drum 1190 * 1191 * => we must map the i/o request from the drum to the correct swapdev. 1192 */ 1193 static void 1194 swstrategy(struct buf *bp) 1195 { 1196 struct swapdev *sdp; 1197 struct vnode *vp; 1198 int pageno, bn; 1199 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 1200 1201 /* 1202 * convert block number to swapdev. note that swapdev can't 1203 * be yanked out from under us because we are holding resources 1204 * in it (i.e. the blocks we are doing I/O on). 1205 */ 1206 pageno = dbtob((int64_t)bp->b_blkno) >> PAGE_SHIFT; 1207 mutex_enter(&uvm_swap_data_lock); 1208 sdp = swapdrum_getsdp(pageno); 1209 mutex_exit(&uvm_swap_data_lock); 1210 if (sdp == NULL) { 1211 bp->b_error = EINVAL; 1212 bp->b_resid = bp->b_bcount; 1213 biodone(bp); 1214 UVMHIST_LOG(pdhist, " failed to get swap device", 0, 0, 0, 0); 1215 return; 1216 } 1217 1218 /* 1219 * convert drum page number to block number on this swapdev. 1220 */ 1221 1222 pageno -= sdp->swd_drumoffset; /* page # on swapdev */ 1223 bn = btodb((uint64_t)pageno << PAGE_SHIFT); /* convert to diskblock */ 1224 1225 UVMHIST_LOG(pdhist, " Rd/Wr (0/1) %jd: mapoff=%jx bn=%jx bcount=%jd", 1226 ((bp->b_flags & B_READ) == 0) ? 1 : 0, 1227 sdp->swd_drumoffset, bn, bp->b_bcount); 1228 1229 /* 1230 * for block devices we finish up here. 1231 * for regular files we have to do more work which we delegate 1232 * to sw_reg_strategy(). 1233 */ 1234 1235 vp = sdp->swd_vp; /* swapdev vnode pointer */ 1236 switch (vp->v_type) { 1237 default: 1238 panic("%s: vnode type 0x%x", __func__, vp->v_type); 1239 1240 case VBLK: 1241 1242 /* 1243 * must convert "bp" from an I/O on /dev/drum to an I/O 1244 * on the swapdev (sdp). 1245 */ 1246 bp->b_blkno = bn; /* swapdev block number */ 1247 bp->b_dev = sdp->swd_dev; /* swapdev dev_t */ 1248 1249 /* 1250 * if we are doing a write, we have to redirect the i/o on 1251 * drum's v_numoutput counter to the swapdevs. 1252 */ 1253 if ((bp->b_flags & B_READ) == 0) { 1254 mutex_enter(bp->b_objlock); 1255 vwakeup(bp); /* kills one 'v_numoutput' on drum */ 1256 mutex_exit(bp->b_objlock); 1257 mutex_enter(vp->v_interlock); 1258 vp->v_numoutput++; /* put it on swapdev */ 1259 mutex_exit(vp->v_interlock); 1260 } 1261 1262 /* 1263 * finally plug in swapdev vnode and start I/O 1264 */ 1265 bp->b_vp = vp; 1266 bp->b_objlock = vp->v_interlock; 1267 VOP_STRATEGY(vp, bp); 1268 return; 1269 1270 case VREG: 1271 /* 1272 * delegate to sw_reg_strategy function. 1273 */ 1274 sw_reg_strategy(sdp, bp, bn); 1275 return; 1276 } 1277 /* NOTREACHED */ 1278 } 1279 1280 /* 1281 * swread: the read function for the drum (just a call to physio) 1282 */ 1283 /*ARGSUSED*/ 1284 static int 1285 swread(dev_t dev, struct uio *uio, int ioflag) 1286 { 1287 UVMHIST_FUNC(__func__); 1288 UVMHIST_CALLARGS(pdhist, " dev=%jx offset=%jx", dev, uio->uio_offset, 0, 0); 1289 1290 return (physio(swstrategy, NULL, dev, B_READ, minphys, uio)); 1291 } 1292 1293 /* 1294 * swwrite: the write function for the drum (just a call to physio) 1295 */ 1296 /*ARGSUSED*/ 1297 static int 1298 swwrite(dev_t dev, struct uio *uio, int ioflag) 1299 { 1300 UVMHIST_FUNC(__func__); 1301 UVMHIST_CALLARGS(pdhist, " dev=%jx offset=%jx", dev, uio->uio_offset, 0, 0); 1302 1303 return (physio(swstrategy, NULL, dev, B_WRITE, minphys, uio)); 1304 } 1305 1306 const struct bdevsw swap_bdevsw = { 1307 .d_open = nullopen, 1308 .d_close = nullclose, 1309 .d_strategy = swstrategy, 1310 .d_ioctl = noioctl, 1311 .d_dump = nodump, 1312 .d_psize = nosize, 1313 .d_discard = nodiscard, 1314 .d_flag = D_OTHER 1315 }; 1316 1317 const struct cdevsw swap_cdevsw = { 1318 .d_open = nullopen, 1319 .d_close = nullclose, 1320 .d_read = swread, 1321 .d_write = swwrite, 1322 .d_ioctl = noioctl, 1323 .d_stop = nostop, 1324 .d_tty = notty, 1325 .d_poll = nopoll, 1326 .d_mmap = nommap, 1327 .d_kqfilter = nokqfilter, 1328 .d_discard = nodiscard, 1329 .d_flag = D_OTHER, 1330 }; 1331 1332 /* 1333 * sw_reg_strategy: handle swap i/o to regular files 1334 */ 1335 static void 1336 sw_reg_strategy(struct swapdev *sdp, struct buf *bp, int bn) 1337 { 1338 struct vnode *vp; 1339 struct vndxfer *vnx; 1340 daddr_t nbn; 1341 char *addr; 1342 off_t byteoff; 1343 int s, off, nra, error, sz, resid; 1344 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 1345 1346 /* 1347 * allocate a vndxfer head for this transfer and point it to 1348 * our buffer. 1349 */ 1350 vnx = pool_get(&vndxfer_pool, PR_WAITOK); 1351 vnx->vx_flags = VX_BUSY; 1352 vnx->vx_error = 0; 1353 vnx->vx_pending = 0; 1354 vnx->vx_bp = bp; 1355 vnx->vx_sdp = sdp; 1356 1357 /* 1358 * setup for main loop where we read filesystem blocks into 1359 * our buffer. 1360 */ 1361 error = 0; 1362 bp->b_resid = bp->b_bcount; /* nothing transferred yet! */ 1363 addr = bp->b_data; /* current position in buffer */ 1364 byteoff = dbtob((uint64_t)bn); 1365 1366 for (resid = bp->b_resid; resid; resid -= sz) { 1367 struct vndbuf *nbp; 1368 1369 /* 1370 * translate byteoffset into block number. return values: 1371 * vp = vnode of underlying device 1372 * nbn = new block number (on underlying vnode dev) 1373 * nra = num blocks we can read-ahead (excludes requested 1374 * block) 1375 */ 1376 nra = 0; 1377 error = VOP_BMAP(sdp->swd_vp, byteoff / sdp->swd_bsize, 1378 &vp, &nbn, &nra); 1379 1380 if (error == 0 && nbn == (daddr_t)-1) { 1381 /* 1382 * this used to just set error, but that doesn't 1383 * do the right thing. Instead, it causes random 1384 * memory errors. The panic() should remain until 1385 * this condition doesn't destabilize the system. 1386 */ 1387 #if 1 1388 panic("%s: swap to sparse file", __func__); 1389 #else 1390 error = EIO; /* failure */ 1391 #endif 1392 } 1393 1394 /* 1395 * punt if there was an error or a hole in the file. 1396 * we must wait for any i/o ops we have already started 1397 * to finish before returning. 1398 * 1399 * XXX we could deal with holes here but it would be 1400 * a hassle (in the write case). 1401 */ 1402 if (error) { 1403 s = splbio(); 1404 vnx->vx_error = error; /* pass error up */ 1405 goto out; 1406 } 1407 1408 /* 1409 * compute the size ("sz") of this transfer (in bytes). 1410 */ 1411 off = byteoff % sdp->swd_bsize; 1412 sz = (1 + nra) * sdp->swd_bsize - off; 1413 if (sz > resid) 1414 sz = resid; 1415 1416 UVMHIST_LOG(pdhist, "sw_reg_strategy: " 1417 "vp %#jx/%#jx offset 0x%jx/0x%jx", 1418 (uintptr_t)sdp->swd_vp, (uintptr_t)vp, byteoff, nbn); 1419 1420 /* 1421 * now get a buf structure. note that the vb_buf is 1422 * at the front of the nbp structure so that you can 1423 * cast pointers between the two structure easily. 1424 */ 1425 nbp = pool_get(&vndbuf_pool, PR_WAITOK); 1426 buf_init(&nbp->vb_buf); 1427 nbp->vb_buf.b_flags = bp->b_flags; 1428 nbp->vb_buf.b_cflags = bp->b_cflags; 1429 nbp->vb_buf.b_oflags = bp->b_oflags; 1430 nbp->vb_buf.b_bcount = sz; 1431 nbp->vb_buf.b_bufsize = sz; 1432 nbp->vb_buf.b_error = 0; 1433 nbp->vb_buf.b_data = addr; 1434 nbp->vb_buf.b_lblkno = 0; 1435 nbp->vb_buf.b_blkno = nbn + btodb(off); 1436 nbp->vb_buf.b_rawblkno = nbp->vb_buf.b_blkno; 1437 nbp->vb_buf.b_iodone = sw_reg_biodone; 1438 nbp->vb_buf.b_vp = vp; 1439 nbp->vb_buf.b_objlock = vp->v_interlock; 1440 if (vp->v_type == VBLK) { 1441 nbp->vb_buf.b_dev = vp->v_rdev; 1442 } 1443 1444 nbp->vb_xfer = vnx; /* patch it back in to vnx */ 1445 1446 /* 1447 * Just sort by block number 1448 */ 1449 s = splbio(); 1450 if (vnx->vx_error != 0) { 1451 buf_destroy(&nbp->vb_buf); 1452 pool_put(&vndbuf_pool, nbp); 1453 goto out; 1454 } 1455 vnx->vx_pending++; 1456 1457 /* sort it in and start I/O if we are not over our limit */ 1458 /* XXXAD locking */ 1459 bufq_put(sdp->swd_tab, &nbp->vb_buf); 1460 sw_reg_start(sdp); 1461 splx(s); 1462 1463 /* 1464 * advance to the next I/O 1465 */ 1466 byteoff += sz; 1467 addr += sz; 1468 } 1469 1470 s = splbio(); 1471 1472 out: /* Arrive here at splbio */ 1473 vnx->vx_flags &= ~VX_BUSY; 1474 if (vnx->vx_pending == 0) { 1475 error = vnx->vx_error; 1476 pool_put(&vndxfer_pool, vnx); 1477 bp->b_error = error; 1478 biodone(bp); 1479 } 1480 splx(s); 1481 } 1482 1483 /* 1484 * sw_reg_start: start an I/O request on the requested swapdev 1485 * 1486 * => reqs are sorted by b_rawblkno (above) 1487 */ 1488 static void 1489 sw_reg_start(struct swapdev *sdp) 1490 { 1491 struct buf *bp; 1492 struct vnode *vp; 1493 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 1494 1495 /* recursion control */ 1496 if ((sdp->swd_flags & SWF_BUSY) != 0) 1497 return; 1498 1499 sdp->swd_flags |= SWF_BUSY; 1500 1501 while (sdp->swd_active < sdp->swd_maxactive) { 1502 bp = bufq_get(sdp->swd_tab); 1503 if (bp == NULL) 1504 break; 1505 sdp->swd_active++; 1506 1507 UVMHIST_LOG(pdhist, 1508 "sw_reg_start: bp %#jx vp %#jx blkno %#jx cnt %jx", 1509 (uintptr_t)bp, (uintptr_t)bp->b_vp, (uintptr_t)bp->b_blkno, 1510 bp->b_bcount); 1511 vp = bp->b_vp; 1512 KASSERT(bp->b_objlock == vp->v_interlock); 1513 if ((bp->b_flags & B_READ) == 0) { 1514 mutex_enter(vp->v_interlock); 1515 vp->v_numoutput++; 1516 mutex_exit(vp->v_interlock); 1517 } 1518 VOP_STRATEGY(vp, bp); 1519 } 1520 sdp->swd_flags &= ~SWF_BUSY; 1521 } 1522 1523 /* 1524 * sw_reg_biodone: one of our i/o's has completed 1525 */ 1526 static void 1527 sw_reg_biodone(struct buf *bp) 1528 { 1529 workqueue_enqueue(sw_reg_workqueue, &bp->b_work, NULL); 1530 } 1531 1532 /* 1533 * sw_reg_iodone: one of our i/o's has completed and needs post-i/o cleanup 1534 * 1535 * => note that we can recover the vndbuf struct by casting the buf ptr 1536 */ 1537 static void 1538 sw_reg_iodone(struct work *wk, void *dummy) 1539 { 1540 struct vndbuf *vbp = (void *)wk; 1541 struct vndxfer *vnx = vbp->vb_xfer; 1542 struct buf *pbp = vnx->vx_bp; /* parent buffer */ 1543 struct swapdev *sdp = vnx->vx_sdp; 1544 int s, resid, error; 1545 KASSERT(&vbp->vb_buf.b_work == wk); 1546 UVMHIST_FUNC(__func__); 1547 UVMHIST_CALLARGS(pdhist, " vbp=%#jx vp=%#jx blkno=%jx addr=%#jx", 1548 (uintptr_t)vbp, (uintptr_t)vbp->vb_buf.b_vp, vbp->vb_buf.b_blkno, 1549 (uintptr_t)vbp->vb_buf.b_data); 1550 UVMHIST_LOG(pdhist, " cnt=%jx resid=%jx", 1551 vbp->vb_buf.b_bcount, vbp->vb_buf.b_resid, 0, 0); 1552 1553 /* 1554 * protect vbp at splbio and update. 1555 */ 1556 1557 s = splbio(); 1558 resid = vbp->vb_buf.b_bcount - vbp->vb_buf.b_resid; 1559 pbp->b_resid -= resid; 1560 vnx->vx_pending--; 1561 1562 if (vbp->vb_buf.b_error != 0) { 1563 /* pass error upward */ 1564 error = vbp->vb_buf.b_error ? vbp->vb_buf.b_error : EIO; 1565 UVMHIST_LOG(pdhist, " got error=%jd !", error, 0, 0, 0); 1566 vnx->vx_error = error; 1567 } 1568 1569 /* 1570 * kill vbp structure 1571 */ 1572 buf_destroy(&vbp->vb_buf); 1573 pool_put(&vndbuf_pool, vbp); 1574 1575 /* 1576 * wrap up this transaction if it has run to completion or, in 1577 * case of an error, when all auxiliary buffers have returned. 1578 */ 1579 if (vnx->vx_error != 0) { 1580 /* pass error upward */ 1581 error = vnx->vx_error; 1582 if ((vnx->vx_flags & VX_BUSY) == 0 && vnx->vx_pending == 0) { 1583 pbp->b_error = error; 1584 biodone(pbp); 1585 pool_put(&vndxfer_pool, vnx); 1586 } 1587 } else if (pbp->b_resid == 0) { 1588 KASSERT(vnx->vx_pending == 0); 1589 if ((vnx->vx_flags & VX_BUSY) == 0) { 1590 UVMHIST_LOG(pdhist, " iodone, pbp=%#jx error=%jd !", 1591 (uintptr_t)pbp, vnx->vx_error, 0, 0); 1592 biodone(pbp); 1593 pool_put(&vndxfer_pool, vnx); 1594 } 1595 } 1596 1597 /* 1598 * done! start next swapdev I/O if one is pending 1599 */ 1600 sdp->swd_active--; 1601 sw_reg_start(sdp); 1602 splx(s); 1603 } 1604 1605 1606 /* 1607 * uvm_swap_alloc: allocate space on swap 1608 * 1609 * => allocation is done "round robin" down the priority list, as we 1610 * allocate in a priority we "rotate" the circle queue. 1611 * => space can be freed with uvm_swap_free 1612 * => we return the page slot number in /dev/drum (0 == invalid slot) 1613 * => we lock uvm_swap_data_lock 1614 * => XXXMRG: "LESSOK" INTERFACE NEEDED TO EXTENT SYSTEM 1615 */ 1616 int 1617 uvm_swap_alloc(int *nslots /* IN/OUT */, bool lessok) 1618 { 1619 struct swapdev *sdp; 1620 struct swappri *spp; 1621 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 1622 1623 /* 1624 * no swap devices configured yet? definite failure. 1625 */ 1626 if (uvmexp.nswapdev < 1) 1627 return 0; 1628 1629 /* 1630 * XXXJAK: BEGIN HACK 1631 * 1632 * blist_alloc() in subr_blist.c will panic if we try to allocate 1633 * too many slots. 1634 */ 1635 if (*nslots > BLIST_MAX_ALLOC) { 1636 if (__predict_false(lessok == false)) 1637 return 0; 1638 *nslots = BLIST_MAX_ALLOC; 1639 } 1640 /* XXXJAK: END HACK */ 1641 1642 /* 1643 * lock data lock, convert slots into blocks, and enter loop 1644 */ 1645 mutex_enter(&uvm_swap_data_lock); 1646 1647 ReTry: /* XXXMRG */ 1648 LIST_FOREACH(spp, &swap_priority, spi_swappri) { 1649 TAILQ_FOREACH(sdp, &spp->spi_swapdev, swd_next) { 1650 uint64_t result; 1651 1652 /* if it's not enabled, then we can't swap from it */ 1653 if ((sdp->swd_flags & SWF_ENABLE) == 0) 1654 continue; 1655 if (sdp->swd_npginuse + *nslots > sdp->swd_npages) 1656 continue; 1657 result = blist_alloc(sdp->swd_blist, *nslots); 1658 if (result == BLIST_NONE) { 1659 continue; 1660 } 1661 KASSERT(result < sdp->swd_drumsize); 1662 1663 /* 1664 * successful allocation! now rotate the tailq. 1665 */ 1666 TAILQ_REMOVE(&spp->spi_swapdev, sdp, swd_next); 1667 TAILQ_INSERT_TAIL(&spp->spi_swapdev, sdp, swd_next); 1668 sdp->swd_npginuse += *nslots; 1669 uvmexp.swpginuse += *nslots; 1670 mutex_exit(&uvm_swap_data_lock); 1671 /* done! return drum slot number */ 1672 UVMHIST_LOG(pdhist, 1673 "success! returning %jd slots starting at %jd", 1674 *nslots, result + sdp->swd_drumoffset, 0, 0); 1675 return (result + sdp->swd_drumoffset); 1676 } 1677 } 1678 1679 /* XXXMRG: BEGIN HACK */ 1680 if (*nslots > 1 && lessok) { 1681 *nslots = 1; 1682 /* XXXMRG: ugh! blist should support this for us */ 1683 goto ReTry; 1684 } 1685 /* XXXMRG: END HACK */ 1686 1687 mutex_exit(&uvm_swap_data_lock); 1688 return 0; 1689 } 1690 1691 /* 1692 * uvm_swapisfull: return true if most of available swap is allocated 1693 * and in use. we don't count some small portion as it may be inaccessible 1694 * to us at any given moment, for example if there is lock contention or if 1695 * pages are busy. 1696 */ 1697 bool 1698 uvm_swapisfull(void) 1699 { 1700 int swpgonly; 1701 bool rv; 1702 1703 mutex_enter(&uvm_swap_data_lock); 1704 KASSERT(uvmexp.swpgonly <= uvmexp.swpages); 1705 swpgonly = (int)((uint64_t)uvmexp.swpgonly * 100 / 1706 uvm_swapisfull_factor); 1707 rv = (swpgonly >= uvmexp.swpgavail); 1708 mutex_exit(&uvm_swap_data_lock); 1709 1710 return (rv); 1711 } 1712 1713 /* 1714 * uvm_swap_markbad: keep track of swap ranges where we've had i/o errors 1715 * 1716 * => we lock uvm_swap_data_lock 1717 */ 1718 void 1719 uvm_swap_markbad(int startslot, int nslots) 1720 { 1721 struct swapdev *sdp; 1722 UVMHIST_FUNC(__func__); UVMHIST_CALLED(pdhist); 1723 1724 mutex_enter(&uvm_swap_data_lock); 1725 sdp = swapdrum_getsdp(startslot); 1726 KASSERT(sdp != NULL); 1727 1728 /* 1729 * we just keep track of how many pages have been marked bad 1730 * in this device, to make everything add up in swap_off(). 1731 * we assume here that the range of slots will all be within 1732 * one swap device. 1733 */ 1734 1735 KASSERT(uvmexp.swpgonly >= nslots); 1736 atomic_add_int(&uvmexp.swpgonly, -nslots); 1737 sdp->swd_npgbad += nslots; 1738 UVMHIST_LOG(pdhist, "now %jd bad", sdp->swd_npgbad, 0,0,0); 1739 mutex_exit(&uvm_swap_data_lock); 1740 } 1741 1742 /* 1743 * uvm_swap_free: free swap slots 1744 * 1745 * => this can be all or part of an allocation made by uvm_swap_alloc 1746 * => we lock uvm_swap_data_lock 1747 */ 1748 void 1749 uvm_swap_free(int startslot, int nslots) 1750 { 1751 struct swapdev *sdp; 1752 UVMHIST_FUNC(__func__); 1753 UVMHIST_CALLARGS(pdhist, "freeing %jd slots starting at %jd", nslots, 1754 startslot, 0, 0); 1755 1756 /* 1757 * ignore attempts to free the "bad" slot. 1758 */ 1759 1760 if (startslot == SWSLOT_BAD) { 1761 return; 1762 } 1763 1764 /* 1765 * convert drum slot offset back to sdp, free the blocks 1766 * in the extent, and return. must hold pri lock to do 1767 * lookup and access the extent. 1768 */ 1769 1770 mutex_enter(&uvm_swap_data_lock); 1771 sdp = swapdrum_getsdp(startslot); 1772 KASSERT(uvmexp.nswapdev >= 1); 1773 KASSERT(sdp != NULL); 1774 KASSERT(sdp->swd_npginuse >= nslots); 1775 blist_free(sdp->swd_blist, startslot - sdp->swd_drumoffset, nslots); 1776 sdp->swd_npginuse -= nslots; 1777 uvmexp.swpginuse -= nslots; 1778 mutex_exit(&uvm_swap_data_lock); 1779 } 1780 1781 /* 1782 * uvm_swap_put: put any number of pages into a contig place on swap 1783 * 1784 * => can be sync or async 1785 */ 1786 1787 int 1788 uvm_swap_put(int swslot, struct vm_page **ppsp, int npages, int flags) 1789 { 1790 int error; 1791 1792 error = uvm_swap_io(ppsp, swslot, npages, B_WRITE | 1793 ((flags & PGO_SYNCIO) ? 0 : B_ASYNC)); 1794 return error; 1795 } 1796 1797 /* 1798 * uvm_swap_get: get a single page from swap 1799 * 1800 * => usually a sync op (from fault) 1801 */ 1802 1803 int 1804 uvm_swap_get(struct vm_page *page, int swslot, int flags) 1805 { 1806 int error; 1807 1808 atomic_inc_uint(&uvmexp.nswget); 1809 KASSERT(flags & PGO_SYNCIO); 1810 if (swslot == SWSLOT_BAD) { 1811 return EIO; 1812 } 1813 1814 error = uvm_swap_io(&page, swslot, 1, B_READ | 1815 ((flags & PGO_SYNCIO) ? 0 : B_ASYNC)); 1816 if (error == 0) { 1817 1818 /* 1819 * this page is no longer only in swap. 1820 */ 1821 1822 KASSERT(uvmexp.swpgonly > 0); 1823 atomic_dec_uint(&uvmexp.swpgonly); 1824 } 1825 return error; 1826 } 1827 1828 /* 1829 * uvm_swap_io: do an i/o operation to swap 1830 */ 1831 1832 static int 1833 uvm_swap_io(struct vm_page **pps, int startslot, int npages, int flags) 1834 { 1835 daddr_t startblk; 1836 struct buf *bp; 1837 vaddr_t kva; 1838 int error, mapinflags; 1839 bool write, async, swap_encrypt; 1840 UVMHIST_FUNC(__func__); 1841 UVMHIST_CALLARGS(pdhist, "<- called, startslot=%jd, npages=%jd, flags=%jd", 1842 startslot, npages, flags, 0); 1843 1844 write = (flags & B_READ) == 0; 1845 async = (flags & B_ASYNC) != 0; 1846 swap_encrypt = atomic_load_relaxed(&uvm_swap_encrypt); 1847 1848 /* 1849 * allocate a buf for the i/o. 1850 */ 1851 1852 KASSERT(curlwp != uvm.pagedaemon_lwp || (write && async)); 1853 bp = getiobuf(swapdev_vp, curlwp != uvm.pagedaemon_lwp); 1854 if (bp == NULL) { 1855 uvm_aio_aiodone_pages(pps, npages, true, ENOMEM); 1856 return ENOMEM; 1857 } 1858 1859 /* 1860 * convert starting drum slot to block number 1861 */ 1862 1863 startblk = btodb((uint64_t)startslot << PAGE_SHIFT); 1864 1865 /* 1866 * first, map the pages into the kernel. 1867 */ 1868 1869 mapinflags = !write ? 1870 UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_READ : 1871 UVMPAGER_MAPIN_WAITOK|UVMPAGER_MAPIN_WRITE; 1872 if (write && swap_encrypt) /* need to encrypt in-place */ 1873 mapinflags |= UVMPAGER_MAPIN_READ; 1874 kva = uvm_pagermapin(pps, npages, mapinflags); 1875 1876 /* 1877 * encrypt writes in place if requested 1878 */ 1879 1880 if (write) do { 1881 struct swapdev *sdp; 1882 int i; 1883 1884 /* 1885 * Get the swapdev so we can discriminate on the 1886 * encryption state. There may or may not be an 1887 * encryption key generated; we may or may not be asked 1888 * to encrypt swap. 1889 * 1890 * 1. NO KEY, NO ENCRYPTION: Nothing to do. 1891 * 1892 * 2. NO KEY, BUT ENCRYPTION: Generate a key, encrypt, 1893 * and mark the slots encrypted. 1894 * 1895 * 3. KEY, BUT NO ENCRYPTION: The slots may already be 1896 * marked encrypted from a past life. Mark them not 1897 * encrypted. 1898 * 1899 * 4. KEY, ENCRYPTION: Encrypt and mark the slots 1900 * encrypted. 1901 */ 1902 mutex_enter(&uvm_swap_data_lock); 1903 sdp = swapdrum_getsdp(startslot); 1904 if (!sdp->swd_encinit) { 1905 if (!swap_encrypt) { 1906 mutex_exit(&uvm_swap_data_lock); 1907 break; 1908 } 1909 uvm_swap_genkey(sdp); 1910 } 1911 KASSERT(sdp->swd_encinit); 1912 mutex_exit(&uvm_swap_data_lock); 1913 1914 for (i = 0; i < npages; i++) { 1915 int s = startslot + i; 1916 KDASSERT(swapdrum_sdp_is(s, sdp)); 1917 KASSERT(s >= sdp->swd_drumoffset); 1918 s -= sdp->swd_drumoffset; 1919 KASSERT(s < sdp->swd_drumsize); 1920 1921 if (swap_encrypt) { 1922 uvm_swap_encryptpage(sdp, 1923 (void *)(kva + (vsize_t)i*PAGE_SIZE), s); 1924 atomic_or_32(&sdp->swd_encmap[s/32], 1925 __BIT(s%32)); 1926 } else { 1927 atomic_and_32(&sdp->swd_encmap[s/32], 1928 ~__BIT(s%32)); 1929 } 1930 } 1931 } while (0); 1932 1933 /* 1934 * fill in the bp/sbp. we currently route our i/o through 1935 * /dev/drum's vnode [swapdev_vp]. 1936 */ 1937 1938 bp->b_cflags = BC_BUSY | BC_NOCACHE; 1939 bp->b_flags = (flags & (B_READ|B_ASYNC)); 1940 bp->b_proc = &proc0; /* XXX */ 1941 bp->b_vnbufs.le_next = NOLIST; 1942 bp->b_data = (void *)kva; 1943 bp->b_blkno = startblk; 1944 bp->b_bufsize = bp->b_bcount = npages << PAGE_SHIFT; 1945 1946 /* 1947 * bump v_numoutput (counter of number of active outputs). 1948 */ 1949 1950 if (write) { 1951 mutex_enter(swapdev_vp->v_interlock); 1952 swapdev_vp->v_numoutput++; 1953 mutex_exit(swapdev_vp->v_interlock); 1954 } 1955 1956 /* 1957 * for async ops we must set up the iodone handler. 1958 */ 1959 1960 if (async) { 1961 bp->b_iodone = uvm_aio_aiodone; 1962 UVMHIST_LOG(pdhist, "doing async!", 0, 0, 0, 0); 1963 if (curlwp == uvm.pagedaemon_lwp) 1964 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL); 1965 else 1966 BIO_SETPRIO(bp, BPRIO_TIMELIMITED); 1967 } else { 1968 bp->b_iodone = NULL; 1969 BIO_SETPRIO(bp, BPRIO_TIMECRITICAL); 1970 } 1971 UVMHIST_LOG(pdhist, 1972 "about to start io: data = %#jx blkno = 0x%jx, bcount = %jd", 1973 (uintptr_t)bp->b_data, bp->b_blkno, bp->b_bcount, 0); 1974 1975 /* 1976 * now we start the I/O, and if async, return. 1977 */ 1978 1979 VOP_STRATEGY(swapdev_vp, bp); 1980 if (async) { 1981 /* 1982 * Reads are always synchronous; if this changes, we 1983 * need to add an asynchronous path for decryption. 1984 */ 1985 KASSERT(write); 1986 return 0; 1987 } 1988 1989 /* 1990 * must be sync i/o. wait for it to finish 1991 */ 1992 1993 error = biowait(bp); 1994 if (error) 1995 goto out; 1996 1997 /* 1998 * decrypt reads in place if needed 1999 */ 2000 2001 if (!write) do { 2002 struct swapdev *sdp; 2003 bool encinit; 2004 int i; 2005 2006 /* 2007 * Get the sdp. Everything about it except the encinit 2008 * bit, saying whether the encryption key is 2009 * initialized or not, and the encrypted bit for each 2010 * page, is stable until all swap pages have been 2011 * released and the device is removed. 2012 */ 2013 mutex_enter(&uvm_swap_data_lock); 2014 sdp = swapdrum_getsdp(startslot); 2015 encinit = sdp->swd_encinit; 2016 mutex_exit(&uvm_swap_data_lock); 2017 2018 if (!encinit) 2019 /* 2020 * If there's no encryption key, there's no way 2021 * any of these slots can be encrypted, so 2022 * nothing to do here. 2023 */ 2024 break; 2025 for (i = 0; i < npages; i++) { 2026 int s = startslot + i; 2027 KDASSERT(swapdrum_sdp_is(s, sdp)); 2028 KASSERT(s >= sdp->swd_drumoffset); 2029 s -= sdp->swd_drumoffset; 2030 KASSERT(s < sdp->swd_drumsize); 2031 if ((atomic_load_relaxed(&sdp->swd_encmap[s/32]) & 2032 __BIT(s%32)) == 0) 2033 continue; 2034 uvm_swap_decryptpage(sdp, 2035 (void *)(kva + (vsize_t)i*PAGE_SIZE), s); 2036 } 2037 } while (0); 2038 out: 2039 /* 2040 * kill the pager mapping 2041 */ 2042 2043 uvm_pagermapout(kva, npages); 2044 2045 /* 2046 * now dispose of the buf and we're done. 2047 */ 2048 2049 if (write) { 2050 mutex_enter(swapdev_vp->v_interlock); 2051 vwakeup(bp); 2052 mutex_exit(swapdev_vp->v_interlock); 2053 } 2054 putiobuf(bp); 2055 UVMHIST_LOG(pdhist, "<- done (sync) error=%jd", error, 0, 0, 0); 2056 2057 return (error); 2058 } 2059 2060 /* 2061 * uvm_swap_genkey(sdp) 2062 * 2063 * Generate a key for swap encryption. 2064 */ 2065 static void 2066 uvm_swap_genkey(struct swapdev *sdp) 2067 { 2068 uint8_t key[32]; 2069 2070 KASSERT(!sdp->swd_encinit); 2071 2072 cprng_strong(kern_cprng, key, sizeof key, 0); 2073 aes_setenckey256(&sdp->swd_enckey, key); 2074 aes_setdeckey256(&sdp->swd_deckey, key); 2075 explicit_memset(key, 0, sizeof key); 2076 2077 sdp->swd_encinit = true; 2078 } 2079 2080 /* 2081 * uvm_swap_encryptpage(sdp, kva, slot) 2082 * 2083 * Encrypt one page of data at kva for the specified slot number 2084 * in the swap device. 2085 */ 2086 static void 2087 uvm_swap_encryptpage(struct swapdev *sdp, void *kva, int slot) 2088 { 2089 uint8_t preiv[16] __aligned(16) = {0}, iv[16] __aligned(16); 2090 2091 /* iv := AES_k(le32enc(slot) || 0^96) */ 2092 le32enc(preiv, slot); 2093 aes_enc(&sdp->swd_enckey, (const void *)preiv, iv, AES_256_NROUNDS); 2094 2095 /* *kva := AES-CBC_k(iv, *kva) */ 2096 aes_cbc_enc(&sdp->swd_enckey, kva, kva, PAGE_SIZE, iv, 2097 AES_256_NROUNDS); 2098 2099 explicit_memset(&iv, 0, sizeof iv); 2100 } 2101 2102 /* 2103 * uvm_swap_decryptpage(sdp, kva, slot) 2104 * 2105 * Decrypt one page of data at kva for the specified slot number 2106 * in the swap device. 2107 */ 2108 static void 2109 uvm_swap_decryptpage(struct swapdev *sdp, void *kva, int slot) 2110 { 2111 uint8_t preiv[16] __aligned(16) = {0}, iv[16] __aligned(16); 2112 2113 /* iv := AES_k(le32enc(slot) || 0^96) */ 2114 le32enc(preiv, slot); 2115 aes_enc(&sdp->swd_enckey, (const void *)preiv, iv, AES_256_NROUNDS); 2116 2117 /* *kva := AES-CBC^{-1}_k(iv, *kva) */ 2118 aes_cbc_dec(&sdp->swd_deckey, kva, kva, PAGE_SIZE, iv, 2119 AES_256_NROUNDS); 2120 2121 explicit_memset(&iv, 0, sizeof iv); 2122 } 2123 2124 SYSCTL_SETUP(sysctl_uvmswap_setup, "sysctl uvmswap setup") 2125 { 2126 2127 sysctl_createv(clog, 0, NULL, NULL, 2128 CTLFLAG_PERMANENT|CTLFLAG_READWRITE, CTLTYPE_BOOL, "swap_encrypt", 2129 SYSCTL_DESCR("Encrypt data when swapped out to disk"), 2130 NULL, 0, &uvm_swap_encrypt, 0, 2131 CTL_VM, CTL_CREATE, CTL_EOL); 2132 } 2133