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