ffs_snapshot.c revision 107915
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: head/sys/ufs/ffs/ffs_snapshot.c 107915 2002-12-15 19:25:59Z mckusick $
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
65static int cgaccount(int, struct vnode *, struct buf *, int);
66static 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);
69static 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);
73static int fullacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
74    struct fs *, ufs_lbn_t, int);
75static int snapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
76    struct fs *, ufs_lbn_t, int);
77static int mapacct_ufs1(struct vnode *, ufs1_daddr_t *, ufs1_daddr_t *,
78    struct fs *, ufs_lbn_t, int);
79static 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);
82static 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);
86static int fullacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
87    struct fs *, ufs_lbn_t, int);
88static int snapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
89    struct fs *, ufs_lbn_t, int);
90static int mapacct_ufs2(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
91    struct fs *, ufs_lbn_t, int);
92static int ffs_copyonwrite(struct vnode *, struct buf *);
93static 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 */
102int dopersistence = 0;
103
104#ifdef DEBUG
105#include <sys/sysctl.h>
106SYSCTL_INT(_debug, OID_AUTO, dopersistence, CTLFLAG_RW, &dopersistence, 0, "");
107int snapdebug = 0;
108SYSCTL_INT(_debug, OID_AUTO, snapdebug, CTLFLAG_RW, &snapdebug, 0, "");
109int collectsnapstats = 0;
110SYSCTL_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 */
117int
118ffs_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	 */
158restart:
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, M_WAITOK);
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, M_WAITOK);
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);
400loop:
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		    M_WAITOK);
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;
499out1:
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, M_WAITOK);
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);
603done:
604	free(copy_fs->fs_csp, M_UFSMNT);
605	bawrite(sbp);
606out:
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 */
633static int
634cgaccount(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 */
740static int
741expunge_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 */
832static int
833indiracct_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, M_WAITOK);
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	}
896out:
897	FREE(bap, M_DEVBUF);
898	return (error);
899}
900
901/*
902 * Do both snap accounting and map accounting.
903 */
904static int
905fullacct_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 */
922static int
923snapacct_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 */
975static int
976mapacct_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
987	/*
988	 * We only care about the leaf block numbers, not the
989	 * meta-block numbers.
990	 */
991	if (lblkno == -1)
992		return (0);
993	ip = VTOI(vp);
994	inum = ip->i_number;
995	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
996		blkno = *oldblkp;
997		if (blkno == 0 || blkno == BLK_NOCOPY)
998			continue;
999		if (expungetype == BLK_SNAP && blkno != BLK_SNAP)
1000			*ip->i_snapblklist++ = lblkno;
1001		if (blkno == BLK_SNAP)
1002			blkno = blkstofrags(fs, lblkno);
1003		ffs_blkfree(fs, vp, blkno, fs->fs_bsize, inum);
1004	}
1005	return (0);
1006}
1007
1008/*
1009 * Before expunging a snapshot inode, note all the
1010 * blocks that it claims with BLK_SNAP so that fsck will
1011 * be able to account for those blocks properly and so
1012 * that this snapshot knows that it need not copy them
1013 * if the other snapshot holding them is freed. This code
1014 * is reproduced once each for UFS1 and UFS2.
1015 */
1016static int
1017expunge_ufs2(snapvp, cancelip, fs, acctfunc, expungetype)
1018	struct vnode *snapvp;
1019	struct inode *cancelip;
1020	struct fs *fs;
1021	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1022	    struct fs *, ufs_lbn_t, int);
1023	int expungetype;
1024{
1025	int i, error, indiroff;
1026	ufs_lbn_t lbn, rlbn;
1027	ufs2_daddr_t len, blkno, numblks, blksperindir;
1028	struct ufs2_dinode *dip;
1029	struct thread *td = curthread;
1030	struct buf *bp;
1031
1032	/*
1033	 * Prepare to expunge the inode. If its inode block has not
1034	 * yet been copied, then allocate and fill the copy.
1035	 */
1036	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1037	blkno = 0;
1038	if (lbn < NDADDR) {
1039		blkno = VTOI(snapvp)->i_din2->di_db[lbn];
1040	} else {
1041		td->td_proc->p_flag |= P_COWINPROGRESS;
1042		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
1043		   fs->fs_bsize, KERNCRED, BA_METAONLY, &bp);
1044		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1045		if (error)
1046			return (error);
1047		indiroff = (lbn - NDADDR) % NINDIR(fs);
1048		blkno = ((ufs2_daddr_t *)(bp->b_data))[indiroff];
1049		bqrelse(bp);
1050	}
1051	if (blkno != 0) {
1052		if ((error = bread(snapvp, lbn, fs->fs_bsize, KERNCRED, &bp)))
1053			return (error);
1054	} else {
1055		error = UFS_BALLOC(snapvp, lblktosize(fs, (off_t)lbn),
1056		    fs->fs_bsize, KERNCRED, 0, &bp);
1057		if (error)
1058			return (error);
1059		if ((error = readblock(bp, lbn)) != 0)
1060			return (error);
1061	}
1062	/*
1063	 * Set a snapshot inode to be a zero length file, regular files
1064	 * to be completely unallocated.
1065	 */
1066	dip = (struct ufs2_dinode *)bp->b_data +
1067	    ino_to_fsbo(fs, cancelip->i_number);
1068	if (expungetype == BLK_NOCOPY)
1069		dip->di_mode = 0;
1070	dip->di_size = 0;
1071	dip->di_blocks = 0;
1072	dip->di_flags &= ~SF_SNAPSHOT;
1073	bzero(&dip->di_db[0], (NDADDR + NIADDR) * sizeof(ufs2_daddr_t));
1074	bdwrite(bp);
1075	/*
1076	 * Now go through and expunge all the blocks in the file
1077	 * using the function requested.
1078	 */
1079	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1080	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_db[0],
1081	    &cancelip->i_din2->di_db[NDADDR], fs, 0, expungetype)))
1082		return (error);
1083	if ((error = (*acctfunc)(snapvp, &cancelip->i_din2->di_ib[0],
1084	    &cancelip->i_din2->di_ib[NIADDR], fs, -1, expungetype)))
1085		return (error);
1086	blksperindir = 1;
1087	lbn = -NDADDR;
1088	len = numblks - NDADDR;
1089	rlbn = NDADDR;
1090	for (i = 0; len > 0 && i < NIADDR; i++) {
1091		error = indiracct_ufs2(snapvp, ITOV(cancelip), i,
1092		    cancelip->i_din2->di_ib[i], lbn, rlbn, len,
1093		    blksperindir, fs, acctfunc, expungetype);
1094		if (error)
1095			return (error);
1096		blksperindir *= NINDIR(fs);
1097		lbn -= blksperindir + 1;
1098		len -= blksperindir;
1099		rlbn += blksperindir;
1100	}
1101	return (0);
1102}
1103
1104/*
1105 * Descend an indirect block chain for vnode cancelvp accounting for all
1106 * its indirect blocks in snapvp.
1107 */
1108static int
1109indiracct_ufs2(snapvp, cancelvp, level, blkno, lbn, rlbn, remblks,
1110	    blksperindir, fs, acctfunc, expungetype)
1111	struct vnode *snapvp;
1112	struct vnode *cancelvp;
1113	int level;
1114	ufs2_daddr_t blkno;
1115	ufs_lbn_t lbn;
1116	ufs_lbn_t rlbn;
1117	ufs_lbn_t remblks;
1118	ufs_lbn_t blksperindir;
1119	struct fs *fs;
1120	int (*acctfunc)(struct vnode *, ufs2_daddr_t *, ufs2_daddr_t *,
1121	    struct fs *, ufs_lbn_t, int);
1122	int expungetype;
1123{
1124	int error, num, i;
1125	ufs_lbn_t subblksperindir;
1126	struct indir indirs[NIADDR + 2];
1127	ufs2_daddr_t last, *bap;
1128	struct buf *bp;
1129
1130	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1131		return (error);
1132	if (lbn != indirs[num - 1 - level].in_lbn || blkno == 0 || num < 2)
1133		panic("indiracct: botched params");
1134	/*
1135	 * We have to expand bread here since it will deadlock looking
1136	 * up the block number for any blocks that are not in the cache.
1137	 */
1138	bp = getblk(cancelvp, lbn, fs->fs_bsize, 0, 0);
1139	bp->b_blkno = fsbtodb(fs, blkno);
1140	if ((bp->b_flags & (B_DONE | B_DELWRI)) == 0 &&
1141	    (error = readblock(bp, fragstoblks(fs, blkno)))) {
1142		brelse(bp);
1143		return (error);
1144	}
1145	/*
1146	 * Account for the block pointers in this indirect block.
1147	 */
1148	last = howmany(remblks, blksperindir);
1149	if (last > NINDIR(fs))
1150		last = NINDIR(fs);
1151	MALLOC(bap, ufs2_daddr_t *, fs->fs_bsize, M_DEVBUF, M_WAITOK);
1152	bcopy(bp->b_data, (caddr_t)bap, fs->fs_bsize);
1153	bqrelse(bp);
1154	error = (*acctfunc)(snapvp, &bap[0], &bap[last], fs,
1155	    level == 0 ? rlbn : -1, expungetype);
1156	if (error || level == 0)
1157		goto out;
1158	/*
1159	 * Account for the block pointers in each of the indirect blocks
1160	 * in the levels below us.
1161	 */
1162	subblksperindir = blksperindir / NINDIR(fs);
1163	for (lbn++, level--, i = 0; i < last; i++) {
1164		error = indiracct_ufs2(snapvp, cancelvp, level, bap[i], lbn,
1165		    rlbn, remblks, subblksperindir, fs, acctfunc, expungetype);
1166		if (error)
1167			goto out;
1168		rlbn += blksperindir;
1169		lbn -= blksperindir;
1170		remblks -= blksperindir;
1171	}
1172out:
1173	FREE(bap, M_DEVBUF);
1174	return (error);
1175}
1176
1177/*
1178 * Do both snap accounting and map accounting.
1179 */
1180static int
1181fullacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)
1182	struct vnode *vp;
1183	ufs2_daddr_t *oldblkp, *lastblkp;
1184	struct fs *fs;
1185	ufs_lbn_t lblkno;
1186	int exptype;	/* BLK_SNAP or BLK_NOCOPY */
1187{
1188	int error;
1189
1190	if ((error = snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype)))
1191		return (error);
1192	return (mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, exptype));
1193}
1194
1195/*
1196 * Identify a set of blocks allocated in a snapshot inode.
1197 */
1198static int
1199snapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
1200	struct vnode *vp;
1201	ufs2_daddr_t *oldblkp, *lastblkp;
1202	struct fs *fs;
1203	ufs_lbn_t lblkno;
1204	int expungetype;	/* BLK_SNAP or BLK_NOCOPY */
1205{
1206	struct inode *ip = VTOI(vp);
1207	ufs2_daddr_t blkno, *blkp;
1208	ufs_lbn_t lbn;
1209	struct buf *ibp;
1210	int error;
1211
1212	for ( ; oldblkp < lastblkp; oldblkp++) {
1213		blkno = *oldblkp;
1214		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1215			continue;
1216		lbn = fragstoblks(fs, blkno);
1217		if (lbn < NDADDR) {
1218			blkp = &ip->i_din2->di_db[lbn];
1219			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1220		} else {
1221			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1222			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1223			if (error)
1224				return (error);
1225			blkp = &((ufs2_daddr_t *)(ibp->b_data))
1226			    [(lbn - NDADDR) % NINDIR(fs)];
1227		}
1228		/*
1229		 * If we are expunging a snapshot vnode and we
1230		 * find a block marked BLK_NOCOPY, then it is
1231		 * one that has been allocated to this snapshot after
1232		 * we took our current snapshot and can be ignored.
1233		 */
1234		if (expungetype == BLK_SNAP && *blkp == BLK_NOCOPY) {
1235			if (lbn >= NDADDR)
1236				brelse(ibp);
1237		} else {
1238			if (*blkp != 0)
1239				panic("snapacct: bad block");
1240			*blkp = expungetype;
1241			if (lbn >= NDADDR)
1242				bdwrite(ibp);
1243		}
1244	}
1245	return (0);
1246}
1247
1248/*
1249 * Account for a set of blocks allocated in a snapshot inode.
1250 */
1251static int
1252mapacct_ufs2(vp, oldblkp, lastblkp, fs, lblkno, expungetype)
1253	struct vnode *vp;
1254	ufs2_daddr_t *oldblkp, *lastblkp;
1255	struct fs *fs;
1256	ufs_lbn_t lblkno;
1257	int expungetype;
1258{
1259	ufs2_daddr_t blkno;
1260	struct inode *ip;
1261	ino_t inum;
1262
1263	/*
1264	 * We only care about the leaf block numbers, not the
1265	 * meta-block numbers.
1266	 */
1267	if (lblkno == -1)
1268		return (0);
1269	ip = VTOI(vp);
1270	inum = ip->i_number;
1271	for ( ; oldblkp < lastblkp; oldblkp++, lblkno++) {
1272		blkno = *oldblkp;
1273		if (blkno == 0 || blkno == BLK_NOCOPY)
1274			continue;
1275		if (expungetype == BLK_SNAP && blkno != BLK_SNAP)
1276			*ip->i_snapblklist++ = lblkno;
1277		if (blkno == BLK_SNAP)
1278			blkno = blkstofrags(fs, lblkno);
1279		ffs_blkfree(fs, vp, blkno, fs->fs_bsize, inum);
1280	}
1281	return (0);
1282}
1283
1284/*
1285 * Decrement extra reference on snapshot when last name is removed.
1286 * It will not be freed until the last open reference goes away.
1287 */
1288void
1289ffs_snapgone(ip)
1290	struct inode *ip;
1291{
1292	struct inode *xp;
1293	struct fs *fs;
1294	int snaploc;
1295
1296	/*
1297	 * Find snapshot in incore list.
1298	 */
1299	TAILQ_FOREACH(xp, &ip->i_devvp->v_rdev->si_snapshots, i_nextsnap)
1300		if (xp == ip)
1301			break;
1302	if (xp != NULL)
1303		vrele(ITOV(ip));
1304	else if (snapdebug)
1305		printf("ffs_snapgone: lost snapshot vnode %d\n",
1306		    ip->i_number);
1307	/*
1308	 * Delete snapshot inode from superblock. Keep list dense.
1309	 */
1310	fs = ip->i_fs;
1311	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
1312		if (fs->fs_snapinum[snaploc] == ip->i_number)
1313			break;
1314	if (snaploc < FSMAXSNAP) {
1315		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
1316			if (fs->fs_snapinum[snaploc] == 0)
1317				break;
1318			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
1319		}
1320		fs->fs_snapinum[snaploc - 1] = 0;
1321	}
1322}
1323
1324/*
1325 * Prepare a snapshot file for being removed.
1326 */
1327void
1328ffs_snapremove(vp)
1329	struct vnode *vp;
1330{
1331	struct inode *ip;
1332	struct vnode *devvp;
1333	struct lock *lkp;
1334	struct buf *ibp;
1335	struct fs *fs;
1336	struct thread *td = curthread;
1337	ufs2_daddr_t numblks, blkno, dblk, *snapblklist;
1338	int error, loc, last;
1339
1340	ip = VTOI(vp);
1341	fs = ip->i_fs;
1342	devvp = ip->i_devvp;
1343	/*
1344	 * If active, delete from incore list (this snapshot may
1345	 * already have been in the process of being deleted, so
1346	 * would not have been active).
1347	 *
1348	 * Clear copy-on-write flag if last snapshot.
1349	 */
1350	if (ip->i_nextsnap.tqe_prev != 0) {
1351		VI_LOCK(devvp);
1352		lockmgr(&vp->v_lock, LK_INTERLOCK | LK_EXCLUSIVE,
1353		    VI_MTX(devvp), td);
1354		VI_LOCK(devvp);
1355		TAILQ_REMOVE(&devvp->v_rdev->si_snapshots, ip, i_nextsnap);
1356		ip->i_nextsnap.tqe_prev = 0;
1357		lkp = vp->v_vnlock;
1358		vp->v_vnlock = &vp->v_lock;
1359		lockmgr(lkp, LK_RELEASE, NULL, td);
1360		if (TAILQ_FIRST(&devvp->v_rdev->si_snapshots) != 0) {
1361			VI_UNLOCK(devvp);
1362		} else {
1363			snapblklist = devvp->v_rdev->si_snapblklist;
1364			devvp->v_rdev->si_snapblklist = 0;
1365			devvp->v_rdev->si_snaplistsize = 0;
1366			devvp->v_rdev->si_copyonwrite = 0;
1367			devvp->v_vflag &= ~VV_COPYONWRITE;
1368			lockmgr(lkp, LK_DRAIN|LK_INTERLOCK, VI_MTX(devvp), td);
1369			lockmgr(lkp, LK_RELEASE, NULL, td);
1370			lockdestroy(lkp);
1371			FREE(lkp, M_UFSMNT);
1372			FREE(snapblklist, M_UFSMNT);
1373		}
1374	}
1375	/*
1376	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
1377	 * snapshots that want them (see ffs_snapblkfree below).
1378	 */
1379	for (blkno = 1; blkno < NDADDR; blkno++) {
1380		dblk = DIP(ip, i_db[blkno]);
1381		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1382			DIP(ip, i_db[blkno]) = 0;
1383		else if ((dblk == blkstofrags(fs, blkno) &&
1384		     ffs_snapblkfree(fs, ip->i_devvp, dblk, fs->fs_bsize,
1385		     ip->i_number))) {
1386			DIP(ip, i_blocks) -= btodb(fs->fs_bsize);
1387			DIP(ip, i_db[blkno]) = 0;
1388		}
1389	}
1390	numblks = howmany(ip->i_size, fs->fs_bsize);
1391	for (blkno = NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
1392		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)blkno),
1393		    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1394		if (error)
1395			continue;
1396		if (fs->fs_size - blkno > NINDIR(fs))
1397			last = NINDIR(fs);
1398		else
1399			last = fs->fs_size - blkno;
1400		for (loc = 0; loc < last; loc++) {
1401			if (ip->i_ump->um_fstype == UFS1) {
1402				dblk = ((ufs1_daddr_t *)(ibp->b_data))[loc];
1403				if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1404					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1405				else if ((dblk == blkstofrags(fs, blkno) &&
1406				     ffs_snapblkfree(fs, ip->i_devvp, dblk,
1407				     fs->fs_bsize, ip->i_number))) {
1408					ip->i_din1->di_blocks -=
1409					    btodb(fs->fs_bsize);
1410					((ufs1_daddr_t *)(ibp->b_data))[loc]= 0;
1411				}
1412				continue;
1413			}
1414			dblk = ((ufs2_daddr_t *)(ibp->b_data))[loc];
1415			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1416				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1417			else if ((dblk == blkstofrags(fs, blkno) &&
1418			     ffs_snapblkfree(fs, ip->i_devvp, dblk,
1419			     fs->fs_bsize, ip->i_number))) {
1420				ip->i_din2->di_blocks -= btodb(fs->fs_bsize);
1421				((ufs2_daddr_t *)(ibp->b_data))[loc] = 0;
1422			}
1423		}
1424		bawrite(ibp);
1425	}
1426	/*
1427	 * Clear snapshot flag and drop reference.
1428	 */
1429	ip->i_flags &= ~SF_SNAPSHOT;
1430	DIP(ip, i_flags) = ip->i_flags;
1431	ip->i_flag |= IN_CHANGE | IN_UPDATE;
1432}
1433
1434/*
1435 * Notification that a block is being freed. Return zero if the free
1436 * should be allowed to proceed. Return non-zero if the snapshot file
1437 * wants to claim the block. The block will be claimed if it is an
1438 * uncopied part of one of the snapshots. It will be freed if it is
1439 * either a BLK_NOCOPY or has already been copied in all of the snapshots.
1440 * If a fragment is being freed, then all snapshots that care about
1441 * it must make a copy since a snapshot file can only claim full sized
1442 * blocks. Note that if more than one snapshot file maps the block,
1443 * we can pick one at random to claim it. Since none of the snapshots
1444 * can change, we are assurred that they will all see the same unmodified
1445 * image. When deleting a snapshot file (see ffs_snapremove above), we
1446 * must push any of these claimed blocks to one of the other snapshots
1447 * that maps it. These claimed blocks are easily identified as they will
1448 * have a block number equal to their logical block number within the
1449 * snapshot. A copied block can never have this property because they
1450 * must always have been allocated from a BLK_NOCOPY location.
1451 */
1452int
1453ffs_snapblkfree(fs, devvp, bno, size, inum)
1454	struct fs *fs;
1455	struct vnode *devvp;
1456	ufs2_daddr_t bno;
1457	long size;
1458	ino_t inum;
1459{
1460	struct buf *ibp, *cbp, *savedcbp = 0;
1461	struct thread *td = curthread;
1462	struct inode *ip;
1463	struct vnode *vp = NULL;
1464	ufs_lbn_t lbn;
1465	ufs2_daddr_t blkno;
1466	int indiroff = 0, snapshot_locked = 0, error = 0, claimedblk = 0;
1467	struct snaphead *snaphead;
1468
1469	lbn = fragstoblks(fs, bno);
1470retry:
1471	VI_LOCK(devvp);
1472	snaphead = &devvp->v_rdev->si_snapshots;
1473	TAILQ_FOREACH(ip, snaphead, i_nextsnap) {
1474		vp = ITOV(ip);
1475		/*
1476		 * Lookup block being written.
1477		 */
1478		if (lbn < NDADDR) {
1479			blkno = DIP(ip, i_db[lbn]);
1480		} else {
1481			if (snapshot_locked == 0 &&
1482			    lockmgr(vp->v_vnlock,
1483			      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1484			      VI_MTX(devvp), td) != 0)
1485				goto retry;
1486			snapshot_locked = 1;
1487			td->td_proc->p_flag |= P_COWINPROGRESS;
1488			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1489			    fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1490			td->td_proc->p_flag &= ~P_COWINPROGRESS;
1491			if (error)
1492				break;
1493			indiroff = (lbn - NDADDR) % NINDIR(fs);
1494			if (ip->i_ump->um_fstype == UFS1)
1495				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1496			else
1497				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1498		}
1499		/*
1500		 * Check to see if block needs to be copied.
1501		 */
1502		if (blkno == 0) {
1503			/*
1504			 * A block that we map is being freed. If it has not
1505			 * been claimed yet, we will claim or copy it (below).
1506			 */
1507			claimedblk = 1;
1508		} else if (blkno == BLK_SNAP) {
1509			/*
1510			 * No previous snapshot claimed the block,
1511			 * so it will be freed and become a BLK_NOCOPY
1512			 * (don't care) for us.
1513			 */
1514			if (claimedblk)
1515				panic("snapblkfree: inconsistent block type");
1516			if (snapshot_locked == 0 &&
1517			    lockmgr(vp->v_vnlock,
1518			      LK_INTERLOCK | LK_EXCLUSIVE | LK_NOWAIT,
1519			      VI_MTX(devvp), td) != 0) {
1520				if (lbn >= NDADDR)
1521					bqrelse(ibp);
1522				vn_lock(vp, LK_EXCLUSIVE | LK_SLEEPFAIL, td);
1523				goto retry;
1524			}
1525			snapshot_locked = 1;
1526			if (lbn < NDADDR) {
1527				DIP(ip, i_db[lbn]) = BLK_NOCOPY;
1528				ip->i_flag |= IN_CHANGE | IN_UPDATE;
1529			} else if (ip->i_ump->um_fstype == UFS1) {
1530				((ufs1_daddr_t *)(ibp->b_data))[indiroff] =
1531				    BLK_NOCOPY;
1532				bdwrite(ibp);
1533			} else {
1534				((ufs2_daddr_t *)(ibp->b_data))[indiroff] =
1535				    BLK_NOCOPY;
1536				bdwrite(ibp);
1537			}
1538			continue;
1539		} else /* BLK_NOCOPY or default */ {
1540			/*
1541			 * If the snapshot has already copied the block
1542			 * (default), or does not care about the block,
1543			 * it is not needed.
1544			 */
1545			if (lbn >= NDADDR)
1546				bqrelse(ibp);
1547			continue;
1548		}
1549		/*
1550		 * If this is a full size block, we will just grab it
1551		 * and assign it to the snapshot inode. Otherwise we
1552		 * will proceed to copy it. See explanation for this
1553		 * routine as to why only a single snapshot needs to
1554		 * claim this block.
1555		 */
1556		if (snapshot_locked == 0 &&
1557		    lockmgr(vp->v_vnlock,
1558		      LK_INTERLOCK | LK_EXCLUSIVE | LK_NOWAIT,
1559		      VI_MTX(devvp), td) != 0) {
1560			if (lbn >= NDADDR)
1561				bqrelse(ibp);
1562			vn_lock(vp, LK_EXCLUSIVE | LK_SLEEPFAIL, td);
1563			goto retry;
1564		}
1565		snapshot_locked = 1;
1566		if (size == fs->fs_bsize) {
1567#ifdef DEBUG
1568			if (snapdebug)
1569				printf("%s %d lbn %jd from inum %d\n",
1570				    "Grabonremove: snapino", ip->i_number,
1571				    (intmax_t)lbn, inum);
1572#endif
1573			if (lbn < NDADDR) {
1574				DIP(ip, i_db[lbn]) = bno;
1575			} else if (ip->i_ump->um_fstype == UFS1) {
1576				((ufs1_daddr_t *)(ibp->b_data))[indiroff] = bno;
1577				bdwrite(ibp);
1578			} else {
1579				((ufs2_daddr_t *)(ibp->b_data))[indiroff] = bno;
1580				bdwrite(ibp);
1581			}
1582			DIP(ip, i_blocks) += btodb(size);
1583			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1584			VOP_UNLOCK(vp, 0, td);
1585			return (1);
1586		}
1587		if (lbn >= NDADDR)
1588			bqrelse(ibp);
1589		/*
1590		 * Allocate the block into which to do the copy. Note that this
1591		 * allocation will never require any additional allocations for
1592		 * the snapshot inode.
1593		 */
1594		td->td_proc->p_flag |= P_COWINPROGRESS;
1595		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1596		    fs->fs_bsize, KERNCRED, 0, &cbp);
1597		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1598		if (error)
1599			break;
1600#ifdef DEBUG
1601		if (snapdebug)
1602			printf("%s%d lbn %jd %s %d size %ld to blkno %jd\n",
1603			    "Copyonremove: snapino ", ip->i_number,
1604			    (intmax_t)lbn, "for inum", inum, size,
1605			    (intmax_t)cbp->b_blkno);
1606#endif
1607		/*
1608		 * If we have already read the old block contents, then
1609		 * simply copy them to the new block. Note that we need
1610		 * to synchronously write snapshots that have not been
1611		 * unlinked, and hence will be visible after a crash,
1612		 * to ensure their integrity.
1613		 */
1614		if (savedcbp != 0) {
1615			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1616			bawrite(cbp);
1617			if (dopersistence && ip->i_effnlink > 0)
1618				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1619			continue;
1620		}
1621		/*
1622		 * Otherwise, read the old block contents into the buffer.
1623		 */
1624		if ((error = readblock(cbp, lbn)) != 0) {
1625			bzero(cbp->b_data, fs->fs_bsize);
1626			bawrite(cbp);
1627			if (dopersistence && ip->i_effnlink > 0)
1628				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1629			break;
1630		}
1631		savedcbp = cbp;
1632	}
1633	/*
1634	 * Note that we need to synchronously write snapshots that
1635	 * have not been unlinked, and hence will be visible after
1636	 * a crash, to ensure their integrity.
1637	 */
1638	if (savedcbp) {
1639		vp = savedcbp->b_vp;
1640		bawrite(savedcbp);
1641		if (dopersistence && VTOI(vp)->i_effnlink > 0)
1642			(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1643	}
1644	/*
1645	 * If we have been unable to allocate a block in which to do
1646	 * the copy, then return non-zero so that the fragment will
1647	 * not be freed. Although space will be lost, the snapshot
1648	 * will stay consistent.
1649	 */
1650	if (snapshot_locked)
1651		VOP_UNLOCK(vp, 0, td);
1652	else
1653		VI_UNLOCK(devvp);
1654	return (error);
1655}
1656
1657/*
1658 * Associate snapshot files when mounting.
1659 */
1660void
1661ffs_snapshot_mount(mp)
1662	struct mount *mp;
1663{
1664	struct ufsmount *ump = VFSTOUFS(mp);
1665	struct vnode *devvp = ump->um_devvp;
1666	struct fs *fs = ump->um_fs;
1667	struct thread *td = curthread;
1668	struct snaphead *snaphead;
1669	struct vnode *vp;
1670	struct inode *ip, *xp;
1671	struct uio auio;
1672	struct iovec aiov;
1673	void *snapblklist;
1674	char *reason;
1675	daddr_t snaplistsize;
1676	int error, snaploc, loc;
1677
1678	/*
1679	 * XXX The following needs to be set before UFS_TRUNCATE or
1680	 * VOP_READ can be called.
1681	 */
1682	mp->mnt_stat.f_iosize = fs->fs_bsize;
1683	/*
1684	 * Process each snapshot listed in the superblock.
1685	 */
1686	vp = NULL;
1687	snaphead = &devvp->v_rdev->si_snapshots;
1688	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
1689		if (fs->fs_snapinum[snaploc] == 0)
1690			break;
1691		if ((error = VFS_VGET(mp, fs->fs_snapinum[snaploc],
1692		    LK_EXCLUSIVE, &vp)) != 0){
1693			printf("ffs_snapshot_mount: vget failed %d\n", error);
1694			continue;
1695		}
1696		ip = VTOI(vp);
1697		if ((ip->i_flags & SF_SNAPSHOT) == 0 || ip->i_size ==
1698		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag))) {
1699			if ((ip->i_flags & SF_SNAPSHOT) == 0) {
1700				reason = "non-snapshot";
1701			} else {
1702				reason = "old format snapshot";
1703				(void)UFS_TRUNCATE(vp, (off_t)0, 0, NOCRED, td);
1704				(void)VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1705			}
1706			printf("ffs_snapshot_mount: %s inode %d\n",
1707			    reason, fs->fs_snapinum[snaploc]);
1708			vput(vp);
1709			vp = NULL;
1710			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
1711				if (fs->fs_snapinum[loc] == 0)
1712					break;
1713				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
1714			}
1715			fs->fs_snapinum[loc - 1] = 0;
1716			snaploc--;
1717			continue;
1718		}
1719		/*
1720		 * If there already exist snapshots on this filesystem, grab a
1721		 * reference to their shared lock. If this is the first snapshot
1722		 * on this filesystem, we need to allocate a lock for the
1723		 * snapshots to share. In either case, acquire the snapshot
1724		 * lock and give up our original private lock.
1725		 */
1726		VI_LOCK(devvp);
1727		if ((xp = TAILQ_FIRST(snaphead)) != NULL) {
1728			VI_LOCK(vp);
1729			vp->v_vnlock = ITOV(xp)->v_vnlock;
1730			VI_UNLOCK(devvp);
1731		} else {
1732			struct lock *lkp;
1733
1734			VI_UNLOCK(devvp);
1735			MALLOC(lkp, struct lock *, sizeof(struct lock),
1736			    M_UFSMNT, M_WAITOK);
1737			lockinit(lkp, PVFS, "snaplk", VLKTIMEOUT,
1738			    LK_CANRECURSE | LK_NOPAUSE);
1739			VI_LOCK(vp);
1740			vp->v_vnlock = lkp;
1741		}
1742		vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE | LK_RETRY, td);
1743		transferlockers(&vp->v_lock, vp->v_vnlock);
1744		lockmgr(&vp->v_lock, LK_RELEASE, NULL, td);
1745		/*
1746		 * Link it onto the active snapshot list.
1747		 */
1748		VI_LOCK(devvp);
1749		if (ip->i_nextsnap.tqe_prev != 0)
1750			panic("ffs_snapshot_mount: %d already on list",
1751			    ip->i_number);
1752		else
1753			TAILQ_INSERT_TAIL(snaphead, ip, i_nextsnap);
1754		vp->v_vflag |= VV_SYSTEM;
1755		VI_UNLOCK(devvp);
1756		VOP_UNLOCK(vp, 0, td);
1757	}
1758	/*
1759	 * No usable snapshots found.
1760	 */
1761	if (vp == NULL)
1762		return;
1763	/*
1764	 * Allocate the space for the block hints list. We always want to
1765	 * use the list from the newest snapshot.
1766	 */
1767	auio.uio_iov = &aiov;
1768	auio.uio_iovcnt = 1;
1769	aiov.iov_base = (void *)&snaplistsize;
1770	aiov.iov_len = sizeof(snaplistsize);
1771	auio.uio_resid = aiov.iov_len;
1772	auio.uio_offset =
1773	    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag));
1774	auio.uio_segflg = UIO_SYSSPACE;
1775	auio.uio_rw = UIO_READ;
1776	auio.uio_td = td;
1777	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1778	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
1779		printf("ffs_snapshot_mount: read_1 failed %d\n", error);
1780		VOP_UNLOCK(vp, 0, td);
1781		return;
1782	}
1783	MALLOC(snapblklist, void *, snaplistsize * sizeof(daddr_t),
1784	    M_UFSMNT, M_WAITOK);
1785	auio.uio_iovcnt = 1;
1786	aiov.iov_base = snapblklist;
1787	aiov.iov_len = snaplistsize * sizeof (daddr_t);
1788	auio.uio_resid = aiov.iov_len;
1789	auio.uio_offset -= sizeof(snaplistsize);
1790	if ((error = VOP_READ(vp, &auio, IO_UNIT, td->td_ucred)) != 0) {
1791		printf("ffs_snapshot_mount: read_2 failed %d\n", error);
1792		VOP_UNLOCK(vp, 0, td);
1793		FREE(snapblklist, M_UFSMNT);
1794		return;
1795	}
1796	VOP_UNLOCK(vp, 0, td);
1797	VI_LOCK(devvp);
1798	ASSERT_VOP_LOCKED(devvp, "ffs_snapshot_mount");
1799	devvp->v_rdev->si_snaplistsize = snaplistsize;
1800	devvp->v_rdev->si_snapblklist = (daddr_t *)snapblklist;
1801	devvp->v_rdev->si_copyonwrite = ffs_copyonwrite;
1802	devvp->v_vflag |= VV_COPYONWRITE;
1803	VI_UNLOCK(devvp);
1804}
1805
1806/*
1807 * Disassociate snapshot files when unmounting.
1808 */
1809void
1810ffs_snapshot_unmount(mp)
1811	struct mount *mp;
1812{
1813	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
1814	struct snaphead *snaphead = &devvp->v_rdev->si_snapshots;
1815	struct lock *lkp = NULL;
1816	struct inode *xp;
1817	struct vnode *vp;
1818
1819	VI_LOCK(devvp);
1820	while ((xp = TAILQ_FIRST(snaphead)) != 0) {
1821		vp = ITOV(xp);
1822		lkp = vp->v_vnlock;
1823		vp->v_vnlock = &vp->v_lock;
1824		TAILQ_REMOVE(snaphead, xp, i_nextsnap);
1825		xp->i_nextsnap.tqe_prev = 0;
1826		if (xp->i_effnlink > 0) {
1827			VI_UNLOCK(devvp);
1828			vrele(vp);
1829			VI_LOCK(devvp);
1830		}
1831	}
1832	if (devvp->v_rdev->si_snapblklist != NULL) {
1833		FREE(devvp->v_rdev->si_snapblklist, M_UFSMNT);
1834		devvp->v_rdev->si_snapblklist = NULL;
1835		devvp->v_rdev->si_snaplistsize = 0;
1836	}
1837	if (lkp != NULL) {
1838		lockdestroy(lkp);
1839		FREE(lkp, M_UFSMNT);
1840	}
1841	ASSERT_VOP_LOCKED(devvp, "ffs_snapshot_unmount");
1842	devvp->v_rdev->si_copyonwrite = 0;
1843	devvp->v_vflag &= ~VV_COPYONWRITE;
1844	VI_UNLOCK(devvp);
1845}
1846
1847/*
1848 * Check for need to copy block that is about to be written,
1849 * copying the block if necessary.
1850 */
1851static int
1852ffs_copyonwrite(devvp, bp)
1853	struct vnode *devvp;
1854	struct buf *bp;
1855{
1856	struct snaphead *snaphead;
1857	struct buf *ibp, *cbp, *savedcbp = 0;
1858	struct thread *td = curthread;
1859	struct fs *fs;
1860	struct inode *ip;
1861	struct vnode *vp = 0;
1862	ufs2_daddr_t lbn, blkno, *snapblklist;
1863	int lower, upper, mid, indiroff, snapshot_locked = 0, error = 0;
1864
1865	if (td->td_proc->p_flag & P_COWINPROGRESS)
1866		panic("ffs_copyonwrite: recursive call");
1867	/*
1868	 * First check to see if it is in the preallocated list.
1869	 * By doing this check we avoid several potential deadlocks.
1870	 */
1871	VI_LOCK(devvp);
1872	snaphead = &devvp->v_rdev->si_snapshots;
1873	ip = TAILQ_FIRST(snaphead);
1874	fs = ip->i_fs;
1875	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
1876	snapblklist = devvp->v_rdev->si_snapblklist;
1877	upper = devvp->v_rdev->si_snaplistsize - 1;
1878	lower = 1;
1879	while (lower <= upper) {
1880		mid = (lower + upper) / 2;
1881		if (snapblklist[mid] == lbn)
1882			break;
1883		if (snapblklist[mid] < lbn)
1884			lower = mid + 1;
1885		else
1886			upper = mid - 1;
1887	}
1888	if (lower <= upper) {
1889		VI_UNLOCK(devvp);
1890		return (0);
1891	}
1892	/*
1893	 * Not in the precomputed list, so check the snapshots.
1894	 */
1895retry:
1896	TAILQ_FOREACH(ip, snaphead, i_nextsnap) {
1897		vp = ITOV(ip);
1898		/*
1899		 * We ensure that everything of our own that needs to be
1900		 * copied will be done at the time that ffs_snapshot is
1901		 * called. Thus we can skip the check here which can
1902		 * deadlock in doing the lookup in UFS_BALLOC.
1903		 */
1904		if (bp->b_vp == vp)
1905			continue;
1906		/*
1907		 * Check to see if block needs to be copied. We do not have
1908		 * to hold the snapshot lock while doing this lookup as it
1909		 * will never require any additional allocations for the
1910		 * snapshot inode.
1911		 */
1912		if (lbn < NDADDR) {
1913			blkno = DIP(ip, i_db[lbn]);
1914		} else {
1915			if (snapshot_locked == 0 &&
1916			    lockmgr(vp->v_vnlock,
1917			      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1918			      VI_MTX(devvp), td) != 0) {
1919				VI_LOCK(devvp);
1920				goto retry;
1921			}
1922			snapshot_locked = 1;
1923			td->td_proc->p_flag |= P_COWINPROGRESS;
1924			error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1925			   fs->fs_bsize, KERNCRED, BA_METAONLY, &ibp);
1926			td->td_proc->p_flag &= ~P_COWINPROGRESS;
1927			if (error)
1928				break;
1929			indiroff = (lbn - NDADDR) % NINDIR(fs);
1930			if (ip->i_ump->um_fstype == UFS1)
1931				blkno=((ufs1_daddr_t *)(ibp->b_data))[indiroff];
1932			else
1933				blkno=((ufs2_daddr_t *)(ibp->b_data))[indiroff];
1934			bqrelse(ibp);
1935		}
1936#ifdef DIAGNOSTIC
1937		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
1938			panic("ffs_copyonwrite: bad copy block");
1939#endif
1940		if (blkno != 0)
1941			continue;
1942		/*
1943		 * Allocate the block into which to do the copy. Since
1944		 * multiple processes may all try to copy the same block,
1945		 * we have to recheck our need to do a copy if we sleep
1946		 * waiting for the lock.
1947		 *
1948		 * Because all snapshots on a filesystem share a single
1949		 * lock, we ensure that we will never be in competition
1950		 * with another process to allocate a block.
1951		 */
1952		if (snapshot_locked == 0 &&
1953		    lockmgr(vp->v_vnlock,
1954		      LK_INTERLOCK | LK_EXCLUSIVE | LK_SLEEPFAIL,
1955		      VI_MTX(devvp), td) != 0) {
1956			VI_LOCK(devvp);
1957			goto retry;
1958		}
1959		snapshot_locked = 1;
1960		td->td_proc->p_flag |= P_COWINPROGRESS;
1961		error = UFS_BALLOC(vp, lblktosize(fs, (off_t)lbn),
1962		    fs->fs_bsize, KERNCRED, 0, &cbp);
1963		td->td_proc->p_flag &= ~P_COWINPROGRESS;
1964		if (error)
1965			break;
1966#ifdef DEBUG
1967		if (snapdebug) {
1968			printf("Copyonwrite: snapino %d lbn %jd for ",
1969			    ip->i_number, (intmax_t)lbn);
1970			if (bp->b_vp == devvp)
1971				printf("fs metadata");
1972			else
1973				printf("inum %d", VTOI(bp->b_vp)->i_number);
1974			printf(" lblkno %jd to blkno %jd\n",
1975			    (intmax_t)bp->b_lblkno, (intmax_t)cbp->b_blkno);
1976		}
1977#endif
1978		/*
1979		 * If we have already read the old block contents, then
1980		 * simply copy them to the new block. Note that we need
1981		 * to synchronously write snapshots that have not been
1982		 * unlinked, and hence will be visible after a crash,
1983		 * to ensure their integrity.
1984		 */
1985		if (savedcbp != 0) {
1986			bcopy(savedcbp->b_data, cbp->b_data, fs->fs_bsize);
1987			bawrite(cbp);
1988			if (dopersistence && ip->i_effnlink > 0)
1989				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
1990			continue;
1991		}
1992		/*
1993		 * Otherwise, read the old block contents into the buffer.
1994		 */
1995		if ((error = readblock(cbp, lbn)) != 0) {
1996			bzero(cbp->b_data, fs->fs_bsize);
1997			bawrite(cbp);
1998			if (dopersistence && ip->i_effnlink > 0)
1999				(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
2000			break;
2001		}
2002		savedcbp = cbp;
2003	}
2004	/*
2005	 * Note that we need to synchronously write snapshots that
2006	 * have not been unlinked, and hence will be visible after
2007	 * a crash, to ensure their integrity.
2008	 */
2009	if (savedcbp) {
2010		vp = savedcbp->b_vp;
2011		bawrite(savedcbp);
2012		if (dopersistence && VTOI(vp)->i_effnlink > 0)
2013			(void) VOP_FSYNC(vp, KERNCRED, MNT_WAIT, td);
2014	}
2015	if (snapshot_locked)
2016		VOP_UNLOCK(vp, 0, td);
2017	else
2018		VI_UNLOCK(devvp);
2019	return (error);
2020}
2021
2022/*
2023 * Read the specified block into the given buffer.
2024 * Much of this boiler-plate comes from bwrite().
2025 */
2026static int
2027readblock(bp, lbn)
2028	struct buf *bp;
2029	ufs2_daddr_t lbn;
2030{
2031	struct uio auio;
2032	struct iovec aiov;
2033	struct thread *td = curthread;
2034	struct inode *ip = VTOI(bp->b_vp);
2035
2036	aiov.iov_base = bp->b_data;
2037	aiov.iov_len = bp->b_bcount;
2038	auio.uio_iov = &aiov;
2039	auio.uio_iovcnt = 1;
2040	auio.uio_offset = dbtob(fsbtodb(ip->i_fs, blkstofrags(ip->i_fs, lbn)));
2041	auio.uio_resid = bp->b_bcount;
2042	auio.uio_rw = UIO_READ;
2043	auio.uio_segflg = UIO_SYSSPACE;
2044	auio.uio_td = td;
2045	return (physio(ip->i_devvp->v_rdev, &auio, 0));
2046}
2047