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