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