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