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