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