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