Home | History | Annotate | Line # | Download | only in dev
fss.c revision 1.1
      1 /*	$NetBSD: fss.c,v 1.1 2003/12/10 11:40:11 hannken Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Juergen Hannken-Illjes.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the NetBSD
     21  *	Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * File system snapshot disk driver.
     41  *
     42  * Block/character interface to the snapshot of a mounted file system.
     43  */
     44 
     45 #include <sys/cdefs.h>
     46 __KERNEL_RCSID(0, "$NetBSD: fss.c,v 1.1 2003/12/10 11:40:11 hannken Exp $");
     47 
     48 #include <sys/param.h>
     49 #include <sys/systm.h>
     50 #include <sys/namei.h>
     51 #include <sys/proc.h>
     52 #include <sys/errno.h>
     53 #include <sys/buf.h>
     54 #include <sys/malloc.h>
     55 #include <sys/ioctl.h>
     56 #include <sys/disklabel.h>
     57 #include <sys/device.h>
     58 #include <sys/disk.h>
     59 #include <sys/stat.h>
     60 #include <sys/mount.h>
     61 #include <sys/vnode.h>
     62 #include <sys/file.h>
     63 #include <sys/uio.h>
     64 #include <sys/conf.h>
     65 #include <sys/kthread.h>
     66 
     67 #include <miscfs/specfs/specdev.h>
     68 
     69 #include <machine/stdarg.h>
     70 
     71 #include "fss.h"
     72 #include <dev/fssvar.h>
     73 
     74 #ifdef DEBUG
     75 #include "opt_ddb.h"
     76 #include <ddb/ddbvar.h>
     77 #include <machine/db_machdep.h>
     78 #include <ddb/db_command.h>
     79 #include <ddb/db_interface.h>
     80 #endif
     81 
     82 #ifdef DEBUG
     83 #define FSS_STATISTICS
     84 #endif
     85 
     86 #ifdef FSS_STATISTICS
     87 struct fss_stat {
     88 	u_int64_t	cow_calls;
     89 	u_int64_t	cow_copied;
     90 	u_int64_t	cow_cache_full;
     91 	u_int64_t	indir_read;
     92 	u_int64_t	indir_write;
     93 };
     94 
     95 static struct fss_stat fss_stat[NFSS];
     96 
     97 #define FSS_STAT_INC(sc, field)	\
     98 			do { \
     99 				fss_stat[sc->sc_unit].field++; \
    100 			} while (0)
    101 #define FSS_STAT_SET(sc, field, value) \
    102 			do { \
    103 				fss_stat[sc->sc_unit].field = value; \
    104 			} while (0)
    105 #define FSS_STAT_ADD(sc, field, value) \
    106 			do { \
    107 				fss_stat[sc->sc_unit].field += value; \
    108 			} while (0)
    109 #define FSS_STAT_VAL(sc, field) fss_stat[sc->sc_unit].field
    110 #define FSS_STAT_CLEAR(sc) \
    111 			do { \
    112 				memset(&fss_stat[sc->sc_unit], 0, \
    113 				    sizeof(struct fss_stat)); \
    114 			} while (0)
    115 #else /* FSS_STATISTICS */
    116 #define FSS_STAT_INC(sc, field)
    117 #define FSS_STAT_SET(sc, field, value)
    118 #define FSS_STAT_ADD(sc, field, value)
    119 #define FSS_STAT_CLEAR(sc)
    120 #endif /* FSS_STATISTICS */
    121 
    122 typedef enum {
    123 	FSS_READ,
    124 	FSS_WRITE
    125 } fss_io_type;
    126 
    127 static int fss_attached;
    128 
    129 void fssattach(int);
    130 int fssdetach(void);
    131 
    132 dev_type_open(fss_open);
    133 dev_type_close(fss_close);
    134 dev_type_read(fss_read);
    135 dev_type_write(fss_write);
    136 dev_type_ioctl(fss_ioctl);
    137 dev_type_strategy(fss_strategy);
    138 dev_type_dump(fss_dump);
    139 dev_type_size(fss_size);
    140 
    141 static inline void fss_error(struct fss_softc *, const char *, ...);
    142 static inline int fss_valid(struct fss_softc *);
    143 static int fss_create_snapshot(struct fss_softc *, struct fss_set *,
    144     struct proc *);
    145 static int fss_delete_snapshot(struct fss_softc *, struct proc *);
    146 static int fss_softc_alloc(struct fss_softc *);
    147 static void fss_softc_free(struct fss_softc *);
    148 static void fss_cluster_iodone(struct buf *);
    149 static void fss_read_cluster(struct fss_softc *, u_int32_t);
    150 static int fss_write_cluster(struct fss_cache *, u_int32_t);
    151 static void fss_bs_thread(void *);
    152 static inline void block_to_cluster(struct fss_softc *, daddr_t, long,
    153     u_int32_t *, long *);
    154 static int fss_bs_io(struct fss_softc *, fss_io_type,
    155     u_int32_t, long, int, caddr_t);
    156 static u_int32_t *fss_bs_indir(struct fss_softc *, u_int32_t);
    157 
    158 const struct bdevsw fss_bdevsw = {
    159 	fss_open, fss_close, fss_strategy, fss_ioctl,
    160 	fss_dump, fss_size, D_DISK
    161 };
    162 
    163 const struct cdevsw fss_cdevsw = {
    164 	fss_open, fss_close, fss_read, fss_write, fss_ioctl,
    165 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
    166 };
    167 
    168 void
    169 fssattach(int num)
    170 {
    171 	int i;
    172 	struct fss_softc *sc;
    173 
    174 	if (fss_attached != 0)
    175 		return;
    176 
    177 	for (i = 0; i < NFSS; i++) {
    178 		sc = &fss_softc[i];
    179 		sc->sc_unit = i;
    180 		sc->sc_bdev = NODEV;
    181 		lockinit(&sc->sc_lock, PRIBIO, "fsslock", 0, 0);
    182 		bufq_alloc(&sc->sc_bufq, BUFQ_FCFS|BUFQ_SORT_RAWBLOCK);
    183 	}
    184 
    185 	fss_attached = 1;
    186 }
    187 
    188 int
    189 fssdetach(void)
    190 {
    191 	int i;
    192 
    193 	if (fss_attached == 0)
    194 		return 0;
    195 
    196 	for (i = 0; i < NFSS; i++)
    197 		if (fss_softc[i].sc_flags != 0)
    198 			return EBUSY;
    199 
    200 	for (i = 0; i < NFSS; i++)
    201 		bufq_free(&fss_softc[i].sc_bufq);
    202 
    203 	fss_attached = 0;
    204 
    205 	return 0;
    206 }
    207 
    208 int
    209 fss_open(dev_t dev, int flags, int mode, struct proc *p)
    210 {
    211 	struct fss_softc *sc;
    212 
    213 	if (fss_dev_to_softc(dev, &sc) != 0)
    214 		return ENXIO;
    215 
    216 	return 0;
    217 }
    218 
    219 int
    220 fss_close(dev_t dev, int flags, int mode, struct proc *p)
    221 {
    222 	struct fss_softc *sc;
    223 
    224 	if (fss_dev_to_softc(dev, &sc) != 0)
    225 		return ENXIO;
    226 
    227 	return 0;
    228 }
    229 
    230 void
    231 fss_strategy(struct buf *bp)
    232 {
    233 	struct fss_softc *sc;
    234 
    235 	if ((bp->b_flags & B_READ) != B_READ ||
    236 	    fss_dev_to_softc(bp->b_dev, &sc) != 0 ||
    237 	    !fss_valid(sc)) {
    238 		bp->b_error = ENXIO;
    239 		bp->b_flags |= B_ERROR;
    240 		bp->b_resid = bp->b_bcount;
    241 		biodone(bp);
    242 		return;
    243 	}
    244 
    245 	bp->b_rawblkno = bp->b_blkno;
    246 	BUFQ_PUT(&sc->sc_bufq, bp);
    247 	wakeup(&sc->sc_bs_proc);
    248 }
    249 
    250 int
    251 fss_read(dev_t dev, struct uio *uio, int flags)
    252 {
    253 	return physio(fss_strategy, NULL, dev, B_READ, minphys, uio);
    254 }
    255 
    256 int
    257 fss_write(dev_t dev, struct uio *uio, int flags)
    258 {
    259 	return physio(fss_strategy, NULL, dev, B_WRITE, minphys, uio);
    260 }
    261 
    262 int
    263 fss_ioctl(dev_t dev, u_long cmd, caddr_t data, int flag, struct proc *p)
    264 {
    265 	int error;
    266 	struct fss_softc *sc;
    267 	struct fss_set *fss = (struct fss_set *)data;
    268 	struct fss_get *fsg = (struct fss_get *)data;
    269 
    270 	if ((error = fss_dev_to_softc(dev, &sc)) != 0)
    271 		return error;
    272 
    273 	lockmgr(&sc->sc_lock, LK_EXCLUSIVE, NULL);
    274 
    275 	error = EINVAL;
    276 
    277 	switch (cmd) {
    278 	case FSSIOCSET:
    279 		if ((flag & FWRITE) == 0)
    280 			error = EPERM;
    281 		else if ((sc->sc_flags & FSS_ACTIVE) != 0)
    282 			error = EBUSY;
    283 		else
    284 			error = fss_create_snapshot(sc, fss, p);
    285 		break;
    286 
    287 	case FSSIOCCLR:
    288 		if ((flag & FWRITE) == 0)
    289 			error = EPERM;
    290 		else if ((sc->sc_flags & FSS_ACTIVE) == 0)
    291 			error = ENXIO;
    292 		else
    293 			error = fss_delete_snapshot(sc, p);
    294 		break;
    295 
    296 	case FSSIOCGET:
    297 		if ((sc->sc_flags & FSS_ACTIVE) == FSS_ACTIVE) {
    298 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
    299 			fsg->fsg_csize = sc->sc_clsize;
    300 			fsg->fsg_time = sc->sc_time;
    301 			fsg->fsg_mount_size = sc->sc_clcount;
    302 			fsg->fsg_bs_size = sc->sc_clnext;
    303 			error = 0;
    304 		} else
    305 			error = ENXIO;
    306 		break;
    307 	}
    308 
    309 	lockmgr(&sc->sc_lock, LK_RELEASE, NULL);
    310 
    311 	return error;
    312 }
    313 
    314 int
    315 fss_size(dev_t dev)
    316 {
    317 	return -1;
    318 }
    319 
    320 int
    321 fss_dump(dev_t dev, daddr_t blkno, caddr_t va, size_t size)
    322 {
    323 	return ENXIO;
    324 }
    325 
    326 /*
    327  * An error occured reading or writing the snapshot or backing store.
    328  * If it is the first error log to console.
    329  */
    330 static inline void
    331 fss_error(struct fss_softc *sc, const char *fmt, ...)
    332 {
    333 	int s;
    334 	va_list ap;
    335 
    336 	s = splbio();
    337 	if ((sc->sc_flags & (FSS_ACTIVE|FSS_ERROR)) == FSS_ACTIVE) {
    338 		va_start(ap, fmt);
    339 		printf("fss%d: snapshot invalid: ", sc->sc_unit);
    340 		vprintf(fmt, ap);
    341 		printf("\n");
    342 		va_end(ap);
    343 	}
    344 	if ((sc->sc_flags & FSS_ACTIVE) == FSS_ACTIVE)
    345 		sc->sc_flags |= FSS_ERROR;
    346 	splx(s);
    347 }
    348 
    349 /*
    350  * Check if this snapshot is still valid.
    351  */
    352 static inline int
    353 fss_valid(struct fss_softc *sc)
    354 {
    355 	int s, valid;
    356 
    357 	s = splbio();
    358 	valid = ((sc->sc_flags & (FSS_ACTIVE|FSS_ERROR)) == FSS_ACTIVE);
    359 	splx(s);
    360 
    361 	return valid;
    362 }
    363 
    364 /*
    365  * Allocate the variable sized parts of the softc and
    366  * fork the kernel thread.
    367  *
    368  * The fields sc_clcount, sc_clsize, sc_cache_size and sc_indir_size
    369  * must be initialized.
    370  */
    371 static int
    372 fss_softc_alloc(struct fss_softc *sc)
    373 {
    374 	int i, len, error;
    375 
    376 	len = (sc->sc_clcount+NBBY-1)/NBBY;
    377 	sc->sc_copied = malloc(len, M_TEMP, M_ZERO|M_WAITOK);
    378 
    379 	len = sc->sc_cache_size*sizeof(struct fss_cache);
    380 	sc->sc_cache = malloc(len, M_TEMP, M_WAITOK);
    381 
    382 	len = sc->sc_clsize;
    383 	for (i = 0; i < sc->sc_cache_size; i++) {
    384 		sc->sc_cache[i].fc_type = FSS_CACHE_FREE;
    385 		sc->sc_cache[i].fc_softc = sc;
    386 		sc->sc_cache[i].fc_xfercount = 0;
    387 		sc->sc_cache[i].fc_data = malloc(len, M_TEMP, M_WAITOK);
    388 	}
    389 
    390 	len = (sc->sc_indir_size+NBBY-1)/NBBY;
    391 	sc->sc_indir_valid = malloc(len, M_TEMP, M_ZERO|M_WAITOK);
    392 
    393 	len = sc->sc_clsize;
    394 	sc->sc_indir_data = malloc(len, M_TEMP, M_ZERO|M_WAITOK);
    395 
    396 	if ((error = kthread_create1(fss_bs_thread, sc, &sc->sc_bs_proc,
    397 	    "fssbs%d", sc->sc_unit)) != 0)
    398 		return error;
    399 
    400 	sc->sc_flags |= FSS_BS_THREAD;
    401 	return 0;
    402 }
    403 
    404 /*
    405  * Free the variable sized parts of the softc.
    406  */
    407 static void
    408 fss_softc_free(struct fss_softc *sc)
    409 {
    410 	int i;
    411 
    412 	if ((sc->sc_flags & FSS_BS_THREAD) != 0) {
    413 		sc->sc_flags &= ~FSS_BS_THREAD;
    414 		wakeup(&sc->sc_bs_proc);
    415 		while (sc->sc_bs_proc != NULL)
    416 			tsleep(sc, PRIBIO, "fssthread", 1);
    417 	}
    418 
    419 	if (sc->sc_copied != NULL)
    420 		free(sc->sc_copied, M_TEMP);
    421 	sc->sc_copied = NULL;
    422 
    423 	if (sc->sc_cache != NULL) {
    424 		for (i = 0; i < sc->sc_cache_size; i++)
    425 			free(sc->sc_cache[i].fc_data, M_TEMP);
    426 		free(sc->sc_cache, M_TEMP);
    427 	}
    428 	sc->sc_cache = NULL;
    429 
    430 	if (sc->sc_indir_valid != NULL)
    431 		free(sc->sc_indir_valid, M_TEMP);
    432 	sc->sc_indir_valid = NULL;
    433 
    434 	if (sc->sc_indir_data != NULL)
    435 		free(sc->sc_indir_data, M_TEMP);
    436 	sc->sc_indir_data = NULL;
    437 }
    438 
    439 /*
    440  * Check if an unmount is ok. If forced, set this snapshot into ERROR state.
    441  */
    442 int
    443 fss_umount_hook(struct mount *mp, int forced)
    444 {
    445 	int i, s;
    446 
    447 	s = splbio();
    448 	for (i = 0; i < NFSS; i++)
    449 		if ((fss_softc[i].sc_flags & FSS_ACTIVE) != 0 &&
    450 		    fss_softc[i].sc_mount == mp) {
    451 			if (forced)
    452 				fss_error(&fss_softc[i], "forced unmount");
    453 			else {
    454 				splx(s);
    455 				return EBUSY;
    456 			}
    457 		}
    458 	splx(s);
    459 	return 0;
    460 }
    461 
    462 /*
    463  * A buffer is written to the snapshotted block device. Copy to
    464  * backing store if needed.
    465  */
    466 void
    467 fss_copy_on_write(struct fss_softc *sc, struct buf *bp)
    468 {
    469 	u_int32_t cl, ch, c;
    470 
    471 #ifdef DIAGNOSTIC
    472 	/*
    473 	 * Buffer written on a suspended file system. This is always an error.
    474 	 */
    475 	if (sc->sc_mount &&
    476 	    (sc->sc_mount->mnt_iflag & IMNT_SUSPENDED) == IMNT_SUSPENDED) {
    477 		printf_nolog("fss%d: write while suspended, %lu@%" PRId64 "\n",
    478 		    sc->sc_unit, bp->b_bcount, bp->b_blkno);
    479 #ifdef DEBUG
    480 		db_stack_trace_print((db_expr_t)__builtin_frame_address(0),
    481 		    TRUE, 65535, "", printf_nolog);
    482 #endif /* DEBUG */
    483 	}
    484 #endif /* DIAGNOSTIC */
    485 
    486 	if (!fss_valid(sc))
    487 		return;
    488 
    489 	sc->sc_cowcount++;
    490 
    491 	FSS_STAT_INC(sc, cow_calls);
    492 
    493 	block_to_cluster(sc, bp->b_blkno, 0, &cl, NULL);
    494 	block_to_cluster(sc, bp->b_blkno, bp->b_bcount-1, &ch, NULL);
    495 	for (c = cl; c <= ch; c++) {
    496 		if (!fss_valid(sc))
    497 			break;
    498 
    499 		fss_read_cluster(sc, c);
    500 	}
    501 
    502 	if (--sc->sc_cowcount == 0)
    503 		wakeup(&sc->sc_cowcount);
    504 }
    505 
    506 /*
    507  * Lookup and open needed files.
    508  *
    509  * Returns dev and size of the underlying block device.
    510  * Initialzes the fields sc_mntname, sc_bs_vp, sc_mount and sc_strategy
    511  */
    512 static int
    513 fss_create_files(struct fss_softc *sc, struct fss_set *fss,
    514     dev_t *bdev, off_t *bsize, struct proc *p)
    515 {
    516 	int error;
    517 	struct stat stat;
    518 	struct statfs statfs;
    519 	struct nameidata nd;
    520 	const struct bdevsw *bdevsw;
    521 
    522 	/*
    523 	 * Get the mounted file system.
    524 	 */
    525 
    526 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_mount, p);
    527 	if ((error = namei(&nd)) != 0)
    528 		return error;
    529 
    530 	if ((nd.ni_vp->v_flag & VROOT) != VROOT) {
    531 		vrele(nd.ni_vp);
    532 		return EINVAL;
    533 	}
    534 
    535 	sc->sc_mount = nd.ni_vp->v_mount;
    536 
    537 	/*
    538 	 * Get the block device it is mounted on.
    539 	 */
    540 
    541 	error = VFS_STATFS(sc->sc_mount, &statfs, p);
    542 	vrele(nd.ni_vp);
    543 	if (error != 0)
    544 		return error;
    545 
    546 	memcpy(sc->sc_mntname, statfs.f_mntonname, MNAMELEN);
    547 
    548 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE, statfs.f_mntfromname, p);
    549 	if ((error = namei(&nd)) != 0)
    550 		return error;
    551 
    552 	if (nd.ni_vp->v_type != VBLK) {
    553 		vrele(nd.ni_vp);
    554 		return EINVAL;
    555 	}
    556 
    557 	if ((error = vn_stat(nd.ni_vp, &stat, p)) != 0) {
    558 		vrele(nd.ni_vp);
    559 		return error;
    560 	}
    561 
    562 	*bdev = nd.ni_vp->v_rdev;
    563 	*bsize = stat.st_size;
    564 	vrele(nd.ni_vp);
    565 
    566 	if ((bdevsw = bdevsw_lookup(*bdev)) == NULL)
    567 		return EINVAL;
    568 	sc->sc_strategy = bdevsw->d_strategy;
    569 
    570 	/*
    571 	 * Get the backing store
    572 	 */
    573 
    574 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore, p);
    575 	if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0)
    576 		return error;
    577 	VOP_UNLOCK(nd.ni_vp, 0);
    578 
    579 	sc->sc_bs_vp = nd.ni_vp;
    580 
    581 	if (nd.ni_vp->v_type != VREG && nd.ni_vp->v_type != VCHR)
    582 		return EINVAL;
    583 
    584 	if (nd.ni_vp->v_mount == sc->sc_mount)
    585 		return EDEADLK;
    586 
    587 	if (sc->sc_bs_vp->v_type == VREG) {
    588 		error = VFS_STATFS(sc->sc_bs_vp->v_mount, &statfs, p);
    589 		if (error != 0)
    590 			return error;
    591 		sc->sc_bs_bsize = statfs.f_iosize;
    592 	} else
    593 		sc->sc_bs_bsize = DEV_BSIZE;
    594 
    595 	/*
    596 	 * As all IO to from/to the backing store goes through
    597 	 * VOP_STRATEGY() clean the buffer cache to prevent
    598 	 * cache incoherencies.
    599 	 */
    600 	if ((error = vinvalbuf(sc->sc_bs_vp, V_SAVE, p->p_ucred, p, 0, 0)) != 0)
    601 		return error;
    602 
    603 	return 0;
    604 }
    605 
    606 /*
    607  * Create a snapshot.
    608  */
    609 static int
    610 fss_create_snapshot(struct fss_softc *sc, struct fss_set *fss, struct proc *p)
    611 {
    612 	int len, error;
    613 	dev_t bdev;
    614 	off_t bsize;
    615 
    616 	/*
    617 	 * Open needed files.
    618 	 */
    619 	if ((error = fss_create_files(sc, fss, &bdev, &bsize, p)) != 0)
    620 		goto bad;
    621 
    622 	/*
    623 	 * Set parameters.
    624 	 */
    625 	if (fss->fss_csize == 0)
    626 		sc->sc_clsize = MAXPHYS;
    627 	else if (fss->fss_csize < 0 || (fss->fss_csize & (DEV_BSIZE-1)) != 0) {
    628 		error = EINVAL;
    629 		goto bad;
    630 	} else if (bsize/fss->fss_csize > FSS_CLUSTER_MAX)
    631 		sc->sc_clsize = (bsize/FSS_CLUSTER_MAX+DEV_BSIZE-1) &
    632 		    ~(DEV_BSIZE-1);
    633 	else
    634 		sc->sc_clsize = fss->fss_csize;
    635 
    636 	if (sc->sc_clsize <= 8192)
    637 		sc->sc_cache_size = 32;
    638 	else if (sc->sc_clsize <= 65536)
    639 		sc->sc_cache_size = 8;
    640 	else
    641 		sc->sc_cache_size = 4;
    642 
    643 	block_to_cluster(sc, btodb(bsize)-1, DEV_BSIZE-1,
    644 	    &sc->sc_clcount, &sc->sc_cllast);
    645 	sc->sc_clcount += 1;
    646 	sc->sc_cllast += 1;
    647 
    648 	len = sc->sc_clcount*sizeof(u_int32_t);
    649 	sc->sc_indir_size = (len+sc->sc_clsize-1)/sc->sc_clsize;
    650 	sc->sc_clnext = sc->sc_indir_size;
    651 	sc->sc_indir_cur = 0;
    652 
    653 	if ((error = fss_softc_alloc(sc)) != 0)
    654 		goto bad;
    655 
    656 	/* XXX FSSNAP_PREPARE */
    657 
    658 	/*
    659 	 * Activate the snapshot.
    660 	 */
    661 
    662 	if ((error = vfs_write_suspend(sc->sc_mount)) != 0)
    663 		goto bad;
    664 
    665 	microtime(&sc->sc_time);
    666 
    667 	/* XXX FSSNAP_CREATE */
    668 
    669 	if (error == 0) {
    670 		sc->sc_flags |= FSS_ACTIVE;
    671 		sc->sc_bdev = bdev;
    672 	}
    673 
    674 	vfs_write_resume(sc->sc_mount);
    675 
    676 	if (error != 0)
    677 		goto bad;
    678 
    679 #ifdef DEBUG
    680 	printf("fss%d: %s snapshot active\n", sc->sc_unit, sc->sc_mntname);
    681 	printf("fss%d: %u clusters of %u, %u cache slots, %u indir clusters\n",
    682 	    sc->sc_unit, sc->sc_clcount, sc->sc_clsize,
    683 	    sc->sc_cache_size, sc->sc_indir_size);
    684 #endif
    685 
    686 	return 0;
    687 
    688 bad:
    689 	fss_softc_free(sc);
    690 	if (sc->sc_bs_vp != NULL)
    691 		vn_close(sc->sc_bs_vp, FREAD|FWRITE, p->p_ucred, p);
    692 	sc->sc_bs_vp = NULL;
    693 
    694 	return error;
    695 }
    696 
    697 /*
    698  * Delete a snapshot.
    699  */
    700 static int
    701 fss_delete_snapshot(struct fss_softc *sc, struct proc *p)
    702 {
    703 	int s;
    704 
    705 	s = splbio();
    706 	sc->sc_flags &= ~(FSS_ACTIVE|FSS_ERROR);
    707 	splx(s);
    708 
    709 	while (sc->sc_cowcount > 0) {
    710 		tsleep(&sc->sc_cowcount, PRIBIO, "cowwait1", 0);
    711 	}
    712 
    713 	sc->sc_mount = NULL;
    714 	sc->sc_bdev = NODEV;
    715 	fss_softc_free(sc);
    716 	vn_close(sc->sc_bs_vp, FREAD|FWRITE, p->p_ucred, p);
    717 	sc->sc_bs_vp = NULL;
    718 
    719 	/* XXX FSSNAP_DESTROY */
    720 
    721 	FSS_STAT_CLEAR(sc);
    722 
    723 	return 0;
    724 }
    725 
    726 /*
    727  * Convert disk block with offset to backing store cluster with offset.
    728  */
    729 static inline void
    730 block_to_cluster(struct fss_softc *sc, daddr_t blkno, long off,
    731                  u_int32_t *cblk, long *coff)
    732 {
    733 	blkno = dbtob(blkno)+off;
    734 	if (cblk != NULL)
    735 		*cblk = blkno/sc->sc_clsize;
    736 	if (coff != NULL)
    737 		*coff = blkno%sc->sc_clsize;
    738 }
    739 
    740 /*
    741  * A read from the snapshotted block device has completed.
    742  */
    743 static void
    744 fss_cluster_iodone(struct buf *bp)
    745 {
    746 	int s;
    747 	struct fss_cache *scp = bp->b_private;
    748 
    749 	s = splbio();
    750 
    751 	if (bp->b_flags & B_EINTR)
    752 		fss_error(scp->fc_softc, "fs read interrupted");
    753 	if (bp->b_flags & B_ERROR)
    754 		fss_error(scp->fc_softc, "fs read error %d", bp->b_error);
    755 
    756 	if (bp->b_vp != NULL)
    757 		brelvp(bp);
    758 
    759 	if (--scp->fc_xfercount == 0)
    760 		wakeup(&scp->fc_data);
    761 
    762 	pool_put(&bufpool, bp);
    763 
    764 	splx(s);
    765 }
    766 
    767 /*
    768  * Read a cluster from the snapshotted block device to the cache.
    769  */
    770 static void
    771 fss_read_cluster(struct fss_softc *sc, u_int32_t cl)
    772 {
    773 	int s, todo, len;
    774 	caddr_t addr;
    775 	daddr_t dblk;
    776 	struct buf *bp;
    777 	struct fss_cache *scp, *scl;
    778 
    779 	/*
    780 	 * Get a free cache slot.
    781 	 */
    782 	scl = sc->sc_cache+sc->sc_cache_size;
    783 
    784 restart:
    785 	if (isset(sc->sc_copied, cl)) {
    786 		return;
    787 	}
    788 
    789 	for (scp = sc->sc_cache; scp < scl; scp++)
    790 		if (scp->fc_type != FSS_CACHE_FREE &&
    791 		    scp->fc_cluster == cl) {
    792 			tsleep(&scp->fc_type, PRIBIO, "cowwait2", 0);
    793 			goto restart;
    794 		}
    795 
    796 	for (scp = sc->sc_cache; scp < scl; scp++)
    797 		if (scp->fc_type == FSS_CACHE_FREE) {
    798 			scp->fc_type = FSS_CACHE_BUSY;
    799 			scp->fc_cluster = cl;
    800 			break;
    801 		}
    802 	if (scp >= scl) {
    803 		FSS_STAT_INC(sc, cow_cache_full);
    804 		tsleep(&sc->sc_cache, PRIBIO, "cowwait3", 0);
    805 		goto restart;
    806 	}
    807 
    808 	/*
    809 	 * Start the read.
    810 	 */
    811 	FSS_STAT_INC(sc, cow_copied);
    812 
    813 	dblk = cl*btodb(sc->sc_clsize);
    814 	addr = scp->fc_data;
    815 	if (cl == sc->sc_clcount-1) {
    816 		todo = sc->sc_cllast;
    817 		memset(addr+todo, 0, sc->sc_clsize-todo);
    818 	} else
    819 		todo = sc->sc_clsize;
    820 	while (todo > 0) {
    821 		len = todo;
    822 		if (len > MAXPHYS)
    823 			len = MAXPHYS;
    824 
    825 		s = splbio();
    826 		bp = pool_get(&bufpool, PR_WAITOK);
    827 		splx(s);
    828 
    829 		BUF_INIT(bp);
    830 		bp->b_flags = B_READ|B_CALL;
    831 		bp->b_bcount = len;
    832 		bp->b_bufsize = bp->b_bcount;
    833 		bp->b_error = 0;
    834 		bp->b_data = addr;
    835 		bp->b_blkno = bp->b_rawblkno = dblk;
    836 		bp->b_proc = NULL;
    837 		bp->b_dev = sc->sc_bdev;
    838 		bp->b_vp = NULLVP;
    839 		bp->b_private = scp;
    840 		bp->b_iodone = fss_cluster_iodone;
    841 
    842 		(*sc->sc_strategy)(bp);
    843 
    844 		s = splbio();
    845 		scp->fc_xfercount++;
    846 		splx(s);
    847 
    848 		dblk += btodb(len);
    849 		addr += len;
    850 		todo -= len;
    851 	}
    852 
    853 	/*
    854 	 * Wait for all read requests to complete.
    855 	 */
    856 	s = splbio();
    857 	while (scp->fc_xfercount > 0)
    858 		tsleep(&scp->fc_data, PRIBIO, "cowwait", 0);
    859 	splx(s);
    860 
    861 	scp->fc_type = FSS_CACHE_VALID;
    862 	setbit(sc->sc_copied, scp->fc_cluster);
    863 	wakeup(&sc->sc_bs_proc);
    864 }
    865 
    866 /*
    867  * Write a cluster from the cache to the backing store.
    868  */
    869 static int
    870 fss_write_cluster(struct fss_cache *scp, u_int32_t cl)
    871 {
    872 	int s, error, todo, len, nra;
    873 	daddr_t nbn;
    874 	caddr_t addr;
    875 	off_t pos;
    876 	struct buf *bp;
    877 	struct vnode *vp;
    878 	struct fss_softc *sc;
    879 
    880 	error = 0;
    881 	sc = scp->fc_softc;
    882 
    883 	pos = (off_t)cl*sc->sc_clsize;
    884 	addr = scp->fc_data;
    885 	todo = sc->sc_clsize;
    886 
    887 	while (todo > 0) {
    888 		vn_lock(sc->sc_bs_vp, LK_EXCLUSIVE|LK_RETRY);
    889 		error = VOP_BMAP(sc->sc_bs_vp, pos/sc->sc_bs_bsize,
    890 		    &vp, &nbn, &nra);
    891 		VOP_UNLOCK(sc->sc_bs_vp, 0);
    892 		if (error == 0 && nbn == (daddr_t)-1)
    893 			error = EIO;
    894 		if (error)
    895 			break;
    896 
    897 		len = (nra+1)*sc->sc_bs_bsize-pos%sc->sc_bs_bsize;
    898 		if (len > todo)
    899 			len = todo;
    900 
    901 		s = splbio();
    902 		bp = pool_get(&bufpool, PR_WAITOK);
    903 		splx(s);
    904 
    905 		BUF_INIT(bp);
    906 		bp->b_flags = B_CALL;
    907 		bp->b_bcount = len;
    908 		bp->b_bufsize = bp->b_bcount;
    909 		bp->b_error = 0;
    910 		bp->b_data = addr;
    911 		bp->b_blkno = bp->b_rawblkno = nbn+btodb(pos%sc->sc_bs_bsize);
    912 		bp->b_proc = NULL;
    913 		bp->b_vp = NULLVP;
    914 		bp->b_private = scp;
    915 		bp->b_iodone = fss_cluster_iodone;
    916 		bgetvp(vp, bp);
    917 		bp->b_vp->v_numoutput++;
    918 
    919 		VOP_STRATEGY(bp);
    920 
    921 		s = splbio();
    922 		scp->fc_xfercount++;
    923 		splx(s);
    924 
    925 		pos += len;
    926 		addr += len;
    927 		todo -= len;
    928 	}
    929 
    930 	/*
    931 	 * Wait for all write requests to complete.
    932 	 */
    933 	s = splbio();
    934 	while (scp->fc_xfercount > 0)
    935 		tsleep(&scp->fc_data, PRIBIO, "bswwait", 0);
    936 	splx(s);
    937 
    938 	return error;
    939 }
    940 
    941 /*
    942  * Read/write clusters from/to backing store.
    943  */
    944 static int
    945 fss_bs_io(struct fss_softc *sc, fss_io_type rw,
    946     u_int32_t cl, long off, int len, caddr_t data)
    947 {
    948 	int s, error, todo, count, nra;
    949 	off_t pos;
    950 	daddr_t nbn;
    951 	struct buf *bp;
    952 	struct vnode *vp;
    953 
    954 	todo = len;
    955 	pos = (off_t)cl*sc->sc_clsize+off;
    956 	error = 0;
    957 
    958 	while (todo > 0) {
    959 		vn_lock(sc->sc_bs_vp, LK_EXCLUSIVE|LK_RETRY);
    960 		error = VOP_BMAP(sc->sc_bs_vp, pos/sc->sc_bs_bsize,
    961 		    &vp, &nbn, &nra);
    962 		VOP_UNLOCK(sc->sc_bs_vp, 0);
    963 		if (error == 0 && nbn == (daddr_t)-1)
    964 			error = EIO;
    965 		if (error)
    966 			break;
    967 
    968 		count = (nra+1)*sc->sc_bs_bsize-pos%sc->sc_bs_bsize;
    969 		if (count > todo)
    970 			count = todo;
    971 
    972 		s = splbio();
    973 		bp = pool_get(&bufpool, PR_WAITOK);
    974 		splx(s);
    975 
    976 		BUF_INIT(bp);
    977 		bp->b_flags = (rw == FSS_READ ? B_READ : 0);
    978 		bp->b_bcount = count;
    979 		bp->b_bufsize = bp->b_bcount;
    980 		bp->b_error = 0;
    981 		bp->b_data = data;
    982 		bp->b_blkno = bp->b_rawblkno = nbn+btodb(pos%sc->sc_bs_bsize);
    983 		bp->b_proc = NULL;
    984 		bp->b_vp = NULLVP;
    985 		bgetvp(vp, bp);
    986 		if ((bp->b_flags & B_READ) == 0)
    987 			bp->b_vp->v_numoutput++;
    988 		VOP_STRATEGY(bp);
    989 
    990 		error = biowait(bp);
    991 
    992 		if (bp->b_vp != NULL)
    993 			brelvp(bp);
    994 
    995 		s = splbio();
    996 		pool_put(&bufpool, bp);
    997 		splx(s);
    998 
    999 		if (error)
   1000 			break;
   1001 
   1002 		todo -= count;
   1003 		data += count;
   1004 		pos += count;
   1005 	}
   1006 
   1007 	return error;
   1008 }
   1009 
   1010 /*
   1011  * Get a pointer to the indirect slot for this cluster.
   1012  */
   1013 static u_int32_t *
   1014 fss_bs_indir(struct fss_softc *sc, u_int32_t cl)
   1015 {
   1016 	u_int32_t icl;
   1017 	int ioff;
   1018 
   1019 	icl = cl/(sc->sc_clsize/sizeof(u_int32_t));
   1020 	ioff = cl%(sc->sc_clsize/sizeof(u_int32_t));
   1021 
   1022 	if (sc->sc_indir_cur == icl)
   1023 		return &sc->sc_indir_data[ioff];
   1024 
   1025 	if (sc->sc_indir_dirty) {
   1026 		FSS_STAT_INC(sc, indir_write);
   1027 		if (fss_bs_io(sc, FSS_WRITE, sc->sc_indir_cur, 0,
   1028 		    sc->sc_clsize, (caddr_t)sc->sc_indir_data) != 0)
   1029 			return NULL;
   1030 		setbit(sc->sc_indir_valid, sc->sc_indir_cur);
   1031 	}
   1032 
   1033 	sc->sc_indir_dirty = 0;
   1034 	sc->sc_indir_cur = icl;
   1035 
   1036 	if (isset(sc->sc_indir_valid, sc->sc_indir_cur)) {
   1037 		FSS_STAT_INC(sc, indir_read);
   1038 		if (fss_bs_io(sc, FSS_READ, sc->sc_indir_cur, 0,
   1039 		    sc->sc_clsize, (caddr_t)sc->sc_indir_data) != 0)
   1040 			return NULL;
   1041 	} else
   1042 		memset(sc->sc_indir_data, 0, sc->sc_clsize);
   1043 
   1044 	return &sc->sc_indir_data[ioff];
   1045 }
   1046 
   1047 /*
   1048  * The kernel thread (one for every active snapshot).
   1049  *
   1050  * After wakeup it cleans the cache and runs the I/O requests.
   1051  */
   1052 static void
   1053 fss_bs_thread(void *arg)
   1054 {
   1055 	int error, len, nfreed, nio, s;
   1056 	long off;
   1057 	caddr_t addr;
   1058 	u_int32_t c, cl, ch, *indirp;
   1059 	struct buf *bp, *nbp;
   1060 	struct fss_softc *sc;
   1061 	struct fss_cache *scp, *scl;
   1062 
   1063 	sc = arg;
   1064 
   1065 	scl = sc->sc_cache+sc->sc_cache_size;
   1066 
   1067 	s = splbio();
   1068 	nbp = pool_get(&bufpool, PR_WAITOK);
   1069 	splx(s);
   1070 
   1071 	nfreed = nio = 1;		/* Dont sleep the first time */
   1072 
   1073 	for (;;) {
   1074 		if (nfreed == 0 && nio == 0)
   1075 			tsleep(&sc->sc_bs_proc, PVM, "fssbs", 0);
   1076 		if ((sc->sc_flags & FSS_BS_THREAD) == 0) {
   1077 			s = splbio();
   1078 			pool_put(&bufpool, nbp);
   1079 			splx(s);
   1080 #ifdef FSS_STATISTICS
   1081 			printf("fss%d: cow called %" PRId64 " times,"
   1082 			    " copied %" PRId64 " clusters,"
   1083 			    " cache full %" PRId64 " times\n",
   1084 			    sc->sc_unit,
   1085 			    FSS_STAT_VAL(sc, cow_calls),
   1086 			    FSS_STAT_VAL(sc, cow_copied),
   1087 			    FSS_STAT_VAL(sc, cow_cache_full));
   1088 			printf("fss%d: %" PRId64 " indir reads,"
   1089 			    " %" PRId64 " indir writes\n",
   1090 			    sc->sc_unit,
   1091 			    FSS_STAT_VAL(sc, indir_read),
   1092 			    FSS_STAT_VAL(sc, indir_write));
   1093 #endif /* FSS_STATISTICS */
   1094 			sc->sc_bs_proc = NULL;
   1095 			kthread_exit(0);
   1096 		}
   1097 
   1098 		/*
   1099 		 * Clean the cache
   1100 		 */
   1101 		nfreed = 0;
   1102 		for (scp = sc->sc_cache; scp < scl; scp++) {
   1103 			if (scp->fc_type != FSS_CACHE_VALID)
   1104 				continue;
   1105 			indirp = fss_bs_indir(sc, scp->fc_cluster);
   1106 			if (indirp != NULL) {
   1107 				error = fss_write_cluster(scp, sc->sc_clnext);
   1108 			} else
   1109 				error = EIO;
   1110 
   1111 			if (error == 0) {
   1112 				*indirp = sc->sc_clnext++;
   1113 				sc->sc_indir_dirty = 1;
   1114 			} else
   1115 				fss_error(sc, "write bs error %d", error);
   1116 
   1117 			scp->fc_type = FSS_CACHE_FREE;
   1118 			nfreed++;
   1119 			wakeup(&scp->fc_type);
   1120 		}
   1121 		if (nfreed)
   1122 			wakeup(&sc->sc_cache);
   1123 
   1124 		/*
   1125 		 * Process I/O requests
   1126 		 */
   1127 		nio = 0;
   1128 
   1129 		if ((bp = BUFQ_GET(&sc->sc_bufq)) == NULL)
   1130 			continue;
   1131 
   1132 		nio++;
   1133 
   1134 		if (!fss_valid(sc)) {
   1135 			bp->b_error = ENXIO;
   1136 			bp->b_flags |= B_ERROR;
   1137 			bp->b_resid = bp->b_bcount;
   1138 			biodone(bp);
   1139 			continue;
   1140 		}
   1141 
   1142 		/*
   1143 		 * First read from the snapshotted block device.
   1144 		 * XXX Split to only read those parts that have not
   1145 		 * been saved to backing store?
   1146 		 */
   1147 		BUF_INIT(nbp);
   1148 		nbp->b_flags = B_READ;
   1149 		nbp->b_bcount = bp->b_bcount;
   1150 		nbp->b_bufsize = bp->b_bcount;
   1151 		nbp->b_error = 0;
   1152 		nbp->b_data = bp->b_data;
   1153 		nbp->b_blkno = nbp->b_rawblkno = bp->b_blkno;
   1154 		nbp->b_proc = bp->b_proc;
   1155 		nbp->b_dev = sc->sc_bdev;
   1156 		nbp->b_vp = NULLVP;
   1157 
   1158 		(*sc->sc_strategy)(nbp);
   1159 
   1160 		if (biowait(nbp) != 0) {
   1161 			bp->b_resid = bp->b_bcount;
   1162 			bp->b_error = nbp->b_error;
   1163 			bp->b_flags |= B_ERROR;
   1164 			biodone(bp);
   1165 			continue;
   1166 		}
   1167 
   1168 		block_to_cluster(sc, bp->b_blkno, 0, &cl, &off);
   1169 		block_to_cluster(sc, bp->b_blkno, bp->b_bcount-1, &ch, NULL);
   1170 		bp->b_resid = bp->b_bcount;
   1171 		addr = bp->b_data;
   1172 
   1173 		/*
   1174 		 * Replace those parts that have been saved to backing store.
   1175 		 */
   1176 		for (c = cl; c <= ch;
   1177 		    c++, off = 0, bp->b_resid -= len, addr += len) {
   1178 			len = sc->sc_clsize-off;
   1179 			if (len > bp->b_resid)
   1180 				len = bp->b_resid;
   1181 
   1182 			if (isclr(sc->sc_copied, c))
   1183 				continue;
   1184 
   1185 			indirp = fss_bs_indir(sc, c);
   1186 			if (indirp == NULL || *indirp == 0) {
   1187 				/*
   1188 				 * Not on backing store. Either in cache
   1189 				 * or hole in the snapshotted block device.
   1190 				 */
   1191 				for (scp = sc->sc_cache; scp < scl; scp++)
   1192 					if (scp->fc_type == FSS_CACHE_VALID &&
   1193 					    scp->fc_cluster == c)
   1194 						break;
   1195 				if (scp < scl)
   1196 					memcpy(addr, scp->fc_data+off, len);
   1197 				else
   1198 					memset(addr, 0, len);
   1199 				continue;
   1200 			}
   1201 			/*
   1202 			 * Read from backing store.
   1203 			 */
   1204 			if ((error = fss_bs_io(sc, FSS_READ, *indirp,
   1205 			    off, len, addr)) != 0) {
   1206 				bp->b_resid = bp->b_bcount;
   1207 				bp->b_error = error;
   1208 				bp->b_flags |= B_ERROR;
   1209 				break;
   1210 			}
   1211 		}
   1212 
   1213 		biodone(bp);
   1214 	}
   1215 }
   1216