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