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