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