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