xref: /freebsd/sys/ufs/ffs/ffs_snapshot.c (revision 4b2eaea43fec8e8792be611dea204071a10b655a)
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  * $FreeBSD$
35  */
36 
37 #include <sys/param.h>
38 #include <sys/stdint.h>
39 #include <sys/kernel.h>
40 #include <sys/systm.h>
41 #include <sys/conf.h>
42 #include <sys/bio.h>
43 #include <sys/buf.h>
44 #include <sys/proc.h>
45 #include <sys/namei.h>
46 #include <sys/stat.h>
47 #include <sys/malloc.h>
48 #include <sys/mount.h>
49 #include <sys/resource.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vnode.h>
52 
53 #include <ufs/ufs/extattr.h>
54 #include <ufs/ufs/quota.h>
55 #include <ufs/ufs/ufsmount.h>
56 #include <ufs/ufs/inode.h>
57 #include <ufs/ufs/ufs_extern.h>
58 
59 #include <ufs/ffs/fs.h>
60 #include <ufs/ffs/ffs_extern.h>
61 
62 #define KERNCRED thread0.td_ucred
63 #define DEBUG 1
64 
65 static int cgaccount(int, struct vnode *, struct buf *, int);
66 static int expunge_ufs1(struct vnode *, struct inode *, struct fs *,
67     int (*)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *, struct fs *,
68     ufs_lbn_t, int), int);
69 static int indiracct_ufs1(struct vnode *, struct vnode *, int,
70     ufs1_daddr_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, struct fs *,
71     int (*)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *, struct fs *,
72     ufs_lbn_t, int), int);
73 static int fullacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
74     struct fs *, ufs_lbn_t, int);
75 static int snapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
76     struct fs *, ufs_lbn_t, int);
77 static int mapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
78     struct fs *, ufs_lbn_t, int);
79 static int expunge_ufs2(struct vnode *, struct inode *, struct fs *,
80     int (*)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *, struct fs *,
81     ufs_lbn_t, int), int);
82 static int indiracct_ufs2(struct vnode *, struct vnode *, int,
83     ufs2_daddr_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, ufs_lbn_t, struct fs *,
84     int (*)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *, struct fs *,
85     ufs_lbn_t, int), int);
86 static int fullacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
87     struct fs *, ufs_lbn_t, int);
88 static int snapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
89     struct fs *, ufs_lbn_t, int);
90 static int mapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
91     struct fs *, ufs_lbn_t, int);
92 static int ffs_copyonwrite(struct vnode *, struct buf *);
93 static int readblock(struct buf *, ufs2_daddr_t);
94 
95 /*
96  * To ensure the consistency of snapshots across crashes, we must
97  * synchronously write out copied blocks before allowing the
98  * originals to be modified. Because of the rather severe speed
99  * penalty that this imposes, the following flag allows this
100  * crash persistence to be disabled.
101  */
102 int dopersistence = 0;
103 
104 #ifdef DEBUG
105 #include <sys/sysctl.h>
106 SYSCTL_INT(_debug, OID_AUTO, dopersistence, CTLFLAG_RW, &dopersistence, 0, "");
107 int snapdebug = 0;
108 SYSCTL_INT(_debug, OID_AUTO, snapdebug, CTLFLAG_RW, &snapdebug, 0, "");
109 int collectsnapstats = 0;
110 SYSCTL_INT(_debug, OID_AUTO, collectsnapstats, CTLFLAG_RW, &collectsnapstats,
111 	0, "");
112 #endif /* DEBUG */
113 
114 /*
115  * Create a snapshot file and initialize it for the filesystem.
116  */
117 int
118 ffs_snapshot(mp, snapfile)
119 	struct mount *mp;
120 	char *snapfile;
121 {
122 	ufs2_daddr_t numblks, blkno;
123 	int error, cg, snaploc;
124 	int i, size, len, loc;
125 	int flag = mp->mnt_flag;
126 	struct timespec starttime = {0, 0}, endtime;
127 	char saved_nice = 0;
128 	long redo = 0, snaplistsize;
129 	int32_t *lp;
130 	void *space;
131 	daddr_t *snapblklist;
132 	struct fs *copy_fs = NULL, *fs = VFSTOUFS(mp)->um_fs;
133 	struct snaphead *snaphead;
134 	struct thread *td = curthread;
135 	struct inode *ip, *xp;
136 	struct buf *bp, *nbp, *ibp, *sbp = NULL;
137 	struct nameidata nd;
138 	struct mount *wrtmp;
139 	struct vattr vat;
140 	struct vnode *vp, *xvp, *nvp, *devvp;
141 	struct uio auio;
142 	struct iovec aiov;
143 
144 	/*
145 	 * Need to serialize access to snapshot code per filesystem.
146 	 */
147 	/*
148 	 * Assign a snapshot slot in the superblock.
149 	 */
150 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
151 		if (fs->fs_snapinum[snaploc] == 0)
152 			break;
153 	if (snaploc == FSMAXSNAP)
154 		return (ENOSPC);
155 	/*
156 	 * Create the snapshot file.
157 	 */
158 restart:
159 	NDINIT(&nd, CREATE, LOCKPARENT | LOCKLEAF, UIO_USERSPACE, snapfile, td);
160 	if ((error = namei(&nd)) != 0)
161 		return (error);
162 	if (nd.ni_vp != NULL) {
163 		vput(nd.ni_vp);
164 		error = EEXIST;
165 	}
166 	if (nd.ni_dvp->v_mount != mp)
167 		error = EXDEV;
168 	if (error) {
169 		NDFREE(&nd, NDF_ONLY_PNBUF);
170 		if (nd.ni_dvp == nd.ni_vp)
171 			vrele(nd.ni_dvp);
172 		else
173 			vput(nd.ni_dvp);
174 		return (error);
175 	}
176 	VATTR_NULL(&vat);
177 	vat.va_type = VREG;
178 	vat.va_mode = S_IRUSR;
179 	vat.va_vaflags |= VA_EXCLUSIVE;
180 	if (VOP_GETWRITEMOUNT(nd.ni_dvp, &wrtmp))
181 		wrtmp = NULL;
182 	if (wrtmp != mp)
183 		panic("ffs_snapshot: mount mismatch");
184 	if (vn_start_write(NULL, &wrtmp, V_NOWAIT) != 0) {
185 		NDFREE(&nd, NDF_ONLY_PNBUF);
186 		vput(nd.ni_dvp);
187 		if ((error = vn_start_write(NULL, &wrtmp,
188 		    V_XSLEEP | PCATCH)) != 0)
189 			return (error);
190 		goto restart;
191 	}
192 	VOP_LEASE(nd.ni_dvp, td, KERNCRED, LEASE_WRITE);
193 	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vat);
194 	vput(nd.ni_dvp);
195 	if (error) {
196 		NDFREE(&nd, NDF_ONLY_PNBUF);
197 		vn_finished_write(wrtmp);
198 		return (error);
199 	}
200 	vp = nd.ni_vp;
201 	ip = VTOI(vp);
202 	devvp = ip->i_devvp;
203 	/*
204 	 * Allocate and copy the last block contents so as to be able
205 	 * to set size to that of the filesystem.
206 	 */
207 	numblks = howmany(fs->fs_size, fs->fs_frag);
208 	error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(numblks - 1)),
209 	    fs->fs_bsize, KERNCRED, BA_CLRBUF, &bp);
210 	if (error)
211 		goto out;
212 	ip->i_size = lblktosize(fs, (off_t)numblks);
213 	DIP(ip, i_size) = ip->i_size;
214 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
215 	if ((error = readblock(bp, numblks - 1)) != 0)
216 		goto out;
217 	bawrite(bp);
218 	/*
219 	 * Preallocate critical data structures so that we can copy
220 	 * them in without further allocation after we suspend all
221 	 * operations on the filesystem. We would like to just release
222 	 * the allocated buffers without writing them since they will
223 	 * be filled in below once we are ready to go, but this upsets
224 	 * the soft update code, so we go ahead and write the new buffers.
225 	 *
226 	 * Allocate all indirect blocks and mark all of them as not
227 	 * needing to be copied.
228 	 */
229 	for (blkno = NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
230 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
231 		    fs->fs_bsize, td->td_ucred, BA_METAONLY, &ibp);
232 		if (error)
233 			goto out;
234 		bawrite(ibp);
235 	}
236 	/*
237 	 * Allocate copies for the superblock and its summary information.
238 	 */
239 	error = UFS_BALLOC(vp, fs->fs_sblockloc, fs->fs_sbsize, KERNCRED,
240 	    0, &nbp);
241 	if (error)
242 		goto out;
243 	bawrite(nbp);
244 	blkno = fragstoblks(fs, fs->fs_csaddr);
245 	len = howmany(fs->fs_cssize, fs->fs_bsize);
246 	for (loc = 0; loc < len; loc++) {
247 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(blkno + loc)),
248 		    fs->fs_bsize, KERNCRED, 0, &nbp);
249 		if (error)
250 			goto out;
251 		bawrite(nbp);
252 	}
253 	/*
254 	 * Allocate all cylinder group blocks.
255 	 */
256 	for (cg = 0; cg < fs->fs_ncg; cg++) {
257 		error = UFS_BALLOC(vp, (off_t)(cgtod(fs, cg)) << fs->fs_fshift,
258 		    fs->fs_bsize, KERNCRED, 0, &nbp);
259 		if (error)
260 			goto out;
261 		bawrite(nbp);
262 	}
263 	/*
264 	 * Copy all the cylinder group maps. Although the
265 	 * filesystem is still active, we hope that only a few
266 	 * cylinder groups will change between now and when we
267 	 * suspend operations. Thus, we will be able to quickly
268 	 * touch up the few cylinder groups that changed during
269 	 * the suspension period.
270 	 */
271 	len = howmany(fs->fs_ncg, NBBY);
272 	MALLOC(fs->fs_active, int *, len, M_DEVBUF, 0);
273 	bzero(fs->fs_active, len);
274 	for (cg = 0; cg < fs->fs_ncg; cg++) {
275 		error = UFS_BALLOC(vp, (off_t)(cgtod(fs, cg)) << fs->fs_fshift,
276 		    fs->fs_bsize, KERNCRED, 0, &nbp);
277 		if (error)
278 			goto out;
279 		error = cgaccount(cg, vp, nbp, 1);
280 		bawrite(nbp);
281 		if (error)
282 			goto out;
283 	}
284 	/*
285 	 * Change inode to snapshot type file.
286 	 */
287 	ip->i_flags |= SF_SNAPSHOT;
288 	DIP(ip, i_flags) = ip->i_flags;
289 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
290 	/*
291 	 * Ensure that the snapshot is completely on disk.
292 	 * Since we have marked it as a snapshot it is safe to
293 	 * unlock it as no process will be allowed to write to it.
294 	 */
295 	if ((error = VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td)) != 0)
296 		goto out;
297 	VOP_UNLOCK(vp, 0, td);
298 	/*
299 	 * All allocations are done, so we can now snapshot the system.
300 	 *
301 	 * Recind nice scheduling while running with the filesystem suspended.
302 	 */
303 	if (td->td_ksegrp->kg_nice > 0) {
304 		saved_nice = td->td_ksegrp->kg_nice;
305 		td->td_ksegrp->kg_nice = 0;
306 	}
307 	/*
308 	 * Suspend operation on filesystem.
309 	 */
310 	for (;;) {
311 		vn_finished_write(wrtmp);
312 		if ((error = vfs_write_suspend(vp->v_mount)) != 0) {
313 			vn_start_write(NULL, &wrtmp, V_WAIT);
314 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
315 			goto out;
316 		}
317 		if (mp->mnt_kern_flag & MNTK_SUSPENDED)
318 			break;
319 		vn_start_write(NULL, &wrtmp, V_WAIT);
320 	}
321 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
322 	if (collectsnapstats)
323 		nanotime(&starttime);
324 	/*
325 	 * First, copy all the cylinder group maps that have changed.
326 	 */
327 	for (cg = 0; cg < fs->fs_ncg; cg++) {
328 		if ((ACTIVECGNUM(fs, cg) & ACTIVECGOFF(cg)) != 0)
329 			continue;
330 		redo++;
331 		error = UFS_BALLOC(vp, (off_t)(cgtod(fs, cg)) << fs->fs_fshift,
332 		    fs->fs_bsize, KERNCRED, 0, &nbp);
333 		if (error)
334 			goto out1;
335 		error = cgaccount(cg, vp, nbp, 2);
336 		bawrite(nbp);
337 		if (error)
338 			goto out1;
339 	}
340 	/*
341 	 * Grab a copy of the superblock and its summary information.
342 	 * We delay writing it until the suspension is released below.
343 	 */
344 	error = bread(vp, lblkno(fs, fs->fs_sblockloc), fs->fs_bsize,
345 	    KERNCRED, &sbp);
346 	if (error) {
347 		brelse(sbp);
348 		sbp = NULL;
349 		goto out1;
350 	}
351 	loc = blkoff(fs, fs->fs_sblockloc);
352 	copy_fs = (struct fs *)(sbp->b_data + loc);
353 	bcopy(fs, copy_fs, fs->fs_sbsize);
354 	if ((fs->fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) == 0)
355 		copy_fs->fs_clean = 1;
356 	if (fs->fs_sbsize < SBLOCKSIZE)
357 		bzero(&sbp->b_data[loc + fs->fs_sbsize],
358 		    SBLOCKSIZE - fs->fs_sbsize);
359 	size = blkroundup(fs, fs->fs_cssize);
360 	if (fs->fs_contigsumsize > 0)
361 		size += fs->fs_ncg * sizeof(int32_t);
362 	space = malloc((u_long)size, M_UFSMNT, 0);
363 	copy_fs->fs_csp = space;
364 	bcopy(fs->fs_csp, copy_fs->fs_csp, fs->fs_cssize);
365 	(char *)space += fs->fs_cssize;
366 	loc = howmany(fs->fs_cssize, fs->fs_fsize);
367 	i = fs->fs_frag - loc % fs->fs_frag;
368 	len = (i == fs->fs_frag) ? 0 : i * fs->fs_fsize;
369 	if (len > 0) {
370 		if ((error = bread(devvp, fsbtodb(fs, fs->fs_csaddr + loc),
371 		    len, KERNCRED, &bp)) != 0) {
372 			brelse(bp);
373 			free(copy_fs->fs_csp, M_UFSMNT);
374 			bawrite(sbp);
375 			sbp = NULL;
376 			goto out1;
377 		}
378 		bcopy(bp->b_data, space, (u_int)len);
379 		(char *)space += len;
380 		bp->b_flags |= B_INVAL | B_NOCACHE;
381 		brelse(bp);
382 	}
383 	if (fs->fs_contigsumsize > 0) {
384 		copy_fs->fs_maxcluster = lp = space;
385 		for (i = 0; i < fs->fs_ncg; i++)
386 			*lp++ = fs->fs_contigsumsize;
387 	}
388 	/*
389 	 * We must check for active files that have been unlinked
390 	 * (e.g., with a zero link count). We have to expunge all
391 	 * trace of these files from the snapshot so that they are
392 	 * not reclaimed prematurely by fsck or unnecessarily dumped.
393 	 * We turn off the MNTK_SUSPENDED flag to avoid a panic from
394 	 * spec_strategy about writing on a suspended filesystem.
395 	 * Note that we skip unlinked snapshot files as they will
396 	 * be handled separately below.
397 	 */
398 	mp->mnt_kern_flag &= ~MNTK_SUSPENDED;
399 	mtx_lock(&mntvnode_mtx);
400 loop:
401 	for (xvp = TAILQ_FIRST(&mp->mnt_nvnodelist); xvp; xvp = nvp) {
402 		/*
403 		 * Make sure this vnode wasn't reclaimed in getnewvnode().
404 		 * Start over if it has (it won't be on the list anymore).
405 		 */
406 		if (xvp->v_mount != mp)
407 			goto loop;
408 		nvp = TAILQ_NEXT(xvp, v_nmntvnodes);
409 		mtx_unlock(&mntvnode_mtx);
410 		mp_fixme("Unlocked GETATTR.");
411 		if (vrefcnt(xvp) == 0 || xvp->v_type == VNON ||
412 		    (VTOI(xvp)->i_flags & SF_SNAPSHOT) ||
413 		    (VOP_GETATTR(xvp, &vat, td->td_proc->p_ucred, td) == 0 &&
414 		    vat.va_nlink > 0)) {
415 			mtx_lock(&mntvnode_mtx);
416 			continue;
417 		}
418 		if (snapdebug)
419 			vprint("ffs_snapshot: busy vnode", xvp);
420 		if (vn_lock(xvp, LK_EXCLUSIVE, td) != 0)
421 			goto loop;
422 		xp = VTOI(xvp);
423 		/*
424 		 * If there is a fragment, clear it here.
425 		 */
426 		blkno = 0;
427 		loc = howmany(xp->i_size, fs->fs_bsize) - 1;
428 		if (loc < NDADDR) {
429 			len = fragroundup(fs, blkoff(fs, xp->i_size));
430 			if (len < fs->fs_bsize) {
431 				ffs_blkfree(copy_fs, vp, DIP(xp, i_db[loc]),
432 				    len, xp->i_number);
433 				blkno = DIP(xp, i_db[loc]);
434 				DIP(xp, i_db[loc]) = 0;
435 			}
436 		}
437 		if (xp->i_ump->um_fstype == UFS1)
438 			error = expunge_ufs1(vp, xp, copy_fs, fullacct_ufs1,
439 			    BLK_NOCOPY);
440 		else
441 			error = expunge_ufs2(vp, xp, copy_fs, fullacct_ufs2,
442 			    BLK_NOCOPY);
443 		if (blkno)
444 			DIP(xp, i_db[loc]) = blkno;
445 		if (!error)
446 			error = ffs_freefile(copy_fs, vp, xp->i_number,
447 			    xp->i_mode);
448 		VOP_UNLOCK(xvp, 0, td);
449 		if (error) {
450 			free(copy_fs->fs_csp, M_UFSMNT);
451 			bawrite(sbp);
452 			sbp = NULL;
453 			goto out1;
454 		}
455 		mtx_lock(&mntvnode_mtx);
456 	}
457 	mtx_unlock(&mntvnode_mtx);
458 	/*
459 	 * If there already exist snapshots on this filesystem, grab a
460 	 * reference to their shared lock. If this is the first snapshot
461 	 * on this filesystem, we need to allocate a lock for the snapshots
462 	 * to share. In either case, acquire the snapshot lock and give
463 	 * up our original private lock.
464 	 */
465 	VI_LOCK(devvp);
466 	snaphead = &devvp->v_rdev->si_snapshots;
467 	if ((xp = TAILQ_FIRST(snaphead)) != NULL) {
468 		VI_LOCK(vp);
469 		vp->v_vnlock = ITOV(xp)->v_vnlock;
470 		VI_UNLOCK(devvp);
471 	} else {
472 		struct lock *lkp;
473 
474 		VI_UNLOCK(devvp);
475 		MALLOC(lkp, struct lock *, sizeof(struct lock), M_UFSMNT,
476 		    0);
477 		lockinit(lkp, PVFS, "snaplk", VLKTIMEOUT,
478 		    LK_CANRECURSE | LK_NOPAUSE);
479 		VI_LOCK(vp);
480 		vp->v_vnlock = lkp;
481 	}
482 	vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE | LK_RETRY, td);
483 	transferlockers(&vp->v_lock, vp->v_vnlock);
484 	lockmgr(&vp->v_lock, LK_RELEASE, NULL, td);
485 	/*
486 	 * Record snapshot inode. Since this is the newest snapshot,
487 	 * it must be placed at the end of the list.
488 	 */
489 	VI_LOCK(devvp);
490 	fs->fs_snapinum[snaploc] = ip->i_number;
491 	if (ip->i_nextsnap.tqe_prev != 0)
492 		panic("ffs_snapshot: %d already on list", ip->i_number);
493 	TAILQ_INSERT_TAIL(snaphead, ip, i_nextsnap);
494 	devvp->v_rdev->si_copyonwrite = ffs_copyonwrite;
495 	devvp->v_vflag |= VV_COPYONWRITE;
496 	VI_UNLOCK(devvp);
497 	ASSERT_VOP_LOCKED(vp, "ffs_snapshot vp");
498 	vp->v_vflag |= VV_SYSTEM;
499 out1:
500 	/*
501 	 * Resume operation on filesystem.
502 	 */
503 	vfs_write_resume(vp->v_mount);
504 	vn_start_write(NULL, &wrtmp, V_WAIT);
505 	if (collectsnapstats && starttime.tv_sec > 0) {
506 		nanotime(&endtime);
507 		timespecsub(&endtime, &starttime);
508 		printf("%s: suspended %ld.%03ld sec, redo %ld of %d\n",
509 		    vp->v_mount->mnt_stat.f_mntonname, (long)endtime.tv_sec,
510 		    endtime.tv_nsec / 1000000, redo, fs->fs_ncg);
511 	}
512 	if (sbp == NULL)
513 		goto out;
514 	/*
515 	 * Copy allocation information from all the snapshots in
516 	 * this snapshot and then expunge them from its view.
517 	 */
518 	snaphead = &devvp->v_rdev->si_snapshots;
519 	TAILQ_FOREACH(xp, snaphead, i_nextsnap) {
520 		if (xp == ip)
521 			break;
522 		if (xp->i_ump->um_fstype == UFS1)
523 			error = expunge_ufs1(vp, xp, fs, snapacct_ufs1,
524 			    BLK_SNAP);
525 		else
526 			error = expunge_ufs2(vp, xp, fs, snapacct_ufs2,
527 			    BLK_SNAP);
528 		if (error) {
529 			fs->fs_snapinum[snaploc] = 0;
530 			goto done;
531 		}
532 	}
533 	/*
534 	 * Allocate the space for the list of preallocated snapshot blocks.
535 	 */
536 	snaplistsize = fs->fs_ncg + howmany(fs->fs_cssize, fs->fs_bsize) +
537 	    FSMAXSNAP + 1 /* superblock */ + 1 /* last block */ + 1 /* size */;
538 	MALLOC(snapblklist, daddr_t *, snaplistsize * sizeof(daddr_t),
539 	    M_UFSMNT, 0);
540 	ip->i_snapblklist = &snapblklist[1];
541 	/*
542 	 * Expunge the blocks used by the snapshots from the set of
543 	 * blocks marked as used in the snapshot bitmaps. Also, collect
544 	 * the list of allocated blocks in i_snapblklist.
545 	 */
546 	if (ip->i_ump->um_fstype == UFS1)
547 		error = expunge_ufs1(vp, ip, copy_fs, mapacct_ufs1, BLK_SNAP);
548 	else
549 		error = expunge_ufs2(vp, ip, copy_fs, mapacct_ufs2, BLK_SNAP);
550 	if (error) {
551 		fs->fs_snapinum[snaploc] = 0;
552 		FREE(snapblklist, M_UFSMNT);
553 		goto done;
554 	}
555 	snaplistsize = ip->i_snapblklist - snapblklist;
556 	snapblklist[0] = snaplistsize;
557 	ip->i_snapblklist = 0;
558 	/*
559 	 * Write out the list of allocated blocks to the end of the snapshot.
560 	 */
561 	auio.uio_iov = &aiov;
562 	auio.uio_iovcnt = 1;
563 	aiov.iov_base = (void *)snapblklist;
564 	aiov.iov_len = snaplistsize * sizeof(daddr_t);
565 	auio.uio_resid = aiov.iov_len;;
566 	auio.uio_offset = ip->i_size;
567 	auio.uio_segflg = UIO_SYSSPACE;
568 	auio.uio_rw = UIO_WRITE;
569 	auio.uio_td = td;
570 	if ((error = VOP_WRITE(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
571 		fs->fs_snapinum[snaploc] = 0;
572 		FREE(snapblklist, M_UFSMNT);
573 		goto done;
574 	}
575 	/*
576 	 * Write the superblock and its summary information
577 	 * to the snapshot.
578 	 */
579 	blkno = fragstoblks(fs, fs->fs_csaddr);
580 	len = howmany(fs->fs_cssize, fs->fs_bsize);
581 	space = copy_fs->fs_csp;
582 	for (loc = 0; loc < len; loc++) {
583 		error = bread(vp, blkno + loc, fs->fs_bsize, KERNCRED, &nbp);
584 		if (error) {
585 			brelse(nbp);
586 			fs->fs_snapinum[snaploc] = 0;
587 			FREE(snapblklist, M_UFSMNT);
588 			goto done;
589 		}
590 		bcopy(space, nbp->b_data, fs->fs_bsize);
591 		space = (char *)space + fs->fs_bsize;
592 		bawrite(nbp);
593 	}
594 	/*
595 	 * As this is the newest list, it is the most inclusive, so
596 	 * should replace the previous list.
597 	 */
598 	VI_LOCK(devvp);
599 	FREE(devvp->v_rdev->si_snapblklist, M_UFSMNT);
600 	devvp->v_rdev->si_snapblklist = snapblklist;
601 	devvp->v_rdev->si_snaplistsize = snaplistsize;
602 	VI_UNLOCK(devvp);
603 done:
604 	free(copy_fs->fs_csp, M_UFSMNT);
605 	bawrite(sbp);
606 out:
607 	if (saved_nice > 0)
608 		td->td_ksegrp->kg_nice = saved_nice;
609 	if (fs->fs_active != 0) {
610 		FREE(fs->fs_active, M_DEVBUF);
611 		fs->fs_active = 0;
612 	}
613 	mp->mnt_flag = flag;
614 	if (error)
615 		(void) UFS_TRUNCATE(vp, (off_t)0, 0, NOCRED, td);
616 	(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
617 	if (error)
618 		vput(vp);
619 	else
620 		VOP_UNLOCK(vp, 0, td);
621 	vn_finished_write(wrtmp);
622 	return (error);
623 }
624 
625 /*
626  * Copy a cylinder group map. All the unallocated blocks are marked
627  * BLK_NOCOPY so that the snapshot knows that it need not copy them
628  * if they are later written. If passno is one, then this is a first
629  * pass, so only setting needs to be done. If passno is 2, then this
630  * is a revision to a previous pass which must be undone as the
631  * replacement pass is done.
632  */
633 static int
634 cgaccount(cg, vp, nbp, passno)
635 	int cg;
636 	struct vnode *vp;
637 	struct buf *nbp;
638 	int passno;
639 {
640 	struct buf *bp, *ibp;
641 	struct inode *ip;
642 	struct cg *cgp;
643 	struct fs *fs;
644 	ufs2_daddr_t base, numblks;
645 	int error, len, loc, indiroff;
646 
647 	ip = VTOI(vp);
648 	fs = ip->i_fs;
649 	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
650 		(int)fs->fs_cgsize, KERNCRED, &bp);
651 	if (error) {
652 		brelse(bp);
653 		return (error);
654 	}
655 	cgp = (struct cg *)bp->b_data;
656 	if (!cg_chkmagic(cgp)) {
657 		brelse(bp);
658 		return (EIO);
659 	}
660 	atomic_set_int(&ACTIVECGNUM(fs, cg), ACTIVECGOFF(cg));
661 	bcopy(bp->b_data, nbp->b_data, fs->fs_cgsize);
662 	if (fs->fs_cgsize < fs->fs_bsize)
663 		bzero(&nbp->b_data[fs->fs_cgsize],
664 		    fs->fs_bsize - fs->fs_cgsize);
665 	if (passno == 2)
666 		nbp->b_flags |= B_VALIDSUSPWRT;
667 	numblks = howmany(fs->fs_size, fs->fs_frag);
668 	len = howmany(fs->fs_fpg, fs->fs_frag);
669 	base = cg * fs->fs_fpg / fs->fs_frag;
670 	if (base + len >= numblks)
671 		len = numblks - base - 1;
672 	loc = 0;
673 	if (base < NDADDR) {
674 		for ( ; loc < NDADDR; loc++) {
675 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
676 				DIP(ip, i_db[loc]) = BLK_NOCOPY;
677 			else if (passno == 2 && DIP(ip, i_db[loc])== BLK_NOCOPY)
678 				DIP(ip, i_db[loc]) = 0;
679 			else if (passno == 1 && DIP(ip, i_db[loc])== BLK_NOCOPY)
680 				panic("ffs_snapshot: lost direct block");
681 		}
682 	}
683 	error = UFS_BALLOC(vp, lblktosize(fs, (off_t)(base + loc)),
684 	    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
685 	if (error) {
686 		brelse(bp);
687 		return (error);
688 	}
689 	indiroff = (base + loc - NDADDR) % NINDIR(fs);
690 	for ( ; loc < len; loc++, indiroff++) {
691 		if (indiroff >= NINDIR(fs)) {
692 			if (passno == 2)
693 				ibp->b_flags |= B_VALIDSUSPWRT;
694 			bawrite(ibp);
695 			error = UFS_BALLOC(vp,
696 			    lblktosize(fs, (off_t)(base + loc)),
697 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
698 			if (error) {
699 				brelse(bp);
700 				return (error);
701 			}
702 			indiroff = 0;
703 		}
704 		if (ip->i_ump->um_fstype == UFS1) {
705 			if (ffs_isblock(fs, cg_blksfree(cgp), loc))
706 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
707 				    BLK_NOCOPY;
708 			else if (passno == 2 && ((ufs1_daddr_t *)(ibp->b_data))
709 			    [indiroff] == BLK_NOCOPY)
710 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = 0;
711 			else if (passno == 1 && ((ufs1_daddr_t *)(ibp->b_data))
712 			    [indiroff] == BLK_NOCOPY)
713 				panic("ffs_snapshot: lost indirect block");
714 			continue;
715 		}
716 		if (ffs_isblock(fs, cg_blksfree(cgp), loc))
717 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = BLK_NOCOPY;
718 		else if (passno == 2 &&
719 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
720 			((ufs2_daddr_t *)(ibp->b_data))[indiroff] = 0;
721 		else if (passno == 1 &&
722 		    ((ufs2_daddr_t *)(ibp->b_data)) [indiroff] == BLK_NOCOPY)
723 			panic("ffs_snapshot: lost indirect block");
724 	}
725 	bqrelse(bp);
726 	if (passno == 2)
727 		ibp->b_flags |= B_VALIDSUSPWRT;
728 	bdwrite(ibp);
729 	return (0);
730 }
731 
732 /*
733  * Before expunging a snapshot inode, note all the
734  * blocks that it claims with BLK_SNAP so that fsck will
735  * be able to account for those blocks properly and so
736  * that this snapshot knows that it need not copy them
737  * if the other snapshot holding them is freed. This code
738  * is reproduced once each for UFS1 and UFS2.
739  */
740 static int
741 expunge_ufs1(snapvp, cancelip, fs, acctfunc, expungetype)
742 	struct vnode *snapvp;
743 	struct inode *cancelip;
744 	struct fs *fs;
745 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
746 	    struct fs *, ufs_lbn_t, int);
747 	int expungetype;
748 {
749 	int i, error, indiroff;
750 	ufs_lbn_t lbn, rlbn;
751 	ufs2_daddr_t len, blkno, numblks, blksperindir;
752 	struct ufs1_dinode *dip;
753 	struct thread *td = curthread;
754 	struct buf *bp;
755 
756 	/*
757 	 * Prepare to expunge the inode. If its inode block has not
758 	 * yet been copied, then allocate and fill the copy.
759 	 */
760 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
761 	blkno = 0;
762 	if (lbn < NDADDR) {
763 		blkno = VTOI(snapvp)->i_din1->di_db[lbn];
764 	} else {
765 		td->td_proc->p_flag |= P_COWINPROGRESS;
766 		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
767 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
768 		td->td_proc->p_flag &= ~P_COWINPROGRESS;
769 		if (error)
770 			return (error);
771 		indiroff = (lbn - NDADDR) % NINDIR(fs);
772 		blkno = ((ufs1_daddr_t *)(bp->b_data))[indiroff];
773 		bqrelse(bp);
774 	}
775 	if (blkno != 0) {
776 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
777 			return (error);
778 	} else {
779 		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
780 		    fs->fs_bsize, KERNCRED, 0, &bp);
781 		if (error)
782 			return (error);
783 		if ((error = readblock(bp, lbn)) != 0)
784 			return (error);
785 	}
786 	/*
787 	 * Set a snapshot inode to be a zero length file, regular files
788 	 * to be completely unallocated.
789 	 */
790 	dip = (struct ufs1_dinode *)bp->b_data +
791 	    ino_to_fsbo(fs, cancelip->i_number);
792 	if (expungetype == BLK_NOCOPY)
793 		dip->di_mode = 0;
794 	dip->di_size = 0;
795 	dip->di_blocks = 0;
796 	dip->di_flags &= ~SF_SNAPSHOT;
797 	bzero(&dip->di_db[0], (NDADDR + NIADDR) * sizeof(ufs1_daddr_t));
798 	bdwrite(bp);
799 	/*
800 	 * Now go through and expunge all the blocks in the file
801 	 * using the function requested.
802 	 */
803 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
804 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_db[0],
805 	    &cancelip->i_din1->di_db[NDADDR], fs, 0, expungetype)))
806 		return (error);
807 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din1->di_ib[0],
808 	    &cancelip->i_din1->di_ib[NIADDR], fs, -1, expungetype)))
809 		return (error);
810 	blksperindir = 1;
811 	lbn = -NDADDR;
812 	len = numblks - NDADDR;
813 	rlbn = NDADDR;
814 	for (i = 0; len > 0 && i < NIADDR; i++) {
815 		error = indiracct_ufs1(snapvp, ITOV(cancelip), i,
816 		    cancelip->i_din1->di_ib[i], lbn, rlbn, len,
817 		    blksperindir, fs, acctfunc, expungetype);
818 		if (error)
819 			return (error);
820 		blksperindir *= NINDIR(fs);
821 		lbn -= blksperindir + 1;
822 		len -= blksperindir;
823 		rlbn += blksperindir;
824 	}
825 	return (0);
826 }
827 
828 /*
829  * Descend an indirect block chain for vnode cancelvp accounting for all
830  * its indirect blocks in snapvp.
831  */
832 static int
833 indiracct_ufs1(snapvp, cancelvp, level, blkno, lbn, rlbn, remblks,
834 	    blksperindir, fs, acctfunc, expungetype)
835 	struct vnode *snapvp;
836 	struct vnode *cancelvp;
837 	int level;
838 	ufs1_daddr_t blkno;
839 	ufs_lbn_t lbn;
840 	ufs_lbn_t rlbn;
841 	ufs_lbn_t remblks;
842 	ufs_lbn_t blksperindir;
843 	struct fs *fs;
844 	int (*acctfunc)(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
845 	    struct fs *, ufs_lbn_t, int);
846 	int expungetype;
847 {
848 	int error, num, i;
849 	ufs_lbn_t subblksperindir;
850 	struct indir indirs[NIADDR + 2];
851 	ufs1_daddr_t last, *bap;
852 	struct buf *bp;
853 
854 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
855 		return (error);
856 	if (lbn != indirs[num - 1 - level].in_lbn || blkno == 0 || num < 2)
857 		panic("indiracct: botched params");
858 	/*
859 	 * We have to expand bread here since it will deadlock looking
860 	 * up the block number for any blocks that are not in the cache.
861 	 */
862 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0);
863 	bp->b_blkno = fsbtodb(fs, blkno);
864 	if ((bp->b_flags & (B_DONE | B_DELWRI)) == 0 &&
865 	    (error = readblock(bp, fragstoblks(fs, blkno)))) {
866 		brelse(bp);
867 		return (error);
868 	}
869 	/*
870 	 * Account for the block pointers in this indirect block.
871 	 */
872 	last = howmany(remblks, blksperindir);
873 	if (last > NINDIR(fs))
874 		last = NINDIR(fs);
875 	MALLOC(bap, ufs1_daddr_t *, fs->fs_bsize, M_DEVBUF, 0);
876 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
877 	bqrelse(bp);
878 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
879 	    level == 0 ? rlbn : -1, expungetype);
880 	if (error || level == 0)
881 		goto out;
882 	/*
883 	 * Account for the block pointers in each of the indirect blocks
884 	 * in the levels below us.
885 	 */
886 	subblksperindir = blksperindir / NINDIR(fs);
887 	for (lbn++, level--, i = 0; i < last; i++) {
888 		error = indiracct_ufs1(snapvp, cancelvp, level, bap[i], lbn,
889 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
890 		if (error)
891 			goto out;
892 		rlbn += blksperindir;
893 		lbn -= blksperindir;
894 		remblks -= blksperindir;
895 	}
896 out:
897 	FREE(bap, M_DEVBUF);
898 	return (error);
899 }
900 
901 /*
902  * Do both snap accounting and map accounting.
903  */
904 static int
905 fullacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype)
906 	struct vnode *vp;
907 	ufs1_daddr_t *oldblkp, *lastblkp;
908 	struct fs *fs;
909 	ufs_lbn_t lblkno;
910 	int exptype;	/* BLK_SNAP or BLK_NOCOPY */
911 {
912 	int error;
913 
914 	if ((error = snapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
915 		return (error);
916 	return (mapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, exptype));
917 }
918 
919 /*
920  * Identify a set of blocks allocated in a snapshot inode.
921  */
922 static int
923 snapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
924 	struct vnode *vp;
925 	ufs1_daddr_t *oldblkp, *lastblkp;
926 	struct fs *fs;
927 	ufs_lbn_t lblkno;
928 	int expungetype;	/* BLK_SNAP or BLK_NOCOPY */
929 {
930 	struct inode *ip = VTOI(vp);
931 	ufs1_daddr_t blkno, *blkp;
932 	ufs_lbn_t lbn;
933 	struct buf *ibp;
934 	int error;
935 
936 	for ( ; oldblkp < lastblkp; oldblkp++) {
937 		blkno = *oldblkp;
938 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
939 			continue;
940 		lbn = fragstoblks(fs, blkno);
941 		if (lbn < NDADDR) {
942 			blkp = &ip->i_din1->di_db[lbn];
943 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
944 		} else {
945 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
946 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
947 			if (error)
948 				return (error);
949 			blkp = &((ufs1_daddr_t *)(ibp->b_data))
950 			    [(lbn - NDADDR) % NINDIR(fs)];
951 		}
952 		/*
953 		 * If we are expunging a snapshot vnode and we
954 		 * find a block marked BLK_NOCOPY, then it is
955 		 * one that has been allocated to this snapshot after
956 		 * we took our current snapshot and can be ignored.
957 		 */
958 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
959 			if (lbn >= NDADDR)
960 				brelse(ibp);
961 		} else {
962 			if (*blkp != 0)
963 				panic("snapacct: bad block");
964 			*blkp = expungetype;
965 			if (lbn >= NDADDR)
966 				bdwrite(ibp);
967 		}
968 	}
969 	return (0);
970 }
971 
972 /*
973  * Account for a set of blocks allocated in a snapshot inode.
974  */
975 static int
976 mapacct_ufs1(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
977 	struct vnode *vp;
978 	ufs1_daddr_t *oldblkp, *lastblkp;
979 	struct fs *fs;
980 	ufs_lbn_t lblkno;
981 	int expungetype;
982 {
983 	ufs1_daddr_t blkno;
984 	struct inode *ip;
985 	ino_t inum;
986 	int acctit;
987 
988 	ip = VTOI(vp);
989 	inum = ip->i_number;
990 	if (lblkno == -1)
991 		acctit = 0;
992 	else
993 		acctit = 1;
994 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
995 		blkno = *oldblkp;
996 		if (blkno == 0 || blkno == BLK_NOCOPY)
997 			continue;
998 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
999 			*ip->i_snapblklist++ = lblkno;
1000 		if (blkno == BLK_SNAP)
1001 			blkno = blkstofrags(fs, lblkno);
1002 		ffs_blkfree(fs, vp, blkno, fs->fs_bsize, inum);
1003 	}
1004 	return (0);
1005 }
1006 
1007 /*
1008  * Before expunging a snapshot inode, note all the
1009  * blocks that it claims with BLK_SNAP so that fsck will
1010  * be able to account for those blocks properly and so
1011  * that this snapshot knows that it need not copy them
1012  * if the other snapshot holding them is freed. This code
1013  * is reproduced once each for UFS1 and UFS2.
1014  */
1015 static int
1016 expunge_ufs2(snapvp, cancelip, fs, acctfunc, expungetype)
1017 	struct vnode *snapvp;
1018 	struct inode *cancelip;
1019 	struct fs *fs;
1020 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1021 	    struct fs *, ufs_lbn_t, int);
1022 	int expungetype;
1023 {
1024 	int i, error, indiroff;
1025 	ufs_lbn_t lbn, rlbn;
1026 	ufs2_daddr_t len, blkno, numblks, blksperindir;
1027 	struct ufs2_dinode *dip;
1028 	struct thread *td = curthread;
1029 	struct buf *bp;
1030 
1031 	/*
1032 	 * Prepare to expunge the inode. If its inode block has not
1033 	 * yet been copied, then allocate and fill the copy.
1034 	 */
1035 	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1036 	blkno = 0;
1037 	if (lbn < NDADDR) {
1038 		blkno = VTOI(snapvp)->i_din2->di_db[lbn];
1039 	} else {
1040 		td->td_proc->p_flag |= P_COWINPROGRESS;
1041 		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
1042 		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1043 		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1044 		if (error)
1045 			return (error);
1046 		indiroff = (lbn - NDADDR) % NINDIR(fs);
1047 		blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
1048 		bqrelse(bp);
1049 	}
1050 	if (blkno != 0) {
1051 		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1052 			return (error);
1053 	} else {
1054 		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
1055 		    fs->fs_bsize, KERNCRED, 0, &bp);
1056 		if (error)
1057 			return (error);
1058 		if ((error = readblock(bp, lbn)) != 0)
1059 			return (error);
1060 	}
1061 	/*
1062 	 * Set a snapshot inode to be a zero length file, regular files
1063 	 * to be completely unallocated.
1064 	 */
1065 	dip = (struct ufs2_dinode *)bp->b_data +
1066 	    ino_to_fsbo(fs, cancelip->i_number);
1067 	if (expungetype == BLK_NOCOPY)
1068 		dip->di_mode = 0;
1069 	dip->di_size = 0;
1070 	dip->di_blocks = 0;
1071 	dip->di_flags &= ~SF_SNAPSHOT;
1072 	bzero(&dip->di_db[0], (NDADDR + NIADDR) * sizeof(ufs2_daddr_t));
1073 	bdwrite(bp);
1074 	/*
1075 	 * Now go through and expunge all the blocks in the file
1076 	 * using the function requested.
1077 	 */
1078 	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1079 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_db[0],
1080 	    &cancelip->i_din2->di_db[NDADDR], fs, 0, expungetype)))
1081 		return (error);
1082 	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_ib[0],
1083 	    &cancelip->i_din2->di_ib[NIADDR], fs, -1, expungetype)))
1084 		return (error);
1085 	blksperindir = 1;
1086 	lbn = -NDADDR;
1087 	len = numblks - NDADDR;
1088 	rlbn = NDADDR;
1089 	for (i = 0; len > 0 && i < NIADDR; i++) {
1090 		error = indiracct_ufs2(snapvp, ITOV(cancelip), i,
1091 		    cancelip->i_din2->di_ib[i], lbn, rlbn, len,
1092 		    blksperindir, fs, acctfunc, expungetype);
1093 		if (error)
1094 			return (error);
1095 		blksperindir *= NINDIR(fs);
1096 		lbn -= blksperindir + 1;
1097 		len -= blksperindir;
1098 		rlbn += blksperindir;
1099 	}
1100 	return (0);
1101 }
1102 
1103 /*
1104  * Descend an indirect block chain for vnode cancelvp accounting for all
1105  * its indirect blocks in snapvp.
1106  */
1107 static int
1108 indiracct_ufs2(snapvp, cancelvp, level, blkno, lbn, rlbn, remblks,
1109 	    blksperindir, fs, acctfunc, expungetype)
1110 	struct vnode *snapvp;
1111 	struct vnode *cancelvp;
1112 	int level;
1113 	ufs2_daddr_t blkno;
1114 	ufs_lbn_t lbn;
1115 	ufs_lbn_t rlbn;
1116 	ufs_lbn_t remblks;
1117 	ufs_lbn_t blksperindir;
1118 	struct fs *fs;
1119 	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1120 	    struct fs *, ufs_lbn_t, int);
1121 	int expungetype;
1122 {
1123 	int error, num, i;
1124 	ufs_lbn_t subblksperindir;
1125 	struct indir indirs[NIADDR + 2];
1126 	ufs2_daddr_t last, *bap;
1127 	struct buf *bp;
1128 
1129 	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1130 		return (error);
1131 	if (lbn != indirs[num - 1 - level].in_lbn || blkno == 0 || num < 2)
1132 		panic("indiracct: botched params");
1133 	/*
1134 	 * We have to expand bread here since it will deadlock looking
1135 	 * up the block number for any blocks that are not in the cache.
1136 	 */
1137 	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0);
1138 	bp->b_blkno = fsbtodb(fs, blkno);
1139 	if ((bp->b_flags & (B_DONE | B_DELWRI)) == 0 &&
1140 	    (error = readblock(bp, fragstoblks(fs, blkno)))) {
1141 		brelse(bp);
1142 		return (error);
1143 	}
1144 	/*
1145 	 * Account for the block pointers in this indirect block.
1146 	 */
1147 	last = howmany(remblks, blksperindir);
1148 	if (last > NINDIR(fs))
1149 		last = NINDIR(fs);
1150 	MALLOC(bap, ufs2_daddr_t *, fs->fs_bsize, M_DEVBUF, 0);
1151 	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1152 	bqrelse(bp);
1153 	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1154 	    level == 0 ? rlbn : -1, expungetype);
1155 	if (error || level == 0)
1156 		goto out;
1157 	/*
1158 	 * Account for the block pointers in each of the indirect blocks
1159 	 * in the levels below us.
1160 	 */
1161 	subblksperindir = blksperindir / NINDIR(fs);
1162 	for (lbn++, level--, i = 0; i < last; i++) {
1163 		error = indiracct_ufs2(snapvp, cancelvp, level, bap[i], lbn,
1164 		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1165 		if (error)
1166 			goto out;
1167 		rlbn += blksperindir;
1168 		lbn -= blksperindir;
1169 		remblks -= blksperindir;
1170 	}
1171 out:
1172 	FREE(bap, M_DEVBUF);
1173 	return (error);
1174 }
1175 
1176 /*
1177  * Do both snap accounting and map accounting.
1178  */
1179 static int
1180 fullacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)
1181 	struct vnode *vp;
1182 	ufs2_daddr_t *oldblkp, *lastblkp;
1183 	struct fs *fs;
1184 	ufs_lbn_t lblkno;
1185 	int exptype;	/* BLK_SNAP or BLK_NOCOPY */
1186 {
1187 	int error;
1188 
1189 	if ((error = snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1190 		return (error);
1191 	return (mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1192 }
1193 
1194 /*
1195  * Identify a set of blocks allocated in a snapshot inode.
1196  */
1197 static int
1198 snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
1199 	struct vnode *vp;
1200 	ufs2_daddr_t *oldblkp, *lastblkp;
1201 	struct fs *fs;
1202 	ufs_lbn_t lblkno;
1203 	int expungetype;	/* BLK_SNAP or BLK_NOCOPY */
1204 {
1205 	struct inode *ip = VTOI(vp);
1206 	ufs2_daddr_t blkno, *blkp;
1207 	ufs_lbn_t lbn;
1208 	struct buf *ibp;
1209 	int error;
1210 
1211 	for ( ; oldblkp < lastblkp; oldblkp++) {
1212 		blkno = *oldblkp;
1213 		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1214 			continue;
1215 		lbn = fragstoblks(fs, blkno);
1216 		if (lbn < NDADDR) {
1217 			blkp = &ip->i_din2->di_db[lbn];
1218 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1219 		} else {
1220 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1221 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1222 			if (error)
1223 				return (error);
1224 			blkp = &((ufs2_daddr_t *)(ibp->b_data))
1225 			    [(lbn - NDADDR) % NINDIR(fs)];
1226 		}
1227 		/*
1228 		 * If we are expunging a snapshot vnode and we
1229 		 * find a block marked BLK_NOCOPY, then it is
1230 		 * one that has been allocated to this snapshot after
1231 		 * we took our current snapshot and can be ignored.
1232 		 */
1233 		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1234 			if (lbn >= NDADDR)
1235 				brelse(ibp);
1236 		} else {
1237 			if (*blkp != 0)
1238 				panic("snapacct: bad block");
1239 			*blkp = expungetype;
1240 			if (lbn >= NDADDR)
1241 				bdwrite(ibp);
1242 		}
1243 	}
1244 	return (0);
1245 }
1246 
1247 /*
1248  * Account for a set of blocks allocated in a snapshot inode.
1249  */
1250 static int
1251 mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
1252 	struct vnode *vp;
1253 	ufs2_daddr_t *oldblkp, *lastblkp;
1254 	struct fs *fs;
1255 	ufs_lbn_t lblkno;
1256 	int expungetype;
1257 {
1258 	ufs2_daddr_t blkno;
1259 	struct inode *ip;
1260 	ino_t inum;
1261 	int acctit;
1262 
1263 	ip = VTOI(vp);
1264 	inum = ip->i_number;
1265 	if (lblkno == -1)
1266 		acctit = 0;
1267 	else
1268 		acctit = 1;
1269 	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1270 		blkno = *oldblkp;
1271 		if (blkno == 0 || blkno == BLK_NOCOPY)
1272 			continue;
1273 		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
1274 			*ip->i_snapblklist++ = lblkno;
1275 		if (blkno == BLK_SNAP)
1276 			blkno = blkstofrags(fs, lblkno);
1277 		ffs_blkfree(fs, vp, blkno, fs->fs_bsize, inum);
1278 	}
1279 	return (0);
1280 }
1281 
1282 /*
1283  * Decrement extra reference on snapshot when last name is removed.
1284  * It will not be freed until the last open reference goes away.
1285  */
1286 void
1287 ffs_snapgone(ip)
1288 	struct inode *ip;
1289 {
1290 	struct inode *xp;
1291 	struct fs *fs;
1292 	int snaploc;
1293 
1294 	/*
1295 	 * Find snapshot in incore list.
1296 	 */
1297 	TAILQ_FOREACH(xp, &ip->i_devvp->v_rdev->si_snapshots, i_nextsnap)
1298 		if (xp == ip)
1299 			break;
1300 	if (xp != NULL)
1301 		vrele(ITOV(ip));
1302 	else if (snapdebug)
1303 		printf("ffs_snapgone: lost snapshot vnode %d\n",
1304 		    ip->i_number);
1305 	/*
1306 	 * Delete snapshot inode from superblock. Keep list dense.
1307 	 */
1308 	fs = ip->i_fs;
1309 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
1310 		if (fs->fs_snapinum[snaploc] == ip->i_number)
1311 			break;
1312 	if (snaploc < FSMAXSNAP) {
1313 		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
1314 			if (fs->fs_snapinum[snaploc] == 0)
1315 				break;
1316 			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
1317 		}
1318 		fs->fs_snapinum[snaploc - 1] = 0;
1319 	}
1320 }
1321 
1322 /*
1323  * Prepare a snapshot file for being removed.
1324  */
1325 void
1326 ffs_snapremove(vp)
1327 	struct vnode *vp;
1328 {
1329 	struct inode *ip;
1330 	struct vnode *devvp;
1331 	struct lock *lkp;
1332 	struct buf *ibp;
1333 	struct fs *fs;
1334 	struct thread *td = curthread;
1335 	ufs2_daddr_t numblks, blkno, dblk, *snapblklist;
1336 	int error, loc, last;
1337 
1338 	ip = VTOI(vp);
1339 	fs = ip->i_fs;
1340 	devvp = ip->i_devvp;
1341 	/*
1342 	 * If active, delete from incore list (this snapshot may
1343 	 * already have been in the process of being deleted, so
1344 	 * would not have been active).
1345 	 *
1346 	 * Clear copy-on-write flag if last snapshot.
1347 	 */
1348 	if (ip->i_nextsnap.tqe_prev != 0) {
1349 		VI_LOCK(devvp);
1350 		lockmgr(&vp->v_lock, LK_INTERLOCK | LK_EXCLUSIVE,
1351 		    VI_MTX(devvp), td);
1352 		VI_LOCK(devvp);
1353 		TAILQ_REMOVE(&devvp->v_rdev->si_snapshots, ip, i_nextsnap);
1354 		ip->i_nextsnap.tqe_prev = 0;
1355 		lkp = vp->v_vnlock;
1356 		vp->v_vnlock = &vp->v_lock;
1357 		lockmgr(lkp, LK_RELEASE, NULL, td);
1358 		if (TAILQ_FIRST(&devvp->v_rdev->si_snapshots) != 0) {
1359 			VI_UNLOCK(devvp);
1360 		} else {
1361 			snapblklist = devvp->v_rdev->si_snapblklist;
1362 			devvp->v_rdev->si_snapblklist = 0;
1363 			devvp->v_rdev->si_snaplistsize = 0;
1364 			devvp->v_rdev->si_copyonwrite = 0;
1365 			devvp->v_vflag &= ~VV_COPYONWRITE;
1366 			lockmgr(lkp, LK_DRAIN|LK_INTERLOCK, VI_MTX(devvp), td);
1367 			lockmgr(lkp, LK_RELEASE, NULL, td);
1368 			lockdestroy(lkp);
1369 			FREE(lkp, M_UFSMNT);
1370 			FREE(snapblklist, M_UFSMNT);
1371 		}
1372 	}
1373 	/*
1374 	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
1375 	 * snapshots that want them (see ffs_snapblkfree below).
1376 	 */
1377 	for (blkno = 1; blkno < NDADDR; blkno++) {
1378 		dblk = DIP(ip, i_db[blkno]);
1379 		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1380 			DIP(ip, i_db[blkno]) = 0;
1381 		else if ((dblk == blkstofrags(fs, blkno) &&
1382 		     ffs_snapblkfree(fs, ip->i_devvp, dblk, fs->fs_bsize,
1383 		     ip->i_number))) {
1384 			DIP(ip, i_blocks) -= btodb(fs->fs_bsize);
1385 			DIP(ip, i_db[blkno]) = 0;
1386 		}
1387 	}
1388 	numblks = howmany(ip->i_size, fs->fs_bsize);
1389 	for (blkno = NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
1390 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
1391 		    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1392 		if (error)
1393 			continue;
1394 		if (fs->fs_size - blkno > NINDIR(fs))
1395 			last = NINDIR(fs);
1396 		else
1397 			last = fs->fs_size - blkno;
1398 		for (loc = 0; loc < last; loc++) {
1399 			if (ip->i_ump->um_fstype == UFS1) {
1400 				dblk = ((ufs1_daddr_t *)(ibp->b_data))[loc];
1401 				if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1402 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1403 				else if ((dblk == blkstofrags(fs, blkno) &&
1404 				     ffs_snapblkfree(fs, ip->i_devvp, dblk,
1405 				     fs->fs_bsize, ip->i_number))) {
1406 					ip->i_din1->di_blocks -=
1407 					    btodb(fs->fs_bsize);
1408 					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1409 				}
1410 				continue;
1411 			}
1412 			dblk = ((ufs2_daddr_t *)(ibp->b_data))[loc];
1413 			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1414 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1415 			else if ((dblk == blkstofrags(fs, blkno) &&
1416 			     ffs_snapblkfree(fs, ip->i_devvp, dblk,
1417 			     fs->fs_bsize, ip->i_number))) {
1418 				ip->i_din2->di_blocks -= btodb(fs->fs_bsize);
1419 				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1420 			}
1421 		}
1422 		bawrite(ibp);
1423 	}
1424 	/*
1425 	 * Clear snapshot flag and drop reference.
1426 	 */
1427 	ip->i_flags &= ~SF_SNAPSHOT;
1428 	DIP(ip, i_flags) = ip->i_flags;
1429 	ip->i_flag |= IN_CHANGE | IN_UPDATE;
1430 }
1431 
1432 /*
1433  * Notification that a block is being freed. Return zero if the free
1434  * should be allowed to proceed. Return non-zero if the snapshot file
1435  * wants to claim the block. The block will be claimed if it is an
1436  * uncopied part of one of the snapshots. It will be freed if it is
1437  * either a BLK_NOCOPY or has already been copied in all of the snapshots.
1438  * If a fragment is being freed, then all snapshots that care about
1439  * it must make a copy since a snapshot file can only claim full sized
1440  * blocks. Note that if more than one snapshot file maps the block,
1441  * we can pick one at random to claim it. Since none of the snapshots
1442  * can change, we are assurred that they will all see the same unmodified
1443  * image. When deleting a snapshot file (see ffs_snapremove above), we
1444  * must push any of these claimed blocks to one of the other snapshots
1445  * that maps it. These claimed blocks are easily identified as they will
1446  * have a block number equal to their logical block number within the
1447  * snapshot. A copied block can never have this property because they
1448  * must always have been allocated from a BLK_NOCOPY location.
1449  */
1450 int
1451 ffs_snapblkfree(fs, devvp, bno, size, inum)
1452 	struct fs *fs;
1453 	struct vnode *devvp;
1454 	ufs2_daddr_t bno;
1455 	long size;
1456 	ino_t inum;
1457 {
1458 	struct buf *ibp, *cbp, *savedcbp = 0;
1459 	struct thread *td = curthread;
1460 	struct inode *ip;
1461 	struct vnode *vp = NULL;
1462 	ufs_lbn_t lbn;
1463 	ufs2_daddr_t blkno;
1464 	int indiroff = 0, snapshot_locked = 0, error = 0, claimedblk = 0;
1465 	struct snaphead *snaphead;
1466 
1467 	lbn = fragstoblks(fs, bno);
1468 retry:
1469 	VI_LOCK(devvp);
1470 	snaphead = &devvp->v_rdev->si_snapshots;
1471 	TAILQ_FOREACH(ip, snaphead, i_nextsnap) {
1472 		vp = ITOV(ip);
1473 		/*
1474 		 * Lookup block being written.
1475 		 */
1476 		if (lbn < NDADDR) {
1477 			blkno = DIP(ip, i_db[lbn]);
1478 		} else {
1479 			if (snapshot_locked == 0 &&
1480 			    lockmgr(vp->v_vnlock,
1481 			      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1482 			      VI_MTX(devvp), td) != 0)
1483 				goto retry;
1484 			snapshot_locked = 1;
1485 			td->td_proc->p_flag |= P_COWINPROGRESS;
1486 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1487 			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1488 			td->td_proc->p_flag &= ~P_COWINPROGRESS;
1489 			if (error)
1490 				break;
1491 			indiroff = (lbn - NDADDR) % NINDIR(fs);
1492 			if (ip->i_ump->um_fstype == UFS1)
1493 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1494 			else
1495 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1496 		}
1497 		/*
1498 		 * Check to see if block needs to be copied.
1499 		 */
1500 		if (blkno == 0) {
1501 			/*
1502 			 * A block that we map is being freed. If it has not
1503 			 * been claimed yet, we will claim or copy it (below).
1504 			 */
1505 			claimedblk = 1;
1506 		} else if (blkno == BLK_SNAP) {
1507 			/*
1508 			 * No previous snapshot claimed the block,
1509 			 * so it will be freed and become a BLK_NOCOPY
1510 			 * (don't care) for us.
1511 			 */
1512 			if (claimedblk)
1513 				panic("snapblkfree: inconsistent block type");
1514 			if (snapshot_locked == 0 &&
1515 			    lockmgr(vp->v_vnlock,
1516 			      LK_INTERLOCK | LK_EXCLUSIVE | LK_NOWAIT,
1517 			      VI_MTX(devvp), td) != 0) {
1518 				if (lbn >= NDADDR)
1519 					bqrelse(ibp);
1520 				vn_lock(vp, LK_EXCLUSIVE | LK_SLEEPFAIL, td);
1521 				goto retry;
1522 			}
1523 			snapshot_locked = 1;
1524 			if (lbn < NDADDR) {
1525 				DIP(ip, i_db[lbn]) = BLK_NOCOPY;
1526 				ip->i_flag |= IN_CHANGE | IN_UPDATE;
1527 			} else if (ip->i_ump->um_fstype == UFS1) {
1528 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
1529 				    BLK_NOCOPY;
1530 				bdwrite(ibp);
1531 			} else {
1532 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] =
1533 				    BLK_NOCOPY;
1534 				bdwrite(ibp);
1535 			}
1536 			continue;
1537 		} else /* BLK_NOCOPY or default */ {
1538 			/*
1539 			 * If the snapshot has already copied the block
1540 			 * (default), or does not care about the block,
1541 			 * it is not needed.
1542 			 */
1543 			if (lbn >= NDADDR)
1544 				bqrelse(ibp);
1545 			continue;
1546 		}
1547 		/*
1548 		 * If this is a full size block, we will just grab it
1549 		 * and assign it to the snapshot inode. Otherwise we
1550 		 * will proceed to copy it. See explanation for this
1551 		 * routine as to why only a single snapshot needs to
1552 		 * claim this block.
1553 		 */
1554 		if (snapshot_locked == 0 &&
1555 		    lockmgr(vp->v_vnlock,
1556 		      LK_INTERLOCK | LK_EXCLUSIVE | LK_NOWAIT,
1557 		      VI_MTX(devvp), td) != 0) {
1558 			if (lbn >= NDADDR)
1559 				bqrelse(ibp);
1560 			vn_lock(vp, LK_EXCLUSIVE | LK_SLEEPFAIL, td);
1561 			goto retry;
1562 		}
1563 		snapshot_locked = 1;
1564 		if (size == fs->fs_bsize) {
1565 #ifdef DEBUG
1566 			if (snapdebug)
1567 				printf("%s %d lbn %jd from inum %d\n",
1568 				    "Grabonremove: snapino", ip->i_number,
1569 				    (intmax_t)lbn, inum);
1570 #endif
1571 			if (lbn < NDADDR) {
1572 				DIP(ip, i_db[lbn]) = bno;
1573 			} else if (ip->i_ump->um_fstype == UFS1) {
1574 				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = bno;
1575 				bdwrite(ibp);
1576 			} else {
1577 				((ufs2_daddr_t *)(ibp->b_data))[indiroff] = bno;
1578 				bdwrite(ibp);
1579 			}
1580 			DIP(ip, i_blocks) += btodb(size);
1581 			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1582 			VOP_UNLOCK(vp, 0, td);
1583 			return (1);
1584 		}
1585 		if (lbn >= NDADDR)
1586 			bqrelse(ibp);
1587 		/*
1588 		 * Allocate the block into which to do the copy. Note that this
1589 		 * allocation will never require any additional allocations for
1590 		 * the snapshot inode.
1591 		 */
1592 		td->td_proc->p_flag |= P_COWINPROGRESS;
1593 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1594 		    fs->fs_bsize, KERNCRED, 0, &cbp);
1595 		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1596 		if (error)
1597 			break;
1598 #ifdef DEBUG
1599 		if (snapdebug)
1600 			printf("%s%d lbn %jd %s %d size %ld to blkno %jd\n",
1601 			    "Copyonremove: snapino ", ip->i_number,
1602 			    (intmax_t)lbn, "for inum", inum, size,
1603 			    (intmax_t)cbp->b_blkno);
1604 #endif
1605 		/*
1606 		 * If we have already read the old block contents, then
1607 		 * simply copy them to the new block. Note that we need
1608 		 * to synchronously write snapshots that have not been
1609 		 * unlinked, and hence will be visible after a crash,
1610 		 * to ensure their integrity.
1611 		 */
1612 		if (savedcbp != 0) {
1613 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1614 			bawrite(cbp);
1615 			if (dopersistence && ip->i_effnlink > 0)
1616 				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1617 			continue;
1618 		}
1619 		/*
1620 		 * Otherwise, read the old block contents into the buffer.
1621 		 */
1622 		if ((error = readblock(cbp, lbn)) != 0) {
1623 			bzero(cbp->b_data, fs->fs_bsize);
1624 			bawrite(cbp);
1625 			if (dopersistence && ip->i_effnlink > 0)
1626 				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1627 			break;
1628 		}
1629 		savedcbp = cbp;
1630 	}
1631 	/*
1632 	 * Note that we need to synchronously write snapshots that
1633 	 * have not been unlinked, and hence will be visible after
1634 	 * a crash, to ensure their integrity.
1635 	 */
1636 	if (savedcbp) {
1637 		vp = savedcbp->b_vp;
1638 		bawrite(savedcbp);
1639 		if (dopersistence && VTOI(vp)->i_effnlink > 0)
1640 			(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1641 	}
1642 	/*
1643 	 * If we have been unable to allocate a block in which to do
1644 	 * the copy, then return non-zero so that the fragment will
1645 	 * not be freed. Although space will be lost, the snapshot
1646 	 * will stay consistent.
1647 	 */
1648 	if (snapshot_locked)
1649 		VOP_UNLOCK(vp, 0, td);
1650 	else
1651 		VI_UNLOCK(devvp);
1652 	return (error);
1653 }
1654 
1655 /*
1656  * Associate snapshot files when mounting.
1657  */
1658 void
1659 ffs_snapshot_mount(mp)
1660 	struct mount *mp;
1661 {
1662 	struct ufsmount *ump = VFSTOUFS(mp);
1663 	struct vnode *devvp = ump->um_devvp;
1664 	struct fs *fs = ump->um_fs;
1665 	struct thread *td = curthread;
1666 	struct snaphead *snaphead;
1667 	struct vnode *vp;
1668 	struct inode *ip, *xp;
1669 	struct uio auio;
1670 	struct iovec aiov;
1671 	void *snapblklist;
1672 	char *reason;
1673 	daddr_t snaplistsize;
1674 	int error, snaploc, loc;
1675 
1676 	/*
1677 	 * XXX The following needs to be set before UFS_TRUNCATE or
1678 	 * VOP_READ can be called.
1679 	 */
1680 	mp->mnt_stat.f_iosize = fs->fs_bsize;
1681 	/*
1682 	 * Process each snapshot listed in the superblock.
1683 	 */
1684 	vp = NULL;
1685 	snaphead = &devvp->v_rdev->si_snapshots;
1686 	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
1687 		if (fs->fs_snapinum[snaploc] == 0)
1688 			break;
1689 		if ((error = VFS_VGET(mp, fs->fs_snapinum[snaploc],
1690 		    LK_EXCLUSIVE, &vp)) != 0){
1691 			printf("ffs_snapshot_mount: vget failed %d\n", error);
1692 			continue;
1693 		}
1694 		ip = VTOI(vp);
1695 		if ((ip->i_flags & SF_SNAPSHOT) == 0 || ip->i_size ==
1696 		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag))) {
1697 			if ((ip->i_flags & SF_SNAPSHOT) == 0) {
1698 				reason = "non-snapshot";
1699 			} else {
1700 				reason = "old format snapshot";
1701 				(void)UFS_TRUNCATE(vp, (off_t)0, 0, NOCRED, td);
1702 				(void)VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1703 			}
1704 			printf("ffs_snapshot_mount: %s inode %d\n",
1705 			    reason, fs->fs_snapinum[snaploc]);
1706 			vput(vp);
1707 			vp = NULL;
1708 			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
1709 				if (fs->fs_snapinum[loc] == 0)
1710 					break;
1711 				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
1712 			}
1713 			fs->fs_snapinum[loc - 1] = 0;
1714 			snaploc--;
1715 			continue;
1716 		}
1717 		/*
1718 		 * If there already exist snapshots on this filesystem, grab a
1719 		 * reference to their shared lock. If this is the first snapshot
1720 		 * on this filesystem, we need to allocate a lock for the
1721 		 * snapshots to share. In either case, acquire the snapshot
1722 		 * lock and give up our original private lock.
1723 		 */
1724 		VI_LOCK(devvp);
1725 		if ((xp = TAILQ_FIRST(snaphead)) != NULL) {
1726 			VI_LOCK(vp);
1727 			vp->v_vnlock = ITOV(xp)->v_vnlock;
1728 			VI_UNLOCK(devvp);
1729 		} else {
1730 			struct lock *lkp;
1731 
1732 			VI_UNLOCK(devvp);
1733 			MALLOC(lkp, struct lock *, sizeof(struct lock),
1734 			    M_UFSMNT, 0);
1735 			lockinit(lkp, PVFS, "snaplk", VLKTIMEOUT,
1736 			    LK_CANRECURSE | LK_NOPAUSE);
1737 			VI_LOCK(vp);
1738 			vp->v_vnlock = lkp;
1739 		}
1740 		vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE | LK_RETRY, td);
1741 		transferlockers(&vp->v_lock, vp->v_vnlock);
1742 		lockmgr(&vp->v_lock, LK_RELEASE, NULL, td);
1743 		/*
1744 		 * Link it onto the active snapshot list.
1745 		 */
1746 		VI_LOCK(devvp);
1747 		if (ip->i_nextsnap.tqe_prev != 0)
1748 			panic("ffs_snapshot_mount: %d already on list",
1749 			    ip->i_number);
1750 		else
1751 			TAILQ_INSERT_TAIL(snaphead, ip, i_nextsnap);
1752 		vp->v_vflag |= VV_SYSTEM;
1753 		VI_UNLOCK(devvp);
1754 		VOP_UNLOCK(vp, 0, td);
1755 	}
1756 	/*
1757 	 * No usable snapshots found.
1758 	 */
1759 	if (vp == NULL)
1760 		return;
1761 	/*
1762 	 * Allocate the space for the block hints list. We always want to
1763 	 * use the list from the newest snapshot.
1764 	 */
1765 	auio.uio_iov = &aiov;
1766 	auio.uio_iovcnt = 1;
1767 	aiov.iov_base = (void *)&snaplistsize;
1768 	aiov.iov_len = sizeof(snaplistsize);
1769 	auio.uio_resid = aiov.iov_len;
1770 	auio.uio_offset =
1771 	    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag));
1772 	auio.uio_segflg = UIO_SYSSPACE;
1773 	auio.uio_rw = UIO_READ;
1774 	auio.uio_td = td;
1775 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1776 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
1777 		printf("ffs_snapshot_mount: read_1 failed %d\n", error);
1778 		VOP_UNLOCK(vp, 0, td);
1779 		return;
1780 	}
1781 	MALLOC(snapblklist, void *, snaplistsize * sizeof(daddr_t),
1782 	    M_UFSMNT, 0);
1783 	auio.uio_iovcnt = 1;
1784 	aiov.iov_base = snapblklist;
1785 	aiov.iov_len = snaplistsize * sizeof (daddr_t);
1786 	auio.uio_resid = aiov.iov_len;
1787 	auio.uio_offset -= sizeof(snaplistsize);
1788 	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
1789 		printf("ffs_snapshot_mount: read_2 failed %d\n", error);
1790 		VOP_UNLOCK(vp, 0, td);
1791 		FREE(snapblklist, M_UFSMNT);
1792 		return;
1793 	}
1794 	VOP_UNLOCK(vp, 0, td);
1795 	VI_LOCK(devvp);
1796 	ASSERT_VOP_LOCKED(devvp, "ffs_snapshot_mount");
1797 	devvp->v_rdev->si_snaplistsize = snaplistsize;
1798 	devvp->v_rdev->si_snapblklist = (daddr_t *)snapblklist;
1799 	devvp->v_rdev->si_copyonwrite = ffs_copyonwrite;
1800 	devvp->v_vflag |= VV_COPYONWRITE;
1801 	VI_UNLOCK(devvp);
1802 }
1803 
1804 /*
1805  * Disassociate snapshot files when unmounting.
1806  */
1807 void
1808 ffs_snapshot_unmount(mp)
1809 	struct mount *mp;
1810 {
1811 	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
1812 	struct snaphead *snaphead = &devvp->v_rdev->si_snapshots;
1813 	struct lock *lkp = NULL;
1814 	struct inode *xp;
1815 	struct vnode *vp;
1816 
1817 	VI_LOCK(devvp);
1818 	while ((xp = TAILQ_FIRST(snaphead)) != 0) {
1819 		vp = ITOV(xp);
1820 		lkp = vp->v_vnlock;
1821 		vp->v_vnlock = &vp->v_lock;
1822 		TAILQ_REMOVE(snaphead, xp, i_nextsnap);
1823 		xp->i_nextsnap.tqe_prev = 0;
1824 		if (xp->i_effnlink > 0) {
1825 			VI_UNLOCK(devvp);
1826 			vrele(vp);
1827 			VI_LOCK(devvp);
1828 		}
1829 	}
1830 	if (devvp->v_rdev->si_snapblklist != NULL) {
1831 		FREE(devvp->v_rdev->si_snapblklist, M_UFSMNT);
1832 		devvp->v_rdev->si_snapblklist = NULL;
1833 		devvp->v_rdev->si_snaplistsize = 0;
1834 	}
1835 	if (lkp != NULL) {
1836 		lockdestroy(lkp);
1837 		FREE(lkp, M_UFSMNT);
1838 	}
1839 	ASSERT_VOP_LOCKED(devvp, "ffs_snapshot_unmount");
1840 	devvp->v_rdev->si_copyonwrite = 0;
1841 	devvp->v_vflag &= ~VV_COPYONWRITE;
1842 	VI_UNLOCK(devvp);
1843 }
1844 
1845 /*
1846  * Check for need to copy block that is about to be written,
1847  * copying the block if necessary.
1848  */
1849 static int
1850 ffs_copyonwrite(devvp, bp)
1851 	struct vnode *devvp;
1852 	struct buf *bp;
1853 {
1854 	struct snaphead *snaphead;
1855 	struct buf *ibp, *cbp, *savedcbp = 0;
1856 	struct thread *td = curthread;
1857 	struct fs *fs;
1858 	struct inode *ip;
1859 	struct vnode *vp = 0;
1860 	ufs2_daddr_t lbn, blkno, *snapblklist;
1861 	int lower, upper, mid, indiroff, snapshot_locked = 0, error = 0;
1862 
1863 	if (td->td_proc->p_flag & P_COWINPROGRESS)
1864 		panic("ffs_copyonwrite: recursive call");
1865 	/*
1866 	 * First check to see if it is in the preallocated list.
1867 	 * By doing this check we avoid several potential deadlocks.
1868 	 */
1869 	VI_LOCK(devvp);
1870 	snaphead = &devvp->v_rdev->si_snapshots;
1871 	ip = TAILQ_FIRST(snaphead);
1872 	fs = ip->i_fs;
1873 	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
1874 	snapblklist = devvp->v_rdev->si_snapblklist;
1875 	upper = devvp->v_rdev->si_snaplistsize - 1;
1876 	lower = 1;
1877 	while (lower <= upper) {
1878 		mid = (lower + upper) / 2;
1879 		if (snapblklist[mid] == lbn)
1880 			break;
1881 		if (snapblklist[mid] < lbn)
1882 			lower = mid + 1;
1883 		else
1884 			upper = mid - 1;
1885 	}
1886 	if (lower <= upper) {
1887 		VI_UNLOCK(devvp);
1888 		return (0);
1889 	}
1890 	/*
1891 	 * Not in the precomputed list, so check the snapshots.
1892 	 */
1893 retry:
1894 	TAILQ_FOREACH(ip, snaphead, i_nextsnap) {
1895 		vp = ITOV(ip);
1896 		/*
1897 		 * We ensure that everything of our own that needs to be
1898 		 * copied will be done at the time that ffs_snapshot is
1899 		 * called. Thus we can skip the check here which can
1900 		 * deadlock in doing the lookup in UFS_BALLOC.
1901 		 */
1902 		if (bp->b_vp == vp)
1903 			continue;
1904 		/*
1905 		 * Check to see if block needs to be copied. We do not have
1906 		 * to hold the snapshot lock while doing this lookup as it
1907 		 * will never require any additional allocations for the
1908 		 * snapshot inode.
1909 		 */
1910 		if (lbn < NDADDR) {
1911 			blkno = DIP(ip, i_db[lbn]);
1912 		} else {
1913 			if (snapshot_locked == 0 &&
1914 			    lockmgr(vp->v_vnlock,
1915 			      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1916 			      VI_MTX(devvp), td) != 0) {
1917 				VI_LOCK(devvp);
1918 				goto retry;
1919 			}
1920 			snapshot_locked = 1;
1921 			td->td_proc->p_flag |= P_COWINPROGRESS;
1922 			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1923 			   fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1924 			td->td_proc->p_flag &= ~P_COWINPROGRESS;
1925 			if (error)
1926 				break;
1927 			indiroff = (lbn - NDADDR) % NINDIR(fs);
1928 			if (ip->i_ump->um_fstype == UFS1)
1929 				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1930 			else
1931 				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1932 			bqrelse(ibp);
1933 		}
1934 #ifdef DIAGNOSTIC
1935 		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
1936 			panic("ffs_copyonwrite: bad copy block");
1937 #endif
1938 		if (blkno != 0)
1939 			continue;
1940 		/*
1941 		 * Allocate the block into which to do the copy. Since
1942 		 * multiple processes may all try to copy the same block,
1943 		 * we have to recheck our need to do a copy if we sleep
1944 		 * waiting for the lock.
1945 		 *
1946 		 * Because all snapshots on a filesystem share a single
1947 		 * lock, we ensure that we will never be in competition
1948 		 * with another process to allocate a block.
1949 		 */
1950 		if (snapshot_locked == 0 &&
1951 		    lockmgr(vp->v_vnlock,
1952 		      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1953 		      VI_MTX(devvp), td) != 0) {
1954 			VI_LOCK(devvp);
1955 			goto retry;
1956 		}
1957 		snapshot_locked = 1;
1958 		td->td_proc->p_flag |= P_COWINPROGRESS;
1959 		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1960 		    fs->fs_bsize, KERNCRED, 0, &cbp);
1961 		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1962 		if (error)
1963 			break;
1964 #ifdef DEBUG
1965 		if (snapdebug) {
1966 			printf("Copyonwrite: snapino %d lbn %jd for ",
1967 			    ip->i_number, (intmax_t)lbn);
1968 			if (bp->b_vp == devvp)
1969 				printf("fs metadata");
1970 			else
1971 				printf("inum %d", VTOI(bp->b_vp)->i_number);
1972 			printf(" lblkno %jd to blkno %jd\n",
1973 			    (intmax_t)bp->b_lblkno, (intmax_t)cbp->b_blkno);
1974 		}
1975 #endif
1976 		/*
1977 		 * If we have already read the old block contents, then
1978 		 * simply copy them to the new block. Note that we need
1979 		 * to synchronously write snapshots that have not been
1980 		 * unlinked, and hence will be visible after a crash,
1981 		 * to ensure their integrity.
1982 		 */
1983 		if (savedcbp != 0) {
1984 			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1985 			bawrite(cbp);
1986 			if (dopersistence && ip->i_effnlink > 0)
1987 				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1988 			continue;
1989 		}
1990 		/*
1991 		 * Otherwise, read the old block contents into the buffer.
1992 		 */
1993 		if ((error = readblock(cbp, lbn)) != 0) {
1994 			bzero(cbp->b_data, fs->fs_bsize);
1995 			bawrite(cbp);
1996 			if (dopersistence && ip->i_effnlink > 0)
1997 				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1998 			break;
1999 		}
2000 		savedcbp = cbp;
2001 	}
2002 	/*
2003 	 * Note that we need to synchronously write snapshots that
2004 	 * have not been unlinked, and hence will be visible after
2005 	 * a crash, to ensure their integrity.
2006 	 */
2007 	if (savedcbp) {
2008 		vp = savedcbp->b_vp;
2009 		bawrite(savedcbp);
2010 		if (dopersistence && VTOI(vp)->i_effnlink > 0)
2011 			(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
2012 	}
2013 	if (snapshot_locked)
2014 		VOP_UNLOCK(vp, 0, td);
2015 	else
2016 		VI_UNLOCK(devvp);
2017 	return (error);
2018 }
2019 
2020 /*
2021  * Read the specified block into the given buffer.
2022  * Much of this boiler-plate comes from bwrite().
2023  */
2024 static int
2025 readblock(bp, lbn)
2026 	struct buf *bp;
2027 	ufs2_daddr_t lbn;
2028 {
2029 	struct uio auio;
2030 	struct iovec aiov;
2031 	struct thread *td = curthread;
2032 	struct inode *ip = VTOI(bp->b_vp);
2033 
2034 	aiov.iov_base = bp->b_data;
2035 	aiov.iov_len = bp->b_bcount;
2036 	auio.uio_iov = &aiov;
2037 	auio.uio_iovcnt = 1;
2038 	auio.uio_offset = dbtob(fsbtodb(ip->i_fs, blkstofrags(ip->i_fs, lbn)));
2039 	auio.uio_resid = bp->b_bcount;
2040 	auio.uio_rw = UIO_READ;
2041 	auio.uio_segflg = UIO_SYSSPACE;
2042 	auio.uio_td = td;
2043 	return (physio(ip->i_devvp->v_rdev, &auio, 0));
2044 }
2045