xref: /freebsd/sys/ufs/ffs/ffs_snapshot.c (revision cefe58791b0fc5243250b2449107540b03d64689)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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@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 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_quota.h"
42 
43 #include <sys/param.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/conf.h>
47 #include <sys/gsb_crc32.h>
48 #include <sys/bio.h>
49 #include <sys/buf.h>
50 #include <sys/fcntl.h>
51 #include <sys/proc.h>
52 #include <sys/namei.h>
53 #include <sys/sched.h>
54 #include <sys/stat.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/resource.h>
58 #include <sys/resourcevar.h>
59 #include <sys/rwlock.h>
60 #include <sys/vnode.h>
61 
62 #include <vm/vm.h>
63 #include <vm/vm_extern.h>
64 
65 #include <geom/geom.h>
66 #include <geom/geom_vfs.h>
67 
68 #include <ufs/ufs/extattr.h>
69 #include <ufs/ufs/quota.h>
70 #include <ufs/ufs/ufsmount.h>
71 #include <ufs/ufs/inode.h>
72 #include <ufs/ufs/ufs_extern.h>
73 
74 #include <ufs/ffs/fs.h>
75 #include <ufs/ffs/ffs_extern.h>
76 
77 #define KERNCRED thread0.td_ucred
78 
79 #include "opt_ffs.h"
80 
81 #ifdef NO_FFS_SNAPSHOT
82 int
83 ffs_snapshot(struct mount *mp, char *snapfile)
84 {
85 	return (EINVAL);
86 }
87 
88 int
89 ffs_snapblkfree(struct fs *fs,
90 	struct vnode *devvp,
91 	ufs2_daddr_t bno,
92 	long size,
93 	ino_t inum,
94 	enum vtype vtype,
95 	struct workhead *wkhd)
96 {
97 	return (EINVAL);
98 }
99 
100 void
101 ffs_snapremove(struct vnode *vp)
102 {
103 }
104 
105 void
106 ffs_snapshot_mount(struct mount *mp)
107 {
108 }
109 
110 void
111 ffs_snapshot_unmount(struct mount *mp)
112 {
113 }
114 
115 void
116 ffs_snapgone(struct inode *ip)
117 {
118 }
119 
120 int
121 ffs_copyonwrite(struct vnode *devvp, struct buf *bp)
122 {
123 	return (EINVAL);
124 }
125 
126 void
127 ffs_sync_snap(struct mount *mp, int waitfor)
128 {
129 }
130 
131 #else
132 FEATURE(ffs_snapshot, "FFS snapshot support");
133 
134 LIST_HEAD(, snapdata) snapfree;
135 static struct mtx snapfree_lock;
136 MTX_SYSINIT(ffs_snapfree, &snapfree_lock, "snapdata free list", MTX_DEF);
137 
138 static int cgaccount(int, struct vnode *, struct buf *, int);
139 static int expunge_ufs1(struct vnode *, struct inode *, struct fs *,
140     int (*)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *, struct fs *,
141     ufs_lbn_t, int), int, int);
142 static int indiracct_ufs1(struct vnode *, struct vnode *, int,
143     ufs1_daddr_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, struct fs *,
144     int (*)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *, struct fs *,
145     ufs_lbn_t, int), int);
146 static int fullacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
147     struct fs *, ufs_lbn_t, int);
148 static int snapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
149     struct fs *, ufs_lbn_t, int);
150 static int mapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
151     struct fs *, ufs_lbn_t, int);
152 static int expunge_ufs2(struct vnode *, struct inode *, struct fs *,
153     int (*)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *, struct fs *,
154     ufs_lbn_t, int), int, int);
155 static int indiracct_ufs2(struct vnode *, struct vnode *, int,
156     ufs2_daddr_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, struct fs *,
157     int (*)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *, struct fs *,
158     ufs_lbn_t, int), int);
159 static int fullacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
160     struct fs *, ufs_lbn_t, int);
161 static int snapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
162     struct fs *, ufs_lbn_t, int);
163 static int mapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
164     struct fs *, ufs_lbn_t, int);
165 static int readblock(struct vnode *vp, struct buf *, ufs2_daddr_t);
166 static void try_free_snapdata(struct vnode *devvp);
167 static void revert_snaplock(struct vnode *, struct vnode *, struct snapdata *);
168 static struct snapdata *ffs_snapdata_acquire(struct vnode *devvp);
169 static int ffs_bp_snapblk(struct vnode *, struct buf *);
170 
171 /*
172  * To ensure the consistency of snapshots across crashes, we must
173  * synchronously write out copied blocks before allowing the
174  * originals to be modified. Because of the rather severe speed
175  * penalty that this imposes, the code normally only ensures
176  * persistence for the filesystem metadata contained within a
177  * snapshot. Setting the following flag allows this crash
178  * persistence to be enabled for file contents.
179  */
180 int dopersistence = 0;
181 
182 #ifdef DIAGNOSTIC
183 #include <sys/sysctl.h>
184 SYSCTL_INT(_debug, OID_AUTO, dopersistence, CTLFLAG_RW, &dopersistence, 0, "");
185 static int snapdebug = 0;
186 SYSCTL_INT(_debug, OID_AUTO, snapdebug, CTLFLAG_RW, &snapdebug, 0, "");
187 int collectsnapstats = 0;
188 SYSCTL_INT(_debug, OID_AUTO, collectsnapstats, CTLFLAG_RW, &collectsnapstats,
189 	0, "");
190 #endif /* DIAGNOSTIC */
191 
192 /*
193  * Create a snapshot file and initialize it for the filesystem.
194  */
195 int
196 ffs_snapshot(struct mount *mp, char *snapfile)
197 {
198 	ufs2_daddr_t numblks, blkno, *blkp, *snapblklist;
199 	int error, cg, snaploc;
200 	int i, size, len, loc;
201 	ufs2_daddr_t blockno;
202 	uint64_t flag;
203 	char saved_nice = 0;
204 	long redo = 0, snaplistsize = 0;
205 	int32_t *lp;
206 	void *space;
207 	struct fs *copy_fs = NULL, *fs;
208 	struct thread *td = curthread;
209 	struct inode *ip, *xp;
210 	struct buf *bp, *nbp, *ibp;
211 	struct nameidata nd;
212 	struct mount *wrtmp;
213 	struct vattr vat;
214 	struct vnode *vp, *xvp, *mvp, *devvp;
215 	struct uio auio;
216 	struct iovec aiov;
217 	struct snapdata *sn;
218 	struct ufsmount *ump;
219 #ifdef DIAGNOSTIC
220 	struct timespec starttime = {0, 0}, endtime;
221 #endif
222 
223 	ump = VFSTOUFS(mp);
224 	fs = ump->um_fs;
225 	sn = NULL;
226 	/*
227 	 * At the moment, journaled soft updates cannot support
228 	 * taking snapshots.
229 	 */
230 	if (MOUNTEDSUJ(mp)) {
231 		vfs_mount_error(mp, "%s: Snapshots are not yet supported when "
232 		    "running with journaled soft updates", fs->fs_fsmnt);
233 		return (EOPNOTSUPP);
234 	}
235 	MNT_ILOCK(mp);
236 	flag = mp->mnt_flag;
237 	MNT_IUNLOCK(mp);
238 	/*
239 	 * Need to serialize access to snapshot code per filesystem.
240 	 */
241 	/*
242 	 * Assign a snapshot slot in the superblock.
243 	 */
244 	UFS_LOCK(ump);
245 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
246 		if (fs->fs_snapinum[snaploc] == 0)
247 			break;
248 	UFS_UNLOCK(ump);
249 	if (snaploc == FSMAXSNAP)
250 		return (ENOSPC);
251 	/*
252 	 * Create the snapshot file.
253 	 */
254 restart:
255 	NDINIT(&nd, CREATE, LOCKPARENT | LOCKLEAF | NOCACHE, UIO_SYSSPACE,
256 	    snapfile);
257 	if ((error = namei(&nd)) != 0)
258 		return (error);
259 	if (nd.ni_vp != NULL) {
260 		vput(nd.ni_vp);
261 		error = EEXIST;
262 	}
263 	if (nd.ni_dvp->v_mount != mp)
264 		error = EXDEV;
265 	if (error) {
266 		NDFREE_PNBUF(&nd);
267 		if (nd.ni_dvp == nd.ni_vp)
268 			vrele(nd.ni_dvp);
269 		else
270 			vput(nd.ni_dvp);
271 		return (error);
272 	}
273 	VATTR_NULL(&vat);
274 	vat.va_type = VREG;
275 	vat.va_mode = S_IRUSR;
276 	vat.va_vaflags |= VA_EXCLUSIVE;
277 	if (VOP_GETWRITEMOUNT(nd.ni_dvp, &wrtmp))
278 		wrtmp = NULL;
279 	if (wrtmp != mp)
280 		panic("ffs_snapshot: mount mismatch");
281 	vfs_rel(wrtmp);
282 	if (vn_start_write(NULL, &wrtmp, V_NOWAIT) != 0) {
283 		NDFREE_PNBUF(&nd);
284 		vput(nd.ni_dvp);
285 		if ((error = vn_start_write(NULL, &wrtmp,
286 		    V_XSLEEP | PCATCH)) != 0)
287 			return (error);
288 		goto restart;
289 	}
290 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vat);
291 	if (error) {
292 		VOP_VPUT_PAIR(nd.ni_dvp, NULL, true);
293 		NDFREE_PNBUF(&nd);
294 		vn_finished_write(wrtmp);
295 		if (error == ERELOOKUP)
296 			goto restart;
297 		return (error);
298 	}
299 	vp = nd.ni_vp;
300 	vref(nd.ni_dvp);
301 	VOP_VPUT_PAIR(nd.ni_dvp, &vp, false);
302 	if (VN_IS_DOOMED(vp)) {
303 		error = EBADF;
304 		goto out;
305 	}
306 	vnode_create_vobject(nd.ni_vp, fs->fs_size, td);
307 	vp->v_vflag |= VV_SYSTEM;
308 	ip = VTOI(vp);
309 	devvp = ITODEVVP(ip);
310 	/*
311 	 * Calculate the size of the filesystem then allocate the block
312 	 * immediately following the last block of the filesystem that
313 	 * will contain the snapshot list. This operation allows us to
314 	 * set the size of the snapshot.
315 	 */
316 	numblks = howmany(fs->fs_size, fs->fs_frag);
317 	error = UFS_BALLOC(vp, lblktosize(fs, (off_t)numblks),
318 	    fs->fs_bsize, KERNCRED, BA_CLRBUF, &bp);
319 	if (error)
320 		goto out;
321 	bawrite(bp);
322 	ip->i_size = lblktosize(fs, (off_t)(numblks + 1));
323 	vnode_pager_setsize(vp, ip->i_size);
324 	DIP_SET(ip, i_size, ip->i_size);
325 	UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
326 	/*
327 	 * Preallocate critical data structures so that we can copy
328 	 * them in without further allocation after we suspend all
329 	 * operations on the filesystem. We would like to just release
330 	 * the allocated buffers without writing them since they will
331 	 * be filled in below once we are ready to go, but this upsets
332 	 * the soft update code, so we go ahead and write the new buffers.
333 	 *
334 	 * Allocate all indirect blocks and mark all of them as not
335 	 * needing to be copied.
336 	 */
337 	for (blkno = UFS_NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
338 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
339 		    fs->fs_bsize, td->td_ucred, BA_METAONLY, &ibp);
340 		if (error)
341 			goto out;
342 		bawrite(ibp);
343 	}
344 	/*
345 	 * Allocate copies for the superblock and its summary information.
346 	 */
347 	error = UFS_BALLOC(vp, fs->fs_sblockloc, fs->fs_sbsize, KERNCRED,
348 	    0, &nbp);
349 	if (error)
350 		goto out;
351 	bawrite(nbp);
352 	blkno = fragstoblks(fs, fs->fs_csaddr);
353 	len = howmany(fs->fs_cssize, fs->fs_bsize);
354 	for (loc = 0; loc < len; loc++) {
355 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(blkno + loc)),
356 		    fs->fs_bsize, KERNCRED, 0, &nbp);
357 		if (error)
358 			goto out;
359 		bawrite(nbp);
360 	}
361 	/*
362 	 * Allocate all cylinder group blocks.
363 	 */
364 	for (cg = 0; cg < fs->fs_ncg; cg++) {
365 		error = UFS_BALLOC(vp, lfragtosize(fs, cgtod(fs, cg)),
366 		    fs->fs_bsize, KERNCRED, 0, &nbp);
367 		if (error)
368 			goto out;
369 		bawrite(nbp);
370 		if (cg % 10 == 0) {
371 			error = ffs_syncvnode(vp, MNT_WAIT, 0);
372 			/* vp possibly reclaimed if unlocked */
373 			if (error != 0)
374 				goto out;
375 		}
376 	}
377 	/*
378 	 * Copy all the cylinder group maps. Although the
379 	 * filesystem is still active, we hope that only a few
380 	 * cylinder groups will change between now and when we
381 	 * suspend operations. Thus, we will be able to quickly
382 	 * touch up the few cylinder groups that changed during
383 	 * the suspension period.
384 	 */
385 	len = roundup2(howmany(fs->fs_ncg, NBBY), sizeof(int));
386 	space = malloc(len, M_DEVBUF, M_WAITOK | M_ZERO);
387 	UFS_LOCK(ump);
388 	fs->fs_active = space;
389 	UFS_UNLOCK(ump);
390 	for (cg = 0; cg < fs->fs_ncg; cg++) {
391 		error = UFS_BALLOC(vp, lfragtosize(fs, cgtod(fs, cg)),
392 		    fs->fs_bsize, KERNCRED, 0, &nbp);
393 		if (error)
394 			goto out;
395 		error = cgaccount(cg, vp, nbp, 1);
396 		bawrite(nbp);
397 		if (cg % 10 == 0 && error == 0)
398 			error = ffs_syncvnode(vp, MNT_WAIT, 0);
399 		if (error)
400 			goto out;
401 	}
402 	/*
403 	 * Change inode to snapshot type file.
404 	 */
405 	ip->i_flags |= SF_SNAPSHOT;
406 	DIP_SET(ip, i_flags, ip->i_flags);
407 	UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
408 	/*
409 	 * Ensure that the snapshot is completely on disk.
410 	 * Since we have marked it as a snapshot it is safe to
411 	 * unlock it as no process will be allowed to write to it.
412 	 */
413 	if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)) != 0)
414 		goto out;
415 	VOP_UNLOCK(vp);
416 	/*
417 	 * All allocations are done, so we can now snapshot the system.
418 	 *
419 	 * Recind nice scheduling while running with the filesystem suspended.
420 	 */
421 	if (td->td_proc->p_nice > 0) {
422 		struct proc *p;
423 
424 		p = td->td_proc;
425 		PROC_LOCK(p);
426 		saved_nice = p->p_nice;
427 		sched_nice(p, 0);
428 		PROC_UNLOCK(p);
429 	}
430 	/*
431 	 * Suspend operation on filesystem.
432 	 */
433 	for (;;) {
434 		vn_finished_write(wrtmp);
435 		if ((error = vfs_write_suspend(vp->v_mount, 0)) != 0) {
436 			vn_start_write(NULL, &wrtmp, V_WAIT);
437 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
438 			goto out;
439 		}
440 		if (mp->mnt_kern_flag & MNTK_SUSPENDED)
441 			break;
442 		vn_start_write(NULL, &wrtmp, V_WAIT);
443 	}
444 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
445 	if (ip->i_effnlink == 0) {
446 		error = ENOENT;		/* Snapshot file unlinked */
447 		goto resumefs;
448 	}
449 #ifdef DIAGNOSTIC
450 	if (collectsnapstats)
451 		nanotime(&starttime);
452 #endif
453 
454 	/*
455 	 * First, copy all the cylinder group maps that have changed.
456 	 */
457 	for (cg = 0; cg < fs->fs_ncg; cg++) {
458 		if ((ACTIVECGNUM(fs, cg) & ACTIVECGOFF(cg)) != 0)
459 			continue;
460 		redo++;
461 		error = UFS_BALLOC(vp, lfragtosize(fs, cgtod(fs, cg)),
462 		    fs->fs_bsize, KERNCRED, 0, &nbp);
463 		if (error)
464 			goto resumefs;
465 		error = cgaccount(cg, vp, nbp, 2);
466 		bawrite(nbp);
467 		if (error)
468 			goto resumefs;
469 	}
470 	/*
471 	 * Grab a copy of the superblock and its summary information.
472 	 * We delay writing it until the suspension is released below.
473 	 */
474 	copy_fs = malloc((u_long)fs->fs_bsize, M_UFSMNT, M_WAITOK);
475 	bcopy(fs, copy_fs, fs->fs_sbsize);
476 	copy_fs->fs_si = malloc(sizeof(struct fs_summary_info), M_UFSMNT,
477 	    M_ZERO | M_WAITOK);
478 	if ((fs->fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0)
479 		copy_fs->fs_clean = 1;
480 	size = fs->fs_bsize < SBLOCKSIZE ? fs->fs_bsize : SBLOCKSIZE;
481 	if (fs->fs_sbsize < size)
482 		bzero(&((char *)copy_fs)[fs->fs_sbsize],
483 		    size - fs->fs_sbsize);
484 	size = blkroundup(fs, fs->fs_cssize);
485 	if (fs->fs_contigsumsize > 0)
486 		size += fs->fs_ncg * sizeof(int32_t);
487 	space = malloc((u_long)size, M_UFSMNT, M_WAITOK);
488 	copy_fs->fs_csp = space;
489 	bcopy(fs->fs_csp, copy_fs->fs_csp, fs->fs_cssize);
490 	space = (char *)space + fs->fs_cssize;
491 	loc = howmany(fs->fs_cssize, fs->fs_fsize);
492 	i = fs->fs_frag - loc % fs->fs_frag;
493 	len = (i == fs->fs_frag) ? 0 : i * fs->fs_fsize;
494 	if (len > 0) {
495 		if ((error = bread(devvp, fsbtodb(fs, fs->fs_csaddr + loc),
496 		    len, KERNCRED, &bp)) != 0) {
497 			brelse(bp);
498 			goto resumefs;
499 		}
500 		bcopy(bp->b_data, space, (u_int)len);
501 		space = (char *)space + len;
502 		bp->b_flags |= B_INVAL | B_NOCACHE;
503 		brelse(bp);
504 	}
505 	if (fs->fs_contigsumsize > 0) {
506 		copy_fs->fs_maxcluster = lp = space;
507 		for (i = 0; i < fs->fs_ncg; i++)
508 			*lp++ = fs->fs_contigsumsize;
509 	}
510 	/*
511 	 * We must check for active files that have been unlinked
512 	 * (e.g., with a zero link count). We have to expunge all
513 	 * trace of these files from the snapshot so that they are
514 	 * not reclaimed prematurely by fsck or unnecessarily dumped.
515 	 * We turn off the MNTK_SUSPENDED flag to avoid a panic from
516 	 * spec_strategy about writing on a suspended filesystem.
517 	 * Note that we skip unlinked snapshot files as they will
518 	 * be handled separately below.
519 	 *
520 	 * We also calculate the size needed for the snapshot list.
521 	 * Initial number of entries is composed of:
522 	 * - one for each cylinder group map
523 	 * - one for each block used by superblock summary table
524 	 * - one for each snapshot inode block
525 	 * - one for the superblock
526 	 * - one for the snapshot list
527 	 * The direct block entries in the snapshot are always
528 	 * copied (see reason below). Note that the superblock and
529 	 * the first cylinder group will almost always be allocated
530 	 * in the direct blocks, but we add the slop for them in case
531 	 * they do not end up there. The snapshot list size may get
532 	 * expanded by one because of an update of an inode block for
533 	 * an unlinked but still open file when it is expunged.
534 	 *
535 	 * Because the direct block pointers are always copied, they
536 	 * are not added to the list. Instead ffs_copyonwrite()
537 	 * explicitly checks for them before checking the snapshot list.
538 	 */
539 	snaplistsize = fs->fs_ncg + howmany(fs->fs_cssize, fs->fs_bsize) +
540 	    FSMAXSNAP + /* superblock */ 1 + /* snaplist */ 1;
541 	MNT_ILOCK(mp);
542 	mp->mnt_kern_flag &= ~MNTK_SUSPENDED;
543 	MNT_IUNLOCK(mp);
544 loop:
545 	MNT_VNODE_FOREACH_ALL(xvp, mp, mvp) {
546 		if ((xvp->v_usecount == 0 &&
547 		     (xvp->v_iflag & (VI_OWEINACT | VI_DOINGINACT)) == 0) ||
548 		    xvp->v_type == VNON ||
549 		    IS_SNAPSHOT(VTOI(xvp))) {
550 			VI_UNLOCK(xvp);
551 			continue;
552 		}
553 		/*
554 		 * We can skip parent directory vnode because it must have
555 		 * this snapshot file in it.
556 		 */
557 		if (xvp == nd.ni_dvp) {
558 			VI_UNLOCK(xvp);
559 			continue;
560 		}
561 		vholdl(xvp);
562 		if (vn_lock(xvp, LK_EXCLUSIVE | LK_INTERLOCK) != 0) {
563 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
564 			vdrop(xvp);
565 			goto loop;
566 		}
567 		VI_LOCK(xvp);
568 		if (xvp->v_usecount == 0 &&
569 		    (xvp->v_iflag & (VI_OWEINACT | VI_DOINGINACT)) == 0) {
570 			VI_UNLOCK(xvp);
571 			VOP_UNLOCK(xvp);
572 			vdrop(xvp);
573 			continue;
574 		}
575 		VI_UNLOCK(xvp);
576 #ifdef DIAGNOSTIC
577 		if (snapdebug)
578 			vn_printf(xvp, "ffs_snapshot: busy vnode ");
579 #endif
580 		if (VOP_GETATTR(xvp, &vat, td->td_ucred) == 0 &&
581 		    vat.va_nlink > 0) {
582 			VOP_UNLOCK(xvp);
583 			vdrop(xvp);
584 			continue;
585 		}
586 		xp = VTOI(xvp);
587 		if (ffs_checkfreefile(copy_fs, vp, xp->i_number)) {
588 			VOP_UNLOCK(xvp);
589 			vdrop(xvp);
590 			continue;
591 		}
592 		/*
593 		 * If there is a fragment, clear it here.
594 		 */
595 		blkno = 0;
596 		loc = howmany(xp->i_size, fs->fs_bsize) - 1;
597 		if (loc < UFS_NDADDR) {
598 			len = fragroundup(fs, blkoff(fs, xp->i_size));
599 			if (len != 0 && len < fs->fs_bsize) {
600 				ffs_blkfree(ump, copy_fs, vp,
601 				    DIP(xp, i_db[loc]), len, xp->i_number,
602 				    xvp->v_type, NULL, SINGLETON_KEY);
603 				blkno = DIP(xp, i_db[loc]);
604 				DIP_SET(xp, i_db[loc], 0);
605 			}
606 		}
607 		snaplistsize += 1;
608 		if (I_IS_UFS1(xp))
609 			error = expunge_ufs1(vp, xp, copy_fs, fullacct_ufs1,
610 			    BLK_NOCOPY, 1);
611 		else
612 			error = expunge_ufs2(vp, xp, copy_fs, fullacct_ufs2,
613 			    BLK_NOCOPY, 1);
614 		if (blkno)
615 			DIP_SET(xp, i_db[loc], blkno);
616 		if (!error)
617 			error = ffs_freefile(ump, copy_fs, vp, xp->i_number,
618 			    xp->i_mode, NULL);
619 		VOP_UNLOCK(xvp);
620 		vdrop(xvp);
621 		if (error) {
622 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
623 			goto resumefs;
624 		}
625 	}
626 	/*
627 	 * Erase the journal file from the snapshot.
628 	 */
629 	if (fs->fs_flags & FS_SUJ) {
630 		error = softdep_journal_lookup(mp, &xvp);
631 		if (error)
632 			goto resumefs;
633 		xp = VTOI(xvp);
634 		if (I_IS_UFS1(xp))
635 			error = expunge_ufs1(vp, xp, copy_fs, fullacct_ufs1,
636 			    BLK_NOCOPY, 0);
637 		else
638 			error = expunge_ufs2(vp, xp, copy_fs, fullacct_ufs2,
639 			    BLK_NOCOPY, 0);
640 		vput(xvp);
641 	}
642 	/*
643 	 * Preallocate all the direct blocks in the snapshot inode so
644 	 * that we never have to write the inode itself to commit an
645 	 * update to the contents of the snapshot. Note that once
646 	 * created, the size of the snapshot will never change, so
647 	 * there will never be a need to write the inode except to
648 	 * update the non-integrity-critical time fields and
649 	 * allocated-block count.
650 	 */
651 	for (blockno = 0; blockno < UFS_NDADDR; blockno++) {
652 		if (DIP(ip, i_db[blockno]) != 0)
653 			continue;
654 		error = UFS_BALLOC(vp, lblktosize(fs, blockno),
655 		    fs->fs_bsize, KERNCRED, BA_CLRBUF, &bp);
656 		if (error)
657 			goto resumefs;
658 		error = readblock(vp, bp, blockno);
659 		bawrite(bp);
660 		if (error != 0)
661 			goto resumefs;
662 	}
663 	/*
664 	 * Acquire a lock on the snapdata structure, creating it if necessary.
665 	 */
666 	sn = ffs_snapdata_acquire(devvp);
667 	/*
668 	 * Change vnode to use shared snapshot lock instead of the original
669 	 * private lock.
670 	 */
671 	vp->v_vnlock = &sn->sn_lock;
672 	lockmgr(&vp->v_lock, LK_RELEASE, NULL);
673 	xp = TAILQ_FIRST(&sn->sn_head);
674 	/*
675 	 * If this is the first snapshot on this filesystem, then we need
676 	 * to allocate the space for the list of preallocated snapshot blocks.
677 	 * This list will be refined below, but this preliminary one will
678 	 * keep us out of deadlock until the full one is ready.
679 	 */
680 	if (xp == NULL) {
681 		snapblklist = malloc(snaplistsize * sizeof(daddr_t),
682 		    M_UFSMNT, M_WAITOK);
683 		blkp = &snapblklist[1];
684 		*blkp++ = lblkno(fs, fs->fs_sblockloc);
685 		blkno = fragstoblks(fs, fs->fs_csaddr);
686 		for (cg = 0; cg < fs->fs_ncg; cg++) {
687 			if (fragstoblks(fs, cgtod(fs, cg) > blkno))
688 				break;
689 			*blkp++ = fragstoblks(fs, cgtod(fs, cg));
690 		}
691 		len = howmany(fs->fs_cssize, fs->fs_bsize);
692 		for (loc = 0; loc < len; loc++)
693 			*blkp++ = blkno + loc;
694 		for (; cg < fs->fs_ncg; cg++)
695 			*blkp++ = fragstoblks(fs, cgtod(fs, cg));
696 		snapblklist[0] = blkp - snapblklist;
697 		VI_LOCK(devvp);
698 		if (sn->sn_blklist != NULL)
699 			panic("ffs_snapshot: non-empty list");
700 		sn->sn_blklist = snapblklist;
701 		sn->sn_listsize = blkp - snapblklist;
702 		VI_UNLOCK(devvp);
703 	}
704 	/*
705 	 * Record snapshot inode. Since this is the newest snapshot,
706 	 * it must be placed at the end of the list.
707 	 */
708 	VI_LOCK(devvp);
709 	fs->fs_snapinum[snaploc] = ip->i_number;
710 	if (ip->i_nextsnap.tqe_prev != 0)
711 		panic("ffs_snapshot: %ju already on list",
712 		    (uintmax_t)ip->i_number);
713 	TAILQ_INSERT_TAIL(&sn->sn_head, ip, i_nextsnap);
714 	devvp->v_vflag |= VV_COPYONWRITE;
715 	VI_UNLOCK(devvp);
716 resumefs:
717 	ASSERT_VOP_LOCKED(vp, "ffs_snapshot vp");
718 	if (error != 0 && copy_fs != NULL) {
719 		free(copy_fs->fs_csp, M_UFSMNT);
720 		free(copy_fs->fs_si, M_UFSMNT);
721 		free(copy_fs, M_UFSMNT);
722 		copy_fs = NULL;
723 	}
724 	KASSERT(error != 0 || (sn != NULL && copy_fs != NULL),
725 		("missing snapshot setup parameters"));
726 	/*
727 	 * Resume operation on filesystem.
728 	 */
729 	vfs_write_resume(vp->v_mount, VR_START_WRITE | VR_NO_SUSPCLR);
730 #ifdef DIAGNOSTIC
731 	if (collectsnapstats && starttime.tv_sec > 0) {
732 		nanotime(&endtime);
733 		timespecsub(&endtime, &starttime, &endtime);
734 		printf("%s: suspended %ld.%03ld sec, redo %ld of %d\n",
735 		    vp->v_mount->mnt_stat.f_mntonname, (long)endtime.tv_sec,
736 		    endtime.tv_nsec / 1000000, redo, fs->fs_ncg);
737 	}
738 #endif
739 	if (copy_fs == NULL)
740 		goto out;
741 	/*
742 	 * Copy allocation information from all the snapshots in
743 	 * this snapshot and then expunge them from its view.
744 	 */
745 	TAILQ_FOREACH(xp, &sn->sn_head, i_nextsnap) {
746 		if (xp == ip)
747 			break;
748 		if (I_IS_UFS1(xp))
749 			error = expunge_ufs1(vp, xp, fs, snapacct_ufs1,
750 			    BLK_SNAP, 0);
751 		else
752 			error = expunge_ufs2(vp, xp, fs, snapacct_ufs2,
753 			    BLK_SNAP, 0);
754 		if (error == 0 && xp->i_effnlink == 0) {
755 			error = ffs_freefile(ump,
756 					     copy_fs,
757 					     vp,
758 					     xp->i_number,
759 					     xp->i_mode, NULL);
760 		}
761 		if (error) {
762 			fs->fs_snapinum[snaploc] = 0;
763 			goto done;
764 		}
765 	}
766 	/*
767 	 * Allocate space for the full list of preallocated snapshot blocks.
768 	 */
769 	snapblklist = malloc(snaplistsize * sizeof(daddr_t),
770 	    M_UFSMNT, M_WAITOK);
771 	ip->i_snapblklist = &snapblklist[1];
772 	/*
773 	 * Expunge the blocks used by the snapshots from the set of
774 	 * blocks marked as used in the snapshot bitmaps. Also, collect
775 	 * the list of allocated blocks in i_snapblklist.
776 	 */
777 	if (I_IS_UFS1(ip))
778 		error = expunge_ufs1(vp, ip, copy_fs, mapacct_ufs1,
779 		    BLK_SNAP, 0);
780 	else
781 		error = expunge_ufs2(vp, ip, copy_fs, mapacct_ufs2,
782 		    BLK_SNAP, 0);
783 	if (error) {
784 		fs->fs_snapinum[snaploc] = 0;
785 		free(snapblklist, M_UFSMNT);
786 		goto done;
787 	}
788 	if (snaplistsize < ip->i_snapblklist - snapblklist)
789 		panic("ffs_snapshot: list too small");
790 	snaplistsize = ip->i_snapblklist - snapblklist;
791 	snapblklist[0] = snaplistsize;
792 	ip->i_snapblklist = 0;
793 	/*
794 	 * Write out the list of allocated blocks to the end of the snapshot.
795 	 */
796 	auio.uio_iov = &aiov;
797 	auio.uio_iovcnt = 1;
798 	aiov.iov_base = (void *)snapblklist;
799 	aiov.iov_len = snaplistsize * sizeof(daddr_t);
800 	auio.uio_resid = aiov.iov_len;
801 	auio.uio_offset = lblktosize(fs, (off_t)numblks);
802 	auio.uio_segflg = UIO_SYSSPACE;
803 	auio.uio_rw = UIO_WRITE;
804 	auio.uio_td = td;
805 	if ((error = VOP_WRITE(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
806 		fs->fs_snapinum[snaploc] = 0;
807 		free(snapblklist, M_UFSMNT);
808 		goto done;
809 	}
810 	/*
811 	 * Write the superblock and its summary information
812 	 * to the snapshot.
813 	 */
814 	blkno = fragstoblks(fs, fs->fs_csaddr);
815 	len = howmany(fs->fs_cssize, fs->fs_bsize);
816 	space = copy_fs->fs_csp;
817 	for (loc = 0; loc < len; loc++) {
818 		error = bread(vp, blkno + loc, fs->fs_bsize, KERNCRED, &nbp);
819 		if (error) {
820 			fs->fs_snapinum[snaploc] = 0;
821 			free(snapblklist, M_UFSMNT);
822 			goto done;
823 		}
824 		bcopy(space, nbp->b_data, fs->fs_bsize);
825 		space = (char *)space + fs->fs_bsize;
826 		bawrite(nbp);
827 	}
828 	error = bread(vp, lblkno(fs, fs->fs_sblockloc), fs->fs_bsize,
829 	    KERNCRED, &nbp);
830 	if (error) {
831 		brelse(nbp);
832 	} else {
833 		loc = blkoff(fs, fs->fs_sblockloc);
834 		copy_fs->fs_fmod = 0;
835 		copy_fs->fs_ckhash = ffs_calc_sbhash(copy_fs);
836 		bcopy((char *)copy_fs, &nbp->b_data[loc], (u_int)fs->fs_sbsize);
837 		bawrite(nbp);
838 	}
839 	/*
840 	 * As this is the newest list, it is the most inclusive, so
841 	 * should replace the previous list.
842 	 */
843 	VI_LOCK(devvp);
844 	space = sn->sn_blklist;
845 	sn->sn_blklist = snapblklist;
846 	sn->sn_listsize = snaplistsize;
847 	VI_UNLOCK(devvp);
848 	if (space != NULL)
849 		free(space, M_UFSMNT);
850 done:
851 	free(copy_fs->fs_csp, M_UFSMNT);
852 	free(copy_fs->fs_si, M_UFSMNT);
853 	free(copy_fs, M_UFSMNT);
854 	copy_fs = NULL;
855 out:
856 	NDFREE_PNBUF(&nd);
857 	if (saved_nice > 0) {
858 		struct proc *p;
859 
860 		p = td->td_proc;
861 		PROC_LOCK(p);
862 		sched_nice(td->td_proc, saved_nice);
863 		PROC_UNLOCK(td->td_proc);
864 	}
865 	UFS_LOCK(ump);
866 	if (fs->fs_active != 0) {
867 		free(fs->fs_active, M_DEVBUF);
868 		fs->fs_active = 0;
869 	}
870 	UFS_UNLOCK(ump);
871 	MNT_ILOCK(mp);
872 	mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
873 	MNT_IUNLOCK(mp);
874 	if (error)
875 		(void) ffs_truncate(vp, (off_t)0, 0, NOCRED);
876 	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
877 	if (error)
878 		vput(vp);
879 	else
880 		VOP_UNLOCK(vp);
881 	vrele(nd.ni_dvp);
882 	vn_finished_write(wrtmp);
883 	process_deferred_inactive(mp);
884 	return (error);
885 }
886 
887 /*
888  * Copy a cylinder group map. All the unallocated blocks are marked
889  * BLK_NOCOPY so that the snapshot knows that it need not copy them
890  * if they are later written. If passno is one, then this is a first
891  * pass, so only setting needs to be done. If passno is 2, then this
892  * is a revision to a previous pass which must be undone as the
893  * replacement pass is done.
894  */
895 static int
896 cgaccount(int cg,
897 	struct vnode *vp,
898 	struct buf *nbp,
899 	int passno)
900 {
901 	struct buf *bp, *ibp;
902 	struct inode *ip;
903 	struct cg *cgp;
904 	struct fs *fs;
905 	ufs2_daddr_t base, numblks;
906 	int error, len, loc, indiroff;
907 
908 	ip = VTOI(vp);
909 	fs = ITOFS(ip);
910 	if ((error = ffs_getcg(fs, ITODEVVP(ip), cg, 0, &bp, &cgp)) != 0)
911 		return (error);
912 	UFS_LOCK(ITOUMP(ip));
913 	ACTIVESET(fs, cg);
914 	/*
915 	 * Recomputation of summary information might not have been performed
916 	 * at mount time.  Sync up summary information for current cylinder
917 	 * group while data is in memory to ensure that result of background
918 	 * fsck is slightly more consistent.
919 	 */
920 	fs->fs_cs(fs, cg) = cgp->cg_cs;
921 	UFS_UNLOCK(ITOUMP(ip));
922 	bcopy(bp->b_data, nbp->b_data, fs->fs_cgsize);
923 	if (fs->fs_cgsize < fs->fs_bsize)
924 		bzero(&nbp->b_data[fs->fs_cgsize],
925 		    fs->fs_bsize - fs->fs_cgsize);
926 	cgp = (struct cg *)nbp->b_data;
927 	bqrelse(bp);
928 	if (passno == 2)
929 		nbp->b_flags |= B_VALIDSUSPWRT;
930 	numblks = howmany(fs->fs_size, fs->fs_frag);
931 	len = howmany(fs->fs_fpg, fs->fs_frag);
932 	base = cgbase(fs, cg) / fs->fs_frag;
933 	if (base + len >= numblks)
934 		len = numblks - base - 1;
935 	loc = 0;
936 	if (base < UFS_NDADDR) {
937 		for ( ; loc < UFS_NDADDR; loc++) {
938 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
939 				DIP_SET(ip, i_db[loc], BLK_NOCOPY);
940 			else if (passno == 2 && DIP(ip, i_db[loc])== BLK_NOCOPY)
941 				DIP_SET(ip, i_db[loc], 0);
942 			else if (passno == 1 && DIP(ip, i_db[loc])== BLK_NOCOPY)
943 				panic("ffs_snapshot: lost direct block");
944 		}
945 	}
946 	error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(base + loc)),
947 	    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
948 	if (error) {
949 		goto out;
950 	}
951 	indiroff = (base + loc - UFS_NDADDR) % NINDIR(fs);
952 	for ( ; loc < len; loc++, indiroff++) {
953 		if (indiroff >= NINDIR(fs)) {
954 			if (passno == 2)
955 				ibp->b_flags |= B_VALIDSUSPWRT;
956 			bawrite(ibp);
957 			error = UFS_BALLOC(vp,
958 			    lblktosize(fs, (off_t)(base + loc)),
959 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
960 			if (error) {
961 				goto out;
962 			}
963 			indiroff = 0;
964 		}
965 		if (I_IS_UFS1(ip)) {
966 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
967 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
968 				    BLK_NOCOPY;
969 			else if (passno == 2 && ((ufs1_daddr_t *)(ibp->b_data))
970 			    [indiroff] == BLK_NOCOPY)
971 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = 0;
972 			else if (passno == 1 && ((ufs1_daddr_t *)(ibp->b_data))
973 			    [indiroff] == BLK_NOCOPY)
974 				panic("ffs_snapshot: lost indirect block");
975 			continue;
976 		}
977 		if (ffs_isblock(fs, cg_blksfree(cgp), loc))
978 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = BLK_NOCOPY;
979 		else if (passno == 2 &&
980 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
981 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = 0;
982 		else if (passno == 1 &&
983 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
984 			panic("ffs_snapshot: lost indirect block");
985 	}
986 	if (passno == 2)
987 		ibp->b_flags |= B_VALIDSUSPWRT;
988 	bdwrite(ibp);
989 out:
990 	/*
991 	 * We have to calculate the crc32c here rather than just setting the
992 	 * BX_CYLGRP b_xflags because the allocation of the block for the
993 	 * the cylinder group map will always be a full size block (fs_bsize)
994 	 * even though the cylinder group may be smaller (fs_cgsize). The
995 	 * crc32c must be computed only over fs_cgsize whereas the BX_CYLGRP
996 	 * flag causes it to be computed over the size of the buffer.
997 	 */
998 	if ((fs->fs_metackhash & CK_CYLGRP) != 0) {
999 		((struct cg *)nbp->b_data)->cg_ckhash = 0;
1000 		((struct cg *)nbp->b_data)->cg_ckhash =
1001 		    calculate_crc32c(~0L, nbp->b_data, fs->fs_cgsize);
1002 	}
1003 	return (error);
1004 }
1005 
1006 /*
1007  * Before expunging a snapshot inode, note all the
1008  * blocks that it claims with BLK_SNAP so that fsck will
1009  * be able to account for those blocks properly and so
1010  * that this snapshot knows that it need not copy them
1011  * if the other snapshot holding them is freed. This code
1012  * is reproduced once each for UFS1 and UFS2.
1013  */
1014 static int
1015 expunge_ufs1(struct vnode *snapvp,
1016 	struct inode *cancelip,
1017 	struct fs *fs,
1018 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
1019 	    struct fs *, ufs_lbn_t, int),
1020 	int expungetype,
1021 	int clearmode)
1022 {
1023 	int i, error, indiroff;
1024 	ufs_lbn_t lbn, rlbn;
1025 	ufs2_daddr_t len, blkno, numblks, blksperindir;
1026 	struct ufs1_dinode *dip;
1027 	struct thread *td = curthread;
1028 	struct buf *bp;
1029 
1030 	/*
1031 	 * Prepare to expunge the inode. If its inode block has not
1032 	 * yet been copied, then allocate and fill the copy.
1033 	 */
1034 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1035 	blkno = 0;
1036 	if (lbn < UFS_NDADDR) {
1037 		blkno = VTOI(snapvp)->i_din1->di_db[lbn];
1038 	} else {
1039 		if (DOINGSOFTDEP(snapvp))
1040 			softdep_prealloc(snapvp, MNT_WAIT);
1041 		td->td_pflags |= TDP_COWINPROGRESS;
1042 		error = ffs_balloc_ufs1(snapvp, lblktosize(fs, (off_t)lbn),
1043 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1044 		td->td_pflags &= ~TDP_COWINPROGRESS;
1045 		if (error)
1046 			return (error);
1047 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1048 		blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
1049 		bqrelse(bp);
1050 	}
1051 	if (blkno != 0) {
1052 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1053 			return (error);
1054 	} else {
1055 		error = ffs_balloc_ufs1(snapvp, lblktosize(fs, (off_t)lbn),
1056 		    fs->fs_bsize, KERNCRED, 0, &bp);
1057 		if (error)
1058 			return (error);
1059 		if ((error = readblock(snapvp, bp, lbn)) != 0)
1060 			return (error);
1061 	}
1062 	/*
1063 	 * Set a snapshot inode to be a zero length file, regular files
1064 	 * or unlinked snapshots to be completely unallocated.
1065 	 */
1066 	dip = (struct ufs1_dinode *)bp->b_data +
1067 	    ino_to_fsbo(fs, cancelip->i_number);
1068 	if (clearmode || cancelip->i_effnlink == 0)
1069 		dip->di_mode = 0;
1070 	dip->di_size = 0;
1071 	dip->di_blocks = 0;
1072 	dip->di_flags &= ~SF_SNAPSHOT;
1073 	bzero(dip->di_db, UFS_NDADDR * sizeof(ufs1_daddr_t));
1074 	bzero(dip->di_ib, UFS_NIADDR * sizeof(ufs1_daddr_t));
1075 	bdwrite(bp);
1076 	/*
1077 	 * Now go through and expunge all the blocks in the file
1078 	 * using the function requested.
1079 	 */
1080 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1081 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_db[0],
1082 	    &cancelip->i_din1->di_db[UFS_NDADDR], fs, 0, expungetype)))
1083 		return (error);
1084 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_ib[0],
1085 	    &cancelip->i_din1->di_ib[UFS_NIADDR], fs, -1, expungetype)))
1086 		return (error);
1087 	blksperindir = 1;
1088 	lbn = -UFS_NDADDR;
1089 	len = numblks - UFS_NDADDR;
1090 	rlbn = UFS_NDADDR;
1091 	for (i = 0; len > 0 && i < UFS_NIADDR; i++) {
1092 		error = indiracct_ufs1(snapvp, ITOV(cancelip), i,
1093 		    cancelip->i_din1->di_ib[i], lbn, rlbn, len,
1094 		    blksperindir, fs, acctfunc, expungetype);
1095 		if (error)
1096 			return (error);
1097 		blksperindir *= NINDIR(fs);
1098 		lbn -= blksperindir + 1;
1099 		len -= blksperindir;
1100 		rlbn += blksperindir;
1101 	}
1102 	return (0);
1103 }
1104 
1105 /*
1106  * Descend an indirect block chain for vnode cancelvp accounting for all
1107  * its indirect blocks in snapvp.
1108  */
1109 static int
1110 indiracct_ufs1(struct vnode *snapvp,
1111 	struct vnode *cancelvp,
1112 	int level,
1113 	ufs1_daddr_t blkno,
1114 	ufs_lbn_t lbn,
1115 	ufs_lbn_t rlbn,
1116 	ufs_lbn_t remblks,
1117 	ufs_lbn_t blksperindir,
1118 	struct fs *fs,
1119 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
1120 	    struct fs *, ufs_lbn_t, int),
1121 	int expungetype)
1122 {
1123 	int error, num, i;
1124 	ufs_lbn_t subblksperindir;
1125 	struct indir indirs[UFS_NIADDR + 2];
1126 	ufs1_daddr_t last, *bap;
1127 	struct buf *bp;
1128 
1129 	if (blkno == 0) {
1130 		if (expungetype == BLK_NOCOPY)
1131 			return (0);
1132 		panic("indiracct_ufs1: missing indir");
1133 	}
1134 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1135 		return (error);
1136 	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
1137 		panic("indiracct_ufs1: botched params");
1138 	/*
1139 	 * We have to expand bread here since it will deadlock looking
1140 	 * up the block number for any blocks that are not in the cache.
1141 	 */
1142 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0, 0);
1143 	bp->b_blkno = fsbtodb(fs, blkno);
1144 	if ((bp->b_flags & (B_DONE | B_DELWRI)) == 0 &&
1145 	    (error = readblock(cancelvp, bp, fragstoblks(fs, blkno)))) {
1146 		brelse(bp);
1147 		return (error);
1148 	}
1149 	/*
1150 	 * Account for the block pointers in this indirect block.
1151 	 */
1152 	last = howmany(remblks, blksperindir);
1153 	if (last > NINDIR(fs))
1154 		last = NINDIR(fs);
1155 	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK);
1156 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1157 	bqrelse(bp);
1158 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1159 	    level == 0 ? rlbn : -1, expungetype);
1160 	if (error || level == 0)
1161 		goto out;
1162 	/*
1163 	 * Account for the block pointers in each of the indirect blocks
1164 	 * in the levels below us.
1165 	 */
1166 	subblksperindir = blksperindir / NINDIR(fs);
1167 	for (lbn++, level--, i = 0; i < last; i++) {
1168 		error = indiracct_ufs1(snapvp, cancelvp, level, bap[i], lbn,
1169 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1170 		if (error)
1171 			goto out;
1172 		rlbn += blksperindir;
1173 		lbn -= blksperindir;
1174 		remblks -= blksperindir;
1175 	}
1176 out:
1177 	free(bap, M_DEVBUF);
1178 	return (error);
1179 }
1180 
1181 /*
1182  * Do both snap accounting and map accounting.
1183  */
1184 static int
1185 fullacct_ufs1(struct vnode *vp,
1186 	ufs1_daddr_t *oldblkp,
1187 	ufs1_daddr_t *lastblkp,
1188 	struct fs *fs,
1189 	ufs_lbn_t lblkno,
1190 	int exptype)	/* BLK_SNAP or BLK_NOCOPY */
1191 {
1192 	int error;
1193 
1194 	if ((error = snapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1195 		return (error);
1196 	return (mapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1197 }
1198 
1199 /*
1200  * Identify a set of blocks allocated in a snapshot inode.
1201  */
1202 static int
1203 snapacct_ufs1(struct vnode *vp,
1204 	ufs1_daddr_t *oldblkp,
1205 	ufs1_daddr_t *lastblkp,
1206 	struct fs *fs,
1207 	ufs_lbn_t lblkno,
1208 	int expungetype)	/* BLK_SNAP or BLK_NOCOPY */
1209 {
1210 	struct inode *ip = VTOI(vp);
1211 	ufs1_daddr_t blkno, *blkp;
1212 	ufs_lbn_t lbn;
1213 	struct buf *ibp;
1214 	int error;
1215 
1216 	for ( ; oldblkp < lastblkp; oldblkp++) {
1217 		blkno = *oldblkp;
1218 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1219 			continue;
1220 		lbn = fragstoblks(fs, blkno);
1221 		if (lbn < UFS_NDADDR) {
1222 			blkp = &ip->i_din1->di_db[lbn];
1223 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1224 		} else {
1225 			error = ffs_balloc_ufs1(vp, lblktosize(fs, (off_t)lbn),
1226 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1227 			if (error)
1228 				return (error);
1229 			blkp = &((ufs1_daddr_t *)(ibp->b_data))
1230 			    [(lbn - UFS_NDADDR) % NINDIR(fs)];
1231 		}
1232 		/*
1233 		 * If we are expunging a snapshot vnode and we
1234 		 * find a block marked BLK_NOCOPY, then it is
1235 		 * one that has been allocated to this snapshot after
1236 		 * we took our current snapshot and can be ignored.
1237 		 */
1238 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1239 			if (lbn >= UFS_NDADDR)
1240 				brelse(ibp);
1241 		} else {
1242 			if (*blkp != 0)
1243 				panic("snapacct_ufs1: bad block");
1244 			*blkp = expungetype;
1245 			if (lbn >= UFS_NDADDR)
1246 				bdwrite(ibp);
1247 		}
1248 	}
1249 	return (0);
1250 }
1251 
1252 /*
1253  * Account for a set of blocks allocated in a snapshot inode.
1254  */
1255 static int
1256 mapacct_ufs1(struct vnode *vp,
1257 	ufs1_daddr_t *oldblkp,
1258 	ufs1_daddr_t *lastblkp,
1259 	struct fs *fs,
1260 	ufs_lbn_t lblkno,
1261 	int expungetype)
1262 {
1263 	ufs1_daddr_t blkno;
1264 	struct inode *ip;
1265 	ino_t inum;
1266 	int acctit;
1267 
1268 	ip = VTOI(vp);
1269 	inum = ip->i_number;
1270 	if (lblkno == -1)
1271 		acctit = 0;
1272 	else
1273 		acctit = 1;
1274 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1275 		blkno = *oldblkp;
1276 		if (blkno == 0 || blkno == BLK_NOCOPY)
1277 			continue;
1278 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
1279 			*ip->i_snapblklist++ = lblkno;
1280 		if (blkno == BLK_SNAP)
1281 			blkno = blkstofrags(fs, lblkno);
1282 		ffs_blkfree(ITOUMP(ip), fs, vp, blkno, fs->fs_bsize, inum,
1283 		    vp->v_type, NULL, SINGLETON_KEY);
1284 	}
1285 	return (0);
1286 }
1287 
1288 /*
1289  * Before expunging a snapshot inode, note all the
1290  * blocks that it claims with BLK_SNAP so that fsck will
1291  * be able to account for those blocks properly and so
1292  * that this snapshot knows that it need not copy them
1293  * if the other snapshot holding them is freed. This code
1294  * is reproduced once each for UFS1 and UFS2.
1295  */
1296 static int
1297 expunge_ufs2(struct vnode *snapvp,
1298 	struct inode *cancelip,
1299 	struct fs *fs,
1300 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1301 	    struct fs *, ufs_lbn_t, int),
1302 	int expungetype,
1303 	int clearmode)
1304 {
1305 	int i, error, indiroff;
1306 	ufs_lbn_t lbn, rlbn;
1307 	ufs2_daddr_t len, blkno, numblks, blksperindir;
1308 	struct ufs2_dinode *dip;
1309 	struct thread *td = curthread;
1310 	struct buf *bp;
1311 
1312 	/*
1313 	 * Prepare to expunge the inode. If its inode block has not
1314 	 * yet been copied, then allocate and fill the copy.
1315 	 */
1316 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1317 	blkno = 0;
1318 	if (lbn < UFS_NDADDR) {
1319 		blkno = VTOI(snapvp)->i_din2->di_db[lbn];
1320 	} else {
1321 		if (DOINGSOFTDEP(snapvp))
1322 			softdep_prealloc(snapvp, MNT_WAIT);
1323 		td->td_pflags |= TDP_COWINPROGRESS;
1324 		error = ffs_balloc_ufs2(snapvp, lblktosize(fs, (off_t)lbn),
1325 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1326 		td->td_pflags &= ~TDP_COWINPROGRESS;
1327 		if (error)
1328 			return (error);
1329 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1330 		blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
1331 		bqrelse(bp);
1332 	}
1333 	if (blkno != 0) {
1334 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1335 			return (error);
1336 	} else {
1337 		error = ffs_balloc_ufs2(snapvp, lblktosize(fs, (off_t)lbn),
1338 		    fs->fs_bsize, KERNCRED, 0, &bp);
1339 		if (error)
1340 			return (error);
1341 		if ((error = readblock(snapvp, bp, lbn)) != 0)
1342 			return (error);
1343 	}
1344 	/*
1345 	 * Set a snapshot inode to be a zero length file, regular files
1346 	 * to be completely unallocated.
1347 	 */
1348 	dip = (struct ufs2_dinode *)bp->b_data +
1349 	    ino_to_fsbo(fs, cancelip->i_number);
1350 	dip->di_size = 0;
1351 	dip->di_blocks = 0;
1352 	dip->di_flags &= ~SF_SNAPSHOT;
1353 	bzero(dip->di_db, UFS_NDADDR * sizeof(ufs2_daddr_t));
1354 	bzero(dip->di_ib, UFS_NIADDR * sizeof(ufs2_daddr_t));
1355 	if (clearmode || cancelip->i_effnlink == 0)
1356 		dip->di_mode = 0;
1357 	else
1358 		ffs_update_dinode_ckhash(fs, dip);
1359 	bdwrite(bp);
1360 	/*
1361 	 * Now go through and expunge all the blocks in the file
1362 	 * using the function requested.
1363 	 */
1364 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1365 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_db[0],
1366 	    &cancelip->i_din2->di_db[UFS_NDADDR], fs, 0, expungetype)))
1367 		return (error);
1368 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_ib[0],
1369 	    &cancelip->i_din2->di_ib[UFS_NIADDR], fs, -1, expungetype)))
1370 		return (error);
1371 	blksperindir = 1;
1372 	lbn = -UFS_NDADDR;
1373 	len = numblks - UFS_NDADDR;
1374 	rlbn = UFS_NDADDR;
1375 	for (i = 0; len > 0 && i < UFS_NIADDR; i++) {
1376 		error = indiracct_ufs2(snapvp, ITOV(cancelip), i,
1377 		    cancelip->i_din2->di_ib[i], lbn, rlbn, len,
1378 		    blksperindir, fs, acctfunc, expungetype);
1379 		if (error)
1380 			return (error);
1381 		blksperindir *= NINDIR(fs);
1382 		lbn -= blksperindir + 1;
1383 		len -= blksperindir;
1384 		rlbn += blksperindir;
1385 	}
1386 	return (0);
1387 }
1388 
1389 /*
1390  * Descend an indirect block chain for vnode cancelvp accounting for all
1391  * its indirect blocks in snapvp.
1392  */
1393 static int
1394 indiracct_ufs2(struct vnode *snapvp,
1395 	struct vnode *cancelvp,
1396 	int level,
1397 	ufs2_daddr_t blkno,
1398 	ufs_lbn_t lbn,
1399 	ufs_lbn_t rlbn,
1400 	ufs_lbn_t remblks,
1401 	ufs_lbn_t blksperindir,
1402 	struct fs *fs,
1403 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1404 	    struct fs *, ufs_lbn_t, int),
1405 	int expungetype)
1406 {
1407 	int error, num, i;
1408 	ufs_lbn_t subblksperindir;
1409 	struct indir indirs[UFS_NIADDR + 2];
1410 	ufs2_daddr_t last, *bap;
1411 	struct buf *bp;
1412 
1413 	if (blkno == 0) {
1414 		if (expungetype == BLK_NOCOPY)
1415 			return (0);
1416 		panic("indiracct_ufs2: missing indir");
1417 	}
1418 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1419 		return (error);
1420 	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
1421 		panic("indiracct_ufs2: botched params");
1422 	/*
1423 	 * We have to expand bread here since it will deadlock looking
1424 	 * up the block number for any blocks that are not in the cache.
1425 	 */
1426 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0, 0);
1427 	bp->b_blkno = fsbtodb(fs, blkno);
1428 	if ((bp->b_flags & B_CACHE) == 0 &&
1429 	    (error = readblock(cancelvp, bp, fragstoblks(fs, blkno)))) {
1430 		brelse(bp);
1431 		return (error);
1432 	}
1433 	/*
1434 	 * Account for the block pointers in this indirect block.
1435 	 */
1436 	last = howmany(remblks, blksperindir);
1437 	if (last > NINDIR(fs))
1438 		last = NINDIR(fs);
1439 	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK);
1440 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1441 	bqrelse(bp);
1442 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1443 	    level == 0 ? rlbn : -1, expungetype);
1444 	if (error || level == 0)
1445 		goto out;
1446 	/*
1447 	 * Account for the block pointers in each of the indirect blocks
1448 	 * in the levels below us.
1449 	 */
1450 	subblksperindir = blksperindir / NINDIR(fs);
1451 	for (lbn++, level--, i = 0; i < last; i++) {
1452 		error = indiracct_ufs2(snapvp, cancelvp, level, bap[i], lbn,
1453 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1454 		if (error)
1455 			goto out;
1456 		rlbn += blksperindir;
1457 		lbn -= blksperindir;
1458 		remblks -= blksperindir;
1459 	}
1460 out:
1461 	free(bap, M_DEVBUF);
1462 	return (error);
1463 }
1464 
1465 /*
1466  * Do both snap accounting and map accounting.
1467  */
1468 static int
1469 fullacct_ufs2(struct vnode *vp,
1470 	ufs2_daddr_t *oldblkp,
1471 	ufs2_daddr_t *lastblkp,
1472 	struct fs *fs,
1473 	ufs_lbn_t lblkno,
1474 	int exptype)	/* BLK_SNAP or BLK_NOCOPY */
1475 {
1476 	int error;
1477 
1478 	if ((error = snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1479 		return (error);
1480 	return (mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1481 }
1482 
1483 /*
1484  * Identify a set of blocks allocated in a snapshot inode.
1485  */
1486 static int
1487 snapacct_ufs2(struct vnode *vp,
1488 	ufs2_daddr_t *oldblkp,
1489 	ufs2_daddr_t *lastblkp,
1490 	struct fs *fs,
1491 	ufs_lbn_t lblkno,
1492 	int expungetype)	/* BLK_SNAP or BLK_NOCOPY */
1493 {
1494 	struct inode *ip = VTOI(vp);
1495 	ufs2_daddr_t blkno, *blkp;
1496 	ufs_lbn_t lbn;
1497 	struct buf *ibp;
1498 	int error;
1499 
1500 	for ( ; oldblkp < lastblkp; oldblkp++) {
1501 		blkno = *oldblkp;
1502 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1503 			continue;
1504 		lbn = fragstoblks(fs, blkno);
1505 		if (lbn < UFS_NDADDR) {
1506 			blkp = &ip->i_din2->di_db[lbn];
1507 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1508 		} else {
1509 			error = ffs_balloc_ufs2(vp, lblktosize(fs, (off_t)lbn),
1510 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1511 			if (error)
1512 				return (error);
1513 			blkp = &((ufs2_daddr_t *)(ibp->b_data))
1514 			    [(lbn - UFS_NDADDR) % NINDIR(fs)];
1515 		}
1516 		/*
1517 		 * If we are expunging a snapshot vnode and we
1518 		 * find a block marked BLK_NOCOPY, then it is
1519 		 * one that has been allocated to this snapshot after
1520 		 * we took our current snapshot and can be ignored.
1521 		 */
1522 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1523 			if (lbn >= UFS_NDADDR)
1524 				brelse(ibp);
1525 		} else {
1526 			if (*blkp != 0)
1527 				panic("snapacct_ufs2: bad block");
1528 			*blkp = expungetype;
1529 			if (lbn >= UFS_NDADDR)
1530 				bdwrite(ibp);
1531 		}
1532 	}
1533 	return (0);
1534 }
1535 
1536 /*
1537  * Account for a set of blocks allocated in a snapshot inode.
1538  */
1539 static int
1540 mapacct_ufs2(struct vnode *vp,
1541 	ufs2_daddr_t *oldblkp,
1542 	ufs2_daddr_t *lastblkp,
1543 	struct fs *fs,
1544 	ufs_lbn_t lblkno,
1545 	int expungetype)
1546 {
1547 	ufs2_daddr_t blkno;
1548 	struct inode *ip;
1549 	ino_t inum;
1550 	int acctit;
1551 
1552 	ip = VTOI(vp);
1553 	inum = ip->i_number;
1554 	if (lblkno == -1)
1555 		acctit = 0;
1556 	else
1557 		acctit = 1;
1558 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1559 		blkno = *oldblkp;
1560 		if (blkno == 0 || blkno == BLK_NOCOPY)
1561 			continue;
1562 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP &&
1563 		    lblkno >= UFS_NDADDR)
1564 			*ip->i_snapblklist++ = lblkno;
1565 		if (blkno == BLK_SNAP)
1566 			blkno = blkstofrags(fs, lblkno);
1567 		ffs_blkfree(ITOUMP(ip), fs, vp, blkno, fs->fs_bsize, inum,
1568 		    vp->v_type, NULL, SINGLETON_KEY);
1569 	}
1570 	return (0);
1571 }
1572 
1573 /*
1574  * Decrement extra reference on snapshot when last name is removed.
1575  * It will not be freed until the last open reference goes away.
1576  */
1577 void
1578 ffs_snapgone(struct inode *ip)
1579 {
1580 	struct inode *xp;
1581 	struct fs *fs;
1582 	int snaploc;
1583 	struct snapdata *sn;
1584 	struct ufsmount *ump;
1585 
1586 	/*
1587 	 * Find snapshot in incore list.
1588 	 */
1589 	xp = NULL;
1590 	sn = ITODEVVP(ip)->v_rdev->si_snapdata;
1591 	if (sn != NULL)
1592 		TAILQ_FOREACH(xp, &sn->sn_head, i_nextsnap)
1593 			if (xp == ip)
1594 				break;
1595 	if (xp != NULL)
1596 		vrele(ITOV(ip));
1597 #ifdef DIAGNOSTIC
1598 	else if (snapdebug)
1599 		printf("ffs_snapgone: lost snapshot vnode %ju\n",
1600 		    (uintmax_t)ip->i_number);
1601 #endif
1602 	/*
1603 	 * Delete snapshot inode from superblock. Keep list dense.
1604 	 */
1605 	ump = ITOUMP(ip);
1606 	fs = ump->um_fs;
1607 	UFS_LOCK(ump);
1608 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
1609 		if (fs->fs_snapinum[snaploc] == ip->i_number)
1610 			break;
1611 	if (snaploc < FSMAXSNAP) {
1612 		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
1613 			if (fs->fs_snapinum[snaploc] == 0)
1614 				break;
1615 			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
1616 		}
1617 		fs->fs_snapinum[snaploc - 1] = 0;
1618 	}
1619 	UFS_UNLOCK(ump);
1620 }
1621 
1622 /*
1623  * Prepare a snapshot file for being removed.
1624  */
1625 void
1626 ffs_snapremove(struct vnode *vp)
1627 {
1628 	struct inode *ip;
1629 	struct vnode *devvp;
1630 	struct buf *ibp;
1631 	struct fs *fs;
1632 	ufs2_daddr_t numblks, blkno, dblk;
1633 	int error, last, loc;
1634 	struct snapdata *sn;
1635 
1636 	ip = VTOI(vp);
1637 	fs = ITOFS(ip);
1638 	devvp = ITODEVVP(ip);
1639 	/*
1640 	 * If active, delete from incore list (this snapshot may
1641 	 * already have been in the process of being deleted, so
1642 	 * would not have been active).
1643 	 *
1644 	 * Clear copy-on-write flag if last snapshot.
1645 	 */
1646 	VI_LOCK(devvp);
1647 	if (ip->i_nextsnap.tqe_prev != 0) {
1648 		sn = devvp->v_rdev->si_snapdata;
1649 		TAILQ_REMOVE(&sn->sn_head, ip, i_nextsnap);
1650 		ip->i_nextsnap.tqe_prev = 0;
1651 		revert_snaplock(vp, devvp, sn);
1652 		try_free_snapdata(devvp);
1653 	}
1654 	VI_UNLOCK(devvp);
1655 	/*
1656 	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
1657 	 * snapshots that want them (see ffs_snapblkfree below).
1658 	 */
1659 	for (blkno = 1; blkno < UFS_NDADDR; blkno++) {
1660 		dblk = DIP(ip, i_db[blkno]);
1661 		if (dblk == 0)
1662 			continue;
1663 		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1664 			DIP_SET(ip, i_db[blkno], 0);
1665 		else if ((dblk == blkstofrags(fs, blkno) &&
1666 		     ffs_snapblkfree(fs, ITODEVVP(ip), dblk, fs->fs_bsize,
1667 		     ip->i_number, vp->v_type, NULL))) {
1668 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) -
1669 			    btodb(fs->fs_bsize));
1670 			DIP_SET(ip, i_db[blkno], 0);
1671 		}
1672 	}
1673 	numblks = howmany(ip->i_size, fs->fs_bsize);
1674 	for (blkno = UFS_NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
1675 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
1676 		    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1677 		if (error)
1678 			continue;
1679 		if (fs->fs_size - blkno > NINDIR(fs))
1680 			last = NINDIR(fs);
1681 		else
1682 			last = fs->fs_size - blkno;
1683 		for (loc = 0; loc < last; loc++) {
1684 			if (I_IS_UFS1(ip)) {
1685 				dblk = ((ufs1_daddr_t *)(ibp->b_data))[loc];
1686 				if (dblk == 0)
1687 					continue;
1688 				if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1689 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1690 				else if ((dblk == blkstofrags(fs, blkno) &&
1691 				     ffs_snapblkfree(fs, ITODEVVP(ip), dblk,
1692 				     fs->fs_bsize, ip->i_number, vp->v_type,
1693 				     NULL))) {
1694 					ip->i_din1->di_blocks -=
1695 					    btodb(fs->fs_bsize);
1696 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1697 				}
1698 				continue;
1699 			}
1700 			dblk = ((ufs2_daddr_t *)(ibp->b_data))[loc];
1701 			if (dblk == 0)
1702 				continue;
1703 			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1704 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1705 			else if ((dblk == blkstofrags(fs, blkno) &&
1706 			     ffs_snapblkfree(fs, ITODEVVP(ip), dblk,
1707 			     fs->fs_bsize, ip->i_number, vp->v_type, NULL))) {
1708 				ip->i_din2->di_blocks -= btodb(fs->fs_bsize);
1709 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1710 			}
1711 		}
1712 		bawrite(ibp);
1713 	}
1714 	/*
1715 	 * Clear snapshot flag and drop reference.
1716 	 */
1717 	ip->i_flags &= ~SF_SNAPSHOT;
1718 	DIP_SET(ip, i_flags, ip->i_flags);
1719 	UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1720 	/*
1721 	 * The dirtied indirects must be written out before
1722 	 * softdep_setup_freeblocks() is called.  Otherwise indir_trunc()
1723 	 * may find indirect pointers using the magic BLK_* values.
1724 	 */
1725 	if (DOINGSOFTDEP(vp))
1726 		ffs_syncvnode(vp, MNT_WAIT, 0);
1727 #ifdef QUOTA
1728 	/*
1729 	 * Reenable disk quotas for ex-snapshot file.
1730 	 */
1731 	if (!getinoquota(ip))
1732 		(void) chkdq(ip, DIP(ip, i_blocks), KERNCRED, FORCE);
1733 #endif
1734 }
1735 
1736 /*
1737  * Notification that a block is being freed. Return zero if the free
1738  * should be allowed to proceed. Return non-zero if the snapshot file
1739  * wants to claim the block. The block will be claimed if it is an
1740  * uncopied part of one of the snapshots. It will be freed if it is
1741  * either a BLK_NOCOPY or has already been copied in all of the snapshots.
1742  * If a fragment is being freed, then all snapshots that care about
1743  * it must make a copy since a snapshot file can only claim full sized
1744  * blocks. Note that if more than one snapshot file maps the block,
1745  * we can pick one at random to claim it. Since none of the snapshots
1746  * can change, we are assurred that they will all see the same unmodified
1747  * image. When deleting a snapshot file (see ffs_snapremove above), we
1748  * must push any of these claimed blocks to one of the other snapshots
1749  * that maps it. These claimed blocks are easily identified as they will
1750  * have a block number equal to their logical block number within the
1751  * snapshot. A copied block can never have this property because they
1752  * must always have been allocated from a BLK_NOCOPY location.
1753  */
1754 int
1755 ffs_snapblkfree(struct fs *fs,
1756 	struct vnode *devvp,
1757 	ufs2_daddr_t bno,
1758 	long size,
1759 	ino_t inum,
1760 	enum vtype vtype,
1761 	struct workhead *wkhd)
1762 {
1763 	struct buf *ibp, *cbp, *savedcbp = NULL;
1764 	struct thread *td = curthread;
1765 	struct inode *ip;
1766 	struct vnode *vp = NULL;
1767 	ufs_lbn_t lbn;
1768 	ufs2_daddr_t blkno;
1769 	int indiroff = 0, error = 0, claimedblk = 0;
1770 	struct snapdata *sn;
1771 
1772 	lbn = fragstoblks(fs, bno);
1773 retry:
1774 	VI_LOCK(devvp);
1775 	sn = devvp->v_rdev->si_snapdata;
1776 	if (sn == NULL) {
1777 		VI_UNLOCK(devvp);
1778 		return (0);
1779 	}
1780 
1781 	/*
1782 	 * Use LK_SLEEPFAIL because sn might be freed under us while
1783 	 * both devvp interlock and snaplk are not owned.
1784 	 */
1785 	if (lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1786 	    VI_MTX(devvp)) != 0)
1787 		goto retry;
1788 
1789 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
1790 		vp = ITOV(ip);
1791 		if (DOINGSOFTDEP(vp))
1792 			softdep_prealloc(vp, MNT_WAIT);
1793 		/*
1794 		 * Lookup block being written.
1795 		 */
1796 		if (lbn < UFS_NDADDR) {
1797 			blkno = DIP(ip, i_db[lbn]);
1798 		} else {
1799 			td->td_pflags |= TDP_COWINPROGRESS;
1800 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1801 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1802 			td->td_pflags &= ~TDP_COWINPROGRESS;
1803 			if (error)
1804 				break;
1805 			indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1806 			if (I_IS_UFS1(ip))
1807 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1808 			else
1809 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1810 		}
1811 		/*
1812 		 * Check to see if block needs to be copied.
1813 		 */
1814 		if (blkno == 0) {
1815 			/*
1816 			 * A block that we map is being freed. If it has not
1817 			 * been claimed yet, we will claim or copy it (below).
1818 			 */
1819 			claimedblk = 1;
1820 		} else if (blkno == BLK_SNAP) {
1821 			/*
1822 			 * No previous snapshot claimed the block,
1823 			 * so it will be freed and become a BLK_NOCOPY
1824 			 * (don't care) for us.
1825 			 */
1826 			if (claimedblk)
1827 				panic("snapblkfree: inconsistent block type");
1828 			if (lbn < UFS_NDADDR) {
1829 				DIP_SET(ip, i_db[lbn], BLK_NOCOPY);
1830 				UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1831 			} else if (I_IS_UFS1(ip)) {
1832 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
1833 				    BLK_NOCOPY;
1834 				bdwrite(ibp);
1835 			} else {
1836 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] =
1837 				    BLK_NOCOPY;
1838 				bdwrite(ibp);
1839 			}
1840 			continue;
1841 		} else /* BLK_NOCOPY or default */ {
1842 			/*
1843 			 * If the snapshot has already copied the block
1844 			 * (default), or does not care about the block,
1845 			 * it is not needed.
1846 			 */
1847 			if (lbn >= UFS_NDADDR)
1848 				bqrelse(ibp);
1849 			continue;
1850 		}
1851 		/*
1852 		 * If this is a full size block, we will just grab it
1853 		 * and assign it to the snapshot inode. Otherwise we
1854 		 * will proceed to copy it. See explanation for this
1855 		 * routine as to why only a single snapshot needs to
1856 		 * claim this block.
1857 		 */
1858 		if (size == fs->fs_bsize) {
1859 #ifdef DIAGNOSTIC
1860 			if (snapdebug)
1861 				printf("%s %ju lbn %jd from inum %ju\n",
1862 				    "Grabonremove: snapino",
1863 				    (uintmax_t)ip->i_number,
1864 				    (intmax_t)lbn, (uintmax_t)inum);
1865 #endif
1866 			/*
1867 			 * If journaling is tracking this write we must add
1868 			 * the work to the inode or indirect being written.
1869 			 */
1870 			if (wkhd != NULL) {
1871 				if (lbn < UFS_NDADDR)
1872 					softdep_inode_append(ip,
1873 					    curthread->td_ucred, wkhd);
1874 				else
1875 					softdep_buf_append(ibp, wkhd);
1876 			}
1877 			if (lbn < UFS_NDADDR) {
1878 				DIP_SET(ip, i_db[lbn], bno);
1879 			} else if (I_IS_UFS1(ip)) {
1880 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = bno;
1881 				bdwrite(ibp);
1882 			} else {
1883 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] = bno;
1884 				bdwrite(ibp);
1885 			}
1886 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + btodb(size));
1887 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1888 			lockmgr(vp->v_vnlock, LK_RELEASE, NULL);
1889 			return (1);
1890 		}
1891 		if (lbn >= UFS_NDADDR)
1892 			bqrelse(ibp);
1893 		/*
1894 		 * Allocate the block into which to do the copy. Note that this
1895 		 * allocation will never require any additional allocations for
1896 		 * the snapshot inode.
1897 		 */
1898 		td->td_pflags |= TDP_COWINPROGRESS;
1899 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1900 		    fs->fs_bsize, KERNCRED, 0, &cbp);
1901 		td->td_pflags &= ~TDP_COWINPROGRESS;
1902 		if (error)
1903 			break;
1904 #ifdef DIAGNOSTIC
1905 		if (snapdebug)
1906 			printf("%s%ju lbn %jd %s %ju size %ld to blkno %jd\n",
1907 			    "Copyonremove: snapino ", (uintmax_t)ip->i_number,
1908 			    (intmax_t)lbn, "for inum", (uintmax_t)inum, size,
1909 			    (intmax_t)cbp->b_blkno);
1910 #endif
1911 		/*
1912 		 * If we have already read the old block contents, then
1913 		 * simply copy them to the new block. Note that we need
1914 		 * to synchronously write snapshots that have not been
1915 		 * unlinked, and hence will be visible after a crash,
1916 		 * to ensure their integrity. At a minimum we ensure the
1917 		 * integrity of the filesystem metadata, but use the
1918 		 * dopersistence sysctl-setable flag to decide on the
1919 		 * persistence needed for file content data.
1920 		 */
1921 		if (savedcbp != NULL) {
1922 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1923 			bawrite(cbp);
1924 			if ((vtype == VDIR || dopersistence) &&
1925 			    ip->i_effnlink > 0)
1926 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1927 			continue;
1928 		}
1929 		/*
1930 		 * Otherwise, read the old block contents into the buffer.
1931 		 */
1932 		if ((error = readblock(vp, cbp, lbn)) != 0) {
1933 			bzero(cbp->b_data, fs->fs_bsize);
1934 			bawrite(cbp);
1935 			if ((vtype == VDIR || dopersistence) &&
1936 			    ip->i_effnlink > 0)
1937 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1938 			break;
1939 		}
1940 		savedcbp = cbp;
1941 	}
1942 	/*
1943 	 * Note that we need to synchronously write snapshots that
1944 	 * have not been unlinked, and hence will be visible after
1945 	 * a crash, to ensure their integrity. At a minimum we
1946 	 * ensure the integrity of the filesystem metadata, but
1947 	 * use the dopersistence sysctl-setable flag to decide on
1948 	 * the persistence needed for file content data.
1949 	 */
1950 	if (savedcbp) {
1951 		vp = savedcbp->b_vp;
1952 		bawrite(savedcbp);
1953 		if ((vtype == VDIR || dopersistence) &&
1954 		    VTOI(vp)->i_effnlink > 0)
1955 			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1956 	}
1957 	/*
1958 	 * If we have been unable to allocate a block in which to do
1959 	 * the copy, then return non-zero so that the fragment will
1960 	 * not be freed. Although space will be lost, the snapshot
1961 	 * will stay consistent.
1962 	 */
1963 	if (error != 0 && wkhd != NULL)
1964 		softdep_freework(wkhd);
1965 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
1966 	return (error);
1967 }
1968 
1969 /*
1970  * Associate snapshot files when mounting.
1971  */
1972 void
1973 ffs_snapshot_mount(struct mount *mp)
1974 {
1975 	struct ufsmount *ump = VFSTOUFS(mp);
1976 	struct vnode *devvp = ump->um_devvp;
1977 	struct fs *fs = ump->um_fs;
1978 	struct thread *td = curthread;
1979 	struct snapdata *sn;
1980 	struct vnode *vp;
1981 	struct vnode *lastvp;
1982 	struct inode *ip;
1983 	struct uio auio;
1984 	struct iovec aiov;
1985 	void *snapblklist;
1986 	char *reason;
1987 	daddr_t snaplistsize;
1988 	int error, snaploc, loc;
1989 
1990 	/*
1991 	 * XXX The following needs to be set before ffs_truncate or
1992 	 * VOP_READ can be called.
1993 	 */
1994 	mp->mnt_stat.f_iosize = fs->fs_bsize;
1995 	/*
1996 	 * Process each snapshot listed in the superblock.
1997 	 */
1998 	vp = NULL;
1999 	lastvp = NULL;
2000 	sn = NULL;
2001 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
2002 		if (fs->fs_snapinum[snaploc] == 0)
2003 			break;
2004 		if ((error = ffs_vget(mp, fs->fs_snapinum[snaploc],
2005 		    LK_EXCLUSIVE, &vp)) != 0){
2006 			printf("ffs_snapshot_mount: vget failed %d\n", error);
2007 			continue;
2008 		}
2009 		ip = VTOI(vp);
2010 		if (vp->v_type != VREG) {
2011 			reason = "non-file snapshot";
2012 		} else if (!IS_SNAPSHOT(ip)) {
2013 			reason = "non-snapshot";
2014 		} else if (ip->i_size ==
2015 		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag))) {
2016 			reason = "old format snapshot";
2017 			(void)ffs_truncate(vp, (off_t)0, 0, NOCRED);
2018 			(void)ffs_syncvnode(vp, MNT_WAIT, 0);
2019 		} else {
2020 			reason = NULL;
2021 		}
2022 		if (reason != NULL) {
2023 			printf("ffs_snapshot_mount: %s inode %d\n",
2024 			    reason, fs->fs_snapinum[snaploc]);
2025 			vput(vp);
2026 			vp = NULL;
2027 			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
2028 				if (fs->fs_snapinum[loc] == 0)
2029 					break;
2030 				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
2031 			}
2032 			fs->fs_snapinum[loc - 1] = 0;
2033 			snaploc--;
2034 			continue;
2035 		}
2036 		/*
2037 		 * Acquire a lock on the snapdata structure, creating it if
2038 		 * necessary.
2039 		 */
2040 		sn = ffs_snapdata_acquire(devvp);
2041 		/*
2042 		 * Change vnode to use shared snapshot lock instead of the
2043 		 * original private lock.
2044 		 */
2045 		vp->v_vnlock = &sn->sn_lock;
2046 		lockmgr(&vp->v_lock, LK_RELEASE, NULL);
2047 		/*
2048 		 * Link it onto the active snapshot list.
2049 		 */
2050 		VI_LOCK(devvp);
2051 		if (ip->i_nextsnap.tqe_prev != 0)
2052 			panic("ffs_snapshot_mount: %ju already on list",
2053 			    (uintmax_t)ip->i_number);
2054 		else
2055 			TAILQ_INSERT_TAIL(&sn->sn_head, ip, i_nextsnap);
2056 		vp->v_vflag |= VV_SYSTEM;
2057 		VI_UNLOCK(devvp);
2058 		VOP_UNLOCK(vp);
2059 		lastvp = vp;
2060 	}
2061 	vp = lastvp;
2062 	/*
2063 	 * No usable snapshots found.
2064 	 */
2065 	if (sn == NULL || vp == NULL)
2066 		return;
2067 	/*
2068 	 * Allocate the space for the block hints list. We always want to
2069 	 * use the list from the newest snapshot.
2070 	 */
2071 	auio.uio_iov = &aiov;
2072 	auio.uio_iovcnt = 1;
2073 	aiov.iov_base = (void *)&snaplistsize;
2074 	aiov.iov_len = sizeof(snaplistsize);
2075 	auio.uio_resid = aiov.iov_len;
2076 	auio.uio_offset =
2077 	    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag));
2078 	auio.uio_segflg = UIO_SYSSPACE;
2079 	auio.uio_rw = UIO_READ;
2080 	auio.uio_td = td;
2081 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2082 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
2083 		printf("ffs_snapshot_mount: read_1 failed %d\n", error);
2084 		VOP_UNLOCK(vp);
2085 		return;
2086 	}
2087 	snapblklist = malloc(snaplistsize * sizeof(daddr_t),
2088 	    M_UFSMNT, M_WAITOK);
2089 	auio.uio_iovcnt = 1;
2090 	aiov.iov_base = snapblklist;
2091 	aiov.iov_len = snaplistsize * sizeof (daddr_t);
2092 	auio.uio_resid = aiov.iov_len;
2093 	auio.uio_offset -= sizeof(snaplistsize);
2094 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
2095 		printf("ffs_snapshot_mount: read_2 failed %d\n", error);
2096 		VOP_UNLOCK(vp);
2097 		free(snapblklist, M_UFSMNT);
2098 		return;
2099 	}
2100 	VOP_UNLOCK(vp);
2101 	VI_LOCK(devvp);
2102 	sn->sn_listsize = snaplistsize;
2103 	sn->sn_blklist = (daddr_t *)snapblklist;
2104 	devvp->v_vflag |= VV_COPYONWRITE;
2105 	VI_UNLOCK(devvp);
2106 }
2107 
2108 /*
2109  * Disassociate snapshot files when unmounting.
2110  */
2111 void
2112 ffs_snapshot_unmount(struct mount *mp)
2113 {
2114 	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
2115 	struct snapdata *sn;
2116 	struct inode *xp;
2117 	struct vnode *vp;
2118 
2119 	VI_LOCK(devvp);
2120 	sn = devvp->v_rdev->si_snapdata;
2121 	while (sn != NULL && (xp = TAILQ_FIRST(&sn->sn_head)) != NULL) {
2122 		vp = ITOV(xp);
2123 		TAILQ_REMOVE(&sn->sn_head, xp, i_nextsnap);
2124 		xp->i_nextsnap.tqe_prev = 0;
2125 		lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE,
2126 		    VI_MTX(devvp));
2127 		VI_LOCK(devvp);
2128 		revert_snaplock(vp, devvp, sn);
2129 		lockmgr(&vp->v_lock, LK_RELEASE, NULL);
2130 		if (xp->i_effnlink > 0) {
2131 			VI_UNLOCK(devvp);
2132 			vrele(vp);
2133 			VI_LOCK(devvp);
2134 		}
2135 		sn = devvp->v_rdev->si_snapdata;
2136 	}
2137 	try_free_snapdata(devvp);
2138 	VI_UNLOCK(devvp);
2139 }
2140 
2141 /*
2142  * Check the buffer block to be belong to device buffer that shall be
2143  * locked after snaplk. devvp shall be locked on entry, and will be
2144  * leaved locked upon exit.
2145  */
2146 static int
2147 ffs_bp_snapblk(struct vnode *devvp, struct buf *bp)
2148 {
2149 	struct snapdata *sn;
2150 	struct fs *fs;
2151 	ufs2_daddr_t lbn, *snapblklist;
2152 	int lower, upper, mid;
2153 
2154 	ASSERT_VI_LOCKED(devvp, "ffs_bp_snapblk");
2155 	KASSERT(devvp->v_type == VCHR, ("Not a device %p", devvp));
2156 	sn = devvp->v_rdev->si_snapdata;
2157 	if (sn == NULL || TAILQ_FIRST(&sn->sn_head) == NULL)
2158 		return (0);
2159 	fs = ITOFS(TAILQ_FIRST(&sn->sn_head));
2160 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
2161 	snapblklist = sn->sn_blklist;
2162 	upper = sn->sn_listsize - 1;
2163 	lower = 1;
2164 	while (lower <= upper) {
2165 		mid = (lower + upper) / 2;
2166 		if (snapblklist[mid] == lbn)
2167 			break;
2168 		if (snapblklist[mid] < lbn)
2169 			lower = mid + 1;
2170 		else
2171 			upper = mid - 1;
2172 	}
2173 	if (lower <= upper)
2174 		return (1);
2175 	return (0);
2176 }
2177 
2178 void
2179 ffs_bdflush(struct bufobj *bo, struct buf *bp)
2180 {
2181 	struct thread *td;
2182 	struct vnode *vp, *devvp;
2183 	struct buf *nbp;
2184 	int bp_bdskip;
2185 
2186 	if (bo->bo_dirty.bv_cnt <= dirtybufthresh)
2187 		return;
2188 
2189 	td = curthread;
2190 	vp = bp->b_vp;
2191 	devvp = bo2vnode(bo);
2192 	KASSERT(vp == devvp, ("devvp != vp %p %p", bo, bp));
2193 
2194 	VI_LOCK(devvp);
2195 	bp_bdskip = ffs_bp_snapblk(devvp, bp);
2196 	if (bp_bdskip)
2197 		bdwriteskip++;
2198 	VI_UNLOCK(devvp);
2199 	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10 && !bp_bdskip) {
2200 		(void) VOP_FSYNC(vp, MNT_NOWAIT, td);
2201 		altbufferflushes++;
2202 	} else {
2203 		BO_LOCK(bo);
2204 		/*
2205 		 * Try to find a buffer to flush.
2206 		 */
2207 		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2208 			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2209 			    BUF_LOCK(nbp,
2210 				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
2211 				continue;
2212 			if (bp == nbp)
2213 				panic("bdwrite: found ourselves");
2214 			BO_UNLOCK(bo);
2215 			/*
2216 			 * Don't countdeps with the bo lock
2217 			 * held.
2218 			 */
2219 			if (buf_countdeps(nbp, 0)) {
2220 				BO_LOCK(bo);
2221 				BUF_UNLOCK(nbp);
2222 				continue;
2223 			}
2224 			if (bp_bdskip) {
2225 				VI_LOCK(devvp);
2226 				if (!ffs_bp_snapblk(vp, nbp)) {
2227 					VI_UNLOCK(devvp);
2228 					BO_LOCK(bo);
2229 					BUF_UNLOCK(nbp);
2230 					continue;
2231 				}
2232 				VI_UNLOCK(devvp);
2233 			}
2234 			if (nbp->b_flags & B_CLUSTEROK) {
2235 				vfs_bio_awrite(nbp);
2236 			} else {
2237 				bremfree(nbp);
2238 				bawrite(nbp);
2239 			}
2240 			dirtybufferflushes++;
2241 			break;
2242 		}
2243 		if (nbp == NULL)
2244 			BO_UNLOCK(bo);
2245 	}
2246 }
2247 
2248 /*
2249  * Check for need to copy block that is about to be written,
2250  * copying the block if necessary.
2251  */
2252 int
2253 ffs_copyonwrite(struct vnode *devvp, struct buf *bp)
2254 {
2255 	struct snapdata *sn;
2256 	struct buf *ibp, *cbp, *savedcbp = NULL;
2257 	struct thread *td = curthread;
2258 	struct fs *fs;
2259 	struct inode *ip;
2260 	struct vnode *vp = NULL;
2261 	ufs2_daddr_t lbn, blkno, *snapblklist;
2262 	int lower, upper, mid, indiroff, error = 0;
2263 	int launched_async_io, prev_norunningbuf;
2264 	long saved_runningbufspace;
2265 
2266 	if (devvp != bp->b_vp && IS_SNAPSHOT(VTOI(bp->b_vp)))
2267 		return (0);		/* Update on a snapshot file */
2268 	if (td->td_pflags & TDP_COWINPROGRESS)
2269 		panic("ffs_copyonwrite: recursive call");
2270 	/*
2271 	 * First check to see if it is in the preallocated list.
2272 	 * By doing this check we avoid several potential deadlocks.
2273 	 */
2274 	VI_LOCK(devvp);
2275 	sn = devvp->v_rdev->si_snapdata;
2276 	if (sn == NULL ||
2277 	    TAILQ_EMPTY(&sn->sn_head)) {
2278 		VI_UNLOCK(devvp);
2279 		return (0);		/* No snapshot */
2280 	}
2281 	ip = TAILQ_FIRST(&sn->sn_head);
2282 	fs = ITOFS(ip);
2283 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
2284 	if (lbn < UFS_NDADDR) {
2285 		VI_UNLOCK(devvp);
2286 		return (0);		/* Direct blocks are always copied */
2287 	}
2288 	snapblklist = sn->sn_blklist;
2289 	upper = sn->sn_listsize - 1;
2290 	lower = 1;
2291 	while (lower <= upper) {
2292 		mid = (lower + upper) / 2;
2293 		if (snapblklist[mid] == lbn)
2294 			break;
2295 		if (snapblklist[mid] < lbn)
2296 			lower = mid + 1;
2297 		else
2298 			upper = mid - 1;
2299 	}
2300 	if (lower <= upper) {
2301 		VI_UNLOCK(devvp);
2302 		return (0);
2303 	}
2304 	launched_async_io = 0;
2305 	prev_norunningbuf = td->td_pflags & TDP_NORUNNINGBUF;
2306 	/*
2307 	 * Since I/O on bp isn't yet in progress and it may be blocked
2308 	 * for a long time waiting on snaplk, back it out of
2309 	 * runningbufspace, possibly waking other threads waiting for space.
2310 	 */
2311 	saved_runningbufspace = bp->b_runningbufspace;
2312 	if (saved_runningbufspace != 0)
2313 		runningbufwakeup(bp);
2314 	/*
2315 	 * Not in the precomputed list, so check the snapshots.
2316 	 */
2317 	while (lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
2318 	    VI_MTX(devvp)) != 0) {
2319 		VI_LOCK(devvp);
2320 		sn = devvp->v_rdev->si_snapdata;
2321 		if (sn == NULL ||
2322 		    TAILQ_EMPTY(&sn->sn_head)) {
2323 			VI_UNLOCK(devvp);
2324 			if (saved_runningbufspace != 0) {
2325 				bp->b_runningbufspace = saved_runningbufspace;
2326 				atomic_add_long(&runningbufspace,
2327 					       bp->b_runningbufspace);
2328 			}
2329 			return (0);		/* Snapshot gone */
2330 		}
2331 	}
2332 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
2333 		vp = ITOV(ip);
2334 		if (DOINGSOFTDEP(vp))
2335 			softdep_prealloc(vp, MNT_WAIT);
2336 		/*
2337 		 * We ensure that everything of our own that needs to be
2338 		 * copied will be done at the time that ffs_snapshot is
2339 		 * called. Thus we can skip the check here which can
2340 		 * deadlock in doing the lookup in UFS_BALLOC.
2341 		 */
2342 		if (bp->b_vp == vp)
2343 			continue;
2344 		/*
2345 		 * Check to see if block needs to be copied. We do not have
2346 		 * to hold the snapshot lock while doing this lookup as it
2347 		 * will never require any additional allocations for the
2348 		 * snapshot inode.
2349 		 */
2350 		if (lbn < UFS_NDADDR) {
2351 			blkno = DIP(ip, i_db[lbn]);
2352 		} else {
2353 			td->td_pflags |= TDP_COWINPROGRESS | TDP_NORUNNINGBUF;
2354 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
2355 			   fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
2356 			td->td_pflags &= ~TDP_COWINPROGRESS;
2357 			if (error)
2358 				break;
2359 			indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
2360 			if (I_IS_UFS1(ip))
2361 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
2362 			else
2363 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
2364 			bqrelse(ibp);
2365 		}
2366 #ifdef INVARIANTS
2367 		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
2368 			panic("ffs_copyonwrite: bad copy block");
2369 #endif
2370 		if (blkno != 0)
2371 			continue;
2372 		/*
2373 		 * Allocate the block into which to do the copy. Since
2374 		 * multiple processes may all try to copy the same block,
2375 		 * we have to recheck our need to do a copy if we sleep
2376 		 * waiting for the lock.
2377 		 *
2378 		 * Because all snapshots on a filesystem share a single
2379 		 * lock, we ensure that we will never be in competition
2380 		 * with another process to allocate a block.
2381 		 */
2382 		td->td_pflags |= TDP_COWINPROGRESS | TDP_NORUNNINGBUF;
2383 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
2384 		    fs->fs_bsize, KERNCRED, 0, &cbp);
2385 		td->td_pflags &= ~TDP_COWINPROGRESS;
2386 		if (error)
2387 			break;
2388 #ifdef DIAGNOSTIC
2389 		if (snapdebug) {
2390 			printf("Copyonwrite: snapino %ju lbn %jd for ",
2391 			    (uintmax_t)ip->i_number, (intmax_t)lbn);
2392 			if (bp->b_vp == devvp)
2393 				printf("fs metadata");
2394 			else
2395 				printf("inum %ju",
2396 				    (uintmax_t)VTOI(bp->b_vp)->i_number);
2397 			printf(" lblkno %jd to blkno %jd\n",
2398 			    (intmax_t)bp->b_lblkno, (intmax_t)cbp->b_blkno);
2399 		}
2400 #endif
2401 		/*
2402 		 * If we have already read the old block contents, then
2403 		 * simply copy them to the new block. Note that we need
2404 		 * to synchronously write snapshots that have not been
2405 		 * unlinked, and hence will be visible after a crash,
2406 		 * to ensure their integrity. At a minimum we ensure the
2407 		 * integrity of the filesystem metadata, but use the
2408 		 * dopersistence sysctl-setable flag to decide on the
2409 		 * persistence needed for file content data.
2410 		 */
2411 		if (savedcbp != NULL) {
2412 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
2413 			bawrite(cbp);
2414 			if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2415 			    dopersistence) && ip->i_effnlink > 0)
2416 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2417 			else
2418 				launched_async_io = 1;
2419 			continue;
2420 		}
2421 		/*
2422 		 * Otherwise, read the old block contents into the buffer.
2423 		 */
2424 		if ((error = readblock(vp, cbp, lbn)) != 0) {
2425 			bzero(cbp->b_data, fs->fs_bsize);
2426 			bawrite(cbp);
2427 			if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2428 			    dopersistence) && ip->i_effnlink > 0)
2429 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2430 			else
2431 				launched_async_io = 1;
2432 			break;
2433 		}
2434 		savedcbp = cbp;
2435 	}
2436 	/*
2437 	 * Note that we need to synchronously write snapshots that
2438 	 * have not been unlinked, and hence will be visible after
2439 	 * a crash, to ensure their integrity. At a minimum we
2440 	 * ensure the integrity of the filesystem metadata, but
2441 	 * use the dopersistence sysctl-setable flag to decide on
2442 	 * the persistence needed for file content data.
2443 	 */
2444 	if (savedcbp) {
2445 		vp = savedcbp->b_vp;
2446 		bawrite(savedcbp);
2447 		if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2448 		    dopersistence) && VTOI(vp)->i_effnlink > 0)
2449 			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2450 		else
2451 			launched_async_io = 1;
2452 	}
2453 	lockmgr(vp->v_vnlock, LK_RELEASE, NULL);
2454 	td->td_pflags = (td->td_pflags & ~TDP_NORUNNINGBUF) |
2455 		prev_norunningbuf;
2456 	if (launched_async_io && (td->td_pflags & TDP_NORUNNINGBUF) == 0)
2457 		waitrunningbufspace();
2458 	/*
2459 	 * I/O on bp will now be started, so count it in runningbufspace.
2460 	 */
2461 	if (saved_runningbufspace != 0) {
2462 		bp->b_runningbufspace = saved_runningbufspace;
2463 		atomic_add_long(&runningbufspace, bp->b_runningbufspace);
2464 	}
2465 	return (error);
2466 }
2467 
2468 /*
2469  * sync snapshots to force freework records waiting on snapshots to claim
2470  * blocks to free.
2471  */
2472 void
2473 ffs_sync_snap(struct mount *mp, int waitfor)
2474 {
2475 	struct snapdata *sn;
2476 	struct vnode *devvp;
2477 	struct vnode *vp;
2478 	struct inode *ip;
2479 
2480 	devvp = VFSTOUFS(mp)->um_devvp;
2481 	if ((devvp->v_vflag & VV_COPYONWRITE) == 0)
2482 		return;
2483 	for (;;) {
2484 		VI_LOCK(devvp);
2485 		sn = devvp->v_rdev->si_snapdata;
2486 		if (sn == NULL) {
2487 			VI_UNLOCK(devvp);
2488 			return;
2489 		}
2490 		if (lockmgr(&sn->sn_lock,
2491 		    LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
2492 		    VI_MTX(devvp)) == 0)
2493 			break;
2494 	}
2495 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
2496 		vp = ITOV(ip);
2497 		ffs_syncvnode(vp, waitfor, NO_INO_UPDT);
2498 	}
2499 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2500 }
2501 
2502 /*
2503  * Read the specified block into the given buffer.
2504  * Much of this boiler-plate comes from bwrite().
2505  */
2506 static int
2507 readblock(struct vnode *vp,
2508 	struct buf *bp,
2509 	ufs2_daddr_t lbn)
2510 {
2511 	struct inode *ip;
2512 	struct fs *fs;
2513 
2514 	ip = VTOI(vp);
2515 	fs = ITOFS(ip);
2516 
2517 	bp->b_iocmd = BIO_READ;
2518 	bp->b_iooffset = dbtob(fsbtodb(fs, blkstofrags(fs, lbn)));
2519 	bp->b_iodone = bdone;
2520 	g_vfs_strategy(&ITODEVVP(ip)->v_bufobj, bp);
2521 	bufwait(bp);
2522 	return (bp->b_error);
2523 }
2524 
2525 #endif
2526 
2527 /*
2528  * Process file deletes that were deferred by ufs_inactive() due to
2529  * the file system being suspended. Transfer IN_LAZYACCESS into
2530  * IN_MODIFIED for vnodes that were accessed during suspension.
2531  */
2532 void
2533 process_deferred_inactive(struct mount *mp)
2534 {
2535 	struct vnode *vp, *mvp;
2536 	struct inode *ip;
2537 	int error;
2538 
2539 	(void) vn_start_secondary_write(NULL, &mp, V_WAIT);
2540  loop:
2541 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2542 		/*
2543 		 * IN_LAZYACCESS is checked here without holding any
2544 		 * vnode lock, but this flag is set only while holding
2545 		 * vnode interlock.
2546 		 */
2547 		if (vp->v_type == VNON ||
2548 		    ((VTOI(vp)->i_flag & IN_LAZYACCESS) == 0 &&
2549 		    ((vp->v_iflag & VI_OWEINACT) == 0 || vp->v_usecount > 0))) {
2550 			VI_UNLOCK(vp);
2551 			continue;
2552 		}
2553 		vholdl(vp);
2554 retry_vnode:
2555 		error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2556 		if (error != 0) {
2557 			vdrop(vp);
2558 			if (error == ENOENT)
2559 				continue;	/* vnode recycled */
2560 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2561 			goto loop;
2562 		}
2563 		ip = VTOI(vp);
2564 		if ((ip->i_flag & IN_LAZYACCESS) != 0) {
2565 			ip->i_flag &= ~IN_LAZYACCESS;
2566 			UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
2567 		}
2568 		VI_LOCK(vp);
2569 		error = vinactive(vp);
2570 		if (error == ERELOOKUP && vp->v_usecount == 0) {
2571 			VI_UNLOCK(vp);
2572 			VOP_UNLOCK(vp);
2573 			goto retry_vnode;
2574 		}
2575 		VI_UNLOCK(vp);
2576 		VOP_UNLOCK(vp);
2577 		vdrop(vp);
2578 	}
2579 	vn_finished_secondary_write(mp);
2580 }
2581 
2582 #ifndef NO_FFS_SNAPSHOT
2583 
2584 static struct snapdata *
2585 ffs_snapdata_alloc(void)
2586 {
2587 	struct snapdata *sn;
2588 
2589 	/*
2590 	 * Fetch a snapdata from the free list if there is one available.
2591 	 */
2592 	mtx_lock(&snapfree_lock);
2593 	sn = LIST_FIRST(&snapfree);
2594 	if (sn != NULL)
2595 		LIST_REMOVE(sn, sn_link);
2596 	mtx_unlock(&snapfree_lock);
2597 	if (sn != NULL)
2598 		return (sn);
2599 	/*
2600  	 * If there were no free snapdatas allocate one.
2601 	 */
2602 	sn = malloc(sizeof *sn, M_UFSMNT, M_WAITOK | M_ZERO);
2603 	TAILQ_INIT(&sn->sn_head);
2604 	lockinit(&sn->sn_lock, PVFS, "snaplk", VLKTIMEOUT,
2605 	    LK_CANRECURSE | LK_NOSHARE);
2606 	return (sn);
2607 }
2608 
2609 /*
2610  * The snapdata is never freed because we can not be certain that
2611  * there are no threads sleeping on the snap lock.  Persisting
2612  * them permanently avoids costly synchronization in ffs_lock().
2613  */
2614 static void
2615 ffs_snapdata_free(struct snapdata *sn)
2616 {
2617 	mtx_lock(&snapfree_lock);
2618 	LIST_INSERT_HEAD(&snapfree, sn, sn_link);
2619 	mtx_unlock(&snapfree_lock);
2620 }
2621 
2622 /* Try to free snapdata associated with devvp */
2623 static void
2624 try_free_snapdata(struct vnode *devvp)
2625 {
2626 	struct snapdata *sn;
2627 	ufs2_daddr_t *snapblklist;
2628 
2629 	ASSERT_VI_LOCKED(devvp, "try_free_snapdata");
2630 	sn = devvp->v_rdev->si_snapdata;
2631 
2632 	if (sn == NULL || TAILQ_FIRST(&sn->sn_head) != NULL ||
2633 	    (devvp->v_vflag & VV_COPYONWRITE) == 0)
2634 		return;
2635 
2636 	devvp->v_rdev->si_snapdata = NULL;
2637 	devvp->v_vflag &= ~VV_COPYONWRITE;
2638 	lockmgr(&sn->sn_lock, LK_DRAIN|LK_INTERLOCK, VI_MTX(devvp));
2639 	snapblklist = sn->sn_blklist;
2640 	sn->sn_blklist = NULL;
2641 	sn->sn_listsize = 0;
2642 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2643 	if (snapblklist != NULL)
2644 		free(snapblklist, M_UFSMNT);
2645 	ffs_snapdata_free(sn);
2646 	VI_LOCK(devvp);
2647 }
2648 
2649 /*
2650  * Revert a vnode lock from using the snapshot lock back to its own lock.
2651  *
2652  * Aquire a lock on the vnode's own lock and release the lock on the
2653  * snapshot lock. If there are any recursions on the snapshot lock
2654  * get the same number of recursions on the vnode's own lock.
2655  */
2656 static void
2657 revert_snaplock(struct vnode *vp,
2658 	struct vnode *devvp,
2659 	struct snapdata *sn)
2660 {
2661 	int i;
2662 
2663 	ASSERT_VI_LOCKED(devvp, "revert_snaplock");
2664 	/*
2665 	 * Avoid LOR with snapshot lock. The LK_NOWAIT should
2666 	 * never fail as the lock is currently unused. Rather than
2667 	 * panic, we recover by doing the blocking lock.
2668 	 */
2669 	for (i = 0; i <= sn->sn_lock.lk_recurse; i++) {
2670 		if (lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_NOWAIT |
2671 		    LK_INTERLOCK, VI_MTX(devvp)) != 0) {
2672 			printf("revert_snaplock: Unexpected LK_NOWAIT "
2673 			    "failure\n");
2674 			lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_INTERLOCK,
2675 			    VI_MTX(devvp));
2676 		}
2677 		VI_LOCK(devvp);
2678 	}
2679 	KASSERT(vp->v_vnlock == &sn->sn_lock,
2680 	    ("revert_snaplock: lost lock mutation"));
2681 	vp->v_vnlock = &vp->v_lock;
2682 	while (sn->sn_lock.lk_recurse > 0)
2683 		lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2684 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2685 }
2686 
2687 static struct snapdata *
2688 ffs_snapdata_acquire(struct vnode *devvp)
2689 {
2690 	struct snapdata *nsn, *sn;
2691 	int error;
2692 
2693 	/*
2694 	 * Allocate a free snapdata.  This is done before acquiring the
2695 	 * devvp lock to avoid allocation while the devvp interlock is
2696 	 * held.
2697 	 */
2698 	nsn = ffs_snapdata_alloc();
2699 
2700 	for (;;) {
2701 		VI_LOCK(devvp);
2702 		sn = devvp->v_rdev->si_snapdata;
2703 		if (sn == NULL) {
2704 			/*
2705 			 * This is the first snapshot on this
2706 			 * filesystem and we use our pre-allocated
2707 			 * snapdata.  Publish sn with the sn_lock
2708 			 * owned by us, to avoid the race.
2709 			 */
2710 			error = lockmgr(&nsn->sn_lock, LK_EXCLUSIVE |
2711 			    LK_NOWAIT, NULL);
2712 			if (error != 0)
2713 				panic("leaked sn, lockmgr error %d", error);
2714 			sn = devvp->v_rdev->si_snapdata = nsn;
2715 			VI_UNLOCK(devvp);
2716 			nsn = NULL;
2717 			break;
2718 		}
2719 
2720 		/*
2721 		 * There is a snapshots which already exists on this
2722 		 * filesystem, grab a reference to the common lock.
2723 		 */
2724 		error = lockmgr(&sn->sn_lock, LK_INTERLOCK |
2725 		    LK_EXCLUSIVE | LK_SLEEPFAIL, VI_MTX(devvp));
2726 		if (error == 0)
2727 			break;
2728 	}
2729 
2730 	/*
2731 	 * Free any unused snapdata.
2732 	 */
2733 	if (nsn != NULL)
2734 		ffs_snapdata_free(nsn);
2735 
2736 	return (sn);
2737 }
2738 
2739 #endif
2740