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