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