xref: /netbsd-src/sys/dev/fss.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: fss.c,v 1.70 2010/06/24 13:03:08 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  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * File system snapshot disk driver.
34  *
35  * Block/character interface to the snapshot of a mounted file system.
36  */
37 
38 #include <sys/cdefs.h>
39 __KERNEL_RCSID(0, "$NetBSD: fss.c,v 1.70 2010/06/24 13:03:08 hannken Exp $");
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/namei.h>
44 #include <sys/proc.h>
45 #include <sys/errno.h>
46 #include <sys/malloc.h>
47 #include <sys/buf.h>
48 #include <sys/ioctl.h>
49 #include <sys/disklabel.h>
50 #include <sys/device.h>
51 #include <sys/disk.h>
52 #include <sys/stat.h>
53 #include <sys/mount.h>
54 #include <sys/vnode.h>
55 #include <sys/file.h>
56 #include <sys/uio.h>
57 #include <sys/conf.h>
58 #include <sys/kthread.h>
59 #include <sys/fstrans.h>
60 #include <sys/simplelock.h>
61 
62 #include <miscfs/specfs/specdev.h>
63 
64 #include <dev/fssvar.h>
65 
66 #include <uvm/uvm.h>
67 
68 void fssattach(int);
69 
70 dev_type_open(fss_open);
71 dev_type_close(fss_close);
72 dev_type_read(fss_read);
73 dev_type_write(fss_write);
74 dev_type_ioctl(fss_ioctl);
75 dev_type_strategy(fss_strategy);
76 dev_type_dump(fss_dump);
77 dev_type_size(fss_size);
78 
79 static void fss_unmount_hook(struct mount *);
80 static int fss_copy_on_write(void *, struct buf *, bool);
81 static inline void fss_error(struct fss_softc *, const char *);
82 static int fss_create_files(struct fss_softc *, struct fss_set *,
83     off_t *, struct lwp *);
84 static int fss_create_snapshot(struct fss_softc *, struct fss_set *,
85     struct lwp *);
86 static int fss_delete_snapshot(struct fss_softc *, struct lwp *);
87 static int fss_softc_alloc(struct fss_softc *);
88 static void fss_softc_free(struct fss_softc *);
89 static int fss_read_cluster(struct fss_softc *, u_int32_t);
90 static void fss_bs_thread(void *);
91 static int fss_bs_io(struct fss_softc *, fss_io_type,
92     u_int32_t, off_t, int, void *);
93 static u_int32_t *fss_bs_indir(struct fss_softc *, u_int32_t);
94 
95 static kmutex_t fss_device_lock;	/* Protect all units. */
96 static int fss_num_attached = 0;	/* Number of attached devices. */
97 static struct vfs_hooks fss_vfs_hooks = {
98 	.vh_unmount = fss_unmount_hook
99 };
100 
101 const struct bdevsw fss_bdevsw = {
102 	fss_open, fss_close, fss_strategy, fss_ioctl,
103 	fss_dump, fss_size, D_DISK | D_MPSAFE
104 };
105 
106 const struct cdevsw fss_cdevsw = {
107 	fss_open, fss_close, fss_read, fss_write, fss_ioctl,
108 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK | D_MPSAFE
109 };
110 
111 static int fss_match(device_t, cfdata_t, void *);
112 static void fss_attach(device_t, device_t, void *);
113 static int fss_detach(device_t, int);
114 
115 CFATTACH_DECL_NEW(fss, sizeof(struct fss_softc),
116     fss_match, fss_attach, fss_detach, NULL);
117 extern struct cfdriver fss_cd;
118 
119 void
120 fssattach(int num)
121 {
122 
123 	mutex_init(&fss_device_lock, MUTEX_DEFAULT, IPL_NONE);
124 	if (config_cfattach_attach(fss_cd.cd_name, &fss_ca))
125 		aprint_error("%s: unable to register\n", fss_cd.cd_name);
126 }
127 
128 static int
129 fss_match(device_t self, cfdata_t cfdata, void *aux)
130 {
131 	return 1;
132 }
133 
134 static void
135 fss_attach(device_t parent, device_t self, void *aux)
136 {
137 	struct fss_softc *sc = device_private(self);
138 
139 	sc->sc_dev = self;
140 	sc->sc_bdev = NODEV;
141 	mutex_init(&sc->sc_slock, MUTEX_DEFAULT, IPL_NONE);
142 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
143 	cv_init(&sc->sc_work_cv, "fssbs");
144 	cv_init(&sc->sc_cache_cv, "cowwait");
145 	bufq_alloc(&sc->sc_bufq, "fcfs", 0);
146 	sc->sc_dkdev = malloc(sizeof(*sc->sc_dkdev), M_DEVBUF, M_WAITOK);
147 	sc->sc_dkdev->dk_info = NULL;
148 	disk_init(sc->sc_dkdev, device_xname(self), NULL);
149 	if (!pmf_device_register(self, NULL, NULL))
150 		aprint_error_dev(self, "couldn't establish power handler\n");
151 
152 	if (fss_num_attached++ == 0)
153 		vfs_hooks_attach(&fss_vfs_hooks);
154 }
155 
156 static int
157 fss_detach(device_t self, int flags)
158 {
159 	struct fss_softc *sc = device_private(self);
160 
161 	if (sc->sc_flags & FSS_ACTIVE)
162 		return EBUSY;
163 
164 	if (--fss_num_attached == 0)
165 		vfs_hooks_detach(&fss_vfs_hooks);
166 
167 	pmf_device_deregister(self);
168 	mutex_destroy(&sc->sc_slock);
169 	mutex_destroy(&sc->sc_lock);
170 	cv_destroy(&sc->sc_work_cv);
171 	cv_destroy(&sc->sc_cache_cv);
172 	bufq_drain(sc->sc_bufq);
173 	bufq_free(sc->sc_bufq);
174 	disk_destroy(sc->sc_dkdev);
175 	free(sc->sc_dkdev, M_DEVBUF);
176 
177 	return 0;
178 }
179 
180 int
181 fss_open(dev_t dev, int flags, int mode, struct lwp *l)
182 {
183 	int mflag;
184 	cfdata_t cf;
185 	struct fss_softc *sc;
186 
187 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
188 
189 	mutex_enter(&fss_device_lock);
190 
191 	sc = device_lookup_private(&fss_cd, minor(dev));
192 	if (sc == NULL) {
193 		cf = malloc(sizeof(*cf), M_DEVBUF, M_WAITOK);
194 		cf->cf_name = fss_cd.cd_name;
195 		cf->cf_atname = fss_cd.cd_name;
196 		cf->cf_unit = minor(dev);
197 		cf->cf_fstate = FSTATE_STAR;
198 		sc = device_private(config_attach_pseudo(cf));
199 		if (sc == NULL) {
200 			mutex_exit(&fss_device_lock);
201 			return ENOMEM;
202 		}
203 	}
204 
205 	mutex_enter(&sc->sc_slock);
206 
207 	sc->sc_flags |= mflag;
208 
209 	mutex_exit(&sc->sc_slock);
210 	mutex_exit(&fss_device_lock);
211 
212 	return 0;
213 }
214 
215 int
216 fss_close(dev_t dev, int flags, int mode, struct lwp *l)
217 {
218 	int mflag, error;
219 	cfdata_t cf;
220 	struct fss_softc *sc = device_lookup_private(&fss_cd, minor(dev));
221 
222 	mflag = (mode == S_IFCHR ? FSS_CDEV_OPEN : FSS_BDEV_OPEN);
223 	error = 0;
224 
225 restart:
226 	mutex_enter(&sc->sc_slock);
227 	if ((sc->sc_flags & (FSS_CDEV_OPEN|FSS_BDEV_OPEN)) != mflag) {
228 		sc->sc_flags &= ~mflag;
229 		mutex_exit(&sc->sc_slock);
230 		return 0;
231 	}
232 	if ((sc->sc_flags & FSS_ACTIVE) != 0 &&
233 	    (sc->sc_uflags & FSS_UNCONFIG_ON_CLOSE) != 0) {
234 		sc->sc_uflags &= ~FSS_UNCONFIG_ON_CLOSE;
235 		mutex_exit(&sc->sc_slock);
236 		error = fss_ioctl(dev, FSSIOCCLR, NULL, FWRITE, l);
237 		goto restart;
238 	}
239 	if ((sc->sc_flags & FSS_ACTIVE) != 0) {
240 		mutex_exit(&sc->sc_slock);
241 		return error;
242 	}
243 	if (! mutex_tryenter(&fss_device_lock)) {
244 		mutex_exit(&sc->sc_slock);
245 		goto restart;
246 	}
247 
248 	KASSERT((sc->sc_flags & FSS_ACTIVE) == 0);
249 	KASSERT((sc->sc_flags & (FSS_CDEV_OPEN|FSS_BDEV_OPEN)) == mflag);
250 	mutex_exit(&sc->sc_slock);
251 	cf = device_cfdata(sc->sc_dev);
252 	error = config_detach(sc->sc_dev, DETACH_QUIET);
253 	if (! error)
254 		free(cf, M_DEVBUF);
255 	mutex_exit(&fss_device_lock);
256 
257 	return error;
258 }
259 
260 void
261 fss_strategy(struct buf *bp)
262 {
263 	const bool write = ((bp->b_flags & B_READ) != B_READ);
264 	struct fss_softc *sc = device_lookup_private(&fss_cd, minor(bp->b_dev));
265 
266 	mutex_enter(&sc->sc_slock);
267 
268 	if (write || !FSS_ISVALID(sc)) {
269 
270 		mutex_exit(&sc->sc_slock);
271 
272 		bp->b_error = (write ? EROFS : ENXIO);
273 		bp->b_resid = bp->b_bcount;
274 		biodone(bp);
275 		return;
276 	}
277 
278 	bp->b_rawblkno = bp->b_blkno;
279 	bufq_put(sc->sc_bufq, bp);
280 	cv_signal(&sc->sc_work_cv);
281 
282 	mutex_exit(&sc->sc_slock);
283 }
284 
285 int
286 fss_read(dev_t dev, struct uio *uio, int flags)
287 {
288 	return physio(fss_strategy, NULL, dev, B_READ, minphys, uio);
289 }
290 
291 int
292 fss_write(dev_t dev, struct uio *uio, int flags)
293 {
294 	return physio(fss_strategy, NULL, dev, B_WRITE, minphys, uio);
295 }
296 
297 int
298 fss_ioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
299 {
300 	int error;
301 	struct fss_softc *sc = device_lookup_private(&fss_cd, minor(dev));
302 	struct fss_set *fss = (struct fss_set *)data;
303 	struct fss_get *fsg = (struct fss_get *)data;
304 
305 	switch (cmd) {
306 	case FSSIOCSET:
307 		mutex_enter(&sc->sc_lock);
308 		if ((flag & FWRITE) == 0)
309 			error = EPERM;
310 		else if ((sc->sc_flags & FSS_ACTIVE) != 0)
311 			error = EBUSY;
312 		else
313 			error = fss_create_snapshot(sc, fss, l);
314 		mutex_exit(&sc->sc_lock);
315 		break;
316 
317 	case FSSIOCCLR:
318 		mutex_enter(&sc->sc_lock);
319 		if ((flag & FWRITE) == 0)
320 			error = EPERM;
321 		else if ((sc->sc_flags & FSS_ACTIVE) == 0)
322 			error = ENXIO;
323 		else
324 			error = fss_delete_snapshot(sc, l);
325 		mutex_exit(&sc->sc_lock);
326 		break;
327 
328 	case FSSIOCGET:
329 		mutex_enter(&sc->sc_lock);
330 		switch (sc->sc_flags & (FSS_PERSISTENT | FSS_ACTIVE)) {
331 		case FSS_ACTIVE:
332 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
333 			fsg->fsg_csize = FSS_CLSIZE(sc);
334 			fsg->fsg_time = sc->sc_time;
335 			fsg->fsg_mount_size = sc->sc_clcount;
336 			fsg->fsg_bs_size = sc->sc_clnext;
337 			error = 0;
338 			break;
339 		case FSS_PERSISTENT | FSS_ACTIVE:
340 			memcpy(fsg->fsg_mount, sc->sc_mntname, MNAMELEN);
341 			fsg->fsg_csize = 0;
342 			fsg->fsg_time = sc->sc_time;
343 			fsg->fsg_mount_size = 0;
344 			fsg->fsg_bs_size = 0;
345 			error = 0;
346 			break;
347 		default:
348 			error = ENXIO;
349 			break;
350 		}
351 		mutex_exit(&sc->sc_lock);
352 		break;
353 
354 	case FSSIOFSET:
355 		mutex_enter(&sc->sc_slock);
356 		sc->sc_uflags = *(int *)data;
357 		mutex_exit(&sc->sc_slock);
358 		error = 0;
359 		break;
360 
361 	case FSSIOFGET:
362 		mutex_enter(&sc->sc_slock);
363 		*(int *)data = sc->sc_uflags;
364 		mutex_exit(&sc->sc_slock);
365 		error = 0;
366 		break;
367 
368 	default:
369 		error = EINVAL;
370 		break;
371 	}
372 
373 	return error;
374 }
375 
376 int
377 fss_size(dev_t dev)
378 {
379 	return -1;
380 }
381 
382 int
383 fss_dump(dev_t dev, daddr_t blkno, void *va,
384     size_t size)
385 {
386 	return EROFS;
387 }
388 
389 /*
390  * An error occurred reading or writing the snapshot or backing store.
391  * If it is the first error log to console.
392  * The caller holds the mutex.
393  */
394 static inline void
395 fss_error(struct fss_softc *sc, const char *msg)
396 {
397 
398 	if ((sc->sc_flags & (FSS_ACTIVE|FSS_ERROR)) == FSS_ACTIVE)
399 		aprint_error_dev(sc->sc_dev, "snapshot invalid: %s\n", msg);
400 	if ((sc->sc_flags & FSS_ACTIVE) == FSS_ACTIVE)
401 		sc->sc_flags |= FSS_ERROR;
402 }
403 
404 /*
405  * Allocate the variable sized parts of the softc and
406  * fork the kernel thread.
407  *
408  * The fields sc_clcount, sc_clshift, sc_cache_size and sc_indir_size
409  * must be initialized.
410  */
411 static int
412 fss_softc_alloc(struct fss_softc *sc)
413 {
414 	int i, error;
415 
416 	if ((sc->sc_flags & FSS_PERSISTENT) == 0) {
417 		sc->sc_copied =
418 		    kmem_zalloc(howmany(sc->sc_clcount, NBBY), KM_SLEEP);
419 		if (sc->sc_copied == NULL)
420 			return(ENOMEM);
421 
422 		sc->sc_cache = kmem_alloc(sc->sc_cache_size *
423 		    sizeof(struct fss_cache), KM_SLEEP);
424 		if (sc->sc_cache == NULL)
425 			return(ENOMEM);
426 
427 		for (i = 0; i < sc->sc_cache_size; i++) {
428 			sc->sc_cache[i].fc_type = FSS_CACHE_FREE;
429 			sc->sc_cache[i].fc_data =
430 			    kmem_alloc(FSS_CLSIZE(sc), KM_SLEEP);
431 			if (sc->sc_cache[i].fc_data == NULL)
432 				return(ENOMEM);
433 			cv_init(&sc->sc_cache[i].fc_state_cv, "cowwait1");
434 		}
435 
436 		sc->sc_indir_valid =
437 		    kmem_zalloc(howmany(sc->sc_indir_size, NBBY), KM_SLEEP);
438 		if (sc->sc_indir_valid == NULL)
439 			return(ENOMEM);
440 
441 		sc->sc_indir_data = kmem_zalloc(FSS_CLSIZE(sc), KM_SLEEP);
442 		if (sc->sc_indir_data == NULL)
443 			return(ENOMEM);
444 	} else {
445 		sc->sc_copied = NULL;
446 		sc->sc_cache = NULL;
447 		sc->sc_indir_valid = NULL;
448 		sc->sc_indir_data = NULL;
449 	}
450 
451 	sc->sc_flags |= FSS_BS_THREAD;
452 	if ((error = kthread_create(PRI_BIO, 0, NULL, fss_bs_thread, sc,
453 	    &sc->sc_bs_lwp, device_xname(sc->sc_dev))) != 0) {
454 		sc->sc_flags &= ~FSS_BS_THREAD;
455 		return error;
456 	}
457 
458 	disk_attach(sc->sc_dkdev);
459 
460 	return 0;
461 }
462 
463 /*
464  * Free the variable sized parts of the softc.
465  */
466 static void
467 fss_softc_free(struct fss_softc *sc)
468 {
469 	int i;
470 
471 	if ((sc->sc_flags & FSS_BS_THREAD) != 0) {
472 		mutex_enter(&sc->sc_slock);
473 		sc->sc_flags &= ~FSS_BS_THREAD;
474 		cv_signal(&sc->sc_work_cv);
475 		while (sc->sc_bs_lwp != NULL)
476 			kpause("fssdetach", false, 1, &sc->sc_slock);
477 		mutex_exit(&sc->sc_slock);
478 
479 		disk_detach(sc->sc_dkdev);
480 	}
481 
482 	if (sc->sc_copied != NULL)
483 		kmem_free(sc->sc_copied, howmany(sc->sc_clcount, NBBY));
484 	sc->sc_copied = NULL;
485 
486 	if (sc->sc_cache != NULL) {
487 		for (i = 0; i < sc->sc_cache_size; i++)
488 			if (sc->sc_cache[i].fc_data != NULL) {
489 				cv_destroy(&sc->sc_cache[i].fc_state_cv);
490 				kmem_free(sc->sc_cache[i].fc_data,
491 				    FSS_CLSIZE(sc));
492 			}
493 		kmem_free(sc->sc_cache,
494 		    sc->sc_cache_size*sizeof(struct fss_cache));
495 	}
496 	sc->sc_cache = NULL;
497 
498 	if (sc->sc_indir_valid != NULL)
499 		kmem_free(sc->sc_indir_valid, howmany(sc->sc_indir_size, NBBY));
500 	sc->sc_indir_valid = NULL;
501 
502 	if (sc->sc_indir_data != NULL)
503 		kmem_free(sc->sc_indir_data, FSS_CLSIZE(sc));
504 	sc->sc_indir_data = NULL;
505 }
506 
507 /*
508  * Set all active snapshots on this file system into ERROR state.
509  */
510 static void
511 fss_unmount_hook(struct mount *mp)
512 {
513 	int i;
514 	struct fss_softc *sc;
515 
516 	mutex_enter(&fss_device_lock);
517 	for (i = 0; i < fss_cd.cd_ndevs; i++) {
518 		if ((sc = device_lookup_private(&fss_cd, i)) == NULL)
519 			continue;
520 		mutex_enter(&sc->sc_slock);
521 		if ((sc->sc_flags & FSS_ACTIVE) != 0 &&
522 		    sc->sc_mount == mp)
523 			fss_error(sc, "forced unmount");
524 		mutex_exit(&sc->sc_slock);
525 	}
526 	mutex_exit(&fss_device_lock);
527 }
528 
529 /*
530  * A buffer is written to the snapshotted block device. Copy to
531  * backing store if needed.
532  */
533 static int
534 fss_copy_on_write(void *v, struct buf *bp, bool data_valid)
535 {
536 	int error;
537 	u_int32_t cl, ch, c;
538 	struct fss_softc *sc = v;
539 
540 	mutex_enter(&sc->sc_slock);
541 	if (!FSS_ISVALID(sc)) {
542 		mutex_exit(&sc->sc_slock);
543 		return 0;
544 	}
545 
546 	cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
547 	ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
548 	error = 0;
549 	if (curlwp == uvm.pagedaemon_lwp) {
550 		for (c = cl; c <= ch; c++)
551 			if (isclr(sc->sc_copied, c)) {
552 				error = ENOMEM;
553 				break;
554 			}
555 	}
556 	mutex_exit(&sc->sc_slock);
557 
558 	if (error == 0)
559 		for (c = cl; c <= ch; c++) {
560 			error = fss_read_cluster(sc, c);
561 			if (error)
562 				break;
563 		}
564 
565 	return error;
566 }
567 
568 /*
569  * Lookup and open needed files.
570  *
571  * For file system internal snapshot initializes sc_mntname, sc_mount,
572  * sc_bs_vp and sc_time.
573  *
574  * Otherwise returns dev and size of the underlying block device.
575  * Initializes sc_mntname, sc_mount, sc_bdev, sc_bs_vp and sc_mount
576  */
577 static int
578 fss_create_files(struct fss_softc *sc, struct fss_set *fss,
579     off_t *bsize, struct lwp *l)
580 {
581 	int error, bits, fsbsize;
582 	struct timespec ts;
583 	struct partinfo dpart;
584 	/* nd -> nd2 to reduce mistakes while updating only some namei calls */
585 	struct nameidata nd2;
586 	struct vnode *vp;
587 
588 	/*
589 	 * Get the mounted file system.
590 	 */
591 
592 	error = namei_simple_user(fss->fss_mount,
593 				NSM_FOLLOW_NOEMULROOT, &vp);
594 	if (error != 0)
595 		return error;
596 
597 	if ((vp->v_vflag & VV_ROOT) != VV_ROOT) {
598 		vrele(vp);
599 		return EINVAL;
600 	}
601 
602 	sc->sc_mount = vp->v_mount;
603 	memcpy(sc->sc_mntname, sc->sc_mount->mnt_stat.f_mntonname, MNAMELEN);
604 
605 	vrele(vp);
606 
607 	/*
608 	 * Check for file system internal snapshot.
609 	 */
610 
611 	error = namei_simple_user(fss->fss_bstore,
612 				NSM_FOLLOW_NOEMULROOT, &vp);
613 	if (error != 0)
614 		return error;
615 	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
616 	if (error != 0) {
617 		vrele(vp);
618 		return error;
619 	}
620 
621 	if (vp->v_type == VREG && vp->v_mount == sc->sc_mount) {
622 		sc->sc_flags |= FSS_PERSISTENT;
623 		sc->sc_bs_vp = vp;
624 
625 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
626 		bits = sizeof(sc->sc_bs_bshift)*NBBY;
627 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < bits;
628 		    sc->sc_bs_bshift++)
629 			if (FSS_FSBSIZE(sc) == fsbsize)
630 				break;
631 		if (sc->sc_bs_bshift >= bits) {
632 			VOP_UNLOCK(sc->sc_bs_vp);
633 			return EINVAL;
634 		}
635 
636 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
637 		sc->sc_clshift = 0;
638 
639 		error = VFS_SNAPSHOT(sc->sc_mount, sc->sc_bs_vp, &ts);
640 		TIMESPEC_TO_TIMEVAL(&sc->sc_time, &ts);
641 
642 		VOP_UNLOCK(sc->sc_bs_vp);
643 
644 		return error;
645 	}
646 	vput(vp);
647 
648 	/*
649 	 * Get the block device it is mounted on.
650 	 */
651 
652 	error = namei_simple_kernel(sc->sc_mount->mnt_stat.f_mntfromname,
653 				NSM_FOLLOW_NOEMULROOT, &vp);
654 	if (error != 0)
655 		return error;
656 
657 	if (vp->v_type != VBLK) {
658 		vrele(vp);
659 		return EINVAL;
660 	}
661 
662 	sc->sc_bdev = vp->v_rdev;
663 	vrele(vp);
664 
665 	/*
666 	 * Get the block device size.
667 	 */
668 
669 	error = bdev_ioctl(sc->sc_bdev, DIOCGPART, &dpart, FREAD, l);
670 	if (error)
671 		return error;
672 
673 	*bsize = (off_t)dpart.disklab->d_secsize*dpart.part->p_size;
674 
675 	/*
676 	 * Get the backing store
677 	 */
678 
679 	NDINIT(&nd2, LOOKUP, FOLLOW, UIO_USERSPACE, fss->fss_bstore);
680 	if ((error = vn_open(&nd2, FREAD|FWRITE, 0)) != 0)
681 		return error;
682 	VOP_UNLOCK(nd2.ni_vp);
683 
684 	sc->sc_bs_vp = nd2.ni_vp;
685 
686 	if (nd2.ni_vp->v_type != VREG && nd2.ni_vp->v_type != VCHR)
687 		return EINVAL;
688 
689 	if (sc->sc_bs_vp->v_type == VREG) {
690 		fsbsize = sc->sc_bs_vp->v_mount->mnt_stat.f_iosize;
691 		if (fsbsize & (fsbsize-1))	/* No power of two */
692 			return EINVAL;
693 		for (sc->sc_bs_bshift = 1; sc->sc_bs_bshift < 32;
694 		    sc->sc_bs_bshift++)
695 			if (FSS_FSBSIZE(sc) == fsbsize)
696 				break;
697 		if (sc->sc_bs_bshift >= 32)
698 			return EINVAL;
699 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
700 	} else {
701 		sc->sc_bs_bshift = DEV_BSHIFT;
702 		sc->sc_bs_bmask = FSS_FSBSIZE(sc)-1;
703 	}
704 
705 	return 0;
706 }
707 
708 /*
709  * Create a snapshot.
710  */
711 static int
712 fss_create_snapshot(struct fss_softc *sc, struct fss_set *fss, struct lwp *l)
713 {
714 	int len, error;
715 	u_int32_t csize;
716 	off_t bsize;
717 
718 	bsize = 0;	/* XXX gcc */
719 
720 	/*
721 	 * Open needed files.
722 	 */
723 	if ((error = fss_create_files(sc, fss, &bsize, l)) != 0)
724 		goto bad;
725 
726 	if (sc->sc_flags & FSS_PERSISTENT) {
727 		fss_softc_alloc(sc);
728 		sc->sc_flags |= FSS_ACTIVE;
729 		return 0;
730 	}
731 
732 	/*
733 	 * Set cluster size. Must be a power of two and
734 	 * a multiple of backing store block size.
735 	 */
736 	if (fss->fss_csize <= 0)
737 		csize = MAXPHYS;
738 	else
739 		csize = fss->fss_csize;
740 	if (bsize/csize > FSS_CLUSTER_MAX)
741 		csize = bsize/FSS_CLUSTER_MAX+1;
742 
743 	for (sc->sc_clshift = sc->sc_bs_bshift; sc->sc_clshift < 32;
744 	    sc->sc_clshift++)
745 		if (FSS_CLSIZE(sc) >= csize)
746 			break;
747 	if (sc->sc_clshift >= 32) {
748 		error = EINVAL;
749 		goto bad;
750 	}
751 	sc->sc_clmask = FSS_CLSIZE(sc)-1;
752 
753 	/*
754 	 * Set number of cache slots.
755 	 */
756 	if (FSS_CLSIZE(sc) <= 8192)
757 		sc->sc_cache_size = 32;
758 	else if (FSS_CLSIZE(sc) <= 65536)
759 		sc->sc_cache_size = 8;
760 	else
761 		sc->sc_cache_size = 4;
762 
763 	/*
764 	 * Set number of clusters and size of last cluster.
765 	 */
766 	sc->sc_clcount = FSS_BTOCL(sc, bsize-1)+1;
767 	sc->sc_clresid = FSS_CLOFF(sc, bsize-1)+1;
768 
769 	/*
770 	 * Set size of indirect table.
771 	 */
772 	len = sc->sc_clcount*sizeof(u_int32_t);
773 	sc->sc_indir_size = FSS_BTOCL(sc, len)+1;
774 	sc->sc_clnext = sc->sc_indir_size;
775 	sc->sc_indir_cur = 0;
776 
777 	if ((error = fss_softc_alloc(sc)) != 0)
778 		goto bad;
779 
780 	/*
781 	 * Activate the snapshot.
782 	 */
783 
784 	if ((error = vfs_suspend(sc->sc_mount, 0)) != 0)
785 		goto bad;
786 
787 	microtime(&sc->sc_time);
788 
789 	if (error == 0)
790 		error = fscow_establish(sc->sc_mount,
791 		    fss_copy_on_write, sc);
792 	if (error == 0)
793 		sc->sc_flags |= FSS_ACTIVE;
794 
795 	vfs_resume(sc->sc_mount);
796 
797 	if (error != 0)
798 		goto bad;
799 
800 	aprint_debug_dev(sc->sc_dev, "%s snapshot active\n", sc->sc_mntname);
801 	aprint_debug_dev(sc->sc_dev,
802 	    "%u clusters of %u, %u cache slots, %u indir clusters\n",
803 	    sc->sc_clcount, FSS_CLSIZE(sc),
804 	    sc->sc_cache_size, sc->sc_indir_size);
805 
806 	return 0;
807 
808 bad:
809 	fss_softc_free(sc);
810 	if (sc->sc_bs_vp != NULL) {
811 		if (sc->sc_flags & FSS_PERSISTENT)
812 			vn_close(sc->sc_bs_vp, FREAD, l->l_cred);
813 		else
814 			vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred);
815 	}
816 	sc->sc_bs_vp = NULL;
817 
818 	return error;
819 }
820 
821 /*
822  * Delete a snapshot.
823  */
824 static int
825 fss_delete_snapshot(struct fss_softc *sc, struct lwp *l)
826 {
827 
828 	if ((sc->sc_flags & FSS_PERSISTENT) == 0)
829 		fscow_disestablish(sc->sc_mount, fss_copy_on_write, sc);
830 
831 	mutex_enter(&sc->sc_slock);
832 	sc->sc_flags &= ~(FSS_ACTIVE|FSS_ERROR);
833 	sc->sc_mount = NULL;
834 	sc->sc_bdev = NODEV;
835 	mutex_exit(&sc->sc_slock);
836 
837 	fss_softc_free(sc);
838 	if (sc->sc_flags & FSS_PERSISTENT)
839 		vn_close(sc->sc_bs_vp, FREAD, l->l_cred);
840 	else
841 		vn_close(sc->sc_bs_vp, FREAD|FWRITE, l->l_cred);
842 	sc->sc_bs_vp = NULL;
843 	sc->sc_flags &= ~FSS_PERSISTENT;
844 
845 	return 0;
846 }
847 
848 /*
849  * Read a cluster from the snapshotted block device to the cache.
850  */
851 static int
852 fss_read_cluster(struct fss_softc *sc, u_int32_t cl)
853 {
854 	int error, todo, offset, len;
855 	daddr_t dblk;
856 	struct buf *bp, *mbp;
857 	struct fss_cache *scp, *scl;
858 
859 	/*
860 	 * Get a free cache slot.
861 	 */
862 	scl = sc->sc_cache+sc->sc_cache_size;
863 
864 	mutex_enter(&sc->sc_slock);
865 
866 restart:
867 	if (isset(sc->sc_copied, cl) || !FSS_ISVALID(sc)) {
868 		mutex_exit(&sc->sc_slock);
869 		return 0;
870 	}
871 
872 	for (scp = sc->sc_cache; scp < scl; scp++)
873 		if (scp->fc_cluster == cl) {
874 			if (scp->fc_type == FSS_CACHE_VALID) {
875 				mutex_exit(&sc->sc_slock);
876 				return 0;
877 			} else if (scp->fc_type == FSS_CACHE_BUSY) {
878 				cv_wait(&scp->fc_state_cv, &sc->sc_slock);
879 				goto restart;
880 			}
881 		}
882 
883 	for (scp = sc->sc_cache; scp < scl; scp++)
884 		if (scp->fc_type == FSS_CACHE_FREE) {
885 			scp->fc_type = FSS_CACHE_BUSY;
886 			scp->fc_cluster = cl;
887 			break;
888 		}
889 	if (scp >= scl) {
890 		cv_wait(&sc->sc_cache_cv, &sc->sc_slock);
891 		goto restart;
892 	}
893 
894 	mutex_exit(&sc->sc_slock);
895 
896 	/*
897 	 * Start the read.
898 	 */
899 	dblk = btodb(FSS_CLTOB(sc, cl));
900 	if (cl == sc->sc_clcount-1) {
901 		todo = sc->sc_clresid;
902 		memset((char *)scp->fc_data + todo, 0, FSS_CLSIZE(sc) - todo);
903 	} else
904 		todo = FSS_CLSIZE(sc);
905 	offset = 0;
906 	mbp = getiobuf(NULL, true);
907 	mbp->b_bufsize = todo;
908 	mbp->b_data = scp->fc_data;
909 	mbp->b_resid = mbp->b_bcount = todo;
910 	mbp->b_flags = B_READ;
911 	mbp->b_cflags = BC_BUSY;
912 	mbp->b_dev = sc->sc_bdev;
913 	while (todo > 0) {
914 		len = todo;
915 		if (len > MAXPHYS)
916 			len = MAXPHYS;
917 		if (btodb(FSS_CLTOB(sc, cl)) == dblk && len == todo)
918 			bp = mbp;
919 		else {
920 			bp = getiobuf(NULL, true);
921 			nestiobuf_setup(mbp, bp, offset, len);
922 		}
923 		bp->b_lblkno = 0;
924 		bp->b_blkno = dblk;
925 		bdev_strategy(bp);
926 		dblk += btodb(len);
927 		offset += len;
928 		todo -= len;
929 	}
930 	error = biowait(mbp);
931 	putiobuf(mbp);
932 
933 	mutex_enter(&sc->sc_slock);
934 	scp->fc_type = (error ? FSS_CACHE_FREE : FSS_CACHE_VALID);
935 	cv_broadcast(&scp->fc_state_cv);
936 	if (error == 0) {
937 		setbit(sc->sc_copied, scp->fc_cluster);
938 		cv_signal(&sc->sc_work_cv);
939 	}
940 	mutex_exit(&sc->sc_slock);
941 
942 	return error;
943 }
944 
945 /*
946  * Read/write clusters from/to backing store.
947  * For persistent snapshots must be called with cl == 0. off is the
948  * offset into the snapshot.
949  */
950 static int
951 fss_bs_io(struct fss_softc *sc, fss_io_type rw,
952     u_int32_t cl, off_t off, int len, void *data)
953 {
954 	int error;
955 
956 	off += FSS_CLTOB(sc, cl);
957 
958 	vn_lock(sc->sc_bs_vp, LK_EXCLUSIVE|LK_RETRY);
959 
960 	error = vn_rdwr((rw == FSS_READ ? UIO_READ : UIO_WRITE), sc->sc_bs_vp,
961 	    data, len, off, UIO_SYSSPACE, IO_UNIT|IO_NODELOCKED,
962 	    sc->sc_bs_lwp->l_cred, NULL, NULL);
963 	if (error == 0) {
964 		mutex_enter(&sc->sc_bs_vp->v_interlock);
965 		error = VOP_PUTPAGES(sc->sc_bs_vp, trunc_page(off),
966 		    round_page(off+len), PGO_CLEANIT|PGO_SYNCIO|PGO_FREE);
967 	}
968 
969 	VOP_UNLOCK(sc->sc_bs_vp);
970 
971 	return error;
972 }
973 
974 /*
975  * Get a pointer to the indirect slot for this cluster.
976  */
977 static u_int32_t *
978 fss_bs_indir(struct fss_softc *sc, u_int32_t cl)
979 {
980 	u_int32_t icl;
981 	int ioff;
982 
983 	icl = cl/(FSS_CLSIZE(sc)/sizeof(u_int32_t));
984 	ioff = cl%(FSS_CLSIZE(sc)/sizeof(u_int32_t));
985 
986 	if (sc->sc_indir_cur == icl)
987 		return &sc->sc_indir_data[ioff];
988 
989 	if (sc->sc_indir_dirty) {
990 		if (fss_bs_io(sc, FSS_WRITE, sc->sc_indir_cur, 0,
991 		    FSS_CLSIZE(sc), (void *)sc->sc_indir_data) != 0)
992 			return NULL;
993 		setbit(sc->sc_indir_valid, sc->sc_indir_cur);
994 	}
995 
996 	sc->sc_indir_dirty = 0;
997 	sc->sc_indir_cur = icl;
998 
999 	if (isset(sc->sc_indir_valid, sc->sc_indir_cur)) {
1000 		if (fss_bs_io(sc, FSS_READ, sc->sc_indir_cur, 0,
1001 		    FSS_CLSIZE(sc), (void *)sc->sc_indir_data) != 0)
1002 			return NULL;
1003 	} else
1004 		memset(sc->sc_indir_data, 0, FSS_CLSIZE(sc));
1005 
1006 	return &sc->sc_indir_data[ioff];
1007 }
1008 
1009 /*
1010  * The kernel thread (one for every active snapshot).
1011  *
1012  * After wakeup it cleans the cache and runs the I/O requests.
1013  */
1014 static void
1015 fss_bs_thread(void *arg)
1016 {
1017 	bool thread_idle, is_valid;
1018 	int error, i, todo, len, crotor, is_read;
1019 	long off;
1020 	char *addr;
1021 	u_int32_t c, cl, ch, *indirp;
1022 	struct buf *bp, *nbp;
1023 	struct fss_softc *sc;
1024 	struct fss_cache *scp, *scl;
1025 
1026 	sc = arg;
1027 	scl = sc->sc_cache+sc->sc_cache_size;
1028 	crotor = 0;
1029 	thread_idle = false;
1030 
1031 	mutex_enter(&sc->sc_slock);
1032 
1033 	for (;;) {
1034 		if (thread_idle)
1035 			cv_wait(&sc->sc_work_cv, &sc->sc_slock);
1036 		thread_idle = true;
1037 		if ((sc->sc_flags & FSS_BS_THREAD) == 0) {
1038 			sc->sc_bs_lwp = NULL;
1039 			mutex_exit(&sc->sc_slock);
1040 			kthread_exit(0);
1041 		}
1042 
1043 		/*
1044 		 * Process I/O requests (persistent)
1045 		 */
1046 
1047 		if (sc->sc_flags & FSS_PERSISTENT) {
1048 			if ((bp = bufq_get(sc->sc_bufq)) == NULL)
1049 				continue;
1050 			is_valid = FSS_ISVALID(sc);
1051 			is_read = (bp->b_flags & B_READ);
1052 			thread_idle = false;
1053 			mutex_exit(&sc->sc_slock);
1054 
1055 			if (is_valid) {
1056 				disk_busy(sc->sc_dkdev);
1057 				error = fss_bs_io(sc, FSS_READ, 0,
1058 				    dbtob(bp->b_blkno), bp->b_bcount,
1059 				    bp->b_data);
1060 				disk_unbusy(sc->sc_dkdev,
1061 				    (error ? 0 : bp->b_bcount), is_read);
1062 			} else
1063 				error = ENXIO;
1064 
1065 			bp->b_error = error;
1066 			bp->b_resid = (error ? bp->b_bcount : 0);
1067 			biodone(bp);
1068 
1069 			mutex_enter(&sc->sc_slock);
1070 			continue;
1071 		}
1072 
1073 		/*
1074 		 * Clean the cache
1075 		 */
1076 		for (i = 0; i < sc->sc_cache_size; i++) {
1077 			crotor = (crotor + 1) % sc->sc_cache_size;
1078 			scp = sc->sc_cache + crotor;
1079 			if (scp->fc_type != FSS_CACHE_VALID)
1080 				continue;
1081 			mutex_exit(&sc->sc_slock);
1082 
1083 			thread_idle = false;
1084 			indirp = fss_bs_indir(sc, scp->fc_cluster);
1085 			if (indirp != NULL) {
1086 				error = fss_bs_io(sc, FSS_WRITE, sc->sc_clnext,
1087 				    0, FSS_CLSIZE(sc), scp->fc_data);
1088 			} else
1089 				error = EIO;
1090 
1091 			mutex_enter(&sc->sc_slock);
1092 			if (error == 0) {
1093 				*indirp = sc->sc_clnext++;
1094 				sc->sc_indir_dirty = 1;
1095 			} else
1096 				fss_error(sc, "write error on backing store");
1097 
1098 			scp->fc_type = FSS_CACHE_FREE;
1099 			cv_signal(&sc->sc_cache_cv);
1100 			break;
1101 		}
1102 
1103 		/*
1104 		 * Process I/O requests
1105 		 */
1106 		if ((bp = bufq_get(sc->sc_bufq)) == NULL)
1107 			continue;
1108 		is_valid = FSS_ISVALID(sc);
1109 		is_read = (bp->b_flags & B_READ);
1110 		thread_idle = false;
1111 
1112 		if (!is_valid) {
1113 			mutex_exit(&sc->sc_slock);
1114 
1115 			bp->b_error = ENXIO;
1116 			bp->b_resid = bp->b_bcount;
1117 			biodone(bp);
1118 
1119 			mutex_enter(&sc->sc_slock);
1120 			continue;
1121 		}
1122 
1123 		disk_busy(sc->sc_dkdev);
1124 
1125 		/*
1126 		 * First read from the snapshotted block device unless
1127 		 * this request is completely covered by backing store.
1128 		 */
1129 
1130 		cl = FSS_BTOCL(sc, dbtob(bp->b_blkno));
1131 		off = FSS_CLOFF(sc, dbtob(bp->b_blkno));
1132 		ch = FSS_BTOCL(sc, dbtob(bp->b_blkno)+bp->b_bcount-1);
1133 		error = 0;
1134 		bp->b_resid = 0;
1135 		bp->b_error = 0;
1136 		for (c = cl; c <= ch; c++) {
1137 			if (isset(sc->sc_copied, c))
1138 				continue;
1139 			mutex_exit(&sc->sc_slock);
1140 
1141 			/* Not on backing store, read from device. */
1142 			nbp = getiobuf(NULL, true);
1143 			nbp->b_flags = B_READ;
1144 			nbp->b_resid = nbp->b_bcount = bp->b_bcount;
1145 			nbp->b_bufsize = bp->b_bcount;
1146 			nbp->b_data = bp->b_data;
1147 			nbp->b_blkno = bp->b_blkno;
1148 			nbp->b_lblkno = 0;
1149 			nbp->b_dev = sc->sc_bdev;
1150 			SET(nbp->b_cflags, BC_BUSY);	/* mark buffer busy */
1151 
1152 			bdev_strategy(nbp);
1153 
1154 			error = biowait(nbp);
1155 			if (error != 0) {
1156 				bp->b_resid = bp->b_bcount;
1157 				bp->b_error = nbp->b_error;
1158 				disk_unbusy(sc->sc_dkdev, 0, is_read);
1159 				biodone(bp);
1160 			}
1161 			putiobuf(nbp);
1162 
1163 			mutex_enter(&sc->sc_slock);
1164 			break;
1165 		}
1166 		if (error)
1167 			continue;
1168 
1169 		/*
1170 		 * Replace those parts that have been saved to backing store.
1171 		 */
1172 
1173 		addr = bp->b_data;
1174 		todo = bp->b_bcount;
1175 		for (c = cl; c <= ch; c++, off = 0, todo -= len, addr += len) {
1176 			len = FSS_CLSIZE(sc)-off;
1177 			if (len > todo)
1178 				len = todo;
1179 			if (isclr(sc->sc_copied, c))
1180 				continue;
1181 			mutex_exit(&sc->sc_slock);
1182 
1183 			indirp = fss_bs_indir(sc, c);
1184 			if (indirp == NULL || *indirp == 0) {
1185 				/*
1186 				 * Not on backing store. Either in cache
1187 				 * or hole in the snapshotted block device.
1188 				 */
1189 
1190 				mutex_enter(&sc->sc_slock);
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, (char *)scp->fc_data+off,
1197 					    len);
1198 				else
1199 					memset(addr, 0, len);
1200 				continue;
1201 			}
1202 
1203 			/*
1204 			 * Read from backing store.
1205 			 */
1206 			error =
1207 			    fss_bs_io(sc, FSS_READ, *indirp, off, len, addr);
1208 
1209 			mutex_enter(&sc->sc_slock);
1210 			if (error) {
1211 				bp->b_resid = bp->b_bcount;
1212 				bp->b_error = error;
1213 				break;
1214 			}
1215 		}
1216 		mutex_exit(&sc->sc_slock);
1217 
1218 		disk_unbusy(sc->sc_dkdev, (error ? 0 : bp->b_bcount), is_read);
1219 		biodone(bp);
1220 
1221 		mutex_enter(&sc->sc_slock);
1222 	}
1223 }
1224 
1225 #ifdef _MODULE
1226 
1227 #include <sys/module.h>
1228 
1229 MODULE(MODULE_CLASS_DRIVER, fss, NULL);
1230 CFDRIVER_DECL(fss, DV_DISK, NULL);
1231 
1232 static int
1233 fss_modcmd(modcmd_t cmd, void *arg)
1234 {
1235 	int bmajor = -1, cmajor = -1,  error = 0;
1236 
1237 	switch (cmd) {
1238 	case MODULE_CMD_INIT:
1239 		mutex_init(&fss_device_lock, MUTEX_DEFAULT, IPL_NONE);
1240 		error = config_cfdriver_attach(&fss_cd);
1241 		if (error) {
1242 			mutex_destroy(&fss_device_lock);
1243 			break;
1244 		}
1245 		error = config_cfattach_attach(fss_cd.cd_name, &fss_ca);
1246 		if (error) {
1247 			config_cfdriver_detach(&fss_cd);
1248 			mutex_destroy(&fss_device_lock);
1249 			break;
1250 		}
1251 		error = devsw_attach(fss_cd.cd_name,
1252 		    &fss_bdevsw, &bmajor, &fss_cdevsw, &cmajor);
1253 		if (error == EEXIST)
1254 			error = 0;
1255 		if (error) {
1256 			config_cfattach_detach(fss_cd.cd_name, &fss_ca);
1257 			config_cfdriver_detach(&fss_cd);
1258 			mutex_destroy(&fss_device_lock);
1259 			break;
1260 		}
1261 		break;
1262 
1263 	case MODULE_CMD_FINI:
1264 		error = config_cfattach_detach(fss_cd.cd_name, &fss_ca);
1265 		if (error)
1266 			break;
1267 		config_cfdriver_detach(&fss_cd);
1268 		devsw_detach(&fss_bdevsw, &fss_cdevsw);
1269 		mutex_destroy(&fss_device_lock);
1270 		break;
1271 
1272 	default:
1273 		error = ENOTTY;
1274 		break;
1275 	}
1276 
1277 	return error;
1278 }
1279 
1280 #endif /* _MODULE */
1281