xref: /freebsd/sys/ufs/ffs/ffs_snapshot.c (revision 81ad6265)
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 #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;
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 		copy_fs->fs_ckhash = ffs_calc_sbhash(copy_fs);
832 		bcopy((char *)copy_fs, &nbp->b_data[loc], (u_int)fs->fs_sbsize);
833 		bawrite(nbp);
834 	}
835 	/*
836 	 * As this is the newest list, it is the most inclusive, so
837 	 * should replace the previous list.
838 	 */
839 	VI_LOCK(devvp);
840 	space = sn->sn_blklist;
841 	sn->sn_blklist = snapblklist;
842 	sn->sn_listsize = snaplistsize;
843 	VI_UNLOCK(devvp);
844 	if (space != NULL)
845 		free(space, M_UFSMNT);
846 done:
847 	free(copy_fs->fs_csp, M_UFSMNT);
848 	free(copy_fs->fs_si, M_UFSMNT);
849 	free(copy_fs, M_UFSMNT);
850 	copy_fs = NULL;
851 out:
852 	NDFREE_PNBUF(&nd);
853 	if (saved_nice > 0) {
854 		struct proc *p;
855 
856 		p = td->td_proc;
857 		PROC_LOCK(p);
858 		sched_nice(td->td_proc, saved_nice);
859 		PROC_UNLOCK(td->td_proc);
860 	}
861 	UFS_LOCK(ump);
862 	if (fs->fs_active != 0) {
863 		free(fs->fs_active, M_DEVBUF);
864 		fs->fs_active = 0;
865 	}
866 	UFS_UNLOCK(ump);
867 	MNT_ILOCK(mp);
868 	mp->mnt_flag = (mp->mnt_flag & MNT_QUOTA) | (flag & ~MNT_QUOTA);
869 	MNT_IUNLOCK(mp);
870 	if (error)
871 		(void) ffs_truncate(vp, (off_t)0, 0, NOCRED);
872 	(void) ffs_syncvnode(vp, MNT_WAIT, 0);
873 	if (error)
874 		vput(vp);
875 	else
876 		VOP_UNLOCK(vp);
877 	vrele(nd.ni_dvp);
878 	vn_finished_write(wrtmp);
879 	process_deferred_inactive(mp);
880 	return (error);
881 }
882 
883 /*
884  * Copy a cylinder group map. All the unallocated blocks are marked
885  * BLK_NOCOPY so that the snapshot knows that it need not copy them
886  * if they are later written. If passno is one, then this is a first
887  * pass, so only setting needs to be done. If passno is 2, then this
888  * is a revision to a previous pass which must be undone as the
889  * replacement pass is done.
890  */
891 static int
892 cgaccount(int cg,
893 	struct vnode *vp,
894 	struct buf *nbp,
895 	int passno)
896 {
897 	struct buf *bp, *ibp;
898 	struct inode *ip;
899 	struct cg *cgp;
900 	struct fs *fs;
901 	ufs2_daddr_t base, numblks;
902 	int error, len, loc, indiroff;
903 
904 	ip = VTOI(vp);
905 	fs = ITOFS(ip);
906 	if ((error = ffs_getcg(fs, ITODEVVP(ip), cg, 0, &bp, &cgp)) != 0)
907 		return (error);
908 	UFS_LOCK(ITOUMP(ip));
909 	ACTIVESET(fs, cg);
910 	/*
911 	 * Recomputation of summary information might not have been performed
912 	 * at mount time.  Sync up summary information for current cylinder
913 	 * group while data is in memory to ensure that result of background
914 	 * fsck is slightly more consistent.
915 	 */
916 	fs->fs_cs(fs, cg) = cgp->cg_cs;
917 	UFS_UNLOCK(ITOUMP(ip));
918 	bcopy(bp->b_data, nbp->b_data, fs->fs_cgsize);
919 	if (fs->fs_cgsize < fs->fs_bsize)
920 		bzero(&nbp->b_data[fs->fs_cgsize],
921 		    fs->fs_bsize - fs->fs_cgsize);
922 	cgp = (struct cg *)nbp->b_data;
923 	bqrelse(bp);
924 	if (passno == 2)
925 		nbp->b_flags |= B_VALIDSUSPWRT;
926 	numblks = howmany(fs->fs_size, fs->fs_frag);
927 	len = howmany(fs->fs_fpg, fs->fs_frag);
928 	base = cgbase(fs, cg) / fs->fs_frag;
929 	if (base + len >= numblks)
930 		len = numblks - base - 1;
931 	loc = 0;
932 	if (base < UFS_NDADDR) {
933 		for ( ; loc < UFS_NDADDR; loc++) {
934 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
935 				DIP_SET(ip, i_db[loc], BLK_NOCOPY);
936 			else if (passno == 2 && DIP(ip, i_db[loc])== BLK_NOCOPY)
937 				DIP_SET(ip, i_db[loc], 0);
938 			else if (passno == 1 && DIP(ip, i_db[loc])== BLK_NOCOPY)
939 				panic("ffs_snapshot: lost direct block");
940 		}
941 	}
942 	error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(base + loc)),
943 	    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
944 	if (error) {
945 		goto out;
946 	}
947 	indiroff = (base + loc - UFS_NDADDR) % NINDIR(fs);
948 	for ( ; loc < len; loc++, indiroff++) {
949 		if (indiroff >= NINDIR(fs)) {
950 			if (passno == 2)
951 				ibp->b_flags |= B_VALIDSUSPWRT;
952 			bawrite(ibp);
953 			error = UFS_BALLOC(vp,
954 			    lblktosize(fs, (off_t)(base + loc)),
955 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
956 			if (error) {
957 				goto out;
958 			}
959 			indiroff = 0;
960 		}
961 		if (I_IS_UFS1(ip)) {
962 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
963 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
964 				    BLK_NOCOPY;
965 			else if (passno == 2 && ((ufs1_daddr_t *)(ibp->b_data))
966 			    [indiroff] == BLK_NOCOPY)
967 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = 0;
968 			else if (passno == 1 && ((ufs1_daddr_t *)(ibp->b_data))
969 			    [indiroff] == BLK_NOCOPY)
970 				panic("ffs_snapshot: lost indirect block");
971 			continue;
972 		}
973 		if (ffs_isblock(fs, cg_blksfree(cgp), loc))
974 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = BLK_NOCOPY;
975 		else if (passno == 2 &&
976 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
977 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = 0;
978 		else if (passno == 1 &&
979 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
980 			panic("ffs_snapshot: lost indirect block");
981 	}
982 	if (passno == 2)
983 		ibp->b_flags |= B_VALIDSUSPWRT;
984 	bdwrite(ibp);
985 out:
986 	/*
987 	 * We have to calculate the crc32c here rather than just setting the
988 	 * BX_CYLGRP b_xflags because the allocation of the block for the
989 	 * the cylinder group map will always be a full size block (fs_bsize)
990 	 * even though the cylinder group may be smaller (fs_cgsize). The
991 	 * crc32c must be computed only over fs_cgsize whereas the BX_CYLGRP
992 	 * flag causes it to be computed over the size of the buffer.
993 	 */
994 	if ((fs->fs_metackhash & CK_CYLGRP) != 0) {
995 		((struct cg *)nbp->b_data)->cg_ckhash = 0;
996 		((struct cg *)nbp->b_data)->cg_ckhash =
997 		    calculate_crc32c(~0L, nbp->b_data, fs->fs_cgsize);
998 	}
999 	return (error);
1000 }
1001 
1002 /*
1003  * Before expunging a snapshot inode, note all the
1004  * blocks that it claims with BLK_SNAP so that fsck will
1005  * be able to account for those blocks properly and so
1006  * that this snapshot knows that it need not copy them
1007  * if the other snapshot holding them is freed. This code
1008  * is reproduced once each for UFS1 and UFS2.
1009  */
1010 static int
1011 expunge_ufs1(struct vnode *snapvp,
1012 	struct inode *cancelip,
1013 	struct fs *fs,
1014 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
1015 	    struct fs *, ufs_lbn_t, int),
1016 	int expungetype,
1017 	int clearmode)
1018 {
1019 	int i, error, indiroff;
1020 	ufs_lbn_t lbn, rlbn;
1021 	ufs2_daddr_t len, blkno, numblks, blksperindir;
1022 	struct ufs1_dinode *dip;
1023 	struct thread *td = curthread;
1024 	struct buf *bp;
1025 
1026 	/*
1027 	 * Prepare to expunge the inode. If its inode block has not
1028 	 * yet been copied, then allocate and fill the copy.
1029 	 */
1030 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1031 	blkno = 0;
1032 	if (lbn < UFS_NDADDR) {
1033 		blkno = VTOI(snapvp)->i_din1->di_db[lbn];
1034 	} else {
1035 		if (DOINGSOFTDEP(snapvp))
1036 			softdep_prealloc(snapvp, MNT_WAIT);
1037 		td->td_pflags |= TDP_COWINPROGRESS;
1038 		error = ffs_balloc_ufs1(snapvp, lblktosize(fs, (off_t)lbn),
1039 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1040 		td->td_pflags &= ~TDP_COWINPROGRESS;
1041 		if (error)
1042 			return (error);
1043 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1044 		blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
1045 		bqrelse(bp);
1046 	}
1047 	if (blkno != 0) {
1048 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1049 			return (error);
1050 	} else {
1051 		error = ffs_balloc_ufs1(snapvp, lblktosize(fs, (off_t)lbn),
1052 		    fs->fs_bsize, KERNCRED, 0, &bp);
1053 		if (error)
1054 			return (error);
1055 		if ((error = readblock(snapvp, bp, lbn)) != 0)
1056 			return (error);
1057 	}
1058 	/*
1059 	 * Set a snapshot inode to be a zero length file, regular files
1060 	 * or unlinked snapshots to be completely unallocated.
1061 	 */
1062 	dip = (struct ufs1_dinode *)bp->b_data +
1063 	    ino_to_fsbo(fs, cancelip->i_number);
1064 	if (clearmode || cancelip->i_effnlink == 0)
1065 		dip->di_mode = 0;
1066 	dip->di_size = 0;
1067 	dip->di_blocks = 0;
1068 	dip->di_flags &= ~SF_SNAPSHOT;
1069 	bzero(dip->di_db, UFS_NDADDR * sizeof(ufs1_daddr_t));
1070 	bzero(dip->di_ib, UFS_NIADDR * sizeof(ufs1_daddr_t));
1071 	bdwrite(bp);
1072 	/*
1073 	 * Now go through and expunge all the blocks in the file
1074 	 * using the function requested.
1075 	 */
1076 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1077 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_db[0],
1078 	    &cancelip->i_din1->di_db[UFS_NDADDR], fs, 0, expungetype)))
1079 		return (error);
1080 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_ib[0],
1081 	    &cancelip->i_din1->di_ib[UFS_NIADDR], fs, -1, expungetype)))
1082 		return (error);
1083 	blksperindir = 1;
1084 	lbn = -UFS_NDADDR;
1085 	len = numblks - UFS_NDADDR;
1086 	rlbn = UFS_NDADDR;
1087 	for (i = 0; len > 0 && i < UFS_NIADDR; i++) {
1088 		error = indiracct_ufs1(snapvp, ITOV(cancelip), i,
1089 		    cancelip->i_din1->di_ib[i], lbn, rlbn, len,
1090 		    blksperindir, fs, acctfunc, expungetype);
1091 		if (error)
1092 			return (error);
1093 		blksperindir *= NINDIR(fs);
1094 		lbn -= blksperindir + 1;
1095 		len -= blksperindir;
1096 		rlbn += blksperindir;
1097 	}
1098 	return (0);
1099 }
1100 
1101 /*
1102  * Descend an indirect block chain for vnode cancelvp accounting for all
1103  * its indirect blocks in snapvp.
1104  */
1105 static int
1106 indiracct_ufs1(struct vnode *snapvp,
1107 	struct vnode *cancelvp,
1108 	int level,
1109 	ufs1_daddr_t blkno,
1110 	ufs_lbn_t lbn,
1111 	ufs_lbn_t rlbn,
1112 	ufs_lbn_t remblks,
1113 	ufs_lbn_t blksperindir,
1114 	struct fs *fs,
1115 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
1116 	    struct fs *, ufs_lbn_t, int),
1117 	int expungetype)
1118 {
1119 	int error, num, i;
1120 	ufs_lbn_t subblksperindir;
1121 	struct indir indirs[UFS_NIADDR + 2];
1122 	ufs1_daddr_t last, *bap;
1123 	struct buf *bp;
1124 
1125 	if (blkno == 0) {
1126 		if (expungetype == BLK_NOCOPY)
1127 			return (0);
1128 		panic("indiracct_ufs1: missing indir");
1129 	}
1130 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1131 		return (error);
1132 	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
1133 		panic("indiracct_ufs1: botched params");
1134 	/*
1135 	 * We have to expand bread here since it will deadlock looking
1136 	 * up the block number for any blocks that are not in the cache.
1137 	 */
1138 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0, 0);
1139 	bp->b_blkno = fsbtodb(fs, blkno);
1140 	if ((bp->b_flags & (B_DONE | B_DELWRI)) == 0 &&
1141 	    (error = readblock(cancelvp, bp, fragstoblks(fs, blkno)))) {
1142 		brelse(bp);
1143 		return (error);
1144 	}
1145 	/*
1146 	 * Account for the block pointers in this indirect block.
1147 	 */
1148 	last = howmany(remblks, blksperindir);
1149 	if (last > NINDIR(fs))
1150 		last = NINDIR(fs);
1151 	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK);
1152 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1153 	bqrelse(bp);
1154 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1155 	    level == 0 ? rlbn : -1, expungetype);
1156 	if (error || level == 0)
1157 		goto out;
1158 	/*
1159 	 * Account for the block pointers in each of the indirect blocks
1160 	 * in the levels below us.
1161 	 */
1162 	subblksperindir = blksperindir / NINDIR(fs);
1163 	for (lbn++, level--, i = 0; i < last; i++) {
1164 		error = indiracct_ufs1(snapvp, cancelvp, level, bap[i], lbn,
1165 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1166 		if (error)
1167 			goto out;
1168 		rlbn += blksperindir;
1169 		lbn -= blksperindir;
1170 		remblks -= blksperindir;
1171 	}
1172 out:
1173 	free(bap, M_DEVBUF);
1174 	return (error);
1175 }
1176 
1177 /*
1178  * Do both snap accounting and map accounting.
1179  */
1180 static int
1181 fullacct_ufs1(struct vnode *vp,
1182 	ufs1_daddr_t *oldblkp,
1183 	ufs1_daddr_t *lastblkp,
1184 	struct fs *fs,
1185 	ufs_lbn_t lblkno,
1186 	int exptype)	/* BLK_SNAP or BLK_NOCOPY */
1187 {
1188 	int error;
1189 
1190 	if ((error = snapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1191 		return (error);
1192 	return (mapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1193 }
1194 
1195 /*
1196  * Identify a set of blocks allocated in a snapshot inode.
1197  */
1198 static int
1199 snapacct_ufs1(struct vnode *vp,
1200 	ufs1_daddr_t *oldblkp,
1201 	ufs1_daddr_t *lastblkp,
1202 	struct fs *fs,
1203 	ufs_lbn_t lblkno,
1204 	int expungetype)	/* BLK_SNAP or BLK_NOCOPY */
1205 {
1206 	struct inode *ip = VTOI(vp);
1207 	ufs1_daddr_t blkno, *blkp;
1208 	ufs_lbn_t lbn;
1209 	struct buf *ibp;
1210 	int error;
1211 
1212 	for ( ; oldblkp < lastblkp; oldblkp++) {
1213 		blkno = *oldblkp;
1214 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1215 			continue;
1216 		lbn = fragstoblks(fs, blkno);
1217 		if (lbn < UFS_NDADDR) {
1218 			blkp = &ip->i_din1->di_db[lbn];
1219 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1220 		} else {
1221 			error = ffs_balloc_ufs1(vp, lblktosize(fs, (off_t)lbn),
1222 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1223 			if (error)
1224 				return (error);
1225 			blkp = &((ufs1_daddr_t *)(ibp->b_data))
1226 			    [(lbn - UFS_NDADDR) % NINDIR(fs)];
1227 		}
1228 		/*
1229 		 * If we are expunging a snapshot vnode and we
1230 		 * find a block marked BLK_NOCOPY, then it is
1231 		 * one that has been allocated to this snapshot after
1232 		 * we took our current snapshot and can be ignored.
1233 		 */
1234 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1235 			if (lbn >= UFS_NDADDR)
1236 				brelse(ibp);
1237 		} else {
1238 			if (*blkp != 0)
1239 				panic("snapacct_ufs1: bad block");
1240 			*blkp = expungetype;
1241 			if (lbn >= UFS_NDADDR)
1242 				bdwrite(ibp);
1243 		}
1244 	}
1245 	return (0);
1246 }
1247 
1248 /*
1249  * Account for a set of blocks allocated in a snapshot inode.
1250  */
1251 static int
1252 mapacct_ufs1(struct vnode *vp,
1253 	ufs1_daddr_t *oldblkp,
1254 	ufs1_daddr_t *lastblkp,
1255 	struct fs *fs,
1256 	ufs_lbn_t lblkno,
1257 	int expungetype)
1258 {
1259 	ufs1_daddr_t blkno;
1260 	struct inode *ip;
1261 	ino_t inum;
1262 	int acctit;
1263 
1264 	ip = VTOI(vp);
1265 	inum = ip->i_number;
1266 	if (lblkno == -1)
1267 		acctit = 0;
1268 	else
1269 		acctit = 1;
1270 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1271 		blkno = *oldblkp;
1272 		if (blkno == 0 || blkno == BLK_NOCOPY)
1273 			continue;
1274 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
1275 			*ip->i_snapblklist++ = lblkno;
1276 		if (blkno == BLK_SNAP)
1277 			blkno = blkstofrags(fs, lblkno);
1278 		ffs_blkfree(ITOUMP(ip), fs, vp, blkno, fs->fs_bsize, inum,
1279 		    vp->v_type, NULL, SINGLETON_KEY);
1280 	}
1281 	return (0);
1282 }
1283 
1284 /*
1285  * Before expunging a snapshot inode, note all the
1286  * blocks that it claims with BLK_SNAP so that fsck will
1287  * be able to account for those blocks properly and so
1288  * that this snapshot knows that it need not copy them
1289  * if the other snapshot holding them is freed. This code
1290  * is reproduced once each for UFS1 and UFS2.
1291  */
1292 static int
1293 expunge_ufs2(struct vnode *snapvp,
1294 	struct inode *cancelip,
1295 	struct fs *fs,
1296 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1297 	    struct fs *, ufs_lbn_t, int),
1298 	int expungetype,
1299 	int clearmode)
1300 {
1301 	int i, error, indiroff;
1302 	ufs_lbn_t lbn, rlbn;
1303 	ufs2_daddr_t len, blkno, numblks, blksperindir;
1304 	struct ufs2_dinode *dip;
1305 	struct thread *td = curthread;
1306 	struct buf *bp;
1307 
1308 	/*
1309 	 * Prepare to expunge the inode. If its inode block has not
1310 	 * yet been copied, then allocate and fill the copy.
1311 	 */
1312 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1313 	blkno = 0;
1314 	if (lbn < UFS_NDADDR) {
1315 		blkno = VTOI(snapvp)->i_din2->di_db[lbn];
1316 	} else {
1317 		if (DOINGSOFTDEP(snapvp))
1318 			softdep_prealloc(snapvp, MNT_WAIT);
1319 		td->td_pflags |= TDP_COWINPROGRESS;
1320 		error = ffs_balloc_ufs2(snapvp, lblktosize(fs, (off_t)lbn),
1321 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1322 		td->td_pflags &= ~TDP_COWINPROGRESS;
1323 		if (error)
1324 			return (error);
1325 		indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1326 		blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
1327 		bqrelse(bp);
1328 	}
1329 	if (blkno != 0) {
1330 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1331 			return (error);
1332 	} else {
1333 		error = ffs_balloc_ufs2(snapvp, lblktosize(fs, (off_t)lbn),
1334 		    fs->fs_bsize, KERNCRED, 0, &bp);
1335 		if (error)
1336 			return (error);
1337 		if ((error = readblock(snapvp, bp, lbn)) != 0)
1338 			return (error);
1339 	}
1340 	/*
1341 	 * Set a snapshot inode to be a zero length file, regular files
1342 	 * to be completely unallocated.
1343 	 */
1344 	dip = (struct ufs2_dinode *)bp->b_data +
1345 	    ino_to_fsbo(fs, cancelip->i_number);
1346 	dip->di_size = 0;
1347 	dip->di_blocks = 0;
1348 	dip->di_flags &= ~SF_SNAPSHOT;
1349 	bzero(dip->di_db, UFS_NDADDR * sizeof(ufs2_daddr_t));
1350 	bzero(dip->di_ib, UFS_NIADDR * sizeof(ufs2_daddr_t));
1351 	if (clearmode || cancelip->i_effnlink == 0)
1352 		dip->di_mode = 0;
1353 	else
1354 		ffs_update_dinode_ckhash(fs, dip);
1355 	bdwrite(bp);
1356 	/*
1357 	 * Now go through and expunge all the blocks in the file
1358 	 * using the function requested.
1359 	 */
1360 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1361 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_db[0],
1362 	    &cancelip->i_din2->di_db[UFS_NDADDR], fs, 0, expungetype)))
1363 		return (error);
1364 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_ib[0],
1365 	    &cancelip->i_din2->di_ib[UFS_NIADDR], fs, -1, expungetype)))
1366 		return (error);
1367 	blksperindir = 1;
1368 	lbn = -UFS_NDADDR;
1369 	len = numblks - UFS_NDADDR;
1370 	rlbn = UFS_NDADDR;
1371 	for (i = 0; len > 0 && i < UFS_NIADDR; i++) {
1372 		error = indiracct_ufs2(snapvp, ITOV(cancelip), i,
1373 		    cancelip->i_din2->di_ib[i], lbn, rlbn, len,
1374 		    blksperindir, fs, acctfunc, expungetype);
1375 		if (error)
1376 			return (error);
1377 		blksperindir *= NINDIR(fs);
1378 		lbn -= blksperindir + 1;
1379 		len -= blksperindir;
1380 		rlbn += blksperindir;
1381 	}
1382 	return (0);
1383 }
1384 
1385 /*
1386  * Descend an indirect block chain for vnode cancelvp accounting for all
1387  * its indirect blocks in snapvp.
1388  */
1389 static int
1390 indiracct_ufs2(struct vnode *snapvp,
1391 	struct vnode *cancelvp,
1392 	int level,
1393 	ufs2_daddr_t blkno,
1394 	ufs_lbn_t lbn,
1395 	ufs_lbn_t rlbn,
1396 	ufs_lbn_t remblks,
1397 	ufs_lbn_t blksperindir,
1398 	struct fs *fs,
1399 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1400 	    struct fs *, ufs_lbn_t, int),
1401 	int expungetype)
1402 {
1403 	int error, num, i;
1404 	ufs_lbn_t subblksperindir;
1405 	struct indir indirs[UFS_NIADDR + 2];
1406 	ufs2_daddr_t last, *bap;
1407 	struct buf *bp;
1408 
1409 	if (blkno == 0) {
1410 		if (expungetype == BLK_NOCOPY)
1411 			return (0);
1412 		panic("indiracct_ufs2: missing indir");
1413 	}
1414 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1415 		return (error);
1416 	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
1417 		panic("indiracct_ufs2: botched params");
1418 	/*
1419 	 * We have to expand bread here since it will deadlock looking
1420 	 * up the block number for any blocks that are not in the cache.
1421 	 */
1422 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0, 0);
1423 	bp->b_blkno = fsbtodb(fs, blkno);
1424 	if ((bp->b_flags & B_CACHE) == 0 &&
1425 	    (error = readblock(cancelvp, bp, fragstoblks(fs, blkno)))) {
1426 		brelse(bp);
1427 		return (error);
1428 	}
1429 	/*
1430 	 * Account for the block pointers in this indirect block.
1431 	 */
1432 	last = howmany(remblks, blksperindir);
1433 	if (last > NINDIR(fs))
1434 		last = NINDIR(fs);
1435 	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK);
1436 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1437 	bqrelse(bp);
1438 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1439 	    level == 0 ? rlbn : -1, expungetype);
1440 	if (error || level == 0)
1441 		goto out;
1442 	/*
1443 	 * Account for the block pointers in each of the indirect blocks
1444 	 * in the levels below us.
1445 	 */
1446 	subblksperindir = blksperindir / NINDIR(fs);
1447 	for (lbn++, level--, i = 0; i < last; i++) {
1448 		error = indiracct_ufs2(snapvp, cancelvp, level, bap[i], lbn,
1449 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1450 		if (error)
1451 			goto out;
1452 		rlbn += blksperindir;
1453 		lbn -= blksperindir;
1454 		remblks -= blksperindir;
1455 	}
1456 out:
1457 	free(bap, M_DEVBUF);
1458 	return (error);
1459 }
1460 
1461 /*
1462  * Do both snap accounting and map accounting.
1463  */
1464 static int
1465 fullacct_ufs2(struct vnode *vp,
1466 	ufs2_daddr_t *oldblkp,
1467 	ufs2_daddr_t *lastblkp,
1468 	struct fs *fs,
1469 	ufs_lbn_t lblkno,
1470 	int exptype)	/* BLK_SNAP or BLK_NOCOPY */
1471 {
1472 	int error;
1473 
1474 	if ((error = snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1475 		return (error);
1476 	return (mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1477 }
1478 
1479 /*
1480  * Identify a set of blocks allocated in a snapshot inode.
1481  */
1482 static int
1483 snapacct_ufs2(struct vnode *vp,
1484 	ufs2_daddr_t *oldblkp,
1485 	ufs2_daddr_t *lastblkp,
1486 	struct fs *fs,
1487 	ufs_lbn_t lblkno,
1488 	int expungetype)	/* BLK_SNAP or BLK_NOCOPY */
1489 {
1490 	struct inode *ip = VTOI(vp);
1491 	ufs2_daddr_t blkno, *blkp;
1492 	ufs_lbn_t lbn;
1493 	struct buf *ibp;
1494 	int error;
1495 
1496 	for ( ; oldblkp < lastblkp; oldblkp++) {
1497 		blkno = *oldblkp;
1498 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1499 			continue;
1500 		lbn = fragstoblks(fs, blkno);
1501 		if (lbn < UFS_NDADDR) {
1502 			blkp = &ip->i_din2->di_db[lbn];
1503 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1504 		} else {
1505 			error = ffs_balloc_ufs2(vp, lblktosize(fs, (off_t)lbn),
1506 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1507 			if (error)
1508 				return (error);
1509 			blkp = &((ufs2_daddr_t *)(ibp->b_data))
1510 			    [(lbn - UFS_NDADDR) % NINDIR(fs)];
1511 		}
1512 		/*
1513 		 * If we are expunging a snapshot vnode and we
1514 		 * find a block marked BLK_NOCOPY, then it is
1515 		 * one that has been allocated to this snapshot after
1516 		 * we took our current snapshot and can be ignored.
1517 		 */
1518 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1519 			if (lbn >= UFS_NDADDR)
1520 				brelse(ibp);
1521 		} else {
1522 			if (*blkp != 0)
1523 				panic("snapacct_ufs2: bad block");
1524 			*blkp = expungetype;
1525 			if (lbn >= UFS_NDADDR)
1526 				bdwrite(ibp);
1527 		}
1528 	}
1529 	return (0);
1530 }
1531 
1532 /*
1533  * Account for a set of blocks allocated in a snapshot inode.
1534  */
1535 static int
1536 mapacct_ufs2(struct vnode *vp,
1537 	ufs2_daddr_t *oldblkp,
1538 	ufs2_daddr_t *lastblkp,
1539 	struct fs *fs,
1540 	ufs_lbn_t lblkno,
1541 	int expungetype)
1542 {
1543 	ufs2_daddr_t blkno;
1544 	struct inode *ip;
1545 	ino_t inum;
1546 	int acctit;
1547 
1548 	ip = VTOI(vp);
1549 	inum = ip->i_number;
1550 	if (lblkno == -1)
1551 		acctit = 0;
1552 	else
1553 		acctit = 1;
1554 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1555 		blkno = *oldblkp;
1556 		if (blkno == 0 || blkno == BLK_NOCOPY)
1557 			continue;
1558 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP &&
1559 		    lblkno >= UFS_NDADDR)
1560 			*ip->i_snapblklist++ = lblkno;
1561 		if (blkno == BLK_SNAP)
1562 			blkno = blkstofrags(fs, lblkno);
1563 		ffs_blkfree(ITOUMP(ip), fs, vp, blkno, fs->fs_bsize, inum,
1564 		    vp->v_type, NULL, SINGLETON_KEY);
1565 	}
1566 	return (0);
1567 }
1568 
1569 /*
1570  * Decrement extra reference on snapshot when last name is removed.
1571  * It will not be freed until the last open reference goes away.
1572  */
1573 void
1574 ffs_snapgone(struct inode *ip)
1575 {
1576 	struct inode *xp;
1577 	struct fs *fs;
1578 	int snaploc;
1579 	struct snapdata *sn;
1580 	struct ufsmount *ump;
1581 
1582 	/*
1583 	 * Find snapshot in incore list.
1584 	 */
1585 	xp = NULL;
1586 	sn = ITODEVVP(ip)->v_rdev->si_snapdata;
1587 	if (sn != NULL)
1588 		TAILQ_FOREACH(xp, &sn->sn_head, i_nextsnap)
1589 			if (xp == ip)
1590 				break;
1591 	if (xp != NULL)
1592 		vrele(ITOV(ip));
1593 #ifdef DIAGNOSTIC
1594 	else if (snapdebug)
1595 		printf("ffs_snapgone: lost snapshot vnode %ju\n",
1596 		    (uintmax_t)ip->i_number);
1597 #endif
1598 	/*
1599 	 * Delete snapshot inode from superblock. Keep list dense.
1600 	 */
1601 	ump = ITOUMP(ip);
1602 	fs = ump->um_fs;
1603 	UFS_LOCK(ump);
1604 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
1605 		if (fs->fs_snapinum[snaploc] == ip->i_number)
1606 			break;
1607 	if (snaploc < FSMAXSNAP) {
1608 		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
1609 			if (fs->fs_snapinum[snaploc] == 0)
1610 				break;
1611 			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
1612 		}
1613 		fs->fs_snapinum[snaploc - 1] = 0;
1614 	}
1615 	UFS_UNLOCK(ump);
1616 }
1617 
1618 /*
1619  * Prepare a snapshot file for being removed.
1620  */
1621 void
1622 ffs_snapremove(struct vnode *vp)
1623 {
1624 	struct inode *ip;
1625 	struct vnode *devvp;
1626 	struct buf *ibp;
1627 	struct fs *fs;
1628 	ufs2_daddr_t numblks, blkno, dblk;
1629 	int error, last, loc;
1630 	struct snapdata *sn;
1631 
1632 	ip = VTOI(vp);
1633 	fs = ITOFS(ip);
1634 	devvp = ITODEVVP(ip);
1635 	/*
1636 	 * If active, delete from incore list (this snapshot may
1637 	 * already have been in the process of being deleted, so
1638 	 * would not have been active).
1639 	 *
1640 	 * Clear copy-on-write flag if last snapshot.
1641 	 */
1642 	VI_LOCK(devvp);
1643 	if (ip->i_nextsnap.tqe_prev != 0) {
1644 		sn = devvp->v_rdev->si_snapdata;
1645 		TAILQ_REMOVE(&sn->sn_head, ip, i_nextsnap);
1646 		ip->i_nextsnap.tqe_prev = 0;
1647 		revert_snaplock(vp, devvp, sn);
1648 		try_free_snapdata(devvp);
1649 	}
1650 	VI_UNLOCK(devvp);
1651 	/*
1652 	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
1653 	 * snapshots that want them (see ffs_snapblkfree below).
1654 	 */
1655 	for (blkno = 1; blkno < UFS_NDADDR; blkno++) {
1656 		dblk = DIP(ip, i_db[blkno]);
1657 		if (dblk == 0)
1658 			continue;
1659 		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1660 			DIP_SET(ip, i_db[blkno], 0);
1661 		else if ((dblk == blkstofrags(fs, blkno) &&
1662 		     ffs_snapblkfree(fs, ITODEVVP(ip), dblk, fs->fs_bsize,
1663 		     ip->i_number, vp->v_type, NULL))) {
1664 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) -
1665 			    btodb(fs->fs_bsize));
1666 			DIP_SET(ip, i_db[blkno], 0);
1667 		}
1668 	}
1669 	numblks = howmany(ip->i_size, fs->fs_bsize);
1670 	for (blkno = UFS_NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
1671 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
1672 		    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1673 		if (error)
1674 			continue;
1675 		if (fs->fs_size - blkno > NINDIR(fs))
1676 			last = NINDIR(fs);
1677 		else
1678 			last = fs->fs_size - blkno;
1679 		for (loc = 0; loc < last; loc++) {
1680 			if (I_IS_UFS1(ip)) {
1681 				dblk = ((ufs1_daddr_t *)(ibp->b_data))[loc];
1682 				if (dblk == 0)
1683 					continue;
1684 				if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1685 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1686 				else if ((dblk == blkstofrags(fs, blkno) &&
1687 				     ffs_snapblkfree(fs, ITODEVVP(ip), dblk,
1688 				     fs->fs_bsize, ip->i_number, vp->v_type,
1689 				     NULL))) {
1690 					ip->i_din1->di_blocks -=
1691 					    btodb(fs->fs_bsize);
1692 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1693 				}
1694 				continue;
1695 			}
1696 			dblk = ((ufs2_daddr_t *)(ibp->b_data))[loc];
1697 			if (dblk == 0)
1698 				continue;
1699 			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1700 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1701 			else if ((dblk == blkstofrags(fs, blkno) &&
1702 			     ffs_snapblkfree(fs, ITODEVVP(ip), dblk,
1703 			     fs->fs_bsize, ip->i_number, vp->v_type, NULL))) {
1704 				ip->i_din2->di_blocks -= btodb(fs->fs_bsize);
1705 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1706 			}
1707 		}
1708 		bawrite(ibp);
1709 	}
1710 	/*
1711 	 * Clear snapshot flag and drop reference.
1712 	 */
1713 	ip->i_flags &= ~SF_SNAPSHOT;
1714 	DIP_SET(ip, i_flags, ip->i_flags);
1715 	UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1716 	/*
1717 	 * The dirtied indirects must be written out before
1718 	 * softdep_setup_freeblocks() is called.  Otherwise indir_trunc()
1719 	 * may find indirect pointers using the magic BLK_* values.
1720 	 */
1721 	if (DOINGSOFTDEP(vp))
1722 		ffs_syncvnode(vp, MNT_WAIT, 0);
1723 #ifdef QUOTA
1724 	/*
1725 	 * Reenable disk quotas for ex-snapshot file.
1726 	 */
1727 	if (!getinoquota(ip))
1728 		(void) chkdq(ip, DIP(ip, i_blocks), KERNCRED, FORCE);
1729 #endif
1730 }
1731 
1732 /*
1733  * Notification that a block is being freed. Return zero if the free
1734  * should be allowed to proceed. Return non-zero if the snapshot file
1735  * wants to claim the block. The block will be claimed if it is an
1736  * uncopied part of one of the snapshots. It will be freed if it is
1737  * either a BLK_NOCOPY or has already been copied in all of the snapshots.
1738  * If a fragment is being freed, then all snapshots that care about
1739  * it must make a copy since a snapshot file can only claim full sized
1740  * blocks. Note that if more than one snapshot file maps the block,
1741  * we can pick one at random to claim it. Since none of the snapshots
1742  * can change, we are assurred that they will all see the same unmodified
1743  * image. When deleting a snapshot file (see ffs_snapremove above), we
1744  * must push any of these claimed blocks to one of the other snapshots
1745  * that maps it. These claimed blocks are easily identified as they will
1746  * have a block number equal to their logical block number within the
1747  * snapshot. A copied block can never have this property because they
1748  * must always have been allocated from a BLK_NOCOPY location.
1749  */
1750 int
1751 ffs_snapblkfree(struct fs *fs,
1752 	struct vnode *devvp,
1753 	ufs2_daddr_t bno,
1754 	long size,
1755 	ino_t inum,
1756 	enum vtype vtype,
1757 	struct workhead *wkhd)
1758 {
1759 	struct buf *ibp, *cbp, *savedcbp = NULL;
1760 	struct thread *td = curthread;
1761 	struct inode *ip;
1762 	struct vnode *vp = NULL;
1763 	ufs_lbn_t lbn;
1764 	ufs2_daddr_t blkno;
1765 	int indiroff = 0, error = 0, claimedblk = 0;
1766 	struct snapdata *sn;
1767 
1768 	lbn = fragstoblks(fs, bno);
1769 retry:
1770 	VI_LOCK(devvp);
1771 	sn = devvp->v_rdev->si_snapdata;
1772 	if (sn == NULL) {
1773 		VI_UNLOCK(devvp);
1774 		return (0);
1775 	}
1776 
1777 	/*
1778 	 * Use LK_SLEEPFAIL because sn might be freed under us while
1779 	 * both devvp interlock and snaplk are not owned.
1780 	 */
1781 	if (lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1782 	    VI_MTX(devvp)) != 0)
1783 		goto retry;
1784 
1785 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
1786 		vp = ITOV(ip);
1787 		if (DOINGSOFTDEP(vp))
1788 			softdep_prealloc(vp, MNT_WAIT);
1789 		/*
1790 		 * Lookup block being written.
1791 		 */
1792 		if (lbn < UFS_NDADDR) {
1793 			blkno = DIP(ip, i_db[lbn]);
1794 		} else {
1795 			td->td_pflags |= TDP_COWINPROGRESS;
1796 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1797 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1798 			td->td_pflags &= ~TDP_COWINPROGRESS;
1799 			if (error)
1800 				break;
1801 			indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1802 			if (I_IS_UFS1(ip))
1803 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1804 			else
1805 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1806 		}
1807 		/*
1808 		 * Check to see if block needs to be copied.
1809 		 */
1810 		if (blkno == 0) {
1811 			/*
1812 			 * A block that we map is being freed. If it has not
1813 			 * been claimed yet, we will claim or copy it (below).
1814 			 */
1815 			claimedblk = 1;
1816 		} else if (blkno == BLK_SNAP) {
1817 			/*
1818 			 * No previous snapshot claimed the block,
1819 			 * so it will be freed and become a BLK_NOCOPY
1820 			 * (don't care) for us.
1821 			 */
1822 			if (claimedblk)
1823 				panic("snapblkfree: inconsistent block type");
1824 			if (lbn < UFS_NDADDR) {
1825 				DIP_SET(ip, i_db[lbn], BLK_NOCOPY);
1826 				UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1827 			} else if (I_IS_UFS1(ip)) {
1828 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
1829 				    BLK_NOCOPY;
1830 				bdwrite(ibp);
1831 			} else {
1832 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] =
1833 				    BLK_NOCOPY;
1834 				bdwrite(ibp);
1835 			}
1836 			continue;
1837 		} else /* BLK_NOCOPY or default */ {
1838 			/*
1839 			 * If the snapshot has already copied the block
1840 			 * (default), or does not care about the block,
1841 			 * it is not needed.
1842 			 */
1843 			if (lbn >= UFS_NDADDR)
1844 				bqrelse(ibp);
1845 			continue;
1846 		}
1847 		/*
1848 		 * If this is a full size block, we will just grab it
1849 		 * and assign it to the snapshot inode. Otherwise we
1850 		 * will proceed to copy it. See explanation for this
1851 		 * routine as to why only a single snapshot needs to
1852 		 * claim this block.
1853 		 */
1854 		if (size == fs->fs_bsize) {
1855 #ifdef DIAGNOSTIC
1856 			if (snapdebug)
1857 				printf("%s %ju lbn %jd from inum %ju\n",
1858 				    "Grabonremove: snapino",
1859 				    (uintmax_t)ip->i_number,
1860 				    (intmax_t)lbn, (uintmax_t)inum);
1861 #endif
1862 			/*
1863 			 * If journaling is tracking this write we must add
1864 			 * the work to the inode or indirect being written.
1865 			 */
1866 			if (wkhd != NULL) {
1867 				if (lbn < UFS_NDADDR)
1868 					softdep_inode_append(ip,
1869 					    curthread->td_ucred, wkhd);
1870 				else
1871 					softdep_buf_append(ibp, wkhd);
1872 			}
1873 			if (lbn < UFS_NDADDR) {
1874 				DIP_SET(ip, i_db[lbn], bno);
1875 			} else if (I_IS_UFS1(ip)) {
1876 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = bno;
1877 				bdwrite(ibp);
1878 			} else {
1879 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] = bno;
1880 				bdwrite(ibp);
1881 			}
1882 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + btodb(size));
1883 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
1884 			lockmgr(vp->v_vnlock, LK_RELEASE, NULL);
1885 			return (1);
1886 		}
1887 		if (lbn >= UFS_NDADDR)
1888 			bqrelse(ibp);
1889 		/*
1890 		 * Allocate the block into which to do the copy. Note that this
1891 		 * allocation will never require any additional allocations for
1892 		 * the snapshot inode.
1893 		 */
1894 		td->td_pflags |= TDP_COWINPROGRESS;
1895 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1896 		    fs->fs_bsize, KERNCRED, 0, &cbp);
1897 		td->td_pflags &= ~TDP_COWINPROGRESS;
1898 		if (error)
1899 			break;
1900 #ifdef DIAGNOSTIC
1901 		if (snapdebug)
1902 			printf("%s%ju lbn %jd %s %ju size %ld to blkno %jd\n",
1903 			    "Copyonremove: snapino ", (uintmax_t)ip->i_number,
1904 			    (intmax_t)lbn, "for inum", (uintmax_t)inum, size,
1905 			    (intmax_t)cbp->b_blkno);
1906 #endif
1907 		/*
1908 		 * If we have already read the old block contents, then
1909 		 * simply copy them to the new block. Note that we need
1910 		 * to synchronously write snapshots that have not been
1911 		 * unlinked, and hence will be visible after a crash,
1912 		 * to ensure their integrity. At a minimum we ensure the
1913 		 * integrity of the filesystem metadata, but use the
1914 		 * dopersistence sysctl-setable flag to decide on the
1915 		 * persistence needed for file content data.
1916 		 */
1917 		if (savedcbp != NULL) {
1918 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1919 			bawrite(cbp);
1920 			if ((vtype == VDIR || dopersistence) &&
1921 			    ip->i_effnlink > 0)
1922 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1923 			continue;
1924 		}
1925 		/*
1926 		 * Otherwise, read the old block contents into the buffer.
1927 		 */
1928 		if ((error = readblock(vp, cbp, lbn)) != 0) {
1929 			bzero(cbp->b_data, fs->fs_bsize);
1930 			bawrite(cbp);
1931 			if ((vtype == VDIR || dopersistence) &&
1932 			    ip->i_effnlink > 0)
1933 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1934 			break;
1935 		}
1936 		savedcbp = cbp;
1937 	}
1938 	/*
1939 	 * Note that we need to synchronously write snapshots that
1940 	 * have not been unlinked, and hence will be visible after
1941 	 * a crash, to ensure their integrity. At a minimum we
1942 	 * ensure the integrity of the filesystem metadata, but
1943 	 * use the dopersistence sysctl-setable flag to decide on
1944 	 * the persistence needed for file content data.
1945 	 */
1946 	if (savedcbp) {
1947 		vp = savedcbp->b_vp;
1948 		bawrite(savedcbp);
1949 		if ((vtype == VDIR || dopersistence) &&
1950 		    VTOI(vp)->i_effnlink > 0)
1951 			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
1952 	}
1953 	/*
1954 	 * If we have been unable to allocate a block in which to do
1955 	 * the copy, then return non-zero so that the fragment will
1956 	 * not be freed. Although space will be lost, the snapshot
1957 	 * will stay consistent.
1958 	 */
1959 	if (error != 0 && wkhd != NULL)
1960 		softdep_freework(wkhd);
1961 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
1962 	return (error);
1963 }
1964 
1965 /*
1966  * Associate snapshot files when mounting.
1967  */
1968 void
1969 ffs_snapshot_mount(struct mount *mp)
1970 {
1971 	struct ufsmount *ump = VFSTOUFS(mp);
1972 	struct vnode *devvp = ump->um_devvp;
1973 	struct fs *fs = ump->um_fs;
1974 	struct thread *td = curthread;
1975 	struct snapdata *sn;
1976 	struct vnode *vp;
1977 	struct vnode *lastvp;
1978 	struct inode *ip;
1979 	struct uio auio;
1980 	struct iovec aiov;
1981 	void *snapblklist;
1982 	char *reason;
1983 	daddr_t snaplistsize;
1984 	int error, snaploc, loc;
1985 
1986 	/*
1987 	 * XXX The following needs to be set before ffs_truncate or
1988 	 * VOP_READ can be called.
1989 	 */
1990 	mp->mnt_stat.f_iosize = fs->fs_bsize;
1991 	/*
1992 	 * Process each snapshot listed in the superblock.
1993 	 */
1994 	vp = NULL;
1995 	lastvp = NULL;
1996 	sn = NULL;
1997 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
1998 		if (fs->fs_snapinum[snaploc] == 0)
1999 			break;
2000 		if ((error = ffs_vget(mp, fs->fs_snapinum[snaploc],
2001 		    LK_EXCLUSIVE, &vp)) != 0){
2002 			printf("ffs_snapshot_mount: vget failed %d\n", error);
2003 			continue;
2004 		}
2005 		ip = VTOI(vp);
2006 		if (vp->v_type != VREG) {
2007 			reason = "non-file snapshot";
2008 		} else if (!IS_SNAPSHOT(ip)) {
2009 			reason = "non-snapshot";
2010 		} else if (ip->i_size ==
2011 		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag))) {
2012 			reason = "old format snapshot";
2013 			(void)ffs_truncate(vp, (off_t)0, 0, NOCRED);
2014 			(void)ffs_syncvnode(vp, MNT_WAIT, 0);
2015 		} else {
2016 			reason = NULL;
2017 		}
2018 		if (reason != NULL) {
2019 			printf("ffs_snapshot_mount: %s inode %d\n",
2020 			    reason, fs->fs_snapinum[snaploc]);
2021 			vput(vp);
2022 			vp = NULL;
2023 			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
2024 				if (fs->fs_snapinum[loc] == 0)
2025 					break;
2026 				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
2027 			}
2028 			fs->fs_snapinum[loc - 1] = 0;
2029 			snaploc--;
2030 			continue;
2031 		}
2032 		/*
2033 		 * Acquire a lock on the snapdata structure, creating it if
2034 		 * necessary.
2035 		 */
2036 		sn = ffs_snapdata_acquire(devvp);
2037 		/*
2038 		 * Change vnode to use shared snapshot lock instead of the
2039 		 * original private lock.
2040 		 */
2041 		vp->v_vnlock = &sn->sn_lock;
2042 		lockmgr(&vp->v_lock, LK_RELEASE, NULL);
2043 		/*
2044 		 * Link it onto the active snapshot list.
2045 		 */
2046 		VI_LOCK(devvp);
2047 		if (ip->i_nextsnap.tqe_prev != 0)
2048 			panic("ffs_snapshot_mount: %ju already on list",
2049 			    (uintmax_t)ip->i_number);
2050 		else
2051 			TAILQ_INSERT_TAIL(&sn->sn_head, ip, i_nextsnap);
2052 		vp->v_vflag |= VV_SYSTEM;
2053 		VI_UNLOCK(devvp);
2054 		VOP_UNLOCK(vp);
2055 		lastvp = vp;
2056 	}
2057 	vp = lastvp;
2058 	/*
2059 	 * No usable snapshots found.
2060 	 */
2061 	if (sn == NULL || vp == NULL)
2062 		return;
2063 	/*
2064 	 * Allocate the space for the block hints list. We always want to
2065 	 * use the list from the newest snapshot.
2066 	 */
2067 	auio.uio_iov = &aiov;
2068 	auio.uio_iovcnt = 1;
2069 	aiov.iov_base = (void *)&snaplistsize;
2070 	aiov.iov_len = sizeof(snaplistsize);
2071 	auio.uio_resid = aiov.iov_len;
2072 	auio.uio_offset =
2073 	    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag));
2074 	auio.uio_segflg = UIO_SYSSPACE;
2075 	auio.uio_rw = UIO_READ;
2076 	auio.uio_td = td;
2077 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
2078 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
2079 		printf("ffs_snapshot_mount: read_1 failed %d\n", error);
2080 		VOP_UNLOCK(vp);
2081 		return;
2082 	}
2083 	snapblklist = malloc(snaplistsize * sizeof(daddr_t),
2084 	    M_UFSMNT, M_WAITOK);
2085 	auio.uio_iovcnt = 1;
2086 	aiov.iov_base = snapblklist;
2087 	aiov.iov_len = snaplistsize * sizeof (daddr_t);
2088 	auio.uio_resid = aiov.iov_len;
2089 	auio.uio_offset -= sizeof(snaplistsize);
2090 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
2091 		printf("ffs_snapshot_mount: read_2 failed %d\n", error);
2092 		VOP_UNLOCK(vp);
2093 		free(snapblklist, M_UFSMNT);
2094 		return;
2095 	}
2096 	VOP_UNLOCK(vp);
2097 	VI_LOCK(devvp);
2098 	sn->sn_listsize = snaplistsize;
2099 	sn->sn_blklist = (daddr_t *)snapblklist;
2100 	devvp->v_vflag |= VV_COPYONWRITE;
2101 	VI_UNLOCK(devvp);
2102 }
2103 
2104 /*
2105  * Disassociate snapshot files when unmounting.
2106  */
2107 void
2108 ffs_snapshot_unmount(struct mount *mp)
2109 {
2110 	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
2111 	struct snapdata *sn;
2112 	struct inode *xp;
2113 	struct vnode *vp;
2114 
2115 	VI_LOCK(devvp);
2116 	sn = devvp->v_rdev->si_snapdata;
2117 	while (sn != NULL && (xp = TAILQ_FIRST(&sn->sn_head)) != NULL) {
2118 		vp = ITOV(xp);
2119 		TAILQ_REMOVE(&sn->sn_head, xp, i_nextsnap);
2120 		xp->i_nextsnap.tqe_prev = 0;
2121 		lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE,
2122 		    VI_MTX(devvp));
2123 		VI_LOCK(devvp);
2124 		revert_snaplock(vp, devvp, sn);
2125 		lockmgr(&vp->v_lock, LK_RELEASE, NULL);
2126 		if (xp->i_effnlink > 0) {
2127 			VI_UNLOCK(devvp);
2128 			vrele(vp);
2129 			VI_LOCK(devvp);
2130 		}
2131 		sn = devvp->v_rdev->si_snapdata;
2132 	}
2133 	try_free_snapdata(devvp);
2134 	VI_UNLOCK(devvp);
2135 }
2136 
2137 /*
2138  * Check the buffer block to be belong to device buffer that shall be
2139  * locked after snaplk. devvp shall be locked on entry, and will be
2140  * leaved locked upon exit.
2141  */
2142 static int
2143 ffs_bp_snapblk(struct vnode *devvp, struct buf *bp)
2144 {
2145 	struct snapdata *sn;
2146 	struct fs *fs;
2147 	ufs2_daddr_t lbn, *snapblklist;
2148 	int lower, upper, mid;
2149 
2150 	ASSERT_VI_LOCKED(devvp, "ffs_bp_snapblk");
2151 	KASSERT(devvp->v_type == VCHR, ("Not a device %p", devvp));
2152 	sn = devvp->v_rdev->si_snapdata;
2153 	if (sn == NULL || TAILQ_FIRST(&sn->sn_head) == NULL)
2154 		return (0);
2155 	fs = ITOFS(TAILQ_FIRST(&sn->sn_head));
2156 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
2157 	snapblklist = sn->sn_blklist;
2158 	upper = sn->sn_listsize - 1;
2159 	lower = 1;
2160 	while (lower <= upper) {
2161 		mid = (lower + upper) / 2;
2162 		if (snapblklist[mid] == lbn)
2163 			break;
2164 		if (snapblklist[mid] < lbn)
2165 			lower = mid + 1;
2166 		else
2167 			upper = mid - 1;
2168 	}
2169 	if (lower <= upper)
2170 		return (1);
2171 	return (0);
2172 }
2173 
2174 void
2175 ffs_bdflush(struct bufobj *bo, struct buf *bp)
2176 {
2177 	struct thread *td;
2178 	struct vnode *vp, *devvp;
2179 	struct buf *nbp;
2180 	int bp_bdskip;
2181 
2182 	if (bo->bo_dirty.bv_cnt <= dirtybufthresh)
2183 		return;
2184 
2185 	td = curthread;
2186 	vp = bp->b_vp;
2187 	devvp = bo2vnode(bo);
2188 	KASSERT(vp == devvp, ("devvp != vp %p %p", bo, bp));
2189 
2190 	VI_LOCK(devvp);
2191 	bp_bdskip = ffs_bp_snapblk(devvp, bp);
2192 	if (bp_bdskip)
2193 		bdwriteskip++;
2194 	VI_UNLOCK(devvp);
2195 	if (bo->bo_dirty.bv_cnt > dirtybufthresh + 10 && !bp_bdskip) {
2196 		(void) VOP_FSYNC(vp, MNT_NOWAIT, td);
2197 		altbufferflushes++;
2198 	} else {
2199 		BO_LOCK(bo);
2200 		/*
2201 		 * Try to find a buffer to flush.
2202 		 */
2203 		TAILQ_FOREACH(nbp, &bo->bo_dirty.bv_hd, b_bobufs) {
2204 			if ((nbp->b_vflags & BV_BKGRDINPROG) ||
2205 			    BUF_LOCK(nbp,
2206 				     LK_EXCLUSIVE | LK_NOWAIT, NULL))
2207 				continue;
2208 			if (bp == nbp)
2209 				panic("bdwrite: found ourselves");
2210 			BO_UNLOCK(bo);
2211 			/*
2212 			 * Don't countdeps with the bo lock
2213 			 * held.
2214 			 */
2215 			if (buf_countdeps(nbp, 0)) {
2216 				BO_LOCK(bo);
2217 				BUF_UNLOCK(nbp);
2218 				continue;
2219 			}
2220 			if (bp_bdskip) {
2221 				VI_LOCK(devvp);
2222 				if (!ffs_bp_snapblk(vp, nbp)) {
2223 					VI_UNLOCK(devvp);
2224 					BO_LOCK(bo);
2225 					BUF_UNLOCK(nbp);
2226 					continue;
2227 				}
2228 				VI_UNLOCK(devvp);
2229 			}
2230 			if (nbp->b_flags & B_CLUSTEROK) {
2231 				vfs_bio_awrite(nbp);
2232 			} else {
2233 				bremfree(nbp);
2234 				bawrite(nbp);
2235 			}
2236 			dirtybufferflushes++;
2237 			break;
2238 		}
2239 		if (nbp == NULL)
2240 			BO_UNLOCK(bo);
2241 	}
2242 }
2243 
2244 /*
2245  * Check for need to copy block that is about to be written,
2246  * copying the block if necessary.
2247  */
2248 int
2249 ffs_copyonwrite(struct vnode *devvp, struct buf *bp)
2250 {
2251 	struct snapdata *sn;
2252 	struct buf *ibp, *cbp, *savedcbp = NULL;
2253 	struct thread *td = curthread;
2254 	struct fs *fs;
2255 	struct inode *ip;
2256 	struct vnode *vp = NULL;
2257 	ufs2_daddr_t lbn, blkno, *snapblklist;
2258 	int lower, upper, mid, indiroff, error = 0;
2259 	int launched_async_io, prev_norunningbuf;
2260 	long saved_runningbufspace;
2261 
2262 	if (devvp != bp->b_vp && IS_SNAPSHOT(VTOI(bp->b_vp)))
2263 		return (0);		/* Update on a snapshot file */
2264 	if (td->td_pflags & TDP_COWINPROGRESS)
2265 		panic("ffs_copyonwrite: recursive call");
2266 	/*
2267 	 * First check to see if it is in the preallocated list.
2268 	 * By doing this check we avoid several potential deadlocks.
2269 	 */
2270 	VI_LOCK(devvp);
2271 	sn = devvp->v_rdev->si_snapdata;
2272 	if (sn == NULL ||
2273 	    TAILQ_EMPTY(&sn->sn_head)) {
2274 		VI_UNLOCK(devvp);
2275 		return (0);		/* No snapshot */
2276 	}
2277 	ip = TAILQ_FIRST(&sn->sn_head);
2278 	fs = ITOFS(ip);
2279 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
2280 	if (lbn < UFS_NDADDR) {
2281 		VI_UNLOCK(devvp);
2282 		return (0);		/* Direct blocks are always copied */
2283 	}
2284 	snapblklist = sn->sn_blklist;
2285 	upper = sn->sn_listsize - 1;
2286 	lower = 1;
2287 	while (lower <= upper) {
2288 		mid = (lower + upper) / 2;
2289 		if (snapblklist[mid] == lbn)
2290 			break;
2291 		if (snapblklist[mid] < lbn)
2292 			lower = mid + 1;
2293 		else
2294 			upper = mid - 1;
2295 	}
2296 	if (lower <= upper) {
2297 		VI_UNLOCK(devvp);
2298 		return (0);
2299 	}
2300 	launched_async_io = 0;
2301 	prev_norunningbuf = td->td_pflags & TDP_NORUNNINGBUF;
2302 	/*
2303 	 * Since I/O on bp isn't yet in progress and it may be blocked
2304 	 * for a long time waiting on snaplk, back it out of
2305 	 * runningbufspace, possibly waking other threads waiting for space.
2306 	 */
2307 	saved_runningbufspace = bp->b_runningbufspace;
2308 	if (saved_runningbufspace != 0)
2309 		runningbufwakeup(bp);
2310 	/*
2311 	 * Not in the precomputed list, so check the snapshots.
2312 	 */
2313 	while (lockmgr(&sn->sn_lock, LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
2314 	    VI_MTX(devvp)) != 0) {
2315 		VI_LOCK(devvp);
2316 		sn = devvp->v_rdev->si_snapdata;
2317 		if (sn == NULL ||
2318 		    TAILQ_EMPTY(&sn->sn_head)) {
2319 			VI_UNLOCK(devvp);
2320 			if (saved_runningbufspace != 0) {
2321 				bp->b_runningbufspace = saved_runningbufspace;
2322 				atomic_add_long(&runningbufspace,
2323 					       bp->b_runningbufspace);
2324 			}
2325 			return (0);		/* Snapshot gone */
2326 		}
2327 	}
2328 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
2329 		vp = ITOV(ip);
2330 		if (DOINGSOFTDEP(vp))
2331 			softdep_prealloc(vp, MNT_WAIT);
2332 		/*
2333 		 * We ensure that everything of our own that needs to be
2334 		 * copied will be done at the time that ffs_snapshot is
2335 		 * called. Thus we can skip the check here which can
2336 		 * deadlock in doing the lookup in UFS_BALLOC.
2337 		 */
2338 		if (bp->b_vp == vp)
2339 			continue;
2340 		/*
2341 		 * Check to see if block needs to be copied. We do not have
2342 		 * to hold the snapshot lock while doing this lookup as it
2343 		 * will never require any additional allocations for the
2344 		 * snapshot inode.
2345 		 */
2346 		if (lbn < UFS_NDADDR) {
2347 			blkno = DIP(ip, i_db[lbn]);
2348 		} else {
2349 			td->td_pflags |= TDP_COWINPROGRESS | TDP_NORUNNINGBUF;
2350 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
2351 			   fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
2352 			td->td_pflags &= ~TDP_COWINPROGRESS;
2353 			if (error)
2354 				break;
2355 			indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
2356 			if (I_IS_UFS1(ip))
2357 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
2358 			else
2359 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
2360 			bqrelse(ibp);
2361 		}
2362 #ifdef INVARIANTS
2363 		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
2364 			panic("ffs_copyonwrite: bad copy block");
2365 #endif
2366 		if (blkno != 0)
2367 			continue;
2368 		/*
2369 		 * Allocate the block into which to do the copy. Since
2370 		 * multiple processes may all try to copy the same block,
2371 		 * we have to recheck our need to do a copy if we sleep
2372 		 * waiting for the lock.
2373 		 *
2374 		 * Because all snapshots on a filesystem share a single
2375 		 * lock, we ensure that we will never be in competition
2376 		 * with another process to allocate a block.
2377 		 */
2378 		td->td_pflags |= TDP_COWINPROGRESS | TDP_NORUNNINGBUF;
2379 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
2380 		    fs->fs_bsize, KERNCRED, 0, &cbp);
2381 		td->td_pflags &= ~TDP_COWINPROGRESS;
2382 		if (error)
2383 			break;
2384 #ifdef DIAGNOSTIC
2385 		if (snapdebug) {
2386 			printf("Copyonwrite: snapino %ju lbn %jd for ",
2387 			    (uintmax_t)ip->i_number, (intmax_t)lbn);
2388 			if (bp->b_vp == devvp)
2389 				printf("fs metadata");
2390 			else
2391 				printf("inum %ju",
2392 				    (uintmax_t)VTOI(bp->b_vp)->i_number);
2393 			printf(" lblkno %jd to blkno %jd\n",
2394 			    (intmax_t)bp->b_lblkno, (intmax_t)cbp->b_blkno);
2395 		}
2396 #endif
2397 		/*
2398 		 * If we have already read the old block contents, then
2399 		 * simply copy them to the new block. Note that we need
2400 		 * to synchronously write snapshots that have not been
2401 		 * unlinked, and hence will be visible after a crash,
2402 		 * to ensure their integrity. At a minimum we ensure the
2403 		 * integrity of the filesystem metadata, but use the
2404 		 * dopersistence sysctl-setable flag to decide on the
2405 		 * persistence needed for file content data.
2406 		 */
2407 		if (savedcbp != NULL) {
2408 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
2409 			bawrite(cbp);
2410 			if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2411 			    dopersistence) && ip->i_effnlink > 0)
2412 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2413 			else
2414 				launched_async_io = 1;
2415 			continue;
2416 		}
2417 		/*
2418 		 * Otherwise, read the old block contents into the buffer.
2419 		 */
2420 		if ((error = readblock(vp, cbp, lbn)) != 0) {
2421 			bzero(cbp->b_data, fs->fs_bsize);
2422 			bawrite(cbp);
2423 			if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2424 			    dopersistence) && ip->i_effnlink > 0)
2425 				(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2426 			else
2427 				launched_async_io = 1;
2428 			break;
2429 		}
2430 		savedcbp = cbp;
2431 	}
2432 	/*
2433 	 * Note that we need to synchronously write snapshots that
2434 	 * have not been unlinked, and hence will be visible after
2435 	 * a crash, to ensure their integrity. At a minimum we
2436 	 * ensure the integrity of the filesystem metadata, but
2437 	 * use the dopersistence sysctl-setable flag to decide on
2438 	 * the persistence needed for file content data.
2439 	 */
2440 	if (savedcbp) {
2441 		vp = savedcbp->b_vp;
2442 		bawrite(savedcbp);
2443 		if ((devvp == bp->b_vp || bp->b_vp->v_type == VDIR ||
2444 		    dopersistence) && VTOI(vp)->i_effnlink > 0)
2445 			(void) ffs_syncvnode(vp, MNT_WAIT, NO_INO_UPDT);
2446 		else
2447 			launched_async_io = 1;
2448 	}
2449 	lockmgr(vp->v_vnlock, LK_RELEASE, NULL);
2450 	td->td_pflags = (td->td_pflags & ~TDP_NORUNNINGBUF) |
2451 		prev_norunningbuf;
2452 	if (launched_async_io && (td->td_pflags & TDP_NORUNNINGBUF) == 0)
2453 		waitrunningbufspace();
2454 	/*
2455 	 * I/O on bp will now be started, so count it in runningbufspace.
2456 	 */
2457 	if (saved_runningbufspace != 0) {
2458 		bp->b_runningbufspace = saved_runningbufspace;
2459 		atomic_add_long(&runningbufspace, bp->b_runningbufspace);
2460 	}
2461 	return (error);
2462 }
2463 
2464 /*
2465  * sync snapshots to force freework records waiting on snapshots to claim
2466  * blocks to free.
2467  */
2468 void
2469 ffs_sync_snap(struct mount *mp, int waitfor)
2470 {
2471 	struct snapdata *sn;
2472 	struct vnode *devvp;
2473 	struct vnode *vp;
2474 	struct inode *ip;
2475 
2476 	devvp = VFSTOUFS(mp)->um_devvp;
2477 	if ((devvp->v_vflag & VV_COPYONWRITE) == 0)
2478 		return;
2479 	for (;;) {
2480 		VI_LOCK(devvp);
2481 		sn = devvp->v_rdev->si_snapdata;
2482 		if (sn == NULL) {
2483 			VI_UNLOCK(devvp);
2484 			return;
2485 		}
2486 		if (lockmgr(&sn->sn_lock,
2487 		    LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
2488 		    VI_MTX(devvp)) == 0)
2489 			break;
2490 	}
2491 	TAILQ_FOREACH(ip, &sn->sn_head, i_nextsnap) {
2492 		vp = ITOV(ip);
2493 		ffs_syncvnode(vp, waitfor, NO_INO_UPDT);
2494 	}
2495 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2496 }
2497 
2498 /*
2499  * Read the specified block into the given buffer.
2500  * Much of this boiler-plate comes from bwrite().
2501  */
2502 static int
2503 readblock(struct vnode *vp,
2504 	struct buf *bp,
2505 	ufs2_daddr_t lbn)
2506 {
2507 	struct inode *ip;
2508 	struct fs *fs;
2509 
2510 	ip = VTOI(vp);
2511 	fs = ITOFS(ip);
2512 
2513 	bp->b_iocmd = BIO_READ;
2514 	bp->b_iooffset = dbtob(fsbtodb(fs, blkstofrags(fs, lbn)));
2515 	bp->b_iodone = bdone;
2516 	g_vfs_strategy(&ITODEVVP(ip)->v_bufobj, bp);
2517 	bufwait(bp);
2518 	return (bp->b_error);
2519 }
2520 
2521 #endif
2522 
2523 /*
2524  * Process file deletes that were deferred by ufs_inactive() due to
2525  * the file system being suspended. Transfer IN_LAZYACCESS into
2526  * IN_MODIFIED for vnodes that were accessed during suspension.
2527  */
2528 void
2529 process_deferred_inactive(struct mount *mp)
2530 {
2531 	struct vnode *vp, *mvp;
2532 	struct inode *ip;
2533 	int error;
2534 
2535 	(void) vn_start_secondary_write(NULL, &mp, V_WAIT);
2536  loop:
2537 	MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
2538 		/*
2539 		 * IN_LAZYACCESS is checked here without holding any
2540 		 * vnode lock, but this flag is set only while holding
2541 		 * vnode interlock.
2542 		 */
2543 		if (vp->v_type == VNON ||
2544 		    ((VTOI(vp)->i_flag & IN_LAZYACCESS) == 0 &&
2545 		    ((vp->v_iflag & VI_OWEINACT) == 0 || vp->v_usecount > 0))) {
2546 			VI_UNLOCK(vp);
2547 			continue;
2548 		}
2549 		vholdl(vp);
2550 retry_vnode:
2551 		error = vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK);
2552 		if (error != 0) {
2553 			vdrop(vp);
2554 			if (error == ENOENT)
2555 				continue;	/* vnode recycled */
2556 			MNT_VNODE_FOREACH_ALL_ABORT(mp, mvp);
2557 			goto loop;
2558 		}
2559 		ip = VTOI(vp);
2560 		if ((ip->i_flag & IN_LAZYACCESS) != 0) {
2561 			ip->i_flag &= ~IN_LAZYACCESS;
2562 			UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
2563 		}
2564 		VI_LOCK(vp);
2565 		error = vinactive(vp);
2566 		if (error == ERELOOKUP && vp->v_usecount == 0) {
2567 			VI_UNLOCK(vp);
2568 			VOP_UNLOCK(vp);
2569 			goto retry_vnode;
2570 		}
2571 		VI_UNLOCK(vp);
2572 		VOP_UNLOCK(vp);
2573 		vdrop(vp);
2574 	}
2575 	vn_finished_secondary_write(mp);
2576 }
2577 
2578 #ifndef NO_FFS_SNAPSHOT
2579 
2580 static struct snapdata *
2581 ffs_snapdata_alloc(void)
2582 {
2583 	struct snapdata *sn;
2584 
2585 	/*
2586 	 * Fetch a snapdata from the free list if there is one available.
2587 	 */
2588 	mtx_lock(&snapfree_lock);
2589 	sn = LIST_FIRST(&snapfree);
2590 	if (sn != NULL)
2591 		LIST_REMOVE(sn, sn_link);
2592 	mtx_unlock(&snapfree_lock);
2593 	if (sn != NULL)
2594 		return (sn);
2595 	/*
2596  	 * If there were no free snapdatas allocate one.
2597 	 */
2598 	sn = malloc(sizeof *sn, M_UFSMNT, M_WAITOK | M_ZERO);
2599 	TAILQ_INIT(&sn->sn_head);
2600 	lockinit(&sn->sn_lock, PVFS, "snaplk", VLKTIMEOUT,
2601 	    LK_CANRECURSE | LK_NOSHARE);
2602 	return (sn);
2603 }
2604 
2605 /*
2606  * The snapdata is never freed because we can not be certain that
2607  * there are no threads sleeping on the snap lock.  Persisting
2608  * them permanently avoids costly synchronization in ffs_lock().
2609  */
2610 static void
2611 ffs_snapdata_free(struct snapdata *sn)
2612 {
2613 	mtx_lock(&snapfree_lock);
2614 	LIST_INSERT_HEAD(&snapfree, sn, sn_link);
2615 	mtx_unlock(&snapfree_lock);
2616 }
2617 
2618 /* Try to free snapdata associated with devvp */
2619 static void
2620 try_free_snapdata(struct vnode *devvp)
2621 {
2622 	struct snapdata *sn;
2623 	ufs2_daddr_t *snapblklist;
2624 
2625 	ASSERT_VI_LOCKED(devvp, "try_free_snapdata");
2626 	sn = devvp->v_rdev->si_snapdata;
2627 
2628 	if (sn == NULL || TAILQ_FIRST(&sn->sn_head) != NULL ||
2629 	    (devvp->v_vflag & VV_COPYONWRITE) == 0)
2630 		return;
2631 
2632 	devvp->v_rdev->si_snapdata = NULL;
2633 	devvp->v_vflag &= ~VV_COPYONWRITE;
2634 	lockmgr(&sn->sn_lock, LK_DRAIN|LK_INTERLOCK, VI_MTX(devvp));
2635 	snapblklist = sn->sn_blklist;
2636 	sn->sn_blklist = NULL;
2637 	sn->sn_listsize = 0;
2638 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2639 	if (snapblklist != NULL)
2640 		free(snapblklist, M_UFSMNT);
2641 	ffs_snapdata_free(sn);
2642 	VI_LOCK(devvp);
2643 }
2644 
2645 /*
2646  * Revert a vnode lock from using the snapshot lock back to its own lock.
2647  *
2648  * Aquire a lock on the vnode's own lock and release the lock on the
2649  * snapshot lock. If there are any recursions on the snapshot lock
2650  * get the same number of recursions on the vnode's own lock.
2651  */
2652 static void
2653 revert_snaplock(struct vnode *vp,
2654 	struct vnode *devvp,
2655 	struct snapdata *sn)
2656 {
2657 	int i;
2658 
2659 	ASSERT_VI_LOCKED(devvp, "revert_snaplock");
2660 	/*
2661 	 * Avoid LOR with snapshot lock. The LK_NOWAIT should
2662 	 * never fail as the lock is currently unused. Rather than
2663 	 * panic, we recover by doing the blocking lock.
2664 	 */
2665 	for (i = 0; i <= sn->sn_lock.lk_recurse; i++) {
2666 		if (lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_NOWAIT |
2667 		    LK_INTERLOCK, VI_MTX(devvp)) != 0) {
2668 			printf("revert_snaplock: Unexpected LK_NOWAIT "
2669 			    "failure\n");
2670 			lockmgr(&vp->v_lock, LK_EXCLUSIVE | LK_INTERLOCK,
2671 			    VI_MTX(devvp));
2672 		}
2673 		VI_LOCK(devvp);
2674 	}
2675 	KASSERT(vp->v_vnlock == &sn->sn_lock,
2676 	    ("revert_snaplock: lost lock mutation"));
2677 	vp->v_vnlock = &vp->v_lock;
2678 	while (sn->sn_lock.lk_recurse > 0)
2679 		lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2680 	lockmgr(&sn->sn_lock, LK_RELEASE, NULL);
2681 }
2682 
2683 static struct snapdata *
2684 ffs_snapdata_acquire(struct vnode *devvp)
2685 {
2686 	struct snapdata *nsn, *sn;
2687 	int error;
2688 
2689 	/*
2690 	 * Allocate a free snapdata.  This is done before acquiring the
2691 	 * devvp lock to avoid allocation while the devvp interlock is
2692 	 * held.
2693 	 */
2694 	nsn = ffs_snapdata_alloc();
2695 
2696 	for (;;) {
2697 		VI_LOCK(devvp);
2698 		sn = devvp->v_rdev->si_snapdata;
2699 		if (sn == NULL) {
2700 			/*
2701 			 * This is the first snapshot on this
2702 			 * filesystem and we use our pre-allocated
2703 			 * snapdata.  Publish sn with the sn_lock
2704 			 * owned by us, to avoid the race.
2705 			 */
2706 			error = lockmgr(&nsn->sn_lock, LK_EXCLUSIVE |
2707 			    LK_NOWAIT, NULL);
2708 			if (error != 0)
2709 				panic("leaked sn, lockmgr error %d", error);
2710 			sn = devvp->v_rdev->si_snapdata = nsn;
2711 			VI_UNLOCK(devvp);
2712 			nsn = NULL;
2713 			break;
2714 		}
2715 
2716 		/*
2717 		 * There is a snapshots which already exists on this
2718 		 * filesystem, grab a reference to the common lock.
2719 		 */
2720 		error = lockmgr(&sn->sn_lock, LK_INTERLOCK |
2721 		    LK_EXCLUSIVE | LK_SLEEPFAIL, VI_MTX(devvp));
2722 		if (error == 0)
2723 			break;
2724 	}
2725 
2726 	/*
2727 	 * Free any unused snapdata.
2728 	 */
2729 	if (nsn != NULL)
2730 		ffs_snapdata_free(nsn);
2731 
2732 	return (sn);
2733 }
2734 
2735 #endif
2736