Home | History | Annotate | Line # | Download | only in ffs
ffs_snapshot.c revision 1.93
      1 /*	$NetBSD: ffs_snapshot.c,v 1.93 2009/03/18 16:00:24 cegger Exp $	*/
      2 
      3 /*
      4  * Copyright 2000 Marshall Kirk McKusick. All Rights Reserved.
      5  *
      6  * Further information about snapshots can be obtained from:
      7  *
      8  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
      9  *	1614 Oxford Street		mckusick (at) mckusick.com
     10  *	Berkeley, CA 94709-1608		+1-510-843-9542
     11  *	USA
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  *
     17  * 1. Redistributions of source code must retain the above copyright
     18  *    notice, this list of conditions and the following disclaimer.
     19  * 2. Redistributions in binary form must reproduce the above copyright
     20  *    notice, this list of conditions and the following disclaimer in the
     21  *    documentation and/or other materials provided with the distribution.
     22  *
     23  * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
     24  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
     25  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
     26  * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
     27  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     33  * SUCH DAMAGE.
     34  *
     35  *	@(#)ffs_snapshot.c	8.11 (McKusick) 7/23/00
     36  *
     37  *	from FreeBSD: ffs_snapshot.c,v 1.79 2004/02/13 02:02:06 kuriyama Exp
     38  */
     39 
     40 #include <sys/cdefs.h>
     41 __KERNEL_RCSID(0, "$NetBSD: ffs_snapshot.c,v 1.93 2009/03/18 16:00:24 cegger Exp $");
     42 
     43 #if defined(_KERNEL_OPT)
     44 #include "opt_ffs.h"
     45 #endif
     46 
     47 #include <sys/param.h>
     48 #include <sys/kernel.h>
     49 #include <sys/systm.h>
     50 #include <sys/conf.h>
     51 #include <sys/buf.h>
     52 #include <sys/proc.h>
     53 #include <sys/namei.h>
     54 #include <sys/sched.h>
     55 #include <sys/stat.h>
     56 #include <sys/malloc.h>
     57 #include <sys/mount.h>
     58 #include <sys/resource.h>
     59 #include <sys/resourcevar.h>
     60 #include <sys/vnode.h>
     61 #include <sys/kauth.h>
     62 #include <sys/fstrans.h>
     63 #include <sys/wapbl.h>
     64 
     65 #include <miscfs/specfs/specdev.h>
     66 
     67 #include <ufs/ufs/quota.h>
     68 #include <ufs/ufs/ufsmount.h>
     69 #include <ufs/ufs/inode.h>
     70 #include <ufs/ufs/ufs_extern.h>
     71 #include <ufs/ufs/ufs_bswap.h>
     72 #include <ufs/ufs/ufs_wapbl.h>
     73 
     74 #include <ufs/ffs/fs.h>
     75 #include <ufs/ffs/ffs_extern.h>
     76 
     77 #include <uvm/uvm.h>
     78 
     79 #if !defined(FFS_NO_SNAPSHOT)
     80 typedef int (*acctfunc_t)
     81     (struct vnode *, void *, int, int, struct fs *, daddr_t, int);
     82 
     83 static int snapshot_setup(struct mount *, struct vnode *);
     84 static int snapshot_copyfs(struct mount *, struct vnode *, void **);
     85 static int snapshot_expunge(struct mount *, struct vnode *,
     86     struct fs *, daddr_t *, daddr_t **);
     87 static int snapshot_expunge_snap(struct mount *, struct vnode *,
     88     struct fs *, daddr_t);
     89 static int snapshot_writefs(struct mount *, struct vnode *, void *);
     90 static int cgaccount(struct vnode *, int, int *);
     91 static int cgaccount1(int, struct vnode *, void *, int);
     92 static int expunge(struct vnode *, struct inode *, struct fs *,
     93     acctfunc_t, int);
     94 static int indiracct(struct vnode *, struct vnode *, int, daddr_t,
     95     daddr_t, daddr_t, daddr_t, daddr_t, struct fs *, acctfunc_t, int);
     96 static int fullacct(struct vnode *, void *, int, int, struct fs *,
     97     daddr_t, int);
     98 static int snapacct(struct vnode *, void *, int, int, struct fs *,
     99     daddr_t, int);
    100 static int mapacct(struct vnode *, void *, int, int, struct fs *,
    101     daddr_t, int);
    102 #endif /* !defined(FFS_NO_SNAPSHOT) */
    103 
    104 static int ffs_copyonwrite(void *, struct buf *, bool);
    105 static int snapblkaddr(struct vnode *, daddr_t, daddr_t *);
    106 static int rwfsblk(struct vnode *, int, void *, daddr_t);
    107 static int syncsnap(struct vnode *);
    108 static int wrsnapblk(struct vnode *, void *, daddr_t);
    109 
    110 static inline daddr_t db_get(struct inode *, int);
    111 static inline void db_assign(struct inode *, int, daddr_t);
    112 static inline daddr_t ib_get(struct inode *, int);
    113 static inline void ib_assign(struct inode *, int, daddr_t);
    114 static inline daddr_t idb_get(struct inode *, void *, int);
    115 static inline void idb_assign(struct inode *, void *, int, daddr_t);
    116 
    117 struct snap_info {
    118 	kmutex_t si_lock;			/* Lock this snapinfo */
    119 	kmutex_t si_snaplock;			/* Snapshot vnode common lock */
    120 	TAILQ_HEAD(inodelst, inode) si_snapshots; /* List of active snapshots */
    121 	daddr_t *si_snapblklist;		/* Snapshot block hints list */
    122 	uint32_t si_gen;			/* Incremented on change */
    123 };
    124 
    125 #ifdef DEBUG
    126 static int snapdebug = 0;
    127 #endif
    128 
    129 int
    130 ffs_snapshot_init(struct ufsmount *ump)
    131 {
    132 	struct snap_info *si;
    133 
    134 	si = ump->um_snapinfo = kmem_alloc(sizeof(*si), KM_SLEEP);
    135 	if (si == NULL)
    136 		return ENOMEM;
    137 
    138 	TAILQ_INIT(&si->si_snapshots);
    139 	mutex_init(&si->si_lock, MUTEX_DEFAULT, IPL_NONE);
    140 	mutex_init(&si->si_snaplock, MUTEX_DEFAULT, IPL_NONE);
    141 	si->si_gen = 0;
    142 	si->si_snapblklist = NULL;
    143 
    144 	return 0;
    145 }
    146 
    147 void
    148 ffs_snapshot_fini(struct ufsmount *ump)
    149 {
    150 	struct snap_info *si;
    151 
    152 	si = ump->um_snapinfo;
    153 	ump->um_snapinfo = NULL;
    154 
    155 	KASSERT(TAILQ_EMPTY(&si->si_snapshots));
    156 	mutex_destroy(&si->si_lock);
    157 	mutex_destroy(&si->si_snaplock);
    158 	KASSERT(si->si_snapblklist == NULL);
    159 	kmem_free(si, sizeof(*si));
    160 }
    161 
    162 /*
    163  * Create a snapshot file and initialize it for the filesystem.
    164  * Vnode is locked on entry and return.
    165  */
    166 int
    167 ffs_snapshot(struct mount *mp, struct vnode *vp, struct timespec *ctime)
    168 {
    169 #if defined(FFS_NO_SNAPSHOT)
    170 	return EOPNOTSUPP;
    171 }
    172 #else /* defined(FFS_NO_SNAPSHOT) */
    173 	bool suspended = false;
    174 	bool snapshot_locked = false;
    175 	int error, redo = 0, snaploc;
    176 	void *sbbuf = NULL;
    177 	daddr_t *snaplist = NULL, snaplistsize = 0;
    178 	struct buf *bp, *nbp;
    179 	struct fs *copy_fs, *fs = VFSTOUFS(mp)->um_fs;
    180 	struct inode *ip = VTOI(vp);
    181 	struct lwp *l = curlwp;
    182 	struct snap_info *si = VFSTOUFS(mp)->um_snapinfo;
    183 	struct timespec ts;
    184 	struct timeval starttime;
    185 #ifdef DEBUG
    186 	struct timeval endtime;
    187 #endif
    188 	struct vnode *devvp = ip->i_devvp;
    189 
    190 	/*
    191 	 * If the vnode already is a snapshot, return.
    192 	 */
    193 	if (VTOI(vp)->i_flags & SF_SNAPSHOT) {
    194 		if (ctime) {
    195 			ctime->tv_sec = DIP(VTOI(vp), mtime);
    196 			ctime->tv_nsec = DIP(VTOI(vp), mtimensec);
    197 		}
    198 		return 0;
    199 	}
    200 	/*
    201 	 * Check for free snapshot slot in the superblock.
    202 	 */
    203 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
    204 		if (fs->fs_snapinum[snaploc] == 0)
    205 			break;
    206 	if (snaploc == FSMAXSNAP)
    207 		return (ENOSPC);
    208 	/*
    209 	 * Prepare the vnode to become a snapshot.
    210 	 */
    211 	error = snapshot_setup(mp, vp);
    212 	if (error)
    213 		goto out;
    214 	/*
    215 	 * Change inode to snapshot type file.
    216 	 */
    217 	ip->i_flags |= SF_SNAPSHOT;
    218 	DIP_ASSIGN(ip, flags, ip->i_flags);
    219 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
    220 	/*
    221 	 * Copy all the cylinder group maps. Although the
    222 	 * filesystem is still active, we hope that only a few
    223 	 * cylinder groups will change between now and when we
    224 	 * suspend operations. Thus, we will be able to quickly
    225 	 * touch up the few cylinder groups that changed during
    226 	 * the suspension period.
    227 	 */
    228 	error = cgaccount(vp, 1, NULL);
    229 	if (error)
    230 		goto out;
    231 	/*
    232 	 * Ensure that the snapshot is completely on disk.
    233 	 * Since we have marked it as a snapshot it is safe to
    234 	 * unlock it as no process will be allowed to write to it.
    235 	 */
    236 	error = VOP_FSYNC(vp, l->l_cred, FSYNC_WAIT, 0, 0);
    237 	if (error)
    238 		goto out;
    239 	VOP_UNLOCK(vp, 0);
    240 	/*
    241 	 * All allocations are done, so we can now suspend the filesystem.
    242 	 */
    243 	error = vfs_suspend(vp->v_mount, 0);
    244 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    245 	if (error)
    246 		goto out;
    247 	suspended = true;
    248 	getmicrotime(&starttime);
    249 	/*
    250 	 * First, copy all the cylinder group maps that have changed.
    251 	 */
    252 	error = cgaccount(vp, 2, &redo);
    253 	if (error)
    254 		goto out;
    255 	/*
    256 	 * Create a copy of the superblock and its summary information.
    257 	 */
    258 	error = snapshot_copyfs(mp, vp, &sbbuf);
    259 	copy_fs = (struct fs *)((char *)sbbuf + blkoff(fs, fs->fs_sblockloc));
    260 	if (error)
    261 		goto out;
    262 	/*
    263 	 * Expunge unlinked files from our view.
    264 	 */
    265 	error = snapshot_expunge(mp, vp, copy_fs, &snaplistsize, &snaplist);
    266 	if (error)
    267 		goto out;
    268 	/*
    269 	 * Acquire the snapshot lock.
    270 	 */
    271 	mutex_enter(&si->si_snaplock);
    272 	snapshot_locked = true;
    273 	/*
    274 	 * Record snapshot inode. Since this is the newest snapshot,
    275 	 * it must be placed at the end of the list.
    276 	 */
    277 	fs->fs_snapinum[snaploc] = ip->i_number;
    278 
    279 	mutex_enter(&si->si_lock);
    280 	if (ip->i_nextsnap.tqe_prev != 0)
    281 		panic("ffs_snapshot: %"PRIu64" already on list", ip->i_number);
    282 	TAILQ_INSERT_TAIL(&si->si_snapshots, ip, i_nextsnap);
    283 	if (TAILQ_FIRST(&si->si_snapshots) == ip) {
    284 		/*
    285 		 * If this is the first snapshot on this filesystem, put the
    286 		 * preliminary list in place and establish the cow handler.
    287 		 */
    288 		si->si_snapblklist = snaplist;
    289 		fscow_establish(mp, ffs_copyonwrite, devvp);
    290 	}
    291 	si->si_gen++;
    292 	mutex_exit(&si->si_lock);
    293 
    294 	vp->v_vflag |= VV_SYSTEM;
    295 	/*
    296 	 * Set the mtime to the time the snapshot has been taken.
    297 	 */
    298 	TIMEVAL_TO_TIMESPEC(&starttime, &ts);
    299 	if (ctime)
    300 		*ctime = ts;
    301 	DIP_ASSIGN(ip, mtime, ts.tv_sec);
    302 	DIP_ASSIGN(ip, mtimensec, ts.tv_nsec);
    303 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
    304 	/*
    305 	 * Copy allocation information from all snapshots and then
    306 	 * expunge them from our view.
    307 	 */
    308 	error = snapshot_expunge_snap(mp, vp, copy_fs, snaplistsize);
    309 	if (error)
    310 		goto out;
    311 	/*
    312 	 * Write the superblock and its summary information to the snapshot.
    313 	 */
    314 	error = snapshot_writefs(mp, vp, sbbuf);
    315 	if (error)
    316 		goto out;
    317 	/*
    318 	 * We're nearly done, ensure that the snapshot is completely on disk.
    319 	 */
    320 	error = VOP_FSYNC(vp, l->l_cred, FSYNC_WAIT, 0, 0);
    321 	if (error)
    322 		goto out;
    323 	/*
    324 	 * Invalidate and free all pages on the snapshot vnode.
    325 	 * We will read and write through the buffercache.
    326 	 */
    327 	mutex_enter(&vp->v_interlock);
    328 	error = VOP_PUTPAGES(vp, 0, 0,
    329 		    PGO_ALLPAGES | PGO_CLEANIT | PGO_SYNCIO | PGO_FREE);
    330 	if (error)
    331 		goto out;
    332 	/*
    333 	 * Invalidate short ( < fs_bsize ) buffers.  We will always read
    334 	 * full size buffers later.
    335 	 */
    336 	mutex_enter(&bufcache_lock);
    337 	KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
    338 	for (bp = LIST_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
    339 		nbp = LIST_NEXT(bp, b_vnbufs);
    340 		KASSERT((bp->b_cflags & BC_BUSY) == 0);
    341 		if (bp->b_bcount < fs->fs_bsize) {
    342 			bp->b_cflags |= BC_BUSY;
    343 			brelsel(bp, BC_INVAL | BC_VFLUSH);
    344 		}
    345 	}
    346 	mutex_exit(&bufcache_lock);
    347 
    348 out:
    349 	if (sbbuf != NULL) {
    350 		free(copy_fs->fs_csp, M_UFSMNT);
    351 		free(sbbuf, M_UFSMNT);
    352 	}
    353 	if (fs->fs_active != NULL) {
    354 		free(fs->fs_active, M_DEVBUF);
    355 		fs->fs_active = NULL;
    356 	}
    357 
    358 	mutex_enter(&si->si_lock);
    359 	if (snaplist != NULL) {
    360 		if (si->si_snapblklist == snaplist)
    361 			si->si_snapblklist = NULL;
    362 		free(snaplist, M_UFSMNT);
    363 	}
    364 	if (error) {
    365 		fs->fs_snapinum[snaploc] = 0;
    366 	} else {
    367 		/*
    368 		 * As this is the newest list, it is the most inclusive, so
    369 		 * should replace the previous list.
    370 		 */
    371 		si->si_snapblklist = ip->i_snapblklist;
    372 	}
    373 	si->si_gen++;
    374 	mutex_exit(&si->si_lock);
    375 
    376 	if (snapshot_locked)
    377 		mutex_exit(&si->si_snaplock);
    378 	if (suspended) {
    379 		vfs_resume(vp->v_mount);
    380 #ifdef DEBUG
    381 		getmicrotime(&endtime);
    382 		timersub(&endtime, &starttime, &endtime);
    383 		printf("%s: suspended %lld.%03d sec, redo %d of %d\n",
    384 		    mp->mnt_stat.f_mntonname, (long long)endtime.tv_sec,
    385 		    endtime.tv_usec / 1000, redo, fs->fs_ncg);
    386 #endif
    387 	}
    388 	if (error) {
    389 		if (!UFS_WAPBL_BEGIN(mp)) {
    390 			(void) ffs_truncate(vp, (off_t)0, 0, NOCRED);
    391 			UFS_WAPBL_END(mp);
    392 		}
    393 	} else
    394 		vref(vp);
    395 	return (error);
    396 }
    397 
    398 /*
    399  * Prepare vnode to become a snapshot.
    400  */
    401 static int
    402 snapshot_setup(struct mount *mp, struct vnode *vp)
    403 {
    404 	int error, i, len, loc;
    405 	daddr_t blkno, numblks;
    406 	struct buf *ibp, *nbp;
    407 	struct fs *fs = VFSTOUFS(mp)->um_fs;
    408 	struct lwp *l = curlwp;
    409 
    410 	/*
    411 	 * Check mount, exclusive reference and owner.
    412 	 */
    413 	if (vp->v_mount != mp)
    414 		return EXDEV;
    415 	if (vp->v_usecount != 1 || vp->v_writecount != 0)
    416 		return EBUSY;
    417 	if (kauth_authorize_generic(l->l_cred, KAUTH_GENERIC_ISSUSER,
    418 	    NULL) != 0 &&
    419 	    VTOI(vp)->i_uid != kauth_cred_geteuid(l->l_cred))
    420 		return EACCES;
    421 
    422 	if (vp->v_size != 0) {
    423 		error = ffs_truncate(vp, 0, 0, NOCRED);
    424 		if (error)
    425 			return error;
    426 	}
    427 	/*
    428 	 * Write an empty list of preallocated blocks to the end of
    429 	 * the snapshot to set size to at least that of the filesystem.
    430 	 */
    431 	numblks = howmany(fs->fs_size, fs->fs_frag);
    432 	blkno = 1;
    433 	blkno = ufs_rw64(blkno, UFS_FSNEEDSWAP(fs));
    434 	error = vn_rdwr(UIO_WRITE, vp,
    435 	    (void *)&blkno, sizeof(blkno), lblktosize(fs, (off_t)numblks),
    436 	    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, l->l_cred, NULL, NULL);
    437 	if (error)
    438 		return error;
    439 	/*
    440 	 * Preallocate critical data structures so that we can copy
    441 	 * them in without further allocation after we suspend all
    442 	 * operations on the filesystem. We would like to just release
    443 	 * the allocated buffers without writing them since they will
    444 	 * be filled in below once we are ready to go, but this upsets
    445 	 * the soft update code, so we go ahead and write the new buffers.
    446 	 *
    447 	 * Allocate all indirect blocks and mark all of them as not
    448 	 * needing to be copied.
    449 	 */
    450 	error = UFS_WAPBL_BEGIN(mp);
    451 	if (error)
    452 		return error;
    453 	for (blkno = NDADDR, i = 0; blkno < numblks; blkno += NINDIR(fs)) {
    454 		error = ffs_balloc(vp, lblktosize(fs, (off_t)blkno),
    455 		    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
    456 		if (error)
    457 			goto out;
    458 		brelse(ibp, 0);
    459 		if ((++i % 16) == 0) {
    460 			UFS_WAPBL_END(mp);
    461 			error = UFS_WAPBL_BEGIN(mp);
    462 			if (error)
    463 				return error;
    464 		}
    465 	}
    466 	/*
    467 	 * Allocate copies for the superblock and its summary information.
    468 	 */
    469 	error = ffs_balloc(vp, fs->fs_sblockloc, fs->fs_sbsize, l->l_cred,
    470 	    0, &nbp);
    471 	if (error)
    472 		goto out;
    473 	bawrite(nbp);
    474 	blkno = fragstoblks(fs, fs->fs_csaddr);
    475 	len = howmany(fs->fs_cssize, fs->fs_bsize);
    476 	for (loc = 0; loc < len; loc++) {
    477 		error = ffs_balloc(vp, lblktosize(fs, (off_t)(blkno + loc)),
    478 		    fs->fs_bsize, l->l_cred, 0, &nbp);
    479 		if (error)
    480 			goto out;
    481 		bawrite(nbp);
    482 	}
    483 
    484 out:
    485 	UFS_WAPBL_END(mp);
    486 	return error;
    487 }
    488 
    489 /*
    490  * Create a copy of the superblock and its summary information.
    491  * It is up to the caller to free copyfs and copy_fs->fs_csp.
    492  */
    493 static int
    494 snapshot_copyfs(struct mount *mp, struct vnode *vp, void **sbbuf)
    495 {
    496 	int error, i, len, loc, size;
    497 	void *space;
    498 	int32_t *lp;
    499 	struct buf *bp;
    500 	struct fs *copyfs, *fs = VFSTOUFS(mp)->um_fs;
    501 	struct lwp *l = curlwp;
    502 	struct vnode *devvp = VTOI(vp)->i_devvp;
    503 
    504 	/*
    505 	 * Grab a copy of the superblock and its summary information.
    506 	 * We delay writing it until the suspension is released below.
    507 	 */
    508 	*sbbuf = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
    509 	loc = blkoff(fs, fs->fs_sblockloc);
    510 	if (loc > 0)
    511 		memset(*sbbuf, 0, loc);
    512 	copyfs = (struct fs *)((char *)(*sbbuf) + loc);
    513 	bcopy(fs, copyfs, fs->fs_sbsize);
    514 	size = fs->fs_bsize < SBLOCKSIZE ? fs->fs_bsize : SBLOCKSIZE;
    515 	if (fs->fs_sbsize < size)
    516 		memset((char *)(*sbbuf) + loc + fs->fs_sbsize, 0,
    517 		    size - fs->fs_sbsize);
    518 	size = blkroundup(fs, fs->fs_cssize);
    519 	if (fs->fs_contigsumsize > 0)
    520 		size += fs->fs_ncg * sizeof(int32_t);
    521 	space = malloc(size, M_UFSMNT, M_WAITOK);
    522 	copyfs->fs_csp = space;
    523 	bcopy(fs->fs_csp, copyfs->fs_csp, fs->fs_cssize);
    524 	space = (char *)space + fs->fs_cssize;
    525 	loc = howmany(fs->fs_cssize, fs->fs_fsize);
    526 	i = fs->fs_frag - loc % fs->fs_frag;
    527 	len = (i == fs->fs_frag) ? 0 : i * fs->fs_fsize;
    528 	if (len > 0) {
    529 		if ((error = bread(devvp, fsbtodb(fs, fs->fs_csaddr + loc),
    530 		    len, l->l_cred, 0, &bp)) != 0) {
    531 			brelse(bp, 0);
    532 			free(copyfs->fs_csp, M_UFSMNT);
    533 			free(*sbbuf, M_UFSMNT);
    534 			*sbbuf = NULL;
    535 			return error;
    536 		}
    537 		bcopy(bp->b_data, space, (u_int)len);
    538 		space = (char *)space + len;
    539 		brelse(bp, BC_INVAL | BC_NOCACHE);
    540 	}
    541 	if (fs->fs_contigsumsize > 0) {
    542 		copyfs->fs_maxcluster = lp = space;
    543 		for (i = 0; i < fs->fs_ncg; i++)
    544 			*lp++ = fs->fs_contigsumsize;
    545 	}
    546 	if (mp->mnt_wapbl)
    547 		copyfs->fs_flags &= ~FS_DOWAPBL;
    548 	return 0;
    549 }
    550 
    551 /*
    552  * We must check for active files that have been unlinked (e.g., with a zero
    553  * link count). We have to expunge all trace of these files from the snapshot
    554  * so that they are not reclaimed prematurely by fsck or unnecessarily dumped.
    555  * Note that we skip unlinked snapshot files as they will be handled separately.
    556  * Calculate the snapshot list size and create a preliminary list.
    557  */
    558 static int
    559 snapshot_expunge(struct mount *mp, struct vnode *vp, struct fs *copy_fs,
    560     daddr_t *snaplistsize, daddr_t **snaplist)
    561 {
    562 	bool has_wapbl = false;
    563 	int cg, error, len, loc;
    564 	daddr_t blkno, *blkp;
    565 	struct fs *fs = VFSTOUFS(mp)->um_fs;
    566 	struct inode *xp;
    567 	struct lwp *l = curlwp;
    568 	struct vattr vat;
    569 	struct vnode *logvp = NULL, *mvp = NULL, *xvp;
    570 
    571 	*snaplist = NULL;
    572 	/*
    573 	 * Get the log inode if any.
    574 	 */
    575 	if ((fs->fs_flags & FS_DOWAPBL) &&
    576 	    fs->fs_journal_location == UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM) {
    577 		error = VFS_VGET(mp,
    578 		    fs->fs_journallocs[UFS_WAPBL_INFS_INO], &logvp);
    579 		if (error)
    580 			goto out;
    581 	}
    582 	/*
    583 	 * Allocate a marker vnode.
    584 	 */
    585 	if ((mvp = vnalloc(mp)) == NULL) {
    586 		error = ENOMEM;
    587 		goto out;
    588 	}
    589 	/*
    590 	 * We also calculate the needed size for the snapshot list.
    591 	 */
    592 	*snaplistsize = fs->fs_ncg + howmany(fs->fs_cssize, fs->fs_bsize) +
    593 	    FSMAXSNAP + 1 /* superblock */ + 1 /* last block */ + 1 /* size */;
    594 	error = UFS_WAPBL_BEGIN(mp);
    595 	if (error)
    596 		goto out;
    597 	has_wapbl = true;
    598 	mutex_enter(&mntvnode_lock);
    599 	/*
    600 	 * NOTE: not using the TAILQ_FOREACH here since in this loop vgone()
    601 	 * and vclean() can be called indirectly
    602 	 */
    603 	for (xvp = TAILQ_FIRST(&mp->mnt_vnodelist); xvp; xvp = vunmark(mvp)) {
    604 		vmark(mvp, xvp);
    605 		/*
    606 		 * Make sure this vnode wasn't reclaimed in getnewvnode().
    607 		 * Start over if it has (it won't be on the list anymore).
    608 		 */
    609 		if (xvp->v_mount != mp || vismarker(xvp))
    610 			continue;
    611 		mutex_enter(&xvp->v_interlock);
    612 		if ((xvp->v_iflag & VI_XLOCK) ||
    613 		    xvp->v_usecount == 0 || xvp->v_type == VNON ||
    614 		    VTOI(xvp) == NULL ||
    615 		    (VTOI(xvp)->i_flags & SF_SNAPSHOT)) {
    616 			mutex_exit(&xvp->v_interlock);
    617 			continue;
    618 		}
    619 		mutex_exit(&mntvnode_lock);
    620 		/*
    621 		 * XXXAD should increase vnode ref count to prevent it
    622 		 * disappearing or being recycled.
    623 		 */
    624 		mutex_exit(&xvp->v_interlock);
    625 #ifdef DEBUG
    626 		if (snapdebug)
    627 			vprint("ffs_snapshot: busy vnode", xvp);
    628 #endif
    629 		xp = VTOI(xvp);
    630 		if (xvp != logvp) {
    631 			if (VOP_GETATTR(xvp, &vat, l->l_cred) == 0 &&
    632 			    vat.va_nlink > 0) {
    633 				mutex_enter(&mntvnode_lock);
    634 				continue;
    635 			}
    636 			if (ffs_checkfreefile(copy_fs, vp, xp->i_number)) {
    637 				mutex_enter(&mntvnode_lock);
    638 				continue;
    639 			}
    640 		}
    641 		/*
    642 		 * If there is a fragment, clear it here.
    643 		 */
    644 		blkno = 0;
    645 		loc = howmany(xp->i_size, fs->fs_bsize) - 1;
    646 		if (loc < NDADDR) {
    647 			len = fragroundup(fs, blkoff(fs, xp->i_size));
    648 			if (len > 0 && len < fs->fs_bsize) {
    649 				ffs_blkfree_snap(copy_fs, vp, db_get(xp, loc),
    650 				    len, xp->i_number);
    651 				blkno = db_get(xp, loc);
    652 				db_assign(xp, loc, 0);
    653 			}
    654 		}
    655 		*snaplistsize += 1;
    656 		error = expunge(vp, xp, copy_fs, fullacct, BLK_NOCOPY);
    657 		if (blkno)
    658 			db_assign(xp, loc, blkno);
    659 		if (!error)
    660 			error = ffs_freefile_snap(copy_fs, vp, xp->i_number,
    661 			    xp->i_mode);
    662 		if (error) {
    663 			(void)vunmark(mvp);
    664 			goto out;
    665 		}
    666 		mutex_enter(&mntvnode_lock);
    667 	}
    668 	mutex_exit(&mntvnode_lock);
    669 	/*
    670 	 * Create a preliminary list of preallocated snapshot blocks.
    671 	 */
    672 	*snaplist = malloc(*snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
    673 	blkp = &(*snaplist)[1];
    674 	*blkp++ = lblkno(fs, fs->fs_sblockloc);
    675 	blkno = fragstoblks(fs, fs->fs_csaddr);
    676 	for (cg = 0; cg < fs->fs_ncg; cg++) {
    677 		if (fragstoblks(fs, cgtod(fs, cg)) > blkno)
    678 			break;
    679 		*blkp++ = fragstoblks(fs, cgtod(fs, cg));
    680 	}
    681 	len = howmany(fs->fs_cssize, fs->fs_bsize);
    682 	for (loc = 0; loc < len; loc++)
    683 		*blkp++ = blkno + loc;
    684 	for (; cg < fs->fs_ncg; cg++)
    685 		*blkp++ = fragstoblks(fs, cgtod(fs, cg));
    686 
    687 out:
    688 	if (has_wapbl)
    689 		UFS_WAPBL_END(mp);
    690 	if (mvp != NULL)
    691 		vnfree(mvp);
    692 	if (logvp != NULL)
    693 		vput(logvp);
    694 	if (error && *snaplist != NULL) {
    695 		free(*snaplist, M_UFSMNT);
    696 		*snaplist = NULL;
    697 	}
    698 
    699 	return error;
    700 }
    701 
    702 /*
    703  * Copy allocation information from all the snapshots in this snapshot and
    704  * then expunge them from its view. Also, collect the list of allocated
    705  * blocks in i_snapblklist.
    706  */
    707 static int
    708 snapshot_expunge_snap(struct mount *mp, struct vnode *vp,
    709     struct fs *copy_fs, daddr_t snaplistsize)
    710 {
    711 	int error, i;
    712 	daddr_t numblks, *snaplist = NULL;
    713 	struct fs *fs = VFSTOUFS(mp)->um_fs;
    714 	struct inode *ip = VTOI(vp), *xp;
    715 	struct lwp *l = curlwp;
    716 	struct snap_info *si = VFSTOUFS(mp)->um_snapinfo;
    717 
    718 	error = UFS_WAPBL_BEGIN(mp);
    719 	if (error)
    720 		return error;
    721 	TAILQ_FOREACH(xp, &si->si_snapshots, i_nextsnap) {
    722 		if (xp == ip)
    723 			break;
    724 		error = expunge(vp, xp, fs, snapacct, BLK_SNAP);
    725 		if (error)
    726 			break;
    727 		if (xp->i_nlink != 0)
    728 			continue;
    729 		error = ffs_freefile_snap(copy_fs, vp, xp->i_number, xp->i_mode);
    730 		if (error)
    731 			break;
    732 	}
    733 	if (error)
    734 		goto out;
    735 	/*
    736 	 * Allocate space for the full list of preallocated snapshot blocks.
    737 	 */
    738 	snaplist = malloc(snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
    739 	ip->i_snapblklist = &snaplist[1];
    740 	/*
    741 	 * Expunge the blocks used by the snapshots from the set of
    742 	 * blocks marked as used in the snapshot bitmaps. Also, collect
    743 	 * the list of allocated blocks in i_snapblklist.
    744 	 */
    745 	error = expunge(vp, ip, copy_fs, mapacct, BLK_SNAP);
    746 	if (error)
    747 		goto out;
    748 	if (snaplistsize < ip->i_snapblklist - snaplist)
    749 		panic("ffs_snapshot: list too small");
    750 	snaplistsize = ip->i_snapblklist - snaplist;
    751 	snaplist[0] = snaplistsize;
    752 	ip->i_snapblklist = &snaplist[0];
    753 	/*
    754 	 * Write out the list of allocated blocks to the end of the snapshot.
    755 	 */
    756 	numblks = howmany(fs->fs_size, fs->fs_frag);
    757 	for (i = 0; i < snaplistsize; i++)
    758 		snaplist[i] = ufs_rw64(snaplist[i], UFS_FSNEEDSWAP(fs));
    759 	error = vn_rdwr(UIO_WRITE, vp, (void *)snaplist,
    760 	    snaplistsize * sizeof(daddr_t), lblktosize(fs, (off_t)numblks),
    761 	    UIO_SYSSPACE, IO_NODELOCKED | IO_JOURNALLOCKED | IO_UNIT,
    762 	    l->l_cred, NULL, NULL);
    763 	for (i = 0; i < snaplistsize; i++)
    764 		snaplist[i] = ufs_rw64(snaplist[i], UFS_FSNEEDSWAP(fs));
    765 out:
    766 	UFS_WAPBL_END(mp);
    767 	if (error && snaplist != NULL) {
    768 		free(snaplist, M_UFSMNT);
    769 		ip->i_snapblklist = NULL;
    770 	}
    771 	return error;
    772 }
    773 
    774 /*
    775  * Write the superblock and its summary information to the snapshot.
    776  * Make sure, the first NDADDR blocks get copied to the snapshot.
    777  */
    778 static int
    779 snapshot_writefs(struct mount *mp, struct vnode *vp, void *sbbuf)
    780 {
    781 	int error, len, loc;
    782 	void *space;
    783 	daddr_t blkno;
    784 	struct buf *bp;
    785 	struct fs *copyfs, *fs = VFSTOUFS(mp)->um_fs;
    786 	struct inode *ip = VTOI(vp);
    787 	struct lwp *l = curlwp;
    788 
    789 	copyfs = (struct fs *)((char *)sbbuf + blkoff(fs, fs->fs_sblockloc));
    790 
    791 	/*
    792 	 * Write the superblock and its summary information
    793 	 * to the snapshot.
    794 	 */
    795 	blkno = fragstoblks(fs, fs->fs_csaddr);
    796 	len = howmany(fs->fs_cssize, fs->fs_bsize);
    797 	space = copyfs->fs_csp;
    798 #ifdef FFS_EI
    799 	if (UFS_FSNEEDSWAP(fs)) {
    800 		ffs_sb_swap(copyfs, copyfs);
    801 		ffs_csum_swap(space, space, fs->fs_cssize);
    802 	}
    803 #endif
    804 	error = UFS_WAPBL_BEGIN(mp);
    805 	if (error)
    806 		return error;
    807 	for (loc = 0; loc < len; loc++) {
    808 		error = bread(vp, blkno + loc, fs->fs_bsize, l->l_cred,
    809 		    B_MODIFY, &bp);
    810 		if (error) {
    811 			brelse(bp, 0);
    812 			break;
    813 		}
    814 		bcopy(space, bp->b_data, fs->fs_bsize);
    815 		space = (char *)space + fs->fs_bsize;
    816 		bawrite(bp);
    817 	}
    818 	if (error)
    819 		goto out;
    820 	error = bread(vp, lblkno(fs, fs->fs_sblockloc),
    821 	    fs->fs_bsize, l->l_cred, B_MODIFY, &bp);
    822 	if (error) {
    823 		brelse(bp, 0);
    824 		goto out;
    825 	} else {
    826 		bcopy(sbbuf, bp->b_data, fs->fs_bsize);
    827 		bawrite(bp);
    828 	}
    829 	/*
    830 	 * Copy the first NDADDR blocks to the snapshot so ffs_copyonwrite()
    831 	 * and ffs_snapblkfree() will always work on indirect blocks.
    832 	 */
    833 	for (loc = 0; loc < NDADDR; loc++) {
    834 		if (db_get(ip, loc) != 0)
    835 			continue;
    836 		error = ffs_balloc(vp, lblktosize(fs, (off_t)loc),
    837 		    fs->fs_bsize, l->l_cred, 0, &bp);
    838 		if (error)
    839 			break;
    840 		error = rwfsblk(vp, B_READ, bp->b_data, loc);
    841 		if (error) {
    842 			brelse(bp, 0);
    843 			break;
    844 		}
    845 		bawrite(bp);
    846 	}
    847 
    848 out:
    849 	UFS_WAPBL_END(mp);
    850 	return error;
    851 }
    852 
    853 /*
    854  * Copy all cylinder group maps.
    855  */
    856 static int
    857 cgaccount(struct vnode *vp, int passno, int *redo)
    858 {
    859 	int cg, error;
    860 	struct buf *nbp;
    861 	struct fs *fs = VTOI(vp)->i_fs;
    862 
    863 	error = UFS_WAPBL_BEGIN(vp->v_mount);
    864 	if (error)
    865 		return error;
    866 	if (redo != NULL)
    867 		*redo = 0;
    868 	if (passno == 1)
    869 		fs->fs_active = malloc(howmany(fs->fs_ncg, NBBY),
    870 		    M_DEVBUF, M_WAITOK | M_ZERO);
    871 	for (cg = 0; cg < fs->fs_ncg; cg++) {
    872 		if (passno == 2 && ACTIVECG_ISSET(fs, cg))
    873 			continue;
    874 		if (redo != NULL)
    875 			*redo += 1;
    876 		error = ffs_balloc(vp, lfragtosize(fs, cgtod(fs, cg)),
    877 		    fs->fs_bsize, curlwp->l_cred, 0, &nbp);
    878 		if (error)
    879 			break;
    880 		error = cgaccount1(cg, vp, nbp->b_data, passno);
    881 		bawrite(nbp);
    882 		if (error)
    883 			break;
    884 	}
    885 	UFS_WAPBL_END(vp->v_mount);
    886 	return error;
    887 }
    888 
    889 /*
    890  * Copy a cylinder group map. All the unallocated blocks are marked
    891  * BLK_NOCOPY so that the snapshot knows that it need not copy them
    892  * if they are later written. If passno is one, then this is a first
    893  * pass, so only setting needs to be done. If passno is 2, then this
    894  * is a revision to a previous pass which must be undone as the
    895  * replacement pass is done.
    896  */
    897 static int
    898 cgaccount1(int cg, struct vnode *vp, void *data, int passno)
    899 {
    900 	struct buf *bp, *ibp;
    901 	struct inode *ip;
    902 	struct cg *cgp;
    903 	struct fs *fs;
    904 	struct lwp *l = curlwp;
    905 	daddr_t base, numblks;
    906 	int error, len, loc, ns, indiroff;
    907 
    908 	ip = VTOI(vp);
    909 	fs = ip->i_fs;
    910 	ns = UFS_FSNEEDSWAP(fs);
    911 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
    912 		(int)fs->fs_cgsize, l->l_cred, 0, &bp);
    913 	if (error) {
    914 		brelse(bp, 0);
    915 		return (error);
    916 	}
    917 	cgp = (struct cg *)bp->b_data;
    918 	if (!cg_chkmagic(cgp, ns)) {
    919 		brelse(bp, 0);
    920 		return (EIO);
    921 	}
    922 	ACTIVECG_SET(fs, cg);
    923 
    924 	bcopy(bp->b_data, data, fs->fs_cgsize);
    925 	brelse(bp, 0);
    926 	if (fs->fs_cgsize < fs->fs_bsize)
    927 		memset((char *)data + fs->fs_cgsize, 0,
    928 		    fs->fs_bsize - fs->fs_cgsize);
    929 	numblks = howmany(fs->fs_size, fs->fs_frag);
    930 	len = howmany(fs->fs_fpg, fs->fs_frag);
    931 	base = cg * fs->fs_fpg / fs->fs_frag;
    932 	if (base + len >= numblks)
    933 		len = numblks - base - 1;
    934 	loc = 0;
    935 	if (base < NDADDR) {
    936 		for ( ; loc < NDADDR; loc++) {
    937 			if (ffs_isblock(fs, cg_blksfree(cgp, ns), loc))
    938 				db_assign(ip, loc, BLK_NOCOPY);
    939 			else if (db_get(ip, loc) == BLK_NOCOPY) {
    940 				if (passno == 2)
    941 					db_assign(ip, loc, 0);
    942 				else if (passno == 1)
    943 					panic("ffs_snapshot: lost direct block");
    944 			}
    945 		}
    946 	}
    947 	if ((error = ffs_balloc(vp, lblktosize(fs, (off_t)(base + loc)),
    948 	    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp)) != 0)
    949 		return (error);
    950 	indiroff = (base + loc - NDADDR) % NINDIR(fs);
    951 	for ( ; loc < len; loc++, indiroff++) {
    952 		if (indiroff >= NINDIR(fs)) {
    953 			bawrite(ibp);
    954 			if ((error = ffs_balloc(vp,
    955 			    lblktosize(fs, (off_t)(base + loc)),
    956 			    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp)) != 0)
    957 				return (error);
    958 			indiroff = 0;
    959 		}
    960 		if (ffs_isblock(fs, cg_blksfree(cgp, ns), loc))
    961 			idb_assign(ip, ibp->b_data, indiroff, BLK_NOCOPY);
    962 		else if (idb_get(ip, ibp->b_data, indiroff) == BLK_NOCOPY) {
    963 			if (passno == 2)
    964 				idb_assign(ip, ibp->b_data, indiroff, 0);
    965 			else if (passno == 1)
    966 				panic("ffs_snapshot: lost indirect block");
    967 		}
    968 	}
    969 	bdwrite(ibp);
    970 	return (0);
    971 }
    972 
    973 /*
    974  * Before expunging a snapshot inode, note all the
    975  * blocks that it claims with BLK_SNAP so that fsck will
    976  * be able to account for those blocks properly and so
    977  * that this snapshot knows that it need not copy them
    978  * if the other snapshot holding them is freed.
    979  */
    980 static int
    981 expunge(struct vnode *snapvp, struct inode *cancelip, struct fs *fs,
    982     acctfunc_t acctfunc, int expungetype)
    983 {
    984 	int i, error, ns;
    985 	daddr_t lbn, rlbn;
    986 	daddr_t len, blkno, numblks, blksperindir;
    987 	struct ufs1_dinode *dip1;
    988 	struct ufs2_dinode *dip2;
    989 	struct lwp *l = curlwp;
    990 	void *bap;
    991 	struct buf *bp;
    992 
    993 	ns = UFS_FSNEEDSWAP(fs);
    994 	/*
    995 	 * Prepare to expunge the inode. If its inode block has not
    996 	 * yet been copied, then allocate and fill the copy.
    997 	 */
    998 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
    999 	error = snapblkaddr(snapvp, lbn, &blkno);
   1000 	if (error)
   1001 		return error;
   1002 	if (blkno != 0) {
   1003 		error = bread(snapvp, lbn, fs->fs_bsize, l->l_cred,
   1004 		    B_MODIFY, &bp);
   1005 	} else {
   1006 		error = ffs_balloc(snapvp, lblktosize(fs, (off_t)lbn),
   1007 		    fs->fs_bsize, l->l_cred, 0, &bp);
   1008 		if (! error)
   1009 			error = rwfsblk(snapvp, B_READ, bp->b_data, lbn);
   1010 	}
   1011 	if (error)
   1012 		return error;
   1013 	/*
   1014 	 * Set a snapshot inode to be a zero length file, regular files
   1015 	 * or unlinked snapshots to be completely unallocated.
   1016 	 */
   1017 	if (fs->fs_magic == FS_UFS1_MAGIC) {
   1018 		dip1 = (struct ufs1_dinode *)bp->b_data +
   1019 		    ino_to_fsbo(fs, cancelip->i_number);
   1020 		if (expungetype == BLK_NOCOPY || cancelip->i_nlink == 0)
   1021 			dip1->di_mode = 0;
   1022 		dip1->di_size = 0;
   1023 		dip1->di_blocks = 0;
   1024 		dip1->di_flags =
   1025 		    ufs_rw32(ufs_rw32(dip1->di_flags, ns) & ~SF_SNAPSHOT, ns);
   1026 		memset(&dip1->di_db[0], 0, (NDADDR + NIADDR) * sizeof(int32_t));
   1027 	} else {
   1028 		dip2 = (struct ufs2_dinode *)bp->b_data +
   1029 		    ino_to_fsbo(fs, cancelip->i_number);
   1030 		if (expungetype == BLK_NOCOPY || cancelip->i_nlink == 0)
   1031 			dip2->di_mode = 0;
   1032 		dip2->di_size = 0;
   1033 		dip2->di_blocks = 0;
   1034 		dip2->di_flags =
   1035 		    ufs_rw32(ufs_rw32(dip2->di_flags, ns) & ~SF_SNAPSHOT, ns);
   1036 		memset(&dip2->di_db[0], 0, (NDADDR + NIADDR) * sizeof(int64_t));
   1037 	}
   1038 	bdwrite(bp);
   1039 	/*
   1040 	 * Now go through and expunge all the blocks in the file
   1041 	 * using the function requested.
   1042 	 */
   1043 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
   1044 	if (fs->fs_magic == FS_UFS1_MAGIC)
   1045 		bap = &cancelip->i_ffs1_db[0];
   1046 	else
   1047 		bap = &cancelip->i_ffs2_db[0];
   1048 	if ((error = (*acctfunc)(snapvp, bap, 0, NDADDR, fs, 0, expungetype)))
   1049 		return (error);
   1050 	if (fs->fs_magic == FS_UFS1_MAGIC)
   1051 		bap = &cancelip->i_ffs1_ib[0];
   1052 	else
   1053 		bap = &cancelip->i_ffs2_ib[0];
   1054 	if ((error = (*acctfunc)(snapvp, bap, 0, NIADDR, fs, -1, expungetype)))
   1055 		return (error);
   1056 	blksperindir = 1;
   1057 	lbn = -NDADDR;
   1058 	len = numblks - NDADDR;
   1059 	rlbn = NDADDR;
   1060 	for (i = 0; len > 0 && i < NIADDR; i++) {
   1061 		error = indiracct(snapvp, ITOV(cancelip), i,
   1062 		    ib_get(cancelip, i), lbn, rlbn, len,
   1063 		    blksperindir, fs, acctfunc, expungetype);
   1064 		if (error)
   1065 			return (error);
   1066 		blksperindir *= NINDIR(fs);
   1067 		lbn -= blksperindir + 1;
   1068 		len -= blksperindir;
   1069 		rlbn += blksperindir;
   1070 	}
   1071 	return (0);
   1072 }
   1073 
   1074 /*
   1075  * Descend an indirect block chain for vnode cancelvp accounting for all
   1076  * its indirect blocks in snapvp.
   1077  */
   1078 static int
   1079 indiracct(struct vnode *snapvp, struct vnode *cancelvp, int level,
   1080     daddr_t blkno, daddr_t lbn, daddr_t rlbn, daddr_t remblks,
   1081     daddr_t blksperindir, struct fs *fs, acctfunc_t acctfunc, int expungetype)
   1082 {
   1083 	int error, num, i;
   1084 	daddr_t subblksperindir;
   1085 	struct indir indirs[NIADDR + 2];
   1086 	daddr_t last;
   1087 	void *bap;
   1088 	struct buf *bp;
   1089 
   1090 	if (blkno == 0) {
   1091 		if (expungetype == BLK_NOCOPY)
   1092 			return (0);
   1093 		panic("indiracct: missing indir");
   1094 	}
   1095 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
   1096 		return (error);
   1097 	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
   1098 		panic("indiracct: botched params");
   1099 	/*
   1100 	 * We have to expand bread here since it will deadlock looking
   1101 	 * up the block number for any blocks that are not in the cache.
   1102 	 */
   1103 	error = ffs_getblk(cancelvp, lbn, fsbtodb(fs, blkno), fs->fs_bsize,
   1104 	    false, &bp);
   1105 	if (error)
   1106 		return error;
   1107 	if ((bp->b_oflags & (BO_DONE | BO_DELWRI)) == 0 && (error =
   1108 	    rwfsblk(bp->b_vp, B_READ, bp->b_data, fragstoblks(fs, blkno)))) {
   1109 		brelse(bp, 0);
   1110 		return (error);
   1111 	}
   1112 	/*
   1113 	 * Account for the block pointers in this indirect block.
   1114 	 */
   1115 	last = howmany(remblks, blksperindir);
   1116 	if (last > NINDIR(fs))
   1117 		last = NINDIR(fs);
   1118 	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK | M_ZERO);
   1119 	bcopy(bp->b_data, (void *)bap, fs->fs_bsize);
   1120 	brelse(bp, 0);
   1121 	error = (*acctfunc)(snapvp, bap, 0, last,
   1122 	    fs, level == 0 ? rlbn : -1, expungetype);
   1123 	if (error || level == 0)
   1124 		goto out;
   1125 	/*
   1126 	 * Account for the block pointers in each of the indirect blocks
   1127 	 * in the levels below us.
   1128 	 */
   1129 	subblksperindir = blksperindir / NINDIR(fs);
   1130 	for (lbn++, level--, i = 0; i < last; i++) {
   1131 		error = indiracct(snapvp, cancelvp, level,
   1132 		    idb_get(VTOI(snapvp), bap, i), lbn, rlbn, remblks,
   1133 		    subblksperindir, fs, acctfunc, expungetype);
   1134 		if (error)
   1135 			goto out;
   1136 		rlbn += blksperindir;
   1137 		lbn -= blksperindir;
   1138 		remblks -= blksperindir;
   1139 	}
   1140 out:
   1141 	free(bap, M_DEVBUF);
   1142 	return (error);
   1143 }
   1144 
   1145 /*
   1146  * Do both snap accounting and map accounting.
   1147  */
   1148 static int
   1149 fullacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
   1150     struct fs *fs, daddr_t lblkno,
   1151     int exptype /* BLK_SNAP or BLK_NOCOPY */)
   1152 {
   1153 	int error;
   1154 
   1155 	if ((error = snapacct(vp, bap, oldblkp, lastblkp, fs, lblkno, exptype)))
   1156 		return (error);
   1157 	return (mapacct(vp, bap, oldblkp, lastblkp, fs, lblkno, exptype));
   1158 }
   1159 
   1160 /*
   1161  * Identify a set of blocks allocated in a snapshot inode.
   1162  */
   1163 static int
   1164 snapacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
   1165     struct fs *fs, daddr_t lblkno,
   1166     int expungetype /* BLK_SNAP or BLK_NOCOPY */)
   1167 {
   1168 	struct inode *ip = VTOI(vp);
   1169 	struct lwp *l = curlwp;
   1170 	daddr_t blkno;
   1171 	daddr_t lbn;
   1172 	struct buf *ibp;
   1173 	int error;
   1174 
   1175 	for ( ; oldblkp < lastblkp; oldblkp++) {
   1176 		blkno = idb_get(ip, bap, oldblkp);
   1177 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
   1178 			continue;
   1179 		lbn = fragstoblks(fs, blkno);
   1180 		if (lbn < NDADDR) {
   1181 			blkno = db_get(ip, lbn);
   1182 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
   1183 		} else {
   1184 			error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn),
   1185 			    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
   1186 			if (error)
   1187 				return (error);
   1188 			blkno = idb_get(ip, ibp->b_data,
   1189 			    (lbn - NDADDR) % NINDIR(fs));
   1190 		}
   1191 		/*
   1192 		 * If we are expunging a snapshot vnode and we
   1193 		 * find a block marked BLK_NOCOPY, then it is
   1194 		 * one that has been allocated to this snapshot after
   1195 		 * we took our current snapshot and can be ignored.
   1196 		 */
   1197 		if (expungetype == BLK_SNAP && blkno == BLK_NOCOPY) {
   1198 			if (lbn >= NDADDR)
   1199 				brelse(ibp, 0);
   1200 		} else {
   1201 			if (blkno != 0)
   1202 				panic("snapacct: bad block");
   1203 			if (lbn < NDADDR)
   1204 				db_assign(ip, lbn, expungetype);
   1205 			else {
   1206 				idb_assign(ip, ibp->b_data,
   1207 				    (lbn - NDADDR) % NINDIR(fs), expungetype);
   1208 				bdwrite(ibp);
   1209 			}
   1210 		}
   1211 	}
   1212 	return (0);
   1213 }
   1214 
   1215 /*
   1216  * Account for a set of blocks allocated in a snapshot inode.
   1217  */
   1218 static int
   1219 mapacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
   1220     struct fs *fs, daddr_t lblkno, int expungetype)
   1221 {
   1222 	daddr_t blkno;
   1223 	struct inode *ip;
   1224 	ino_t inum;
   1225 	int acctit;
   1226 
   1227 	ip = VTOI(vp);
   1228 	inum = ip->i_number;
   1229 	if (lblkno == -1)
   1230 		acctit = 0;
   1231 	else
   1232 		acctit = 1;
   1233 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
   1234 		blkno = idb_get(ip, bap, oldblkp);
   1235 		if (blkno == 0 || blkno == BLK_NOCOPY)
   1236 			continue;
   1237 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
   1238 			*ip->i_snapblklist++ = lblkno;
   1239 		if (blkno == BLK_SNAP)
   1240 			blkno = blkstofrags(fs, lblkno);
   1241 		ffs_blkfree_snap(fs, vp, blkno, fs->fs_bsize, inum);
   1242 	}
   1243 	return (0);
   1244 }
   1245 #endif /* defined(FFS_NO_SNAPSHOT) */
   1246 
   1247 /*
   1248  * Decrement extra reference on snapshot when last name is removed.
   1249  * It will not be freed until the last open reference goes away.
   1250  */
   1251 void
   1252 ffs_snapgone(struct inode *ip)
   1253 {
   1254 	struct mount *mp = ip->i_devvp->v_specmountpoint;
   1255 	struct inode *xp;
   1256 	struct fs *fs;
   1257 	struct snap_info *si;
   1258 	int snaploc;
   1259 
   1260 	si = VFSTOUFS(mp)->um_snapinfo;
   1261 
   1262 	/*
   1263 	 * Find snapshot in incore list.
   1264 	 */
   1265 	mutex_enter(&si->si_lock);
   1266 	TAILQ_FOREACH(xp, &si->si_snapshots, i_nextsnap)
   1267 		if (xp == ip)
   1268 			break;
   1269 	mutex_exit(&si->si_lock);
   1270 	if (xp != NULL)
   1271 		vrele(ITOV(ip));
   1272 #ifdef DEBUG
   1273 	else if (snapdebug)
   1274 		printf("ffs_snapgone: lost snapshot vnode %llu\n",
   1275 		    (unsigned long long)ip->i_number);
   1276 #endif
   1277 	/*
   1278 	 * Delete snapshot inode from superblock. Keep list dense.
   1279 	 */
   1280 	mutex_enter(&si->si_lock);
   1281 	fs = ip->i_fs;
   1282 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
   1283 		if (fs->fs_snapinum[snaploc] == ip->i_number)
   1284 			break;
   1285 	if (snaploc < FSMAXSNAP) {
   1286 		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
   1287 			if (fs->fs_snapinum[snaploc] == 0)
   1288 				break;
   1289 			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
   1290 		}
   1291 		fs->fs_snapinum[snaploc - 1] = 0;
   1292 	}
   1293 	si->si_gen++;
   1294 	mutex_exit(&si->si_lock);
   1295 }
   1296 
   1297 /*
   1298  * Prepare a snapshot file for being removed.
   1299  */
   1300 void
   1301 ffs_snapremove(struct vnode *vp)
   1302 {
   1303 	struct inode *ip = VTOI(vp), *xp;
   1304 	struct vnode *devvp = ip->i_devvp;
   1305 	struct fs *fs = ip->i_fs;
   1306 	struct mount *mp = devvp->v_specmountpoint;
   1307 	struct buf *ibp;
   1308 	struct snap_info *si;
   1309 	struct lwp *l = curlwp;
   1310 	daddr_t numblks, blkno, dblk;
   1311 	int error, loc, last;
   1312 
   1313 	si = VFSTOUFS(mp)->um_snapinfo;
   1314 	mutex_enter(&si->si_snaplock);
   1315 	/*
   1316 	 * If active, delete from incore list (this snapshot may
   1317 	 * already have been in the process of being deleted, so
   1318 	 * would not have been active).
   1319 	 *
   1320 	 * Clear copy-on-write flag if last snapshot.
   1321 	 */
   1322 	if (ip->i_nextsnap.tqe_prev != 0) {
   1323 		mutex_enter(&si->si_lock);
   1324 		TAILQ_REMOVE(&si->si_snapshots, ip, i_nextsnap);
   1325 		ip->i_nextsnap.tqe_prev = 0;
   1326 		if (TAILQ_FIRST(&si->si_snapshots) != 0) {
   1327 			/* Roll back the list of preallocated blocks. */
   1328 			xp = TAILQ_LAST(&si->si_snapshots, inodelst);
   1329 			si->si_snapblklist = xp->i_snapblklist;
   1330 		} else {
   1331 			si->si_snapblklist = 0;
   1332 			si->si_gen++;
   1333 			mutex_exit(&si->si_lock);
   1334 			fscow_disestablish(mp, ffs_copyonwrite, devvp);
   1335 			mutex_enter(&si->si_lock);
   1336 		}
   1337 		si->si_gen++;
   1338 		mutex_exit(&si->si_lock);
   1339 		if (ip->i_snapblklist != NULL) {
   1340 			free(ip->i_snapblklist, M_UFSMNT);
   1341 			ip->i_snapblklist = NULL;
   1342 		}
   1343 	}
   1344 	mutex_exit(&si->si_snaplock);
   1345 	/*
   1346 	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
   1347 	 * snapshots that want them (see ffs_snapblkfree below).
   1348 	 */
   1349 	for (blkno = 1; blkno < NDADDR; blkno++) {
   1350 		dblk = db_get(ip, blkno);
   1351 		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
   1352 			db_assign(ip, blkno, 0);
   1353 		else if ((dblk == blkstofrags(fs, blkno) &&
   1354 		     ffs_snapblkfree(fs, ip->i_devvp, dblk, fs->fs_bsize,
   1355 		     ip->i_number))) {
   1356 			DIP_ADD(ip, blocks, -btodb(fs->fs_bsize));
   1357 			db_assign(ip, blkno, 0);
   1358 		}
   1359 	}
   1360 	numblks = howmany(ip->i_size, fs->fs_bsize);
   1361 	for (blkno = NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
   1362 		error = ffs_balloc(vp, lblktosize(fs, (off_t)blkno),
   1363 		    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
   1364 		if (error)
   1365 			continue;
   1366 		if (fs->fs_size - blkno > NINDIR(fs))
   1367 			last = NINDIR(fs);
   1368 		else
   1369 			last = fs->fs_size - blkno;
   1370 		for (loc = 0; loc < last; loc++) {
   1371 			dblk = idb_get(ip, ibp->b_data, loc);
   1372 			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
   1373 				idb_assign(ip, ibp->b_data, loc, 0);
   1374 			else if (dblk == blkstofrags(fs, blkno) &&
   1375 			    ffs_snapblkfree(fs, ip->i_devvp, dblk,
   1376 			    fs->fs_bsize, ip->i_number)) {
   1377 				DIP_ADD(ip, blocks, -btodb(fs->fs_bsize));
   1378 				idb_assign(ip, ibp->b_data, loc, 0);
   1379 			}
   1380 		}
   1381 		bawrite(ibp);
   1382 	}
   1383 	/*
   1384 	 * Clear snapshot flag and drop reference.
   1385 	 */
   1386 	ip->i_flags &= ~SF_SNAPSHOT;
   1387 	DIP_ASSIGN(ip, flags, ip->i_flags);
   1388 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
   1389 }
   1390 
   1391 /*
   1392  * Notification that a block is being freed. Return zero if the free
   1393  * should be allowed to proceed. Return non-zero if the snapshot file
   1394  * wants to claim the block. The block will be claimed if it is an
   1395  * uncopied part of one of the snapshots. It will be freed if it is
   1396  * either a BLK_NOCOPY or has already been copied in all of the snapshots.
   1397  * If a fragment is being freed, then all snapshots that care about
   1398  * it must make a copy since a snapshot file can only claim full sized
   1399  * blocks. Note that if more than one snapshot file maps the block,
   1400  * we can pick one at random to claim it. Since none of the snapshots
   1401  * can change, we are assurred that they will all see the same unmodified
   1402  * image. When deleting a snapshot file (see ffs_snapremove above), we
   1403  * must push any of these claimed blocks to one of the other snapshots
   1404  * that maps it. These claimed blocks are easily identified as they will
   1405  * have a block number equal to their logical block number within the
   1406  * snapshot. A copied block can never have this property because they
   1407  * must always have been allocated from a BLK_NOCOPY location.
   1408  */
   1409 int
   1410 ffs_snapblkfree(struct fs *fs, struct vnode *devvp, daddr_t bno,
   1411     long size, ino_t inum)
   1412 {
   1413 	struct mount *mp = devvp->v_specmountpoint;
   1414 	struct buf *ibp;
   1415 	struct inode *ip;
   1416 	struct vnode *vp = NULL;
   1417 	struct snap_info *si;
   1418 	void *saved_data = NULL;
   1419 	daddr_t lbn;
   1420 	daddr_t blkno;
   1421 	uint32_t gen;
   1422 	int indiroff = 0, snapshot_locked = 0, error = 0, claimedblk = 0;
   1423 
   1424 	si = VFSTOUFS(mp)->um_snapinfo;
   1425 	lbn = fragstoblks(fs, bno);
   1426 	mutex_enter(&si->si_lock);
   1427 retry:
   1428 	gen = si->si_gen;
   1429 	TAILQ_FOREACH(ip, &si->si_snapshots, i_nextsnap) {
   1430 		vp = ITOV(ip);
   1431 		if (snapshot_locked == 0) {
   1432 			if (!mutex_tryenter(&si->si_snaplock)) {
   1433 				mutex_exit(&si->si_lock);
   1434 				mutex_enter(&si->si_snaplock);
   1435 				mutex_enter(&si->si_lock);
   1436 			}
   1437 			snapshot_locked = 1;
   1438 			if (gen != si->si_gen)
   1439 				goto retry;
   1440 		}
   1441 		/*
   1442 		 * Lookup block being written.
   1443 		 */
   1444 		if (lbn < NDADDR) {
   1445 			blkno = db_get(ip, lbn);
   1446 		} else {
   1447 			mutex_exit(&si->si_lock);
   1448 			error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn),
   1449 			    fs->fs_bsize, FSCRED, B_METAONLY, &ibp);
   1450 			if (error) {
   1451 				mutex_enter(&si->si_lock);
   1452 				break;
   1453 			}
   1454 			indiroff = (lbn - NDADDR) % NINDIR(fs);
   1455 			blkno = idb_get(ip, ibp->b_data, indiroff);
   1456 			mutex_enter(&si->si_lock);
   1457 			if (gen != si->si_gen) {
   1458 				brelse(ibp, 0);
   1459 				goto retry;
   1460 			}
   1461 		}
   1462 		/*
   1463 		 * Check to see if block needs to be copied.
   1464 		 */
   1465 		if (blkno == 0) {
   1466 			/*
   1467 			 * A block that we map is being freed. If it has not
   1468 			 * been claimed yet, we will claim or copy it (below).
   1469 			 */
   1470 			claimedblk = 1;
   1471 		} else if (blkno == BLK_SNAP) {
   1472 			/*
   1473 			 * No previous snapshot claimed the block,
   1474 			 * so it will be freed and become a BLK_NOCOPY
   1475 			 * (don't care) for us.
   1476 			 */
   1477 			if (claimedblk)
   1478 				panic("snapblkfree: inconsistent block type");
   1479 			if (lbn < NDADDR) {
   1480 				db_assign(ip, lbn, BLK_NOCOPY);
   1481 				ip->i_flag |= IN_CHANGE | IN_UPDATE;
   1482 			} else {
   1483 				idb_assign(ip, ibp->b_data, indiroff,
   1484 				    BLK_NOCOPY);
   1485 				mutex_exit(&si->si_lock);
   1486 				if (ip->i_nlink > 0)
   1487 					bwrite(ibp);
   1488 				else
   1489 					bdwrite(ibp);
   1490 				mutex_enter(&si->si_lock);
   1491 				if (gen != si->si_gen)
   1492 					goto retry;
   1493 			}
   1494 			continue;
   1495 		} else /* BLK_NOCOPY or default */ {
   1496 			/*
   1497 			 * If the snapshot has already copied the block
   1498 			 * (default), or does not care about the block,
   1499 			 * it is not needed.
   1500 			 */
   1501 			if (lbn >= NDADDR)
   1502 				brelse(ibp, 0);
   1503 			continue;
   1504 		}
   1505 		/*
   1506 		 * If this is a full size block, we will just grab it
   1507 		 * and assign it to the snapshot inode. Otherwise we
   1508 		 * will proceed to copy it. See explanation for this
   1509 		 * routine as to why only a single snapshot needs to
   1510 		 * claim this block.
   1511 		 */
   1512 		if (size == fs->fs_bsize) {
   1513 #ifdef DEBUG
   1514 			if (snapdebug)
   1515 				printf("%s %llu lbn %" PRId64
   1516 				    "from inum %llu\n",
   1517 				    "Grabonremove: snapino",
   1518 				    (unsigned long long)ip->i_number,
   1519 				    lbn, (unsigned long long)inum);
   1520 #endif
   1521 			mutex_exit(&si->si_lock);
   1522 			if (lbn < NDADDR) {
   1523 				db_assign(ip, lbn, bno);
   1524 			} else {
   1525 				idb_assign(ip, ibp->b_data, indiroff, bno);
   1526 				if (ip->i_nlink > 0)
   1527 					bwrite(ibp);
   1528 				else
   1529 					bdwrite(ibp);
   1530 			}
   1531 			DIP_ADD(ip, blocks, btodb(size));
   1532 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
   1533 			if (ip->i_nlink > 0 && mp->mnt_wapbl)
   1534 				error = syncsnap(vp);
   1535 			else
   1536 				error = 0;
   1537 			mutex_exit(&si->si_snaplock);
   1538 			return (error == 0);
   1539 		}
   1540 		if (lbn >= NDADDR)
   1541 			brelse(ibp, 0);
   1542 #ifdef DEBUG
   1543 		if (snapdebug)
   1544 			printf("%s%llu lbn %" PRId64 " %s %llu size %ld\n",
   1545 			    "Copyonremove: snapino ",
   1546 			    (unsigned long long)ip->i_number,
   1547 			    lbn, "for inum", (unsigned long long)inum, size);
   1548 #endif
   1549 		/*
   1550 		 * If we have already read the old block contents, then
   1551 		 * simply copy them to the new block. Note that we need
   1552 		 * to synchronously write snapshots that have not been
   1553 		 * unlinked, and hence will be visible after a crash,
   1554 		 * to ensure their integrity.
   1555 		 */
   1556 		mutex_exit(&si->si_lock);
   1557 		if (saved_data == NULL) {
   1558 			saved_data = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
   1559 			error = rwfsblk(vp, B_READ, saved_data, lbn);
   1560 			if (error) {
   1561 				free(saved_data, M_UFSMNT);
   1562 				saved_data = NULL;
   1563 				mutex_enter(&si->si_lock);
   1564 				break;
   1565 			}
   1566 		}
   1567 		error = wrsnapblk(vp, saved_data, lbn);
   1568 		if (error == 0 && ip->i_nlink > 0 && mp->mnt_wapbl)
   1569 			error = syncsnap(vp);
   1570 		mutex_enter(&si->si_lock);
   1571 		if (error)
   1572 			break;
   1573 		if (gen != si->si_gen)
   1574 			goto retry;
   1575 	}
   1576 	mutex_exit(&si->si_lock);
   1577 	if (saved_data)
   1578 		free(saved_data, M_UFSMNT);
   1579 	/*
   1580 	 * If we have been unable to allocate a block in which to do
   1581 	 * the copy, then return non-zero so that the fragment will
   1582 	 * not be freed. Although space will be lost, the snapshot
   1583 	 * will stay consistent.
   1584 	 */
   1585 	if (snapshot_locked)
   1586 		mutex_exit(&si->si_snaplock);
   1587 	return (error);
   1588 }
   1589 
   1590 /*
   1591  * Associate snapshot files when mounting.
   1592  */
   1593 void
   1594 ffs_snapshot_mount(struct mount *mp)
   1595 {
   1596 	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
   1597 	struct fs *fs = VFSTOUFS(mp)->um_fs;
   1598 	struct lwp *l = curlwp;
   1599 	struct vnode *vp;
   1600 	struct inode *ip, *xp;
   1601 	struct snap_info *si;
   1602 	daddr_t snaplistsize, *snapblklist;
   1603 	int i, error, ns, snaploc, loc;
   1604 
   1605 	/*
   1606 	 * No persistent snapshots on apple ufs file systems.
   1607 	 */
   1608 	if (UFS_MPISAPPLEUFS(VFSTOUFS(mp)))
   1609 		return;
   1610 
   1611 	si = VFSTOUFS(mp)->um_snapinfo;
   1612 	ns = UFS_FSNEEDSWAP(fs);
   1613 	/*
   1614 	 * XXX The following needs to be set before ffs_truncate or
   1615 	 * VOP_READ can be called.
   1616 	 */
   1617 	mp->mnt_stat.f_iosize = fs->fs_bsize;
   1618 	/*
   1619 	 * Process each snapshot listed in the superblock.
   1620 	 */
   1621 	vp = NULL;
   1622 	mutex_enter(&si->si_lock);
   1623 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
   1624 		if (fs->fs_snapinum[snaploc] == 0)
   1625 			break;
   1626 		if ((error = VFS_VGET(mp, fs->fs_snapinum[snaploc],
   1627 		    &vp)) != 0) {
   1628 			printf("ffs_snapshot_mount: vget failed %d\n", error);
   1629 			continue;
   1630 		}
   1631 		ip = VTOI(vp);
   1632 		if ((ip->i_flags & SF_SNAPSHOT) == 0) {
   1633 			printf("ffs_snapshot_mount: non-snapshot inode %d\n",
   1634 			    fs->fs_snapinum[snaploc]);
   1635 			vput(vp);
   1636 			vp = NULL;
   1637 			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
   1638 				if (fs->fs_snapinum[loc] == 0)
   1639 					break;
   1640 				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
   1641 			}
   1642 			fs->fs_snapinum[loc - 1] = 0;
   1643 			snaploc--;
   1644 			continue;
   1645 		}
   1646 
   1647 		/*
   1648 		 * Read the block hints list. Use an empty list on
   1649 		 * read errors.
   1650 		 */
   1651 		error = vn_rdwr(UIO_READ, vp,
   1652 		    (void *)&snaplistsize, sizeof(snaplistsize),
   1653 		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag)),
   1654 		    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT|IO_ALTSEMANTICS,
   1655 		    l->l_cred, NULL, NULL);
   1656 		if (error) {
   1657 			printf("ffs_snapshot_mount: read_1 failed %d\n", error);
   1658 			snaplistsize = 1;
   1659 		} else
   1660 			snaplistsize = ufs_rw64(snaplistsize, ns);
   1661 		snapblklist = malloc(
   1662 		    snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
   1663 		if (error)
   1664 			snapblklist[0] = 1;
   1665 		else {
   1666 			error = vn_rdwr(UIO_READ, vp, (void *)snapblklist,
   1667 			    snaplistsize * sizeof(daddr_t),
   1668 			    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag)),
   1669 			    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT|IO_ALTSEMANTICS,
   1670 			    l->l_cred, NULL, NULL);
   1671 			for (i = 0; i < snaplistsize; i++)
   1672 				snapblklist[i] = ufs_rw64(snapblklist[i], ns);
   1673 			if (error) {
   1674 				printf("ffs_snapshot_mount: read_2 failed %d\n",
   1675 				    error);
   1676 				snapblklist[0] = 1;
   1677 			}
   1678 		}
   1679 		ip->i_snapblklist = &snapblklist[0];
   1680 
   1681 		/*
   1682 		 * Link it onto the active snapshot list.
   1683 		 */
   1684 		if (ip->i_nextsnap.tqe_prev != 0)
   1685 			panic("ffs_snapshot_mount: %llu already on list",
   1686 			    (unsigned long long)ip->i_number);
   1687 		else
   1688 			TAILQ_INSERT_TAIL(&si->si_snapshots, ip, i_nextsnap);
   1689 		vp->v_vflag |= VV_SYSTEM;
   1690 		VOP_UNLOCK(vp, 0);
   1691 	}
   1692 	/*
   1693 	 * No usable snapshots found.
   1694 	 */
   1695 	if (vp == NULL) {
   1696 		mutex_exit(&si->si_lock);
   1697 		return;
   1698 	}
   1699 	/*
   1700 	 * Attach the block hints list. We always want to
   1701 	 * use the list from the newest snapshot.
   1702 	*/
   1703 	xp = TAILQ_LAST(&si->si_snapshots, inodelst);
   1704 	si->si_snapblklist = xp->i_snapblklist;
   1705 	fscow_establish(mp, ffs_copyonwrite, devvp);
   1706 	si->si_gen++;
   1707 	mutex_exit(&si->si_lock);
   1708 }
   1709 
   1710 /*
   1711  * Disassociate snapshot files when unmounting.
   1712  */
   1713 void
   1714 ffs_snapshot_unmount(struct mount *mp)
   1715 {
   1716 	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
   1717 	struct inode *xp;
   1718 	struct vnode *vp = NULL;
   1719 	struct snap_info *si;
   1720 
   1721 	si = VFSTOUFS(mp)->um_snapinfo;
   1722 	mutex_enter(&si->si_lock);
   1723 	while ((xp = TAILQ_FIRST(&si->si_snapshots)) != 0) {
   1724 		vp = ITOV(xp);
   1725 		TAILQ_REMOVE(&si->si_snapshots, xp, i_nextsnap);
   1726 		xp->i_nextsnap.tqe_prev = 0;
   1727 		if (xp->i_snapblklist == si->si_snapblklist)
   1728 			si->si_snapblklist = NULL;
   1729 		free(xp->i_snapblklist, M_UFSMNT);
   1730 		if (xp->i_nlink > 0) {
   1731 			si->si_gen++;
   1732 			mutex_exit(&si->si_lock);
   1733 			vrele(vp);
   1734 			mutex_enter(&si->si_lock);
   1735 		}
   1736 	}
   1737 	if (vp)
   1738 		fscow_disestablish(mp, ffs_copyonwrite, devvp);
   1739 	si->si_gen++;
   1740 	mutex_exit(&si->si_lock);
   1741 }
   1742 
   1743 /*
   1744  * Check for need to copy block that is about to be written,
   1745  * copying the block if necessary.
   1746  */
   1747 static int
   1748 ffs_copyonwrite(void *v, struct buf *bp, bool data_valid)
   1749 {
   1750 	struct fs *fs;
   1751 	struct inode *ip;
   1752 	struct vnode *devvp = v, *vp = NULL;
   1753 	struct mount *mp = devvp->v_specmountpoint;
   1754 	struct snap_info *si;
   1755 	void *saved_data = NULL;
   1756 	daddr_t lbn, blkno, *snapblklist;
   1757 	uint32_t gen;
   1758 	int lower, upper, mid, snapshot_locked = 0, error = 0;
   1759 
   1760 	/*
   1761 	 * Check for valid snapshots.
   1762 	 */
   1763 	si = VFSTOUFS(mp)->um_snapinfo;
   1764 	mutex_enter(&si->si_lock);
   1765 	ip = TAILQ_FIRST(&si->si_snapshots);
   1766 	if (ip == NULL) {
   1767 		mutex_exit(&si->si_lock);
   1768 		return 0;
   1769 	}
   1770 	/*
   1771 	 * First check to see if it is after the file system or
   1772 	 * in the preallocated list.
   1773 	 * By doing this check we avoid several potential deadlocks.
   1774 	 */
   1775 	fs = ip->i_fs;
   1776 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
   1777 	if (bp->b_blkno >= fsbtodb(fs, fs->fs_size)) {
   1778 		mutex_exit(&si->si_lock);
   1779 		return 0;
   1780 	}
   1781 	snapblklist = si->si_snapblklist;
   1782 	upper = (snapblklist != NULL ? snapblklist[0] - 1 : 0);
   1783 	lower = 1;
   1784 	while (lower <= upper) {
   1785 		mid = (lower + upper) / 2;
   1786 		if (snapblklist[mid] == lbn)
   1787 			break;
   1788 		if (snapblklist[mid] < lbn)
   1789 			lower = mid + 1;
   1790 		else
   1791 			upper = mid - 1;
   1792 	}
   1793 	if (lower <= upper) {
   1794 		mutex_exit(&si->si_lock);
   1795 		return 0;
   1796 	}
   1797 	/*
   1798 	 * Not in the precomputed list, so check the snapshots.
   1799 	 */
   1800 	 if (data_valid && bp->b_bcount == fs->fs_bsize)
   1801 		saved_data = bp->b_data;
   1802 retry:
   1803 	gen = si->si_gen;
   1804 	TAILQ_FOREACH(ip, &si->si_snapshots, i_nextsnap) {
   1805 		vp = ITOV(ip);
   1806 		/*
   1807 		 * We ensure that everything of our own that needs to be
   1808 		 * copied will be done at the time that ffs_snapshot is
   1809 		 * called. Thus we can skip the check here which can
   1810 		 * deadlock in doing the lookup in ffs_balloc.
   1811 		 */
   1812 		if (bp->b_vp == vp)
   1813 			continue;
   1814 		/*
   1815 		 * Check to see if block needs to be copied.
   1816 		 */
   1817 		if (lbn < NDADDR) {
   1818 			blkno = db_get(ip, lbn);
   1819 		} else {
   1820 			mutex_exit(&si->si_lock);
   1821 			if ((error = snapblkaddr(vp, lbn, &blkno)) != 0) {
   1822 				mutex_enter(&si->si_lock);
   1823 				break;
   1824 			}
   1825 			mutex_enter(&si->si_lock);
   1826 			if (gen != si->si_gen)
   1827 				goto retry;
   1828 		}
   1829 #ifdef DIAGNOSTIC
   1830 		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
   1831 			panic("ffs_copyonwrite: bad copy block");
   1832 #endif
   1833 		if (blkno != 0)
   1834 			continue;
   1835 
   1836 		if (curlwp == uvm.pagedaemon_lwp) {
   1837 			error = ENOMEM;
   1838 			break;
   1839 		}
   1840 
   1841 		if (snapshot_locked == 0) {
   1842 			if (!mutex_tryenter(&si->si_snaplock)) {
   1843 				mutex_exit(&si->si_lock);
   1844 				mutex_enter(&si->si_snaplock);
   1845 				mutex_enter(&si->si_lock);
   1846 			}
   1847 			snapshot_locked = 1;
   1848 			if (gen != si->si_gen)
   1849 				goto retry;
   1850 
   1851 			/* Check again if block still needs to be copied */
   1852 			if (lbn < NDADDR) {
   1853 				blkno = db_get(ip, lbn);
   1854 			} else {
   1855 				mutex_exit(&si->si_lock);
   1856 				if ((error = snapblkaddr(vp, lbn, &blkno)) != 0) {
   1857 					mutex_enter(&si->si_lock);
   1858 					break;
   1859 				}
   1860 				mutex_enter(&si->si_lock);
   1861 				if (gen != si->si_gen)
   1862 					goto retry;
   1863 			}
   1864 
   1865 			if (blkno != 0)
   1866 				continue;
   1867 		}
   1868 		/*
   1869 		 * Allocate the block into which to do the copy. Since
   1870 		 * multiple processes may all try to copy the same block,
   1871 		 * we have to recheck our need to do a copy if we sleep
   1872 		 * waiting for the lock.
   1873 		 *
   1874 		 * Because all snapshots on a filesystem share a single
   1875 		 * lock, we ensure that we will never be in competition
   1876 		 * with another process to allocate a block.
   1877 		 */
   1878 #ifdef DEBUG
   1879 		if (snapdebug) {
   1880 			printf("Copyonwrite: snapino %llu lbn %" PRId64 " for ",
   1881 			    (unsigned long long)ip->i_number, lbn);
   1882 			if (bp->b_vp == devvp)
   1883 				printf("fs metadata");
   1884 			else
   1885 				printf("inum %llu", (unsigned long long)
   1886 				    VTOI(bp->b_vp)->i_number);
   1887 			printf(" lblkno %" PRId64 "\n", bp->b_lblkno);
   1888 		}
   1889 #endif
   1890 		/*
   1891 		 * If we have already read the old block contents, then
   1892 		 * simply copy them to the new block. Note that we need
   1893 		 * to synchronously write snapshots that have not been
   1894 		 * unlinked, and hence will be visible after a crash,
   1895 		 * to ensure their integrity.
   1896 		 */
   1897 		mutex_exit(&si->si_lock);
   1898 		if (saved_data == NULL) {
   1899 			saved_data = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
   1900 			error = rwfsblk(vp, B_READ, saved_data, lbn);
   1901 			if (error) {
   1902 				free(saved_data, M_UFSMNT);
   1903 				saved_data = NULL;
   1904 				mutex_enter(&si->si_lock);
   1905 				break;
   1906 			}
   1907 		}
   1908 		error = wrsnapblk(vp, saved_data, lbn);
   1909 		if (error == 0 && ip->i_nlink > 0 && mp->mnt_wapbl)
   1910 			error = syncsnap(vp);
   1911 		mutex_enter(&si->si_lock);
   1912 		if (error)
   1913 			break;
   1914 		if (gen != si->si_gen)
   1915 			goto retry;
   1916 	}
   1917 	/*
   1918 	 * Note that we need to synchronously write snapshots that
   1919 	 * have not been unlinked, and hence will be visible after
   1920 	 * a crash, to ensure their integrity.
   1921 	 */
   1922 	mutex_exit(&si->si_lock);
   1923 	if (saved_data && saved_data != bp->b_data)
   1924 		free(saved_data, M_UFSMNT);
   1925 	if (snapshot_locked)
   1926 		mutex_exit(&si->si_snaplock);
   1927 	return error;
   1928 }
   1929 
   1930 /*
   1931  * Read from a snapshot.
   1932  */
   1933 int
   1934 ffs_snapshot_read(struct vnode *vp, struct uio *uio, int ioflag)
   1935 {
   1936 	struct inode *ip = VTOI(vp);
   1937 	struct fs *fs = ip->i_fs;
   1938 	struct snap_info *si = VFSTOUFS(vp->v_mount)->um_snapinfo;
   1939 	struct buf *bp;
   1940 	daddr_t lbn, nextlbn;
   1941 	off_t fsbytes, bytesinfile;
   1942 	long size, xfersize, blkoffset;
   1943 	int error;
   1944 
   1945 	fstrans_start(vp->v_mount, FSTRANS_SHARED);
   1946 	mutex_enter(&si->si_snaplock);
   1947 
   1948 	if (ioflag & IO_ALTSEMANTICS)
   1949 		fsbytes = ip->i_size;
   1950 	else
   1951 		fsbytes = lfragtosize(fs, fs->fs_size);
   1952 	for (error = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
   1953 		bytesinfile = fsbytes - uio->uio_offset;
   1954 		if (bytesinfile <= 0)
   1955 			break;
   1956 		lbn = lblkno(fs, uio->uio_offset);
   1957 		nextlbn = lbn + 1;
   1958 		size = fs->fs_bsize;
   1959 		blkoffset = blkoff(fs, uio->uio_offset);
   1960 		xfersize = MIN(MIN(fs->fs_bsize - blkoffset, uio->uio_resid),
   1961 		    bytesinfile);
   1962 
   1963 		if (lblktosize(fs, nextlbn + 1) >= fsbytes) {
   1964 			if (lblktosize(fs, lbn) + size > fsbytes)
   1965 				size = fragroundup(fs,
   1966 				    fsbytes - lblktosize(fs, lbn));
   1967 			error = bread(vp, lbn, size, NOCRED, 0, &bp);
   1968 		} else {
   1969 			int nextsize = fs->fs_bsize;
   1970 			error = breadn(vp, lbn,
   1971 			    size, &nextlbn, &nextsize, 1, NOCRED, 0, &bp);
   1972 		}
   1973 		if (error)
   1974 			break;
   1975 
   1976 		/*
   1977 		 * We should only get non-zero b_resid when an I/O error
   1978 		 * has occurred, which should cause us to break above.
   1979 		 * However, if the short read did not cause an error,
   1980 		 * then we want to ensure that we do not uiomove bad
   1981 		 * or uninitialized data.
   1982 		 */
   1983 		size -= bp->b_resid;
   1984 		if (size < blkoffset + xfersize) {
   1985 			xfersize = size - blkoffset;
   1986 			if (xfersize <= 0)
   1987 				break;
   1988 		}
   1989 		error = uiomove((char *)bp->b_data + blkoffset, xfersize, uio);
   1990 		if (error)
   1991 			break;
   1992 		brelse(bp, BC_AGE);
   1993 	}
   1994 	if (bp != NULL)
   1995 		brelse(bp, BC_AGE);
   1996 
   1997 	mutex_exit(&si->si_snaplock);
   1998 	fstrans_done(vp->v_mount);
   1999 	return error;
   2000 }
   2001 
   2002 /*
   2003  * Lookup a snapshots data block address.
   2004  * Simpler than UFS_BALLOC() as we know all metadata is already allocated
   2005  * and safe even for the pagedaemon where we cannot bread().
   2006  */
   2007 static int
   2008 snapblkaddr(struct vnode *vp, daddr_t lbn, daddr_t *res)
   2009 {
   2010 	struct indir indirs[NIADDR + 2];
   2011 	struct inode *ip = VTOI(vp);
   2012 	struct fs *fs = ip->i_fs;
   2013 	struct buf *bp;
   2014 	int error, num;
   2015 
   2016 	KASSERT(lbn >= 0);
   2017 
   2018 	if (lbn < NDADDR) {
   2019 		*res = db_get(ip, lbn);
   2020 		return 0;
   2021 	}
   2022 	if ((error = ufs_getlbns(vp, lbn, indirs, &num)) != 0)
   2023 		return error;
   2024 	if (curlwp == uvm.pagedaemon_lwp) {
   2025 		mutex_enter(&bufcache_lock);
   2026 		bp = incore(vp, indirs[num-1].in_lbn);
   2027 		if (bp && (bp->b_oflags & (BO_DONE | BO_DELWRI))) {
   2028 			*res = idb_get(ip, bp->b_data, indirs[num-1].in_off);
   2029 			error = 0;
   2030 		} else
   2031 			error = ENOMEM;
   2032 		mutex_exit(&bufcache_lock);
   2033 		return error;
   2034 	}
   2035 	error = bread(vp, indirs[num-1].in_lbn, fs->fs_bsize, NOCRED, 0, &bp);
   2036 	if (error == 0)
   2037 		*res = idb_get(ip, bp->b_data, indirs[num-1].in_off);
   2038 	brelse(bp, 0);
   2039 
   2040 	return error;
   2041 }
   2042 
   2043 /*
   2044  * Read or write the specified block of the filesystem vp resides on
   2045  * from or to the disk bypassing the buffer cache.
   2046  */
   2047 static int
   2048 rwfsblk(struct vnode *vp, int flags, void *data, daddr_t lbn)
   2049 {
   2050 	int error;
   2051 	struct inode *ip = VTOI(vp);
   2052 	struct fs *fs = ip->i_fs;
   2053 	struct buf *nbp;
   2054 
   2055 	nbp = getiobuf(NULL, true);
   2056 	nbp->b_flags = flags;
   2057 	nbp->b_bcount = nbp->b_bufsize = fs->fs_bsize;
   2058 	nbp->b_error = 0;
   2059 	nbp->b_data = data;
   2060 	nbp->b_blkno = nbp->b_rawblkno = fsbtodb(fs, blkstofrags(fs, lbn));
   2061 	nbp->b_proc = NULL;
   2062 	nbp->b_dev = ip->i_devvp->v_rdev;
   2063 	SET(nbp->b_cflags, BC_BUSY);	/* mark buffer busy */
   2064 
   2065 	bdev_strategy(nbp);
   2066 
   2067 	error = biowait(nbp);
   2068 
   2069 	putiobuf(nbp);
   2070 
   2071 	return error;
   2072 }
   2073 
   2074 /*
   2075  * Write all dirty buffers to disk and invalidate them.
   2076  */
   2077 static int
   2078 syncsnap(struct vnode *vp)
   2079 {
   2080 	int error;
   2081 	buf_t *bp;
   2082 	struct fs *fs = VTOI(vp)->i_fs;
   2083 
   2084 	mutex_enter(&bufcache_lock);
   2085 	while ((bp = LIST_FIRST(&vp->v_dirtyblkhd))) {
   2086 		KASSERT((bp->b_cflags & BC_BUSY) == 0);
   2087 		KASSERT(bp->b_bcount == fs->fs_bsize);
   2088 		bp->b_cflags |= BC_BUSY;
   2089 		mutex_exit(&bufcache_lock);
   2090 		error = rwfsblk(vp, B_WRITE, bp->b_data,
   2091 		    fragstoblks(fs, dbtofsb(fs, bp->b_blkno)));
   2092 		brelse(bp, BC_INVAL | BC_VFLUSH);
   2093 		if (error)
   2094 			return error;
   2095 		mutex_enter(&bufcache_lock);
   2096 	}
   2097 	mutex_exit(&bufcache_lock);
   2098 
   2099 	return 0;
   2100 }
   2101 
   2102 /*
   2103  * Write the specified block to a snapshot.
   2104  */
   2105 static int
   2106 wrsnapblk(struct vnode *vp, void *data, daddr_t lbn)
   2107 {
   2108 	struct inode *ip = VTOI(vp);
   2109 	struct fs *fs = ip->i_fs;
   2110 	struct buf *bp;
   2111 	int error;
   2112 
   2113 	error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
   2114 	    FSCRED, (ip->i_nlink > 0 ? B_SYNC : 0), &bp);
   2115 	if (error)
   2116 		return error;
   2117 	bcopy(data, bp->b_data, fs->fs_bsize);
   2118 	if (ip->i_nlink > 0)
   2119 		error = bwrite(bp);
   2120 	else
   2121 		bawrite(bp);
   2122 
   2123 	return error;
   2124 }
   2125 
   2126 /*
   2127  * Get/Put direct block from inode or buffer containing disk addresses. Take
   2128  * care for fs type (UFS1/UFS2) and byte swapping. These functions should go
   2129  * into a global include.
   2130  */
   2131 static inline daddr_t
   2132 db_get(struct inode *ip, int loc)
   2133 {
   2134 	if (ip->i_ump->um_fstype == UFS1)
   2135 		return ufs_rw32(ip->i_ffs1_db[loc], UFS_IPNEEDSWAP(ip));
   2136 	else
   2137 		return ufs_rw64(ip->i_ffs2_db[loc], UFS_IPNEEDSWAP(ip));
   2138 }
   2139 
   2140 static inline void
   2141 db_assign(struct inode *ip, int loc, daddr_t val)
   2142 {
   2143 	if (ip->i_ump->um_fstype == UFS1)
   2144 		ip->i_ffs1_db[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
   2145 	else
   2146 		ip->i_ffs2_db[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
   2147 }
   2148 
   2149 static inline daddr_t
   2150 ib_get(struct inode *ip, int loc)
   2151 {
   2152 	if (ip->i_ump->um_fstype == UFS1)
   2153 		return ufs_rw32(ip->i_ffs1_ib[loc], UFS_IPNEEDSWAP(ip));
   2154 	else
   2155 		return ufs_rw64(ip->i_ffs2_ib[loc], UFS_IPNEEDSWAP(ip));
   2156 }
   2157 
   2158 static inline void
   2159 ib_assign(struct inode *ip, int loc, daddr_t val)
   2160 {
   2161 	if (ip->i_ump->um_fstype == UFS1)
   2162 		ip->i_ffs1_ib[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
   2163 	else
   2164 		ip->i_ffs2_ib[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
   2165 }
   2166 
   2167 static inline daddr_t
   2168 idb_get(struct inode *ip, void *bf, int loc)
   2169 {
   2170 	if (ip->i_ump->um_fstype == UFS1)
   2171 		return ufs_rw32(((int32_t *)(bf))[loc], UFS_IPNEEDSWAP(ip));
   2172 	else
   2173 		return ufs_rw64(((int64_t *)(bf))[loc], UFS_IPNEEDSWAP(ip));
   2174 }
   2175 
   2176 static inline void
   2177 idb_assign(struct inode *ip, void *bf, int loc, daddr_t val)
   2178 {
   2179 	if (ip->i_ump->um_fstype == UFS1)
   2180 		((int32_t *)(bf))[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
   2181 	else
   2182 		((int64_t *)(bf))[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
   2183 }
   2184