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