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