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