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