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