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