xref: /netbsd-src/sys/dev/fss.c (revision 267197ec1eebfcb9810ea27a89625b6ddf68e3e7)
1 /*	$NetBSD: fss.c,v 1.43 2008/01/04 21:17:47 ad 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.43 2008/01/04 21:17:47 ad Exp $");
47 
48 #include "fss.h"
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/namei.h>
53 #include <sys/proc.h>
54 #include <sys/errno.h>
55 #include <sys/buf.h>
56 #include <sys/malloc.h>
57 #include <sys/ioctl.h>
58 #include <sys/disklabel.h>
59 #include <sys/device.h>
60 #include <sys/disk.h>
61 #include <sys/stat.h>
62 #include <sys/mount.h>
63 #include <sys/vnode.h>
64 #include <sys/file.h>
65 #include <sys/uio.h>
66 #include <sys/conf.h>
67 #include <sys/kthread.h>
68 #include <sys/fstrans.h>
69 #include <sys/simplelock.h>
70 
71 #include <miscfs/specfs/specdev.h>
72 
73 #include <dev/fssvar.h>
74 
75 #include <machine/stdarg.h>
76 
77 #ifdef DEBUG
78 #define FSS_STATISTICS
79 #endif
80 
81 #ifdef FSS_STATISTICS
82 struct fss_stat {
83 	u_int64_t	cow_calls;
84 	u_int64_t	cow_copied;
85 	u_int64_t	cow_cache_full;
86 	u_int64_t	indir_read;
87 	u_int64_t	indir_write;
88 };
89 
90 static struct fss_stat fss_stat[NFSS];
91 
92 #define FSS_STAT_INC(sc, field)	\
93 			do { \
94 				fss_stat[sc->sc_unit].field++; \
95 			} while (0)
96 #define FSS_STAT_SET(sc, field, value) \
97 			do { \
98 				fss_stat[sc->sc_unit].field = value; \
99 			} while (0)
100 #define FSS_STAT_ADD(sc, field, value) \
101 			do { \
102 				fss_stat[sc->sc_unit].field += value; \
103 			} while (0)
104 #define FSS_STAT_VAL(sc, field) fss_stat[sc->sc_unit].field
105 #define FSS_STAT_CLEAR(sc) \
106 			do { \
107 				memset(&fss_stat[sc->sc_unit], 0, \
108 				    sizeof(struct fss_stat)); \
109 			} while (0)
110 #else /* FSS_STATISTICS */
111 #define FSS_STAT_INC(sc, field)
112 #define FSS_STAT_SET(sc, field, value)
113 #define FSS_STAT_ADD(sc, field, value)
114 #define FSS_STAT_CLEAR(sc)
115 #endif /* FSS_STATISTICS */
116 
117 static struct fss_softc fss_softc[NFSS];
118 
119 void fssattach(int);
120 
121 dev_type_open(fss_open);
122 dev_type_close(fss_close);
123 dev_type_read(fss_read);
124 dev_type_write(fss_write);
125 dev_type_ioctl(fss_ioctl);
126 dev_type_strategy(fss_strategy);
127 dev_type_dump(fss_dump);
128 dev_type_size(fss_size);
129 
130 static int fss_copy_on_write(void *, struct buf *, bool);
131 static inline void fss_error(struct fss_softc *, const char *, ...);
132 static int fss_create_files(struct fss_softc *, struct fss_set *,
133     off_t *, struct lwp *);
134 static int fss_create_snapshot(struct fss_softc *, struct fss_set *,
135     struct lwp *);
136 static int fss_delete_snapshot(struct fss_softc *, struct lwp *);
137 static int fss_softc_alloc(struct fss_softc *);
138 static void fss_softc_free(struct fss_softc *);
139 static void fss_cluster_iodone(struct buf *);
140 static void fss_read_cluster(struct fss_softc *, u_int32_t);
141 static void fss_bs_thread(void *);
142 static int fss_bs_io(struct fss_softc *, fss_io_type,
143     u_int32_t, off_t, int, void *);
144 static u_int32_t *fss_bs_indir(struct fss_softc *, u_int32_t);
145 
146 const struct bdevsw fss_bdevsw = {
147 	fss_open, fss_close, fss_strategy, fss_ioctl,
148 	fss_dump, fss_size, D_DISK
149 };
150 
151 const struct cdevsw fss_cdevsw = {
152 	fss_open, fss_close, fss_read, fss_write, fss_ioctl,
153 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
154 };
155 
156 void
157 fssattach(int num)
158 {
159 	int i;
160 	struct fss_softc *sc;
161 
162 	for (i = 0; i < NFSS; i++) {
163 		sc = &fss_softc[i];
164 		sc->sc_unit = i;
165 		sc->sc_bdev = NODEV;
166 		simple_lock_init(&sc->sc_slock);
167 		mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
168 		bufq_alloc(&sc->sc_bufq, "fcfs", 0);
169 	}
170 }
171 
172 int
173 fss_open(dev_t dev, int flags, int mode, struct lwp *l)
174 {
175 	int s, mflag;
176 	struct fss_softc *sc;
177 
178 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
179 
180 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
181 		return ENODEV;
182 
183 	FSS_LOCK(sc, s);
184 
185 	sc->sc_flags |= mflag;
186 
187 	FSS_UNLOCK(sc, s);
188 
189 	return 0;
190 }
191 
192 int
193 fss_close(dev_t dev, int flags, int mode, struct lwp *l)
194 {
195 	int s, mflag, error;
196 	struct fss_softc *sc;
197 
198 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
199 
200 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
201 		return ENODEV;
202 
203 	FSS_LOCK(sc, s);
204 
205 	if ((sc->sc_flags & (FSS_CDEV_OPEN|FSS_BDEV_OPEN)) == mflag) {
206 		if ((sc->sc_uflags & FSS_UNCONFIG_ON_CLOSE) != 0 &&
207 		    (sc->sc_flags & FSS_ACTIVE) != 0) {
208 			FSS_UNLOCK(sc, s);
209 			error = fss_ioctl(dev, FSSIOCCLR, NULL, FWRITE, l);
210 			if (error)
211 				return error;
212 			FSS_LOCK(sc, s);
213 		}
214 		sc->sc_uflags &= ~FSS_UNCONFIG_ON_CLOSE;
215 	}
216 
217 	sc->sc_flags &= ~mflag;
218 
219 	FSS_UNLOCK(sc, s);
220 
221 	return 0;
222 }
223 
224 void
225 fss_strategy(struct buf *bp)
226 {
227 	int s;
228 	struct fss_softc *sc;
229 
230 	sc = FSS_DEV_TO_SOFTC(bp->b_dev);
231 
232 	FSS_LOCK(sc, s);
233 
234 	if ((bp->b_flags & B_READ) != B_READ ||
235 	    sc == NULL || !FSS_ISVALID(sc)) {
236 
237 		FSS_UNLOCK(sc, s);
238 
239 		bp->b_error = (sc == NULL ? ENODEV : EROFS);
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_lwp);
248 
249 	FSS_UNLOCK(sc, s);
250 }
251 
252 int
253 fss_read(dev_t dev, struct uio *uio, int flags)
254 {
255 	return physio(fss_strategy, NULL, dev, B_READ, minphys, uio);
256 }
257 
258 int
259 fss_write(dev_t dev, struct uio *uio, int flags)
260 {
261 	return physio(fss_strategy, NULL, dev, B_WRITE, minphys, uio);
262 }
263 
264 int
265 fss_ioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
266 {
267 	int error;
268 	struct fss_softc *sc;
269 	struct fss_set *fss = (struct fss_set *)data;
270 	struct fss_get *fsg = (struct fss_get *)data;
271 
272 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
273 		return ENODEV;
274 
275 	switch (cmd) {
276 	case FSSIOCSET:
277 		mutex_enter(&sc->sc_lock);
278 		if ((flag & FWRITE) == 0)
279 			error = EPERM;
280 		else if ((sc->sc_flags & FSS_ACTIVE) != 0)
281 			error = EBUSY;
282 		else
283 			error = fss_create_snapshot(sc, fss, l);
284 		mutex_exit(&sc->sc_lock);
285 		break;
286 
287 	case FSSIOCCLR:
288 		mutex_enter(&sc->sc_lock);
289 		if ((flag & FWRITE) == 0)
290 			error = EPERM;
291 		else if ((sc->sc_flags & FSS_ACTIVE) == 0)
292 			error = ENXIO;
293 		else
294 			error = fss_delete_snapshot(sc, l);
295 		mutex_exit(&sc->sc_lock);
296 		break;
297 
298 	case FSSIOCGET:
299 		mutex_enter(&sc->sc_lock);
300 		switch (sc->sc_flags & (FSS_PERSISTENT | FSS_ACTIVE)) {
301 		case FSS_ACTIVE:
302 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
303 			fsg->fsg_csize = FSS_CLSIZE(sc);
304 			fsg->fsg_time = sc->sc_time;
305 			fsg->fsg_mount_size = sc->sc_clcount;
306 			fsg->fsg_bs_size = sc->sc_clnext;
307 			error = 0;
308 			break;
309 		case FSS_PERSISTENT | FSS_ACTIVE:
310 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
311 			fsg->fsg_csize = 0;
312 			fsg->fsg_time = sc->sc_time;
313 			fsg->fsg_mount_size = 0;
314 			fsg->fsg_bs_size = 0;
315 			error = 0;
316 			break;
317 		default:
318 			error = ENXIO;
319 			break;
320 		}
321 		mutex_exit(&sc->sc_lock);
322 		break;
323 
324 	case FSSIOFSET:
325 		sc->sc_uflags = *(int *)data;
326 		error = 0;
327 		break;
328 
329 	case FSSIOFGET:
330 		*(int *)data = sc->sc_uflags;
331 		error = 0;
332 		break;
333 
334 	default:
335 		error = EINVAL;
336 		break;
337 	}
338 
339 	return error;
340 }
341 
342 int
343 fss_size(dev_t dev)
344 {
345 	return -1;
346 }
347 
348 int
349 fss_dump(dev_t dev, daddr_t blkno, void *va,
350     size_t size)
351 {
352 	return EROFS;
353 }
354 
355 /*
356  * An error occurred reading or writing the snapshot or backing store.
357  * If it is the first error log to console.
358  * The caller holds the simplelock.
359  */
360 static inline void
361 fss_error(struct fss_softc *sc, const char *fmt, ...)
362 {
363 	va_list ap;
364 
365 	if ((sc->sc_flags & (FSS_ACTIVE|FSS_ERROR)) == FSS_ACTIVE) {
366 		va_start(ap, fmt);
367 		printf("fss%d: snapshot invalid: ", sc->sc_unit);
368 		vprintf(fmt, ap);
369 		printf("\n");
370 		va_end(ap);
371 	}
372 	if ((sc->sc_flags & FSS_ACTIVE) == FSS_ACTIVE)
373 		sc->sc_flags |= FSS_ERROR;
374 }
375 
376 /*
377  * Allocate the variable sized parts of the softc and
378  * fork the kernel thread.
379  *
380  * The fields sc_clcount, sc_clshift, sc_cache_size and sc_indir_size
381  * must be initialized.
382  */
383 static int
384 fss_softc_alloc(struct fss_softc *sc)
385 {
386 	int i, len, error;
387 
388 	len = (sc->sc_clcount+NBBY-1)/NBBY;
389 	sc->sc_copied = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
390 	if (sc->sc_copied == NULL)
391 		return(ENOMEM);
392 
393 	len = sc->sc_cache_size*sizeof(struct fss_cache);
394 	sc->sc_cache = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
395 	if (sc->sc_cache == NULL)
396 		return(ENOMEM);
397 
398 	len = FSS_CLSIZE(sc);
399 	for (i = 0; i < sc->sc_cache_size; i++) {
400 		sc->sc_cache[i].fc_type = FSS_CACHE_FREE;
401 		sc->sc_cache[i].fc_softc = sc;
402 		sc->sc_cache[i].fc_xfercount = 0;
403 		sc->sc_cache[i].fc_data = malloc(len, M_TEMP,
404 		    M_WAITOK|M_CANFAIL);
405 		if (sc->sc_cache[i].fc_data == NULL)
406 			return(ENOMEM);
407 	}
408 
409 	len = (sc->sc_indir_size+NBBY-1)/NBBY;
410 	sc->sc_indir_valid = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
411 	if (sc->sc_indir_valid == NULL)
412 		return(ENOMEM);
413 
414 	len = FSS_CLSIZE(sc);
415 	sc->sc_indir_data = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
416 	if (sc->sc_indir_data == NULL)
417 		return(ENOMEM);
418 
419 	if ((error = kthread_create(PRI_BIO, 0, NULL, fss_bs_thread, sc,
420 	    &sc->sc_bs_lwp, "fssbs%d", sc->sc_unit)) != 0)
421 		return error;
422 
423 	sc->sc_flags |= FSS_BS_THREAD;
424 	return 0;
425 }
426 
427 /*
428  * Free the variable sized parts of the softc.
429  */
430 static void
431 fss_softc_free(struct fss_softc *sc)
432 {
433 	int s, i;
434 
435 	if ((sc->sc_flags & FSS_BS_THREAD) != 0) {
436 		FSS_LOCK(sc, s);
437 		sc->sc_flags &= ~FSS_BS_THREAD;
438 		wakeup(&sc->sc_bs_lwp);
439 		while (sc->sc_bs_lwp != NULL)
440 			ltsleep(&sc->sc_bs_lwp, PRIBIO, "fssthread", 0,
441 			    &sc->sc_slock);
442 		FSS_UNLOCK(sc, s);
443 	}
444 
445 	if (sc->sc_copied != NULL)
446 		free(sc->sc_copied, M_TEMP);
447 	sc->sc_copied = NULL;
448 
449 	if (sc->sc_cache != NULL) {
450 		for (i = 0; i < sc->sc_cache_size; i++)
451 			if (sc->sc_cache[i].fc_data != NULL)
452 				free(sc->sc_cache[i].fc_data, M_TEMP);
453 		free(sc->sc_cache, M_TEMP);
454 	}
455 	sc->sc_cache = NULL;
456 
457 	if (sc->sc_indir_valid != NULL)
458 		free(sc->sc_indir_valid, M_TEMP);
459 	sc->sc_indir_valid = NULL;
460 
461 	if (sc->sc_indir_data != NULL)
462 		free(sc->sc_indir_data, M_TEMP);
463 	sc->sc_indir_data = NULL;
464 }
465 
466 /*
467  * Check if an unmount is ok. If forced, set this snapshot into ERROR state.
468  */
469 int
470 fss_umount_hook(struct mount *mp, int forced)
471 {
472 	int i, s;
473 
474 	for (i = 0; i < NFSS; i++) {
475 		FSS_LOCK(&fss_softc[i], s);
476 		if ((fss_softc[i].sc_flags & FSS_ACTIVE) != 0 &&
477 		    fss_softc[i].sc_mount == mp) {
478 			if (forced)
479 				fss_error(&fss_softc[i], "forced unmount");
480 			else {
481 				FSS_UNLOCK(&fss_softc[i], s);
482 				return EBUSY;
483 			}
484 		}
485 		FSS_UNLOCK(&fss_softc[i], s);
486 	}
487 
488 	return 0;
489 }
490 
491 /*
492  * A buffer is written to the snapshotted block device. Copy to
493  * backing store if needed.
494  */
495 static int
496 fss_copy_on_write(void *v, struct buf *bp, bool data_valid)
497 {
498 	int s;
499 	u_int32_t cl, ch, c;
500 	struct fss_softc *sc = v;
501 
502 	FSS_LOCK(sc, s);
503 	if (!FSS_ISVALID(sc)) {
504 		FSS_UNLOCK(sc, s);
505 		return 0;
506 	}
507 
508 	FSS_UNLOCK(sc, s);
509 
510 	FSS_STAT_INC(sc, cow_calls);
511 
512 	cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
513 	ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
514 
515 	for (c = cl; c <= ch; c++)
516 		fss_read_cluster(sc, c);
517 
518 	return 0;
519 }
520 
521 /*
522  * Lookup and open needed files.
523  *
524  * For file system internal snapshot initializes sc_mntname, sc_mount,
525  * sc_bs_vp and sc_time.
526  *
527  * Otherwise returns dev and size of the underlying block device.
528  * Initializes sc_mntname, sc_mount, sc_bdev, sc_bs_vp and sc_mount
529  */
530 static int
531 fss_create_files(struct fss_softc *sc, struct fss_set *fss,
532     off_t *bsize, struct lwp *l)
533 {
534 	int error, bits, fsbsize;
535 	struct timespec ts;
536 	struct partinfo dpart;
537 	struct vattr va;
538 	struct nameidata nd;
539 
540 	/*
541 	 * Get the mounted file system.
542 	 */
543 
544 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_mount);
545 	if ((error = namei(&nd)) != 0)
546 		return error;
547 
548 	if ((nd.ni_vp->v_vflag & VV_ROOT) != VV_ROOT) {
549 		vrele(nd.ni_vp);
550 		return EINVAL;
551 	}
552 
553 	sc->sc_mount = nd.ni_vp->v_mount;
554 	memcpy(sc->sc_mntname, sc->sc_mount->mnt_stat.f_mntonname, MNAMELEN);
555 
556 	vrele(nd.ni_vp);
557 
558 	/*
559 	 * Check for file system internal snapshot.
560 	 */
561 
562 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
563 	if ((error = namei(&nd)) != 0)
564 		return error;
565 
566 	if (nd.ni_vp->v_type == VREG && nd.ni_vp->v_mount == sc->sc_mount) {
567 		vrele(nd.ni_vp);
568 		sc->sc_flags |= FSS_PERSISTENT;
569 
570 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
571 		if ((error = vn_open(&nd, FREAD, 0)) != 0)
572 			return error;
573 		sc->sc_bs_vp = nd.ni_vp;
574 
575 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
576 		bits = sizeof(sc->sc_bs_bshift)*NBBY;
577 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < bits;
578 		    sc->sc_bs_bshift++)
579 			if (FSS_FSBSIZE(sc) == fsbsize)
580 				break;
581 		if (sc->sc_bs_bshift >= bits) {
582 			VOP_UNLOCK(sc->sc_bs_vp, 0);
583 			return EINVAL;
584 		}
585 
586 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
587 		sc->sc_clshift = 0;
588 
589 		error = VFS_SNAPSHOT(sc->sc_mount, sc->sc_bs_vp, &ts);
590 		TIMESPEC_TO_TIMEVAL(&sc->sc_time, &ts);
591 
592 		VOP_UNLOCK(sc->sc_bs_vp, 0);
593 
594 		return error;
595 	}
596 	vrele(nd.ni_vp);
597 
598 	/*
599 	 * Get the block device it is mounted on.
600 	 */
601 
602 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE,
603 	    sc->sc_mount->mnt_stat.f_mntfromname);
604 	if ((error = namei(&nd)) != 0)
605 		return error;
606 
607 	if (nd.ni_vp->v_type != VBLK) {
608 		vrele(nd.ni_vp);
609 		return EINVAL;
610 	}
611 
612 	error = VOP_IOCTL(nd.ni_vp, DIOCGPART, &dpart, FREAD, l->l_cred);
613 	if (error) {
614 		vrele(nd.ni_vp);
615 		return error;
616 	}
617 
618 	sc->sc_bdev = nd.ni_vp->v_rdev;
619 	*bsize = (off_t)dpart.disklab->d_secsize*dpart.part->p_size;
620 	vrele(nd.ni_vp);
621 
622 	/*
623 	 * Get the backing store
624 	 */
625 
626 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
627 	if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0)
628 		return error;
629 	VOP_UNLOCK(nd.ni_vp, 0);
630 
631 	sc->sc_bs_vp = nd.ni_vp;
632 
633 	if (nd.ni_vp->v_type != VREG && nd.ni_vp->v_type != VCHR)
634 		return EINVAL;
635 
636 	if (sc->sc_bs_vp->v_type == VREG) {
637 		error = VOP_GETATTR(sc->sc_bs_vp, &va, l->l_cred);
638 		if (error != 0)
639 			return error;
640 		sc->sc_bs_size = va.va_size;
641 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
642 		if (fsbsize & (fsbsize-1))	/* No power of two */
643 			return EINVAL;
644 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < 32;
645 		    sc->sc_bs_bshift++)
646 			if (FSS_FSBSIZE(sc) == fsbsize)
647 				break;
648 		if (sc->sc_bs_bshift >= 32)
649 			return EINVAL;
650 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
651 	} else {
652 		sc->sc_bs_bshift = DEV_BSHIFT;
653 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
654 	}
655 
656 	/*
657 	 * As all IO to from/to the backing store goes through
658 	 * VOP_STRATEGY() clean the buffer cache to prevent
659 	 * cache incoherencies.
660 	 */
661 	if ((error = vinvalbuf(sc->sc_bs_vp, V_SAVE, l->l_cred, l, 0, 0)) != 0)
662 		return error;
663 
664 	return 0;
665 }
666 
667 /*
668  * Create a snapshot.
669  */
670 static int
671 fss_create_snapshot(struct fss_softc *sc, struct fss_set *fss, struct lwp *l)
672 {
673 	int len, error;
674 	u_int32_t csize;
675 	off_t bsize;
676 
677 	bsize = 0;	/* XXX gcc */
678 
679 	/*
680 	 * Open needed files.
681 	 */
682 	if ((error = fss_create_files(sc, fss, &bsize, l)) != 0)
683 		goto bad;
684 
685 	if (sc->sc_flags & FSS_PERSISTENT) {
686 		fss_softc_alloc(sc);
687 		sc->sc_flags |= FSS_ACTIVE;
688 		return 0;
689 	}
690 
691 	/*
692 	 * Set cluster size. Must be a power of two and
693 	 * a multiple of backing store block size.
694 	 */
695 	if (fss->fss_csize <= 0)
696 		csize = MAXPHYS;
697 	else
698 		csize = fss->fss_csize;
699 	if (bsize/csize > FSS_CLUSTER_MAX)
700 		csize = bsize/FSS_CLUSTER_MAX+1;
701 
702 	for (sc->sc_clshift = sc->sc_bs_bshift; sc->sc_clshift < 32;
703 	    sc->sc_clshift++)
704 		if (FSS_CLSIZE(sc) >= csize)
705 			break;
706 	if (sc->sc_clshift >= 32) {
707 		error = EINVAL;
708 		goto bad;
709 	}
710 	sc->sc_clmask = FSS_CLSIZE(sc)-1;
711 
712 	/*
713 	 * Set number of cache slots.
714 	 */
715 	if (FSS_CLSIZE(sc) <= 8192)
716 		sc->sc_cache_size = 32;
717 	else if (FSS_CLSIZE(sc) <= 65536)
718 		sc->sc_cache_size = 8;
719 	else
720 		sc->sc_cache_size = 4;
721 
722 	/*
723 	 * Set number of clusters and size of last cluster.
724 	 */
725 	sc->sc_clcount = FSS_BTOCL(sc, bsize-1)+1;
726 	sc->sc_clresid = FSS_CLOFF(sc, bsize-1)+1;
727 
728 	/*
729 	 * Set size of indirect table.
730 	 */
731 	len = sc->sc_clcount*sizeof(u_int32_t);
732 	sc->sc_indir_size = FSS_BTOCL(sc, len)+1;
733 	sc->sc_clnext = sc->sc_indir_size;
734 	sc->sc_indir_cur = 0;
735 
736 	if ((error = fss_softc_alloc(sc)) != 0)
737 		goto bad;
738 
739 	/*
740 	 * Activate the snapshot.
741 	 */
742 
743 	if ((error = vfs_suspend(sc->sc_mount, 0)) != 0)
744 		goto bad;
745 
746 	microtime(&sc->sc_time);
747 
748 	if (error == 0)
749 		error = fscow_establish(sc->sc_mount,
750 		    fss_copy_on_write, sc);
751 	if (error == 0)
752 		sc->sc_flags |= FSS_ACTIVE;
753 
754 	vfs_resume(sc->sc_mount);
755 
756 	if (error != 0)
757 		goto bad;
758 
759 #ifdef DEBUG
760 	printf("fss%d: %s snapshot active\n", sc->sc_unit, sc->sc_mntname);
761 	printf("fss%d: %u clusters of %u, %u cache slots, %u indir clusters\n",
762 	    sc->sc_unit, sc->sc_clcount, FSS_CLSIZE(sc),
763 	    sc->sc_cache_size, sc->sc_indir_size);
764 #endif
765 
766 	return 0;
767 
768 bad:
769 	fss_softc_free(sc);
770 	if (sc->sc_bs_vp != NULL) {
771 		if (sc->sc_flags & FSS_PERSISTENT)
772 			vn_close(sc->sc_bs_vp, FREAD, l->l_cred, l);
773 		else
774 			vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred, l);
775 	}
776 	sc->sc_bs_vp = NULL;
777 
778 	return error;
779 }
780 
781 /*
782  * Delete a snapshot.
783  */
784 static int
785 fss_delete_snapshot(struct fss_softc *sc, struct lwp *l)
786 {
787 	int s;
788 
789 	if ((sc->sc_flags & FSS_PERSISTENT) == 0)
790 		fscow_disestablish(sc->sc_mount, fss_copy_on_write, sc);
791 
792 	FSS_LOCK(sc, s);
793 	sc->sc_flags &= ~(FSS_ACTIVE|FSS_ERROR);
794 	sc->sc_mount = NULL;
795 	sc->sc_bdev = NODEV;
796 	FSS_UNLOCK(sc, s);
797 
798 	fss_softc_free(sc);
799 	if (sc->sc_flags & FSS_PERSISTENT)
800 		vn_close(sc->sc_bs_vp, FREAD, l->l_cred, l);
801 	else
802 		vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred, l);
803 	sc->sc_bs_vp = NULL;
804 	sc->sc_flags &= ~FSS_PERSISTENT;
805 
806 	FSS_STAT_CLEAR(sc);
807 
808 	return 0;
809 }
810 
811 /*
812  * A read from the snapshotted block device has completed.
813  */
814 static void
815 fss_cluster_iodone(struct buf *bp)
816 {
817 	int s;
818 	struct fss_cache *scp = bp->b_private;
819 
820 	KASSERT(bp->b_vp == NULL);
821 
822 	FSS_LOCK(scp->fc_softc, s);
823 
824 	if (bp->b_error != 0)
825 		fss_error(scp->fc_softc, "fs read error %d", bp->b_error);
826 
827 	if (--scp->fc_xfercount == 0)
828 		wakeup(&scp->fc_data);
829 
830 	FSS_UNLOCK(scp->fc_softc, s);
831 
832 	putiobuf(bp);
833 }
834 
835 /*
836  * Read a cluster from the snapshotted block device to the cache.
837  */
838 static void
839 fss_read_cluster(struct fss_softc *sc, u_int32_t cl)
840 {
841 	int s, todo, len;
842 	char *addr;
843 	daddr_t dblk;
844 	struct buf *bp;
845 	struct fss_cache *scp, *scl;
846 
847 	/*
848 	 * Get a free cache slot.
849 	 */
850 	scl = sc->sc_cache+sc->sc_cache_size;
851 
852 	FSS_LOCK(sc, s);
853 
854 restart:
855 	if (isset(sc->sc_copied, cl) || !FSS_ISVALID(sc)) {
856 		FSS_UNLOCK(sc, s);
857 		return;
858 	}
859 
860 	for (scp = sc->sc_cache; scp < scl; scp++)
861 		if (scp->fc_type != FSS_CACHE_FREE &&
862 		    scp->fc_cluster == cl) {
863 			ltsleep(&scp->fc_type, PRIBIO, "cowwait2", 0,
864 			    &sc->sc_slock);
865 			goto restart;
866 		}
867 
868 	for (scp = sc->sc_cache; scp < scl; scp++)
869 		if (scp->fc_type == FSS_CACHE_FREE) {
870 			scp->fc_type = FSS_CACHE_BUSY;
871 			scp->fc_cluster = cl;
872 			break;
873 		}
874 	if (scp >= scl) {
875 		FSS_STAT_INC(sc, cow_cache_full);
876 		ltsleep(&sc->sc_cache, PRIBIO, "cowwait3", 0, &sc->sc_slock);
877 		goto restart;
878 	}
879 
880 	FSS_UNLOCK(sc, s);
881 
882 	/*
883 	 * Start the read.
884 	 */
885 	FSS_STAT_INC(sc, cow_copied);
886 
887 	dblk = btodb(FSS_CLTOB(sc, cl));
888 	addr = scp->fc_data;
889 	if (cl == sc->sc_clcount-1) {
890 		todo = sc->sc_clresid;
891 		memset((char *)addr + todo, 0, FSS_CLSIZE(sc) - todo);
892 	} else
893 		todo = FSS_CLSIZE(sc);
894 	while (todo > 0) {
895 		len = todo;
896 		if (len > MAXPHYS)
897 			len = MAXPHYS;
898 
899 		bp = getiobuf(NULL, true);
900 		bp->b_flags = B_READ;
901 		bp->b_bcount = len;
902 		bp->b_bufsize = bp->b_bcount;
903 		bp->b_error = 0;
904 		bp->b_data = addr;
905 		bp->b_blkno = dblk;
906 		bp->b_proc = NULL;
907 		bp->b_dev = sc->sc_bdev;
908 		bp->b_private = scp;
909 		bp->b_iodone = fss_cluster_iodone;
910 
911 		bdev_strategy(bp);
912 
913 		FSS_LOCK(sc, s);
914 		scp->fc_xfercount++;
915 		FSS_UNLOCK(sc, s);
916 
917 		dblk += btodb(len);
918 		addr += len;
919 		todo -= len;
920 	}
921 
922 	/*
923 	 * Wait for all read requests to complete.
924 	 */
925 	FSS_LOCK(sc, s);
926 	while (scp->fc_xfercount > 0)
927 		ltsleep(&scp->fc_data, PRIBIO, "cowwait", 0, &sc->sc_slock);
928 
929 	scp->fc_type = FSS_CACHE_VALID;
930 	setbit(sc->sc_copied, scp->fc_cluster);
931 	FSS_UNLOCK(sc, s);
932 
933 	wakeup(&sc->sc_bs_lwp);
934 }
935 
936 /*
937  * Read/write clusters from/to backing store.
938  * For persistent snapshots must be called with cl == 0. off is the
939  * offset into the snapshot.
940  */
941 static int
942 fss_bs_io(struct fss_softc *sc, fss_io_type rw,
943     u_int32_t cl, off_t off, int len, void *data)
944 {
945 	int error;
946 
947 	off += FSS_CLTOB(sc, cl);
948 
949 	vn_lock(sc->sc_bs_vp, LK_EXCLUSIVE|LK_RETRY);
950 
951 	error = vn_rdwr((rw == FSS_READ ? UIO_READ : UIO_WRITE), sc->sc_bs_vp,
952 	    data, len, off, UIO_SYSSPACE, IO_UNIT|IO_NODELOCKED,
953 	    sc->sc_bs_lwp->l_cred, NULL, NULL);
954 	if (error == 0) {
955 		mutex_enter(&sc->sc_bs_vp->v_interlock);
956 		error = VOP_PUTPAGES(sc->sc_bs_vp, trunc_page(off),
957 		    round_page(off+len), PGO_CLEANIT|PGO_SYNCIO|PGO_FREE);
958 	}
959 
960 	VOP_UNLOCK(sc->sc_bs_vp, 0);
961 
962 	return error;
963 }
964 
965 /*
966  * Get a pointer to the indirect slot for this cluster.
967  */
968 static u_int32_t *
969 fss_bs_indir(struct fss_softc *sc, u_int32_t cl)
970 {
971 	u_int32_t icl;
972 	int ioff;
973 
974 	icl = cl/(FSS_CLSIZE(sc)/sizeof(u_int32_t));
975 	ioff = cl%(FSS_CLSIZE(sc)/sizeof(u_int32_t));
976 
977 	if (sc->sc_indir_cur == icl)
978 		return &sc->sc_indir_data[ioff];
979 
980 	if (sc->sc_indir_dirty) {
981 		FSS_STAT_INC(sc, indir_write);
982 		if (fss_bs_io(sc, FSS_WRITE, sc->sc_indir_cur, 0,
983 		    FSS_CLSIZE(sc), (void *)sc->sc_indir_data) != 0)
984 			return NULL;
985 		setbit(sc->sc_indir_valid, sc->sc_indir_cur);
986 	}
987 
988 	sc->sc_indir_dirty = 0;
989 	sc->sc_indir_cur = icl;
990 
991 	if (isset(sc->sc_indir_valid, sc->sc_indir_cur)) {
992 		FSS_STAT_INC(sc, indir_read);
993 		if (fss_bs_io(sc, FSS_READ, sc->sc_indir_cur, 0,
994 		    FSS_CLSIZE(sc), (void *)sc->sc_indir_data) != 0)
995 			return NULL;
996 	} else
997 		memset(sc->sc_indir_data, 0, FSS_CLSIZE(sc));
998 
999 	return &sc->sc_indir_data[ioff];
1000 }
1001 
1002 /*
1003  * The kernel thread (one for every active snapshot).
1004  *
1005  * After wakeup it cleans the cache and runs the I/O requests.
1006  */
1007 static void
1008 fss_bs_thread(void *arg)
1009 {
1010 	int error, len, nfreed, nio, s;
1011 	long off;
1012 	char *addr;
1013 	u_int32_t c, cl, ch, *indirp;
1014 	struct buf *bp, *nbp;
1015 	struct fss_softc *sc;
1016 	struct fss_cache *scp, *scl;
1017 
1018 	sc = arg;
1019 
1020 	scl = sc->sc_cache+sc->sc_cache_size;
1021 
1022 	nbp = getiobuf(NULL, true);
1023 
1024 	nfreed = nio = 1;		/* Dont sleep the first time */
1025 
1026 	FSS_LOCK(sc, s);
1027 
1028 	for (;;) {
1029 		if (nfreed == 0 && nio == 0)
1030 			ltsleep(&sc->sc_bs_lwp, PVM-1, "fssbs", 0,
1031 			    &sc->sc_slock);
1032 
1033 		if ((sc->sc_flags & FSS_BS_THREAD) == 0) {
1034 			sc->sc_bs_lwp = NULL;
1035 			wakeup(&sc->sc_bs_lwp);
1036 
1037 			FSS_UNLOCK(sc, s);
1038 
1039 			putiobuf(nbp);
1040 #ifdef FSS_STATISTICS
1041 			if ((sc->sc_flags & FSS_PERSISTENT) == 0) {
1042 				printf("fss%d: cow called %" PRId64 " times,"
1043 				    " copied %" PRId64 " clusters,"
1044 				    " cache full %" PRId64 " times\n",
1045 				    sc->sc_unit,
1046 				    FSS_STAT_VAL(sc, cow_calls),
1047 				    FSS_STAT_VAL(sc, cow_copied),
1048 				    FSS_STAT_VAL(sc, cow_cache_full));
1049 				printf("fss%d: %" PRId64 " indir reads,"
1050 				    " %" PRId64 " indir writes\n",
1051 				    sc->sc_unit,
1052 				    FSS_STAT_VAL(sc, indir_read),
1053 				    FSS_STAT_VAL(sc, indir_write));
1054 			}
1055 #endif /* FSS_STATISTICS */
1056 			kthread_exit(0);
1057 		}
1058 
1059 		/*
1060 		 * Process I/O requests (persistent)
1061 		 */
1062 
1063 		if (sc->sc_flags & FSS_PERSISTENT) {
1064 			nfreed = nio = 0;
1065 
1066 			if ((bp = BUFQ_GET(sc->sc_bufq)) == NULL)
1067 				continue;
1068 
1069 			nio++;
1070 
1071 			if (FSS_ISVALID(sc)) {
1072 				FSS_UNLOCK(sc, s);
1073 
1074 				error = fss_bs_io(sc, FSS_READ, 0,
1075 				    dbtob(bp->b_blkno), bp->b_bcount,
1076 				    bp->b_data);
1077 
1078 				FSS_LOCK(sc, s);
1079 			} else
1080 				error = ENXIO;
1081 
1082 			if (error) {
1083 				bp->b_error = error;
1084 				bp->b_resid = bp->b_bcount;
1085 			} else
1086 				bp->b_resid = 0;
1087 
1088 			biodone(bp);
1089 
1090 			continue;
1091 		}
1092 
1093 		/*
1094 		 * Clean the cache
1095 		 */
1096 		nfreed = 0;
1097 		for (scp = sc->sc_cache; scp < scl; scp++) {
1098 			if (scp->fc_type != FSS_CACHE_VALID)
1099 				continue;
1100 
1101 			FSS_UNLOCK(sc, s);
1102 
1103 			indirp = fss_bs_indir(sc, scp->fc_cluster);
1104 			if (indirp != NULL) {
1105 				error = fss_bs_io(sc, FSS_WRITE, sc->sc_clnext,
1106 				    0, FSS_CLSIZE(sc), scp->fc_data);
1107 			} else
1108 				error = EIO;
1109 
1110 			FSS_LOCK(sc, s);
1111 
1112 			if (error == 0) {
1113 				*indirp = sc->sc_clnext++;
1114 				sc->sc_indir_dirty = 1;
1115 			} else
1116 				fss_error(sc, "write bs error %d", error);
1117 
1118 			scp->fc_type = FSS_CACHE_FREE;
1119 			nfreed++;
1120 			wakeup(&scp->fc_type);
1121 		}
1122 
1123 		if (nfreed)
1124 			wakeup(&sc->sc_cache);
1125 
1126 		/*
1127 		 * Process I/O requests
1128 		 */
1129 		nio = 0;
1130 
1131 		if ((bp = BUFQ_GET(sc->sc_bufq)) == NULL)
1132 			continue;
1133 
1134 		nio++;
1135 
1136 		if (!FSS_ISVALID(sc)) {
1137 			bp->b_error = ENXIO;
1138 			bp->b_resid = bp->b_bcount;
1139 			biodone(bp);
1140 			continue;
1141 		}
1142 
1143 		/*
1144 		 * First read from the snapshotted block device.
1145 		 * XXX Split to only read those parts that have not
1146 		 * been saved to backing store?
1147 		 */
1148 
1149 		FSS_UNLOCK(sc, s);
1150 
1151 		buf_init(nbp);
1152 		nbp->b_flags = B_READ;
1153 		nbp->b_bcount = bp->b_bcount;
1154 		nbp->b_bufsize = bp->b_bcount;
1155 		nbp->b_error = 0;
1156 		nbp->b_data = bp->b_data;
1157 		nbp->b_blkno = bp->b_blkno;
1158 		nbp->b_proc = bp->b_proc;
1159 		nbp->b_dev = sc->sc_bdev;
1160 
1161 		bdev_strategy(nbp);
1162 
1163 		if (biowait(nbp) != 0) {
1164 			bp->b_resid = bp->b_bcount;
1165 			bp->b_error = nbp->b_error;
1166 			biodone(bp);
1167 			FSS_LOCK(sc, s);
1168 			continue;
1169 		}
1170 
1171 		cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
1172 		off = FSS_CLOFF(sc, dbtob(bp->b_blkno));
1173 		ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
1174 		bp->b_resid = bp->b_bcount;
1175 		addr = bp->b_data;
1176 
1177 		FSS_LOCK(sc, s);
1178 
1179 		/*
1180 		 * Replace those parts that have been saved to backing store.
1181 		 */
1182 
1183 		for (c = cl; c <= ch;
1184 		    c++, off = 0, bp->b_resid -= len, addr += len) {
1185 			len = FSS_CLSIZE(sc)-off;
1186 			if (len > bp->b_resid)
1187 				len = bp->b_resid;
1188 
1189 			if (isclr(sc->sc_copied, c))
1190 				continue;
1191 
1192 			FSS_UNLOCK(sc, s);
1193 
1194 			indirp = fss_bs_indir(sc, c);
1195 
1196 			FSS_LOCK(sc, s);
1197 
1198 			if (indirp == NULL || *indirp == 0) {
1199 				/*
1200 				 * Not on backing store. Either in cache
1201 				 * or hole in the snapshotted block device.
1202 				 */
1203 				for (scp = sc->sc_cache; scp < scl; scp++)
1204 					if (scp->fc_type == FSS_CACHE_VALID &&
1205 					    scp->fc_cluster == c)
1206 						break;
1207 				if (scp < scl)
1208 					memcpy(addr, (char *)scp->fc_data+off, len);
1209 				else
1210 					memset(addr, 0, len);
1211 				continue;
1212 			}
1213 			/*
1214 			 * Read from backing store.
1215 			 */
1216 
1217 			FSS_UNLOCK(sc, s);
1218 
1219 			if ((error = fss_bs_io(sc, FSS_READ, *indirp,
1220 			    off, len, addr)) != 0) {
1221 				bp->b_resid = bp->b_bcount;
1222 				bp->b_error = error;
1223 				FSS_LOCK(sc, s);
1224 				break;
1225 			}
1226 
1227 			FSS_LOCK(sc, s);
1228 
1229 		}
1230 
1231 		biodone(bp);
1232 	}
1233 }
1234