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