xref: /netbsd-src/sys/dev/fss.c (revision 8b0f9554ff8762542c4defc4f70e1eb76fb508fa)
1 /*	$NetBSD: fss.c,v 1.41 2007/12/08 19:29:41 pooka 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.41 2007/12/08 19:29:41 pooka 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 
70 #include <miscfs/specfs/specdev.h>
71 
72 #include <dev/fssvar.h>
73 
74 #include <machine/stdarg.h>
75 
76 #ifdef DEBUG
77 #define FSS_STATISTICS
78 #endif
79 
80 #ifdef FSS_STATISTICS
81 struct fss_stat {
82 	u_int64_t	cow_calls;
83 	u_int64_t	cow_copied;
84 	u_int64_t	cow_cache_full;
85 	u_int64_t	indir_read;
86 	u_int64_t	indir_write;
87 };
88 
89 static struct fss_stat fss_stat[NFSS];
90 
91 #define FSS_STAT_INC(sc, field)	\
92 			do { \
93 				fss_stat[sc->sc_unit].field++; \
94 			} while (0)
95 #define FSS_STAT_SET(sc, field, value) \
96 			do { \
97 				fss_stat[sc->sc_unit].field = value; \
98 			} while (0)
99 #define FSS_STAT_ADD(sc, field, value) \
100 			do { \
101 				fss_stat[sc->sc_unit].field += value; \
102 			} while (0)
103 #define FSS_STAT_VAL(sc, field) fss_stat[sc->sc_unit].field
104 #define FSS_STAT_CLEAR(sc) \
105 			do { \
106 				memset(&fss_stat[sc->sc_unit], 0, \
107 				    sizeof(struct fss_stat)); \
108 			} while (0)
109 #else /* FSS_STATISTICS */
110 #define FSS_STAT_INC(sc, field)
111 #define FSS_STAT_SET(sc, field, value)
112 #define FSS_STAT_ADD(sc, field, value)
113 #define FSS_STAT_CLEAR(sc)
114 #endif /* FSS_STATISTICS */
115 
116 static struct fss_softc fss_softc[NFSS];
117 
118 void fssattach(int);
119 
120 dev_type_open(fss_open);
121 dev_type_close(fss_close);
122 dev_type_read(fss_read);
123 dev_type_write(fss_write);
124 dev_type_ioctl(fss_ioctl);
125 dev_type_strategy(fss_strategy);
126 dev_type_dump(fss_dump);
127 dev_type_size(fss_size);
128 
129 static int fss_copy_on_write(void *, struct buf *, bool);
130 static inline void fss_error(struct fss_softc *, const char *, ...);
131 static int fss_create_files(struct fss_softc *, struct fss_set *,
132     off_t *, struct lwp *);
133 static int fss_create_snapshot(struct fss_softc *, struct fss_set *,
134     struct lwp *);
135 static int fss_delete_snapshot(struct fss_softc *, struct lwp *);
136 static int fss_softc_alloc(struct fss_softc *);
137 static void fss_softc_free(struct fss_softc *);
138 static void fss_cluster_iodone(struct buf *);
139 static void fss_read_cluster(struct fss_softc *, u_int32_t);
140 static void fss_bs_thread(void *);
141 static int fss_bs_io(struct fss_softc *, fss_io_type,
142     u_int32_t, off_t, int, void *);
143 static u_int32_t *fss_bs_indir(struct fss_softc *, u_int32_t);
144 
145 const struct bdevsw fss_bdevsw = {
146 	fss_open, fss_close, fss_strategy, fss_ioctl,
147 	fss_dump, fss_size, D_DISK
148 };
149 
150 const struct cdevsw fss_cdevsw = {
151 	fss_open, fss_close, fss_read, fss_write, fss_ioctl,
152 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
153 };
154 
155 void
156 fssattach(int num)
157 {
158 	int i;
159 	struct fss_softc *sc;
160 
161 	for (i = 0; i < NFSS; i++) {
162 		sc = &fss_softc[i];
163 		sc->sc_unit = i;
164 		sc->sc_bdev = NODEV;
165 		simple_lock_init(&sc->sc_slock);
166 		mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
167 		bufq_alloc(&sc->sc_bufq, "fcfs", 0);
168 	}
169 }
170 
171 int
172 fss_open(dev_t dev, int flags, int mode, struct lwp *l)
173 {
174 	int s, mflag;
175 	struct fss_softc *sc;
176 
177 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
178 
179 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
180 		return ENODEV;
181 
182 	FSS_LOCK(sc, s);
183 
184 	sc->sc_flags |= mflag;
185 
186 	FSS_UNLOCK(sc, s);
187 
188 	return 0;
189 }
190 
191 int
192 fss_close(dev_t dev, int flags, int mode, struct lwp *l)
193 {
194 	int s, mflag, error;
195 	struct fss_softc *sc;
196 
197 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
198 
199 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
200 		return ENODEV;
201 
202 	FSS_LOCK(sc, s);
203 
204 	if ((sc->sc_flags & (FSS_CDEV_OPEN|FSS_BDEV_OPEN)) == mflag) {
205 		if ((sc->sc_uflags & FSS_UNCONFIG_ON_CLOSE) != 0 &&
206 		    (sc->sc_flags & FSS_ACTIVE) != 0) {
207 			FSS_UNLOCK(sc, s);
208 			error = fss_ioctl(dev, FSSIOCCLR, NULL, FWRITE, l);
209 			if (error)
210 				return error;
211 			FSS_LOCK(sc, s);
212 		}
213 		sc->sc_uflags &= ~FSS_UNCONFIG_ON_CLOSE;
214 	}
215 
216 	sc->sc_flags &= ~mflag;
217 
218 	FSS_UNLOCK(sc, s);
219 
220 	return 0;
221 }
222 
223 void
224 fss_strategy(struct buf *bp)
225 {
226 	int s;
227 	struct fss_softc *sc;
228 
229 	sc = FSS_DEV_TO_SOFTC(bp->b_dev);
230 
231 	FSS_LOCK(sc, s);
232 
233 	if ((bp->b_flags & B_READ) != B_READ ||
234 	    sc == NULL || !FSS_ISVALID(sc)) {
235 
236 		FSS_UNLOCK(sc, s);
237 
238 		bp->b_error = (sc == NULL ? ENODEV : EROFS);
239 		bp->b_resid = bp->b_bcount;
240 		biodone(bp);
241 		return;
242 	}
243 
244 	bp->b_rawblkno = bp->b_blkno;
245 	BUFQ_PUT(sc->sc_bufq, bp);
246 	wakeup(&sc->sc_bs_lwp);
247 
248 	FSS_UNLOCK(sc, s);
249 }
250 
251 int
252 fss_read(dev_t dev, struct uio *uio, int flags)
253 {
254 	return physio(fss_strategy, NULL, dev, B_READ, minphys, uio);
255 }
256 
257 int
258 fss_write(dev_t dev, struct uio *uio, int flags)
259 {
260 	return physio(fss_strategy, NULL, dev, B_WRITE, minphys, uio);
261 }
262 
263 int
264 fss_ioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
265 {
266 	int error;
267 	struct fss_softc *sc;
268 	struct fss_set *fss = (struct fss_set *)data;
269 	struct fss_get *fsg = (struct fss_get *)data;
270 
271 	if ((sc = FSS_DEV_TO_SOFTC(dev)) == NULL)
272 		return ENODEV;
273 
274 	switch (cmd) {
275 	case FSSIOCSET:
276 		mutex_enter(&sc->sc_lock);
277 		if ((flag & FWRITE) == 0)
278 			error = EPERM;
279 		else if ((sc->sc_flags & FSS_ACTIVE) != 0)
280 			error = EBUSY;
281 		else
282 			error = fss_create_snapshot(sc, fss, l);
283 		mutex_exit(&sc->sc_lock);
284 		break;
285 
286 	case FSSIOCCLR:
287 		mutex_enter(&sc->sc_lock);
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, l);
294 		mutex_exit(&sc->sc_lock);
295 		break;
296 
297 	case FSSIOCGET:
298 		mutex_enter(&sc->sc_lock);
299 		switch (sc->sc_flags & (FSS_PERSISTENT | FSS_ACTIVE)) {
300 		case FSS_ACTIVE:
301 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
302 			fsg->fsg_csize = FSS_CLSIZE(sc);
303 			fsg->fsg_time = sc->sc_time;
304 			fsg->fsg_mount_size = sc->sc_clcount;
305 			fsg->fsg_bs_size = sc->sc_clnext;
306 			error = 0;
307 			break;
308 		case FSS_PERSISTENT | FSS_ACTIVE:
309 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
310 			fsg->fsg_csize = 0;
311 			fsg->fsg_time = sc->sc_time;
312 			fsg->fsg_mount_size = 0;
313 			fsg->fsg_bs_size = 0;
314 			error = 0;
315 			break;
316 		default:
317 			error = ENXIO;
318 			break;
319 		}
320 		mutex_exit(&sc->sc_lock);
321 		break;
322 
323 	case FSSIOFSET:
324 		sc->sc_uflags = *(int *)data;
325 		error = 0;
326 		break;
327 
328 	case FSSIOFGET:
329 		*(int *)data = sc->sc_uflags;
330 		error = 0;
331 		break;
332 
333 	default:
334 		error = EINVAL;
335 		break;
336 	}
337 
338 	return error;
339 }
340 
341 int
342 fss_size(dev_t dev)
343 {
344 	return -1;
345 }
346 
347 int
348 fss_dump(dev_t dev, daddr_t blkno, void *va,
349     size_t size)
350 {
351 	return EROFS;
352 }
353 
354 /*
355  * An error occurred reading or writing the snapshot or backing store.
356  * If it is the first error log to console.
357  * The caller holds the simplelock.
358  */
359 static inline void
360 fss_error(struct fss_softc *sc, const char *fmt, ...)
361 {
362 	va_list ap;
363 
364 	if ((sc->sc_flags & (FSS_ACTIVE|FSS_ERROR)) == FSS_ACTIVE) {
365 		va_start(ap, fmt);
366 		printf("fss%d: snapshot invalid: ", sc->sc_unit);
367 		vprintf(fmt, ap);
368 		printf("\n");
369 		va_end(ap);
370 	}
371 	if ((sc->sc_flags & FSS_ACTIVE) == FSS_ACTIVE)
372 		sc->sc_flags |= FSS_ERROR;
373 }
374 
375 /*
376  * Allocate the variable sized parts of the softc and
377  * fork the kernel thread.
378  *
379  * The fields sc_clcount, sc_clshift, sc_cache_size and sc_indir_size
380  * must be initialized.
381  */
382 static int
383 fss_softc_alloc(struct fss_softc *sc)
384 {
385 	int i, len, error;
386 
387 	len = (sc->sc_clcount+NBBY-1)/NBBY;
388 	sc->sc_copied = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
389 	if (sc->sc_copied == NULL)
390 		return(ENOMEM);
391 
392 	len = sc->sc_cache_size*sizeof(struct fss_cache);
393 	sc->sc_cache = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
394 	if (sc->sc_cache == NULL)
395 		return(ENOMEM);
396 
397 	len = FSS_CLSIZE(sc);
398 	for (i = 0; i < sc->sc_cache_size; i++) {
399 		sc->sc_cache[i].fc_type = FSS_CACHE_FREE;
400 		sc->sc_cache[i].fc_softc = sc;
401 		sc->sc_cache[i].fc_xfercount = 0;
402 		sc->sc_cache[i].fc_data = malloc(len, M_TEMP,
403 		    M_WAITOK|M_CANFAIL);
404 		if (sc->sc_cache[i].fc_data == NULL)
405 			return(ENOMEM);
406 	}
407 
408 	len = (sc->sc_indir_size+NBBY-1)/NBBY;
409 	sc->sc_indir_valid = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
410 	if (sc->sc_indir_valid == NULL)
411 		return(ENOMEM);
412 
413 	len = FSS_CLSIZE(sc);
414 	sc->sc_indir_data = malloc(len, M_TEMP, M_ZERO|M_WAITOK|M_CANFAIL);
415 	if (sc->sc_indir_data == NULL)
416 		return(ENOMEM);
417 
418 	if ((error = kthread_create(PRI_BIO, 0, NULL, fss_bs_thread, sc,
419 	    &sc->sc_bs_lwp, "fssbs%d", sc->sc_unit)) != 0)
420 		return error;
421 
422 	sc->sc_flags |= FSS_BS_THREAD;
423 	return 0;
424 }
425 
426 /*
427  * Free the variable sized parts of the softc.
428  */
429 static void
430 fss_softc_free(struct fss_softc *sc)
431 {
432 	int s, i;
433 
434 	if ((sc->sc_flags & FSS_BS_THREAD) != 0) {
435 		FSS_LOCK(sc, s);
436 		sc->sc_flags &= ~FSS_BS_THREAD;
437 		wakeup(&sc->sc_bs_lwp);
438 		while (sc->sc_bs_lwp != NULL)
439 			ltsleep(&sc->sc_bs_lwp, PRIBIO, "fssthread", 0,
440 			    &sc->sc_slock);
441 		FSS_UNLOCK(sc, s);
442 	}
443 
444 	if (sc->sc_copied != NULL)
445 		free(sc->sc_copied, M_TEMP);
446 	sc->sc_copied = NULL;
447 
448 	if (sc->sc_cache != NULL) {
449 		for (i = 0; i < sc->sc_cache_size; i++)
450 			if (sc->sc_cache[i].fc_data != NULL)
451 				free(sc->sc_cache[i].fc_data, M_TEMP);
452 		free(sc->sc_cache, M_TEMP);
453 	}
454 	sc->sc_cache = NULL;
455 
456 	if (sc->sc_indir_valid != NULL)
457 		free(sc->sc_indir_valid, M_TEMP);
458 	sc->sc_indir_valid = NULL;
459 
460 	if (sc->sc_indir_data != NULL)
461 		free(sc->sc_indir_data, M_TEMP);
462 	sc->sc_indir_data = NULL;
463 }
464 
465 /*
466  * Check if an unmount is ok. If forced, set this snapshot into ERROR state.
467  */
468 int
469 fss_umount_hook(struct mount *mp, int forced)
470 {
471 	int i, s;
472 
473 	for (i = 0; i < NFSS; i++) {
474 		FSS_LOCK(&fss_softc[i], s);
475 		if ((fss_softc[i].sc_flags & FSS_ACTIVE) != 0 &&
476 		    fss_softc[i].sc_mount == mp) {
477 			if (forced)
478 				fss_error(&fss_softc[i], "forced unmount");
479 			else {
480 				FSS_UNLOCK(&fss_softc[i], s);
481 				return EBUSY;
482 			}
483 		}
484 		FSS_UNLOCK(&fss_softc[i], s);
485 	}
486 
487 	return 0;
488 }
489 
490 /*
491  * A buffer is written to the snapshotted block device. Copy to
492  * backing store if needed.
493  */
494 static int
495 fss_copy_on_write(void *v, struct buf *bp, bool data_valid)
496 {
497 	int s;
498 	u_int32_t cl, ch, c;
499 	struct fss_softc *sc = v;
500 
501 	FSS_LOCK(sc, s);
502 	if (!FSS_ISVALID(sc)) {
503 		FSS_UNLOCK(sc, s);
504 		return 0;
505 	}
506 
507 	FSS_UNLOCK(sc, s);
508 
509 	FSS_STAT_INC(sc, cow_calls);
510 
511 	cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
512 	ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
513 
514 	for (c = cl; c <= ch; c++)
515 		fss_read_cluster(sc, c);
516 
517 	return 0;
518 }
519 
520 /*
521  * Lookup and open needed files.
522  *
523  * For file system internal snapshot initializes sc_mntname, sc_mount,
524  * sc_bs_vp and sc_time.
525  *
526  * Otherwise returns dev and size of the underlying block device.
527  * Initializes sc_mntname, sc_mount, sc_bdev, sc_bs_vp and sc_mount
528  */
529 static int
530 fss_create_files(struct fss_softc *sc, struct fss_set *fss,
531     off_t *bsize, struct lwp *l)
532 {
533 	int error, bits, fsbsize;
534 	struct timespec ts;
535 	struct partinfo dpart;
536 	struct vattr va;
537 	struct nameidata nd;
538 
539 	/*
540 	 * Get the mounted file system.
541 	 */
542 
543 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_mount);
544 	if ((error = namei(&nd)) != 0)
545 		return error;
546 
547 	if ((nd.ni_vp->v_vflag & VV_ROOT) != VV_ROOT) {
548 		vrele(nd.ni_vp);
549 		return EINVAL;
550 	}
551 
552 	sc->sc_mount = nd.ni_vp->v_mount;
553 	memcpy(sc->sc_mntname, sc->sc_mount->mnt_stat.f_mntonname, MNAMELEN);
554 
555 	vrele(nd.ni_vp);
556 
557 	/*
558 	 * Check for file system internal snapshot.
559 	 */
560 
561 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
562 	if ((error = namei(&nd)) != 0)
563 		return error;
564 
565 	if (nd.ni_vp->v_type == VREG && nd.ni_vp->v_mount == sc->sc_mount) {
566 		vrele(nd.ni_vp);
567 		sc->sc_flags |= FSS_PERSISTENT;
568 
569 		NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
570 		if ((error = vn_open(&nd, FREAD, 0)) != 0)
571 			return error;
572 		sc->sc_bs_vp = nd.ni_vp;
573 
574 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
575 		bits = sizeof(sc->sc_bs_bshift)*NBBY;
576 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < bits;
577 		    sc->sc_bs_bshift++)
578 			if (FSS_FSBSIZE(sc) == fsbsize)
579 				break;
580 		if (sc->sc_bs_bshift >= bits) {
581 			VOP_UNLOCK(sc->sc_bs_vp, 0);
582 			return EINVAL;
583 		}
584 
585 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
586 		sc->sc_clshift = 0;
587 
588 		error = VFS_SNAPSHOT(sc->sc_mount, sc->sc_bs_vp, &ts);
589 		TIMESPEC_TO_TIMEVAL(&sc->sc_time, &ts);
590 
591 		VOP_UNLOCK(sc->sc_bs_vp, 0);
592 
593 		return error;
594 	}
595 	vrele(nd.ni_vp);
596 
597 	/*
598 	 * Get the block device it is mounted on.
599 	 */
600 
601 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_SYSSPACE,
602 	    sc->sc_mount->mnt_stat.f_mntfromname);
603 	if ((error = namei(&nd)) != 0)
604 		return error;
605 
606 	if (nd.ni_vp->v_type != VBLK) {
607 		vrele(nd.ni_vp);
608 		return EINVAL;
609 	}
610 
611 	error = VOP_IOCTL(nd.ni_vp, DIOCGPART, &dpart, FREAD, l->l_cred);
612 	if (error) {
613 		vrele(nd.ni_vp);
614 		return error;
615 	}
616 
617 	sc->sc_bdev = nd.ni_vp->v_rdev;
618 	*bsize = (off_t)dpart.disklab->d_secsize*dpart.part->p_size;
619 	vrele(nd.ni_vp);
620 
621 	/*
622 	 * Get the backing store
623 	 */
624 
625 	NDINIT(&nd, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
626 	if ((error = vn_open(&nd, FREAD|FWRITE, 0)) != 0)
627 		return error;
628 	VOP_UNLOCK(nd.ni_vp, 0);
629 
630 	sc->sc_bs_vp = nd.ni_vp;
631 
632 	if (nd.ni_vp->v_type != VREG && nd.ni_vp->v_type != VCHR)
633 		return EINVAL;
634 
635 	if (sc->sc_bs_vp->v_type == VREG) {
636 		error = VOP_GETATTR(sc->sc_bs_vp, &va, l->l_cred);
637 		if (error != 0)
638 			return error;
639 		sc->sc_bs_size = va.va_size;
640 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
641 		if (fsbsize & (fsbsize-1))	/* No power of two */
642 			return EINVAL;
643 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < 32;
644 		    sc->sc_bs_bshift++)
645 			if (FSS_FSBSIZE(sc) == fsbsize)
646 				break;
647 		if (sc->sc_bs_bshift >= 32)
648 			return EINVAL;
649 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
650 	} else {
651 		sc->sc_bs_bshift = DEV_BSHIFT;
652 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
653 	}
654 
655 	/*
656 	 * As all IO to from/to the backing store goes through
657 	 * VOP_STRATEGY() clean the buffer cache to prevent
658 	 * cache incoherencies.
659 	 */
660 	if ((error = vinvalbuf(sc->sc_bs_vp, V_SAVE, l->l_cred, l, 0, 0)) != 0)
661 		return error;
662 
663 	return 0;
664 }
665 
666 /*
667  * Create a snapshot.
668  */
669 static int
670 fss_create_snapshot(struct fss_softc *sc, struct fss_set *fss, struct lwp *l)
671 {
672 	int len, error;
673 	u_int32_t csize;
674 	off_t bsize;
675 
676 	bsize = 0;	/* XXX gcc */
677 
678 	/*
679 	 * Open needed files.
680 	 */
681 	if ((error = fss_create_files(sc, fss, &bsize, l)) != 0)
682 		goto bad;
683 
684 	if (sc->sc_flags & FSS_PERSISTENT) {
685 		fss_softc_alloc(sc);
686 		sc->sc_flags |= FSS_ACTIVE;
687 		return 0;
688 	}
689 
690 	/*
691 	 * Set cluster size. Must be a power of two and
692 	 * a multiple of backing store block size.
693 	 */
694 	if (fss->fss_csize <= 0)
695 		csize = MAXPHYS;
696 	else
697 		csize = fss->fss_csize;
698 	if (bsize/csize > FSS_CLUSTER_MAX)
699 		csize = bsize/FSS_CLUSTER_MAX+1;
700 
701 	for (sc->sc_clshift = sc->sc_bs_bshift; sc->sc_clshift < 32;
702 	    sc->sc_clshift++)
703 		if (FSS_CLSIZE(sc) >= csize)
704 			break;
705 	if (sc->sc_clshift >= 32) {
706 		error = EINVAL;
707 		goto bad;
708 	}
709 	sc->sc_clmask = FSS_CLSIZE(sc)-1;
710 
711 	/*
712 	 * Set number of cache slots.
713 	 */
714 	if (FSS_CLSIZE(sc) <= 8192)
715 		sc->sc_cache_size = 32;
716 	else if (FSS_CLSIZE(sc) <= 65536)
717 		sc->sc_cache_size = 8;
718 	else
719 		sc->sc_cache_size = 4;
720 
721 	/*
722 	 * Set number of clusters and size of last cluster.
723 	 */
724 	sc->sc_clcount = FSS_BTOCL(sc, bsize-1)+1;
725 	sc->sc_clresid = FSS_CLOFF(sc, bsize-1)+1;
726 
727 	/*
728 	 * Set size of indirect table.
729 	 */
730 	len = sc->sc_clcount*sizeof(u_int32_t);
731 	sc->sc_indir_size = FSS_BTOCL(sc, len)+1;
732 	sc->sc_clnext = sc->sc_indir_size;
733 	sc->sc_indir_cur = 0;
734 
735 	if ((error = fss_softc_alloc(sc)) != 0)
736 		goto bad;
737 
738 	/*
739 	 * Activate the snapshot.
740 	 */
741 
742 	if ((error = vfs_suspend(sc->sc_mount, 0)) != 0)
743 		goto bad;
744 
745 	microtime(&sc->sc_time);
746 
747 	if (error == 0)
748 		error = fscow_establish(sc->sc_mount,
749 		    fss_copy_on_write, sc);
750 	if (error == 0)
751 		sc->sc_flags |= FSS_ACTIVE;
752 
753 	vfs_resume(sc->sc_mount);
754 
755 	if (error != 0)
756 		goto bad;
757 
758 #ifdef DEBUG
759 	printf("fss%d: %s snapshot active\n", sc->sc_unit, sc->sc_mntname);
760 	printf("fss%d: %u clusters of %u, %u cache slots, %u indir clusters\n",
761 	    sc->sc_unit, sc->sc_clcount, FSS_CLSIZE(sc),
762 	    sc->sc_cache_size, sc->sc_indir_size);
763 #endif
764 
765 	return 0;
766 
767 bad:
768 	fss_softc_free(sc);
769 	if (sc->sc_bs_vp != NULL) {
770 		if (sc->sc_flags & FSS_PERSISTENT)
771 			vn_close(sc->sc_bs_vp, FREAD, l->l_cred, l);
772 		else
773 			vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred, l);
774 	}
775 	sc->sc_bs_vp = NULL;
776 
777 	return error;
778 }
779 
780 /*
781  * Delete a snapshot.
782  */
783 static int
784 fss_delete_snapshot(struct fss_softc *sc, struct lwp *l)
785 {
786 	int s;
787 
788 	if ((sc->sc_flags & FSS_PERSISTENT) == 0)
789 		fscow_disestablish(sc->sc_mount, fss_copy_on_write, sc);
790 
791 	FSS_LOCK(sc, s);
792 	sc->sc_flags &= ~(FSS_ACTIVE|FSS_ERROR);
793 	sc->sc_mount = NULL;
794 	sc->sc_bdev = NODEV;
795 	FSS_UNLOCK(sc, s);
796 
797 	fss_softc_free(sc);
798 	if (sc->sc_flags & FSS_PERSISTENT)
799 		vn_close(sc->sc_bs_vp, FREAD, l->l_cred, l);
800 	else
801 		vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred, l);
802 	sc->sc_bs_vp = NULL;
803 	sc->sc_flags &= ~FSS_PERSISTENT;
804 
805 	FSS_STAT_CLEAR(sc);
806 
807 	return 0;
808 }
809 
810 /*
811  * A read from the snapshotted block device has completed.
812  */
813 static void
814 fss_cluster_iodone(struct buf *bp)
815 {
816 	int s;
817 	struct fss_cache *scp = bp->b_private;
818 
819 	KASSERT(bp->b_vp == NULL);
820 
821 	FSS_LOCK(scp->fc_softc, s);
822 
823 	if (bp->b_error != 0)
824 		fss_error(scp->fc_softc, "fs read error %d", bp->b_error);
825 
826 	if (--scp->fc_xfercount == 0)
827 		wakeup(&scp->fc_data);
828 
829 	FSS_UNLOCK(scp->fc_softc, s);
830 
831 	putiobuf(bp);
832 }
833 
834 /*
835  * Read a cluster from the snapshotted block device to the cache.
836  */
837 static void
838 fss_read_cluster(struct fss_softc *sc, u_int32_t cl)
839 {
840 	int s, todo, len;
841 	char *addr;
842 	daddr_t dblk;
843 	struct buf *bp;
844 	struct fss_cache *scp, *scl;
845 
846 	/*
847 	 * Get a free cache slot.
848 	 */
849 	scl = sc->sc_cache+sc->sc_cache_size;
850 
851 	FSS_LOCK(sc, s);
852 
853 restart:
854 	if (isset(sc->sc_copied, cl) || !FSS_ISVALID(sc)) {
855 		FSS_UNLOCK(sc, s);
856 		return;
857 	}
858 
859 	for (scp = sc->sc_cache; scp < scl; scp++)
860 		if (scp->fc_type != FSS_CACHE_FREE &&
861 		    scp->fc_cluster == cl) {
862 			ltsleep(&scp->fc_type, PRIBIO, "cowwait2", 0,
863 			    &sc->sc_slock);
864 			goto restart;
865 		}
866 
867 	for (scp = sc->sc_cache; scp < scl; scp++)
868 		if (scp->fc_type == FSS_CACHE_FREE) {
869 			scp->fc_type = FSS_CACHE_BUSY;
870 			scp->fc_cluster = cl;
871 			break;
872 		}
873 	if (scp >= scl) {
874 		FSS_STAT_INC(sc, cow_cache_full);
875 		ltsleep(&sc->sc_cache, PRIBIO, "cowwait3", 0, &sc->sc_slock);
876 		goto restart;
877 	}
878 
879 	FSS_UNLOCK(sc, s);
880 
881 	/*
882 	 * Start the read.
883 	 */
884 	FSS_STAT_INC(sc, cow_copied);
885 
886 	dblk = btodb(FSS_CLTOB(sc, cl));
887 	addr = scp->fc_data;
888 	if (cl == sc->sc_clcount-1) {
889 		todo = sc->sc_clresid;
890 		memset((char *)addr + todo, 0, FSS_CLSIZE(sc) - todo);
891 	} else
892 		todo = FSS_CLSIZE(sc);
893 	while (todo > 0) {
894 		len = todo;
895 		if (len > MAXPHYS)
896 			len = MAXPHYS;
897 
898 		bp = getiobuf();
899 		bp->b_flags = B_READ|B_CALL;
900 		bp->b_bcount = len;
901 		bp->b_bufsize = bp->b_bcount;
902 		bp->b_error = 0;
903 		bp->b_data = addr;
904 		bp->b_blkno = dblk;
905 		bp->b_proc = NULL;
906 		bp->b_dev = sc->sc_bdev;
907 		bp->b_vp = NULLVP;
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 		simple_lock(&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();
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 		nbp->b_vp = NULLVP;
1161 
1162 		bdev_strategy(nbp);
1163 
1164 		if (biowait(nbp) != 0) {
1165 			bp->b_resid = bp->b_bcount;
1166 			bp->b_error = nbp->b_error;
1167 			biodone(bp);
1168 			FSS_LOCK(sc, s);
1169 			continue;
1170 		}
1171 
1172 		cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
1173 		off = FSS_CLOFF(sc, dbtob(bp->b_blkno));
1174 		ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
1175 		bp->b_resid = bp->b_bcount;
1176 		addr = bp->b_data;
1177 
1178 		FSS_LOCK(sc, s);
1179 
1180 		/*
1181 		 * Replace those parts that have been saved to backing store.
1182 		 */
1183 
1184 		for (c = cl; c <= ch;
1185 		    c++, off = 0, bp->b_resid -= len, addr += len) {
1186 			len = FSS_CLSIZE(sc)-off;
1187 			if (len > bp->b_resid)
1188 				len = bp->b_resid;
1189 
1190 			if (isclr(sc->sc_copied, c))
1191 				continue;
1192 
1193 			FSS_UNLOCK(sc, s);
1194 
1195 			indirp = fss_bs_indir(sc, c);
1196 
1197 			FSS_LOCK(sc, s);
1198 
1199 			if (indirp == NULL || *indirp == 0) {
1200 				/*
1201 				 * Not on backing store. Either in cache
1202 				 * or hole in the snapshotted block device.
1203 				 */
1204 				for (scp = sc->sc_cache; scp < scl; scp++)
1205 					if (scp->fc_type == FSS_CACHE_VALID &&
1206 					    scp->fc_cluster == c)
1207 						break;
1208 				if (scp < scl)
1209 					memcpy(addr, (char *)scp->fc_data+off, len);
1210 				else
1211 					memset(addr, 0, len);
1212 				continue;
1213 			}
1214 			/*
1215 			 * Read from backing store.
1216 			 */
1217 
1218 			FSS_UNLOCK(sc, s);
1219 
1220 			if ((error = fss_bs_io(sc, FSS_READ, *indirp,
1221 			    off, len, addr)) != 0) {
1222 				bp->b_resid = bp->b_bcount;
1223 				bp->b_error = error;
1224 				FSS_LOCK(sc, s);
1225 				break;
1226 			}
1227 
1228 			FSS_LOCK(sc, s);
1229 
1230 		}
1231 
1232 		biodone(bp);
1233 	}
1234 }
1235