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