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