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