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