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