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