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