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