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