ffs_snapshot.c revision 1.123
1/*	$NetBSD: ffs_snapshot.c,v 1.123 2013/06/16 13:33:30 hannken Exp $	*/
2
3/*
4 * Copyright 2000 Marshall Kirk McKusick. All Rights Reserved.
5 *
6 * Further information about snapshots can be obtained from:
7 *
8 *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
9 *	1614 Oxford Street		mckusick@mckusick.com
10 *	Berkeley, CA 94709-1608		+1-510-843-9542
11 *	USA
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 *
17 * 1. Redistributions of source code must retain the above copyright
18 *    notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 *    notice, this list of conditions and the following disclaimer in the
21 *    documentation and/or other materials provided with the distribution.
22 *
23 * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
24 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
27 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 *	@(#)ffs_snapshot.c	8.11 (McKusick) 7/23/00
36 *
37 *	from FreeBSD: ffs_snapshot.c,v 1.79 2004/02/13 02:02:06 kuriyama Exp
38 */
39
40#include <sys/cdefs.h>
41__KERNEL_RCSID(0, "$NetBSD: ffs_snapshot.c,v 1.123 2013/06/16 13:33:30 hannken Exp $");
42
43#if defined(_KERNEL_OPT)
44#include "opt_ffs.h"
45#include "opt_quota.h"
46#endif
47
48#include <sys/param.h>
49#include <sys/kernel.h>
50#include <sys/systm.h>
51#include <sys/conf.h>
52#include <sys/buf.h>
53#include <sys/proc.h>
54#include <sys/namei.h>
55#include <sys/sched.h>
56#include <sys/stat.h>
57#include <sys/malloc.h>
58#include <sys/mount.h>
59#include <sys/resource.h>
60#include <sys/resourcevar.h>
61#include <sys/vnode.h>
62#include <sys/kauth.h>
63#include <sys/fstrans.h>
64#include <sys/wapbl.h>
65
66#include <miscfs/specfs/specdev.h>
67
68#include <ufs/ufs/quota.h>
69#include <ufs/ufs/ufsmount.h>
70#include <ufs/ufs/inode.h>
71#include <ufs/ufs/ufs_extern.h>
72#include <ufs/ufs/ufs_bswap.h>
73#include <ufs/ufs/ufs_wapbl.h>
74
75#include <ufs/ffs/fs.h>
76#include <ufs/ffs/ffs_extern.h>
77
78#include <uvm/uvm.h>
79
80struct snap_info {
81	kmutex_t si_lock;			/* Lock this snapinfo */
82	kmutex_t si_snaplock;			/* Snapshot vnode common lock */
83	lwp_t *si_owner;			/* Sanplock owner */
84	TAILQ_HEAD(inodelst, inode) si_snapshots; /* List of active snapshots */
85	daddr_t *si_snapblklist;		/* Snapshot block hints list */
86	uint32_t si_gen;			/* Incremented on change */
87};
88
89#if !defined(FFS_NO_SNAPSHOT)
90typedef int (*acctfunc_t)
91    (struct vnode *, void *, int, int, struct fs *, daddr_t, int);
92
93static int snapshot_setup(struct mount *, struct vnode *);
94static int snapshot_copyfs(struct mount *, struct vnode *, void **);
95static int snapshot_expunge(struct mount *, struct vnode *,
96    struct fs *, daddr_t *, daddr_t **);
97static int snapshot_expunge_snap(struct mount *, struct vnode *,
98    struct fs *, daddr_t);
99static int snapshot_writefs(struct mount *, struct vnode *, void *);
100static int cgaccount(struct vnode *, int, int *);
101static int cgaccount1(int, struct vnode *, void *, int);
102static int expunge(struct vnode *, struct inode *, struct fs *,
103    acctfunc_t, int);
104static int indiracct(struct vnode *, struct vnode *, int, daddr_t,
105    daddr_t, daddr_t, daddr_t, daddr_t, struct fs *, acctfunc_t, int);
106static int fullacct(struct vnode *, void *, int, int, struct fs *,
107    daddr_t, int);
108static int snapacct(struct vnode *, void *, int, int, struct fs *,
109    daddr_t, int);
110static int mapacct(struct vnode *, void *, int, int, struct fs *,
111    daddr_t, int);
112#endif /* !defined(FFS_NO_SNAPSHOT) */
113
114static int ffs_copyonwrite(void *, struct buf *, bool);
115static int snapblkaddr(struct vnode *, daddr_t, daddr_t *);
116static int rwfsblk(struct vnode *, int, void *, daddr_t);
117static int syncsnap(struct vnode *);
118static int wrsnapblk(struct vnode *, void *, daddr_t);
119#if !defined(FFS_NO_SNAPSHOT)
120static int blocks_in_journal(struct fs *);
121#endif
122
123static inline bool is_active_snapshot(struct snap_info *, struct inode *);
124static inline daddr_t db_get(struct inode *, int);
125static inline void db_assign(struct inode *, int, daddr_t);
126static inline daddr_t ib_get(struct inode *, int);
127static inline void ib_assign(struct inode *, int, daddr_t);
128static inline daddr_t idb_get(struct inode *, void *, int);
129static inline void idb_assign(struct inode *, void *, int, daddr_t);
130
131#ifdef DEBUG
132static int snapdebug = 0;
133#endif
134
135int
136ffs_snapshot_init(struct ufsmount *ump)
137{
138	struct snap_info *si;
139
140	si = ump->um_snapinfo = kmem_alloc(sizeof(*si), KM_SLEEP);
141	if (si == NULL)
142		return ENOMEM;
143
144	TAILQ_INIT(&si->si_snapshots);
145	mutex_init(&si->si_lock, MUTEX_DEFAULT, IPL_NONE);
146	mutex_init(&si->si_snaplock, MUTEX_DEFAULT, IPL_NONE);
147	si->si_owner = NULL;
148	si->si_gen = 0;
149	si->si_snapblklist = NULL;
150
151	return 0;
152}
153
154void
155ffs_snapshot_fini(struct ufsmount *ump)
156{
157	struct snap_info *si;
158
159	si = ump->um_snapinfo;
160	ump->um_snapinfo = NULL;
161
162	KASSERT(TAILQ_EMPTY(&si->si_snapshots));
163	mutex_destroy(&si->si_lock);
164	mutex_destroy(&si->si_snaplock);
165	KASSERT(si->si_snapblklist == NULL);
166	kmem_free(si, sizeof(*si));
167}
168
169/*
170 * Create a snapshot file and initialize it for the filesystem.
171 * Vnode is locked on entry and return.
172 */
173int
174ffs_snapshot(struct mount *mp, struct vnode *vp, struct timespec *ctime)
175{
176#if defined(FFS_NO_SNAPSHOT)
177	return EOPNOTSUPP;
178}
179#else /* defined(FFS_NO_SNAPSHOT) */
180	bool suspended = false;
181	int error, redo = 0, snaploc;
182	void *sbbuf = NULL;
183	daddr_t *snaplist = NULL, snaplistsize = 0;
184	struct buf *bp, *nbp;
185	struct fs *copy_fs = NULL;
186	struct fs *fs = VFSTOUFS(mp)->um_fs;
187	struct inode *ip = VTOI(vp);
188	struct lwp *l = curlwp;
189	struct snap_info *si = VFSTOUFS(mp)->um_snapinfo;
190	struct timespec ts;
191	struct timeval starttime;
192#ifdef DEBUG
193	struct timeval endtime;
194#endif
195	struct vnode *devvp = ip->i_devvp;
196
197	/*
198	 * If the vnode already is a snapshot, return.
199	 */
200	if ((VTOI(vp)->i_flags & SF_SNAPSHOT)) {
201		if ((VTOI(vp)->i_flags & SF_SNAPINVAL))
202			return EINVAL;
203		if (ctime) {
204			ctime->tv_sec = DIP(VTOI(vp), mtime);
205			ctime->tv_nsec = DIP(VTOI(vp), mtimensec);
206		}
207		return 0;
208	}
209	/*
210	 * Check for free snapshot slot in the superblock.
211	 */
212	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
213		if (fs->fs_snapinum[snaploc] == 0)
214			break;
215	if (snaploc == FSMAXSNAP)
216		return (ENOSPC);
217	/*
218	 * Prepare the vnode to become a snapshot.
219	 */
220	error = snapshot_setup(mp, vp);
221	if (error)
222		goto out;
223
224	/*
225	 * Copy all the cylinder group maps. Although the
226	 * filesystem is still active, we hope that only a few
227	 * cylinder groups will change between now and when we
228	 * suspend operations. Thus, we will be able to quickly
229	 * touch up the few cylinder groups that changed during
230	 * the suspension period.
231	 */
232	error = cgaccount(vp, 1, NULL);
233	if (error)
234		goto out;
235
236	/*
237	 * snapshot is now valid
238	 */
239	ip->i_flags &= ~SF_SNAPINVAL;
240	DIP_ASSIGN(ip, flags, ip->i_flags);
241	ip->i_flag |= IN_CHANGE | IN_UPDATE;
242
243	/*
244	 * Ensure that the snapshot is completely on disk.
245	 * Since we have marked it as a snapshot it is safe to
246	 * unlock it as no process will be allowed to write to it.
247	 */
248	error = VOP_FSYNC(vp, l->l_cred, FSYNC_WAIT, 0, 0);
249	if (error)
250		goto out;
251	VOP_UNLOCK(vp);
252	/*
253	 * All allocations are done, so we can now suspend the filesystem.
254	 */
255	error = vfs_suspend(vp->v_mount, 0);
256	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
257	if (error)
258		goto out;
259	suspended = true;
260	getmicrotime(&starttime);
261	/*
262	 * First, copy all the cylinder group maps that have changed.
263	 */
264	error = cgaccount(vp, 2, &redo);
265	if (error)
266		goto out;
267	/*
268	 * Create a copy of the superblock and its summary information.
269	 */
270	error = snapshot_copyfs(mp, vp, &sbbuf);
271	copy_fs = (struct fs *)((char *)sbbuf + blkoff(fs, fs->fs_sblockloc));
272	if (error)
273		goto out;
274	/*
275	 * Expunge unlinked files from our view.
276	 */
277	error = snapshot_expunge(mp, vp, copy_fs, &snaplistsize, &snaplist);
278	if (error)
279		goto out;
280	/*
281	 * Record snapshot inode. Since this is the newest snapshot,
282	 * it must be placed at the end of the list.
283	 */
284	if (ip->i_nlink > 0)
285		fs->fs_snapinum[snaploc] = ip->i_number;
286
287	mutex_enter(&si->si_lock);
288	if (is_active_snapshot(si, ip))
289		panic("ffs_snapshot: %"PRIu64" already on list", ip->i_number);
290	TAILQ_INSERT_TAIL(&si->si_snapshots, ip, i_nextsnap);
291	if (TAILQ_FIRST(&si->si_snapshots) == ip) {
292		/*
293		 * If this is the first snapshot on this filesystem, put the
294		 * preliminary list in place and establish the cow handler.
295		 */
296		si->si_snapblklist = snaplist;
297		fscow_establish(mp, ffs_copyonwrite, devvp);
298	}
299	si->si_gen++;
300	mutex_exit(&si->si_lock);
301
302	vp->v_vflag |= VV_SYSTEM;
303	/*
304	 * Set the mtime to the time the snapshot has been taken.
305	 */
306	TIMEVAL_TO_TIMESPEC(&starttime, &ts);
307	if (ctime)
308		*ctime = ts;
309	DIP_ASSIGN(ip, mtime, ts.tv_sec);
310	DIP_ASSIGN(ip, mtimensec, ts.tv_nsec);
311	ip->i_flag |= IN_CHANGE | IN_UPDATE;
312	/*
313	 * Copy allocation information from all snapshots and then
314	 * expunge them from our view.
315	 */
316	error = snapshot_expunge_snap(mp, vp, copy_fs, snaplistsize);
317	if (error)
318		goto out;
319	/*
320	 * Write the superblock and its summary information to the snapshot.
321	 */
322	error = snapshot_writefs(mp, vp, sbbuf);
323	if (error)
324		goto out;
325	/*
326	 * We're nearly done, ensure that the snapshot is completely on disk.
327	 */
328	error = VOP_FSYNC(vp, l->l_cred, FSYNC_WAIT, 0, 0);
329	if (error)
330		goto out;
331	/*
332	 * Invalidate and free all pages on the snapshot vnode.
333	 * We will read and write through the buffercache.
334	 */
335	mutex_enter(vp->v_interlock);
336	error = VOP_PUTPAGES(vp, 0, 0,
337		    PGO_ALLPAGES | PGO_CLEANIT | PGO_SYNCIO | PGO_FREE);
338	if (error)
339		goto out;
340	/*
341	 * Invalidate short ( < fs_bsize ) buffers.  We will always read
342	 * full size buffers later.
343	 */
344	mutex_enter(&bufcache_lock);
345	KASSERT(LIST_FIRST(&vp->v_dirtyblkhd) == NULL);
346	for (bp = LIST_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
347		nbp = LIST_NEXT(bp, b_vnbufs);
348		if (bp->b_bcount == fs->fs_bsize)
349			continue;
350		error = bbusy(bp, false, 0, NULL);
351		if (error != 0) {
352			if (error == EPASSTHROUGH) {
353				nbp = LIST_FIRST(&vp->v_cleanblkhd);
354				continue;
355			}
356			break;
357		}
358		brelsel(bp, BC_INVAL | BC_VFLUSH);
359	}
360	mutex_exit(&bufcache_lock);
361
362out:
363	if (sbbuf != NULL) {
364		free(copy_fs->fs_csp, M_UFSMNT);
365		free(sbbuf, M_UFSMNT);
366	}
367	if (fs->fs_active != NULL) {
368		free(fs->fs_active, M_DEVBUF);
369		fs->fs_active = NULL;
370	}
371
372	mutex_enter(&si->si_lock);
373	if (snaplist != NULL) {
374		if (si->si_snapblklist == snaplist)
375			si->si_snapblklist = NULL;
376		free(snaplist, M_UFSMNT);
377	}
378	if (error) {
379		fs->fs_snapinum[snaploc] = 0;
380	} else {
381		/*
382		 * As this is the newest list, it is the most inclusive, so
383		 * should replace the previous list.
384		 */
385		si->si_snapblklist = ip->i_snapblklist;
386	}
387	si->si_gen++;
388	mutex_exit(&si->si_lock);
389
390	if (suspended) {
391		VOP_UNLOCK(vp);
392		vfs_resume(vp->v_mount);
393		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
394#ifdef DEBUG
395		getmicrotime(&endtime);
396		timersub(&endtime, &starttime, &endtime);
397		printf("%s: suspended %lld.%03d sec, redo %d of %d\n",
398		    mp->mnt_stat.f_mntonname, (long long)endtime.tv_sec,
399		    endtime.tv_usec / 1000, redo, fs->fs_ncg);
400#endif
401	}
402	if (error) {
403		if (!UFS_WAPBL_BEGIN(mp)) {
404			(void) ffs_truncate(vp, (off_t)0, 0, NOCRED);
405			UFS_WAPBL_END(mp);
406		}
407	} else if (ip->i_nlink > 0)
408		vref(vp);
409	return (error);
410}
411
412/*
413 * Prepare vnode to become a snapshot.
414 */
415static int
416snapshot_setup(struct mount *mp, struct vnode *vp)
417{
418	int error, n, len, loc, cg;
419	daddr_t blkno, numblks;
420	struct buf *ibp, *nbp;
421	struct fs *fs = VFSTOUFS(mp)->um_fs;
422	struct lwp *l = curlwp;
423	const int wbreak = blocks_in_journal(fs)/8;
424	struct inode *ip = VTOI(vp);
425
426	/*
427	 * Check mount, exclusive reference and owner.
428	 */
429	if (vp->v_mount != mp)
430		return EXDEV;
431	if (vp->v_usecount != 1 || vp->v_writecount != 0)
432		return EBUSY;
433	error = kauth_authorize_system(l->l_cred, KAUTH_SYSTEM_FS_SNAPSHOT,
434	    0, mp, vp, NULL);
435	if (error)
436		return EACCES;
437
438	if (vp->v_size != 0) {
439		error = ffs_truncate(vp, 0, 0, NOCRED);
440		if (error)
441			return error;
442	}
443
444	/* Change inode to snapshot type file. */
445	error = UFS_WAPBL_BEGIN(mp);
446	if (error)
447		return error;
448#if defined(QUOTA) || defined(QUOTA2)
449	/* shapshot inodes are not accounted in quotas */
450	chkiq(ip, -1, l->l_cred, 0);
451#endif
452	ip->i_flags |= (SF_SNAPSHOT | SF_SNAPINVAL);
453	DIP_ASSIGN(ip, flags, ip->i_flags);
454	ip->i_flag |= IN_CHANGE | IN_UPDATE;
455	ffs_update(vp, NULL, NULL, UPDATE_WAIT);
456	UFS_WAPBL_END(mp);
457
458	KASSERT(ip->i_flags & SF_SNAPSHOT);
459	/*
460	 * Write an empty list of preallocated blocks to the end of
461	 * the snapshot to set size to at least that of the filesystem.
462	 */
463	numblks = howmany(fs->fs_size, fs->fs_frag);
464	blkno = 1;
465	blkno = ufs_rw64(blkno, UFS_FSNEEDSWAP(fs));
466	error = vn_rdwr(UIO_WRITE, vp,
467	    (void *)&blkno, sizeof(blkno), lblktosize(fs, (off_t)numblks),
468	    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT, l->l_cred, NULL, NULL);
469	if (error)
470		return error;
471	/*
472	 * Preallocate critical data structures so that we can copy
473	 * them in without further allocation after we suspend all
474	 * operations on the filesystem. We would like to just release
475	 * the allocated buffers without writing them since they will
476	 * be filled in below once we are ready to go, but this upsets
477	 * the soft update code, so we go ahead and write the new buffers.
478	 *
479	 * Allocate all indirect blocks and mark all of them as not
480	 * needing to be copied.
481	 */
482	error = UFS_WAPBL_BEGIN(mp);
483	if (error)
484		return error;
485	for (blkno = UFS_NDADDR, n = 0; blkno < numblks; blkno += NINDIR(fs)) {
486		error = ffs_balloc(vp, lblktosize(fs, (off_t)blkno),
487		    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
488		if (error)
489			goto out;
490		brelse(ibp, 0);
491		if (wbreak > 0 && (++n % wbreak) == 0) {
492			UFS_WAPBL_END(mp);
493			error = UFS_WAPBL_BEGIN(mp);
494			if (error)
495				return error;
496		}
497	}
498	/*
499	 * Allocate copies for the superblock and its summary information.
500	 */
501	error = ffs_balloc(vp, fs->fs_sblockloc, fs->fs_sbsize, l->l_cred,
502	    0, &nbp);
503	if (error)
504		goto out;
505	bawrite(nbp);
506	blkno = fragstoblks(fs, fs->fs_csaddr);
507	len = howmany(fs->fs_cssize, fs->fs_bsize);
508	for (loc = 0; loc < len; loc++) {
509		error = ffs_balloc(vp, lblktosize(fs, (off_t)(blkno + loc)),
510		    fs->fs_bsize, l->l_cred, 0, &nbp);
511		if (error)
512			goto out;
513		bawrite(nbp);
514		if (wbreak > 0 && (++n % wbreak) == 0) {
515			UFS_WAPBL_END(mp);
516			error = UFS_WAPBL_BEGIN(mp);
517			if (error)
518				return error;
519		}
520	}
521	/*
522	 * Allocate all cylinder group blocks.
523	 */
524	for (cg = 0; cg < fs->fs_ncg; cg++) {
525		error = ffs_balloc(vp, lfragtosize(fs, cgtod(fs, cg)),
526		    fs->fs_bsize, l->l_cred, 0, &nbp);
527		if (error)
528			goto out;
529		bawrite(nbp);
530		if (wbreak > 0 && (++n % wbreak) == 0) {
531			UFS_WAPBL_END(mp);
532			error = UFS_WAPBL_BEGIN(mp);
533			if (error)
534				return error;
535		}
536	}
537
538out:
539	UFS_WAPBL_END(mp);
540	return error;
541}
542
543/*
544 * Create a copy of the superblock and its summary information.
545 * It is up to the caller to free copyfs and copy_fs->fs_csp.
546 */
547static int
548snapshot_copyfs(struct mount *mp, struct vnode *vp, void **sbbuf)
549{
550	int error, i, len, loc, size;
551	void *space;
552	int32_t *lp;
553	struct buf *bp;
554	struct fs *copyfs, *fs = VFSTOUFS(mp)->um_fs;
555	struct lwp *l = curlwp;
556	struct vnode *devvp = VTOI(vp)->i_devvp;
557
558	/*
559	 * Grab a copy of the superblock and its summary information.
560	 * We delay writing it until the suspension is released below.
561	 */
562	*sbbuf = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
563	loc = blkoff(fs, fs->fs_sblockloc);
564	if (loc > 0)
565		memset(*sbbuf, 0, loc);
566	copyfs = (struct fs *)((char *)(*sbbuf) + loc);
567	memcpy(copyfs, fs, fs->fs_sbsize);
568	size = fs->fs_bsize < SBLOCKSIZE ? fs->fs_bsize : SBLOCKSIZE;
569	if (fs->fs_sbsize < size)
570		memset((char *)(*sbbuf) + loc + fs->fs_sbsize, 0,
571		    size - fs->fs_sbsize);
572	size = blkroundup(fs, fs->fs_cssize);
573	if (fs->fs_contigsumsize > 0)
574		size += fs->fs_ncg * sizeof(int32_t);
575	space = malloc(size, M_UFSMNT, M_WAITOK);
576	copyfs->fs_csp = space;
577	memcpy(copyfs->fs_csp, fs->fs_csp, fs->fs_cssize);
578	space = (char *)space + fs->fs_cssize;
579	loc = howmany(fs->fs_cssize, fs->fs_fsize);
580	i = fs->fs_frag - loc % fs->fs_frag;
581	len = (i == fs->fs_frag) ? 0 : i * fs->fs_fsize;
582	if (len > 0) {
583		if ((error = bread(devvp, fsbtodb(fs, fs->fs_csaddr + loc),
584		    len, l->l_cred, 0, &bp)) != 0) {
585			free(copyfs->fs_csp, M_UFSMNT);
586			free(*sbbuf, M_UFSMNT);
587			*sbbuf = NULL;
588			return error;
589		}
590		memcpy(space, bp->b_data, (u_int)len);
591		space = (char *)space + len;
592		brelse(bp, BC_INVAL | BC_NOCACHE);
593	}
594	if (fs->fs_contigsumsize > 0) {
595		copyfs->fs_maxcluster = lp = space;
596		for (i = 0; i < fs->fs_ncg; i++)
597			*lp++ = fs->fs_contigsumsize;
598	}
599	if (mp->mnt_wapbl)
600		copyfs->fs_flags &= ~FS_DOWAPBL;
601	return 0;
602}
603
604/*
605 * We must check for active files that have been unlinked (e.g., with a zero
606 * link count). We have to expunge all trace of these files from the snapshot
607 * so that they are not reclaimed prematurely by fsck or unnecessarily dumped.
608 * Note that we skip unlinked snapshot files as they will be handled separately.
609 * Calculate the snapshot list size and create a preliminary list.
610 */
611static int
612snapshot_expunge(struct mount *mp, struct vnode *vp, struct fs *copy_fs,
613    daddr_t *snaplistsize, daddr_t **snaplist)
614{
615	int cg, error = 0, len, loc;
616	daddr_t blkno, *blkp;
617	struct fs *fs = VFSTOUFS(mp)->um_fs;
618	struct inode *xp;
619	struct lwp *l = curlwp;
620	struct vattr vat;
621	struct vnode *logvp = NULL, *mvp = NULL, *xvp;
622
623	*snaplist = NULL;
624	/*
625	 * Get the log inode if any.
626	 */
627	if ((fs->fs_flags & FS_DOWAPBL) &&
628	    fs->fs_journal_location == UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM) {
629		error = VFS_VGET(mp,
630		    fs->fs_journallocs[UFS_WAPBL_INFS_INO], &logvp);
631		if (error)
632			goto out;
633	}
634	/*
635	 * Allocate a marker vnode.
636	 */
637	mvp = vnalloc(mp);
638	/*
639	 * We also calculate the needed size for the snapshot list.
640	 */
641	*snaplistsize = fs->fs_ncg + howmany(fs->fs_cssize, fs->fs_bsize) +
642	    FSMAXSNAP + 1 /* superblock */ + 1 /* last block */ + 1 /* size */;
643	mutex_enter(&mntvnode_lock);
644	/*
645	 * NOTE: not using the TAILQ_FOREACH here since in this loop vgone()
646	 * and vclean() can be called indirectly
647	 */
648	for (xvp = TAILQ_FIRST(&mp->mnt_vnodelist); xvp; xvp = vunmark(mvp)) {
649		vmark(mvp, xvp);
650		/*
651		 * Make sure this vnode wasn't reclaimed in getnewvnode().
652		 * Start over if it has (it won't be on the list anymore).
653		 */
654		if (xvp->v_mount != mp || vismarker(xvp))
655			continue;
656		mutex_enter(xvp->v_interlock);
657		if ((xvp->v_iflag & VI_XLOCK) ||
658		    xvp->v_usecount == 0 || xvp->v_type == VNON ||
659		    VTOI(xvp) == NULL ||
660		    (VTOI(xvp)->i_flags & SF_SNAPSHOT)) {
661			mutex_exit(xvp->v_interlock);
662			continue;
663		}
664		mutex_exit(&mntvnode_lock);
665		/*
666		 * XXXAD should increase vnode ref count to prevent it
667		 * disappearing or being recycled.
668		 */
669		mutex_exit(xvp->v_interlock);
670#ifdef DEBUG
671		if (snapdebug)
672			vprint("ffs_snapshot: busy vnode", xvp);
673#endif
674		xp = VTOI(xvp);
675		if (xvp != logvp) {
676			if (VOP_GETATTR(xvp, &vat, l->l_cred) == 0 &&
677			    vat.va_nlink > 0) {
678				mutex_enter(&mntvnode_lock);
679				continue;
680			}
681			if (ffs_checkfreefile(copy_fs, vp, xp->i_number)) {
682				mutex_enter(&mntvnode_lock);
683				continue;
684			}
685		}
686		/*
687		 * If there is a fragment, clear it here.
688		 */
689		blkno = 0;
690		loc = howmany(xp->i_size, fs->fs_bsize) - 1;
691		if (loc < UFS_NDADDR) {
692			len = fragroundup(fs, blkoff(fs, xp->i_size));
693			if (len > 0 && len < fs->fs_bsize) {
694				error = UFS_WAPBL_BEGIN(mp);
695				if (error) {
696					(void)vunmark(mvp);
697					goto out;
698				}
699				ffs_blkfree_snap(copy_fs, vp, db_get(xp, loc),
700				    len, xp->i_number);
701				blkno = db_get(xp, loc);
702				db_assign(xp, loc, 0);
703				UFS_WAPBL_END(mp);
704			}
705		}
706		*snaplistsize += 1;
707		error = expunge(vp, xp, copy_fs, fullacct, BLK_NOCOPY);
708		if (blkno)
709			db_assign(xp, loc, blkno);
710		if (!error) {
711			error = UFS_WAPBL_BEGIN(mp);
712			if (!error) {
713				error = ffs_freefile_snap(copy_fs, vp,
714				    xp->i_number, xp->i_mode);
715				UFS_WAPBL_END(mp);
716			}
717		}
718		if (error) {
719			(void)vunmark(mvp);
720			goto out;
721		}
722		mutex_enter(&mntvnode_lock);
723	}
724	mutex_exit(&mntvnode_lock);
725	/*
726	 * Create a preliminary list of preallocated snapshot blocks.
727	 */
728	*snaplist = malloc(*snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
729	blkp = &(*snaplist)[1];
730	*blkp++ = lblkno(fs, fs->fs_sblockloc);
731	blkno = fragstoblks(fs, fs->fs_csaddr);
732	for (cg = 0; cg < fs->fs_ncg; cg++) {
733		if (fragstoblks(fs, cgtod(fs, cg)) > blkno)
734			break;
735		*blkp++ = fragstoblks(fs, cgtod(fs, cg));
736	}
737	len = howmany(fs->fs_cssize, fs->fs_bsize);
738	for (loc = 0; loc < len; loc++)
739		*blkp++ = blkno + loc;
740	for (; cg < fs->fs_ncg; cg++)
741		*blkp++ = fragstoblks(fs, cgtod(fs, cg));
742	(*snaplist)[0] = blkp - &(*snaplist)[0];
743
744out:
745	if (mvp != NULL)
746		vnfree(mvp);
747	if (logvp != NULL)
748		vput(logvp);
749	if (error && *snaplist != NULL) {
750		free(*snaplist, M_UFSMNT);
751		*snaplist = NULL;
752	}
753
754	return error;
755}
756
757/*
758 * Copy allocation information from all the snapshots in this snapshot and
759 * then expunge them from its view. Also, collect the list of allocated
760 * blocks in i_snapblklist.
761 */
762static int
763snapshot_expunge_snap(struct mount *mp, struct vnode *vp,
764    struct fs *copy_fs, daddr_t snaplistsize)
765{
766	int error = 0, i;
767	daddr_t numblks, *snaplist = NULL;
768	struct fs *fs = VFSTOUFS(mp)->um_fs;
769	struct inode *ip = VTOI(vp), *xp;
770	struct lwp *l = curlwp;
771	struct snap_info *si = VFSTOUFS(mp)->um_snapinfo;
772
773	TAILQ_FOREACH(xp, &si->si_snapshots, i_nextsnap) {
774		if (xp != ip) {
775			error = expunge(vp, xp, fs, snapacct, BLK_SNAP);
776			if (error)
777				break;
778		}
779		if (xp->i_nlink != 0)
780			continue;
781		error = UFS_WAPBL_BEGIN(mp);
782		if (error)
783			break;
784		error = ffs_freefile_snap(copy_fs, vp, xp->i_number, xp->i_mode);
785		UFS_WAPBL_END(mp);
786		if (error)
787			break;
788	}
789	if (error)
790		goto out;
791	/*
792	 * Allocate space for the full list of preallocated snapshot blocks.
793	 */
794	snaplist = malloc(snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
795	ip->i_snapblklist = &snaplist[1];
796	/*
797	 * Expunge the blocks used by the snapshots from the set of
798	 * blocks marked as used in the snapshot bitmaps. Also, collect
799	 * the list of allocated blocks in i_snapblklist.
800	 */
801	error = expunge(vp, ip, copy_fs, mapacct, BLK_SNAP);
802	if (error)
803		goto out;
804	if (snaplistsize < ip->i_snapblklist - snaplist)
805		panic("ffs_snapshot: list too small");
806	snaplistsize = ip->i_snapblklist - snaplist;
807	snaplist[0] = snaplistsize;
808	ip->i_snapblklist = &snaplist[0];
809	/*
810	 * Write out the list of allocated blocks to the end of the snapshot.
811	 */
812	numblks = howmany(fs->fs_size, fs->fs_frag);
813	for (i = 0; i < snaplistsize; i++)
814		snaplist[i] = ufs_rw64(snaplist[i], UFS_FSNEEDSWAP(fs));
815	error = vn_rdwr(UIO_WRITE, vp, (void *)snaplist,
816	    snaplistsize * sizeof(daddr_t), lblktosize(fs, (off_t)numblks),
817	    UIO_SYSSPACE, IO_NODELOCKED | IO_UNIT, l->l_cred, NULL, NULL);
818	for (i = 0; i < snaplistsize; i++)
819		snaplist[i] = ufs_rw64(snaplist[i], UFS_FSNEEDSWAP(fs));
820out:
821	if (error && snaplist != NULL) {
822		free(snaplist, M_UFSMNT);
823		ip->i_snapblklist = NULL;
824	}
825	return error;
826}
827
828/*
829 * Write the superblock and its summary information to the snapshot.
830 * Make sure, the first UFS_NDADDR blocks get copied to the snapshot.
831 */
832static int
833snapshot_writefs(struct mount *mp, struct vnode *vp, void *sbbuf)
834{
835	int error, len, loc;
836	void *space;
837	daddr_t blkno;
838	struct buf *bp;
839	struct fs *copyfs, *fs = VFSTOUFS(mp)->um_fs;
840	struct inode *ip = VTOI(vp);
841	struct lwp *l = curlwp;
842
843	copyfs = (struct fs *)((char *)sbbuf + blkoff(fs, fs->fs_sblockloc));
844
845	/*
846	 * Write the superblock and its summary information
847	 * to the snapshot.
848	 */
849	blkno = fragstoblks(fs, fs->fs_csaddr);
850	len = howmany(fs->fs_cssize, fs->fs_bsize);
851	space = copyfs->fs_csp;
852#ifdef FFS_EI
853	if (UFS_FSNEEDSWAP(fs)) {
854		ffs_sb_swap(copyfs, copyfs);
855		ffs_csum_swap(space, space, fs->fs_cssize);
856	}
857#endif
858	error = UFS_WAPBL_BEGIN(mp);
859	if (error)
860		return error;
861	for (loc = 0; loc < len; loc++) {
862		error = bread(vp, blkno + loc, fs->fs_bsize, l->l_cred,
863		    B_MODIFY, &bp);
864		if (error) {
865			break;
866		}
867		memcpy(bp->b_data, space, fs->fs_bsize);
868		space = (char *)space + fs->fs_bsize;
869		bawrite(bp);
870	}
871	if (error)
872		goto out;
873	error = bread(vp, lblkno(fs, fs->fs_sblockloc),
874	    fs->fs_bsize, l->l_cred, B_MODIFY, &bp);
875	if (error) {
876		goto out;
877	} else {
878		memcpy(bp->b_data, sbbuf, fs->fs_bsize);
879		bawrite(bp);
880	}
881	/*
882	 * Copy the first UFS_NDADDR blocks to the snapshot so
883	 * ffs_copyonwrite() and ffs_snapblkfree() will always work on
884	 * indirect blocks.
885	 */
886	for (loc = 0; loc < UFS_NDADDR; loc++) {
887		if (db_get(ip, loc) != 0)
888			continue;
889		error = ffs_balloc(vp, lblktosize(fs, (off_t)loc),
890		    fs->fs_bsize, l->l_cred, 0, &bp);
891		if (error)
892			break;
893		error = rwfsblk(vp, B_READ, bp->b_data, loc);
894		if (error) {
895			brelse(bp, 0);
896			break;
897		}
898		bawrite(bp);
899	}
900
901out:
902	UFS_WAPBL_END(mp);
903	return error;
904}
905
906/*
907 * Copy all cylinder group maps.
908 */
909static int
910cgaccount(struct vnode *vp, int passno, int *redo)
911{
912	int cg, error = 0;
913	struct buf *nbp;
914	struct fs *fs = VTOI(vp)->i_fs;
915
916	if (redo != NULL)
917		*redo = 0;
918	if (passno == 1)
919		fs->fs_active = malloc(howmany(fs->fs_ncg, NBBY),
920		    M_DEVBUF, M_WAITOK | M_ZERO);
921	for (cg = 0; cg < fs->fs_ncg; cg++) {
922		if (passno == 2 && ACTIVECG_ISSET(fs, cg))
923			continue;
924
925		if (redo != NULL)
926			*redo += 1;
927		error = UFS_WAPBL_BEGIN(vp->v_mount);
928		if (error)
929			return error;
930		error = ffs_balloc(vp, lfragtosize(fs, cgtod(fs, cg)),
931		    fs->fs_bsize, curlwp->l_cred, 0, &nbp);
932		if (error) {
933			UFS_WAPBL_END(vp->v_mount);
934			break;
935		}
936		error = cgaccount1(cg, vp, nbp->b_data, passno);
937		bawrite(nbp);
938		UFS_WAPBL_END(vp->v_mount);
939		if (error)
940			break;
941	}
942	return error;
943}
944
945/*
946 * Copy a cylinder group map. All the unallocated blocks are marked
947 * BLK_NOCOPY so that the snapshot knows that it need not copy them
948 * if they are later written. If passno is one, then this is a first
949 * pass, so only setting needs to be done. If passno is 2, then this
950 * is a revision to a previous pass which must be undone as the
951 * replacement pass is done.
952 */
953static int
954cgaccount1(int cg, struct vnode *vp, void *data, int passno)
955{
956	struct buf *bp, *ibp;
957	struct inode *ip;
958	struct cg *cgp;
959	struct fs *fs;
960	struct lwp *l = curlwp;
961	daddr_t base, numblks;
962	int error, len, loc, ns, indiroff;
963
964	ip = VTOI(vp);
965	fs = ip->i_fs;
966	ns = UFS_FSNEEDSWAP(fs);
967	error = bread(ip->i_devvp, fsbtodb(fs, cgtod(fs, cg)),
968		(int)fs->fs_cgsize, l->l_cred, 0, &bp);
969	if (error) {
970		return (error);
971	}
972	cgp = (struct cg *)bp->b_data;
973	if (!cg_chkmagic(cgp, ns)) {
974		brelse(bp, 0);
975		return (EIO);
976	}
977	ACTIVECG_SET(fs, cg);
978
979	memcpy(data, bp->b_data, fs->fs_cgsize);
980	brelse(bp, 0);
981	if (fs->fs_cgsize < fs->fs_bsize)
982		memset((char *)data + fs->fs_cgsize, 0,
983		    fs->fs_bsize - fs->fs_cgsize);
984	numblks = howmany(fs->fs_size, fs->fs_frag);
985	len = howmany(fs->fs_fpg, fs->fs_frag);
986	base = cg * fs->fs_fpg / fs->fs_frag;
987	if (base + len >= numblks)
988		len = numblks - base - 1;
989	loc = 0;
990	if (base < UFS_NDADDR) {
991		for ( ; loc < UFS_NDADDR; loc++) {
992			if (ffs_isblock(fs, cg_blksfree(cgp, ns), loc))
993				db_assign(ip, loc, BLK_NOCOPY);
994			else if (db_get(ip, loc) == BLK_NOCOPY) {
995				if (passno == 2)
996					db_assign(ip, loc, 0);
997				else if (passno == 1)
998					panic("ffs_snapshot: lost direct block");
999			}
1000		}
1001	}
1002	if ((error = ffs_balloc(vp, lblktosize(fs, (off_t)(base + loc)),
1003	    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp)) != 0)
1004		return (error);
1005	indiroff = (base + loc - UFS_NDADDR) % NINDIR(fs);
1006	for ( ; loc < len; loc++, indiroff++) {
1007		if (indiroff >= NINDIR(fs)) {
1008			bawrite(ibp);
1009			if ((error = ffs_balloc(vp,
1010			    lblktosize(fs, (off_t)(base + loc)),
1011			    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp)) != 0)
1012				return (error);
1013			indiroff = 0;
1014		}
1015		if (ffs_isblock(fs, cg_blksfree(cgp, ns), loc))
1016			idb_assign(ip, ibp->b_data, indiroff, BLK_NOCOPY);
1017		else if (idb_get(ip, ibp->b_data, indiroff) == BLK_NOCOPY) {
1018			if (passno == 2)
1019				idb_assign(ip, ibp->b_data, indiroff, 0);
1020			else if (passno == 1)
1021				panic("ffs_snapshot: lost indirect block");
1022		}
1023	}
1024	bdwrite(ibp);
1025	return (0);
1026}
1027
1028/*
1029 * Before expunging a snapshot inode, note all the
1030 * blocks that it claims with BLK_SNAP so that fsck will
1031 * be able to account for those blocks properly and so
1032 * that this snapshot knows that it need not copy them
1033 * if the other snapshot holding them is freed.
1034 */
1035static int
1036expunge(struct vnode *snapvp, struct inode *cancelip, struct fs *fs,
1037    acctfunc_t acctfunc, int expungetype)
1038{
1039	int i, error, ns;
1040	daddr_t lbn, rlbn;
1041	daddr_t len, blkno, numblks, blksperindir;
1042	struct ufs1_dinode *dip1;
1043	struct ufs2_dinode *dip2;
1044	struct lwp *l = curlwp;
1045	void *bap;
1046	struct buf *bp;
1047	struct mount *mp;
1048
1049	ns = UFS_FSNEEDSWAP(fs);
1050	mp = snapvp->v_mount;
1051
1052	error = UFS_WAPBL_BEGIN(mp);
1053	if (error)
1054		return error;
1055	/*
1056	 * Prepare to expunge the inode. If its inode block has not
1057	 * yet been copied, then allocate and fill the copy.
1058	 */
1059	lbn = fragstoblks(fs, ino_to_fsba(fs, cancelip->i_number));
1060	error = snapblkaddr(snapvp, lbn, &blkno);
1061	if (error)
1062		return error;
1063	if (blkno != 0) {
1064		error = bread(snapvp, lbn, fs->fs_bsize, l->l_cred,
1065		    B_MODIFY, &bp);
1066	} else {
1067		error = ffs_balloc(snapvp, lblktosize(fs, (off_t)lbn),
1068		    fs->fs_bsize, l->l_cred, 0, &bp);
1069		if (! error)
1070			error = rwfsblk(snapvp, B_READ, bp->b_data, lbn);
1071	}
1072	if (error) {
1073		UFS_WAPBL_END(mp);
1074		return error;
1075	}
1076	/*
1077	 * Set a snapshot inode to be a zero length file, regular files
1078	 * or unlinked snapshots to be completely unallocated.
1079	 */
1080	if (fs->fs_magic == FS_UFS1_MAGIC) {
1081		dip1 = (struct ufs1_dinode *)bp->b_data +
1082		    ino_to_fsbo(fs, cancelip->i_number);
1083		if (cancelip->i_flags & SF_SNAPSHOT) {
1084			dip1->di_flags =
1085			    ufs_rw32(ufs_rw32(dip1->di_flags, ns) |
1086			    SF_SNAPINVAL, ns);
1087		}
1088		if (expungetype == BLK_NOCOPY || cancelip->i_nlink == 0)
1089			dip1->di_mode = 0;
1090		dip1->di_size = 0;
1091		dip1->di_blocks = 0;
1092		memset(&dip1->di_db[0], 0, (UFS_NDADDR + UFS_NIADDR) * sizeof(int32_t));
1093	} else {
1094		dip2 = (struct ufs2_dinode *)bp->b_data +
1095		    ino_to_fsbo(fs, cancelip->i_number);
1096		if (cancelip->i_flags & SF_SNAPSHOT) {
1097			dip2->di_flags =
1098			    ufs_rw32(ufs_rw32(dip2->di_flags, ns) |
1099			    SF_SNAPINVAL, ns);
1100		}
1101		if (expungetype == BLK_NOCOPY || cancelip->i_nlink == 0)
1102			dip2->di_mode = 0;
1103		dip2->di_size = 0;
1104		dip2->di_blocks = 0;
1105		memset(&dip2->di_db[0], 0, (UFS_NDADDR + UFS_NIADDR) * sizeof(int64_t));
1106	}
1107	bdwrite(bp);
1108	UFS_WAPBL_END(mp);
1109	/*
1110	 * Now go through and expunge all the blocks in the file
1111	 * using the function requested.
1112	 */
1113	numblks = howmany(cancelip->i_size, fs->fs_bsize);
1114	if (fs->fs_magic == FS_UFS1_MAGIC)
1115		bap = &cancelip->i_ffs1_db[0];
1116	else
1117		bap = &cancelip->i_ffs2_db[0];
1118	error = (*acctfunc)(snapvp, bap, 0, UFS_NDADDR, fs, 0, expungetype);
1119	if (error)
1120		return (error);
1121	if (fs->fs_magic == FS_UFS1_MAGIC)
1122		bap = &cancelip->i_ffs1_ib[0];
1123	else
1124		bap = &cancelip->i_ffs2_ib[0];
1125	error = (*acctfunc)(snapvp, bap, 0, UFS_NIADDR, fs, -1, expungetype);
1126	if (error)
1127		return (error);
1128	blksperindir = 1;
1129	lbn = -UFS_NDADDR;
1130	len = numblks - UFS_NDADDR;
1131	rlbn = UFS_NDADDR;
1132	for (i = 0; len > 0 && i < UFS_NIADDR; i++) {
1133		error = indiracct(snapvp, ITOV(cancelip), i,
1134		    ib_get(cancelip, i), lbn, rlbn, len,
1135		    blksperindir, fs, acctfunc, expungetype);
1136		if (error)
1137			return (error);
1138		blksperindir *= NINDIR(fs);
1139		lbn -= blksperindir + 1;
1140		len -= blksperindir;
1141		rlbn += blksperindir;
1142	}
1143	return (0);
1144}
1145
1146/*
1147 * Descend an indirect block chain for vnode cancelvp accounting for all
1148 * its indirect blocks in snapvp.
1149 */
1150static int
1151indiracct(struct vnode *snapvp, struct vnode *cancelvp, int level,
1152    daddr_t blkno, daddr_t lbn, daddr_t rlbn, daddr_t remblks,
1153    daddr_t blksperindir, struct fs *fs, acctfunc_t acctfunc, int expungetype)
1154{
1155	int error, num, i;
1156	daddr_t subblksperindir;
1157	struct indir indirs[UFS_NIADDR + 2];
1158	daddr_t last;
1159	void *bap;
1160	struct buf *bp;
1161
1162	if (blkno == 0) {
1163		if (expungetype == BLK_NOCOPY)
1164			return (0);
1165		panic("indiracct: missing indir");
1166	}
1167	if ((error = ufs_getlbns(cancelvp, rlbn, indirs, &num)) != 0)
1168		return (error);
1169	if (lbn != indirs[num - 1 - level].in_lbn || num < 2)
1170		panic("indiracct: botched params");
1171	/*
1172	 * We have to expand bread here since it will deadlock looking
1173	 * up the block number for any blocks that are not in the cache.
1174	 */
1175	error = ffs_getblk(cancelvp, lbn, fsbtodb(fs, blkno), fs->fs_bsize,
1176	    false, &bp);
1177	if (error)
1178		return error;
1179	if ((bp->b_oflags & (BO_DONE | BO_DELWRI)) == 0 && (error =
1180	    rwfsblk(bp->b_vp, B_READ, bp->b_data, fragstoblks(fs, blkno)))) {
1181		brelse(bp, 0);
1182		return (error);
1183	}
1184	/*
1185	 * Account for the block pointers in this indirect block.
1186	 */
1187	last = howmany(remblks, blksperindir);
1188	if (last > NINDIR(fs))
1189		last = NINDIR(fs);
1190	bap = malloc(fs->fs_bsize, M_DEVBUF, M_WAITOK | M_ZERO);
1191	memcpy((void *)bap, bp->b_data, fs->fs_bsize);
1192	brelse(bp, 0);
1193	error = (*acctfunc)(snapvp, bap, 0, last,
1194	    fs, level == 0 ? rlbn : -1, expungetype);
1195	if (error || level == 0)
1196		goto out;
1197	/*
1198	 * Account for the block pointers in each of the indirect blocks
1199	 * in the levels below us.
1200	 */
1201	subblksperindir = blksperindir / NINDIR(fs);
1202	for (lbn++, level--, i = 0; i < last; i++) {
1203		error = indiracct(snapvp, cancelvp, level,
1204		    idb_get(VTOI(snapvp), bap, i), lbn, rlbn, remblks,
1205		    subblksperindir, fs, acctfunc, expungetype);
1206		if (error)
1207			goto out;
1208		rlbn += blksperindir;
1209		lbn -= blksperindir;
1210		remblks -= blksperindir;
1211	}
1212out:
1213	free(bap, M_DEVBUF);
1214	return (error);
1215}
1216
1217/*
1218 * Do both snap accounting and map accounting.
1219 */
1220static int
1221fullacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
1222    struct fs *fs, daddr_t lblkno,
1223    int exptype /* BLK_SNAP or BLK_NOCOPY */)
1224{
1225	int error;
1226
1227	if ((error = snapacct(vp, bap, oldblkp, lastblkp, fs, lblkno, exptype)))
1228		return (error);
1229	return (mapacct(vp, bap, oldblkp, lastblkp, fs, lblkno, exptype));
1230}
1231
1232/*
1233 * Identify a set of blocks allocated in a snapshot inode.
1234 */
1235static int
1236snapacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
1237    struct fs *fs, daddr_t lblkno,
1238    int expungetype /* BLK_SNAP or BLK_NOCOPY */)
1239{
1240	struct inode *ip = VTOI(vp);
1241	struct lwp *l = curlwp;
1242	struct mount *mp = vp->v_mount;
1243	daddr_t blkno;
1244	daddr_t lbn;
1245	struct buf *ibp;
1246	int error, n;
1247	const int wbreak = blocks_in_journal(VFSTOUFS(mp)->um_fs)/8;
1248
1249	error = UFS_WAPBL_BEGIN(mp);
1250	if (error)
1251		return error;
1252	for ( n = 0; oldblkp < lastblkp; oldblkp++) {
1253		blkno = idb_get(ip, bap, oldblkp);
1254		if (blkno == 0 || blkno == BLK_NOCOPY || blkno == BLK_SNAP)
1255			continue;
1256		lbn = fragstoblks(fs, blkno);
1257		if (lbn < UFS_NDADDR) {
1258			blkno = db_get(ip, lbn);
1259			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1260		} else {
1261			error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn),
1262			    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
1263			if (error)
1264				break;
1265			blkno = idb_get(ip, ibp->b_data,
1266			    (lbn - UFS_NDADDR) % NINDIR(fs));
1267		}
1268		/*
1269		 * If we are expunging a snapshot vnode and we
1270		 * find a block marked BLK_NOCOPY, then it is
1271		 * one that has been allocated to this snapshot after
1272		 * we took our current snapshot and can be ignored.
1273		 */
1274		if (expungetype == BLK_SNAP && blkno == BLK_NOCOPY) {
1275			if (lbn >= UFS_NDADDR)
1276				brelse(ibp, 0);
1277		} else {
1278			if (blkno != 0)
1279				panic("snapacct: bad block");
1280			if (lbn < UFS_NDADDR)
1281				db_assign(ip, lbn, expungetype);
1282			else {
1283				idb_assign(ip, ibp->b_data,
1284				    (lbn - UFS_NDADDR) % NINDIR(fs), expungetype);
1285				bdwrite(ibp);
1286			}
1287		}
1288		if (wbreak > 0 && (++n % wbreak) == 0) {
1289			UFS_WAPBL_END(mp);
1290			error = UFS_WAPBL_BEGIN(mp);
1291			if (error)
1292				return error;
1293		}
1294	}
1295	UFS_WAPBL_END(mp);
1296	return error;
1297}
1298
1299/*
1300 * Account for a set of blocks allocated in a snapshot inode.
1301 */
1302static int
1303mapacct(struct vnode *vp, void *bap, int oldblkp, int lastblkp,
1304    struct fs *fs, daddr_t lblkno, int expungetype)
1305{
1306	daddr_t blkno;
1307	struct inode *ip;
1308	struct mount *mp = vp->v_mount;
1309	ino_t inum;
1310	int acctit, error, n;
1311	const int wbreak = blocks_in_journal(VFSTOUFS(mp)->um_fs)/8;
1312
1313	error = UFS_WAPBL_BEGIN(mp);
1314	if (error)
1315		return error;
1316	ip = VTOI(vp);
1317	inum = ip->i_number;
1318	if (lblkno == -1)
1319		acctit = 0;
1320	else
1321		acctit = 1;
1322	for ( n = 0; oldblkp < lastblkp; oldblkp++, lblkno++) {
1323		blkno = idb_get(ip, bap, oldblkp);
1324		if (blkno == 0 || blkno == BLK_NOCOPY)
1325			continue;
1326		if (acctit && expungetype == BLK_SNAP && blkno != BLK_SNAP)
1327			*ip->i_snapblklist++ = lblkno;
1328		if (blkno == BLK_SNAP)
1329			blkno = blkstofrags(fs, lblkno);
1330		ffs_blkfree_snap(fs, vp, blkno, fs->fs_bsize, inum);
1331		if (wbreak > 0 && (++n % wbreak) == 0) {
1332			UFS_WAPBL_END(mp);
1333			error = UFS_WAPBL_BEGIN(mp);
1334			if (error)
1335				return error;
1336		}
1337	}
1338	UFS_WAPBL_END(mp);
1339	return (0);
1340}
1341
1342/*
1343 * Number of blocks that fit into the journal or zero if not logging.
1344 */
1345static int
1346blocks_in_journal(struct fs *fs)
1347{
1348	off_t bpj;
1349
1350	if ((fs->fs_flags & FS_DOWAPBL) == 0)
1351		return 0;
1352	bpj = 1;
1353	if (fs->fs_journal_version == UFS_WAPBL_VERSION) {
1354		switch (fs->fs_journal_location) {
1355		case UFS_WAPBL_JOURNALLOC_END_PARTITION:
1356			bpj = (off_t)fs->fs_journallocs[UFS_WAPBL_EPART_BLKSZ]*
1357			    fs->fs_journallocs[UFS_WAPBL_EPART_COUNT];
1358			break;
1359		case UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM:
1360			bpj = (off_t)fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ]*
1361			    fs->fs_journallocs[UFS_WAPBL_INFS_COUNT];
1362			break;
1363		}
1364	}
1365	bpj /= fs->fs_bsize;
1366	return (bpj > 0 ? bpj : 1);
1367}
1368#endif /* defined(FFS_NO_SNAPSHOT) */
1369
1370/*
1371 * Decrement extra reference on snapshot when last name is removed.
1372 * It will not be freed until the last open reference goes away.
1373 */
1374void
1375ffs_snapgone(struct vnode *vp)
1376{
1377	struct inode *xp, *ip = VTOI(vp);
1378	struct mount *mp = ip->i_devvp->v_specmountpoint;
1379	struct fs *fs;
1380	struct snap_info *si;
1381	int snaploc;
1382
1383	si = VFSTOUFS(mp)->um_snapinfo;
1384
1385	/*
1386	 * Find snapshot in incore list.
1387	 */
1388	mutex_enter(&si->si_lock);
1389	TAILQ_FOREACH(xp, &si->si_snapshots, i_nextsnap)
1390		if (xp == ip)
1391			break;
1392	mutex_exit(&si->si_lock);
1393	if (xp != NULL)
1394		vrele(ITOV(ip));
1395#ifdef DEBUG
1396	else if (snapdebug)
1397		printf("ffs_snapgone: lost snapshot vnode %llu\n",
1398		    (unsigned long long)ip->i_number);
1399#endif
1400	/*
1401	 * Delete snapshot inode from superblock. Keep list dense.
1402	 */
1403	mutex_enter(&si->si_lock);
1404	fs = ip->i_fs;
1405	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++)
1406		if (fs->fs_snapinum[snaploc] == ip->i_number)
1407			break;
1408	if (snaploc < FSMAXSNAP) {
1409		for (snaploc++; snaploc < FSMAXSNAP; snaploc++) {
1410			if (fs->fs_snapinum[snaploc] == 0)
1411				break;
1412			fs->fs_snapinum[snaploc - 1] = fs->fs_snapinum[snaploc];
1413		}
1414		fs->fs_snapinum[snaploc - 1] = 0;
1415	}
1416	si->si_gen++;
1417	mutex_exit(&si->si_lock);
1418}
1419
1420/*
1421 * Prepare a snapshot file for being removed.
1422 */
1423void
1424ffs_snapremove(struct vnode *vp)
1425{
1426	struct inode *ip = VTOI(vp), *xp;
1427	struct vnode *devvp = ip->i_devvp;
1428	struct fs *fs = ip->i_fs;
1429	struct mount *mp = devvp->v_specmountpoint;
1430	struct buf *ibp;
1431	struct snap_info *si;
1432	struct lwp *l = curlwp;
1433	daddr_t numblks, blkno, dblk;
1434	int error, loc, last;
1435
1436	si = VFSTOUFS(mp)->um_snapinfo;
1437	/*
1438	 * If active, delete from incore list (this snapshot may
1439	 * already have been in the process of being deleted, so
1440	 * would not have been active).
1441	 *
1442	 * Clear copy-on-write flag if last snapshot.
1443	 */
1444	mutex_enter(&si->si_snaplock);
1445	mutex_enter(&si->si_lock);
1446	if (is_active_snapshot(si, ip)) {
1447		TAILQ_REMOVE(&si->si_snapshots, ip, i_nextsnap);
1448		if (TAILQ_FIRST(&si->si_snapshots) != 0) {
1449			/* Roll back the list of preallocated blocks. */
1450			xp = TAILQ_LAST(&si->si_snapshots, inodelst);
1451			si->si_snapblklist = xp->i_snapblklist;
1452			si->si_gen++;
1453			mutex_exit(&si->si_lock);
1454			mutex_exit(&si->si_snaplock);
1455		} else {
1456			si->si_snapblklist = 0;
1457			si->si_gen++;
1458			mutex_exit(&si->si_lock);
1459			mutex_exit(&si->si_snaplock);
1460			fscow_disestablish(mp, ffs_copyonwrite, devvp);
1461		}
1462		if (ip->i_snapblklist != NULL) {
1463			free(ip->i_snapblklist, M_UFSMNT);
1464			ip->i_snapblklist = NULL;
1465		}
1466	} else {
1467		mutex_exit(&si->si_lock);
1468		mutex_exit(&si->si_snaplock);
1469	}
1470	/*
1471	 * Clear all BLK_NOCOPY fields. Pass any block claims to other
1472	 * snapshots that want them (see ffs_snapblkfree below).
1473	 */
1474	for (blkno = 1; blkno < UFS_NDADDR; blkno++) {
1475		dblk = db_get(ip, blkno);
1476		if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1477			db_assign(ip, blkno, 0);
1478		else if ((dblk == blkstofrags(fs, blkno) &&
1479		     ffs_snapblkfree(fs, ip->i_devvp, dblk, fs->fs_bsize,
1480		     ip->i_number))) {
1481			DIP_ADD(ip, blocks, -btodb(fs->fs_bsize));
1482			db_assign(ip, blkno, 0);
1483		}
1484	}
1485	numblks = howmany(ip->i_size, fs->fs_bsize);
1486	for (blkno = UFS_NDADDR; blkno < numblks; blkno += NINDIR(fs)) {
1487		error = ffs_balloc(vp, lblktosize(fs, (off_t)blkno),
1488		    fs->fs_bsize, l->l_cred, B_METAONLY, &ibp);
1489		if (error)
1490			continue;
1491		if (fs->fs_size - blkno > NINDIR(fs))
1492			last = NINDIR(fs);
1493		else
1494			last = fs->fs_size - blkno;
1495		for (loc = 0; loc < last; loc++) {
1496			dblk = idb_get(ip, ibp->b_data, loc);
1497			if (dblk == BLK_NOCOPY || dblk == BLK_SNAP)
1498				idb_assign(ip, ibp->b_data, loc, 0);
1499			else if (dblk == blkstofrags(fs, blkno) &&
1500			    ffs_snapblkfree(fs, ip->i_devvp, dblk,
1501			    fs->fs_bsize, ip->i_number)) {
1502				DIP_ADD(ip, blocks, -btodb(fs->fs_bsize));
1503				idb_assign(ip, ibp->b_data, loc, 0);
1504			}
1505		}
1506		bawrite(ibp);
1507		UFS_WAPBL_END(mp);
1508		error = UFS_WAPBL_BEGIN(mp);
1509		KASSERT(error == 0);
1510	}
1511	/*
1512	 * Clear snapshot flag and drop reference.
1513	 */
1514	ip->i_flags &= ~(SF_SNAPSHOT | SF_SNAPINVAL);
1515	DIP_ASSIGN(ip, flags, ip->i_flags);
1516	ip->i_flag |= IN_CHANGE | IN_UPDATE;
1517#if defined(QUOTA) || defined(QUOTA2)
1518	chkdq(ip, DIP(ip, blocks), l->l_cred, FORCE);
1519	chkiq(ip, 1, l->l_cred, FORCE);
1520#endif
1521}
1522
1523/*
1524 * Notification that a block is being freed. Return zero if the free
1525 * should be allowed to proceed. Return non-zero if the snapshot file
1526 * wants to claim the block. The block will be claimed if it is an
1527 * uncopied part of one of the snapshots. It will be freed if it is
1528 * either a BLK_NOCOPY or has already been copied in all of the snapshots.
1529 * If a fragment is being freed, then all snapshots that care about
1530 * it must make a copy since a snapshot file can only claim full sized
1531 * blocks. Note that if more than one snapshot file maps the block,
1532 * we can pick one at random to claim it. Since none of the snapshots
1533 * can change, we are assurred that they will all see the same unmodified
1534 * image. When deleting a snapshot file (see ffs_snapremove above), we
1535 * must push any of these claimed blocks to one of the other snapshots
1536 * that maps it. These claimed blocks are easily identified as they will
1537 * have a block number equal to their logical block number within the
1538 * snapshot. A copied block can never have this property because they
1539 * must always have been allocated from a BLK_NOCOPY location.
1540 */
1541int
1542ffs_snapblkfree(struct fs *fs, struct vnode *devvp, daddr_t bno,
1543    long size, ino_t inum)
1544{
1545	struct mount *mp = devvp->v_specmountpoint;
1546	struct buf *ibp;
1547	struct inode *ip;
1548	struct vnode *vp = NULL;
1549	struct snap_info *si;
1550	void *saved_data = NULL;
1551	daddr_t lbn;
1552	daddr_t blkno;
1553	uint32_t gen;
1554	int indiroff = 0, error = 0, claimedblk = 0;
1555
1556	si = VFSTOUFS(mp)->um_snapinfo;
1557	lbn = fragstoblks(fs, bno);
1558	mutex_enter(&si->si_snaplock);
1559	mutex_enter(&si->si_lock);
1560	si->si_owner = curlwp;
1561
1562retry:
1563	gen = si->si_gen;
1564	TAILQ_FOREACH(ip, &si->si_snapshots, i_nextsnap) {
1565		vp = ITOV(ip);
1566		/*
1567		 * Lookup block being written.
1568		 */
1569		if (lbn < UFS_NDADDR) {
1570			blkno = db_get(ip, lbn);
1571		} else {
1572			mutex_exit(&si->si_lock);
1573			error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn),
1574			    fs->fs_bsize, FSCRED, B_METAONLY, &ibp);
1575			if (error) {
1576				mutex_enter(&si->si_lock);
1577				break;
1578			}
1579			indiroff = (lbn - UFS_NDADDR) % NINDIR(fs);
1580			blkno = idb_get(ip, ibp->b_data, indiroff);
1581			mutex_enter(&si->si_lock);
1582			if (gen != si->si_gen) {
1583				brelse(ibp, 0);
1584				goto retry;
1585			}
1586		}
1587		/*
1588		 * Check to see if block needs to be copied.
1589		 */
1590		if (blkno == 0) {
1591			/*
1592			 * A block that we map is being freed. If it has not
1593			 * been claimed yet, we will claim or copy it (below).
1594			 */
1595			claimedblk = 1;
1596		} else if (blkno == BLK_SNAP) {
1597			/*
1598			 * No previous snapshot claimed the block,
1599			 * so it will be freed and become a BLK_NOCOPY
1600			 * (don't care) for us.
1601			 */
1602			if (claimedblk)
1603				panic("snapblkfree: inconsistent block type");
1604			if (lbn < UFS_NDADDR) {
1605				db_assign(ip, lbn, BLK_NOCOPY);
1606				ip->i_flag |= IN_CHANGE | IN_UPDATE;
1607			} else {
1608				idb_assign(ip, ibp->b_data, indiroff,
1609				    BLK_NOCOPY);
1610				mutex_exit(&si->si_lock);
1611				if (ip->i_nlink > 0)
1612					bwrite(ibp);
1613				else
1614					bdwrite(ibp);
1615				mutex_enter(&si->si_lock);
1616				if (gen != si->si_gen)
1617					goto retry;
1618			}
1619			continue;
1620		} else /* BLK_NOCOPY or default */ {
1621			/*
1622			 * If the snapshot has already copied the block
1623			 * (default), or does not care about the block,
1624			 * it is not needed.
1625			 */
1626			if (lbn >= UFS_NDADDR)
1627				brelse(ibp, 0);
1628			continue;
1629		}
1630		/*
1631		 * If this is a full size block, we will just grab it
1632		 * and assign it to the snapshot inode. Otherwise we
1633		 * will proceed to copy it. See explanation for this
1634		 * routine as to why only a single snapshot needs to
1635		 * claim this block.
1636		 */
1637		if (size == fs->fs_bsize) {
1638#ifdef DEBUG
1639			if (snapdebug)
1640				printf("%s %llu lbn %" PRId64
1641				    "from inum %llu\n",
1642				    "Grabonremove: snapino",
1643				    (unsigned long long)ip->i_number,
1644				    lbn, (unsigned long long)inum);
1645#endif
1646			mutex_exit(&si->si_lock);
1647			if (lbn < UFS_NDADDR) {
1648				db_assign(ip, lbn, bno);
1649			} else {
1650				idb_assign(ip, ibp->b_data, indiroff, bno);
1651				if (ip->i_nlink > 0)
1652					bwrite(ibp);
1653				else
1654					bdwrite(ibp);
1655			}
1656			DIP_ADD(ip, blocks, btodb(size));
1657			ip->i_flag |= IN_CHANGE | IN_UPDATE;
1658			if (ip->i_nlink > 0 && mp->mnt_wapbl)
1659				error = syncsnap(vp);
1660			else
1661				error = 0;
1662			mutex_enter(&si->si_lock);
1663			si->si_owner = NULL;
1664			mutex_exit(&si->si_lock);
1665			mutex_exit(&si->si_snaplock);
1666			return (error == 0);
1667		}
1668		if (lbn >= UFS_NDADDR)
1669			brelse(ibp, 0);
1670#ifdef DEBUG
1671		if (snapdebug)
1672			printf("%s%llu lbn %" PRId64 " %s %llu size %ld\n",
1673			    "Copyonremove: snapino ",
1674			    (unsigned long long)ip->i_number,
1675			    lbn, "for inum", (unsigned long long)inum, size);
1676#endif
1677		/*
1678		 * If we have already read the old block contents, then
1679		 * simply copy them to the new block. Note that we need
1680		 * to synchronously write snapshots that have not been
1681		 * unlinked, and hence will be visible after a crash,
1682		 * to ensure their integrity.
1683		 */
1684		mutex_exit(&si->si_lock);
1685		if (saved_data == NULL) {
1686			saved_data = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
1687			error = rwfsblk(vp, B_READ, saved_data, lbn);
1688			if (error) {
1689				free(saved_data, M_UFSMNT);
1690				saved_data = NULL;
1691				mutex_enter(&si->si_lock);
1692				break;
1693			}
1694		}
1695		error = wrsnapblk(vp, saved_data, lbn);
1696		if (error == 0 && ip->i_nlink > 0 && mp->mnt_wapbl)
1697			error = syncsnap(vp);
1698		mutex_enter(&si->si_lock);
1699		if (error)
1700			break;
1701		if (gen != si->si_gen)
1702			goto retry;
1703	}
1704	si->si_owner = NULL;
1705	mutex_exit(&si->si_lock);
1706	mutex_exit(&si->si_snaplock);
1707	if (saved_data)
1708		free(saved_data, M_UFSMNT);
1709	/*
1710	 * If we have been unable to allocate a block in which to do
1711	 * the copy, then return non-zero so that the fragment will
1712	 * not be freed. Although space will be lost, the snapshot
1713	 * will stay consistent.
1714	 */
1715	return (error);
1716}
1717
1718/*
1719 * Associate snapshot files when mounting.
1720 */
1721void
1722ffs_snapshot_mount(struct mount *mp)
1723{
1724	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
1725	struct fs *fs = VFSTOUFS(mp)->um_fs;
1726	struct lwp *l = curlwp;
1727	struct vnode *vp;
1728	struct inode *ip, *xp;
1729	struct snap_info *si;
1730	daddr_t snaplistsize, *snapblklist;
1731	int i, error, ns, snaploc, loc;
1732
1733	/*
1734	 * No persistent snapshots on apple ufs file systems.
1735	 */
1736	if (UFS_MPISAPPLEUFS(VFSTOUFS(mp)))
1737		return;
1738
1739	si = VFSTOUFS(mp)->um_snapinfo;
1740	ns = UFS_FSNEEDSWAP(fs);
1741	/*
1742	 * XXX The following needs to be set before ffs_truncate or
1743	 * VOP_READ can be called.
1744	 */
1745	mp->mnt_stat.f_iosize = fs->fs_bsize;
1746	/*
1747	 * Process each snapshot listed in the superblock.
1748	 */
1749	vp = NULL;
1750	mutex_enter(&si->si_lock);
1751	for (snaploc = 0; snaploc < FSMAXSNAP; snaploc++) {
1752		if (fs->fs_snapinum[snaploc] == 0)
1753			break;
1754		if ((error = VFS_VGET(mp, fs->fs_snapinum[snaploc],
1755		    &vp)) != 0) {
1756			printf("ffs_snapshot_mount: vget failed %d\n", error);
1757			continue;
1758		}
1759		ip = VTOI(vp);
1760		if ((ip->i_flags & (SF_SNAPSHOT | SF_SNAPINVAL)) !=
1761		    SF_SNAPSHOT) {
1762			printf("ffs_snapshot_mount: non-snapshot inode %d\n",
1763			    fs->fs_snapinum[snaploc]);
1764			vput(vp);
1765			vp = NULL;
1766			for (loc = snaploc + 1; loc < FSMAXSNAP; loc++) {
1767				if (fs->fs_snapinum[loc] == 0)
1768					break;
1769				fs->fs_snapinum[loc - 1] = fs->fs_snapinum[loc];
1770			}
1771			fs->fs_snapinum[loc - 1] = 0;
1772			snaploc--;
1773			continue;
1774		}
1775
1776		/*
1777		 * Read the block hints list. Use an empty list on
1778		 * read errors.
1779		 */
1780		error = vn_rdwr(UIO_READ, vp,
1781		    (void *)&snaplistsize, sizeof(snaplistsize),
1782		    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag)),
1783		    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT|IO_ALTSEMANTICS,
1784		    l->l_cred, NULL, NULL);
1785		if (error) {
1786			printf("ffs_snapshot_mount: read_1 failed %d\n", error);
1787			snaplistsize = 1;
1788		} else
1789			snaplistsize = ufs_rw64(snaplistsize, ns);
1790		snapblklist = malloc(
1791		    snaplistsize * sizeof(daddr_t), M_UFSMNT, M_WAITOK);
1792		if (error)
1793			snapblklist[0] = 1;
1794		else {
1795			error = vn_rdwr(UIO_READ, vp, (void *)snapblklist,
1796			    snaplistsize * sizeof(daddr_t),
1797			    lblktosize(fs, howmany(fs->fs_size, fs->fs_frag)),
1798			    UIO_SYSSPACE, IO_NODELOCKED|IO_UNIT|IO_ALTSEMANTICS,
1799			    l->l_cred, NULL, NULL);
1800			for (i = 0; i < snaplistsize; i++)
1801				snapblklist[i] = ufs_rw64(snapblklist[i], ns);
1802			if (error) {
1803				printf("ffs_snapshot_mount: read_2 failed %d\n",
1804				    error);
1805				snapblklist[0] = 1;
1806			}
1807		}
1808		ip->i_snapblklist = &snapblklist[0];
1809
1810		/*
1811		 * Link it onto the active snapshot list.
1812		 */
1813		if (is_active_snapshot(si, ip))
1814			panic("ffs_snapshot_mount: %"PRIu64" already on list",
1815			    ip->i_number);
1816		else
1817			TAILQ_INSERT_TAIL(&si->si_snapshots, ip, i_nextsnap);
1818		vp->v_vflag |= VV_SYSTEM;
1819		VOP_UNLOCK(vp);
1820	}
1821	/*
1822	 * No usable snapshots found.
1823	 */
1824	if (vp == NULL) {
1825		mutex_exit(&si->si_lock);
1826		return;
1827	}
1828	/*
1829	 * Attach the block hints list. We always want to
1830	 * use the list from the newest snapshot.
1831	*/
1832	xp = TAILQ_LAST(&si->si_snapshots, inodelst);
1833	si->si_snapblklist = xp->i_snapblklist;
1834	fscow_establish(mp, ffs_copyonwrite, devvp);
1835	si->si_gen++;
1836	mutex_exit(&si->si_lock);
1837}
1838
1839/*
1840 * Disassociate snapshot files when unmounting.
1841 */
1842void
1843ffs_snapshot_unmount(struct mount *mp)
1844{
1845	struct vnode *devvp = VFSTOUFS(mp)->um_devvp;
1846	struct inode *xp;
1847	struct vnode *vp = NULL;
1848	struct snap_info *si;
1849
1850	si = VFSTOUFS(mp)->um_snapinfo;
1851	mutex_enter(&si->si_lock);
1852	while ((xp = TAILQ_FIRST(&si->si_snapshots)) != 0) {
1853		vp = ITOV(xp);
1854		TAILQ_REMOVE(&si->si_snapshots, xp, i_nextsnap);
1855		if (xp->i_snapblklist == si->si_snapblklist)
1856			si->si_snapblklist = NULL;
1857		free(xp->i_snapblklist, M_UFSMNT);
1858		if (xp->i_nlink > 0) {
1859			si->si_gen++;
1860			mutex_exit(&si->si_lock);
1861			vrele(vp);
1862			mutex_enter(&si->si_lock);
1863		}
1864	}
1865	si->si_gen++;
1866	mutex_exit(&si->si_lock);
1867	if (vp)
1868		fscow_disestablish(mp, ffs_copyonwrite, devvp);
1869}
1870
1871/*
1872 * Check for need to copy block that is about to be written,
1873 * copying the block if necessary.
1874 */
1875static int
1876ffs_copyonwrite(void *v, struct buf *bp, bool data_valid)
1877{
1878	struct fs *fs;
1879	struct inode *ip;
1880	struct vnode *devvp = v, *vp = NULL;
1881	struct mount *mp = devvp->v_specmountpoint;
1882	struct snap_info *si;
1883	void *saved_data = NULL;
1884	daddr_t lbn, blkno, *snapblklist;
1885	uint32_t gen;
1886	int lower, upper, mid, snapshot_locked = 0, error = 0;
1887
1888	/*
1889	 * Check for valid snapshots.
1890	 */
1891	si = VFSTOUFS(mp)->um_snapinfo;
1892	mutex_enter(&si->si_lock);
1893	ip = TAILQ_FIRST(&si->si_snapshots);
1894	if (ip == NULL) {
1895		mutex_exit(&si->si_lock);
1896		return 0;
1897	}
1898	/*
1899	 * First check to see if it is after the file system,
1900	 * in the journal or in the preallocated list.
1901	 * By doing these checks we avoid several potential deadlocks.
1902	 */
1903	fs = ip->i_fs;
1904	lbn = fragstoblks(fs, dbtofsb(fs, bp->b_blkno));
1905	if (bp->b_blkno >= fsbtodb(fs, fs->fs_size)) {
1906		mutex_exit(&si->si_lock);
1907		return 0;
1908	}
1909	if ((fs->fs_flags & FS_DOWAPBL) &&
1910	    fs->fs_journal_location == UFS_WAPBL_JOURNALLOC_IN_FILESYSTEM) {
1911		off_t blk_off, log_start, log_end;
1912
1913		log_start = (off_t)fs->fs_journallocs[UFS_WAPBL_INFS_ADDR] *
1914		    fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ];
1915		log_end = log_start + fs->fs_journallocs[UFS_WAPBL_INFS_COUNT] *
1916		    fs->fs_journallocs[UFS_WAPBL_INFS_BLKSZ];
1917		blk_off = dbtob(bp->b_blkno);
1918		if (blk_off >= log_start && blk_off < log_end) {
1919			mutex_exit(&si->si_lock);
1920			return 0;
1921		}
1922	}
1923	snapblklist = si->si_snapblklist;
1924	upper = (snapblklist != NULL ? snapblklist[0] - 1 : 0);
1925	lower = 1;
1926	while (lower <= upper) {
1927		mid = (lower + upper) / 2;
1928		if (snapblklist[mid] == lbn)
1929			break;
1930		if (snapblklist[mid] < lbn)
1931			lower = mid + 1;
1932		else
1933			upper = mid - 1;
1934	}
1935	if (lower <= upper) {
1936		mutex_exit(&si->si_lock);
1937		return 0;
1938	}
1939	/*
1940	 * Not in the precomputed list, so check the snapshots.
1941	 */
1942	 if (si->si_owner != curlwp) {
1943		if (!mutex_tryenter(&si->si_snaplock)) {
1944			mutex_exit(&si->si_lock);
1945			mutex_enter(&si->si_snaplock);
1946			mutex_enter(&si->si_lock);
1947		}
1948		si->si_owner = curlwp;
1949		snapshot_locked = 1;
1950	 }
1951	 if (data_valid && bp->b_bcount == fs->fs_bsize)
1952		saved_data = bp->b_data;
1953retry:
1954	gen = si->si_gen;
1955	TAILQ_FOREACH(ip, &si->si_snapshots, i_nextsnap) {
1956		vp = ITOV(ip);
1957		/*
1958		 * We ensure that everything of our own that needs to be
1959		 * copied will be done at the time that ffs_snapshot is
1960		 * called. Thus we can skip the check here which can
1961		 * deadlock in doing the lookup in ffs_balloc.
1962		 */
1963		if (bp->b_vp == vp)
1964			continue;
1965		/*
1966		 * Check to see if block needs to be copied.
1967		 */
1968		if (lbn < UFS_NDADDR) {
1969			blkno = db_get(ip, lbn);
1970		} else {
1971			mutex_exit(&si->si_lock);
1972			blkno = 0; /* XXX: GCC */
1973			if ((error = snapblkaddr(vp, lbn, &blkno)) != 0) {
1974				mutex_enter(&si->si_lock);
1975				break;
1976			}
1977			mutex_enter(&si->si_lock);
1978			if (gen != si->si_gen)
1979				goto retry;
1980		}
1981#ifdef DIAGNOSTIC
1982		if (blkno == BLK_SNAP && bp->b_lblkno >= 0)
1983			panic("ffs_copyonwrite: bad copy block");
1984#endif
1985		if (blkno != 0)
1986			continue;
1987
1988		if (curlwp == uvm.pagedaemon_lwp) {
1989			error = ENOMEM;
1990			break;
1991		}
1992		/* Only one level of recursion allowed. */
1993		KASSERT(snapshot_locked);
1994		/*
1995		 * Allocate the block into which to do the copy. Since
1996		 * multiple processes may all try to copy the same block,
1997		 * we have to recheck our need to do a copy if we sleep
1998		 * waiting for the lock.
1999		 *
2000		 * Because all snapshots on a filesystem share a single
2001		 * lock, we ensure that we will never be in competition
2002		 * with another process to allocate a block.
2003		 */
2004#ifdef DEBUG
2005		if (snapdebug) {
2006			printf("Copyonwrite: snapino %llu lbn %" PRId64 " for ",
2007			    (unsigned long long)ip->i_number, lbn);
2008			if (bp->b_vp == devvp)
2009				printf("fs metadata");
2010			else
2011				printf("inum %llu", (unsigned long long)
2012				    VTOI(bp->b_vp)->i_number);
2013			printf(" lblkno %" PRId64 "\n", bp->b_lblkno);
2014		}
2015#endif
2016		/*
2017		 * If we have already read the old block contents, then
2018		 * simply copy them to the new block. Note that we need
2019		 * to synchronously write snapshots that have not been
2020		 * unlinked, and hence will be visible after a crash,
2021		 * to ensure their integrity.
2022		 */
2023		mutex_exit(&si->si_lock);
2024		if (saved_data == NULL) {
2025			saved_data = malloc(fs->fs_bsize, M_UFSMNT, M_WAITOK);
2026			error = rwfsblk(vp, B_READ, saved_data, lbn);
2027			if (error) {
2028				free(saved_data, M_UFSMNT);
2029				saved_data = NULL;
2030				mutex_enter(&si->si_lock);
2031				break;
2032			}
2033		}
2034		error = wrsnapblk(vp, saved_data, lbn);
2035		if (error == 0 && ip->i_nlink > 0 && mp->mnt_wapbl)
2036			error = syncsnap(vp);
2037		mutex_enter(&si->si_lock);
2038		if (error)
2039			break;
2040		if (gen != si->si_gen)
2041			goto retry;
2042	}
2043	/*
2044	 * Note that we need to synchronously write snapshots that
2045	 * have not been unlinked, and hence will be visible after
2046	 * a crash, to ensure their integrity.
2047	 */
2048	if (snapshot_locked) {
2049		si->si_owner = NULL;
2050		mutex_exit(&si->si_lock);
2051		mutex_exit(&si->si_snaplock);
2052	} else
2053		mutex_exit(&si->si_lock);
2054	if (saved_data && saved_data != bp->b_data)
2055		free(saved_data, M_UFSMNT);
2056	return error;
2057}
2058
2059/*
2060 * Read from a snapshot.
2061 */
2062int
2063ffs_snapshot_read(struct vnode *vp, struct uio *uio, int ioflag)
2064{
2065	struct inode *ip = VTOI(vp);
2066	struct fs *fs = ip->i_fs;
2067	struct snap_info *si = VFSTOUFS(vp->v_mount)->um_snapinfo;
2068	struct buf *bp;
2069	daddr_t lbn, nextlbn;
2070	off_t fsbytes, bytesinfile;
2071	long size, xfersize, blkoffset;
2072	int error;
2073
2074	fstrans_start(vp->v_mount, FSTRANS_SHARED);
2075	mutex_enter(&si->si_snaplock);
2076
2077	if (ioflag & IO_ALTSEMANTICS)
2078		fsbytes = ip->i_size;
2079	else
2080		fsbytes = lfragtosize(fs, fs->fs_size);
2081	for (error = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
2082		bytesinfile = fsbytes - uio->uio_offset;
2083		if (bytesinfile <= 0)
2084			break;
2085		lbn = lblkno(fs, uio->uio_offset);
2086		nextlbn = lbn + 1;
2087		size = fs->fs_bsize;
2088		blkoffset = blkoff(fs, uio->uio_offset);
2089		xfersize = MIN(MIN(fs->fs_bsize - blkoffset, uio->uio_resid),
2090		    bytesinfile);
2091
2092		if (lblktosize(fs, nextlbn + 1) >= fsbytes) {
2093			if (lblktosize(fs, lbn) + size > fsbytes)
2094				size = fragroundup(fs,
2095				    fsbytes - lblktosize(fs, lbn));
2096			error = bread(vp, lbn, size, NOCRED, 0, &bp);
2097		} else {
2098			int nextsize = fs->fs_bsize;
2099			error = breadn(vp, lbn,
2100			    size, &nextlbn, &nextsize, 1, NOCRED, 0, &bp);
2101		}
2102		if (error)
2103			break;
2104
2105		/*
2106		 * We should only get non-zero b_resid when an I/O error
2107		 * has occurred, which should cause us to break above.
2108		 * However, if the short read did not cause an error,
2109		 * then we want to ensure that we do not uiomove bad
2110		 * or uninitialized data.
2111		 */
2112		size -= bp->b_resid;
2113		if (size < blkoffset + xfersize) {
2114			xfersize = size - blkoffset;
2115			if (xfersize <= 0)
2116				break;
2117		}
2118		error = uiomove((char *)bp->b_data + blkoffset, xfersize, uio);
2119		if (error)
2120			break;
2121		brelse(bp, BC_AGE);
2122	}
2123	if (bp != NULL)
2124		brelse(bp, BC_AGE);
2125
2126	mutex_exit(&si->si_snaplock);
2127	fstrans_done(vp->v_mount);
2128	return error;
2129}
2130
2131/*
2132 * Lookup a snapshots data block address.
2133 * Simpler than UFS_BALLOC() as we know all metadata is already allocated
2134 * and safe even for the pagedaemon where we cannot bread().
2135 */
2136static int
2137snapblkaddr(struct vnode *vp, daddr_t lbn, daddr_t *res)
2138{
2139	struct indir indirs[UFS_NIADDR + 2];
2140	struct inode *ip = VTOI(vp);
2141	struct fs *fs = ip->i_fs;
2142	struct buf *bp;
2143	int error, num;
2144
2145	KASSERT(lbn >= 0);
2146
2147	if (lbn < UFS_NDADDR) {
2148		*res = db_get(ip, lbn);
2149		return 0;
2150	}
2151	if ((error = ufs_getlbns(vp, lbn, indirs, &num)) != 0)
2152		return error;
2153	if (curlwp == uvm.pagedaemon_lwp) {
2154		mutex_enter(&bufcache_lock);
2155		bp = incore(vp, indirs[num-1].in_lbn);
2156		if (bp && (bp->b_oflags & (BO_DONE | BO_DELWRI))) {
2157			*res = idb_get(ip, bp->b_data, indirs[num-1].in_off);
2158			error = 0;
2159		} else
2160			error = ENOMEM;
2161		mutex_exit(&bufcache_lock);
2162		return error;
2163	}
2164	error = bread(vp, indirs[num-1].in_lbn, fs->fs_bsize, NOCRED, 0, &bp);
2165	if (error == 0) {
2166		*res = idb_get(ip, bp->b_data, indirs[num-1].in_off);
2167		brelse(bp, 0);
2168	}
2169
2170	return error;
2171}
2172
2173/*
2174 * Read or write the specified block of the filesystem vp resides on
2175 * from or to the disk bypassing the buffer cache.
2176 */
2177static int
2178rwfsblk(struct vnode *vp, int flags, void *data, daddr_t lbn)
2179{
2180	int error;
2181	struct inode *ip = VTOI(vp);
2182	struct fs *fs = ip->i_fs;
2183	struct buf *nbp;
2184
2185	nbp = getiobuf(NULL, true);
2186	nbp->b_flags = flags;
2187	nbp->b_bcount = nbp->b_bufsize = fs->fs_bsize;
2188	nbp->b_error = 0;
2189	nbp->b_data = data;
2190	nbp->b_blkno = nbp->b_rawblkno = fsbtodb(fs, blkstofrags(fs, lbn));
2191	nbp->b_proc = NULL;
2192	nbp->b_dev = ip->i_devvp->v_rdev;
2193	SET(nbp->b_cflags, BC_BUSY);	/* mark buffer busy */
2194
2195	bdev_strategy(nbp);
2196
2197	error = biowait(nbp);
2198
2199	putiobuf(nbp);
2200
2201	return error;
2202}
2203
2204/*
2205 * Write all dirty buffers to disk and invalidate them.
2206 */
2207static int
2208syncsnap(struct vnode *vp)
2209{
2210	int error;
2211	buf_t *bp;
2212	struct fs *fs = VTOI(vp)->i_fs;
2213
2214	mutex_enter(&bufcache_lock);
2215	while ((bp = LIST_FIRST(&vp->v_dirtyblkhd))) {
2216		error = bbusy(bp, false, 0, NULL);
2217		if (error == EPASSTHROUGH)
2218			continue;
2219		else if (error != 0) {
2220			mutex_exit(&bufcache_lock);
2221			return error;
2222		}
2223		KASSERT(bp->b_bcount == fs->fs_bsize);
2224		mutex_exit(&bufcache_lock);
2225		error = rwfsblk(vp, B_WRITE, bp->b_data,
2226		    fragstoblks(fs, dbtofsb(fs, bp->b_blkno)));
2227		brelse(bp, BC_INVAL | BC_VFLUSH);
2228		if (error)
2229			return error;
2230		mutex_enter(&bufcache_lock);
2231	}
2232	mutex_exit(&bufcache_lock);
2233
2234	return 0;
2235}
2236
2237/*
2238 * Write the specified block to a snapshot.
2239 */
2240static int
2241wrsnapblk(struct vnode *vp, void *data, daddr_t lbn)
2242{
2243	struct inode *ip = VTOI(vp);
2244	struct fs *fs = ip->i_fs;
2245	struct buf *bp;
2246	int error;
2247
2248	error = ffs_balloc(vp, lblktosize(fs, (off_t)lbn), fs->fs_bsize,
2249	    FSCRED, (ip->i_nlink > 0 ? B_SYNC : 0), &bp);
2250	if (error)
2251		return error;
2252	memcpy(bp->b_data, data, fs->fs_bsize);
2253	if (ip->i_nlink > 0)
2254		error = bwrite(bp);
2255	else
2256		bawrite(bp);
2257
2258	return error;
2259}
2260
2261/*
2262 * Check if this inode is present on the active snapshot list.
2263 * Must be called with snapinfo locked.
2264 */
2265static inline bool
2266is_active_snapshot(struct snap_info *si, struct inode *ip)
2267{
2268	struct inode *xp;
2269
2270	KASSERT(mutex_owned(&si->si_lock));
2271
2272	TAILQ_FOREACH(xp, &si->si_snapshots, i_nextsnap)
2273		if (xp == ip)
2274			return true;
2275	return false;
2276}
2277
2278/*
2279 * Get/Put direct block from inode or buffer containing disk addresses. Take
2280 * care for fs type (UFS1/UFS2) and byte swapping. These functions should go
2281 * into a global include.
2282 */
2283static inline daddr_t
2284db_get(struct inode *ip, int loc)
2285{
2286	if (ip->i_ump->um_fstype == UFS1)
2287		return ufs_rw32(ip->i_ffs1_db[loc], UFS_IPNEEDSWAP(ip));
2288	else
2289		return ufs_rw64(ip->i_ffs2_db[loc], UFS_IPNEEDSWAP(ip));
2290}
2291
2292static inline void
2293db_assign(struct inode *ip, int loc, daddr_t val)
2294{
2295	if (ip->i_ump->um_fstype == UFS1)
2296		ip->i_ffs1_db[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
2297	else
2298		ip->i_ffs2_db[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
2299}
2300
2301static inline daddr_t
2302ib_get(struct inode *ip, int loc)
2303{
2304	if (ip->i_ump->um_fstype == UFS1)
2305		return ufs_rw32(ip->i_ffs1_ib[loc], UFS_IPNEEDSWAP(ip));
2306	else
2307		return ufs_rw64(ip->i_ffs2_ib[loc], UFS_IPNEEDSWAP(ip));
2308}
2309
2310static inline void
2311ib_assign(struct inode *ip, int loc, daddr_t val)
2312{
2313	if (ip->i_ump->um_fstype == UFS1)
2314		ip->i_ffs1_ib[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
2315	else
2316		ip->i_ffs2_ib[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
2317}
2318
2319static inline daddr_t
2320idb_get(struct inode *ip, void *bf, int loc)
2321{
2322	if (ip->i_ump->um_fstype == UFS1)
2323		return ufs_rw32(((int32_t *)(bf))[loc], UFS_IPNEEDSWAP(ip));
2324	else
2325		return ufs_rw64(((int64_t *)(bf))[loc], UFS_IPNEEDSWAP(ip));
2326}
2327
2328static inline void
2329idb_assign(struct inode *ip, void *bf, int loc, daddr_t val)
2330{
2331	if (ip->i_ump->um_fstype == UFS1)
2332		((int32_t *)(bf))[loc] = ufs_rw32(val, UFS_IPNEEDSWAP(ip));
2333	else
2334		((int64_t *)(bf))[loc] = ufs_rw64(val, UFS_IPNEEDSWAP(ip));
2335}
2336