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