]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - sys/ufs/ffs/ffs_softdep.c
MFC r320876:
[FreeBSD/stable/9.git] / sys / ufs / ffs / ffs_softdep.c
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *      Marshall Kirk McKusick          http://www.mckusick.com/softdep/
14  *      1614 Oxford Street              mckusick@mckusick.com
15  *      Berkeley, CA 94709-1608         +1-510-843-9542
16  *      USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *      from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
40  */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/stat.h>
73 #include <sys/sysctl.h>
74 #include <sys/syslog.h>
75 #include <sys/vnode.h>
76 #include <sys/conf.h>
77
78 #include <ufs/ufs/dir.h>
79 #include <ufs/ufs/extattr.h>
80 #include <ufs/ufs/quota.h>
81 #include <ufs/ufs/inode.h>
82 #include <ufs/ufs/ufsmount.h>
83 #include <ufs/ffs/fs.h>
84 #include <ufs/ffs/softdep.h>
85 #include <ufs/ffs/ffs_extern.h>
86 #include <ufs/ufs/ufs_extern.h>
87
88 #include <vm/vm.h>
89 #include <vm/vm_extern.h>
90 #include <vm/vm_object.h>
91
92 #include <geom/geom.h>
93
94 #include <ddb/ddb.h>
95
96 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
97
98 #ifndef SOFTUPDATES
99
100 int
101 softdep_flushfiles(oldmnt, flags, td)
102         struct mount *oldmnt;
103         int flags;
104         struct thread *td;
105 {
106
107         panic("softdep_flushfiles called");
108 }
109
110 int
111 softdep_mount(devvp, mp, fs, cred)
112         struct vnode *devvp;
113         struct mount *mp;
114         struct fs *fs;
115         struct ucred *cred;
116 {
117
118         return (0);
119 }
120
121 void
122 softdep_initialize()
123 {
124
125         return;
126 }
127
128 void
129 softdep_uninitialize()
130 {
131
132         return;
133 }
134
135 void
136 softdep_unmount(mp)
137         struct mount *mp;
138 {
139
140 }
141
142 void
143 softdep_setup_sbupdate(ump, fs, bp)
144         struct ufsmount *ump;
145         struct fs *fs;
146         struct buf *bp;
147 {
148 }
149
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152         struct buf *bp;
153         struct inode *ip;
154         ino_t newinum;
155         int mode;
156 {
157
158         panic("softdep_setup_inomapdep called");
159 }
160
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163         struct buf *bp;
164         struct mount *mp;
165         ufs2_daddr_t newblkno;
166         int frags;
167         int oldfrags;
168 {
169
170         panic("softdep_setup_blkmapdep called");
171 }
172
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175         struct inode *ip;
176         ufs_lbn_t lbn;
177         ufs2_daddr_t newblkno;
178         ufs2_daddr_t oldblkno;
179         long newsize;
180         long oldsize;
181         struct buf *bp;
182 {
183         
184         panic("softdep_setup_allocdirect called");
185 }
186
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189         struct inode *ip;
190         ufs_lbn_t lbn;
191         ufs2_daddr_t newblkno;
192         ufs2_daddr_t oldblkno;
193         long newsize;
194         long oldsize;
195         struct buf *bp;
196 {
197         
198         panic("softdep_setup_allocext called");
199 }
200
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203         struct inode *ip;
204         ufs_lbn_t lbn;
205         struct buf *bp;
206         int ptrno;
207         ufs2_daddr_t newblkno;
208         ufs2_daddr_t oldblkno;
209         struct buf *nbp;
210 {
211
212         panic("softdep_setup_allocindir_page called");
213 }
214
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217         struct buf *nbp;
218         struct inode *ip;
219         struct buf *bp;
220         int ptrno;
221         ufs2_daddr_t newblkno;
222 {
223
224         panic("softdep_setup_allocindir_meta called");
225 }
226
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229         struct inode *ip;
230         struct ucred *cred;
231         off_t length;
232         int flags;
233 {
234         
235         panic("softdep_journal_freeblocks called");
236 }
237
238 void
239 softdep_journal_fsync(ip)
240         struct inode *ip;
241 {
242
243         panic("softdep_journal_fsync called");
244 }
245
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248         struct inode *ip;
249         off_t length;
250         int flags;
251 {
252         
253         panic("softdep_setup_freeblocks called");
254 }
255
256 void
257 softdep_freefile(pvp, ino, mode)
258                 struct vnode *pvp;
259                 ino_t ino;
260                 int mode;
261 {
262
263         panic("softdep_freefile called");
264 }
265
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268         struct buf *bp;
269         struct inode *dp;
270         off_t diroffset;
271         ino_t newinum;
272         struct buf *newdirbp;
273         int isnewblk;
274 {
275
276         panic("softdep_setup_directory_add called");
277 }
278
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281         struct buf *bp;
282         struct inode *dp;
283         caddr_t base;
284         caddr_t oldloc;
285         caddr_t newloc;
286         int entrysize;
287 {
288
289         panic("softdep_change_directoryentry_offset called");
290 }
291
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294         struct buf *bp;
295         struct inode *dp;
296         struct inode *ip;
297         int isrmdir;
298 {
299         
300         panic("softdep_setup_remove called");
301 }
302
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305         struct buf *bp;
306         struct inode *dp;
307         struct inode *ip;
308         ino_t newinum;
309         int isrmdir;
310 {
311
312         panic("softdep_setup_directory_change called");
313 }
314
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317         struct mount *mp;
318         struct buf *bp;
319         ufs2_daddr_t blkno;
320         int frags;
321         struct workhead *wkhd;
322 {
323
324         panic("%s called", __FUNCTION__);
325 }
326
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329         struct mount *mp;
330         struct buf *bp;
331         ino_t ino;
332         struct workhead *wkhd;
333 {
334
335         panic("%s called", __FUNCTION__);
336 }
337
338 void
339 softdep_setup_unlink(dp, ip)
340         struct inode *dp;
341         struct inode *ip;
342 {
343
344         panic("%s called", __FUNCTION__);
345 }
346
347 void
348 softdep_setup_link(dp, ip)
349         struct inode *dp;
350         struct inode *ip;
351 {
352
353         panic("%s called", __FUNCTION__);
354 }
355
356 void
357 softdep_revert_link(dp, ip)
358         struct inode *dp;
359         struct inode *ip;
360 {
361
362         panic("%s called", __FUNCTION__);
363 }
364
365 void
366 softdep_setup_rmdir(dp, ip)
367         struct inode *dp;
368         struct inode *ip;
369 {
370
371         panic("%s called", __FUNCTION__);
372 }
373
374 void
375 softdep_revert_rmdir(dp, ip)
376         struct inode *dp;
377         struct inode *ip;
378 {
379
380         panic("%s called", __FUNCTION__);
381 }
382
383 void
384 softdep_setup_create(dp, ip)
385         struct inode *dp;
386         struct inode *ip;
387 {
388
389         panic("%s called", __FUNCTION__);
390 }
391
392 void
393 softdep_revert_create(dp, ip)
394         struct inode *dp;
395         struct inode *ip;
396 {
397
398         panic("%s called", __FUNCTION__);
399 }
400
401 void
402 softdep_setup_mkdir(dp, ip)
403         struct inode *dp;
404         struct inode *ip;
405 {
406
407         panic("%s called", __FUNCTION__);
408 }
409
410 void
411 softdep_revert_mkdir(dp, ip)
412         struct inode *dp;
413         struct inode *ip;
414 {
415
416         panic("%s called", __FUNCTION__);
417 }
418
419 void
420 softdep_setup_dotdot_link(dp, ip)
421         struct inode *dp;
422         struct inode *ip;
423 {
424
425         panic("%s called", __FUNCTION__);
426 }
427
428 int
429 softdep_prealloc(vp, waitok)
430         struct vnode *vp;
431         int waitok;
432 {
433
434         panic("%s called", __FUNCTION__);
435
436         return (0);
437 }
438
439 int
440 softdep_journal_lookup(mp, vpp)
441         struct mount *mp;
442         struct vnode **vpp;
443 {
444
445         return (ENOENT);
446 }
447
448 void
449 softdep_change_linkcnt(ip)
450         struct inode *ip;
451 {
452
453         panic("softdep_change_linkcnt called");
454 }
455
456 void 
457 softdep_load_inodeblock(ip)
458         struct inode *ip;
459 {
460
461         panic("softdep_load_inodeblock called");
462 }
463
464 void
465 softdep_update_inodeblock(ip, bp, waitfor)
466         struct inode *ip;
467         struct buf *bp;
468         int waitfor;
469 {
470
471         panic("softdep_update_inodeblock called");
472 }
473
474 int
475 softdep_fsync(vp)
476         struct vnode *vp;       /* the "in_core" copy of the inode */
477 {
478
479         return (0);
480 }
481
482 void
483 softdep_fsync_mountdev(vp)
484         struct vnode *vp;
485 {
486
487         return;
488 }
489
490 int
491 softdep_flushworklist(oldmnt, countp, td)
492         struct mount *oldmnt;
493         int *countp;
494         struct thread *td;
495 {
496
497         *countp = 0;
498         return (0);
499 }
500
501 int
502 softdep_sync_metadata(struct vnode *vp)
503 {
504
505         return (0);
506 }
507
508 int
509 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
510 {
511
512         return (0);
513 }
514
515 int
516 softdep_slowdown(vp)
517         struct vnode *vp;
518 {
519
520         panic("softdep_slowdown called");
521 }
522
523 void
524 softdep_releasefile(ip)
525         struct inode *ip;       /* inode with the zero effective link count */
526 {
527
528         panic("softdep_releasefile called");
529 }
530
531 int
532 softdep_request_cleanup(fs, vp, cred, resource)
533         struct fs *fs;
534         struct vnode *vp;
535         struct ucred *cred;
536         int resource;
537 {
538
539         return (0);
540 }
541
542 int
543 softdep_check_suspend(struct mount *mp,
544                       struct vnode *devvp,
545                       int softdep_deps,
546                       int softdep_accdeps,
547                       int secondary_writes,
548                       int secondary_accwrites)
549 {
550         struct bufobj *bo;
551         int error;
552         
553         (void) softdep_deps,
554         (void) softdep_accdeps;
555
556         bo = &devvp->v_bufobj;
557         ASSERT_BO_LOCKED(bo);
558
559         MNT_ILOCK(mp);
560         while (mp->mnt_secondary_writes != 0) {
561                 BO_UNLOCK(bo);
562                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
563                     (PUSER - 1) | PDROP, "secwr", 0);
564                 BO_LOCK(bo);
565                 MNT_ILOCK(mp);
566         }
567
568         /*
569          * Reasons for needing more work before suspend:
570          * - Dirty buffers on devvp.
571          * - Secondary writes occurred after start of vnode sync loop
572          */
573         error = 0;
574         if (bo->bo_numoutput > 0 ||
575             bo->bo_dirty.bv_cnt > 0 ||
576             secondary_writes != 0 ||
577             mp->mnt_secondary_writes != 0 ||
578             secondary_accwrites != mp->mnt_secondary_accwrites)
579                 error = EAGAIN;
580         BO_UNLOCK(bo);
581         return (error);
582 }
583
584 void
585 softdep_get_depcounts(struct mount *mp,
586                       int *softdepactivep,
587                       int *softdepactiveaccp)
588 {
589         (void) mp;
590         *softdepactivep = 0;
591         *softdepactiveaccp = 0;
592 }
593
594 void
595 softdep_buf_append(bp, wkhd)
596         struct buf *bp;
597         struct workhead *wkhd;
598 {
599
600         panic("softdep_buf_appendwork called");
601 }
602
603 void
604 softdep_inode_append(ip, cred, wkhd)
605         struct inode *ip;
606         struct ucred *cred;
607         struct workhead *wkhd;
608 {
609
610         panic("softdep_inode_appendwork called");
611 }
612
613 void
614 softdep_freework(wkhd)
615         struct workhead *wkhd;
616 {
617
618         panic("softdep_freework called");
619 }
620
621 #else
622
623 FEATURE(softupdates, "FFS soft-updates support");
624
625 /*
626  * These definitions need to be adapted to the system to which
627  * this file is being ported.
628  */
629
630 #define M_SOFTDEP_FLAGS (M_WAITOK)
631
632 #define D_PAGEDEP       0
633 #define D_INODEDEP      1
634 #define D_BMSAFEMAP     2
635 #define D_NEWBLK        3
636 #define D_ALLOCDIRECT   4
637 #define D_INDIRDEP      5
638 #define D_ALLOCINDIR    6
639 #define D_FREEFRAG      7
640 #define D_FREEBLKS      8
641 #define D_FREEFILE      9
642 #define D_DIRADD        10
643 #define D_MKDIR         11
644 #define D_DIRREM        12
645 #define D_NEWDIRBLK     13
646 #define D_FREEWORK      14
647 #define D_FREEDEP       15
648 #define D_JADDREF       16
649 #define D_JREMREF       17
650 #define D_JMVREF        18
651 #define D_JNEWBLK       19
652 #define D_JFREEBLK      20
653 #define D_JFREEFRAG     21
654 #define D_JSEG          22
655 #define D_JSEGDEP       23
656 #define D_SBDEP         24
657 #define D_JTRUNC        25
658 #define D_JFSYNC        26
659 #define D_SENTINEL      27
660 #define D_LAST          D_SENTINEL
661
662 unsigned long dep_current[D_LAST + 1];
663 unsigned long dep_highuse[D_LAST + 1];
664 unsigned long dep_total[D_LAST + 1];
665 unsigned long dep_write[D_LAST + 1];
666
667 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
668     "soft updates stats");
669 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
670     "total dependencies allocated");
671 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
672     "high use dependencies allocated");
673 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
674     "current dependencies allocated");
675 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
676     "current dependencies written");
677
678 #define SOFTDEP_TYPE(type, str, long)                                   \
679     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
680     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
681         &dep_total[D_ ## type], 0, "");                                 \
682     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
683         &dep_current[D_ ## type], 0, "");                               \
684     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
685         &dep_highuse[D_ ## type], 0, "");                               \
686     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
687         &dep_write[D_ ## type], 0, "");
688
689 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
690 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
691 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
692     "Block or frag allocated from cyl group map");
693 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
694 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
695 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
696 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
697 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
698 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
699 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
700 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
701 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
702 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
703 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
704 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
705 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
706 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
707 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
708 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
709 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
710 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
711 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
712 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
713 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
714 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
715 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
716 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
717
718 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
719
720 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
721 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
722
723 /* 
724  * translate from workitem type to memory type
725  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
726  */
727 static struct malloc_type *memtype[] = {
728         M_PAGEDEP,
729         M_INODEDEP,
730         M_BMSAFEMAP,
731         M_NEWBLK,
732         M_ALLOCDIRECT,
733         M_INDIRDEP,
734         M_ALLOCINDIR,
735         M_FREEFRAG,
736         M_FREEBLKS,
737         M_FREEFILE,
738         M_DIRADD,
739         M_MKDIR,
740         M_DIRREM,
741         M_NEWDIRBLK,
742         M_FREEWORK,
743         M_FREEDEP,
744         M_JADDREF,
745         M_JREMREF,
746         M_JMVREF,
747         M_JNEWBLK,
748         M_JFREEBLK,
749         M_JFREEFRAG,
750         M_JSEG,
751         M_JSEGDEP,
752         M_SBDEP,
753         M_JTRUNC,
754         M_JFSYNC,
755         M_SENTINEL
756 };
757
758 static LIST_HEAD(mkdirlist, mkdir) mkdirlisthd;
759
760 #define DtoM(type) (memtype[type])
761
762 /*
763  * Names of malloc types.
764  */
765 #define TYPENAME(type)  \
766         ((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
767 /*
768  * End system adaptation definitions.
769  */
770
771 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
772 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
773
774 /*
775  * Forward declarations.
776  */
777 struct inodedep_hashhead;
778 struct newblk_hashhead;
779 struct pagedep_hashhead;
780 struct bmsafemap_hashhead;
781
782 /*
783  * Private journaling structures.
784  */
785 struct jblocks {
786         struct jseglst  jb_segs;        /* TAILQ of current segments. */
787         struct jseg     *jb_writeseg;   /* Next write to complete. */
788         struct jseg     *jb_oldestseg;  /* Oldest segment with valid entries. */
789         struct jextent  *jb_extent;     /* Extent array. */
790         uint64_t        jb_nextseq;     /* Next sequence number. */
791         uint64_t        jb_oldestwrseq; /* Oldest written sequence number. */
792         uint8_t         jb_needseg;     /* Need a forced segment. */
793         uint8_t         jb_suspended;   /* Did journal suspend writes? */
794         int             jb_avail;       /* Available extents. */
795         int             jb_used;        /* Last used extent. */
796         int             jb_head;        /* Allocator head. */
797         int             jb_off;         /* Allocator extent offset. */
798         int             jb_blocks;      /* Total disk blocks covered. */
799         int             jb_free;        /* Total disk blocks free. */
800         int             jb_min;         /* Minimum free space. */
801         int             jb_low;         /* Low on space. */
802         int             jb_age;         /* Insertion time of oldest rec. */
803 };
804
805 struct jextent {
806         ufs2_daddr_t    je_daddr;       /* Disk block address. */
807         int             je_blocks;      /* Disk block count. */
808 };
809
810 /*
811  * Internal function prototypes.
812  */
813 static  void softdep_error(char *, int);
814 static  void drain_output(struct vnode *);
815 static  struct buf *getdirtybuf(struct buf *, struct mtx *, int);
816 static  void clear_remove(struct thread *);
817 static  void clear_inodedeps(struct thread *);
818 static  void unlinked_inodedep(struct mount *, struct inodedep *);
819 static  void clear_unlinked_inodedep(struct inodedep *);
820 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
821 static  int flush_pagedep_deps(struct vnode *, struct mount *,
822             struct diraddhd *);
823 static  int free_pagedep(struct pagedep *);
824 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
825 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
826 static  int flush_deplist(struct allocdirectlst *, int, int *);
827 static  int sync_cgs(struct mount *, int);
828 static  int handle_written_filepage(struct pagedep *, struct buf *);
829 static  int handle_written_sbdep(struct sbdep *, struct buf *);
830 static  void initiate_write_sbdep(struct sbdep *);
831 static  void diradd_inode_written(struct diradd *, struct inodedep *);
832 static  int handle_written_indirdep(struct indirdep *, struct buf *,
833             struct buf**);
834 static  int handle_written_inodeblock(struct inodedep *, struct buf *);
835 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
836             uint8_t *);
837 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
838 static  void handle_written_jaddref(struct jaddref *);
839 static  void handle_written_jremref(struct jremref *);
840 static  void handle_written_jseg(struct jseg *, struct buf *);
841 static  void handle_written_jnewblk(struct jnewblk *);
842 static  void handle_written_jblkdep(struct jblkdep *);
843 static  void handle_written_jfreefrag(struct jfreefrag *);
844 static  void complete_jseg(struct jseg *);
845 static  void complete_jsegs(struct jseg *);
846 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
847 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
848 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
849 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
850 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
851 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
852 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
853 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
854 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
855 static  inline void inoref_write(struct inoref *, struct jseg *,
856             struct jrefrec *);
857 static  void handle_allocdirect_partdone(struct allocdirect *,
858             struct workhead *);
859 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
860             struct workhead *);
861 static  void indirdep_complete(struct indirdep *);
862 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
863 static  void indirblk_insert(struct freework *);
864 static  void indirblk_remove(struct freework *);
865 static  void handle_allocindir_partdone(struct allocindir *);
866 static  void initiate_write_filepage(struct pagedep *, struct buf *);
867 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
868 static  void handle_written_mkdir(struct mkdir *, int);
869 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
870             uint8_t *);
871 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
872 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
873 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
874 static  void handle_workitem_freefile(struct freefile *);
875 static  int handle_workitem_remove(struct dirrem *, int);
876 static  struct dirrem *newdirrem(struct buf *, struct inode *,
877             struct inode *, int, struct dirrem **);
878 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
879             struct buf *);
880 static  void cancel_indirdep(struct indirdep *, struct buf *,
881             struct freeblks *);
882 static  void free_indirdep(struct indirdep *);
883 static  void free_diradd(struct diradd *, struct workhead *);
884 static  void merge_diradd(struct inodedep *, struct diradd *);
885 static  void complete_diradd(struct diradd *);
886 static  struct diradd *diradd_lookup(struct pagedep *, int);
887 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
888             struct jremref *);
889 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
890             struct jremref *);
891 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
892             struct jremref *, struct jremref *);
893 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
894             struct jremref *);
895 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
896             struct freeblks *, int);
897 static  int setup_trunc_indir(struct freeblks *, struct inode *,
898             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
899 static  void complete_trunc_indir(struct freework *);
900 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
901             int);
902 static  void complete_mkdir(struct mkdir *);
903 static  void free_newdirblk(struct newdirblk *);
904 static  void free_jremref(struct jremref *);
905 static  void free_jaddref(struct jaddref *);
906 static  void free_jsegdep(struct jsegdep *);
907 static  void free_jsegs(struct jblocks *);
908 static  void rele_jseg(struct jseg *);
909 static  void free_jseg(struct jseg *, struct jblocks *);
910 static  void free_jnewblk(struct jnewblk *);
911 static  void free_jblkdep(struct jblkdep *);
912 static  void free_jfreefrag(struct jfreefrag *);
913 static  void free_freedep(struct freedep *);
914 static  void journal_jremref(struct dirrem *, struct jremref *,
915             struct inodedep *);
916 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
917 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
918             struct workhead *);
919 static  void cancel_jfreefrag(struct jfreefrag *);
920 static  inline void setup_freedirect(struct freeblks *, struct inode *,
921             int, int);
922 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
923 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
924             ufs_lbn_t, int);
925 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
926 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
927 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
928 ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
929 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
930 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
931             int, int);
932 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
933 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
934 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
935 static  void newblk_freefrag(struct newblk*);
936 static  void free_newblk(struct newblk *);
937 static  void cancel_allocdirect(struct allocdirectlst *,
938             struct allocdirect *, struct freeblks *);
939 static  int check_inode_unwritten(struct inodedep *);
940 static  int free_inodedep(struct inodedep *);
941 static  void freework_freeblock(struct freework *);
942 static  void freework_enqueue(struct freework *);
943 static  int handle_workitem_freeblocks(struct freeblks *, int);
944 static  int handle_complete_freeblocks(struct freeblks *, int);
945 static  void handle_workitem_indirblk(struct freework *);
946 static  void handle_written_freework(struct freework *);
947 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
948 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
949             struct workhead *);
950 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
951             struct inodedep *, struct allocindir *, ufs_lbn_t);
952 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
953             ufs2_daddr_t, ufs_lbn_t);
954 static  void handle_workitem_freefrag(struct freefrag *);
955 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
956             ufs_lbn_t);
957 static  void allocdirect_merge(struct allocdirectlst *,
958             struct allocdirect *, struct allocdirect *);
959 static  struct freefrag *allocindir_merge(struct allocindir *,
960             struct allocindir *);
961 static  int bmsafemap_find(struct bmsafemap_hashhead *, struct mount *, int,
962             struct bmsafemap **);
963 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
964             int cg, struct bmsafemap *);
965 static  int newblk_find(struct newblk_hashhead *, struct mount *, ufs2_daddr_t,
966             int, struct newblk **);
967 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
968 static  int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
969             struct inodedep **);
970 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
971 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
972             int, struct pagedep **);
973 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
974             struct mount *mp, int, struct pagedep **);
975 static  void pause_timer(void *);
976 static  int request_cleanup(struct mount *, int);
977 static  int process_worklist_item(struct mount *, int, int);
978 static  void process_removes(struct vnode *);
979 static  void process_truncates(struct vnode *);
980 static  void jwork_move(struct workhead *, struct workhead *);
981 static  void jwork_insert(struct workhead *, struct jsegdep *);
982 static  void add_to_worklist(struct worklist *, int);
983 static  void wake_worklist(struct worklist *);
984 static  void wait_worklist(struct worklist *, char *);
985 static  void remove_from_worklist(struct worklist *);
986 static  void softdep_flush(void);
987 static  void softdep_flushjournal(struct mount *);
988 static  int softdep_speedup(void);
989 static  void worklist_speedup(void);
990 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
991 static  void journal_unmount(struct mount *);
992 static  int journal_space(struct ufsmount *, int);
993 static  void journal_suspend(struct ufsmount *);
994 static  int journal_unsuspend(struct ufsmount *ump);
995 static  void softdep_prelink(struct vnode *, struct vnode *);
996 static  void add_to_journal(struct worklist *);
997 static  void remove_from_journal(struct worklist *);
998 static  void softdep_process_journal(struct mount *, struct worklist *, int);
999 static  struct jremref *newjremref(struct dirrem *, struct inode *,
1000             struct inode *ip, off_t, nlink_t);
1001 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
1002             uint16_t);
1003 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
1004             uint16_t);
1005 static  inline struct jsegdep *inoref_jseg(struct inoref *);
1006 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
1007 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
1008             ufs2_daddr_t, int);
1009 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
1010 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
1011 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
1012 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
1013             ufs2_daddr_t, long, ufs_lbn_t);
1014 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
1015             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
1016 static  int jwait(struct worklist *, int);
1017 static  struct inodedep *inodedep_lookup_ip(struct inode *);
1018 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
1019 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
1020 static  void handle_jwork(struct workhead *);
1021 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
1022             struct mkdir **);
1023 static  struct jblocks *jblocks_create(void);
1024 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
1025 static  void jblocks_free(struct jblocks *, struct mount *, int);
1026 static  void jblocks_destroy(struct jblocks *);
1027 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
1028
1029 /*
1030  * Exported softdep operations.
1031  */
1032 static  void softdep_disk_io_initiation(struct buf *);
1033 static  void softdep_disk_write_complete(struct buf *);
1034 static  void softdep_deallocate_dependencies(struct buf *);
1035 static  int softdep_count_dependencies(struct buf *bp, int);
1036
1037 static struct mtx lk;
1038 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
1039
1040 #define TRY_ACQUIRE_LOCK(lk)            mtx_trylock(lk)
1041 #define ACQUIRE_LOCK(lk)                mtx_lock(lk)
1042 #define FREE_LOCK(lk)                   mtx_unlock(lk)
1043
1044 #define BUF_AREC(bp)                    lockallowrecurse(&(bp)->b_lock)
1045 #define BUF_NOREC(bp)                   lockdisablerecurse(&(bp)->b_lock)
1046
1047 /*
1048  * Worklist queue management.
1049  * These routines require that the lock be held.
1050  */
1051 #ifndef /* NOT */ DEBUG
1052 #define WORKLIST_INSERT(head, item) do {        \
1053         (item)->wk_state |= ONWORKLIST;         \
1054         LIST_INSERT_HEAD(head, item, wk_list);  \
1055 } while (0)
1056 #define WORKLIST_REMOVE(item) do {              \
1057         (item)->wk_state &= ~ONWORKLIST;        \
1058         LIST_REMOVE(item, wk_list);             \
1059 } while (0)
1060 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1061 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1062
1063 #else /* DEBUG */
1064 static  void worklist_insert(struct workhead *, struct worklist *, int);
1065 static  void worklist_remove(struct worklist *, int);
1066
1067 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1068 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1069 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1070 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1071
1072 static void
1073 worklist_insert(head, item, locked)
1074         struct workhead *head;
1075         struct worklist *item;
1076         int locked;
1077 {
1078
1079         if (locked)
1080                 mtx_assert(&lk, MA_OWNED);
1081         if (item->wk_state & ONWORKLIST)
1082                 panic("worklist_insert: %p %s(0x%X) already on list",
1083                     item, TYPENAME(item->wk_type), item->wk_state);
1084         item->wk_state |= ONWORKLIST;
1085         LIST_INSERT_HEAD(head, item, wk_list);
1086 }
1087
1088 static void
1089 worklist_remove(item, locked)
1090         struct worklist *item;
1091         int locked;
1092 {
1093
1094         if (locked)
1095                 mtx_assert(&lk, MA_OWNED);
1096         if ((item->wk_state & ONWORKLIST) == 0)
1097                 panic("worklist_remove: %p %s(0x%X) not on list",
1098                     item, TYPENAME(item->wk_type), item->wk_state);
1099         item->wk_state &= ~ONWORKLIST;
1100         LIST_REMOVE(item, wk_list);
1101 }
1102 #endif /* DEBUG */
1103
1104 /*
1105  * Merge two jsegdeps keeping only the oldest one as newer references
1106  * can't be discarded until after older references.
1107  */
1108 static inline struct jsegdep *
1109 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1110 {
1111         struct jsegdep *swp;
1112
1113         if (two == NULL)
1114                 return (one);
1115
1116         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1117                 swp = one;
1118                 one = two;
1119                 two = swp;
1120         }
1121         WORKLIST_REMOVE(&two->jd_list);
1122         free_jsegdep(two);
1123
1124         return (one);
1125 }
1126
1127 /*
1128  * If two freedeps are compatible free one to reduce list size.
1129  */
1130 static inline struct freedep *
1131 freedep_merge(struct freedep *one, struct freedep *two)
1132 {
1133         if (two == NULL)
1134                 return (one);
1135
1136         if (one->fd_freework == two->fd_freework) {
1137                 WORKLIST_REMOVE(&two->fd_list);
1138                 free_freedep(two);
1139         }
1140         return (one);
1141 }
1142
1143 /*
1144  * Move journal work from one list to another.  Duplicate freedeps and
1145  * jsegdeps are coalesced to keep the lists as small as possible.
1146  */
1147 static void
1148 jwork_move(dst, src)
1149         struct workhead *dst;
1150         struct workhead *src;
1151 {
1152         struct freedep *freedep;
1153         struct jsegdep *jsegdep;
1154         struct worklist *wkn;
1155         struct worklist *wk;
1156
1157         KASSERT(dst != src,
1158             ("jwork_move: dst == src"));
1159         freedep = NULL;
1160         jsegdep = NULL;
1161         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1162                 if (wk->wk_type == D_JSEGDEP)
1163                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1164                 if (wk->wk_type == D_FREEDEP)
1165                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1166         }
1167
1168         mtx_assert(&lk, MA_OWNED);
1169         while ((wk = LIST_FIRST(src)) != NULL) {
1170                 WORKLIST_REMOVE(wk);
1171                 WORKLIST_INSERT(dst, wk);
1172                 if (wk->wk_type == D_JSEGDEP) {
1173                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1174                         continue;
1175                 }
1176                 if (wk->wk_type == D_FREEDEP)
1177                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1178         }
1179 }
1180
1181 static void
1182 jwork_insert(dst, jsegdep)
1183         struct workhead *dst;
1184         struct jsegdep *jsegdep;
1185 {
1186         struct jsegdep *jsegdepn;
1187         struct worklist *wk;
1188
1189         LIST_FOREACH(wk, dst, wk_list)
1190                 if (wk->wk_type == D_JSEGDEP)
1191                         break;
1192         if (wk == NULL) {
1193                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1194                 return;
1195         }
1196         jsegdepn = WK_JSEGDEP(wk);
1197         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1198                 WORKLIST_REMOVE(wk);
1199                 free_jsegdep(jsegdepn);
1200                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1201         } else
1202                 free_jsegdep(jsegdep);
1203 }
1204
1205 /*
1206  * Routines for tracking and managing workitems.
1207  */
1208 static  void workitem_free(struct worklist *, int);
1209 static  void workitem_alloc(struct worklist *, int, struct mount *);
1210 static  void workitem_reassign(struct worklist *, int);
1211
1212 #define WORKITEM_FREE(item, type) \
1213         workitem_free((struct worklist *)(item), (type))
1214 #define WORKITEM_REASSIGN(item, type) \
1215         workitem_reassign((struct worklist *)(item), (type))
1216
1217 static void
1218 workitem_free(item, type)
1219         struct worklist *item;
1220         int type;
1221 {
1222         struct ufsmount *ump;
1223         mtx_assert(&lk, MA_OWNED);
1224
1225 #ifdef DEBUG
1226         if (item->wk_state & ONWORKLIST)
1227                 panic("workitem_free: %s(0x%X) still on list",
1228                     TYPENAME(item->wk_type), item->wk_state);
1229         if (item->wk_type != type && type != D_NEWBLK)
1230                 panic("workitem_free: type mismatch %s != %s",
1231                     TYPENAME(item->wk_type), TYPENAME(type));
1232 #endif
1233         if (item->wk_state & IOWAITING)
1234                 wakeup(item);
1235         ump = VFSTOUFS(item->wk_mp);
1236         KASSERT(ump->softdep_deps > 0,
1237             ("workitem_free: %s: softdep_deps going negative",
1238             ump->um_fs->fs_fsmnt));
1239         if (--ump->softdep_deps == 0 && ump->softdep_req)
1240                 wakeup(&ump->softdep_deps);
1241         KASSERT(dep_current[item->wk_type] > 0,
1242             ("workitem_free: %s: dep_current[%s] going negative",
1243             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1244         dep_current[item->wk_type]--;
1245         free(item, DtoM(type));
1246 }
1247
1248 static void
1249 workitem_alloc(item, type, mp)
1250         struct worklist *item;
1251         int type;
1252         struct mount *mp;
1253 {
1254         struct ufsmount *ump;
1255
1256         item->wk_type = type;
1257         item->wk_mp = mp;
1258         item->wk_state = 0;
1259
1260         ump = VFSTOUFS(mp);
1261         ACQUIRE_LOCK(&lk);
1262         dep_current[type]++;
1263         if (dep_current[type] > dep_highuse[type])
1264                 dep_highuse[type] = dep_current[type];
1265         dep_total[type]++;
1266         ump->softdep_deps++;
1267         ump->softdep_accdeps++;
1268         FREE_LOCK(&lk);
1269 }
1270
1271 static void
1272 workitem_reassign(item, newtype)
1273         struct worklist *item;
1274         int newtype;
1275 {
1276
1277         KASSERT(dep_current[item->wk_type] > 0,
1278             ("workitem_reassign: %s: dep_current[%s] going negative",
1279             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1280         dep_current[item->wk_type]--;
1281         dep_current[newtype]++;
1282         if (dep_current[newtype] > dep_highuse[newtype])
1283                 dep_highuse[newtype] = dep_current[newtype];
1284         dep_total[newtype]++;
1285         item->wk_type = newtype;
1286 }
1287
1288 /*
1289  * Workitem queue management
1290  */
1291 static int max_softdeps;        /* maximum number of structs before slowdown */
1292 static int maxindirdeps = 50;   /* max number of indirdeps before slowdown */
1293 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1294 static int proc_waiting;        /* tracks whether we have a timeout posted */
1295 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1296 static struct callout softdep_callout;
1297 static int req_pending;
1298 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1299 static int req_clear_remove;    /* syncer process flush some freeblks */
1300 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1301
1302 /*
1303  * runtime statistics
1304  */
1305 static int stat_worklist_push;  /* number of worklist cleanups */
1306 static int stat_blk_limit_push; /* number of times block limit neared */
1307 static int stat_ino_limit_push; /* number of times inode limit neared */
1308 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1309 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1310 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1311 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1312 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1313 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1314 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1315 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1316 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1317 static int stat_journal_min;    /* Times hit journal min threshold */
1318 static int stat_journal_low;    /* Times hit journal low threshold */
1319 static int stat_journal_wait;   /* Times blocked in jwait(). */
1320 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1321 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1322 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1323 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1324 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1325 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1326 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1327 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1328 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1329
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1331     &max_softdeps, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1333     &tickdelay, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1335     &maxindirdeps, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1337     &stat_worklist_push, 0,"");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1339     &stat_blk_limit_push, 0,"");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1341     &stat_ino_limit_push, 0,"");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1343     &stat_blk_limit_hit, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1345     &stat_ino_limit_hit, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1347     &stat_sync_limit_hit, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1349     &stat_indir_blk_ptrs, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1351     &stat_inode_bitmap, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1353     &stat_direct_blk_ptrs, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1355     &stat_dir_entry, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1357     &stat_jaddref, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1359     &stat_jnewblk, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1361     &stat_journal_low, 0, "");
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1363     &stat_journal_min, 0, "");
1364 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1365     &stat_journal_wait, 0, "");
1366 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1367     &stat_jwait_filepage, 0, "");
1368 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1369     &stat_jwait_freeblks, 0, "");
1370 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1371     &stat_jwait_inode, 0, "");
1372 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1373     &stat_jwait_newblk, 0, "");
1374 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1375     &stat_cleanup_blkrequests, 0, "");
1376 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1377     &stat_cleanup_inorequests, 0, "");
1378 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1379     &stat_cleanup_high_delay, 0, "");
1380 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1381     &stat_cleanup_retries, 0, "");
1382 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1383     &stat_cleanup_failures, 0, "");
1384 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1385     &softdep_flushcache, 0, "");
1386
1387 SYSCTL_DECL(_vfs_ffs);
1388
1389 LIST_HEAD(bmsafemap_hashhead, bmsafemap) *bmsafemap_hashtbl;
1390 static u_long   bmsafemap_hash; /* size of hash table - 1 */
1391
1392 static int compute_summary_at_mount = 0;        /* Whether to recompute the summary at mount time */
1393 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1394            &compute_summary_at_mount, 0, "Recompute summary at mount");
1395
1396 static struct proc *softdepproc;
1397 static struct kproc_desc softdep_kp = {
1398         "softdepflush",
1399         softdep_flush,
1400         &softdepproc
1401 };
1402 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1403     &softdep_kp);
1404
1405 static void
1406 softdep_flush(void)
1407 {
1408         struct mount *nmp;
1409         struct mount *mp;
1410         struct ufsmount *ump;
1411         struct thread *td;
1412         int remaining;
1413         int progress;
1414         int vfslocked;
1415
1416         td = curthread;
1417         td->td_pflags |= TDP_NORUNNINGBUF;
1418
1419         for (;;) {      
1420                 kproc_suspend_check(softdepproc);
1421                 vfslocked = VFS_LOCK_GIANT((struct mount *)NULL);
1422                 ACQUIRE_LOCK(&lk);
1423                 /*
1424                  * If requested, try removing inode or removal dependencies.
1425                  */
1426                 if (req_clear_inodedeps) {
1427                         clear_inodedeps(td);
1428                         req_clear_inodedeps -= 1;
1429                         wakeup_one(&proc_waiting);
1430                 }
1431                 if (req_clear_remove) {
1432                         clear_remove(td);
1433                         req_clear_remove -= 1;
1434                         wakeup_one(&proc_waiting);
1435                 }
1436                 FREE_LOCK(&lk);
1437                 VFS_UNLOCK_GIANT(vfslocked);
1438                 remaining = progress = 0;
1439                 mtx_lock(&mountlist_mtx);
1440                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1441                         nmp = TAILQ_NEXT(mp, mnt_list);
1442                         if (MOUNTEDSOFTDEP(mp) == 0)
1443                                 continue;
1444                         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1445                                 continue;
1446                         vfslocked = VFS_LOCK_GIANT(mp);
1447                         progress += softdep_process_worklist(mp, 0);
1448                         ump = VFSTOUFS(mp);
1449                         remaining += ump->softdep_on_worklist;
1450                         VFS_UNLOCK_GIANT(vfslocked);
1451                         mtx_lock(&mountlist_mtx);
1452                         nmp = TAILQ_NEXT(mp, mnt_list);
1453                         vfs_unbusy(mp);
1454                 }
1455                 mtx_unlock(&mountlist_mtx);
1456                 if (remaining && progress)
1457                         continue;
1458                 ACQUIRE_LOCK(&lk);
1459                 if (!req_pending)
1460                         msleep(&req_pending, &lk, PVM, "sdflush", hz);
1461                 req_pending = 0;
1462                 FREE_LOCK(&lk);
1463         }
1464 }
1465
1466 static void
1467 worklist_speedup(void)
1468 {
1469         mtx_assert(&lk, MA_OWNED);
1470         if (req_pending == 0) {
1471                 req_pending = 1;
1472                 wakeup(&req_pending);
1473         }
1474 }
1475
1476 static int
1477 softdep_speedup(void)
1478 {
1479
1480         worklist_speedup();
1481         bd_speedup();
1482         return speedup_syncer();
1483 }
1484
1485 /*
1486  * Add an item to the end of the work queue.
1487  * This routine requires that the lock be held.
1488  * This is the only routine that adds items to the list.
1489  * The following routine is the only one that removes items
1490  * and does so in order from first to last.
1491  */
1492
1493 #define WK_HEAD         0x0001  /* Add to HEAD. */
1494 #define WK_NODELAY      0x0002  /* Process immediately. */
1495
1496 static void
1497 add_to_worklist(wk, flags)
1498         struct worklist *wk;
1499         int flags;
1500 {
1501         struct ufsmount *ump;
1502
1503         mtx_assert(&lk, MA_OWNED);
1504         ump = VFSTOUFS(wk->wk_mp);
1505         if (wk->wk_state & ONWORKLIST)
1506                 panic("add_to_worklist: %s(0x%X) already on list",
1507                     TYPENAME(wk->wk_type), wk->wk_state);
1508         wk->wk_state |= ONWORKLIST;
1509         if (ump->softdep_on_worklist == 0) {
1510                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1511                 ump->softdep_worklist_tail = wk;
1512         } else if (flags & WK_HEAD) {
1513                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1514         } else {
1515                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1516                 ump->softdep_worklist_tail = wk;
1517         }
1518         ump->softdep_on_worklist += 1;
1519         if (flags & WK_NODELAY)
1520                 worklist_speedup();
1521 }
1522
1523 /*
1524  * Remove the item to be processed. If we are removing the last
1525  * item on the list, we need to recalculate the tail pointer.
1526  */
1527 static void
1528 remove_from_worklist(wk)
1529         struct worklist *wk;
1530 {
1531         struct ufsmount *ump;
1532
1533         ump = VFSTOUFS(wk->wk_mp);
1534         WORKLIST_REMOVE(wk);
1535         if (ump->softdep_worklist_tail == wk)
1536                 ump->softdep_worklist_tail =
1537                     (struct worklist *)wk->wk_list.le_prev;
1538         ump->softdep_on_worklist -= 1;
1539 }
1540
1541 static void
1542 wake_worklist(wk)
1543         struct worklist *wk;
1544 {
1545         if (wk->wk_state & IOWAITING) {
1546                 wk->wk_state &= ~IOWAITING;
1547                 wakeup(wk);
1548         }
1549 }
1550
1551 static void
1552 wait_worklist(wk, wmesg)
1553         struct worklist *wk;
1554         char *wmesg;
1555 {
1556
1557         wk->wk_state |= IOWAITING;
1558         msleep(wk, &lk, PVM, wmesg, 0);
1559 }
1560
1561 /*
1562  * Process that runs once per second to handle items in the background queue.
1563  *
1564  * Note that we ensure that everything is done in the order in which they
1565  * appear in the queue. The code below depends on this property to ensure
1566  * that blocks of a file are freed before the inode itself is freed. This
1567  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1568  * until all the old ones have been purged from the dependency lists.
1569  */
1570 int 
1571 softdep_process_worklist(mp, full)
1572         struct mount *mp;
1573         int full;
1574 {
1575         struct thread *td = curthread;
1576         int cnt, matchcnt;
1577         struct ufsmount *ump;
1578         long starttime;
1579
1580         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1581         /*
1582          * Record the process identifier of our caller so that we can give
1583          * this process preferential treatment in request_cleanup below.
1584          */
1585         matchcnt = 0;
1586         ump = VFSTOUFS(mp);
1587         ACQUIRE_LOCK(&lk);
1588         starttime = time_second;
1589         softdep_process_journal(mp, NULL, full?MNT_WAIT:0);
1590         while (ump->softdep_on_worklist > 0) {
1591                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1592                         break;
1593                 else
1594                         matchcnt += cnt;
1595                 /*
1596                  * If requested, try removing inode or removal dependencies.
1597                  */
1598                 if (req_clear_inodedeps) {
1599                         clear_inodedeps(td);
1600                         req_clear_inodedeps -= 1;
1601                         wakeup_one(&proc_waiting);
1602                 }
1603                 if (req_clear_remove) {
1604                         clear_remove(td);
1605                         req_clear_remove -= 1;
1606                         wakeup_one(&proc_waiting);
1607                 }
1608                 /*
1609                  * We do not generally want to stop for buffer space, but if
1610                  * we are really being a buffer hog, we will stop and wait.
1611                  */
1612                 if (should_yield()) {
1613                         FREE_LOCK(&lk);
1614                         kern_yield(PRI_UNCHANGED);
1615                         bwillwrite();
1616                         ACQUIRE_LOCK(&lk);
1617                 }
1618                 /*
1619                  * Never allow processing to run for more than one
1620                  * second. Otherwise the other mountpoints may get
1621                  * excessively backlogged.
1622                  */
1623                 if (!full && starttime != time_second)
1624                         break;
1625         }
1626         if (full == 0)
1627                 journal_unsuspend(ump);
1628         FREE_LOCK(&lk);
1629         return (matchcnt);
1630 }
1631
1632 /*
1633  * Process all removes associated with a vnode if we are running out of
1634  * journal space.  Any other process which attempts to flush these will
1635  * be unable as we have the vnodes locked.
1636  */
1637 static void
1638 process_removes(vp)
1639         struct vnode *vp;
1640 {
1641         struct inodedep *inodedep;
1642         struct dirrem *dirrem;
1643         struct mount *mp;
1644         ino_t inum;
1645
1646         mtx_assert(&lk, MA_OWNED);
1647
1648         mp = vp->v_mount;
1649         inum = VTOI(vp)->i_number;
1650         for (;;) {
1651 top:
1652                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1653                         return;
1654                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1655                         /*
1656                          * If another thread is trying to lock this vnode
1657                          * it will fail but we must wait for it to do so
1658                          * before we can proceed.
1659                          */
1660                         if (dirrem->dm_state & INPROGRESS) {
1661                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1662                                 goto top;
1663                         }
1664                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1665                             (COMPLETE | ONWORKLIST))
1666                                 break;
1667                 }
1668                 if (dirrem == NULL)
1669                         return;
1670                 remove_from_worklist(&dirrem->dm_list);
1671                 FREE_LOCK(&lk);
1672                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1673                         panic("process_removes: suspended filesystem");
1674                 handle_workitem_remove(dirrem, 0);
1675                 vn_finished_secondary_write(mp);
1676                 ACQUIRE_LOCK(&lk);
1677         }
1678 }
1679
1680 /*
1681  * Process all truncations associated with a vnode if we are running out
1682  * of journal space.  This is called when the vnode lock is already held
1683  * and no other process can clear the truncation.  This function returns
1684  * a value greater than zero if it did any work.
1685  */
1686 static void
1687 process_truncates(vp)
1688         struct vnode *vp;
1689 {
1690         struct inodedep *inodedep;
1691         struct freeblks *freeblks;
1692         struct mount *mp;
1693         ino_t inum;
1694         int cgwait;
1695
1696         mtx_assert(&lk, MA_OWNED);
1697
1698         mp = vp->v_mount;
1699         inum = VTOI(vp)->i_number;
1700         for (;;) {
1701                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1702                         return;
1703                 cgwait = 0;
1704                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1705                         /* Journal entries not yet written.  */
1706                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1707                                 jwait(&LIST_FIRST(
1708                                     &freeblks->fb_jblkdephd)->jb_list,
1709                                     MNT_WAIT);
1710                                 break;
1711                         }
1712                         /* Another thread is executing this item. */
1713                         if (freeblks->fb_state & INPROGRESS) {
1714                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1715                                 break;
1716                         }
1717                         /* Freeblks is waiting on a inode write. */
1718                         if ((freeblks->fb_state & COMPLETE) == 0) {
1719                                 FREE_LOCK(&lk);
1720                                 ffs_update(vp, 1);
1721                                 ACQUIRE_LOCK(&lk);
1722                                 break;
1723                         }
1724                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1725                             (ALLCOMPLETE | ONWORKLIST)) {
1726                                 remove_from_worklist(&freeblks->fb_list);
1727                                 freeblks->fb_state |= INPROGRESS;
1728                                 FREE_LOCK(&lk);
1729                                 if (vn_start_secondary_write(NULL, &mp,
1730                                     V_NOWAIT))
1731                                         panic("process_truncates: "
1732                                             "suspended filesystem");
1733                                 handle_workitem_freeblocks(freeblks, 0);
1734                                 vn_finished_secondary_write(mp);
1735                                 ACQUIRE_LOCK(&lk);
1736                                 break;
1737                         }
1738                         if (freeblks->fb_cgwait)
1739                                 cgwait++;
1740                 }
1741                 if (cgwait) {
1742                         FREE_LOCK(&lk);
1743                         sync_cgs(mp, MNT_WAIT);
1744                         ffs_sync_snap(mp, MNT_WAIT);
1745                         ACQUIRE_LOCK(&lk);
1746                         continue;
1747                 }
1748                 if (freeblks == NULL)
1749                         break;
1750         }
1751         return;
1752 }
1753
1754 /*
1755  * Process one item on the worklist.
1756  */
1757 static int
1758 process_worklist_item(mp, target, flags)
1759         struct mount *mp;
1760         int target;
1761         int flags;
1762 {
1763         struct worklist sentinel;
1764         struct worklist *wk;
1765         struct ufsmount *ump;
1766         int matchcnt;
1767         int error;
1768
1769         mtx_assert(&lk, MA_OWNED);
1770         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1771         /*
1772          * If we are being called because of a process doing a
1773          * copy-on-write, then it is not safe to write as we may
1774          * recurse into the copy-on-write routine.
1775          */
1776         if (curthread->td_pflags & TDP_COWINPROGRESS)
1777                 return (-1);
1778         PHOLD(curproc); /* Don't let the stack go away. */
1779         ump = VFSTOUFS(mp);
1780         matchcnt = 0;
1781         sentinel.wk_mp = NULL;
1782         sentinel.wk_type = D_SENTINEL;
1783         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1784         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1785             wk = LIST_NEXT(&sentinel, wk_list)) {
1786                 if (wk->wk_type == D_SENTINEL) {
1787                         LIST_REMOVE(&sentinel, wk_list);
1788                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1789                         continue;
1790                 }
1791                 if (wk->wk_state & INPROGRESS)
1792                         panic("process_worklist_item: %p already in progress.",
1793                             wk);
1794                 wk->wk_state |= INPROGRESS;
1795                 remove_from_worklist(wk);
1796                 FREE_LOCK(&lk);
1797                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1798                         panic("process_worklist_item: suspended filesystem");
1799                 switch (wk->wk_type) {
1800                 case D_DIRREM:
1801                         /* removal of a directory entry */
1802                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1803                         break;
1804
1805                 case D_FREEBLKS:
1806                         /* releasing blocks and/or fragments from a file */
1807                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1808                             flags);
1809                         break;
1810
1811                 case D_FREEFRAG:
1812                         /* releasing a fragment when replaced as a file grows */
1813                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1814                         error = 0;
1815                         break;
1816
1817                 case D_FREEFILE:
1818                         /* releasing an inode when its link count drops to 0 */
1819                         handle_workitem_freefile(WK_FREEFILE(wk));
1820                         error = 0;
1821                         break;
1822
1823                 default:
1824                         panic("%s_process_worklist: Unknown type %s",
1825                             "softdep", TYPENAME(wk->wk_type));
1826                         /* NOTREACHED */
1827                 }
1828                 vn_finished_secondary_write(mp);
1829                 ACQUIRE_LOCK(&lk);
1830                 if (error == 0) {
1831                         if (++matchcnt == target)
1832                                 break;
1833                         continue;
1834                 }
1835                 /*
1836                  * We have to retry the worklist item later.  Wake up any
1837                  * waiters who may be able to complete it immediately and
1838                  * add the item back to the head so we don't try to execute
1839                  * it again.
1840                  */
1841                 wk->wk_state &= ~INPROGRESS;
1842                 wake_worklist(wk);
1843                 add_to_worklist(wk, WK_HEAD);
1844         }
1845         LIST_REMOVE(&sentinel, wk_list);
1846         /* Sentinal could've become the tail from remove_from_worklist. */
1847         if (ump->softdep_worklist_tail == &sentinel)
1848                 ump->softdep_worklist_tail =
1849                     (struct worklist *)sentinel.wk_list.le_prev;
1850         PRELE(curproc);
1851         return (matchcnt);
1852 }
1853
1854 /*
1855  * Move dependencies from one buffer to another.
1856  */
1857 int
1858 softdep_move_dependencies(oldbp, newbp)
1859         struct buf *oldbp;
1860         struct buf *newbp;
1861 {
1862         struct worklist *wk, *wktail;
1863         int dirty;
1864
1865         dirty = 0;
1866         wktail = NULL;
1867         ACQUIRE_LOCK(&lk);
1868         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1869                 LIST_REMOVE(wk, wk_list);
1870                 if (wk->wk_type == D_BMSAFEMAP &&
1871                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1872                         dirty = 1;
1873                 if (wktail == NULL)
1874                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1875                 else
1876                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1877                 wktail = wk;
1878         }
1879         FREE_LOCK(&lk);
1880
1881         return (dirty);
1882 }
1883
1884 /*
1885  * Purge the work list of all items associated with a particular mount point.
1886  */
1887 int
1888 softdep_flushworklist(oldmnt, countp, td)
1889         struct mount *oldmnt;
1890         int *countp;
1891         struct thread *td;
1892 {
1893         struct vnode *devvp;
1894         int count, error = 0;
1895         struct ufsmount *ump;
1896
1897         /*
1898          * Alternately flush the block device associated with the mount
1899          * point and process any dependencies that the flushing
1900          * creates. We continue until no more worklist dependencies
1901          * are found.
1902          */
1903         *countp = 0;
1904         ump = VFSTOUFS(oldmnt);
1905         devvp = ump->um_devvp;
1906         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1907                 *countp += count;
1908                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1909                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1910                 VOP_UNLOCK(devvp, 0);
1911                 if (error)
1912                         break;
1913         }
1914         return (error);
1915 }
1916
1917 int
1918 softdep_waitidle(struct mount *mp)
1919 {
1920         struct ufsmount *ump;
1921         int error;
1922         int i;
1923
1924         ump = VFSTOUFS(mp);
1925         ACQUIRE_LOCK(&lk);
1926         for (i = 0; i < 10 && ump->softdep_deps; i++) {
1927                 ump->softdep_req = 1;
1928                 if (ump->softdep_on_worklist)
1929                         panic("softdep_waitidle: work added after flush.");
1930                 msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1931         }
1932         ump->softdep_req = 0;
1933         FREE_LOCK(&lk);
1934         error = 0;
1935         if (i == 10) {
1936                 error = EBUSY;
1937                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1938                     mp);
1939         }
1940
1941         return (error);
1942 }
1943
1944 /*
1945  * Flush all vnodes and worklist items associated with a specified mount point.
1946  */
1947 int
1948 softdep_flushfiles(oldmnt, flags, td)
1949         struct mount *oldmnt;
1950         int flags;
1951         struct thread *td;
1952 {
1953 #ifdef QUOTA
1954         struct ufsmount *ump;
1955         int i;
1956 #endif
1957         int error, early, depcount, loopcnt, retry_flush_count, retry;
1958         int morework;
1959
1960         loopcnt = 10;
1961         retry_flush_count = 3;
1962 retry_flush:
1963         error = 0;
1964
1965         /*
1966          * Alternately flush the vnodes associated with the mount
1967          * point and process any dependencies that the flushing
1968          * creates. In theory, this loop can happen at most twice,
1969          * but we give it a few extra just to be sure.
1970          */
1971         for (; loopcnt > 0; loopcnt--) {
1972                 /*
1973                  * Do another flush in case any vnodes were brought in
1974                  * as part of the cleanup operations.
1975                  */
1976                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1977                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1978                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1979                         break;
1980                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1981                     depcount == 0)
1982                         break;
1983         }
1984         /*
1985          * If we are unmounting then it is an error to fail. If we
1986          * are simply trying to downgrade to read-only, then filesystem
1987          * activity can keep us busy forever, so we just fail with EBUSY.
1988          */
1989         if (loopcnt == 0) {
1990                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1991                         panic("softdep_flushfiles: looping");
1992                 error = EBUSY;
1993         }
1994         if (!error)
1995                 error = softdep_waitidle(oldmnt);
1996         if (!error) {
1997                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1998                         retry = 0;
1999                         MNT_ILOCK(oldmnt);
2000                         KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2001                             ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2002                         morework = oldmnt->mnt_nvnodelistsize > 0;
2003 #ifdef QUOTA
2004                         ump = VFSTOUFS(oldmnt);
2005                         UFS_LOCK(ump);
2006                         for (i = 0; i < MAXQUOTAS; i++) {
2007                                 if (ump->um_quotas[i] != NULLVP)
2008                                         morework = 1;
2009                         }
2010                         UFS_UNLOCK(ump);
2011 #endif
2012                         if (morework) {
2013                                 if (--retry_flush_count > 0) {
2014                                         retry = 1;
2015                                         loopcnt = 3;
2016                                 } else
2017                                         error = EBUSY;
2018                         }
2019                         MNT_IUNLOCK(oldmnt);
2020                         if (retry)
2021                                 goto retry_flush;
2022                 }
2023         }
2024         return (error);
2025 }
2026
2027 /*
2028  * Structure hashing.
2029  * 
2030  * There are three types of structures that can be looked up:
2031  *      1) pagedep structures identified by mount point, inode number,
2032  *         and logical block.
2033  *      2) inodedep structures identified by mount point and inode number.
2034  *      3) newblk structures identified by mount point and
2035  *         physical block number.
2036  *
2037  * The "pagedep" and "inodedep" dependency structures are hashed
2038  * separately from the file blocks and inodes to which they correspond.
2039  * This separation helps when the in-memory copy of an inode or
2040  * file block must be replaced. It also obviates the need to access
2041  * an inode or file page when simply updating (or de-allocating)
2042  * dependency structures. Lookup of newblk structures is needed to
2043  * find newly allocated blocks when trying to associate them with
2044  * their allocdirect or allocindir structure.
2045  *
2046  * The lookup routines optionally create and hash a new instance when
2047  * an existing entry is not found.
2048  */
2049 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2050 #define NODELAY         0x0002  /* cannot do background work */
2051
2052 /*
2053  * Structures and routines associated with pagedep caching.
2054  */
2055 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
2056 u_long  pagedep_hash;           /* size of hash table - 1 */
2057 #define PAGEDEP_HASH(mp, inum, lbn) \
2058         (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
2059             pagedep_hash])
2060
2061 static int
2062 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
2063         struct pagedep_hashhead *pagedephd;
2064         ino_t ino;
2065         ufs_lbn_t lbn;
2066         struct mount *mp;
2067         int flags;
2068         struct pagedep **pagedeppp;
2069 {
2070         struct pagedep *pagedep;
2071
2072         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2073                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn &&
2074                     mp == pagedep->pd_list.wk_mp) {
2075                         *pagedeppp = pagedep;
2076                         return (1);
2077                 }
2078         }
2079         *pagedeppp = NULL;
2080         return (0);
2081 }
2082 /*
2083  * Look up a pagedep. Return 1 if found, 0 otherwise.
2084  * If not found, allocate if DEPALLOC flag is passed.
2085  * Found or allocated entry is returned in pagedeppp.
2086  * This routine must be called with splbio interrupts blocked.
2087  */
2088 static int
2089 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2090         struct mount *mp;
2091         struct buf *bp;
2092         ino_t ino;
2093         ufs_lbn_t lbn;
2094         int flags;
2095         struct pagedep **pagedeppp;
2096 {
2097         struct pagedep *pagedep;
2098         struct pagedep_hashhead *pagedephd;
2099         struct worklist *wk;
2100         int ret;
2101         int i;
2102
2103         mtx_assert(&lk, MA_OWNED);
2104         if (bp) {
2105                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2106                         if (wk->wk_type == D_PAGEDEP) {
2107                                 *pagedeppp = WK_PAGEDEP(wk);
2108                                 return (1);
2109                         }
2110                 }
2111         }
2112         pagedephd = PAGEDEP_HASH(mp, ino, lbn);
2113         ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2114         if (ret) {
2115                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2116                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2117                 return (1);
2118         }
2119         if ((flags & DEPALLOC) == 0)
2120                 return (0);
2121         FREE_LOCK(&lk);
2122         pagedep = malloc(sizeof(struct pagedep),
2123             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2124         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2125         ACQUIRE_LOCK(&lk);
2126         ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2127         if (*pagedeppp) {
2128                 /*
2129                  * This should never happen since we only create pagedeps
2130                  * with the vnode lock held.  Could be an assert.
2131                  */
2132                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2133                 return (ret);
2134         }
2135         pagedep->pd_ino = ino;
2136         pagedep->pd_lbn = lbn;
2137         LIST_INIT(&pagedep->pd_dirremhd);
2138         LIST_INIT(&pagedep->pd_pendinghd);
2139         for (i = 0; i < DAHASHSZ; i++)
2140                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2141         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2142         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2143         *pagedeppp = pagedep;
2144         return (0);
2145 }
2146
2147 /*
2148  * Structures and routines associated with inodedep caching.
2149  */
2150 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
2151 static u_long   inodedep_hash;  /* size of hash table - 1 */
2152 #define INODEDEP_HASH(fs, inum) \
2153       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
2154
2155 static int
2156 inodedep_find(inodedephd, fs, inum, inodedeppp)
2157         struct inodedep_hashhead *inodedephd;
2158         struct fs *fs;
2159         ino_t inum;
2160         struct inodedep **inodedeppp;
2161 {
2162         struct inodedep *inodedep;
2163
2164         LIST_FOREACH(inodedep, inodedephd, id_hash)
2165                 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
2166                         break;
2167         if (inodedep) {
2168                 *inodedeppp = inodedep;
2169                 return (1);
2170         }
2171         *inodedeppp = NULL;
2172
2173         return (0);
2174 }
2175 /*
2176  * Look up an inodedep. Return 1 if found, 0 if not found.
2177  * If not found, allocate if DEPALLOC flag is passed.
2178  * Found or allocated entry is returned in inodedeppp.
2179  * This routine must be called with splbio interrupts blocked.
2180  */
2181 static int
2182 inodedep_lookup(mp, inum, flags, inodedeppp)
2183         struct mount *mp;
2184         ino_t inum;
2185         int flags;
2186         struct inodedep **inodedeppp;
2187 {
2188         struct inodedep *inodedep;
2189         struct inodedep_hashhead *inodedephd;
2190         struct fs *fs;
2191
2192         mtx_assert(&lk, MA_OWNED);
2193         fs = VFSTOUFS(mp)->um_fs;
2194         inodedephd = INODEDEP_HASH(fs, inum);
2195
2196         if (inodedep_find(inodedephd, fs, inum, inodedeppp))
2197                 return (1);
2198         if ((flags & DEPALLOC) == 0)
2199                 return (0);
2200         /*
2201          * If we are over our limit, try to improve the situation.
2202          */
2203         if (dep_current[D_INODEDEP] > max_softdeps && (flags & NODELAY) == 0)
2204                 request_cleanup(mp, FLUSH_INODES);
2205         FREE_LOCK(&lk);
2206         inodedep = malloc(sizeof(struct inodedep),
2207                 M_INODEDEP, M_SOFTDEP_FLAGS);
2208         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2209         ACQUIRE_LOCK(&lk);
2210         if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
2211                 WORKITEM_FREE(inodedep, D_INODEDEP);
2212                 return (1);
2213         }
2214         inodedep->id_fs = fs;
2215         inodedep->id_ino = inum;
2216         inodedep->id_state = ALLCOMPLETE;
2217         inodedep->id_nlinkdelta = 0;
2218         inodedep->id_savedino1 = NULL;
2219         inodedep->id_savedsize = -1;
2220         inodedep->id_savedextsize = -1;
2221         inodedep->id_savednlink = -1;
2222         inodedep->id_bmsafemap = NULL;
2223         inodedep->id_mkdiradd = NULL;
2224         LIST_INIT(&inodedep->id_dirremhd);
2225         LIST_INIT(&inodedep->id_pendinghd);
2226         LIST_INIT(&inodedep->id_inowait);
2227         LIST_INIT(&inodedep->id_bufwait);
2228         TAILQ_INIT(&inodedep->id_inoreflst);
2229         TAILQ_INIT(&inodedep->id_inoupdt);
2230         TAILQ_INIT(&inodedep->id_newinoupdt);
2231         TAILQ_INIT(&inodedep->id_extupdt);
2232         TAILQ_INIT(&inodedep->id_newextupdt);
2233         TAILQ_INIT(&inodedep->id_freeblklst);
2234         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2235         *inodedeppp = inodedep;
2236         return (0);
2237 }
2238
2239 /*
2240  * Structures and routines associated with newblk caching.
2241  */
2242 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
2243 u_long  newblk_hash;            /* size of hash table - 1 */
2244 #define NEWBLK_HASH(fs, inum) \
2245         (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
2246
2247 static int
2248 newblk_find(newblkhd, mp, newblkno, flags, newblkpp)
2249         struct newblk_hashhead *newblkhd;
2250         struct mount *mp;
2251         ufs2_daddr_t newblkno;
2252         int flags;
2253         struct newblk **newblkpp;
2254 {
2255         struct newblk *newblk;
2256
2257         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2258                 if (newblkno != newblk->nb_newblkno)
2259                         continue;
2260                 if (mp != newblk->nb_list.wk_mp)
2261                         continue;
2262                 /*
2263                  * If we're creating a new dependency don't match those that
2264                  * have already been converted to allocdirects.  This is for
2265                  * a frag extend.
2266                  */
2267                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2268                         continue;
2269                 break;
2270         }
2271         if (newblk) {
2272                 *newblkpp = newblk;
2273                 return (1);
2274         }
2275         *newblkpp = NULL;
2276         return (0);
2277 }
2278
2279 /*
2280  * Look up a newblk. Return 1 if found, 0 if not found.
2281  * If not found, allocate if DEPALLOC flag is passed.
2282  * Found or allocated entry is returned in newblkpp.
2283  */
2284 static int
2285 newblk_lookup(mp, newblkno, flags, newblkpp)
2286         struct mount *mp;
2287         ufs2_daddr_t newblkno;
2288         int flags;
2289         struct newblk **newblkpp;
2290 {
2291         struct newblk *newblk;
2292         struct newblk_hashhead *newblkhd;
2293
2294         newblkhd = NEWBLK_HASH(VFSTOUFS(mp)->um_fs, newblkno);
2295         if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp))
2296                 return (1);
2297         if ((flags & DEPALLOC) == 0)
2298                 return (0);
2299         FREE_LOCK(&lk);
2300         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2301             M_SOFTDEP_FLAGS | M_ZERO);
2302         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2303         ACQUIRE_LOCK(&lk);
2304         if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp)) {
2305                 WORKITEM_FREE(newblk, D_NEWBLK);
2306                 return (1);
2307         }
2308         newblk->nb_freefrag = NULL;
2309         LIST_INIT(&newblk->nb_indirdeps);
2310         LIST_INIT(&newblk->nb_newdirblk);
2311         LIST_INIT(&newblk->nb_jwork);
2312         newblk->nb_state = ATTACHED;
2313         newblk->nb_newblkno = newblkno;
2314         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2315         *newblkpp = newblk;
2316         return (0);
2317 }
2318
2319 /*
2320  * Structures and routines associated with freed indirect block caching.
2321  */
2322 struct freeworklst *indir_hashtbl;
2323 u_long  indir_hash;             /* size of hash table - 1 */
2324 #define INDIR_HASH(mp, blkno) \
2325         (&indir_hashtbl[((((register_t)(mp)) >> 13) + (blkno)) & indir_hash])
2326
2327 /*
2328  * Lookup an indirect block in the indir hash table.  The freework is
2329  * removed and potentially freed.  The caller must do a blocking journal
2330  * write before writing to the blkno.
2331  */
2332 static int
2333 indirblk_lookup(mp, blkno)
2334         struct mount *mp;
2335         ufs2_daddr_t blkno;
2336 {
2337         struct freework *freework;
2338         struct freeworklst *wkhd;
2339
2340         wkhd = INDIR_HASH(mp, blkno);
2341         TAILQ_FOREACH(freework, wkhd, fw_next) {
2342                 if (freework->fw_blkno != blkno)
2343                         continue;
2344                 if (freework->fw_list.wk_mp != mp)
2345                         continue;
2346                 indirblk_remove(freework);
2347                 return (1);
2348         }
2349         return (0);
2350 }
2351
2352 /*
2353  * Insert an indirect block represented by freework into the indirblk
2354  * hash table so that it may prevent the block from being re-used prior
2355  * to the journal being written.
2356  */
2357 static void
2358 indirblk_insert(freework)
2359         struct freework *freework;
2360 {
2361         struct jblocks *jblocks;
2362         struct jseg *jseg;
2363
2364         jblocks = VFSTOUFS(freework->fw_list.wk_mp)->softdep_jblocks;
2365         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2366         if (jseg == NULL)
2367                 return;
2368         
2369         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2370         TAILQ_INSERT_HEAD(INDIR_HASH(freework->fw_list.wk_mp,
2371             freework->fw_blkno), freework, fw_next);
2372         freework->fw_state &= ~DEPCOMPLETE;
2373 }
2374
2375 static void
2376 indirblk_remove(freework)
2377         struct freework *freework;
2378 {
2379
2380         LIST_REMOVE(freework, fw_segs);
2381         TAILQ_REMOVE(INDIR_HASH(freework->fw_list.wk_mp,
2382             freework->fw_blkno), freework, fw_next);
2383         freework->fw_state |= DEPCOMPLETE;
2384         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2385                 WORKITEM_FREE(freework, D_FREEWORK);
2386 }
2387
2388 /*
2389  * Executed during filesystem system initialization before
2390  * mounting any filesystems.
2391  */
2392 void 
2393 softdep_initialize()
2394 {
2395         int i;
2396
2397         LIST_INIT(&mkdirlisthd);
2398         max_softdeps = desiredvnodes * 4;
2399         pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP, &pagedep_hash);
2400         inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
2401         newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK, &newblk_hash);
2402         bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP, &bmsafemap_hash);
2403         i = 1 << (ffs(desiredvnodes / 10) - 1);
2404         indir_hashtbl = malloc(i * sizeof(indir_hashtbl[0]), M_FREEWORK,
2405             M_WAITOK);
2406         indir_hash = i - 1;
2407         for (i = 0; i <= indir_hash; i++)
2408                 TAILQ_INIT(&indir_hashtbl[i]);
2409
2410         /* initialise bioops hack */
2411         bioops.io_start = softdep_disk_io_initiation;
2412         bioops.io_complete = softdep_disk_write_complete;
2413         bioops.io_deallocate = softdep_deallocate_dependencies;
2414         bioops.io_countdeps = softdep_count_dependencies;
2415
2416         /* Initialize the callout with an mtx. */
2417         callout_init_mtx(&softdep_callout, &lk, 0);
2418 }
2419
2420 /*
2421  * Executed after all filesystems have been unmounted during
2422  * filesystem module unload.
2423  */
2424 void
2425 softdep_uninitialize()
2426 {
2427
2428         callout_drain(&softdep_callout);
2429         hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
2430         hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
2431         hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
2432         hashdestroy(bmsafemap_hashtbl, M_BMSAFEMAP, bmsafemap_hash);
2433         free(indir_hashtbl, M_FREEWORK);
2434 }
2435
2436 /*
2437  * Called at mount time to notify the dependency code that a
2438  * filesystem wishes to use it.
2439  */
2440 int
2441 softdep_mount(devvp, mp, fs, cred)
2442         struct vnode *devvp;
2443         struct mount *mp;
2444         struct fs *fs;
2445         struct ucred *cred;
2446 {
2447         struct csum_total cstotal;
2448         struct ufsmount *ump;
2449         struct cg *cgp;
2450         struct buf *bp;
2451         int error, cyl;
2452
2453         MNT_ILOCK(mp);
2454         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2455         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2456                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2457                         MNTK_SOFTDEP | MNTK_NOASYNC;
2458         }
2459         MNT_IUNLOCK(mp);
2460         ump = VFSTOUFS(mp);
2461         LIST_INIT(&ump->softdep_workitem_pending);
2462         LIST_INIT(&ump->softdep_journal_pending);
2463         TAILQ_INIT(&ump->softdep_unlinked);
2464         LIST_INIT(&ump->softdep_dirtycg);
2465         ump->softdep_worklist_tail = NULL;
2466         ump->softdep_on_worklist = 0;
2467         ump->softdep_deps = 0;
2468         if ((fs->fs_flags & FS_SUJ) &&
2469             (error = journal_mount(mp, fs, cred)) != 0) {
2470                 printf("Failed to start journal: %d\n", error);
2471                 return (error);
2472         }
2473         /*
2474          * When doing soft updates, the counters in the
2475          * superblock may have gotten out of sync. Recomputation
2476          * can take a long time and can be deferred for background
2477          * fsck.  However, the old behavior of scanning the cylinder
2478          * groups and recalculating them at mount time is available
2479          * by setting vfs.ffs.compute_summary_at_mount to one.
2480          */
2481         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2482                 return (0);
2483         bzero(&cstotal, sizeof cstotal);
2484         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2485                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2486                     fs->fs_cgsize, cred, &bp)) != 0) {
2487                         brelse(bp);
2488                         return (error);
2489                 }
2490                 cgp = (struct cg *)bp->b_data;
2491                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2492                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2493                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2494                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2495                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2496                 brelse(bp);
2497         }
2498 #ifdef DEBUG
2499         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2500                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2501 #endif
2502         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2503         return (0);
2504 }
2505
2506 void
2507 softdep_unmount(mp)
2508         struct mount *mp;
2509 {
2510
2511         MNT_ILOCK(mp);
2512         mp->mnt_flag &= ~MNT_SOFTDEP;
2513         if (MOUNTEDSUJ(mp) == 0) {
2514                 MNT_IUNLOCK(mp);
2515                 return;
2516         }
2517         mp->mnt_flag &= ~MNT_SUJ;
2518         MNT_IUNLOCK(mp);
2519         journal_unmount(mp);
2520 }
2521
2522 static struct jblocks *
2523 jblocks_create(void)
2524 {
2525         struct jblocks *jblocks;
2526
2527         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2528         TAILQ_INIT(&jblocks->jb_segs);
2529         jblocks->jb_avail = 10;
2530         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2531             M_JBLOCKS, M_WAITOK | M_ZERO);
2532
2533         return (jblocks);
2534 }
2535
2536 static ufs2_daddr_t
2537 jblocks_alloc(jblocks, bytes, actual)
2538         struct jblocks *jblocks;
2539         int bytes;
2540         int *actual;
2541 {
2542         ufs2_daddr_t daddr;
2543         struct jextent *jext;
2544         int freecnt;
2545         int blocks;
2546
2547         blocks = bytes / DEV_BSIZE;
2548         jext = &jblocks->jb_extent[jblocks->jb_head];
2549         freecnt = jext->je_blocks - jblocks->jb_off;
2550         if (freecnt == 0) {
2551                 jblocks->jb_off = 0;
2552                 if (++jblocks->jb_head > jblocks->jb_used)
2553                         jblocks->jb_head = 0;
2554                 jext = &jblocks->jb_extent[jblocks->jb_head];
2555                 freecnt = jext->je_blocks;
2556         }
2557         if (freecnt > blocks)
2558                 freecnt = blocks;
2559         *actual = freecnt * DEV_BSIZE;
2560         daddr = jext->je_daddr + jblocks->jb_off;
2561         jblocks->jb_off += freecnt;
2562         jblocks->jb_free -= freecnt;
2563
2564         return (daddr);
2565 }
2566
2567 static void
2568 jblocks_free(jblocks, mp, bytes)
2569         struct jblocks *jblocks;
2570         struct mount *mp;
2571         int bytes;
2572 {
2573
2574         jblocks->jb_free += bytes / DEV_BSIZE;
2575         if (jblocks->jb_suspended)
2576                 worklist_speedup();
2577         wakeup(jblocks);
2578 }
2579
2580 static void
2581 jblocks_destroy(jblocks)
2582         struct jblocks *jblocks;
2583 {
2584
2585         if (jblocks->jb_extent)
2586                 free(jblocks->jb_extent, M_JBLOCKS);
2587         free(jblocks, M_JBLOCKS);
2588 }
2589
2590 static void
2591 jblocks_add(jblocks, daddr, blocks)
2592         struct jblocks *jblocks;
2593         ufs2_daddr_t daddr;
2594         int blocks;
2595 {
2596         struct jextent *jext;
2597
2598         jblocks->jb_blocks += blocks;
2599         jblocks->jb_free += blocks;
2600         jext = &jblocks->jb_extent[jblocks->jb_used];
2601         /* Adding the first block. */
2602         if (jext->je_daddr == 0) {
2603                 jext->je_daddr = daddr;
2604                 jext->je_blocks = blocks;
2605                 return;
2606         }
2607         /* Extending the last extent. */
2608         if (jext->je_daddr + jext->je_blocks == daddr) {
2609                 jext->je_blocks += blocks;
2610                 return;
2611         }
2612         /* Adding a new extent. */
2613         if (++jblocks->jb_used == jblocks->jb_avail) {
2614                 jblocks->jb_avail *= 2;
2615                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2616                     M_JBLOCKS, M_WAITOK | M_ZERO);
2617                 memcpy(jext, jblocks->jb_extent,
2618                     sizeof(struct jextent) * jblocks->jb_used);
2619                 free(jblocks->jb_extent, M_JBLOCKS);
2620                 jblocks->jb_extent = jext;
2621         }
2622         jext = &jblocks->jb_extent[jblocks->jb_used];
2623         jext->je_daddr = daddr;
2624         jext->je_blocks = blocks;
2625         return;
2626 }
2627
2628 int
2629 softdep_journal_lookup(mp, vpp)
2630         struct mount *mp;
2631         struct vnode **vpp;
2632 {
2633         struct componentname cnp;
2634         struct vnode *dvp;
2635         ino_t sujournal;
2636         int error;
2637
2638         error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2639         if (error)
2640                 return (error);
2641         bzero(&cnp, sizeof(cnp));
2642         cnp.cn_nameiop = LOOKUP;
2643         cnp.cn_flags = ISLASTCN;
2644         cnp.cn_thread = curthread;
2645         cnp.cn_cred = curthread->td_ucred;
2646         cnp.cn_pnbuf = SUJ_FILE;
2647         cnp.cn_nameptr = SUJ_FILE;
2648         cnp.cn_namelen = strlen(SUJ_FILE);
2649         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2650         vput(dvp);
2651         if (error != 0)
2652                 return (error);
2653         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2654         return (error);
2655 }
2656
2657 /*
2658  * Open and verify the journal file.
2659  */
2660 static int
2661 journal_mount(mp, fs, cred)
2662         struct mount *mp;
2663         struct fs *fs;
2664         struct ucred *cred;
2665 {
2666         struct jblocks *jblocks;
2667         struct vnode *vp;
2668         struct inode *ip;
2669         ufs2_daddr_t blkno;
2670         int bcount;
2671         int error;
2672         int i;
2673
2674         error = softdep_journal_lookup(mp, &vp);
2675         if (error != 0) {
2676                 printf("Failed to find journal.  Use tunefs to create one\n");
2677                 return (error);
2678         }
2679         ip = VTOI(vp);
2680         if (ip->i_size < SUJ_MIN) {
2681                 error = ENOSPC;
2682                 goto out;
2683         }
2684         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2685         jblocks = jblocks_create();
2686         for (i = 0; i < bcount; i++) {
2687                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2688                 if (error)
2689                         break;
2690                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2691         }
2692         if (error) {
2693                 jblocks_destroy(jblocks);
2694                 goto out;
2695         }
2696         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2697         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2698         VFSTOUFS(mp)->softdep_jblocks = jblocks;
2699 out:
2700         if (error == 0) {
2701                 MNT_ILOCK(mp);
2702                 mp->mnt_flag |= MNT_SUJ;
2703                 mp->mnt_flag &= ~MNT_SOFTDEP;
2704                 MNT_IUNLOCK(mp);
2705                 /*
2706                  * Only validate the journal contents if the
2707                  * filesystem is clean, otherwise we write the logs
2708                  * but they'll never be used.  If the filesystem was
2709                  * still dirty when we mounted it the journal is
2710                  * invalid and a new journal can only be valid if it
2711                  * starts from a clean mount.
2712                  */
2713                 if (fs->fs_clean) {
2714                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2715                         ip->i_flags |= IN_MODIFIED;
2716                         ffs_update(vp, 1);
2717                 }
2718         }
2719         vput(vp);
2720         return (error);
2721 }
2722
2723 static void
2724 journal_unmount(mp)
2725         struct mount *mp;
2726 {
2727         struct ufsmount *ump;
2728
2729         ump = VFSTOUFS(mp);
2730         if (ump->softdep_jblocks)
2731                 jblocks_destroy(ump->softdep_jblocks);
2732         ump->softdep_jblocks = NULL;
2733 }
2734
2735 /*
2736  * Called when a journal record is ready to be written.  Space is allocated
2737  * and the journal entry is created when the journal is flushed to stable
2738  * store.
2739  */
2740 static void
2741 add_to_journal(wk)
2742         struct worklist *wk;
2743 {
2744         struct ufsmount *ump;
2745
2746         mtx_assert(&lk, MA_OWNED);
2747         ump = VFSTOUFS(wk->wk_mp);
2748         if (wk->wk_state & ONWORKLIST)
2749                 panic("add_to_journal: %s(0x%X) already on list",
2750                     TYPENAME(wk->wk_type), wk->wk_state);
2751         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2752         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2753                 ump->softdep_jblocks->jb_age = ticks;
2754                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2755         } else
2756                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2757         ump->softdep_journal_tail = wk;
2758         ump->softdep_on_journal += 1;
2759 }
2760
2761 /*
2762  * Remove an arbitrary item for the journal worklist maintain the tail
2763  * pointer.  This happens when a new operation obviates the need to
2764  * journal an old operation.
2765  */
2766 static void
2767 remove_from_journal(wk)
2768         struct worklist *wk;
2769 {
2770         struct ufsmount *ump;
2771
2772         mtx_assert(&lk, MA_OWNED);
2773         ump = VFSTOUFS(wk->wk_mp);
2774 #ifdef SUJ_DEBUG
2775         {
2776                 struct worklist *wkn;
2777
2778                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2779                         if (wkn == wk)
2780                                 break;
2781                 if (wkn == NULL)
2782                         panic("remove_from_journal: %p is not in journal", wk);
2783         }
2784 #endif
2785         /*
2786          * We emulate a TAILQ to save space in most structures which do not
2787          * require TAILQ semantics.  Here we must update the tail position
2788          * when removing the tail which is not the final entry. This works
2789          * only if the worklist linkage are at the beginning of the structure.
2790          */
2791         if (ump->softdep_journal_tail == wk)
2792                 ump->softdep_journal_tail =
2793                     (struct worklist *)wk->wk_list.le_prev;
2794
2795         WORKLIST_REMOVE(wk);
2796         ump->softdep_on_journal -= 1;
2797 }
2798
2799 /*
2800  * Check for journal space as well as dependency limits so the prelink
2801  * code can throttle both journaled and non-journaled filesystems.
2802  * Threshold is 0 for low and 1 for min.
2803  */
2804 static int
2805 journal_space(ump, thresh)
2806         struct ufsmount *ump;
2807         int thresh;
2808 {
2809         struct jblocks *jblocks;
2810         int avail;
2811
2812         jblocks = ump->softdep_jblocks;
2813         if (jblocks == NULL)
2814                 return (1);
2815         /*
2816          * We use a tighter restriction here to prevent request_cleanup()
2817          * running in threads from running into locks we currently hold.
2818          */
2819         if (dep_current[D_INODEDEP] > (max_softdeps / 10) * 9)
2820                 return (0);
2821         if (thresh)
2822                 thresh = jblocks->jb_min;
2823         else
2824                 thresh = jblocks->jb_low;
2825         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2826         avail = jblocks->jb_free - avail;
2827
2828         return (avail > thresh);
2829 }
2830
2831 static void
2832 journal_suspend(ump)
2833         struct ufsmount *ump;
2834 {
2835         struct jblocks *jblocks;
2836         struct mount *mp;
2837
2838         mp = UFSTOVFS(ump);
2839         jblocks = ump->softdep_jblocks;
2840         MNT_ILOCK(mp);
2841         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2842                 stat_journal_min++;
2843                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2844                 mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2845         }
2846         jblocks->jb_suspended = 1;
2847         MNT_IUNLOCK(mp);
2848 }
2849
2850 static int
2851 journal_unsuspend(struct ufsmount *ump)
2852 {
2853         struct jblocks *jblocks;
2854         struct mount *mp;
2855
2856         mp = UFSTOVFS(ump);
2857         jblocks = ump->softdep_jblocks;
2858
2859         if (jblocks != NULL && jblocks->jb_suspended &&
2860             journal_space(ump, jblocks->jb_min)) {
2861                 jblocks->jb_suspended = 0;
2862                 FREE_LOCK(&lk);
2863                 mp->mnt_susp_owner = curthread;
2864                 vfs_write_resume(mp);
2865                 ACQUIRE_LOCK(&lk);
2866                 return (1);
2867         }
2868         return (0);
2869 }
2870
2871 /*
2872  * Called before any allocation function to be certain that there is
2873  * sufficient space in the journal prior to creating any new records.
2874  * Since in the case of block allocation we may have multiple locked
2875  * buffers at the time of the actual allocation we can not block
2876  * when the journal records are created.  Doing so would create a deadlock
2877  * if any of these buffers needed to be flushed to reclaim space.  Instead
2878  * we require a sufficiently large amount of available space such that
2879  * each thread in the system could have passed this allocation check and
2880  * still have sufficient free space.  With 20% of a minimum journal size
2881  * of 1MB we have 6553 records available.
2882  */
2883 int
2884 softdep_prealloc(vp, waitok)
2885         struct vnode *vp;
2886         int waitok;
2887 {
2888         struct ufsmount *ump;
2889
2890         /*
2891          * Nothing to do if we are not running journaled soft updates.
2892          * If we currently hold the snapshot lock, we must avoid handling
2893          * other resources that could cause deadlock.
2894          */
2895         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
2896                 return (0);
2897         ump = VFSTOUFS(vp->v_mount);
2898         ACQUIRE_LOCK(&lk);
2899         if (journal_space(ump, 0)) {
2900                 FREE_LOCK(&lk);
2901                 return (0);
2902         }
2903         stat_journal_low++;
2904         FREE_LOCK(&lk);
2905         if (waitok == MNT_NOWAIT)
2906                 return (ENOSPC);
2907         /*
2908          * Attempt to sync this vnode once to flush any journal
2909          * work attached to it.
2910          */
2911         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2912                 ffs_syncvnode(vp, waitok, 0);
2913         ACQUIRE_LOCK(&lk);
2914         process_removes(vp);
2915         process_truncates(vp);
2916         if (journal_space(ump, 0) == 0) {
2917                 softdep_speedup();
2918                 if (journal_space(ump, 1) == 0)
2919                         journal_suspend(ump);
2920         }
2921         FREE_LOCK(&lk);
2922
2923         return (0);
2924 }
2925
2926 /*
2927  * Before adjusting a link count on a vnode verify that we have sufficient
2928  * journal space.  If not, process operations that depend on the currently
2929  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2930  * and softdep flush threads can not acquire these locks to reclaim space.
2931  */
2932 static void
2933 softdep_prelink(dvp, vp)
2934         struct vnode *dvp;
2935         struct vnode *vp;
2936 {
2937         struct ufsmount *ump;
2938
2939         ump = VFSTOUFS(dvp->v_mount);
2940         mtx_assert(&lk, MA_OWNED);
2941         /*
2942          * Nothing to do if we have sufficient journal space.
2943          * If we currently hold the snapshot lock, we must avoid
2944          * handling other resources that could cause deadlock.
2945          */
2946         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
2947                 return;
2948         stat_journal_low++;
2949         FREE_LOCK(&lk);
2950         if (vp)
2951                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
2952         ffs_syncvnode(dvp, MNT_WAIT, 0);
2953         ACQUIRE_LOCK(&lk);
2954         /* Process vp before dvp as it may create .. removes. */
2955         if (vp) {
2956                 process_removes(vp);
2957                 process_truncates(vp);
2958         }
2959         process_removes(dvp);
2960         process_truncates(dvp);
2961         softdep_speedup();
2962         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
2963         if (journal_space(ump, 0) == 0) {
2964                 softdep_speedup();
2965                 if (journal_space(ump, 1) == 0)
2966                         journal_suspend(ump);
2967         }
2968 }
2969
2970 static void
2971 jseg_write(ump, jseg, data)
2972         struct ufsmount *ump;
2973         struct jseg *jseg;
2974         uint8_t *data;
2975 {
2976         struct jsegrec *rec;
2977
2978         rec = (struct jsegrec *)data;
2979         rec->jsr_seq = jseg->js_seq;
2980         rec->jsr_oldest = jseg->js_oldseq;
2981         rec->jsr_cnt = jseg->js_cnt;
2982         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
2983         rec->jsr_crc = 0;
2984         rec->jsr_time = ump->um_fs->fs_mtime;
2985 }
2986
2987 static inline void
2988 inoref_write(inoref, jseg, rec)
2989         struct inoref *inoref;
2990         struct jseg *jseg;
2991         struct jrefrec *rec;
2992 {
2993
2994         inoref->if_jsegdep->jd_seg = jseg;
2995         rec->jr_ino = inoref->if_ino;
2996         rec->jr_parent = inoref->if_parent;
2997         rec->jr_nlink = inoref->if_nlink;
2998         rec->jr_mode = inoref->if_mode;
2999         rec->jr_diroff = inoref->if_diroff;
3000 }
3001
3002 static void
3003 jaddref_write(jaddref, jseg, data)
3004         struct jaddref *jaddref;
3005         struct jseg *jseg;
3006         uint8_t *data;
3007 {
3008         struct jrefrec *rec;
3009
3010         rec = (struct jrefrec *)data;
3011         rec->jr_op = JOP_ADDREF;
3012         inoref_write(&jaddref->ja_ref, jseg, rec);
3013 }
3014
3015 static void
3016 jremref_write(jremref, jseg, data)
3017         struct jremref *jremref;
3018         struct jseg *jseg;
3019         uint8_t *data;
3020 {
3021         struct jrefrec *rec;
3022
3023         rec = (struct jrefrec *)data;
3024         rec->jr_op = JOP_REMREF;
3025         inoref_write(&jremref->jr_ref, jseg, rec);
3026 }
3027
3028 static void
3029 jmvref_write(jmvref, jseg, data)
3030         struct jmvref *jmvref;
3031         struct jseg *jseg;
3032         uint8_t *data;
3033 {
3034         struct jmvrec *rec;
3035
3036         rec = (struct jmvrec *)data;
3037         rec->jm_op = JOP_MVREF;
3038         rec->jm_ino = jmvref->jm_ino;
3039         rec->jm_parent = jmvref->jm_parent;
3040         rec->jm_oldoff = jmvref->jm_oldoff;
3041         rec->jm_newoff = jmvref->jm_newoff;
3042 }
3043
3044 static void
3045 jnewblk_write(jnewblk, jseg, data)
3046         struct jnewblk *jnewblk;
3047         struct jseg *jseg;
3048         uint8_t *data;
3049 {
3050         struct jblkrec *rec;
3051
3052         jnewblk->jn_jsegdep->jd_seg = jseg;
3053         rec = (struct jblkrec *)data;
3054         rec->jb_op = JOP_NEWBLK;
3055         rec->jb_ino = jnewblk->jn_ino;
3056         rec->jb_blkno = jnewblk->jn_blkno;
3057         rec->jb_lbn = jnewblk->jn_lbn;
3058         rec->jb_frags = jnewblk->jn_frags;
3059         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3060 }
3061
3062 static void
3063 jfreeblk_write(jfreeblk, jseg, data)
3064         struct jfreeblk *jfreeblk;
3065         struct jseg *jseg;
3066         uint8_t *data;
3067 {
3068         struct jblkrec *rec;
3069
3070         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3071         rec = (struct jblkrec *)data;
3072         rec->jb_op = JOP_FREEBLK;
3073         rec->jb_ino = jfreeblk->jf_ino;
3074         rec->jb_blkno = jfreeblk->jf_blkno;
3075         rec->jb_lbn = jfreeblk->jf_lbn;
3076         rec->jb_frags = jfreeblk->jf_frags;
3077         rec->jb_oldfrags = 0;
3078 }
3079
3080 static void
3081 jfreefrag_write(jfreefrag, jseg, data)
3082         struct jfreefrag *jfreefrag;
3083         struct jseg *jseg;
3084         uint8_t *data;
3085 {
3086         struct jblkrec *rec;
3087
3088         jfreefrag->fr_jsegdep->jd_seg = jseg;
3089         rec = (struct jblkrec *)data;
3090         rec->jb_op = JOP_FREEBLK;
3091         rec->jb_ino = jfreefrag->fr_ino;
3092         rec->jb_blkno = jfreefrag->fr_blkno;
3093         rec->jb_lbn = jfreefrag->fr_lbn;
3094         rec->jb_frags = jfreefrag->fr_frags;
3095         rec->jb_oldfrags = 0;
3096 }
3097
3098 static void
3099 jtrunc_write(jtrunc, jseg, data)
3100         struct jtrunc *jtrunc;
3101         struct jseg *jseg;
3102         uint8_t *data;
3103 {
3104         struct jtrncrec *rec;
3105
3106         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3107         rec = (struct jtrncrec *)data;
3108         rec->jt_op = JOP_TRUNC;
3109         rec->jt_ino = jtrunc->jt_ino;
3110         rec->jt_size = jtrunc->jt_size;
3111         rec->jt_extsize = jtrunc->jt_extsize;
3112 }
3113
3114 static void
3115 jfsync_write(jfsync, jseg, data)
3116         struct jfsync *jfsync;
3117         struct jseg *jseg;
3118         uint8_t *data;
3119 {
3120         struct jtrncrec *rec;
3121
3122         rec = (struct jtrncrec *)data;
3123         rec->jt_op = JOP_SYNC;
3124         rec->jt_ino = jfsync->jfs_ino;
3125         rec->jt_size = jfsync->jfs_size;
3126         rec->jt_extsize = jfsync->jfs_extsize;
3127 }
3128
3129 static void
3130 softdep_flushjournal(mp)
3131         struct mount *mp;
3132 {
3133         struct jblocks *jblocks;
3134         struct ufsmount *ump;
3135
3136         if (MOUNTEDSUJ(mp) == 0)
3137                 return;
3138         ump = VFSTOUFS(mp);
3139         jblocks = ump->softdep_jblocks;
3140         ACQUIRE_LOCK(&lk);
3141         while (ump->softdep_on_journal) {
3142                 jblocks->jb_needseg = 1;
3143                 softdep_process_journal(mp, NULL, MNT_WAIT);
3144         }
3145         FREE_LOCK(&lk);
3146 }
3147
3148 static void softdep_synchronize_completed(struct bio *);
3149 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3150
3151 static void
3152 softdep_synchronize_completed(bp)
3153         struct bio *bp;
3154 {
3155         struct jseg *oldest;
3156         struct jseg *jseg;
3157
3158         /*
3159          * caller1 marks the last segment written before we issued the
3160          * synchronize cache.
3161          */
3162         jseg = bp->bio_caller1;
3163         oldest = NULL;
3164         ACQUIRE_LOCK(&lk);
3165         /*
3166          * Mark all the journal entries waiting on the synchronize cache
3167          * as completed so they may continue on.
3168          */
3169         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3170                 jseg->js_state |= COMPLETE;
3171                 oldest = jseg;
3172                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3173         }
3174         /*
3175          * Restart deferred journal entry processing from the oldest
3176          * completed jseg.
3177          */
3178         if (oldest)
3179                 complete_jsegs(oldest);
3180
3181         FREE_LOCK(&lk);
3182         g_destroy_bio(bp);
3183 }
3184
3185 /*
3186  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3187  * barriers.  The journal must be written prior to any blocks that depend
3188  * on it and the journal can not be released until the blocks have be
3189  * written.  This code handles both barriers simultaneously.
3190  */
3191 static void
3192 softdep_synchronize(bp, ump, caller1)
3193         struct bio *bp;
3194         struct ufsmount *ump;
3195         void *caller1;
3196 {
3197
3198         bp->bio_cmd = BIO_FLUSH;
3199         bp->bio_flags |= BIO_ORDERED;
3200         bp->bio_data = NULL;
3201         bp->bio_offset = ump->um_cp->provider->mediasize;
3202         bp->bio_length = 0;
3203         bp->bio_done = softdep_synchronize_completed;
3204         bp->bio_caller1 = caller1;
3205         g_io_request(bp,
3206             (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3207 }
3208
3209 /*
3210  * Flush some journal records to disk.
3211  */
3212 static void
3213 softdep_process_journal(mp, needwk, flags)
3214         struct mount *mp;
3215         struct worklist *needwk;
3216         int flags;
3217 {
3218         struct jblocks *jblocks;
3219         struct ufsmount *ump;
3220         struct worklist *wk;
3221         struct jseg *jseg;
3222         struct buf *bp;
3223         struct bio *bio;
3224         uint8_t *data;
3225         struct fs *fs;
3226         int shouldflush;
3227         int segwritten;
3228         int jrecmin;    /* Minimum records per block. */
3229         int jrecmax;    /* Maximum records per block. */
3230         int size;
3231         int cnt;
3232         int off;
3233         int devbsize;
3234
3235         if (MOUNTEDSUJ(mp) == 0)
3236                 return;
3237         shouldflush = softdep_flushcache;
3238         bio = NULL;
3239         jseg = NULL;
3240         ump = VFSTOUFS(mp);
3241         fs = ump->um_fs;
3242         jblocks = ump->softdep_jblocks;
3243         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3244         /*
3245          * We write anywhere between a disk block and fs block.  The upper
3246          * bound is picked to prevent buffer cache fragmentation and limit
3247          * processing time per I/O.
3248          */
3249         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3250         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3251         segwritten = 0;
3252         for (;;) {
3253                 cnt = ump->softdep_on_journal;
3254                 /*
3255                  * Criteria for writing a segment:
3256                  * 1) We have a full block.
3257                  * 2) We're called from jwait() and haven't found the
3258                  *    journal item yet.
3259                  * 3) Always write if needseg is set.
3260                  * 4) If we are called from process_worklist and have
3261                  *    not yet written anything we write a partial block
3262                  *    to enforce a 1 second maximum latency on journal
3263                  *    entries.
3264                  */
3265                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3266                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3267                         break;
3268                 cnt++;
3269                 /*
3270                  * Verify some free journal space.  softdep_prealloc() should
3271                  * guarantee that we don't run out so this is indicative of
3272                  * a problem with the flow control.  Try to recover
3273                  * gracefully in any event.
3274                  */
3275                 while (jblocks->jb_free == 0) {
3276                         if (flags != MNT_WAIT)
3277                                 break;
3278                         printf("softdep: Out of journal space!\n");
3279                         softdep_speedup();
3280                         msleep(jblocks, &lk, PRIBIO, "jblocks", hz);
3281                 }
3282                 FREE_LOCK(&lk);
3283                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3284                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3285                 LIST_INIT(&jseg->js_entries);
3286                 LIST_INIT(&jseg->js_indirs);
3287                 jseg->js_state = ATTACHED;
3288                 if (shouldflush == 0)
3289                         jseg->js_state |= COMPLETE;
3290                 else if (bio == NULL)
3291                         bio = g_alloc_bio();
3292                 jseg->js_jblocks = jblocks;
3293                 bp = geteblk(fs->fs_bsize, 0);
3294                 ACQUIRE_LOCK(&lk);
3295                 /*
3296                  * If there was a race while we were allocating the block
3297                  * and jseg the entry we care about was likely written.
3298                  * We bail out in both the WAIT and NOWAIT case and assume
3299                  * the caller will loop if the entry it cares about is
3300                  * not written.
3301                  */
3302                 cnt = ump->softdep_on_journal;
3303                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3304                         bp->b_flags |= B_INVAL | B_NOCACHE;
3305                         WORKITEM_FREE(jseg, D_JSEG);
3306                         FREE_LOCK(&lk);
3307                         brelse(bp);
3308                         ACQUIRE_LOCK(&lk);
3309                         break;
3310                 }
3311                 /*
3312                  * Calculate the disk block size required for the available
3313                  * records rounded to the min size.
3314                  */
3315                 if (cnt == 0)
3316                         size = devbsize;
3317                 else if (cnt < jrecmax)
3318                         size = howmany(cnt, jrecmin) * devbsize;
3319                 else
3320                         size = fs->fs_bsize;
3321                 /*
3322                  * Allocate a disk block for this journal data and account
3323                  * for truncation of the requested size if enough contiguous
3324                  * space was not available.
3325                  */
3326                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3327                 bp->b_lblkno = bp->b_blkno;
3328                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3329                 bp->b_bcount = size;
3330                 bp->b_bufobj = &ump->um_devvp->v_bufobj;
3331                 bp->b_flags &= ~B_INVAL;
3332                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3333                 /*
3334                  * Initialize our jseg with cnt records.  Assign the next
3335                  * sequence number to it and link it in-order.
3336                  */
3337                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3338                 jseg->js_buf = bp;
3339                 jseg->js_cnt = cnt;
3340                 jseg->js_refs = cnt + 1;        /* Self ref. */
3341                 jseg->js_size = size;
3342                 jseg->js_seq = jblocks->jb_nextseq++;
3343                 if (jblocks->jb_oldestseg == NULL)
3344                         jblocks->jb_oldestseg = jseg;
3345                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3346                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3347                 if (jblocks->jb_writeseg == NULL)
3348                         jblocks->jb_writeseg = jseg;
3349                 /*
3350                  * Start filling in records from the pending list.
3351                  */
3352                 data = bp->b_data;
3353                 off = 0;
3354                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3355                     != NULL) {
3356                         if (cnt == 0)
3357                                 break;
3358                         /* Place a segment header on every device block. */
3359                         if ((off % devbsize) == 0) {
3360                                 jseg_write(ump, jseg, data);
3361                                 off += JREC_SIZE;
3362                                 data = bp->b_data + off;
3363                         }
3364                         if (wk == needwk)
3365                                 needwk = NULL;
3366                         remove_from_journal(wk);
3367                         wk->wk_state |= INPROGRESS;
3368                         WORKLIST_INSERT(&jseg->js_entries, wk);
3369                         switch (wk->wk_type) {
3370                         case D_JADDREF:
3371                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3372                                 break;
3373                         case D_JREMREF:
3374                                 jremref_write(WK_JREMREF(wk), jseg, data);
3375                                 break;
3376                         case D_JMVREF:
3377                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3378                                 break;
3379                         case D_JNEWBLK:
3380                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3381                                 break;
3382                         case D_JFREEBLK:
3383                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3384                                 break;
3385                         case D_JFREEFRAG:
3386                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3387                                 break;
3388                         case D_JTRUNC:
3389                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3390                                 break;
3391                         case D_JFSYNC:
3392                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3393                                 break;
3394                         default:
3395                                 panic("process_journal: Unknown type %s",
3396                                     TYPENAME(wk->wk_type));
3397                                 /* NOTREACHED */
3398                         }
3399                         off += JREC_SIZE;
3400                         data = bp->b_data + off;
3401                         cnt--;
3402                 }
3403                 /*
3404                  * Write this one buffer and continue.
3405                  */
3406                 segwritten = 1;
3407                 jblocks->jb_needseg = 0;
3408                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3409                 FREE_LOCK(&lk);
3410                 BO_LOCK(bp->b_bufobj);
3411                 bgetvp(ump->um_devvp, bp);
3412                 BO_UNLOCK(bp->b_bufobj);
3413                 /*
3414                  * We only do the blocking wait once we find the journal
3415                  * entry we're looking for.
3416                  */
3417                 if (needwk == NULL && flags == MNT_WAIT)
3418                         bwrite(bp);
3419                 else
3420                         bawrite(bp);
3421                 ACQUIRE_LOCK(&lk);
3422         }
3423         /*
3424          * If we wrote a segment issue a synchronize cache so the journal
3425          * is reflected on disk before the data is written.  Since reclaiming
3426          * journal space also requires writing a journal record this
3427          * process also enforces a barrier before reclamation.
3428          */
3429         if (segwritten && shouldflush) {
3430                 softdep_synchronize(bio, ump, 
3431                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3432         } else if (bio)
3433                 g_destroy_bio(bio);
3434         /*
3435          * If we've suspended the filesystem because we ran out of journal
3436          * space either try to sync it here to make some progress or
3437          * unsuspend it if we already have.
3438          */
3439         if (flags == 0 && jblocks->jb_suspended) {
3440                 if (journal_unsuspend(ump))
3441                         return;
3442                 FREE_LOCK(&lk);
3443                 VFS_SYNC(mp, MNT_NOWAIT);
3444                 ffs_sbupdate(ump, MNT_WAIT, 0);
3445                 ACQUIRE_LOCK(&lk);
3446         }
3447 }
3448
3449 /*
3450  * Complete a jseg, allowing all dependencies awaiting journal writes
3451  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3452  * structures so that the journal segment can be freed to reclaim space.
3453  */
3454 static void
3455 complete_jseg(jseg)
3456         struct jseg *jseg;
3457 {
3458         struct worklist *wk;
3459         struct jmvref *jmvref;
3460         int waiting;
3461 #ifdef INVARIANTS
3462         int i = 0;
3463 #endif
3464
3465         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3466                 WORKLIST_REMOVE(wk);
3467                 waiting = wk->wk_state & IOWAITING;
3468                 wk->wk_state &= ~(INPROGRESS | IOWAITING);
3469                 wk->wk_state |= COMPLETE;
3470                 KASSERT(i++ < jseg->js_cnt,
3471                     ("handle_written_jseg: overflow %d >= %d",
3472                     i - 1, jseg->js_cnt));
3473                 switch (wk->wk_type) {
3474                 case D_JADDREF:
3475                         handle_written_jaddref(WK_JADDREF(wk));
3476                         break;
3477                 case D_JREMREF:
3478                         handle_written_jremref(WK_JREMREF(wk));
3479                         break;
3480                 case D_JMVREF:
3481                         rele_jseg(jseg);        /* No jsegdep. */
3482                         jmvref = WK_JMVREF(wk);
3483                         LIST_REMOVE(jmvref, jm_deps);
3484                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3485                                 free_pagedep(jmvref->jm_pagedep);
3486                         WORKITEM_FREE(jmvref, D_JMVREF);
3487                         break;
3488                 case D_JNEWBLK:
3489                         handle_written_jnewblk(WK_JNEWBLK(wk));
3490                         break;
3491                 case D_JFREEBLK:
3492                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3493                         break;
3494                 case D_JTRUNC:
3495                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3496                         break;
3497                 case D_JFSYNC:
3498                         rele_jseg(jseg);        /* No jsegdep. */
3499                         WORKITEM_FREE(wk, D_JFSYNC);
3500                         break;
3501                 case D_JFREEFRAG:
3502                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3503                         break;
3504                 default:
3505                         panic("handle_written_jseg: Unknown type %s",
3506                             TYPENAME(wk->wk_type));
3507                         /* NOTREACHED */
3508                 }
3509                 if (waiting)
3510                         wakeup(wk);
3511         }
3512         /* Release the self reference so the structure may be freed. */
3513         rele_jseg(jseg);
3514 }
3515
3516 /*
3517  * Determine which jsegs are ready for completion processing.  Waits for
3518  * synchronize cache to complete as well as forcing in-order completion
3519  * of journal entries.
3520  */
3521 static void
3522 complete_jsegs(jseg)
3523         struct jseg *jseg;
3524 {
3525         struct jblocks *jblocks;
3526         struct jseg *jsegn;
3527
3528         jblocks = jseg->js_jblocks;
3529         /*
3530          * Don't allow out of order completions.  If this isn't the first
3531          * block wait for it to write before we're done.
3532          */
3533         if (jseg != jblocks->jb_writeseg)
3534                 return;
3535         /* Iterate through available jsegs processing their entries. */
3536         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3537                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3538                 jsegn = TAILQ_NEXT(jseg, js_next);
3539                 complete_jseg(jseg);
3540                 jseg = jsegn;
3541         }
3542         jblocks->jb_writeseg = jseg;
3543         /*
3544          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3545          */
3546         free_jsegs(jblocks);
3547 }
3548
3549 /*
3550  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3551  * the final completions.
3552  */
3553 static void
3554 handle_written_jseg(jseg, bp)
3555         struct jseg *jseg;
3556         struct buf *bp;
3557 {
3558
3559         if (jseg->js_refs == 0)
3560                 panic("handle_written_jseg: No self-reference on %p", jseg);
3561         jseg->js_state |= DEPCOMPLETE;
3562         /*
3563          * We'll never need this buffer again, set flags so it will be
3564          * discarded.
3565          */
3566         bp->b_flags |= B_INVAL | B_NOCACHE;
3567         complete_jsegs(jseg);
3568 }
3569
3570 static inline struct jsegdep *
3571 inoref_jseg(inoref)
3572         struct inoref *inoref;
3573 {
3574         struct jsegdep *jsegdep;
3575
3576         jsegdep = inoref->if_jsegdep;
3577         inoref->if_jsegdep = NULL;
3578
3579         return (jsegdep);
3580 }
3581
3582 /*
3583  * Called once a jremref has made it to stable store.  The jremref is marked
3584  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3585  * for the jremref to complete will be awoken by free_jremref.
3586  */
3587 static void
3588 handle_written_jremref(jremref)
3589         struct jremref *jremref;
3590 {
3591         struct inodedep *inodedep;
3592         struct jsegdep *jsegdep;
3593         struct dirrem *dirrem;
3594
3595         /* Grab the jsegdep. */
3596         jsegdep = inoref_jseg(&jremref->jr_ref);
3597         /*
3598          * Remove us from the inoref list.
3599          */
3600         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3601             0, &inodedep) == 0)
3602                 panic("handle_written_jremref: Lost inodedep");
3603         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3604         /*
3605          * Complete the dirrem.
3606          */
3607         dirrem = jremref->jr_dirrem;
3608         jremref->jr_dirrem = NULL;
3609         LIST_REMOVE(jremref, jr_deps);
3610         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3611         jwork_insert(&dirrem->dm_jwork, jsegdep);
3612         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3613             (dirrem->dm_state & COMPLETE) != 0)
3614                 add_to_worklist(&dirrem->dm_list, 0);
3615         free_jremref(jremref);
3616 }
3617
3618 /*
3619  * Called once a jaddref has made it to stable store.  The dependency is
3620  * marked complete and any dependent structures are added to the inode
3621  * bufwait list to be completed as soon as it is written.  If a bitmap write
3622  * depends on this entry we move the inode into the inodedephd of the
3623  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3624  */
3625 static void
3626 handle_written_jaddref(jaddref)
3627         struct jaddref *jaddref;
3628 {
3629         struct jsegdep *jsegdep;
3630         struct inodedep *inodedep;
3631         struct diradd *diradd;
3632         struct mkdir *mkdir;
3633
3634         /* Grab the jsegdep. */
3635         jsegdep = inoref_jseg(&jaddref->ja_ref);
3636         mkdir = NULL;
3637         diradd = NULL;
3638         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3639             0, &inodedep) == 0)
3640                 panic("handle_written_jaddref: Lost inodedep.");
3641         if (jaddref->ja_diradd == NULL)
3642                 panic("handle_written_jaddref: No dependency");
3643         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3644                 diradd = jaddref->ja_diradd;
3645                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3646         } else if (jaddref->ja_state & MKDIR_PARENT) {
3647                 mkdir = jaddref->ja_mkdir;
3648                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3649         } else if (jaddref->ja_state & MKDIR_BODY)
3650                 mkdir = jaddref->ja_mkdir;
3651         else
3652                 panic("handle_written_jaddref: Unknown dependency %p",
3653                     jaddref->ja_diradd);
3654         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3655         /*
3656          * Remove us from the inode list.
3657          */
3658         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3659         /*
3660          * The mkdir may be waiting on the jaddref to clear before freeing.
3661          */
3662         if (mkdir) {
3663                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3664                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3665                     TYPENAME(mkdir->md_list.wk_type)));
3666                 mkdir->md_jaddref = NULL;
3667                 diradd = mkdir->md_diradd;
3668                 mkdir->md_state |= DEPCOMPLETE;
3669                 complete_mkdir(mkdir);
3670         }
3671         jwork_insert(&diradd->da_jwork, jsegdep);
3672         if (jaddref->ja_state & NEWBLOCK) {
3673                 inodedep->id_state |= ONDEPLIST;
3674                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3675                     inodedep, id_deps);
3676         }
3677         free_jaddref(jaddref);
3678 }
3679
3680 /*
3681  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3682  * is placed in the bmsafemap to await notification of a written bitmap.  If
3683  * the operation was canceled we add the segdep to the appropriate
3684  * dependency to free the journal space once the canceling operation
3685  * completes.
3686  */
3687 static void
3688 handle_written_jnewblk(jnewblk)
3689         struct jnewblk *jnewblk;
3690 {
3691         struct bmsafemap *bmsafemap;
3692         struct freefrag *freefrag;
3693         struct freework *freework;
3694         struct jsegdep *jsegdep;
3695         struct newblk *newblk;
3696
3697         /* Grab the jsegdep. */
3698         jsegdep = jnewblk->jn_jsegdep;
3699         jnewblk->jn_jsegdep = NULL;
3700         if (jnewblk->jn_dep == NULL) 
3701                 panic("handle_written_jnewblk: No dependency for the segdep.");
3702         switch (jnewblk->jn_dep->wk_type) {
3703         case D_NEWBLK:
3704         case D_ALLOCDIRECT:
3705         case D_ALLOCINDIR:
3706                 /*
3707                  * Add the written block to the bmsafemap so it can
3708                  * be notified when the bitmap is on disk.
3709                  */
3710                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3711                 newblk->nb_jnewblk = NULL;
3712                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3713                         bmsafemap = newblk->nb_bmsafemap;
3714                         newblk->nb_state |= ONDEPLIST;
3715                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3716                             nb_deps);
3717                 }
3718                 jwork_insert(&newblk->nb_jwork, jsegdep);
3719                 break;
3720         case D_FREEFRAG:
3721                 /*
3722                  * A newblock being removed by a freefrag when replaced by
3723                  * frag extension.
3724                  */
3725                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3726                 freefrag->ff_jdep = NULL;
3727                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3728                 break;
3729         case D_FREEWORK:
3730                 /*
3731                  * A direct block was removed by truncate.
3732                  */
3733                 freework = WK_FREEWORK(jnewblk->jn_dep);
3734                 freework->fw_jnewblk = NULL;
3735                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3736                 break;
3737         default:
3738                 panic("handle_written_jnewblk: Unknown type %d.",
3739                     jnewblk->jn_dep->wk_type);
3740         }
3741         jnewblk->jn_dep = NULL;
3742         free_jnewblk(jnewblk);
3743 }
3744
3745 /*
3746  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3747  * an in-flight allocation that has not yet been committed.  Divorce us
3748  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3749  * to the worklist.
3750  */
3751 static void
3752 cancel_jfreefrag(jfreefrag)
3753         struct jfreefrag *jfreefrag;
3754 {
3755         struct freefrag *freefrag;
3756
3757         if (jfreefrag->fr_jsegdep) {
3758                 free_jsegdep(jfreefrag->fr_jsegdep);
3759                 jfreefrag->fr_jsegdep = NULL;
3760         }
3761         freefrag = jfreefrag->fr_freefrag;
3762         jfreefrag->fr_freefrag = NULL;
3763         free_jfreefrag(jfreefrag);
3764         freefrag->ff_state |= DEPCOMPLETE;
3765         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3766 }
3767
3768 /*
3769  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3770  */
3771 static void
3772 free_jfreefrag(jfreefrag)
3773         struct jfreefrag *jfreefrag;
3774 {
3775
3776         if (jfreefrag->fr_state & INPROGRESS)
3777                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3778         else if (jfreefrag->fr_state & ONWORKLIST)
3779                 remove_from_journal(&jfreefrag->fr_list);
3780         if (jfreefrag->fr_freefrag != NULL)
3781                 panic("free_jfreefrag:  Still attached to a freefrag.");
3782         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3783 }
3784
3785 /*
3786  * Called when the journal write for a jfreefrag completes.  The parent
3787  * freefrag is added to the worklist if this completes its dependencies.
3788  */
3789 static void
3790 handle_written_jfreefrag(jfreefrag)
3791         struct jfreefrag *jfreefrag;
3792 {
3793         struct jsegdep *jsegdep;
3794         struct freefrag *freefrag;
3795
3796         /* Grab the jsegdep. */
3797         jsegdep = jfreefrag->fr_jsegdep;
3798         jfreefrag->fr_jsegdep = NULL;
3799         freefrag = jfreefrag->fr_freefrag;
3800         if (freefrag == NULL)
3801                 panic("handle_written_jfreefrag: No freefrag.");
3802         freefrag->ff_state |= DEPCOMPLETE;
3803         freefrag->ff_jdep = NULL;
3804         jwork_insert(&freefrag->ff_jwork, jsegdep);
3805         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3806                 add_to_worklist(&freefrag->ff_list, 0);
3807         jfreefrag->fr_freefrag = NULL;
3808         free_jfreefrag(jfreefrag);
3809 }
3810
3811 /*
3812  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3813  * is removed from the freeblks list of pending journal writes and the
3814  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3815  * have been reclaimed.
3816  */
3817 static void
3818 handle_written_jblkdep(jblkdep)
3819         struct jblkdep *jblkdep;
3820 {
3821         struct freeblks *freeblks;
3822         struct jsegdep *jsegdep;
3823
3824         /* Grab the jsegdep. */
3825         jsegdep = jblkdep->jb_jsegdep;
3826         jblkdep->jb_jsegdep = NULL;
3827         freeblks = jblkdep->jb_freeblks;
3828         LIST_REMOVE(jblkdep, jb_deps);
3829         jwork_insert(&freeblks->fb_jwork, jsegdep);
3830         /*
3831          * If the freeblks is all journaled, we can add it to the worklist.
3832          */
3833         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3834             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3835                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3836
3837         free_jblkdep(jblkdep);
3838 }
3839
3840 static struct jsegdep *
3841 newjsegdep(struct worklist *wk)
3842 {
3843         struct jsegdep *jsegdep;
3844
3845         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3846         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3847         jsegdep->jd_seg = NULL;
3848
3849         return (jsegdep);
3850 }
3851
3852 static struct jmvref *
3853 newjmvref(dp, ino, oldoff, newoff)
3854         struct inode *dp;
3855         ino_t ino;
3856         off_t oldoff;
3857         off_t newoff;
3858 {
3859         struct jmvref *jmvref;
3860
3861         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3862         workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3863         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3864         jmvref->jm_parent = dp->i_number;
3865         jmvref->jm_ino = ino;
3866         jmvref->jm_oldoff = oldoff;
3867         jmvref->jm_newoff = newoff;
3868
3869         return (jmvref);
3870 }
3871
3872 /*
3873  * Allocate a new jremref that tracks the removal of ip from dp with the
3874  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3875  * DEPCOMPLETE as we have all the information required for the journal write
3876  * and the directory has already been removed from the buffer.  The caller
3877  * is responsible for linking the jremref into the pagedep and adding it
3878  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3879  * a DOTDOT addition so handle_workitem_remove() can properly assign
3880  * the jsegdep when we're done.
3881  */
3882 static struct jremref *
3883 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3884     off_t diroff, nlink_t nlink)
3885 {
3886         struct jremref *jremref;
3887
3888         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3889         workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3890         jremref->jr_state = ATTACHED;
3891         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3892            nlink, ip->i_mode);
3893         jremref->jr_dirrem = dirrem;
3894
3895         return (jremref);
3896 }
3897
3898 static inline void
3899 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3900     nlink_t nlink, uint16_t mode)
3901 {
3902
3903         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3904         inoref->if_diroff = diroff;
3905         inoref->if_ino = ino;
3906         inoref->if_parent = parent;
3907         inoref->if_nlink = nlink;
3908         inoref->if_mode = mode;
3909 }
3910
3911 /*
3912  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3913  * directory offset may not be known until later.  The caller is responsible
3914  * adding the entry to the journal when this information is available.  nlink
3915  * should be the link count prior to the addition and mode is only required
3916  * to have the correct FMT.
3917  */
3918 static struct jaddref *
3919 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3920     uint16_t mode)
3921 {
3922         struct jaddref *jaddref;
3923
3924         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3925         workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3926         jaddref->ja_state = ATTACHED;
3927         jaddref->ja_mkdir = NULL;
3928         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3929
3930         return (jaddref);
3931 }
3932
3933 /*
3934  * Create a new free dependency for a freework.  The caller is responsible
3935  * for adjusting the reference count when it has the lock held.  The freedep
3936  * will track an outstanding bitmap write that will ultimately clear the
3937  * freework to continue.
3938  */
3939 static struct freedep *
3940 newfreedep(struct freework *freework)
3941 {
3942         struct freedep *freedep;
3943
3944         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3945         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3946         freedep->fd_freework = freework;
3947
3948         return (freedep);
3949 }
3950
3951 /*
3952  * Free a freedep structure once the buffer it is linked to is written.  If
3953  * this is the last reference to the freework schedule it for completion.
3954  */
3955 static void
3956 free_freedep(freedep)
3957         struct freedep *freedep;
3958 {
3959         struct freework *freework;
3960
3961         freework = freedep->fd_freework;
3962         freework->fw_freeblks->fb_cgwait--;
3963         if (--freework->fw_ref == 0)
3964                 freework_enqueue(freework);
3965         WORKITEM_FREE(freedep, D_FREEDEP);
3966 }
3967
3968 /*
3969  * Allocate a new freework structure that may be a level in an indirect
3970  * when parent is not NULL or a top level block when it is.  The top level
3971  * freework structures are allocated without lk held and before the freeblks
3972  * is visible outside of softdep_setup_freeblocks().
3973  */
3974 static struct freework *
3975 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
3976         struct ufsmount *ump;
3977         struct freeblks *freeblks;
3978         struct freework *parent;
3979         ufs_lbn_t lbn;
3980         ufs2_daddr_t nb;
3981         int frags;
3982         int off;
3983         int journal;
3984 {
3985         struct freework *freework;
3986
3987         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3988         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3989         freework->fw_state = ATTACHED;
3990         freework->fw_jnewblk = NULL;
3991         freework->fw_freeblks = freeblks;
3992         freework->fw_parent = parent;
3993         freework->fw_lbn = lbn;
3994         freework->fw_blkno = nb;
3995         freework->fw_frags = frags;
3996         freework->fw_indir = NULL;
3997         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
3998                 ? 0 : NINDIR(ump->um_fs) + 1;
3999         freework->fw_start = freework->fw_off = off;
4000         if (journal)
4001                 newjfreeblk(freeblks, lbn, nb, frags);
4002         if (parent == NULL) {
4003                 ACQUIRE_LOCK(&lk);
4004                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4005                 freeblks->fb_ref++;
4006                 FREE_LOCK(&lk);
4007         }
4008
4009         return (freework);
4010 }
4011
4012 /*
4013  * Eliminate a jfreeblk for a block that does not need journaling.
4014  */
4015 static void
4016 cancel_jfreeblk(freeblks, blkno)
4017         struct freeblks *freeblks;
4018         ufs2_daddr_t blkno;
4019 {
4020         struct jfreeblk *jfreeblk;
4021         struct jblkdep *jblkdep;
4022
4023         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4024                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4025                         continue;
4026                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4027                 if (jfreeblk->jf_blkno == blkno)
4028                         break;
4029         }
4030         if (jblkdep == NULL)
4031                 return;
4032         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4033         free_jsegdep(jblkdep->jb_jsegdep);
4034         LIST_REMOVE(jblkdep, jb_deps);
4035         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4036 }
4037
4038 /*
4039  * Allocate a new jfreeblk to journal top level block pointer when truncating
4040  * a file.  The caller must add this to the worklist when lk is held.
4041  */
4042 static struct jfreeblk *
4043 newjfreeblk(freeblks, lbn, blkno, frags)
4044         struct freeblks *freeblks;
4045         ufs_lbn_t lbn;
4046         ufs2_daddr_t blkno;
4047         int frags;
4048 {
4049         struct jfreeblk *jfreeblk;
4050
4051         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4052         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4053             freeblks->fb_list.wk_mp);
4054         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4055         jfreeblk->jf_dep.jb_freeblks = freeblks;
4056         jfreeblk->jf_ino = freeblks->fb_inum;
4057         jfreeblk->jf_lbn = lbn;
4058         jfreeblk->jf_blkno = blkno;
4059         jfreeblk->jf_frags = frags;
4060         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4061
4062         return (jfreeblk);
4063 }
4064
4065 /*
4066  * Allocate a new jtrunc to track a partial truncation.
4067  */
4068 static struct jtrunc *
4069 newjtrunc(freeblks, size, extsize)
4070         struct freeblks *freeblks;
4071         off_t size;
4072         int extsize;
4073 {
4074         struct jtrunc *jtrunc;
4075
4076         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4077         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4078             freeblks->fb_list.wk_mp);
4079         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4080         jtrunc->jt_dep.jb_freeblks = freeblks;
4081         jtrunc->jt_ino = freeblks->fb_inum;
4082         jtrunc->jt_size = size;
4083         jtrunc->jt_extsize = extsize;
4084         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4085
4086         return (jtrunc);
4087 }
4088
4089 /*
4090  * If we're canceling a new bitmap we have to search for another ref
4091  * to move into the bmsafemap dep.  This might be better expressed
4092  * with another structure.
4093  */
4094 static void
4095 move_newblock_dep(jaddref, inodedep)
4096         struct jaddref *jaddref;
4097         struct inodedep *inodedep;
4098 {
4099         struct inoref *inoref;
4100         struct jaddref *jaddrefn;
4101
4102         jaddrefn = NULL;
4103         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4104             inoref = TAILQ_NEXT(inoref, if_deps)) {
4105                 if ((jaddref->ja_state & NEWBLOCK) &&
4106                     inoref->if_list.wk_type == D_JADDREF) {
4107                         jaddrefn = (struct jaddref *)inoref;
4108                         break;
4109                 }
4110         }
4111         if (jaddrefn == NULL)
4112                 return;
4113         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4114         jaddrefn->ja_state |= jaddref->ja_state &
4115             (ATTACHED | UNDONE | NEWBLOCK);
4116         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4117         jaddref->ja_state |= ATTACHED;
4118         LIST_REMOVE(jaddref, ja_bmdeps);
4119         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4120             ja_bmdeps);
4121 }
4122
4123 /*
4124  * Cancel a jaddref either before it has been written or while it is being
4125  * written.  This happens when a link is removed before the add reaches
4126  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4127  * and inode to prevent the link count or bitmap from reaching the disk
4128  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4129  * required.
4130  *
4131  * Returns 1 if the canceled addref requires journaling of the remove and
4132  * 0 otherwise.
4133  */
4134 static int
4135 cancel_jaddref(jaddref, inodedep, wkhd)
4136         struct jaddref *jaddref;
4137         struct inodedep *inodedep;
4138         struct workhead *wkhd;
4139 {
4140         struct inoref *inoref;
4141         struct jsegdep *jsegdep;
4142         int needsj;
4143
4144         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4145             ("cancel_jaddref: Canceling complete jaddref"));
4146         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4147                 needsj = 1;
4148         else
4149                 needsj = 0;
4150         if (inodedep == NULL)
4151                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4152                     0, &inodedep) == 0)
4153                         panic("cancel_jaddref: Lost inodedep");
4154         /*
4155          * We must adjust the nlink of any reference operation that follows
4156          * us so that it is consistent with the in-memory reference.  This
4157          * ensures that inode nlink rollbacks always have the correct link.
4158          */
4159         if (needsj == 0) {
4160                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4161                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4162                         if (inoref->if_state & GOINGAWAY)
4163                                 break;
4164                         inoref->if_nlink--;
4165                 }
4166         }
4167         jsegdep = inoref_jseg(&jaddref->ja_ref);
4168         if (jaddref->ja_state & NEWBLOCK)
4169                 move_newblock_dep(jaddref, inodedep);
4170         wake_worklist(&jaddref->ja_list);
4171         jaddref->ja_mkdir = NULL;
4172         if (jaddref->ja_state & INPROGRESS) {
4173                 jaddref->ja_state &= ~INPROGRESS;
4174                 WORKLIST_REMOVE(&jaddref->ja_list);
4175                 jwork_insert(wkhd, jsegdep);
4176         } else {
4177                 free_jsegdep(jsegdep);
4178                 if (jaddref->ja_state & DEPCOMPLETE)
4179                         remove_from_journal(&jaddref->ja_list);
4180         }
4181         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4182         /*
4183          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4184          * can arrange for them to be freed with the bitmap.  Otherwise we
4185          * no longer need this addref attached to the inoreflst and it
4186          * will incorrectly adjust nlink if we leave it.
4187          */
4188         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4189                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4190                     if_deps);
4191                 jaddref->ja_state |= COMPLETE;
4192                 free_jaddref(jaddref);
4193                 return (needsj);
4194         }
4195         /*
4196          * Leave the head of the list for jsegdeps for fast merging.
4197          */
4198         if (LIST_FIRST(wkhd) != NULL) {
4199                 jaddref->ja_state |= ONWORKLIST;
4200                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4201         } else
4202                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4203
4204         return (needsj);
4205 }
4206
4207 /* 
4208  * Attempt to free a jaddref structure when some work completes.  This
4209  * should only succeed once the entry is written and all dependencies have
4210  * been notified.
4211  */
4212 static void
4213 free_jaddref(jaddref)
4214         struct jaddref *jaddref;
4215 {
4216
4217         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4218                 return;
4219         if (jaddref->ja_ref.if_jsegdep)
4220                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4221                     jaddref, jaddref->ja_state);
4222         if (jaddref->ja_state & NEWBLOCK)
4223                 LIST_REMOVE(jaddref, ja_bmdeps);
4224         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4225                 panic("free_jaddref: Bad state %p(0x%X)",
4226                     jaddref, jaddref->ja_state);
4227         if (jaddref->ja_mkdir != NULL)
4228                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4229         WORKITEM_FREE(jaddref, D_JADDREF);
4230 }
4231
4232 /*
4233  * Free a jremref structure once it has been written or discarded.
4234  */
4235 static void
4236 free_jremref(jremref)
4237         struct jremref *jremref;
4238 {
4239
4240         if (jremref->jr_ref.if_jsegdep)
4241                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4242         if (jremref->jr_state & INPROGRESS)
4243                 panic("free_jremref: IO still pending");
4244         WORKITEM_FREE(jremref, D_JREMREF);
4245 }
4246
4247 /*
4248  * Free a jnewblk structure.
4249  */
4250 static void
4251 free_jnewblk(jnewblk)
4252         struct jnewblk *jnewblk;
4253 {
4254
4255         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4256                 return;
4257         LIST_REMOVE(jnewblk, jn_deps);
4258         if (jnewblk->jn_dep != NULL)
4259                 panic("free_jnewblk: Dependency still attached.");
4260         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4261 }
4262
4263 /*
4264  * Cancel a jnewblk which has been been made redundant by frag extension.
4265  */
4266 static void
4267 cancel_jnewblk(jnewblk, wkhd)
4268         struct jnewblk *jnewblk;
4269         struct workhead *wkhd;
4270 {
4271         struct jsegdep *jsegdep;
4272
4273         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4274         jsegdep = jnewblk->jn_jsegdep;
4275         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4276                 panic("cancel_jnewblk: Invalid state");
4277         jnewblk->jn_jsegdep  = NULL;
4278         jnewblk->jn_dep = NULL;
4279         jnewblk->jn_state |= GOINGAWAY;
4280         if (jnewblk->jn_state & INPROGRESS) {
4281                 jnewblk->jn_state &= ~INPROGRESS;
4282                 WORKLIST_REMOVE(&jnewblk->jn_list);
4283                 jwork_insert(wkhd, jsegdep);
4284         } else {
4285                 free_jsegdep(jsegdep);
4286                 remove_from_journal(&jnewblk->jn_list);
4287         }
4288         wake_worklist(&jnewblk->jn_list);
4289         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4290 }
4291
4292 static void
4293 free_jblkdep(jblkdep)
4294         struct jblkdep *jblkdep;
4295 {
4296
4297         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4298                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4299         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4300                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4301         else
4302                 panic("free_jblkdep: Unexpected type %s",
4303                     TYPENAME(jblkdep->jb_list.wk_type));
4304 }
4305
4306 /*
4307  * Free a single jseg once it is no longer referenced in memory or on
4308  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4309  * to disappear.
4310  */
4311 static void
4312 free_jseg(jseg, jblocks)
4313         struct jseg *jseg;
4314         struct jblocks *jblocks;
4315 {
4316         struct freework *freework;
4317
4318         /*
4319          * Free freework structures that were lingering to indicate freed
4320          * indirect blocks that forced journal write ordering on reallocate.
4321          */
4322         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4323                 indirblk_remove(freework);
4324         if (jblocks->jb_oldestseg == jseg)
4325                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4326         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4327         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4328         KASSERT(LIST_EMPTY(&jseg->js_entries),
4329             ("free_jseg: Freed jseg has valid entries."));
4330         WORKITEM_FREE(jseg, D_JSEG);
4331 }
4332
4333 /*
4334  * Free all jsegs that meet the criteria for being reclaimed and update
4335  * oldestseg.
4336  */
4337 static void
4338 free_jsegs(jblocks)
4339         struct jblocks *jblocks;
4340 {
4341         struct jseg *jseg;
4342
4343         /*
4344          * Free only those jsegs which have none allocated before them to
4345          * preserve the journal space ordering.
4346          */
4347         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4348                 /*
4349                  * Only reclaim space when nothing depends on this journal
4350                  * set and another set has written that it is no longer
4351                  * valid.
4352                  */
4353                 if (jseg->js_refs != 0) {
4354                         jblocks->jb_oldestseg = jseg;
4355                         return;
4356                 }
4357                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4358                         break;
4359                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4360                         break;
4361                 /*
4362                  * We can free jsegs that didn't write entries when
4363                  * oldestwrseq == js_seq.
4364                  */
4365                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4366                     jseg->js_cnt != 0)
4367                         break;
4368                 free_jseg(jseg, jblocks);
4369         }
4370         /*
4371          * If we exited the loop above we still must discover the
4372          * oldest valid segment.
4373          */
4374         if (jseg)
4375                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4376                      jseg = TAILQ_NEXT(jseg, js_next))
4377                         if (jseg->js_refs != 0)
4378                                 break;
4379         jblocks->jb_oldestseg = jseg;
4380         /*
4381          * The journal has no valid records but some jsegs may still be
4382          * waiting on oldestwrseq to advance.  We force a small record
4383          * out to permit these lingering records to be reclaimed.
4384          */
4385         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4386                 jblocks->jb_needseg = 1;
4387 }
4388
4389 /*
4390  * Release one reference to a jseg and free it if the count reaches 0.  This
4391  * should eventually reclaim journal space as well.
4392  */
4393 static void
4394 rele_jseg(jseg)
4395         struct jseg *jseg;
4396 {
4397
4398         KASSERT(jseg->js_refs > 0,
4399             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4400         if (--jseg->js_refs != 0)
4401                 return;
4402         free_jsegs(jseg->js_jblocks);
4403 }
4404
4405 /*
4406  * Release a jsegdep and decrement the jseg count.
4407  */
4408 static void
4409 free_jsegdep(jsegdep)
4410         struct jsegdep *jsegdep;
4411 {
4412
4413         if (jsegdep->jd_seg)
4414                 rele_jseg(jsegdep->jd_seg);
4415         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4416 }
4417
4418 /*
4419  * Wait for a journal item to make it to disk.  Initiate journal processing
4420  * if required.
4421  */
4422 static int
4423 jwait(wk, waitfor)
4424         struct worklist *wk;
4425         int waitfor;
4426 {
4427
4428         /*
4429          * Blocking journal waits cause slow synchronous behavior.  Record
4430          * stats on the frequency of these blocking operations.
4431          */
4432         if (waitfor == MNT_WAIT) {
4433                 stat_journal_wait++;
4434                 switch (wk->wk_type) {
4435                 case D_JREMREF:
4436                 case D_JMVREF:
4437                         stat_jwait_filepage++;
4438                         break;
4439                 case D_JTRUNC:
4440                 case D_JFREEBLK:
4441                         stat_jwait_freeblks++;
4442                         break;
4443                 case D_JNEWBLK:
4444                         stat_jwait_newblk++;
4445                         break;
4446                 case D_JADDREF:
4447                         stat_jwait_inode++;
4448                         break;
4449                 default:
4450                         break;
4451                 }
4452         }
4453         /*
4454          * If IO has not started we process the journal.  We can't mark the
4455          * worklist item as IOWAITING because we drop the lock while
4456          * processing the journal and the worklist entry may be freed after
4457          * this point.  The caller may call back in and re-issue the request.
4458          */
4459         if ((wk->wk_state & INPROGRESS) == 0) {
4460                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4461                 if (waitfor != MNT_WAIT)
4462                         return (EBUSY);
4463                 return (0);
4464         }
4465         if (waitfor != MNT_WAIT)
4466                 return (EBUSY);
4467         wait_worklist(wk, "jwait");
4468         return (0);
4469 }
4470
4471 /*
4472  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4473  * appropriate.  This is a convenience function to reduce duplicate code
4474  * for the setup and revert functions below.
4475  */
4476 static struct inodedep *
4477 inodedep_lookup_ip(ip)
4478         struct inode *ip;
4479 {
4480         struct inodedep *inodedep;
4481         int dflags;
4482
4483         KASSERT(ip->i_nlink >= ip->i_effnlink,
4484             ("inodedep_lookup_ip: bad delta"));
4485         dflags = DEPALLOC;
4486         if (IS_SNAPSHOT(ip))
4487                 dflags |= NODELAY;
4488         (void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
4489             &inodedep);
4490         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4491         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4492
4493         return (inodedep);
4494 }
4495
4496 /*
4497  * Called prior to creating a new inode and linking it to a directory.  The
4498  * jaddref structure must already be allocated by softdep_setup_inomapdep
4499  * and it is discovered here so we can initialize the mode and update
4500  * nlinkdelta.
4501  */
4502 void
4503 softdep_setup_create(dp, ip)
4504         struct inode *dp;
4505         struct inode *ip;
4506 {
4507         struct inodedep *inodedep;
4508         struct jaddref *jaddref;
4509         struct vnode *dvp;
4510
4511         KASSERT(ip->i_nlink == 1,
4512             ("softdep_setup_create: Invalid link count."));
4513         dvp = ITOV(dp);
4514         ACQUIRE_LOCK(&lk);
4515         inodedep = inodedep_lookup_ip(ip);
4516         if (DOINGSUJ(dvp)) {
4517                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4518                     inoreflst);
4519                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4520                     ("softdep_setup_create: No addref structure present."));
4521         }
4522         softdep_prelink(dvp, NULL);
4523         FREE_LOCK(&lk);
4524 }
4525
4526 /*
4527  * Create a jaddref structure to track the addition of a DOTDOT link when
4528  * we are reparenting an inode as part of a rename.  This jaddref will be
4529  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4530  * non-journaling softdep.
4531  */
4532 void
4533 softdep_setup_dotdot_link(dp, ip)
4534         struct inode *dp;
4535         struct inode *ip;
4536 {
4537         struct inodedep *inodedep;
4538         struct jaddref *jaddref;
4539         struct vnode *dvp;
4540         struct vnode *vp;
4541
4542         dvp = ITOV(dp);
4543         vp = ITOV(ip);
4544         jaddref = NULL;
4545         /*
4546          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4547          * is used as a normal link would be.
4548          */
4549         if (DOINGSUJ(dvp))
4550                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4551                     dp->i_effnlink - 1, dp->i_mode);
4552         ACQUIRE_LOCK(&lk);
4553         inodedep = inodedep_lookup_ip(dp);
4554         if (jaddref)
4555                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4556                     if_deps);
4557         softdep_prelink(dvp, ITOV(ip));
4558         FREE_LOCK(&lk);
4559 }
4560
4561 /*
4562  * Create a jaddref structure to track a new link to an inode.  The directory
4563  * offset is not known until softdep_setup_directory_add or
4564  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4565  * softdep.
4566  */
4567 void
4568 softdep_setup_link(dp, ip)
4569         struct inode *dp;
4570         struct inode *ip;
4571 {
4572         struct inodedep *inodedep;
4573         struct jaddref *jaddref;
4574         struct vnode *dvp;
4575
4576         dvp = ITOV(dp);
4577         jaddref = NULL;
4578         if (DOINGSUJ(dvp))
4579                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4580                     ip->i_mode);
4581         ACQUIRE_LOCK(&lk);
4582         inodedep = inodedep_lookup_ip(ip);
4583         if (jaddref)
4584                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4585                     if_deps);
4586         softdep_prelink(dvp, ITOV(ip));
4587         FREE_LOCK(&lk);
4588 }
4589
4590 /*
4591  * Called to create the jaddref structures to track . and .. references as
4592  * well as lookup and further initialize the incomplete jaddref created
4593  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4594  * nlinkdelta for non-journaling softdep.
4595  */
4596 void
4597 softdep_setup_mkdir(dp, ip)
4598         struct inode *dp;
4599         struct inode *ip;
4600 {
4601         struct inodedep *inodedep;
4602         struct jaddref *dotdotaddref;
4603         struct jaddref *dotaddref;
4604         struct jaddref *jaddref;
4605         struct vnode *dvp;
4606
4607         dvp = ITOV(dp);
4608         dotaddref = dotdotaddref = NULL;
4609         if (DOINGSUJ(dvp)) {
4610                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4611                     ip->i_mode);
4612                 dotaddref->ja_state |= MKDIR_BODY;
4613                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4614                     dp->i_effnlink - 1, dp->i_mode);
4615                 dotdotaddref->ja_state |= MKDIR_PARENT;
4616         }
4617         ACQUIRE_LOCK(&lk);
4618         inodedep = inodedep_lookup_ip(ip);
4619         if (DOINGSUJ(dvp)) {
4620                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4621                     inoreflst);
4622                 KASSERT(jaddref != NULL,
4623                     ("softdep_setup_mkdir: No addref structure present."));
4624                 KASSERT(jaddref->ja_parent == dp->i_number, 
4625                     ("softdep_setup_mkdir: bad parent %d",
4626                     jaddref->ja_parent));
4627                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4628                     if_deps);
4629         }
4630         inodedep = inodedep_lookup_ip(dp);
4631         if (DOINGSUJ(dvp))
4632                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4633                     &dotdotaddref->ja_ref, if_deps);
4634         softdep_prelink(ITOV(dp), NULL);
4635         FREE_LOCK(&lk);
4636 }
4637
4638 /*
4639  * Called to track nlinkdelta of the inode and parent directories prior to
4640  * unlinking a directory.
4641  */
4642 void
4643 softdep_setup_rmdir(dp, ip)
4644         struct inode *dp;
4645         struct inode *ip;
4646 {
4647         struct vnode *dvp;
4648
4649         dvp = ITOV(dp);
4650         ACQUIRE_LOCK(&lk);
4651         (void) inodedep_lookup_ip(ip);
4652         (void) inodedep_lookup_ip(dp);
4653         softdep_prelink(dvp, ITOV(ip));
4654         FREE_LOCK(&lk);
4655 }
4656
4657 /*
4658  * Called to track nlinkdelta of the inode and parent directories prior to
4659  * unlink.
4660  */
4661 void
4662 softdep_setup_unlink(dp, ip)
4663         struct inode *dp;
4664         struct inode *ip;
4665 {
4666         struct vnode *dvp;
4667
4668         dvp = ITOV(dp);
4669         ACQUIRE_LOCK(&lk);
4670         (void) inodedep_lookup_ip(ip);
4671         (void) inodedep_lookup_ip(dp);
4672         softdep_prelink(dvp, ITOV(ip));
4673         FREE_LOCK(&lk);
4674 }
4675
4676 /*
4677  * Called to release the journal structures created by a failed non-directory
4678  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4679  */
4680 void
4681 softdep_revert_create(dp, ip)
4682         struct inode *dp;
4683         struct inode *ip;
4684 {
4685         struct inodedep *inodedep;
4686         struct jaddref *jaddref;
4687         struct vnode *dvp;
4688
4689         dvp = ITOV(dp);
4690         ACQUIRE_LOCK(&lk);
4691         inodedep = inodedep_lookup_ip(ip);
4692         if (DOINGSUJ(dvp)) {
4693                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4694                     inoreflst);
4695                 KASSERT(jaddref->ja_parent == dp->i_number,
4696                     ("softdep_revert_create: addref parent mismatch"));
4697                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4698         }
4699         FREE_LOCK(&lk);
4700 }
4701
4702 /*
4703  * Called to release the journal structures created by a failed dotdot link
4704  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4705  */
4706 void
4707 softdep_revert_dotdot_link(dp, ip)
4708         struct inode *dp;
4709         struct inode *ip;
4710 {
4711         struct inodedep *inodedep;
4712         struct jaddref *jaddref;
4713         struct vnode *dvp;
4714
4715         dvp = ITOV(dp);
4716         ACQUIRE_LOCK(&lk);
4717         inodedep = inodedep_lookup_ip(dp);
4718         if (DOINGSUJ(dvp)) {
4719                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4720                     inoreflst);
4721                 KASSERT(jaddref->ja_parent == ip->i_number,
4722                     ("softdep_revert_dotdot_link: addref parent mismatch"));
4723                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4724         }
4725         FREE_LOCK(&lk);
4726 }
4727
4728 /*
4729  * Called to release the journal structures created by a failed link
4730  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4731  */
4732 void
4733 softdep_revert_link(dp, ip)
4734         struct inode *dp;
4735         struct inode *ip;
4736 {
4737         struct inodedep *inodedep;
4738         struct jaddref *jaddref;
4739         struct vnode *dvp;
4740
4741         dvp = ITOV(dp);
4742         ACQUIRE_LOCK(&lk);
4743         inodedep = inodedep_lookup_ip(ip);
4744         if (DOINGSUJ(dvp)) {
4745                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4746                     inoreflst);
4747                 KASSERT(jaddref->ja_parent == dp->i_number,
4748                     ("softdep_revert_link: addref parent mismatch"));
4749                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4750         }
4751         FREE_LOCK(&lk);
4752 }
4753
4754 /*
4755  * Called to release the journal structures created by a failed mkdir
4756  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4757  */
4758 void
4759 softdep_revert_mkdir(dp, ip)
4760         struct inode *dp;
4761         struct inode *ip;
4762 {
4763         struct inodedep *inodedep;
4764         struct jaddref *jaddref;
4765         struct jaddref *dotaddref;
4766         struct vnode *dvp;
4767
4768         dvp = ITOV(dp);
4769
4770         ACQUIRE_LOCK(&lk);
4771         inodedep = inodedep_lookup_ip(dp);
4772         if (DOINGSUJ(dvp)) {
4773                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4774                     inoreflst);
4775                 KASSERT(jaddref->ja_parent == ip->i_number,
4776                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4777                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4778         }
4779         inodedep = inodedep_lookup_ip(ip);
4780         if (DOINGSUJ(dvp)) {
4781                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4782                     inoreflst);
4783                 KASSERT(jaddref->ja_parent == dp->i_number,
4784                     ("softdep_revert_mkdir: addref parent mismatch"));
4785                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4786                     inoreflst, if_deps);
4787                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4788                 KASSERT(dotaddref->ja_parent == ip->i_number,
4789                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4790                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4791         }
4792         FREE_LOCK(&lk);
4793 }
4794
4795 /* 
4796  * Called to correct nlinkdelta after a failed rmdir.
4797  */
4798 void
4799 softdep_revert_rmdir(dp, ip)
4800         struct inode *dp;
4801         struct inode *ip;
4802 {
4803
4804         ACQUIRE_LOCK(&lk);
4805         (void) inodedep_lookup_ip(ip);
4806         (void) inodedep_lookup_ip(dp);
4807         FREE_LOCK(&lk);
4808 }
4809
4810 /*
4811  * Protecting the freemaps (or bitmaps).
4812  * 
4813  * To eliminate the need to execute fsck before mounting a filesystem
4814  * after a power failure, one must (conservatively) guarantee that the
4815  * on-disk copy of the bitmaps never indicate that a live inode or block is
4816  * free.  So, when a block or inode is allocated, the bitmap should be
4817  * updated (on disk) before any new pointers.  When a block or inode is
4818  * freed, the bitmap should not be updated until all pointers have been
4819  * reset.  The latter dependency is handled by the delayed de-allocation
4820  * approach described below for block and inode de-allocation.  The former
4821  * dependency is handled by calling the following procedure when a block or
4822  * inode is allocated. When an inode is allocated an "inodedep" is created
4823  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4824  * Each "inodedep" is also inserted into the hash indexing structure so
4825  * that any additional link additions can be made dependent on the inode
4826  * allocation.
4827  * 
4828  * The ufs filesystem maintains a number of free block counts (e.g., per
4829  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4830  * in addition to the bitmaps.  These counts are used to improve efficiency
4831  * during allocation and therefore must be consistent with the bitmaps.
4832  * There is no convenient way to guarantee post-crash consistency of these
4833  * counts with simple update ordering, for two main reasons: (1) The counts
4834  * and bitmaps for a single cylinder group block are not in the same disk
4835  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4836  * be written and the other not.  (2) Some of the counts are located in the
4837  * superblock rather than the cylinder group block. So, we focus our soft
4838  * updates implementation on protecting the bitmaps. When mounting a
4839  * filesystem, we recompute the auxiliary counts from the bitmaps.
4840  */
4841
4842 /*
4843  * Called just after updating the cylinder group block to allocate an inode.
4844  */
4845 void
4846 softdep_setup_inomapdep(bp, ip, newinum, mode)
4847         struct buf *bp;         /* buffer for cylgroup block with inode map */
4848         struct inode *ip;       /* inode related to allocation */
4849         ino_t newinum;          /* new inode number being allocated */
4850         int mode;
4851 {
4852         struct inodedep *inodedep;
4853         struct bmsafemap *bmsafemap;
4854         struct jaddref *jaddref;
4855         struct mount *mp;
4856         struct fs *fs;
4857
4858         mp = UFSTOVFS(ip->i_ump);
4859         fs = ip->i_ump->um_fs;
4860         jaddref = NULL;
4861
4862         /*
4863          * Allocate the journal reference add structure so that the bitmap
4864          * can be dependent on it.
4865          */
4866         if (MOUNTEDSUJ(mp)) {
4867                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
4868                 jaddref->ja_state |= NEWBLOCK;
4869         }
4870
4871         /*
4872          * Create a dependency for the newly allocated inode.
4873          * Panic if it already exists as something is seriously wrong.
4874          * Otherwise add it to the dependency list for the buffer holding
4875          * the cylinder group map from which it was allocated.
4876          *
4877          * We have to preallocate a bmsafemap entry in case it is needed
4878          * in bmsafemap_lookup since once we allocate the inodedep, we
4879          * have to finish initializing it before we can FREE_LOCK().
4880          * By preallocating, we avoid FREE_LOCK() while doing a malloc
4881          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
4882          * creating the inodedep as it can be freed during the time
4883          * that we FREE_LOCK() while allocating the inodedep. We must
4884          * call workitem_alloc() before entering the locked section as
4885          * it also acquires the lock and we must avoid trying doing so
4886          * recursively.
4887          */
4888         bmsafemap = malloc(sizeof(struct bmsafemap),
4889             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4890         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4891         ACQUIRE_LOCK(&lk);
4892         if ((inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep)))
4893                 panic("softdep_setup_inomapdep: dependency %p for new"
4894                     "inode already exists", inodedep);
4895         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
4896         if (jaddref) {
4897                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4898                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4899                     if_deps);
4900         } else {
4901                 inodedep->id_state |= ONDEPLIST;
4902                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4903         }
4904         inodedep->id_bmsafemap = bmsafemap;
4905         inodedep->id_state &= ~DEPCOMPLETE;
4906         FREE_LOCK(&lk);
4907 }
4908
4909 /*
4910  * Called just after updating the cylinder group block to
4911  * allocate block or fragment.
4912  */
4913 void
4914 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4915         struct buf *bp;         /* buffer for cylgroup block with block map */
4916         struct mount *mp;       /* filesystem doing allocation */
4917         ufs2_daddr_t newblkno;  /* number of newly allocated block */
4918         int frags;              /* Number of fragments. */
4919         int oldfrags;           /* Previous number of fragments for extend. */
4920 {
4921         struct newblk *newblk;
4922         struct bmsafemap *bmsafemap;
4923         struct jnewblk *jnewblk;
4924         struct fs *fs;
4925
4926         fs = VFSTOUFS(mp)->um_fs;
4927         jnewblk = NULL;
4928         /*
4929          * Create a dependency for the newly allocated block.
4930          * Add it to the dependency list for the buffer holding
4931          * the cylinder group map from which it was allocated.
4932          */
4933         if (MOUNTEDSUJ(mp)) {
4934                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4935                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4936                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4937                 jnewblk->jn_state = ATTACHED;
4938                 jnewblk->jn_blkno = newblkno;
4939                 jnewblk->jn_frags = frags;
4940                 jnewblk->jn_oldfrags = oldfrags;
4941 #ifdef SUJ_DEBUG
4942                 {
4943                         struct cg *cgp;
4944                         uint8_t *blksfree;
4945                         long bno;
4946                         int i;
4947         
4948                         cgp = (struct cg *)bp->b_data;
4949                         blksfree = cg_blksfree(cgp);
4950                         bno = dtogd(fs, jnewblk->jn_blkno);
4951                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4952                             i++) {
4953                                 if (isset(blksfree, bno + i))
4954                                         panic("softdep_setup_blkmapdep: "
4955                                             "free fragment %d from %d-%d "
4956                                             "state 0x%X dep %p", i,
4957                                             jnewblk->jn_oldfrags,
4958                                             jnewblk->jn_frags,
4959                                             jnewblk->jn_state,
4960                                             jnewblk->jn_dep);
4961                         }
4962                 }
4963 #endif
4964         }
4965
4966         CTR3(KTR_SUJ,
4967             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
4968             newblkno, frags, oldfrags);
4969         ACQUIRE_LOCK(&lk);
4970         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4971                 panic("softdep_setup_blkmapdep: found block");
4972         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4973             dtog(fs, newblkno), NULL);
4974         if (jnewblk) {
4975                 jnewblk->jn_dep = (struct worklist *)newblk;
4976                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4977         } else {
4978                 newblk->nb_state |= ONDEPLIST;
4979                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4980         }
4981         newblk->nb_bmsafemap = bmsafemap;
4982         newblk->nb_jnewblk = jnewblk;
4983         FREE_LOCK(&lk);
4984 }
4985
4986 #define BMSAFEMAP_HASH(fs, cg) \
4987       (&bmsafemap_hashtbl[((((register_t)(fs)) >> 13) + (cg)) & bmsafemap_hash])
4988
4989 static int
4990 bmsafemap_find(bmsafemaphd, mp, cg, bmsafemapp)
4991         struct bmsafemap_hashhead *bmsafemaphd;
4992         struct mount *mp;
4993         int cg;
4994         struct bmsafemap **bmsafemapp;
4995 {
4996         struct bmsafemap *bmsafemap;
4997
4998         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
4999                 if (bmsafemap->sm_list.wk_mp == mp && bmsafemap->sm_cg == cg)
5000                         break;
5001         if (bmsafemap) {
5002                 *bmsafemapp = bmsafemap;
5003                 return (1);
5004         }
5005         *bmsafemapp = NULL;
5006
5007         return (0);
5008 }
5009
5010 /*
5011  * Find the bmsafemap associated with a cylinder group buffer.
5012  * If none exists, create one. The buffer must be locked when
5013  * this routine is called and this routine must be called with
5014  * the softdep lock held. To avoid giving up the lock while
5015  * allocating a new bmsafemap, a preallocated bmsafemap may be
5016  * provided. If it is provided but not needed, it is freed.
5017  */
5018 static struct bmsafemap *
5019 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5020         struct mount *mp;
5021         struct buf *bp;
5022         int cg;
5023         struct bmsafemap *newbmsafemap;
5024 {
5025         struct bmsafemap_hashhead *bmsafemaphd;
5026         struct bmsafemap *bmsafemap, *collision;
5027         struct worklist *wk;
5028         struct fs *fs;
5029
5030         mtx_assert(&lk, MA_OWNED);
5031         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5032         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5033                 if (wk->wk_type == D_BMSAFEMAP) {
5034                         if (newbmsafemap)
5035                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5036                         return (WK_BMSAFEMAP(wk));
5037                 }
5038         }
5039         fs = VFSTOUFS(mp)->um_fs;
5040         bmsafemaphd = BMSAFEMAP_HASH(fs, cg);
5041         if (bmsafemap_find(bmsafemaphd, mp, cg, &bmsafemap) == 1) {
5042                 if (newbmsafemap)
5043                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5044                 return (bmsafemap);
5045         }
5046         if (newbmsafemap) {
5047                 bmsafemap = newbmsafemap;
5048         } else {
5049                 FREE_LOCK(&lk);
5050                 bmsafemap = malloc(sizeof(struct bmsafemap),
5051                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5052                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5053                 ACQUIRE_LOCK(&lk);
5054         }
5055         bmsafemap->sm_buf = bp;
5056         LIST_INIT(&bmsafemap->sm_inodedephd);
5057         LIST_INIT(&bmsafemap->sm_inodedepwr);
5058         LIST_INIT(&bmsafemap->sm_newblkhd);
5059         LIST_INIT(&bmsafemap->sm_newblkwr);
5060         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5061         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5062         LIST_INIT(&bmsafemap->sm_freehd);
5063         LIST_INIT(&bmsafemap->sm_freewr);
5064         if (bmsafemap_find(bmsafemaphd, mp, cg, &collision) == 1) {
5065                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5066                 return (collision);
5067         }
5068         bmsafemap->sm_cg = cg;
5069         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5070         LIST_INSERT_HEAD(&VFSTOUFS(mp)->softdep_dirtycg, bmsafemap, sm_next);
5071         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5072         return (bmsafemap);
5073 }
5074
5075 /*
5076  * Direct block allocation dependencies.
5077  * 
5078  * When a new block is allocated, the corresponding disk locations must be
5079  * initialized (with zeros or new data) before the on-disk inode points to
5080  * them.  Also, the freemap from which the block was allocated must be
5081  * updated (on disk) before the inode's pointer. These two dependencies are
5082  * independent of each other and are needed for all file blocks and indirect
5083  * blocks that are pointed to directly by the inode.  Just before the
5084  * "in-core" version of the inode is updated with a newly allocated block
5085  * number, a procedure (below) is called to setup allocation dependency
5086  * structures.  These structures are removed when the corresponding
5087  * dependencies are satisfied or when the block allocation becomes obsolete
5088  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5089  * fragment that gets upgraded).  All of these cases are handled in
5090  * procedures described later.
5091  * 
5092  * When a file extension causes a fragment to be upgraded, either to a larger
5093  * fragment or to a full block, the on-disk location may change (if the
5094  * previous fragment could not simply be extended). In this case, the old
5095  * fragment must be de-allocated, but not until after the inode's pointer has
5096  * been updated. In most cases, this is handled by later procedures, which
5097  * will construct a "freefrag" structure to be added to the workitem queue
5098  * when the inode update is complete (or obsolete).  The main exception to
5099  * this is when an allocation occurs while a pending allocation dependency
5100  * (for the same block pointer) remains.  This case is handled in the main
5101  * allocation dependency setup procedure by immediately freeing the
5102  * unreferenced fragments.
5103  */ 
5104 void 
5105 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5106         struct inode *ip;       /* inode to which block is being added */
5107         ufs_lbn_t off;          /* block pointer within inode */
5108         ufs2_daddr_t newblkno;  /* disk block number being added */
5109         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5110         long newsize;           /* size of new block */
5111         long oldsize;           /* size of new block */
5112         struct buf *bp;         /* bp for allocated block */
5113 {
5114         struct allocdirect *adp, *oldadp;
5115         struct allocdirectlst *adphead;
5116         struct freefrag *freefrag;
5117         struct inodedep *inodedep;
5118         struct pagedep *pagedep;
5119         struct jnewblk *jnewblk;
5120         struct newblk *newblk;
5121         struct mount *mp;
5122         ufs_lbn_t lbn;
5123
5124         lbn = bp->b_lblkno;
5125         mp = UFSTOVFS(ip->i_ump);
5126         if (oldblkno && oldblkno != newblkno)
5127                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5128         else
5129                 freefrag = NULL;
5130
5131         CTR6(KTR_SUJ,
5132             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5133             "off %jd newsize %ld oldsize %d",
5134             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5135         ACQUIRE_LOCK(&lk);
5136         if (off >= NDADDR) {
5137                 if (lbn > 0)
5138                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5139                             lbn, off);
5140                 /* allocating an indirect block */
5141                 if (oldblkno != 0)
5142                         panic("softdep_setup_allocdirect: non-zero indir");
5143         } else {
5144                 if (off != lbn)
5145                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5146                             lbn, off);
5147                 /*
5148                  * Allocating a direct block.
5149                  *
5150                  * If we are allocating a directory block, then we must
5151                  * allocate an associated pagedep to track additions and
5152                  * deletions.
5153                  */
5154                 if ((ip->i_mode & IFMT) == IFDIR)
5155                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5156                             &pagedep);
5157         }
5158         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5159                 panic("softdep_setup_allocdirect: lost block");
5160         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5161             ("softdep_setup_allocdirect: newblk already initialized"));
5162         /*
5163          * Convert the newblk to an allocdirect.
5164          */
5165         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5166         adp = (struct allocdirect *)newblk;
5167         newblk->nb_freefrag = freefrag;
5168         adp->ad_offset = off;
5169         adp->ad_oldblkno = oldblkno;
5170         adp->ad_newsize = newsize;
5171         adp->ad_oldsize = oldsize;
5172
5173         /*
5174          * Finish initializing the journal.
5175          */
5176         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5177                 jnewblk->jn_ino = ip->i_number;
5178                 jnewblk->jn_lbn = lbn;
5179                 add_to_journal(&jnewblk->jn_list);
5180         }
5181         if (freefrag && freefrag->ff_jdep != NULL &&
5182             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5183                 add_to_journal(freefrag->ff_jdep);
5184         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5185         adp->ad_inodedep = inodedep;
5186
5187         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5188         /*
5189          * The list of allocdirects must be kept in sorted and ascending
5190          * order so that the rollback routines can quickly determine the
5191          * first uncommitted block (the size of the file stored on disk
5192          * ends at the end of the lowest committed fragment, or if there
5193          * are no fragments, at the end of the highest committed block).
5194          * Since files generally grow, the typical case is that the new
5195          * block is to be added at the end of the list. We speed this
5196          * special case by checking against the last allocdirect in the
5197          * list before laboriously traversing the list looking for the
5198          * insertion point.
5199          */
5200         adphead = &inodedep->id_newinoupdt;
5201         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5202         if (oldadp == NULL || oldadp->ad_offset <= off) {
5203                 /* insert at end of list */
5204                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5205                 if (oldadp != NULL && oldadp->ad_offset == off)
5206                         allocdirect_merge(adphead, adp, oldadp);
5207                 FREE_LOCK(&lk);
5208                 return;
5209         }
5210         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5211                 if (oldadp->ad_offset >= off)
5212                         break;
5213         }
5214         if (oldadp == NULL)
5215                 panic("softdep_setup_allocdirect: lost entry");
5216         /* insert in middle of list */
5217         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5218         if (oldadp->ad_offset == off)
5219                 allocdirect_merge(adphead, adp, oldadp);
5220
5221         FREE_LOCK(&lk);
5222 }
5223
5224 /*
5225  * Merge a newer and older journal record to be stored either in a
5226  * newblock or freefrag.  This handles aggregating journal records for
5227  * fragment allocation into a second record as well as replacing a
5228  * journal free with an aborted journal allocation.  A segment for the
5229  * oldest record will be placed on wkhd if it has been written.  If not
5230  * the segment for the newer record will suffice.
5231  */
5232 static struct worklist *
5233 jnewblk_merge(new, old, wkhd)
5234         struct worklist *new;
5235         struct worklist *old;
5236         struct workhead *wkhd;
5237 {
5238         struct jnewblk *njnewblk;
5239         struct jnewblk *jnewblk;
5240
5241         /* Handle NULLs to simplify callers. */
5242         if (new == NULL)
5243                 return (old);
5244         if (old == NULL)
5245                 return (new);
5246         /* Replace a jfreefrag with a jnewblk. */
5247         if (new->wk_type == D_JFREEFRAG) {
5248                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5249                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5250                             old, new);
5251                 cancel_jfreefrag(WK_JFREEFRAG(new));
5252                 return (old);
5253         }
5254         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5255                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5256                     old->wk_type, new->wk_type);
5257         /*
5258          * Handle merging of two jnewblk records that describe
5259          * different sets of fragments in the same block.
5260          */
5261         jnewblk = WK_JNEWBLK(old);
5262         njnewblk = WK_JNEWBLK(new);
5263         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5264                 panic("jnewblk_merge: Merging disparate blocks.");
5265         /*
5266          * The record may be rolled back in the cg.
5267          */
5268         if (jnewblk->jn_state & UNDONE) {
5269                 jnewblk->jn_state &= ~UNDONE;
5270                 njnewblk->jn_state |= UNDONE;
5271                 njnewblk->jn_state &= ~ATTACHED;
5272         }
5273         /*
5274          * We modify the newer addref and free the older so that if neither
5275          * has been written the most up-to-date copy will be on disk.  If
5276          * both have been written but rolled back we only temporarily need
5277          * one of them to fix the bits when the cg write completes.
5278          */
5279         jnewblk->jn_state |= ATTACHED | COMPLETE;
5280         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5281         cancel_jnewblk(jnewblk, wkhd);
5282         WORKLIST_REMOVE(&jnewblk->jn_list);
5283         free_jnewblk(jnewblk);
5284         return (new);
5285 }
5286
5287 /*
5288  * Replace an old allocdirect dependency with a newer one.
5289  * This routine must be called with splbio interrupts blocked.
5290  */
5291 static void
5292 allocdirect_merge(adphead, newadp, oldadp)
5293         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5294         struct allocdirect *newadp;     /* allocdirect being added */
5295         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5296 {
5297         struct worklist *wk;
5298         struct freefrag *freefrag;
5299
5300         freefrag = NULL;
5301         mtx_assert(&lk, MA_OWNED);
5302         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5303             newadp->ad_oldsize != oldadp->ad_newsize ||
5304             newadp->ad_offset >= NDADDR)
5305                 panic("%s %jd != new %jd || old size %ld != new %ld",
5306                     "allocdirect_merge: old blkno",
5307                     (intmax_t)newadp->ad_oldblkno,
5308                     (intmax_t)oldadp->ad_newblkno,
5309                     newadp->ad_oldsize, oldadp->ad_newsize);
5310         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5311         newadp->ad_oldsize = oldadp->ad_oldsize;
5312         /*
5313          * If the old dependency had a fragment to free or had never
5314          * previously had a block allocated, then the new dependency
5315          * can immediately post its freefrag and adopt the old freefrag.
5316          * This action is done by swapping the freefrag dependencies.
5317          * The new dependency gains the old one's freefrag, and the
5318          * old one gets the new one and then immediately puts it on
5319          * the worklist when it is freed by free_newblk. It is
5320          * not possible to do this swap when the old dependency had a
5321          * non-zero size but no previous fragment to free. This condition
5322          * arises when the new block is an extension of the old block.
5323          * Here, the first part of the fragment allocated to the new
5324          * dependency is part of the block currently claimed on disk by
5325          * the old dependency, so cannot legitimately be freed until the
5326          * conditions for the new dependency are fulfilled.
5327          */
5328         freefrag = newadp->ad_freefrag;
5329         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5330                 newadp->ad_freefrag = oldadp->ad_freefrag;
5331                 oldadp->ad_freefrag = freefrag;
5332         }
5333         /*
5334          * If we are tracking a new directory-block allocation,
5335          * move it from the old allocdirect to the new allocdirect.
5336          */
5337         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5338                 WORKLIST_REMOVE(wk);
5339                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5340                         panic("allocdirect_merge: extra newdirblk");
5341                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5342         }
5343         TAILQ_REMOVE(adphead, oldadp, ad_next);
5344         /*
5345          * We need to move any journal dependencies over to the freefrag
5346          * that releases this block if it exists.  Otherwise we are
5347          * extending an existing block and we'll wait until that is
5348          * complete to release the journal space and extend the
5349          * new journal to cover this old space as well.
5350          */
5351         if (freefrag == NULL) {
5352                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5353                         panic("allocdirect_merge: %jd != %jd",
5354                             oldadp->ad_newblkno, newadp->ad_newblkno);
5355                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5356                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5357                     &oldadp->ad_block.nb_jnewblk->jn_list,
5358                     &newadp->ad_block.nb_jwork);
5359                 oldadp->ad_block.nb_jnewblk = NULL;
5360                 cancel_newblk(&oldadp->ad_block, NULL,
5361                     &newadp->ad_block.nb_jwork);
5362         } else {
5363                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5364                     &freefrag->ff_list, &freefrag->ff_jwork);
5365                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5366                     &freefrag->ff_jwork);
5367         }
5368         free_newblk(&oldadp->ad_block);
5369 }
5370
5371 /*
5372  * Allocate a jfreefrag structure to journal a single block free.
5373  */
5374 static struct jfreefrag *
5375 newjfreefrag(freefrag, ip, blkno, size, lbn)
5376         struct freefrag *freefrag;
5377         struct inode *ip;
5378         ufs2_daddr_t blkno;
5379         long size;
5380         ufs_lbn_t lbn;
5381 {
5382         struct jfreefrag *jfreefrag;
5383         struct fs *fs;
5384
5385         fs = ip->i_fs;
5386         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5387             M_SOFTDEP_FLAGS);
5388         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5389         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5390         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5391         jfreefrag->fr_ino = ip->i_number;
5392         jfreefrag->fr_lbn = lbn;
5393         jfreefrag->fr_blkno = blkno;
5394         jfreefrag->fr_frags = numfrags(fs, size);
5395         jfreefrag->fr_freefrag = freefrag;
5396
5397         return (jfreefrag);
5398 }
5399
5400 /*
5401  * Allocate a new freefrag structure.
5402  */
5403 static struct freefrag *
5404 newfreefrag(ip, blkno, size, lbn)
5405         struct inode *ip;
5406         ufs2_daddr_t blkno;
5407         long size;
5408         ufs_lbn_t lbn;
5409 {
5410         struct freefrag *freefrag;
5411         struct fs *fs;
5412
5413         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5414             ip->i_number, blkno, size, lbn);
5415         fs = ip->i_fs;
5416         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5417                 panic("newfreefrag: frag size");
5418         freefrag = malloc(sizeof(struct freefrag),
5419             M_FREEFRAG, M_SOFTDEP_FLAGS);
5420         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5421         freefrag->ff_state = ATTACHED;
5422         LIST_INIT(&freefrag->ff_jwork);
5423         freefrag->ff_inum = ip->i_number;
5424         freefrag->ff_vtype = ITOV(ip)->v_type;
5425         freefrag->ff_blkno = blkno;
5426         freefrag->ff_fragsize = size;
5427
5428         if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5429                 freefrag->ff_jdep = (struct worklist *)
5430                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5431         } else {
5432                 freefrag->ff_state |= DEPCOMPLETE;
5433                 freefrag->ff_jdep = NULL;
5434         }
5435
5436         return (freefrag);
5437 }
5438
5439 /*
5440  * This workitem de-allocates fragments that were replaced during
5441  * file block allocation.
5442  */
5443 static void 
5444 handle_workitem_freefrag(freefrag)
5445         struct freefrag *freefrag;
5446 {
5447         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5448         struct workhead wkhd;
5449
5450         CTR3(KTR_SUJ,
5451             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5452             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5453         /*
5454          * It would be illegal to add new completion items to the
5455          * freefrag after it was schedule to be done so it must be
5456          * safe to modify the list head here.
5457          */
5458         LIST_INIT(&wkhd);
5459         ACQUIRE_LOCK(&lk);
5460         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5461         /*
5462          * If the journal has not been written we must cancel it here.
5463          */
5464         if (freefrag->ff_jdep) {
5465                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5466                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5467                             freefrag->ff_jdep->wk_type);
5468                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5469         }
5470         FREE_LOCK(&lk);
5471         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5472            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5473         ACQUIRE_LOCK(&lk);
5474         WORKITEM_FREE(freefrag, D_FREEFRAG);
5475         FREE_LOCK(&lk);
5476 }
5477
5478 /*
5479  * Set up a dependency structure for an external attributes data block.
5480  * This routine follows much of the structure of softdep_setup_allocdirect.
5481  * See the description of softdep_setup_allocdirect above for details.
5482  */
5483 void 
5484 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5485         struct inode *ip;
5486         ufs_lbn_t off;
5487         ufs2_daddr_t newblkno;
5488         ufs2_daddr_t oldblkno;
5489         long newsize;
5490         long oldsize;
5491         struct buf *bp;
5492 {
5493         struct allocdirect *adp, *oldadp;
5494         struct allocdirectlst *adphead;
5495         struct freefrag *freefrag;
5496         struct inodedep *inodedep;
5497         struct jnewblk *jnewblk;
5498         struct newblk *newblk;
5499         struct mount *mp;
5500         ufs_lbn_t lbn;
5501
5502         if (off >= NXADDR)
5503                 panic("softdep_setup_allocext: lbn %lld > NXADDR",
5504                     (long long)off);
5505
5506         lbn = bp->b_lblkno;
5507         mp = UFSTOVFS(ip->i_ump);
5508         if (oldblkno && oldblkno != newblkno)
5509                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5510         else
5511                 freefrag = NULL;
5512
5513         ACQUIRE_LOCK(&lk);
5514         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5515                 panic("softdep_setup_allocext: lost block");
5516         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5517             ("softdep_setup_allocext: newblk already initialized"));
5518         /*
5519          * Convert the newblk to an allocdirect.
5520          */
5521         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5522         adp = (struct allocdirect *)newblk;
5523         newblk->nb_freefrag = freefrag;
5524         adp->ad_offset = off;
5525         adp->ad_oldblkno = oldblkno;
5526         adp->ad_newsize = newsize;
5527         adp->ad_oldsize = oldsize;
5528         adp->ad_state |=  EXTDATA;
5529
5530         /*
5531          * Finish initializing the journal.
5532          */
5533         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5534                 jnewblk->jn_ino = ip->i_number;
5535                 jnewblk->jn_lbn = lbn;
5536                 add_to_journal(&jnewblk->jn_list);
5537         }
5538         if (freefrag && freefrag->ff_jdep != NULL &&
5539             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5540                 add_to_journal(freefrag->ff_jdep);
5541         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5542         adp->ad_inodedep = inodedep;
5543
5544         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5545         /*
5546          * The list of allocdirects must be kept in sorted and ascending
5547          * order so that the rollback routines can quickly determine the
5548          * first uncommitted block (the size of the file stored on disk
5549          * ends at the end of the lowest committed fragment, or if there
5550          * are no fragments, at the end of the highest committed block).
5551          * Since files generally grow, the typical case is that the new
5552          * block is to be added at the end of the list. We speed this
5553          * special case by checking against the last allocdirect in the
5554          * list before laboriously traversing the list looking for the
5555          * insertion point.
5556          */
5557         adphead = &inodedep->id_newextupdt;
5558         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5559         if (oldadp == NULL || oldadp->ad_offset <= off) {
5560                 /* insert at end of list */
5561                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5562                 if (oldadp != NULL && oldadp->ad_offset == off)
5563                         allocdirect_merge(adphead, adp, oldadp);
5564                 FREE_LOCK(&lk);
5565                 return;
5566         }
5567         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5568                 if (oldadp->ad_offset >= off)
5569                         break;
5570         }
5571         if (oldadp == NULL)
5572                 panic("softdep_setup_allocext: lost entry");
5573         /* insert in middle of list */
5574         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5575         if (oldadp->ad_offset == off)
5576                 allocdirect_merge(adphead, adp, oldadp);
5577         FREE_LOCK(&lk);
5578 }
5579
5580 /*
5581  * Indirect block allocation dependencies.
5582  * 
5583  * The same dependencies that exist for a direct block also exist when
5584  * a new block is allocated and pointed to by an entry in a block of
5585  * indirect pointers. The undo/redo states described above are also
5586  * used here. Because an indirect block contains many pointers that
5587  * may have dependencies, a second copy of the entire in-memory indirect
5588  * block is kept. The buffer cache copy is always completely up-to-date.
5589  * The second copy, which is used only as a source for disk writes,
5590  * contains only the safe pointers (i.e., those that have no remaining
5591  * update dependencies). The second copy is freed when all pointers
5592  * are safe. The cache is not allowed to replace indirect blocks with
5593  * pending update dependencies. If a buffer containing an indirect
5594  * block with dependencies is written, these routines will mark it
5595  * dirty again. It can only be successfully written once all the
5596  * dependencies are removed. The ffs_fsync routine in conjunction with
5597  * softdep_sync_metadata work together to get all the dependencies
5598  * removed so that a file can be successfully written to disk. Three
5599  * procedures are used when setting up indirect block pointer
5600  * dependencies. The division is necessary because of the organization
5601  * of the "balloc" routine and because of the distinction between file
5602  * pages and file metadata blocks.
5603  */
5604
5605 /*
5606  * Allocate a new allocindir structure.
5607  */
5608 static struct allocindir *
5609 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5610         struct inode *ip;       /* inode for file being extended */
5611         int ptrno;              /* offset of pointer in indirect block */
5612         ufs2_daddr_t newblkno;  /* disk block number being added */
5613         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5614         ufs_lbn_t lbn;
5615 {
5616         struct newblk *newblk;
5617         struct allocindir *aip;
5618         struct freefrag *freefrag;
5619         struct jnewblk *jnewblk;
5620
5621         if (oldblkno)
5622                 freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5623         else
5624                 freefrag = NULL;
5625         ACQUIRE_LOCK(&lk);
5626         if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5627                 panic("new_allocindir: lost block");
5628         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5629             ("newallocindir: newblk already initialized"));
5630         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5631         newblk->nb_freefrag = freefrag;
5632         aip = (struct allocindir *)newblk;
5633         aip->ai_offset = ptrno;
5634         aip->ai_oldblkno = oldblkno;
5635         aip->ai_lbn = lbn;
5636         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5637                 jnewblk->jn_ino = ip->i_number;
5638                 jnewblk->jn_lbn = lbn;
5639                 add_to_journal(&jnewblk->jn_list);
5640         }
5641         if (freefrag && freefrag->ff_jdep != NULL &&
5642             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5643                 add_to_journal(freefrag->ff_jdep);
5644         return (aip);
5645 }
5646
5647 /*
5648  * Called just before setting an indirect block pointer
5649  * to a newly allocated file page.
5650  */
5651 void
5652 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5653         struct inode *ip;       /* inode for file being extended */
5654         ufs_lbn_t lbn;          /* allocated block number within file */
5655         struct buf *bp;         /* buffer with indirect blk referencing page */
5656         int ptrno;              /* offset of pointer in indirect block */
5657         ufs2_daddr_t newblkno;  /* disk block number being added */
5658         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5659         struct buf *nbp;        /* buffer holding allocated page */
5660 {
5661         struct inodedep *inodedep;
5662         struct freefrag *freefrag;
5663         struct allocindir *aip;
5664         struct pagedep *pagedep;
5665         struct mount *mp;
5666         int dflags;
5667
5668         if (lbn != nbp->b_lblkno)
5669                 panic("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5670                     lbn, bp->b_lblkno);
5671         CTR4(KTR_SUJ,
5672             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5673             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5674         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5675         mp = UFSTOVFS(ip->i_ump);
5676         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5677         dflags = DEPALLOC;
5678         if (IS_SNAPSHOT(ip))
5679                 dflags |= NODELAY;
5680         (void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
5681         /*
5682          * If we are allocating a directory page, then we must
5683          * allocate an associated pagedep to track additions and
5684          * deletions.
5685          */
5686         if ((ip->i_mode & IFMT) == IFDIR)
5687                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5688         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5689         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5690         FREE_LOCK(&lk);
5691         if (freefrag)
5692                 handle_workitem_freefrag(freefrag);
5693 }
5694
5695 /*
5696  * Called just before setting an indirect block pointer to a
5697  * newly allocated indirect block.
5698  */
5699 void
5700 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5701         struct buf *nbp;        /* newly allocated indirect block */
5702         struct inode *ip;       /* inode for file being extended */
5703         struct buf *bp;         /* indirect block referencing allocated block */
5704         int ptrno;              /* offset of pointer in indirect block */
5705         ufs2_daddr_t newblkno;  /* disk block number being added */
5706 {
5707         struct inodedep *inodedep;
5708         struct allocindir *aip;
5709         ufs_lbn_t lbn;
5710         int dflags;
5711
5712         CTR3(KTR_SUJ,
5713             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5714             ip->i_number, newblkno, ptrno);
5715         lbn = nbp->b_lblkno;
5716         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5717         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5718         dflags = DEPALLOC;
5719         if (IS_SNAPSHOT(ip))
5720                 dflags |= NODELAY;
5721         inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
5722         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5723         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5724                 panic("softdep_setup_allocindir_meta: Block already existed");
5725         FREE_LOCK(&lk);
5726 }
5727
5728 static void
5729 indirdep_complete(indirdep)
5730         struct indirdep *indirdep;
5731 {
5732         struct allocindir *aip;
5733
5734         LIST_REMOVE(indirdep, ir_next);
5735         indirdep->ir_state |= DEPCOMPLETE;
5736
5737         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5738                 LIST_REMOVE(aip, ai_next);
5739                 free_newblk(&aip->ai_block);
5740         }
5741         /*
5742          * If this indirdep is not attached to a buf it was simply waiting
5743          * on completion to clear completehd.  free_indirdep() asserts
5744          * that nothing is dangling.
5745          */
5746         if ((indirdep->ir_state & ONWORKLIST) == 0)
5747                 free_indirdep(indirdep);
5748 }
5749
5750 static struct indirdep *
5751 indirdep_lookup(mp, ip, bp)
5752         struct mount *mp;
5753         struct inode *ip;
5754         struct buf *bp;
5755 {
5756         struct indirdep *indirdep, *newindirdep;
5757         struct newblk *newblk;
5758         struct worklist *wk;
5759         struct fs *fs;
5760         ufs2_daddr_t blkno;
5761
5762         mtx_assert(&lk, MA_OWNED);
5763         indirdep = NULL;
5764         newindirdep = NULL;
5765         fs = ip->i_fs;
5766         for (;;) {
5767                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5768                         if (wk->wk_type != D_INDIRDEP)
5769                                 continue;
5770                         indirdep = WK_INDIRDEP(wk);
5771                         break;
5772                 }
5773                 /* Found on the buffer worklist, no new structure to free. */
5774                 if (indirdep != NULL && newindirdep == NULL)
5775                         return (indirdep);
5776                 if (indirdep != NULL && newindirdep != NULL)
5777                         panic("indirdep_lookup: simultaneous create");
5778                 /* None found on the buffer and a new structure is ready. */
5779                 if (indirdep == NULL && newindirdep != NULL)
5780                         break;
5781                 /* None found and no new structure available. */
5782                 FREE_LOCK(&lk);
5783                 newindirdep = malloc(sizeof(struct indirdep),
5784                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5785                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5786                 newindirdep->ir_state = ATTACHED;
5787                 if (ip->i_ump->um_fstype == UFS1)
5788                         newindirdep->ir_state |= UFS1FMT;
5789                 TAILQ_INIT(&newindirdep->ir_trunc);
5790                 newindirdep->ir_saveddata = NULL;
5791                 LIST_INIT(&newindirdep->ir_deplisthd);
5792                 LIST_INIT(&newindirdep->ir_donehd);
5793                 LIST_INIT(&newindirdep->ir_writehd);
5794                 LIST_INIT(&newindirdep->ir_completehd);
5795                 if (bp->b_blkno == bp->b_lblkno) {
5796                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5797                             NULL, NULL);
5798                         bp->b_blkno = blkno;
5799                 }
5800                 newindirdep->ir_freeblks = NULL;
5801                 newindirdep->ir_savebp =
5802                     getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5803                 newindirdep->ir_bp = bp;
5804                 BUF_KERNPROC(newindirdep->ir_savebp);
5805                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5806                 ACQUIRE_LOCK(&lk);
5807         }
5808         indirdep = newindirdep;
5809         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5810         /*
5811          * If the block is not yet allocated we don't set DEPCOMPLETE so
5812          * that we don't free dependencies until the pointers are valid.
5813          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5814          * than using the hash.
5815          */
5816         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5817                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5818         else
5819                 indirdep->ir_state |= DEPCOMPLETE;
5820         return (indirdep);
5821 }
5822
5823 /*
5824  * Called to finish the allocation of the "aip" allocated
5825  * by one of the two routines above.
5826  */
5827 static struct freefrag *
5828 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5829         struct buf *bp;         /* in-memory copy of the indirect block */
5830         struct inode *ip;       /* inode for file being extended */
5831         struct inodedep *inodedep; /* Inodedep for ip */
5832         struct allocindir *aip; /* allocindir allocated by the above routines */
5833         ufs_lbn_t lbn;          /* Logical block number for this block. */
5834 {
5835         struct fs *fs;
5836         struct indirdep *indirdep;
5837         struct allocindir *oldaip;
5838         struct freefrag *freefrag;
5839         struct mount *mp;
5840
5841         mtx_assert(&lk, MA_OWNED);
5842         mp = UFSTOVFS(ip->i_ump);
5843         fs = ip->i_fs;
5844         if (bp->b_lblkno >= 0)
5845                 panic("setup_allocindir_phase2: not indir blk");
5846         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
5847             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
5848         indirdep = indirdep_lookup(mp, ip, bp);
5849         KASSERT(indirdep->ir_savebp != NULL,
5850             ("setup_allocindir_phase2 NULL ir_savebp"));
5851         aip->ai_indirdep = indirdep;
5852         /*
5853          * Check for an unwritten dependency for this indirect offset.  If
5854          * there is, merge the old dependency into the new one.  This happens
5855          * as a result of reallocblk only.
5856          */
5857         freefrag = NULL;
5858         if (aip->ai_oldblkno != 0) {
5859                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
5860                         if (oldaip->ai_offset == aip->ai_offset) {
5861                                 freefrag = allocindir_merge(aip, oldaip);
5862                                 goto done;
5863                         }
5864                 }
5865                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
5866                         if (oldaip->ai_offset == aip->ai_offset) {
5867                                 freefrag = allocindir_merge(aip, oldaip);
5868                                 goto done;
5869                         }
5870                 }
5871         }
5872 done:
5873         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
5874         return (freefrag);
5875 }
5876
5877 /*
5878  * Merge two allocindirs which refer to the same block.  Move newblock
5879  * dependencies and setup the freefrags appropriately.
5880  */
5881 static struct freefrag *
5882 allocindir_merge(aip, oldaip)
5883         struct allocindir *aip;
5884         struct allocindir *oldaip;
5885 {
5886         struct freefrag *freefrag;
5887         struct worklist *wk;
5888
5889         if (oldaip->ai_newblkno != aip->ai_oldblkno)
5890                 panic("allocindir_merge: blkno");
5891         aip->ai_oldblkno = oldaip->ai_oldblkno;
5892         freefrag = aip->ai_freefrag;
5893         aip->ai_freefrag = oldaip->ai_freefrag;
5894         oldaip->ai_freefrag = NULL;
5895         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5896         /*
5897          * If we are tracking a new directory-block allocation,
5898          * move it from the old allocindir to the new allocindir.
5899          */
5900         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5901                 WORKLIST_REMOVE(wk);
5902                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5903                         panic("allocindir_merge: extra newdirblk");
5904                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
5905         }
5906         /*
5907          * We can skip journaling for this freefrag and just complete
5908          * any pending journal work for the allocindir that is being
5909          * removed after the freefrag completes.
5910          */
5911         if (freefrag->ff_jdep)
5912                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
5913         LIST_REMOVE(oldaip, ai_next);
5914         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
5915             &freefrag->ff_list, &freefrag->ff_jwork);
5916         free_newblk(&oldaip->ai_block);
5917
5918         return (freefrag);
5919 }
5920
5921 static inline void
5922 setup_freedirect(freeblks, ip, i, needj)
5923         struct freeblks *freeblks;
5924         struct inode *ip;
5925         int i;
5926         int needj;
5927 {
5928         ufs2_daddr_t blkno;
5929         int frags;
5930
5931         blkno = DIP(ip, i_db[i]);
5932         if (blkno == 0)
5933                 return;
5934         DIP_SET(ip, i_db[i], 0);
5935         frags = sblksize(ip->i_fs, ip->i_size, i);
5936         frags = numfrags(ip->i_fs, frags);
5937         newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
5938 }
5939
5940 static inline void
5941 setup_freeext(freeblks, ip, i, needj)
5942         struct freeblks *freeblks;
5943         struct inode *ip;
5944         int i;
5945         int needj;
5946 {
5947         ufs2_daddr_t blkno;
5948         int frags;
5949
5950         blkno = ip->i_din2->di_extb[i];
5951         if (blkno == 0)
5952                 return;
5953         ip->i_din2->di_extb[i] = 0;
5954         frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
5955         frags = numfrags(ip->i_fs, frags);
5956         newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
5957 }
5958
5959 static inline void
5960 setup_freeindir(freeblks, ip, i, lbn, needj)
5961         struct freeblks *freeblks;
5962         struct inode *ip;
5963         int i;
5964         ufs_lbn_t lbn;
5965         int needj;
5966 {
5967         ufs2_daddr_t blkno;
5968
5969         blkno = DIP(ip, i_ib[i]);
5970         if (blkno == 0)
5971                 return;
5972         DIP_SET(ip, i_ib[i], 0);
5973         newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
5974             0, needj);
5975 }
5976
5977 static inline struct freeblks *
5978 newfreeblks(mp, ip)
5979         struct mount *mp;
5980         struct inode *ip;
5981 {
5982         struct freeblks *freeblks;
5983
5984         freeblks = malloc(sizeof(struct freeblks),
5985                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5986         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5987         LIST_INIT(&freeblks->fb_jblkdephd);
5988         LIST_INIT(&freeblks->fb_jwork);
5989         freeblks->fb_ref = 0;
5990         freeblks->fb_cgwait = 0;
5991         freeblks->fb_state = ATTACHED;
5992         freeblks->fb_uid = ip->i_uid;
5993         freeblks->fb_inum = ip->i_number;
5994         freeblks->fb_vtype = ITOV(ip)->v_type;
5995         freeblks->fb_modrev = DIP(ip, i_modrev);
5996         freeblks->fb_devvp = ip->i_devvp;
5997         freeblks->fb_chkcnt = 0;
5998         freeblks->fb_len = 0;
5999
6000         return (freeblks);
6001 }
6002
6003 static void
6004 trunc_indirdep(indirdep, freeblks, bp, off)
6005         struct indirdep *indirdep;
6006         struct freeblks *freeblks;
6007         struct buf *bp;
6008         int off;
6009 {
6010         struct allocindir *aip, *aipn;
6011
6012         /*
6013          * The first set of allocindirs won't be in savedbp.
6014          */
6015         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6016                 if (aip->ai_offset > off)
6017                         cancel_allocindir(aip, bp, freeblks, 1);
6018         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6019                 if (aip->ai_offset > off)
6020                         cancel_allocindir(aip, bp, freeblks, 1);
6021         /*
6022          * These will exist in savedbp.
6023          */
6024         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6025                 if (aip->ai_offset > off)
6026                         cancel_allocindir(aip, NULL, freeblks, 0);
6027         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6028                 if (aip->ai_offset > off)
6029                         cancel_allocindir(aip, NULL, freeblks, 0);
6030 }
6031
6032 /*
6033  * Follow the chain of indirects down to lastlbn creating a freework
6034  * structure for each.  This will be used to start indir_trunc() at
6035  * the right offset and create the journal records for the parrtial
6036  * truncation.  A second step will handle the truncated dependencies.
6037  */
6038 static int
6039 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6040         struct freeblks *freeblks;
6041         struct inode *ip;
6042         ufs_lbn_t lbn;
6043         ufs_lbn_t lastlbn;
6044         ufs2_daddr_t blkno;
6045 {
6046         struct indirdep *indirdep;
6047         struct indirdep *indirn;
6048         struct freework *freework;
6049         struct newblk *newblk;
6050         struct mount *mp;
6051         struct buf *bp;
6052         uint8_t *start;
6053         uint8_t *end;
6054         ufs_lbn_t lbnadd;
6055         int level;
6056         int error;
6057         int off;
6058
6059
6060         freework = NULL;
6061         if (blkno == 0)
6062                 return (0);
6063         mp = freeblks->fb_list.wk_mp;
6064         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6065         if ((bp->b_flags & B_CACHE) == 0) {
6066                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6067                 bp->b_iocmd = BIO_READ;
6068                 bp->b_flags &= ~B_INVAL;
6069                 bp->b_ioflags &= ~BIO_ERROR;
6070                 vfs_busy_pages(bp, 0);
6071                 bp->b_iooffset = dbtob(bp->b_blkno);
6072                 bstrategy(bp);
6073                 curthread->td_ru.ru_inblock++;
6074                 error = bufwait(bp);
6075                 if (error) {
6076                         brelse(bp);
6077                         return (error);
6078                 }
6079         }
6080         level = lbn_level(lbn);
6081         lbnadd = lbn_offset(ip->i_fs, level);
6082         /*
6083          * Compute the offset of the last block we want to keep.  Store
6084          * in the freework the first block we want to completely free.
6085          */
6086         off = (lastlbn - -(lbn + level)) / lbnadd;
6087         if (off + 1 == NINDIR(ip->i_fs))
6088                 goto nowork;
6089         freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
6090             0);
6091         /*
6092          * Link the freework into the indirdep.  This will prevent any new
6093          * allocations from proceeding until we are finished with the
6094          * truncate and the block is written.
6095          */
6096         ACQUIRE_LOCK(&lk);
6097         indirdep = indirdep_lookup(mp, ip, bp);
6098         if (indirdep->ir_freeblks)
6099                 panic("setup_trunc_indir: indirdep already truncated.");
6100         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6101         freework->fw_indir = indirdep;
6102         /*
6103          * Cancel any allocindirs that will not make it to disk.
6104          * We have to do this for all copies of the indirdep that
6105          * live on this newblk.
6106          */
6107         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6108                 newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
6109                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6110                         trunc_indirdep(indirn, freeblks, bp, off);
6111         } else
6112                 trunc_indirdep(indirdep, freeblks, bp, off);
6113         FREE_LOCK(&lk);
6114         /*
6115          * Creation is protected by the buf lock. The saveddata is only
6116          * needed if a full truncation follows a partial truncation but it
6117          * is difficult to allocate in that case so we fetch it anyway.
6118          */
6119         if (indirdep->ir_saveddata == NULL)
6120                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6121                     M_SOFTDEP_FLAGS);
6122 nowork:
6123         /* Fetch the blkno of the child and the zero start offset. */
6124         if (ip->i_ump->um_fstype == UFS1) {
6125                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6126                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6127         } else {
6128                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6129                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6130         }
6131         if (freework) {
6132                 /* Zero the truncated pointers. */
6133                 end = bp->b_data + bp->b_bcount;
6134                 bzero(start, end - start);
6135                 bdwrite(bp);
6136         } else
6137                 bqrelse(bp);
6138         if (level == 0)
6139                 return (0);
6140         lbn++; /* adjust level */
6141         lbn -= (off * lbnadd);
6142         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6143 }
6144
6145 /*
6146  * Complete the partial truncation of an indirect block setup by
6147  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6148  * copy and writes them to disk before the freeblks is allowed to complete.
6149  */
6150 static void
6151 complete_trunc_indir(freework)
6152         struct freework *freework;
6153 {
6154         struct freework *fwn;
6155         struct indirdep *indirdep;
6156         struct buf *bp;
6157         uintptr_t start;
6158         int count;
6159
6160         indirdep = freework->fw_indir;
6161         for (;;) {
6162                 bp = indirdep->ir_bp;
6163                 /* See if the block was discarded. */
6164                 if (bp == NULL)
6165                         break;
6166                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6167                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6168                         break;
6169                 if (BUF_LOCK(bp,
6170                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, &lk) == 0)
6171                         BUF_UNLOCK(bp);
6172                 ACQUIRE_LOCK(&lk);
6173         }
6174         mtx_assert(&lk, MA_OWNED);
6175         freework->fw_state |= DEPCOMPLETE;
6176         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6177         /*
6178          * Zero the pointers in the saved copy.
6179          */
6180         if (indirdep->ir_state & UFS1FMT)
6181                 start = sizeof(ufs1_daddr_t);
6182         else
6183                 start = sizeof(ufs2_daddr_t);
6184         start *= freework->fw_start;
6185         count = indirdep->ir_savebp->b_bcount - start;
6186         start += (uintptr_t)indirdep->ir_savebp->b_data;
6187         bzero((char *)start, count);
6188         /*
6189          * We need to start the next truncation in the list if it has not
6190          * been started yet.
6191          */
6192         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6193         if (fwn != NULL) {
6194                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6195                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6196                 if ((fwn->fw_state & ONWORKLIST) == 0)
6197                         freework_enqueue(fwn);
6198         }
6199         /*
6200          * If bp is NULL the block was fully truncated, restore
6201          * the saved block list otherwise free it if it is no
6202          * longer needed.
6203          */
6204         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6205                 if (bp == NULL)
6206                         bcopy(indirdep->ir_saveddata,
6207                             indirdep->ir_savebp->b_data,
6208                             indirdep->ir_savebp->b_bcount);
6209                 free(indirdep->ir_saveddata, M_INDIRDEP);
6210                 indirdep->ir_saveddata = NULL;
6211         }
6212         /*
6213          * When bp is NULL there is a full truncation pending.  We
6214          * must wait for this full truncation to be journaled before
6215          * we can release this freework because the disk pointers will
6216          * never be written as zero.
6217          */
6218         if (bp == NULL)  {
6219                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6220                         handle_written_freework(freework);
6221                 else
6222                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6223                            &freework->fw_list);
6224         } else {
6225                 /* Complete when the real copy is written. */
6226                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6227                 BUF_UNLOCK(bp);
6228         }
6229 }
6230
6231 /*
6232  * Calculate the number of blocks we are going to release where datablocks
6233  * is the current total and length is the new file size.
6234  */
6235 ufs2_daddr_t
6236 blkcount(fs, datablocks, length)
6237         struct fs *fs;
6238         ufs2_daddr_t datablocks;
6239         off_t length;
6240 {
6241         off_t totblks, numblks;
6242
6243         totblks = 0;
6244         numblks = howmany(length, fs->fs_bsize);
6245         if (numblks <= NDADDR) {
6246                 totblks = howmany(length, fs->fs_fsize);
6247                 goto out;
6248         }
6249         totblks = blkstofrags(fs, numblks);
6250         numblks -= NDADDR;
6251         /*
6252          * Count all single, then double, then triple indirects required.
6253          * Subtracting one indirects worth of blocks for each pass
6254          * acknowledges one of each pointed to by the inode.
6255          */
6256         for (;;) {
6257                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6258                 numblks -= NINDIR(fs);
6259                 if (numblks <= 0)
6260                         break;
6261                 numblks = howmany(numblks, NINDIR(fs));
6262         }
6263 out:
6264         totblks = fsbtodb(fs, totblks);
6265         /*
6266          * Handle sparse files.  We can't reclaim more blocks than the inode
6267          * references.  We will correct it later in handle_complete_freeblks()
6268          * when we know the real count.
6269          */
6270         if (totblks > datablocks)
6271                 return (0);
6272         return (datablocks - totblks);
6273 }
6274
6275 /*
6276  * Handle freeblocks for journaled softupdate filesystems.
6277  *
6278  * Contrary to normal softupdates, we must preserve the block pointers in
6279  * indirects until their subordinates are free.  This is to avoid journaling
6280  * every block that is freed which may consume more space than the journal
6281  * itself.  The recovery program will see the free block journals at the
6282  * base of the truncated area and traverse them to reclaim space.  The
6283  * pointers in the inode may be cleared immediately after the journal
6284  * records are written because each direct and indirect pointer in the
6285  * inode is recorded in a journal.  This permits full truncation to proceed
6286  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6287  *
6288  * The algorithm is as follows:
6289  * 1) Traverse the in-memory state and create journal entries to release
6290  *    the relevant blocks and full indirect trees.
6291  * 2) Traverse the indirect block chain adding partial truncation freework
6292  *    records to indirects in the path to lastlbn.  The freework will
6293  *    prevent new allocation dependencies from being satisfied in this
6294  *    indirect until the truncation completes.
6295  * 3) Read and lock the inode block, performing an update with the new size
6296  *    and pointers.  This prevents truncated data from becoming valid on
6297  *    disk through step 4.
6298  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6299  *    eliminate journal work for those records that do not require it.
6300  * 5) Schedule the journal records to be written followed by the inode block.
6301  * 6) Allocate any necessary frags for the end of file.
6302  * 7) Zero any partially truncated blocks.
6303  *
6304  * From this truncation proceeds asynchronously using the freework and
6305  * indir_trunc machinery.  The file will not be extended again into a
6306  * partially truncated indirect block until all work is completed but
6307  * the normal dependency mechanism ensures that it is rolled back/forward
6308  * as appropriate.  Further truncation may occur without delay and is
6309  * serialized in indir_trunc().
6310  */
6311 void
6312 softdep_journal_freeblocks(ip, cred, length, flags)
6313         struct inode *ip;       /* The inode whose length is to be reduced */
6314         struct ucred *cred;
6315         off_t length;           /* The new length for the file */
6316         int flags;              /* IO_EXT and/or IO_NORMAL */
6317 {
6318         struct freeblks *freeblks, *fbn;
6319         struct worklist *wk, *wkn;
6320         struct inodedep *inodedep;
6321         struct jblkdep *jblkdep;
6322         struct allocdirect *adp, *adpn;
6323         struct fs *fs;
6324         struct buf *bp;
6325         struct vnode *vp;
6326         struct mount *mp;
6327         ufs2_daddr_t extblocks, datablocks;
6328         ufs_lbn_t tmpval, lbn, lastlbn;
6329         int frags, lastoff, iboff, allocblock, needj, dflags, error, i;
6330
6331         fs = ip->i_fs;
6332         mp = UFSTOVFS(ip->i_ump);
6333         vp = ITOV(ip);
6334         needj = 1;
6335         iboff = -1;
6336         allocblock = 0;
6337         extblocks = 0;
6338         datablocks = 0;
6339         frags = 0;
6340         freeblks = newfreeblks(mp, ip);
6341         ACQUIRE_LOCK(&lk);
6342         /*
6343          * If we're truncating a removed file that will never be written
6344          * we don't need to journal the block frees.  The canceled journals
6345          * for the allocations will suffice.
6346          */
6347         dflags = DEPALLOC;
6348         if (IS_SNAPSHOT(ip))
6349                 dflags |= NODELAY;
6350         inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6351         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6352             length == 0)
6353                 needj = 0;
6354         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6355             ip->i_number, length, needj);
6356         FREE_LOCK(&lk);
6357         /*
6358          * Calculate the lbn that we are truncating to.  This results in -1
6359          * if we're truncating the 0 bytes.  So it is the last lbn we want
6360          * to keep, not the first lbn we want to truncate.
6361          */
6362         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6363         lastoff = blkoff(fs, length);
6364         /*
6365          * Compute frags we are keeping in lastlbn.  0 means all.
6366          */
6367         if (lastlbn >= 0 && lastlbn < NDADDR) {
6368                 frags = fragroundup(fs, lastoff);
6369                 /* adp offset of last valid allocdirect. */
6370                 iboff = lastlbn;
6371         } else if (lastlbn > 0)
6372                 iboff = NDADDR;
6373         if (fs->fs_magic == FS_UFS2_MAGIC)
6374                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6375         /*
6376          * Handle normal data blocks and indirects.  This section saves
6377          * values used after the inode update to complete frag and indirect
6378          * truncation.
6379          */
6380         if ((flags & IO_NORMAL) != 0) {
6381                 /*
6382                  * Handle truncation of whole direct and indirect blocks.
6383                  */
6384                 for (i = iboff + 1; i < NDADDR; i++)
6385                         setup_freedirect(freeblks, ip, i, needj);
6386                 for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6387                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6388                         /* Release a whole indirect tree. */
6389                         if (lbn > lastlbn) {
6390                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6391                                     needj);
6392                                 continue;
6393                         }
6394                         iboff = i + NDADDR;
6395                         /*
6396                          * Traverse partially truncated indirect tree.
6397                          */
6398                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6399                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6400                                     lastlbn, DIP(ip, i_ib[i]));
6401                 }
6402                 /*
6403                  * Handle partial truncation to a frag boundary.
6404                  */
6405                 if (frags) {
6406                         ufs2_daddr_t blkno;
6407                         long oldfrags;
6408
6409                         oldfrags = blksize(fs, ip, lastlbn);
6410                         blkno = DIP(ip, i_db[lastlbn]);
6411                         if (blkno && oldfrags != frags) {
6412                                 oldfrags -= frags;
6413                                 oldfrags = numfrags(ip->i_fs, oldfrags);
6414                                 blkno += numfrags(ip->i_fs, frags);
6415                                 newfreework(ip->i_ump, freeblks, NULL, lastlbn,
6416                                     blkno, oldfrags, 0, needj);
6417                         } else if (blkno == 0)
6418                                 allocblock = 1;
6419                 }
6420                 /*
6421                  * Add a journal record for partial truncate if we are
6422                  * handling indirect blocks.  Non-indirects need no extra
6423                  * journaling.
6424                  */
6425                 if (length != 0 && lastlbn >= NDADDR) {
6426                         ip->i_flag |= IN_TRUNCATED;
6427                         newjtrunc(freeblks, length, 0);
6428                 }
6429                 ip->i_size = length;
6430                 DIP_SET(ip, i_size, ip->i_size);
6431                 datablocks = DIP(ip, i_blocks) - extblocks;
6432                 if (length != 0)
6433                         datablocks = blkcount(ip->i_fs, datablocks, length);
6434                 freeblks->fb_len = length;
6435         }
6436         if ((flags & IO_EXT) != 0) {
6437                 for (i = 0; i < NXADDR; i++)
6438                         setup_freeext(freeblks, ip, i, needj);
6439                 ip->i_din2->di_extsize = 0;
6440                 datablocks += extblocks;
6441         }
6442 #ifdef QUOTA
6443         /* Reference the quotas in case the block count is wrong in the end. */
6444         quotaref(vp, freeblks->fb_quota);
6445         (void) chkdq(ip, -datablocks, NOCRED, 0);
6446 #endif
6447         freeblks->fb_chkcnt = -datablocks;
6448         UFS_LOCK(ip->i_ump);
6449         fs->fs_pendingblocks += datablocks;
6450         UFS_UNLOCK(ip->i_ump);
6451         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6452         /*
6453          * Handle truncation of incomplete alloc direct dependencies.  We
6454          * hold the inode block locked to prevent incomplete dependencies
6455          * from reaching the disk while we are eliminating those that
6456          * have been truncated.  This is a partially inlined ffs_update().
6457          */
6458         ufs_itimes(vp);
6459         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6460         error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6461             (int)fs->fs_bsize, cred, &bp);
6462         if (error) {
6463                 brelse(bp);
6464                 softdep_error("softdep_journal_freeblocks", error);
6465                 return;
6466         }
6467         if (bp->b_bufsize == fs->fs_bsize)
6468                 bp->b_flags |= B_CLUSTEROK;
6469         softdep_update_inodeblock(ip, bp, 0);
6470         if (ip->i_ump->um_fstype == UFS1)
6471                 *((struct ufs1_dinode *)bp->b_data +
6472                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6473         else
6474                 *((struct ufs2_dinode *)bp->b_data +
6475                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6476         ACQUIRE_LOCK(&lk);
6477         (void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6478         if ((inodedep->id_state & IOSTARTED) != 0)
6479                 panic("softdep_setup_freeblocks: inode busy");
6480         /*
6481          * Add the freeblks structure to the list of operations that
6482          * must await the zero'ed inode being written to disk. If we
6483          * still have a bitmap dependency (needj), then the inode
6484          * has never been written to disk, so we can process the
6485          * freeblks below once we have deleted the dependencies.
6486          */
6487         if (needj)
6488                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6489         else
6490                 freeblks->fb_state |= COMPLETE;
6491         if ((flags & IO_NORMAL) != 0) {
6492                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6493                         if (adp->ad_offset > iboff)
6494                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6495                                     freeblks);
6496                         /*
6497                          * Truncate the allocdirect.  We could eliminate
6498                          * or modify journal records as well.
6499                          */
6500                         else if (adp->ad_offset == iboff && frags)
6501                                 adp->ad_newsize = frags;
6502                 }
6503         }
6504         if ((flags & IO_EXT) != 0)
6505                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6506                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6507                             freeblks);
6508         /*
6509          * Scan the bufwait list for newblock dependencies that will never
6510          * make it to disk.
6511          */
6512         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6513                 if (wk->wk_type != D_ALLOCDIRECT)
6514                         continue;
6515                 adp = WK_ALLOCDIRECT(wk);
6516                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6517                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6518                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6519                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6520                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6521                 }
6522         }
6523         /*
6524          * Add journal work.
6525          */
6526         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6527                 add_to_journal(&jblkdep->jb_list);
6528         FREE_LOCK(&lk);
6529         bdwrite(bp);
6530         /*
6531          * Truncate dependency structures beyond length.
6532          */
6533         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6534         /*
6535          * This is only set when we need to allocate a fragment because
6536          * none existed at the end of a frag-sized file.  It handles only
6537          * allocating a new, zero filled block.
6538          */
6539         if (allocblock) {
6540                 ip->i_size = length - lastoff;
6541                 DIP_SET(ip, i_size, ip->i_size);
6542                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6543                 if (error != 0) {
6544                         softdep_error("softdep_journal_freeblks", error);
6545                         return;
6546                 }
6547                 ip->i_size = length;
6548                 DIP_SET(ip, i_size, length);
6549                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6550                 allocbuf(bp, frags);
6551                 ffs_update(vp, 0);
6552                 bawrite(bp);
6553         } else if (lastoff != 0 && vp->v_type != VDIR) {
6554                 int size;
6555
6556                 /*
6557                  * Zero the end of a truncated frag or block.
6558                  */
6559                 size = sblksize(fs, length, lastlbn);
6560                 error = bread(vp, lastlbn, size, cred, &bp);
6561                 if (error) {
6562                         softdep_error("softdep_journal_freeblks", error);
6563                         return;
6564                 }
6565                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6566                 bawrite(bp);
6567
6568         }
6569         ACQUIRE_LOCK(&lk);
6570         inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6571         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6572         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6573         /*
6574          * We zero earlier truncations so they don't erroneously
6575          * update i_blocks.
6576          */
6577         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6578                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6579                         fbn->fb_len = 0;
6580         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6581             LIST_EMPTY(&freeblks->fb_jblkdephd))
6582                 freeblks->fb_state |= INPROGRESS;
6583         else
6584                 freeblks = NULL;
6585         FREE_LOCK(&lk);
6586         if (freeblks)
6587                 handle_workitem_freeblocks(freeblks, 0);
6588         trunc_pages(ip, length, extblocks, flags);
6589
6590 }
6591
6592 /*
6593  * Flush a JOP_SYNC to the journal.
6594  */
6595 void
6596 softdep_journal_fsync(ip)
6597         struct inode *ip;
6598 {
6599         struct jfsync *jfsync;
6600
6601         if ((ip->i_flag & IN_TRUNCATED) == 0)
6602                 return;
6603         ip->i_flag &= ~IN_TRUNCATED;
6604         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6605         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6606         jfsync->jfs_size = ip->i_size;
6607         jfsync->jfs_ino = ip->i_number;
6608         ACQUIRE_LOCK(&lk);
6609         add_to_journal(&jfsync->jfs_list);
6610         jwait(&jfsync->jfs_list, MNT_WAIT);
6611         FREE_LOCK(&lk);
6612 }
6613
6614 /*
6615  * Block de-allocation dependencies.
6616  * 
6617  * When blocks are de-allocated, the on-disk pointers must be nullified before
6618  * the blocks are made available for use by other files.  (The true
6619  * requirement is that old pointers must be nullified before new on-disk
6620  * pointers are set.  We chose this slightly more stringent requirement to
6621  * reduce complexity.) Our implementation handles this dependency by updating
6622  * the inode (or indirect block) appropriately but delaying the actual block
6623  * de-allocation (i.e., freemap and free space count manipulation) until
6624  * after the updated versions reach stable storage.  After the disk is
6625  * updated, the blocks can be safely de-allocated whenever it is convenient.
6626  * This implementation handles only the common case of reducing a file's
6627  * length to zero. Other cases are handled by the conventional synchronous
6628  * write approach.
6629  *
6630  * The ffs implementation with which we worked double-checks
6631  * the state of the block pointers and file size as it reduces
6632  * a file's length.  Some of this code is replicated here in our
6633  * soft updates implementation.  The freeblks->fb_chkcnt field is
6634  * used to transfer a part of this information to the procedure
6635  * that eventually de-allocates the blocks.
6636  *
6637  * This routine should be called from the routine that shortens
6638  * a file's length, before the inode's size or block pointers
6639  * are modified. It will save the block pointer information for
6640  * later release and zero the inode so that the calling routine
6641  * can release it.
6642  */
6643 void
6644 softdep_setup_freeblocks(ip, length, flags)
6645         struct inode *ip;       /* The inode whose length is to be reduced */
6646         off_t length;           /* The new length for the file */
6647         int flags;              /* IO_EXT and/or IO_NORMAL */
6648 {
6649         struct ufs1_dinode *dp1;
6650         struct ufs2_dinode *dp2;
6651         struct freeblks *freeblks;
6652         struct inodedep *inodedep;
6653         struct allocdirect *adp;
6654         struct buf *bp;
6655         struct fs *fs;
6656         ufs2_daddr_t extblocks, datablocks;
6657         struct mount *mp;
6658         int i, delay, error, dflags;
6659         ufs_lbn_t tmpval;
6660         ufs_lbn_t lbn;
6661
6662         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6663             ip->i_number, length);
6664         fs = ip->i_fs;
6665         mp = UFSTOVFS(ip->i_ump);
6666         if (length != 0)
6667                 panic("softdep_setup_freeblocks: non-zero length");
6668         freeblks = newfreeblks(mp, ip);
6669         extblocks = 0;
6670         datablocks = 0;
6671         if (fs->fs_magic == FS_UFS2_MAGIC)
6672                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6673         if ((flags & IO_NORMAL) != 0) {
6674                 for (i = 0; i < NDADDR; i++)
6675                         setup_freedirect(freeblks, ip, i, 0);
6676                 for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6677                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6678                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6679                 ip->i_size = 0;
6680                 DIP_SET(ip, i_size, 0);
6681                 datablocks = DIP(ip, i_blocks) - extblocks;
6682         }
6683         if ((flags & IO_EXT) != 0) {
6684                 for (i = 0; i < NXADDR; i++)
6685                         setup_freeext(freeblks, ip, i, 0);
6686                 ip->i_din2->di_extsize = 0;
6687                 datablocks += extblocks;
6688         }
6689 #ifdef QUOTA
6690         /* Reference the quotas in case the block count is wrong in the end. */
6691         quotaref(ITOV(ip), freeblks->fb_quota);
6692         (void) chkdq(ip, -datablocks, NOCRED, 0);
6693 #endif
6694         freeblks->fb_chkcnt = -datablocks;
6695         UFS_LOCK(ip->i_ump);
6696         fs->fs_pendingblocks += datablocks;
6697         UFS_UNLOCK(ip->i_ump);
6698         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6699         /*
6700          * Push the zero'ed inode to to its disk buffer so that we are free
6701          * to delete its dependencies below. Once the dependencies are gone
6702          * the buffer can be safely released.
6703          */
6704         if ((error = bread(ip->i_devvp,
6705             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6706             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6707                 brelse(bp);
6708                 softdep_error("softdep_setup_freeblocks", error);
6709         }
6710         if (ip->i_ump->um_fstype == UFS1) {
6711                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6712                     ino_to_fsbo(fs, ip->i_number));
6713                 ip->i_din1->di_freelink = dp1->di_freelink;
6714                 *dp1 = *ip->i_din1;
6715         } else {
6716                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6717                     ino_to_fsbo(fs, ip->i_number));
6718                 ip->i_din2->di_freelink = dp2->di_freelink;
6719                 *dp2 = *ip->i_din2;
6720         }
6721         /*
6722          * Find and eliminate any inode dependencies.
6723          */
6724         ACQUIRE_LOCK(&lk);
6725         dflags = DEPALLOC;
6726         if (IS_SNAPSHOT(ip))
6727                 dflags |= NODELAY;
6728         (void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6729         if ((inodedep->id_state & IOSTARTED) != 0)
6730                 panic("softdep_setup_freeblocks: inode busy");
6731         /*
6732          * Add the freeblks structure to the list of operations that
6733          * must await the zero'ed inode being written to disk. If we
6734          * still have a bitmap dependency (delay == 0), then the inode
6735          * has never been written to disk, so we can process the
6736          * freeblks below once we have deleted the dependencies.
6737          */
6738         delay = (inodedep->id_state & DEPCOMPLETE);
6739         if (delay)
6740                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6741         else
6742                 freeblks->fb_state |= COMPLETE;
6743         /*
6744          * Because the file length has been truncated to zero, any
6745          * pending block allocation dependency structures associated
6746          * with this inode are obsolete and can simply be de-allocated.
6747          * We must first merge the two dependency lists to get rid of
6748          * any duplicate freefrag structures, then purge the merged list.
6749          * If we still have a bitmap dependency, then the inode has never
6750          * been written to disk, so we can free any fragments without delay.
6751          */
6752         if (flags & IO_NORMAL) {
6753                 merge_inode_lists(&inodedep->id_newinoupdt,
6754                     &inodedep->id_inoupdt);
6755                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6756                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6757                             freeblks);
6758         }
6759         if (flags & IO_EXT) {
6760                 merge_inode_lists(&inodedep->id_newextupdt,
6761                     &inodedep->id_extupdt);
6762                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6763                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6764                             freeblks);
6765         }
6766         FREE_LOCK(&lk);
6767         bdwrite(bp);
6768         trunc_dependencies(ip, freeblks, -1, 0, flags);
6769         ACQUIRE_LOCK(&lk);
6770         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6771                 (void) free_inodedep(inodedep);
6772         freeblks->fb_state |= DEPCOMPLETE;
6773         /*
6774          * If the inode with zeroed block pointers is now on disk
6775          * we can start freeing blocks.
6776          */  
6777         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6778                 freeblks->fb_state |= INPROGRESS;
6779         else
6780                 freeblks = NULL;
6781         FREE_LOCK(&lk);
6782         if (freeblks)
6783                 handle_workitem_freeblocks(freeblks, 0);
6784         trunc_pages(ip, length, extblocks, flags);
6785 }
6786
6787 /*
6788  * Eliminate pages from the page cache that back parts of this inode and
6789  * adjust the vnode pager's idea of our size.  This prevents stale data
6790  * from hanging around in the page cache.
6791  */
6792 static void
6793 trunc_pages(ip, length, extblocks, flags)
6794         struct inode *ip;
6795         off_t length;
6796         ufs2_daddr_t extblocks;
6797         int flags;
6798 {
6799         struct vnode *vp;
6800         struct fs *fs;
6801         ufs_lbn_t lbn;
6802         off_t end, extend;
6803
6804         vp = ITOV(ip);
6805         fs = ip->i_fs;
6806         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6807         if ((flags & IO_EXT) != 0)
6808                 vn_pages_remove(vp, extend, 0);
6809         if ((flags & IO_NORMAL) == 0)
6810                 return;
6811         BO_LOCK(&vp->v_bufobj);
6812         drain_output(vp);
6813         BO_UNLOCK(&vp->v_bufobj);
6814         /*
6815          * The vnode pager eliminates file pages we eliminate indirects
6816          * below.
6817          */
6818         vnode_pager_setsize(vp, length);
6819         /*
6820          * Calculate the end based on the last indirect we want to keep.  If
6821          * the block extends into indirects we can just use the negative of
6822          * its lbn.  Doubles and triples exist at lower numbers so we must
6823          * be careful not to remove those, if they exist.  double and triple
6824          * indirect lbns do not overlap with others so it is not important
6825          * to verify how many levels are required.
6826          */
6827         lbn = lblkno(fs, length);
6828         if (lbn >= NDADDR) {
6829                 /* Calculate the virtual lbn of the triple indirect. */
6830                 lbn = -lbn - (NIADDR - 1);
6831                 end = OFF_TO_IDX(lblktosize(fs, lbn));
6832         } else
6833                 end = extend;
6834         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
6835 }
6836
6837 /*
6838  * See if the buf bp is in the range eliminated by truncation.
6839  */
6840 static int
6841 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
6842         struct buf *bp;
6843         int *blkoffp;
6844         ufs_lbn_t lastlbn;
6845         int lastoff;
6846         int flags;
6847 {
6848         ufs_lbn_t lbn;
6849
6850         *blkoffp = 0;
6851         /* Only match ext/normal blocks as appropriate. */
6852         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
6853             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
6854                 return (0);
6855         /* ALTDATA is always a full truncation. */
6856         if ((bp->b_xflags & BX_ALTDATA) != 0)
6857                 return (1);
6858         /* -1 is full truncation. */
6859         if (lastlbn == -1)
6860                 return (1);
6861         /*
6862          * If this is a partial truncate we only want those
6863          * blocks and indirect blocks that cover the range
6864          * we're after.
6865          */
6866         lbn = bp->b_lblkno;
6867         if (lbn < 0)
6868                 lbn = -(lbn + lbn_level(lbn));
6869         if (lbn < lastlbn)
6870                 return (0);
6871         /* Here we only truncate lblkno if it's partial. */
6872         if (lbn == lastlbn) {
6873                 if (lastoff == 0)
6874                         return (0);
6875                 *blkoffp = lastoff;
6876         }
6877         return (1);
6878 }
6879
6880 /*
6881  * Eliminate any dependencies that exist in memory beyond lblkno:off
6882  */
6883 static void
6884 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
6885         struct inode *ip;
6886         struct freeblks *freeblks;
6887         ufs_lbn_t lastlbn;
6888         int lastoff;
6889         int flags;
6890 {
6891         struct bufobj *bo;
6892         struct vnode *vp;
6893         struct buf *bp;
6894         struct fs *fs;
6895         int blkoff;
6896
6897         /*
6898          * We must wait for any I/O in progress to finish so that
6899          * all potential buffers on the dirty list will be visible.
6900          * Once they are all there, walk the list and get rid of
6901          * any dependencies.
6902          */
6903         fs = ip->i_fs;
6904         vp = ITOV(ip);
6905         bo = &vp->v_bufobj;
6906         BO_LOCK(bo);
6907         drain_output(vp);
6908         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
6909                 bp->b_vflags &= ~BV_SCANNED;
6910 restart:
6911         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
6912                 if (bp->b_vflags & BV_SCANNED)
6913                         continue;
6914                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6915                         bp->b_vflags |= BV_SCANNED;
6916                         continue;
6917                 }
6918                 if ((bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT)) == NULL)
6919                         goto restart;
6920                 BO_UNLOCK(bo);
6921                 if (deallocate_dependencies(bp, freeblks, blkoff))
6922                         bqrelse(bp);
6923                 else
6924                         brelse(bp);
6925                 BO_LOCK(bo);
6926                 goto restart;
6927         }
6928         /*
6929          * Now do the work of vtruncbuf while also matching indirect blocks.
6930          */
6931         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
6932                 bp->b_vflags &= ~BV_SCANNED;
6933 cleanrestart:
6934         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
6935                 if (bp->b_vflags & BV_SCANNED)
6936                         continue;
6937                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6938                         bp->b_vflags |= BV_SCANNED;
6939                         continue;
6940                 }
6941                 if (BUF_LOCK(bp,
6942                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6943                     BO_MTX(bo)) == ENOLCK) {
6944                         BO_LOCK(bo);
6945                         goto cleanrestart;
6946                 }
6947                 bp->b_vflags |= BV_SCANNED;
6948                 BO_LOCK(bo);
6949                 bremfree(bp);
6950                 BO_UNLOCK(bo);
6951                 if (blkoff != 0) {
6952                         allocbuf(bp, blkoff);
6953                         bqrelse(bp);
6954                 } else {
6955                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
6956                         brelse(bp);
6957                 }
6958                 BO_LOCK(bo);
6959                 goto cleanrestart;
6960         }
6961         drain_output(vp);
6962         BO_UNLOCK(bo);
6963 }
6964
6965 static int
6966 cancel_pagedep(pagedep, freeblks, blkoff)
6967         struct pagedep *pagedep;
6968         struct freeblks *freeblks;
6969         int blkoff;
6970 {
6971         struct jremref *jremref;
6972         struct jmvref *jmvref;
6973         struct dirrem *dirrem, *tmp;
6974         int i;
6975
6976         /*
6977          * Copy any directory remove dependencies to the list
6978          * to be processed after the freeblks proceeds.  If
6979          * directory entry never made it to disk they
6980          * can be dumped directly onto the work list.
6981          */
6982         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
6983                 /* Skip this directory removal if it is intended to remain. */
6984                 if (dirrem->dm_offset < blkoff)
6985                         continue;
6986                 /*
6987                  * If there are any dirrems we wait for the journal write
6988                  * to complete and then restart the buf scan as the lock
6989                  * has been dropped.
6990                  */
6991                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
6992                         jwait(&jremref->jr_list, MNT_WAIT);
6993                         return (ERESTART);
6994                 }
6995                 LIST_REMOVE(dirrem, dm_next);
6996                 dirrem->dm_dirinum = pagedep->pd_ino;
6997                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
6998         }
6999         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7000                 jwait(&jmvref->jm_list, MNT_WAIT);
7001                 return (ERESTART);
7002         }
7003         /*
7004          * When we're partially truncating a pagedep we just want to flush
7005          * journal entries and return.  There can not be any adds in the
7006          * truncated portion of the directory and newblk must remain if
7007          * part of the block remains.
7008          */
7009         if (blkoff != 0) {
7010                 struct diradd *dap;
7011
7012                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7013                         if (dap->da_offset > blkoff)
7014                                 panic("cancel_pagedep: diradd %p off %d > %d",
7015                                     dap, dap->da_offset, blkoff);
7016                 for (i = 0; i < DAHASHSZ; i++)
7017                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7018                                 if (dap->da_offset > blkoff)
7019                                         panic("cancel_pagedep: diradd %p off %d > %d",
7020                                             dap, dap->da_offset, blkoff);
7021                 return (0);
7022         }
7023         /*
7024          * There should be no directory add dependencies present
7025          * as the directory could not be truncated until all
7026          * children were removed.
7027          */
7028         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7029             ("deallocate_dependencies: pendinghd != NULL"));
7030         for (i = 0; i < DAHASHSZ; i++)
7031                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7032                     ("deallocate_dependencies: diraddhd != NULL"));
7033         if ((pagedep->pd_state & NEWBLOCK) != 0)
7034                 free_newdirblk(pagedep->pd_newdirblk);
7035         if (free_pagedep(pagedep) == 0)
7036                 panic("Failed to free pagedep %p", pagedep);
7037         return (0);
7038 }
7039
7040 /*
7041  * Reclaim any dependency structures from a buffer that is about to
7042  * be reallocated to a new vnode. The buffer must be locked, thus,
7043  * no I/O completion operations can occur while we are manipulating
7044  * its associated dependencies. The mutex is held so that other I/O's
7045  * associated with related dependencies do not occur.
7046  */
7047 static int
7048 deallocate_dependencies(bp, freeblks, off)
7049         struct buf *bp;
7050         struct freeblks *freeblks;
7051         int off;
7052 {
7053         struct indirdep *indirdep;
7054         struct pagedep *pagedep;
7055         struct allocdirect *adp;
7056         struct worklist *wk, *wkn;
7057
7058         ACQUIRE_LOCK(&lk);
7059         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7060                 switch (wk->wk_type) {
7061                 case D_INDIRDEP:
7062                         indirdep = WK_INDIRDEP(wk);
7063                         if (bp->b_lblkno >= 0 ||
7064                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7065                                 panic("deallocate_dependencies: not indir");
7066                         cancel_indirdep(indirdep, bp, freeblks);
7067                         continue;
7068
7069                 case D_PAGEDEP:
7070                         pagedep = WK_PAGEDEP(wk);
7071                         if (cancel_pagedep(pagedep, freeblks, off)) {
7072                                 FREE_LOCK(&lk);
7073                                 return (ERESTART);
7074                         }
7075                         continue;
7076
7077                 case D_ALLOCINDIR:
7078                         /*
7079                          * Simply remove the allocindir, we'll find it via
7080                          * the indirdep where we can clear pointers if
7081                          * needed.
7082                          */
7083                         WORKLIST_REMOVE(wk);
7084                         continue;
7085
7086                 case D_FREEWORK:
7087                         /*
7088                          * A truncation is waiting for the zero'd pointers
7089                          * to be written.  It can be freed when the freeblks
7090                          * is journaled.
7091                          */
7092                         WORKLIST_REMOVE(wk);
7093                         wk->wk_state |= ONDEPLIST;
7094                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7095                         break;
7096
7097                 case D_ALLOCDIRECT:
7098                         adp = WK_ALLOCDIRECT(wk);
7099                         if (off != 0)
7100                                 continue;
7101                         /* FALLTHROUGH */
7102                 default:
7103                         panic("deallocate_dependencies: Unexpected type %s",
7104                             TYPENAME(wk->wk_type));
7105                         /* NOTREACHED */
7106                 }
7107         }
7108         FREE_LOCK(&lk);
7109         /*
7110          * Don't throw away this buf, we were partially truncating and
7111          * some deps may always remain.
7112          */
7113         if (off) {
7114                 allocbuf(bp, off);
7115                 bp->b_vflags |= BV_SCANNED;
7116                 return (EBUSY);
7117         }
7118         bp->b_flags |= B_INVAL | B_NOCACHE;
7119
7120         return (0);
7121 }
7122
7123 /*
7124  * An allocdirect is being canceled due to a truncate.  We must make sure
7125  * the journal entry is released in concert with the blkfree that releases
7126  * the storage.  Completed journal entries must not be released until the
7127  * space is no longer pointed to by the inode or in the bitmap.
7128  */
7129 static void
7130 cancel_allocdirect(adphead, adp, freeblks)
7131         struct allocdirectlst *adphead;
7132         struct allocdirect *adp;
7133         struct freeblks *freeblks;
7134 {
7135         struct freework *freework;
7136         struct newblk *newblk;
7137         struct worklist *wk;
7138
7139         TAILQ_REMOVE(adphead, adp, ad_next);
7140         newblk = (struct newblk *)adp;
7141         freework = NULL;
7142         /*
7143          * Find the correct freework structure.
7144          */
7145         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7146                 if (wk->wk_type != D_FREEWORK)
7147                         continue;
7148                 freework = WK_FREEWORK(wk);
7149                 if (freework->fw_blkno == newblk->nb_newblkno)
7150                         break;
7151         }
7152         if (freework == NULL)
7153                 panic("cancel_allocdirect: Freework not found");
7154         /*
7155          * If a newblk exists at all we still have the journal entry that
7156          * initiated the allocation so we do not need to journal the free.
7157          */
7158         cancel_jfreeblk(freeblks, freework->fw_blkno);
7159         /*
7160          * If the journal hasn't been written the jnewblk must be passed
7161          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7162          * this by linking the journal dependency into the freework to be
7163          * freed when freework_freeblock() is called.  If the journal has
7164          * been written we can simply reclaim the journal space when the
7165          * freeblks work is complete.
7166          */
7167         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7168             &freeblks->fb_jwork);
7169         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7170 }
7171
7172
7173 /*
7174  * Cancel a new block allocation.  May be an indirect or direct block.  We
7175  * remove it from various lists and return any journal record that needs to
7176  * be resolved by the caller.
7177  *
7178  * A special consideration is made for indirects which were never pointed
7179  * at on disk and will never be found once this block is released.
7180  */
7181 static struct jnewblk *
7182 cancel_newblk(newblk, wk, wkhd)
7183         struct newblk *newblk;
7184         struct worklist *wk;
7185         struct workhead *wkhd;
7186 {
7187         struct jnewblk *jnewblk;
7188
7189         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7190             
7191         newblk->nb_state |= GOINGAWAY;
7192         /*
7193          * Previously we traversed the completedhd on each indirdep
7194          * attached to this newblk to cancel them and gather journal
7195          * work.  Since we need only the oldest journal segment and
7196          * the lowest point on the tree will always have the oldest
7197          * journal segment we are free to release the segments
7198          * of any subordinates and may leave the indirdep list to
7199          * indirdep_complete() when this newblk is freed.
7200          */
7201         if (newblk->nb_state & ONDEPLIST) {
7202                 newblk->nb_state &= ~ONDEPLIST;
7203                 LIST_REMOVE(newblk, nb_deps);
7204         }
7205         if (newblk->nb_state & ONWORKLIST)
7206                 WORKLIST_REMOVE(&newblk->nb_list);
7207         /*
7208          * If the journal entry hasn't been written we save a pointer to
7209          * the dependency that frees it until it is written or the
7210          * superseding operation completes.
7211          */
7212         jnewblk = newblk->nb_jnewblk;
7213         if (jnewblk != NULL && wk != NULL) {
7214                 newblk->nb_jnewblk = NULL;
7215                 jnewblk->jn_dep = wk;
7216         }
7217         if (!LIST_EMPTY(&newblk->nb_jwork))
7218                 jwork_move(wkhd, &newblk->nb_jwork);
7219         /*
7220          * When truncating we must free the newdirblk early to remove
7221          * the pagedep from the hash before returning.
7222          */
7223         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7224                 free_newdirblk(WK_NEWDIRBLK(wk));
7225         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7226                 panic("cancel_newblk: extra newdirblk");
7227
7228         return (jnewblk);
7229 }
7230
7231 /*
7232  * Schedule the freefrag associated with a newblk to be released once
7233  * the pointers are written and the previous block is no longer needed.
7234  */
7235 static void
7236 newblk_freefrag(newblk)
7237         struct newblk *newblk;
7238 {
7239         struct freefrag *freefrag;
7240
7241         if (newblk->nb_freefrag == NULL)
7242                 return;
7243         freefrag = newblk->nb_freefrag;
7244         newblk->nb_freefrag = NULL;
7245         freefrag->ff_state |= COMPLETE;
7246         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7247                 add_to_worklist(&freefrag->ff_list, 0);
7248 }
7249
7250 /*
7251  * Free a newblk. Generate a new freefrag work request if appropriate.
7252  * This must be called after the inode pointer and any direct block pointers
7253  * are valid or fully removed via truncate or frag extension.
7254  */
7255 static void
7256 free_newblk(newblk)
7257         struct newblk *newblk;
7258 {
7259         struct indirdep *indirdep;
7260         struct worklist *wk;
7261
7262         KASSERT(newblk->nb_jnewblk == NULL,
7263             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7264         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7265             ("free_newblk: unclaimed newblk"));
7266         mtx_assert(&lk, MA_OWNED);
7267         newblk_freefrag(newblk);
7268         if (newblk->nb_state & ONDEPLIST)
7269                 LIST_REMOVE(newblk, nb_deps);
7270         if (newblk->nb_state & ONWORKLIST)
7271                 WORKLIST_REMOVE(&newblk->nb_list);
7272         LIST_REMOVE(newblk, nb_hash);
7273         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7274                 free_newdirblk(WK_NEWDIRBLK(wk));
7275         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7276                 panic("free_newblk: extra newdirblk");
7277         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7278                 indirdep_complete(indirdep);
7279         handle_jwork(&newblk->nb_jwork);
7280         WORKITEM_FREE(newblk, D_NEWBLK);
7281 }
7282
7283 /*
7284  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7285  * This routine must be called with splbio interrupts blocked.
7286  */
7287 static void
7288 free_newdirblk(newdirblk)
7289         struct newdirblk *newdirblk;
7290 {
7291         struct pagedep *pagedep;
7292         struct diradd *dap;
7293         struct worklist *wk;
7294
7295         mtx_assert(&lk, MA_OWNED);
7296         WORKLIST_REMOVE(&newdirblk->db_list);
7297         /*
7298          * If the pagedep is still linked onto the directory buffer
7299          * dependency chain, then some of the entries on the
7300          * pd_pendinghd list may not be committed to disk yet. In
7301          * this case, we will simply clear the NEWBLOCK flag and
7302          * let the pd_pendinghd list be processed when the pagedep
7303          * is next written. If the pagedep is no longer on the buffer
7304          * dependency chain, then all the entries on the pd_pending
7305          * list are committed to disk and we can free them here.
7306          */
7307         pagedep = newdirblk->db_pagedep;
7308         pagedep->pd_state &= ~NEWBLOCK;
7309         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7310                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7311                         free_diradd(dap, NULL);
7312                 /*
7313                  * If no dependencies remain, the pagedep will be freed.
7314                  */
7315                 free_pagedep(pagedep);
7316         }
7317         /* Should only ever be one item in the list. */
7318         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7319                 WORKLIST_REMOVE(wk);
7320                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7321         }
7322         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7323 }
7324
7325 /*
7326  * Prepare an inode to be freed. The actual free operation is not
7327  * done until the zero'ed inode has been written to disk.
7328  */
7329 void
7330 softdep_freefile(pvp, ino, mode)
7331         struct vnode *pvp;
7332         ino_t ino;
7333         int mode;
7334 {
7335         struct inode *ip = VTOI(pvp);
7336         struct inodedep *inodedep;
7337         struct freefile *freefile;
7338         struct freeblks *freeblks;
7339
7340         /*
7341          * This sets up the inode de-allocation dependency.
7342          */
7343         freefile = malloc(sizeof(struct freefile),
7344                 M_FREEFILE, M_SOFTDEP_FLAGS);
7345         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7346         freefile->fx_mode = mode;
7347         freefile->fx_oldinum = ino;
7348         freefile->fx_devvp = ip->i_devvp;
7349         LIST_INIT(&freefile->fx_jwork);
7350         UFS_LOCK(ip->i_ump);
7351         ip->i_fs->fs_pendinginodes += 1;
7352         UFS_UNLOCK(ip->i_ump);
7353
7354         /*
7355          * If the inodedep does not exist, then the zero'ed inode has
7356          * been written to disk. If the allocated inode has never been
7357          * written to disk, then the on-disk inode is zero'ed. In either
7358          * case we can free the file immediately.  If the journal was
7359          * canceled before being written the inode will never make it to
7360          * disk and we must send the canceled journal entrys to
7361          * ffs_freefile() to be cleared in conjunction with the bitmap.
7362          * Any blocks waiting on the inode to write can be safely freed
7363          * here as it will never been written.
7364          */
7365         ACQUIRE_LOCK(&lk);
7366         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7367         if (inodedep) {
7368                 /*
7369                  * Clear out freeblks that no longer need to reference
7370                  * this inode.
7371                  */
7372                 while ((freeblks =
7373                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7374                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7375                             fb_next);
7376                         freeblks->fb_state &= ~ONDEPLIST;
7377                 }
7378                 /*
7379                  * Remove this inode from the unlinked list.
7380                  */
7381                 if (inodedep->id_state & UNLINKED) {
7382                         /*
7383                          * Save the journal work to be freed with the bitmap
7384                          * before we clear UNLINKED.  Otherwise it can be lost
7385                          * if the inode block is written.
7386                          */
7387                         handle_bufwait(inodedep, &freefile->fx_jwork);
7388                         clear_unlinked_inodedep(inodedep);
7389                         /* Re-acquire inodedep as we've dropped lk. */
7390                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7391                 }
7392         }
7393         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7394                 FREE_LOCK(&lk);
7395                 handle_workitem_freefile(freefile);
7396                 return;
7397         }
7398         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7399                 inodedep->id_state |= GOINGAWAY;
7400         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7401         FREE_LOCK(&lk);
7402         if (ip->i_number == ino)
7403                 ip->i_flag |= IN_MODIFIED;
7404 }
7405
7406 /*
7407  * Check to see if an inode has never been written to disk. If
7408  * so free the inodedep and return success, otherwise return failure.
7409  * This routine must be called with splbio interrupts blocked.
7410  *
7411  * If we still have a bitmap dependency, then the inode has never
7412  * been written to disk. Drop the dependency as it is no longer
7413  * necessary since the inode is being deallocated. We set the
7414  * ALLCOMPLETE flags since the bitmap now properly shows that the
7415  * inode is not allocated. Even if the inode is actively being
7416  * written, it has been rolled back to its zero'ed state, so we
7417  * are ensured that a zero inode is what is on the disk. For short
7418  * lived files, this change will usually result in removing all the
7419  * dependencies from the inode so that it can be freed immediately.
7420  */
7421 static int
7422 check_inode_unwritten(inodedep)
7423         struct inodedep *inodedep;
7424 {
7425
7426         mtx_assert(&lk, MA_OWNED);
7427
7428         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7429             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7430             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7431             !LIST_EMPTY(&inodedep->id_bufwait) ||
7432             !LIST_EMPTY(&inodedep->id_inowait) ||
7433             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7434             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7435             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7436             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7437             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7438             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7439             inodedep->id_mkdiradd != NULL || 
7440             inodedep->id_nlinkdelta != 0)
7441                 return (0);
7442         /*
7443          * Another process might be in initiate_write_inodeblock_ufs[12]
7444          * trying to allocate memory without holding "Softdep Lock".
7445          */
7446         if ((inodedep->id_state & IOSTARTED) != 0 &&
7447             inodedep->id_savedino1 == NULL)
7448                 return (0);
7449
7450         if (inodedep->id_state & ONDEPLIST)
7451                 LIST_REMOVE(inodedep, id_deps);
7452         inodedep->id_state &= ~ONDEPLIST;
7453         inodedep->id_state |= ALLCOMPLETE;
7454         inodedep->id_bmsafemap = NULL;
7455         if (inodedep->id_state & ONWORKLIST)
7456                 WORKLIST_REMOVE(&inodedep->id_list);
7457         if (inodedep->id_savedino1 != NULL) {
7458                 free(inodedep->id_savedino1, M_SAVEDINO);
7459                 inodedep->id_savedino1 = NULL;
7460         }
7461         if (free_inodedep(inodedep) == 0)
7462                 panic("check_inode_unwritten: busy inode");
7463         return (1);
7464 }
7465
7466 /*
7467  * Try to free an inodedep structure. Return 1 if it could be freed.
7468  */
7469 static int
7470 free_inodedep(inodedep)
7471         struct inodedep *inodedep;
7472 {
7473
7474         mtx_assert(&lk, MA_OWNED);
7475         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7476             (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7477             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7478             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7479             !LIST_EMPTY(&inodedep->id_bufwait) ||
7480             !LIST_EMPTY(&inodedep->id_inowait) ||
7481             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7482             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7483             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7484             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7485             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7486             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7487             inodedep->id_mkdiradd != NULL ||
7488             inodedep->id_nlinkdelta != 0 ||
7489             inodedep->id_savedino1 != NULL)
7490                 return (0);
7491         if (inodedep->id_state & ONDEPLIST)
7492                 LIST_REMOVE(inodedep, id_deps);
7493         LIST_REMOVE(inodedep, id_hash);
7494         WORKITEM_FREE(inodedep, D_INODEDEP);
7495         return (1);
7496 }
7497
7498 /*
7499  * Free the block referenced by a freework structure.  The parent freeblks
7500  * structure is released and completed when the final cg bitmap reaches
7501  * the disk.  This routine may be freeing a jnewblk which never made it to
7502  * disk in which case we do not have to wait as the operation is undone
7503  * in memory immediately.
7504  */
7505 static void
7506 freework_freeblock(freework)
7507         struct freework *freework;
7508 {
7509         struct freeblks *freeblks;
7510         struct jnewblk *jnewblk;
7511         struct ufsmount *ump;
7512         struct workhead wkhd;
7513         struct fs *fs;
7514         int bsize;
7515         int needj;
7516
7517         mtx_assert(&lk, MA_OWNED);
7518         /*
7519          * Handle partial truncate separately.
7520          */
7521         if (freework->fw_indir) {
7522                 complete_trunc_indir(freework);
7523                 return;
7524         }
7525         freeblks = freework->fw_freeblks;
7526         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7527         fs = ump->um_fs;
7528         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7529         bsize = lfragtosize(fs, freework->fw_frags);
7530         LIST_INIT(&wkhd);
7531         /*
7532          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7533          * on the indirblk hashtable and prevents premature freeing.
7534          */
7535         freework->fw_state |= DEPCOMPLETE;
7536         /*
7537          * SUJ needs to wait for the segment referencing freed indirect
7538          * blocks to expire so that we know the checker will not confuse
7539          * a re-allocated indirect block with its old contents.
7540          */
7541         if (needj && freework->fw_lbn <= -NDADDR)
7542                 indirblk_insert(freework);
7543         /*
7544          * If we are canceling an existing jnewblk pass it to the free
7545          * routine, otherwise pass the freeblk which will ultimately
7546          * release the freeblks.  If we're not journaling, we can just
7547          * free the freeblks immediately.
7548          */
7549         jnewblk = freework->fw_jnewblk;
7550         if (jnewblk != NULL) {
7551                 cancel_jnewblk(jnewblk, &wkhd);
7552                 needj = 0;
7553         } else if (needj) {
7554                 freework->fw_state |= DELAYEDFREE;
7555                 freeblks->fb_cgwait++;
7556                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7557         }
7558         FREE_LOCK(&lk);
7559         freeblks_free(ump, freeblks, btodb(bsize));
7560         CTR4(KTR_SUJ,
7561             "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7562             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7563         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7564             freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7565         ACQUIRE_LOCK(&lk);
7566         /*
7567          * The jnewblk will be discarded and the bits in the map never
7568          * made it to disk.  We can immediately free the freeblk.
7569          */
7570         if (needj == 0)
7571                 handle_written_freework(freework);
7572 }
7573
7574 /*
7575  * We enqueue freework items that need processing back on the freeblks and
7576  * add the freeblks to the worklist.  This makes it easier to find all work
7577  * required to flush a truncation in process_truncates().
7578  */
7579 static void
7580 freework_enqueue(freework)
7581         struct freework *freework;
7582 {
7583         struct freeblks *freeblks;
7584
7585         freeblks = freework->fw_freeblks;
7586         if ((freework->fw_state & INPROGRESS) == 0)
7587                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7588         if ((freeblks->fb_state &
7589             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7590             LIST_EMPTY(&freeblks->fb_jblkdephd))
7591                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7592 }
7593
7594 /*
7595  * Start, continue, or finish the process of freeing an indirect block tree.
7596  * The free operation may be paused at any point with fw_off containing the
7597  * offset to restart from.  This enables us to implement some flow control
7598  * for large truncates which may fan out and generate a huge number of
7599  * dependencies.
7600  */
7601 static void
7602 handle_workitem_indirblk(freework)
7603         struct freework *freework;
7604 {
7605         struct freeblks *freeblks;
7606         struct ufsmount *ump;
7607         struct fs *fs;
7608
7609         freeblks = freework->fw_freeblks;
7610         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7611         fs = ump->um_fs;
7612         if (freework->fw_state & DEPCOMPLETE) {
7613                 handle_written_freework(freework);
7614                 return;
7615         }
7616         if (freework->fw_off == NINDIR(fs)) {
7617                 freework_freeblock(freework);
7618                 return;
7619         }
7620         freework->fw_state |= INPROGRESS;
7621         FREE_LOCK(&lk);
7622         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7623             freework->fw_lbn);
7624         ACQUIRE_LOCK(&lk);
7625 }
7626
7627 /*
7628  * Called when a freework structure attached to a cg buf is written.  The
7629  * ref on either the parent or the freeblks structure is released and
7630  * the freeblks is added back to the worklist if there is more work to do.
7631  */
7632 static void
7633 handle_written_freework(freework)
7634         struct freework *freework;
7635 {
7636         struct freeblks *freeblks;
7637         struct freework *parent;
7638
7639         freeblks = freework->fw_freeblks;
7640         parent = freework->fw_parent;
7641         if (freework->fw_state & DELAYEDFREE)
7642                 freeblks->fb_cgwait--;
7643         freework->fw_state |= COMPLETE;
7644         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7645                 WORKITEM_FREE(freework, D_FREEWORK);
7646         if (parent) {
7647                 if (--parent->fw_ref == 0)
7648                         freework_enqueue(parent);
7649                 return;
7650         }
7651         if (--freeblks->fb_ref != 0)
7652                 return;
7653         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7654             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7655                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7656 }
7657
7658 /*
7659  * This workitem routine performs the block de-allocation.
7660  * The workitem is added to the pending list after the updated
7661  * inode block has been written to disk.  As mentioned above,
7662  * checks regarding the number of blocks de-allocated (compared
7663  * to the number of blocks allocated for the file) are also
7664  * performed in this function.
7665  */
7666 static int
7667 handle_workitem_freeblocks(freeblks, flags)
7668         struct freeblks *freeblks;
7669         int flags;
7670 {
7671         struct freework *freework;
7672         struct newblk *newblk;
7673         struct allocindir *aip;
7674         struct ufsmount *ump;
7675         struct worklist *wk;
7676
7677         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7678             ("handle_workitem_freeblocks: Journal entries not written."));
7679         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7680         ACQUIRE_LOCK(&lk);
7681         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7682                 WORKLIST_REMOVE(wk);
7683                 switch (wk->wk_type) {
7684                 case D_DIRREM:
7685                         wk->wk_state |= COMPLETE;
7686                         add_to_worklist(wk, 0);
7687                         continue;
7688
7689                 case D_ALLOCDIRECT:
7690                         free_newblk(WK_NEWBLK(wk));
7691                         continue;
7692
7693                 case D_ALLOCINDIR:
7694                         aip = WK_ALLOCINDIR(wk);
7695                         freework = NULL;
7696                         if (aip->ai_state & DELAYEDFREE) {
7697                                 FREE_LOCK(&lk);
7698                                 freework = newfreework(ump, freeblks, NULL,
7699                                     aip->ai_lbn, aip->ai_newblkno,
7700                                     ump->um_fs->fs_frag, 0, 0);
7701                                 ACQUIRE_LOCK(&lk);
7702                         }
7703                         newblk = WK_NEWBLK(wk);
7704                         if (newblk->nb_jnewblk) {
7705                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7706                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7707                                 newblk->nb_jnewblk = NULL;
7708                         }
7709                         free_newblk(newblk);
7710                         continue;
7711
7712                 case D_FREEWORK:
7713                         freework = WK_FREEWORK(wk);
7714                         if (freework->fw_lbn <= -NDADDR)
7715                                 handle_workitem_indirblk(freework);
7716                         else
7717                                 freework_freeblock(freework);
7718                         continue;
7719                 default:
7720                         panic("handle_workitem_freeblocks: Unknown type %s",
7721                             TYPENAME(wk->wk_type));
7722                 }
7723         }
7724         if (freeblks->fb_ref != 0) {
7725                 freeblks->fb_state &= ~INPROGRESS;
7726                 wake_worklist(&freeblks->fb_list);
7727                 freeblks = NULL;
7728         }
7729         FREE_LOCK(&lk);
7730         if (freeblks)
7731                 return handle_complete_freeblocks(freeblks, flags);
7732         return (0);
7733 }
7734
7735 /*
7736  * Handle completion of block free via truncate.  This allows fs_pending
7737  * to track the actual free block count more closely than if we only updated
7738  * it at the end.  We must be careful to handle cases where the block count
7739  * on free was incorrect.
7740  */
7741 static void
7742 freeblks_free(ump, freeblks, blocks)
7743         struct ufsmount *ump;
7744         struct freeblks *freeblks;
7745         int blocks;
7746 {
7747         struct fs *fs;
7748         ufs2_daddr_t remain;
7749
7750         UFS_LOCK(ump);
7751         remain = -freeblks->fb_chkcnt;
7752         freeblks->fb_chkcnt += blocks;
7753         if (remain > 0) {
7754                 if (remain < blocks)
7755                         blocks = remain;
7756                 fs = ump->um_fs;
7757                 fs->fs_pendingblocks -= blocks;
7758         }
7759         UFS_UNLOCK(ump);
7760 }
7761
7762 /*
7763  * Once all of the freework workitems are complete we can retire the
7764  * freeblocks dependency and any journal work awaiting completion.  This
7765  * can not be called until all other dependencies are stable on disk.
7766  */
7767 static int
7768 handle_complete_freeblocks(freeblks, flags)
7769         struct freeblks *freeblks;
7770         int flags;
7771 {
7772         struct inodedep *inodedep;
7773         struct inode *ip;
7774         struct vnode *vp;
7775         struct fs *fs;
7776         struct ufsmount *ump;
7777         ufs2_daddr_t spare;
7778
7779         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7780         fs = ump->um_fs;
7781         flags = LK_EXCLUSIVE | flags;
7782         spare = freeblks->fb_chkcnt;
7783
7784         /*
7785          * If we did not release the expected number of blocks we may have
7786          * to adjust the inode block count here.  Only do so if it wasn't
7787          * a truncation to zero and the modrev still matches.
7788          */
7789         if (spare && freeblks->fb_len != 0) {
7790                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7791                     flags, &vp, FFSV_FORCEINSMQ) != 0)
7792                         return (EBUSY);
7793                 ip = VTOI(vp);
7794                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7795                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7796                         ip->i_flag |= IN_CHANGE;
7797                         /*
7798                          * We must wait so this happens before the
7799                          * journal is reclaimed.
7800                          */
7801                         ffs_update(vp, 1);
7802                 }
7803                 vput(vp);
7804         }
7805         if (spare < 0) {
7806                 UFS_LOCK(ump);
7807                 fs->fs_pendingblocks += spare;
7808                 UFS_UNLOCK(ump);
7809         }
7810 #ifdef QUOTA
7811         /* Handle spare. */
7812         if (spare)
7813                 quotaadj(freeblks->fb_quota, ump, -spare);
7814         quotarele(freeblks->fb_quota);
7815 #endif
7816         ACQUIRE_LOCK(&lk);
7817         if (freeblks->fb_state & ONDEPLIST) {
7818                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7819                     0, &inodedep);
7820                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
7821                 freeblks->fb_state &= ~ONDEPLIST;
7822                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
7823                         free_inodedep(inodedep);
7824         }
7825         /*
7826          * All of the freeblock deps must be complete prior to this call
7827          * so it's now safe to complete earlier outstanding journal entries.
7828          */
7829         handle_jwork(&freeblks->fb_jwork);
7830         WORKITEM_FREE(freeblks, D_FREEBLKS);
7831         FREE_LOCK(&lk);
7832         return (0);
7833 }
7834
7835 /*
7836  * Release blocks associated with the freeblks and stored in the indirect
7837  * block dbn. If level is greater than SINGLE, the block is an indirect block
7838  * and recursive calls to indirtrunc must be used to cleanse other indirect
7839  * blocks.
7840  *
7841  * This handles partial and complete truncation of blocks.  Partial is noted
7842  * with goingaway == 0.  In this case the freework is completed after the
7843  * zero'd indirects are written to disk.  For full truncation the freework
7844  * is completed after the block is freed.
7845  */
7846 static void
7847 indir_trunc(freework, dbn, lbn)
7848         struct freework *freework;
7849         ufs2_daddr_t dbn;
7850         ufs_lbn_t lbn;
7851 {
7852         struct freework *nfreework;
7853         struct workhead wkhd;
7854         struct freeblks *freeblks;
7855         struct buf *bp;
7856         struct fs *fs;
7857         struct indirdep *indirdep;
7858         struct ufsmount *ump;
7859         ufs1_daddr_t *bap1;
7860         ufs2_daddr_t nb, nnb, *bap2;
7861         ufs_lbn_t lbnadd, nlbn;
7862         int i, nblocks, ufs1fmt;
7863         int freedblocks;
7864         int goingaway;
7865         int freedeps;
7866         int needj;
7867         int level;
7868         int cnt;
7869
7870         freeblks = freework->fw_freeblks;
7871         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7872         fs = ump->um_fs;
7873         /*
7874          * Get buffer of block pointers to be freed.  There are three cases:
7875          * 
7876          * 1) Partial truncate caches the indirdep pointer in the freework
7877          *    which provides us a back copy to the save bp which holds the
7878          *    pointers we want to clear.  When this completes the zero
7879          *    pointers are written to the real copy.
7880          * 2) The indirect is being completely truncated, cancel_indirdep()
7881          *    eliminated the real copy and placed the indirdep on the saved
7882          *    copy.  The indirdep and buf are discarded when this completes.
7883          * 3) The indirect was not in memory, we read a copy off of the disk
7884          *    using the devvp and drop and invalidate the buffer when we're
7885          *    done.
7886          */
7887         goingaway = 1;
7888         indirdep = NULL;
7889         if (freework->fw_indir != NULL) {
7890                 goingaway = 0;
7891                 indirdep = freework->fw_indir;
7892                 bp = indirdep->ir_savebp;
7893                 if (bp == NULL || bp->b_blkno != dbn)
7894                         panic("indir_trunc: Bad saved buf %p blkno %jd",
7895                             bp, (intmax_t)dbn);
7896         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
7897                 /*
7898                  * The lock prevents the buf dep list from changing and
7899                  * indirects on devvp should only ever have one dependency.
7900                  */
7901                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
7902                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
7903                         panic("indir_trunc: Bad indirdep %p from buf %p",
7904                             indirdep, bp);
7905         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
7906             NOCRED, &bp) != 0) {
7907                 brelse(bp);
7908                 return;
7909         }
7910         ACQUIRE_LOCK(&lk);
7911         /* Protects against a race with complete_trunc_indir(). */
7912         freework->fw_state &= ~INPROGRESS;
7913         /*
7914          * If we have an indirdep we need to enforce the truncation order
7915          * and discard it when it is complete.
7916          */
7917         if (indirdep) {
7918                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
7919                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
7920                         /*
7921                          * Add the complete truncate to the list on the
7922                          * indirdep to enforce in-order processing.
7923                          */
7924                         if (freework->fw_indir == NULL)
7925                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
7926                                     freework, fw_next);
7927                         FREE_LOCK(&lk);
7928                         return;
7929                 }
7930                 /*
7931                  * If we're goingaway, free the indirdep.  Otherwise it will
7932                  * linger until the write completes.
7933                  */
7934                 if (goingaway) {
7935                         free_indirdep(indirdep);
7936                         ump->um_numindirdeps -= 1;
7937                 }
7938         }
7939         FREE_LOCK(&lk);
7940         /* Initialize pointers depending on block size. */
7941         if (ump->um_fstype == UFS1) {
7942                 bap1 = (ufs1_daddr_t *)bp->b_data;
7943                 nb = bap1[freework->fw_off];
7944                 ufs1fmt = 1;
7945                 bap2 = NULL;
7946         } else {
7947                 bap2 = (ufs2_daddr_t *)bp->b_data;
7948                 nb = bap2[freework->fw_off];
7949                 ufs1fmt = 0;
7950                 bap1 = NULL;
7951         }
7952         level = lbn_level(lbn);
7953         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
7954         lbnadd = lbn_offset(fs, level);
7955         nblocks = btodb(fs->fs_bsize);
7956         nfreework = freework;
7957         freedeps = 0;
7958         cnt = 0;
7959         /*
7960          * Reclaim blocks.  Traverses into nested indirect levels and
7961          * arranges for the current level to be freed when subordinates
7962          * are free when journaling.
7963          */
7964         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
7965                 if (i != NINDIR(fs) - 1) {
7966                         if (ufs1fmt)
7967                                 nnb = bap1[i+1];
7968                         else
7969                                 nnb = bap2[i+1];
7970                 } else
7971                         nnb = 0;
7972                 if (nb == 0)
7973                         continue;
7974                 cnt++;
7975                 if (level != 0) {
7976                         nlbn = (lbn + 1) - (i * lbnadd);
7977                         if (needj != 0) {
7978                                 nfreework = newfreework(ump, freeblks, freework,
7979                                     nlbn, nb, fs->fs_frag, 0, 0);
7980                                 freedeps++;
7981                         }
7982                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
7983                 } else {
7984                         struct freedep *freedep;
7985
7986                         /*
7987                          * Attempt to aggregate freedep dependencies for
7988                          * all blocks being released to the same CG.
7989                          */
7990                         LIST_INIT(&wkhd);
7991                         if (needj != 0 &&
7992                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
7993                                 freedep = newfreedep(freework);
7994                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
7995                                     &freedep->fd_list);
7996                                 freedeps++;
7997                         }
7998                         CTR3(KTR_SUJ,
7999                             "indir_trunc: ino %d blkno %jd size %ld",
8000                             freeblks->fb_inum, nb, fs->fs_bsize);
8001                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8002                             fs->fs_bsize, freeblks->fb_inum,
8003                             freeblks->fb_vtype, &wkhd);
8004                 }
8005         }
8006         if (goingaway) {
8007                 bp->b_flags |= B_INVAL | B_NOCACHE;
8008                 brelse(bp);
8009         }
8010         freedblocks = 0;
8011         if (level == 0)
8012                 freedblocks = (nblocks * cnt);
8013         if (needj == 0)
8014                 freedblocks += nblocks;
8015         freeblks_free(ump, freeblks, freedblocks);
8016         /*
8017          * If we are journaling set up the ref counts and offset so this
8018          * indirect can be completed when its children are free.
8019          */
8020         if (needj) {
8021                 ACQUIRE_LOCK(&lk);
8022                 freework->fw_off = i;
8023                 freework->fw_ref += freedeps;
8024                 freework->fw_ref -= NINDIR(fs) + 1;
8025                 if (level == 0)
8026                         freeblks->fb_cgwait += freedeps;
8027                 if (freework->fw_ref == 0)
8028                         freework_freeblock(freework);
8029                 FREE_LOCK(&lk);
8030                 return;
8031         }
8032         /*
8033          * If we're not journaling we can free the indirect now.
8034          */
8035         dbn = dbtofsb(fs, dbn);
8036         CTR3(KTR_SUJ,
8037             "indir_trunc 2: ino %d blkno %jd size %ld",
8038             freeblks->fb_inum, dbn, fs->fs_bsize);
8039         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8040             freeblks->fb_inum, freeblks->fb_vtype, NULL);
8041         /* Non SUJ softdep does single-threaded truncations. */
8042         if (freework->fw_blkno == dbn) {
8043                 freework->fw_state |= ALLCOMPLETE;
8044                 ACQUIRE_LOCK(&lk);
8045                 handle_written_freework(freework);
8046                 FREE_LOCK(&lk);
8047         }
8048         return;
8049 }
8050
8051 /*
8052  * Cancel an allocindir when it is removed via truncation.  When bp is not
8053  * NULL the indirect never appeared on disk and is scheduled to be freed
8054  * independently of the indir so we can more easily track journal work.
8055  */
8056 static void
8057 cancel_allocindir(aip, bp, freeblks, trunc)
8058         struct allocindir *aip;
8059         struct buf *bp;
8060         struct freeblks *freeblks;
8061         int trunc;
8062 {
8063         struct indirdep *indirdep;
8064         struct freefrag *freefrag;
8065         struct newblk *newblk;
8066
8067         newblk = (struct newblk *)aip;
8068         LIST_REMOVE(aip, ai_next);
8069         /*
8070          * We must eliminate the pointer in bp if it must be freed on its
8071          * own due to partial truncate or pending journal work.
8072          */
8073         if (bp && (trunc || newblk->nb_jnewblk)) {
8074                 /*
8075                  * Clear the pointer and mark the aip to be freed
8076                  * directly if it never existed on disk.
8077                  */
8078                 aip->ai_state |= DELAYEDFREE;
8079                 indirdep = aip->ai_indirdep;
8080                 if (indirdep->ir_state & UFS1FMT)
8081                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8082                 else
8083                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8084         }
8085         /*
8086          * When truncating the previous pointer will be freed via
8087          * savedbp.  Eliminate the freefrag which would dup free.
8088          */
8089         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8090                 newblk->nb_freefrag = NULL;
8091                 if (freefrag->ff_jdep)
8092                         cancel_jfreefrag(
8093                             WK_JFREEFRAG(freefrag->ff_jdep));
8094                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8095                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8096         }
8097         /*
8098          * If the journal hasn't been written the jnewblk must be passed
8099          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8100          * this by leaving the journal dependency on the newblk to be freed
8101          * when a freework is created in handle_workitem_freeblocks().
8102          */
8103         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8104         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8105 }
8106
8107 /*
8108  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8109  * in to a newdirblk so any subsequent additions are tracked properly.  The
8110  * caller is responsible for adding the mkdir1 dependency to the journal
8111  * and updating id_mkdiradd.  This function returns with lk held.
8112  */
8113 static struct mkdir *
8114 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8115         struct diradd *dap;
8116         ino_t newinum;
8117         ino_t dinum;
8118         struct buf *newdirbp;
8119         struct mkdir **mkdirp;
8120 {
8121         struct newblk *newblk;
8122         struct pagedep *pagedep;
8123         struct inodedep *inodedep;
8124         struct newdirblk *newdirblk;
8125         struct mkdir *mkdir1, *mkdir2;
8126         struct worklist *wk;
8127         struct jaddref *jaddref;
8128         struct mount *mp;
8129
8130         mp = dap->da_list.wk_mp;
8131         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8132             M_SOFTDEP_FLAGS);
8133         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8134         LIST_INIT(&newdirblk->db_mkdir);
8135         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8136         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8137         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8138         mkdir1->md_diradd = dap;
8139         mkdir1->md_jaddref = NULL;
8140         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8141         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8142         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8143         mkdir2->md_diradd = dap;
8144         mkdir2->md_jaddref = NULL;
8145         if (MOUNTEDSUJ(mp) == 0) {
8146                 mkdir1->md_state |= DEPCOMPLETE;
8147                 mkdir2->md_state |= DEPCOMPLETE;
8148         }
8149         /*
8150          * Dependency on "." and ".." being written to disk.
8151          */
8152         mkdir1->md_buf = newdirbp;
8153         ACQUIRE_LOCK(&lk);
8154         LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
8155         /*
8156          * We must link the pagedep, allocdirect, and newdirblk for
8157          * the initial file page so the pointer to the new directory
8158          * is not written until the directory contents are live and
8159          * any subsequent additions are not marked live until the
8160          * block is reachable via the inode.
8161          */
8162         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8163                 panic("setup_newdir: lost pagedep");
8164         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8165                 if (wk->wk_type == D_ALLOCDIRECT)
8166                         break;
8167         if (wk == NULL)
8168                 panic("setup_newdir: lost allocdirect");
8169         if (pagedep->pd_state & NEWBLOCK)
8170                 panic("setup_newdir: NEWBLOCK already set");
8171         newblk = WK_NEWBLK(wk);
8172         pagedep->pd_state |= NEWBLOCK;
8173         pagedep->pd_newdirblk = newdirblk;
8174         newdirblk->db_pagedep = pagedep;
8175         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8176         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8177         /*
8178          * Look up the inodedep for the parent directory so that we
8179          * can link mkdir2 into the pending dotdot jaddref or
8180          * the inode write if there is none.  If the inode is
8181          * ALLCOMPLETE and no jaddref is present all dependencies have
8182          * been satisfied and mkdir2 can be freed.
8183          */
8184         inodedep_lookup(mp, dinum, 0, &inodedep);
8185         if (MOUNTEDSUJ(mp)) {
8186                 if (inodedep == NULL)
8187                         panic("setup_newdir: Lost parent.");
8188                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8189                     inoreflst);
8190                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8191                     (jaddref->ja_state & MKDIR_PARENT),
8192                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8193                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
8194                 mkdir2->md_jaddref = jaddref;
8195                 jaddref->ja_mkdir = mkdir2;
8196         } else if (inodedep == NULL ||
8197             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8198                 dap->da_state &= ~MKDIR_PARENT;
8199                 WORKITEM_FREE(mkdir2, D_MKDIR);
8200                 mkdir2 = NULL;
8201         } else {
8202                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
8203                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8204         }
8205         *mkdirp = mkdir2;
8206
8207         return (mkdir1);
8208 }
8209
8210 /*
8211  * Directory entry addition dependencies.
8212  * 
8213  * When adding a new directory entry, the inode (with its incremented link
8214  * count) must be written to disk before the directory entry's pointer to it.
8215  * Also, if the inode is newly allocated, the corresponding freemap must be
8216  * updated (on disk) before the directory entry's pointer. These requirements
8217  * are met via undo/redo on the directory entry's pointer, which consists
8218  * simply of the inode number.
8219  * 
8220  * As directory entries are added and deleted, the free space within a
8221  * directory block can become fragmented.  The ufs filesystem will compact
8222  * a fragmented directory block to make space for a new entry. When this
8223  * occurs, the offsets of previously added entries change. Any "diradd"
8224  * dependency structures corresponding to these entries must be updated with
8225  * the new offsets.
8226  */
8227
8228 /*
8229  * This routine is called after the in-memory inode's link
8230  * count has been incremented, but before the directory entry's
8231  * pointer to the inode has been set.
8232  */
8233 int
8234 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8235         struct buf *bp;         /* buffer containing directory block */
8236         struct inode *dp;       /* inode for directory */
8237         off_t diroffset;        /* offset of new entry in directory */
8238         ino_t newinum;          /* inode referenced by new directory entry */
8239         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8240         int isnewblk;           /* entry is in a newly allocated block */
8241 {
8242         int offset;             /* offset of new entry within directory block */
8243         ufs_lbn_t lbn;          /* block in directory containing new entry */
8244         struct fs *fs;
8245         struct diradd *dap;
8246         struct newblk *newblk;
8247         struct pagedep *pagedep;
8248         struct inodedep *inodedep;
8249         struct newdirblk *newdirblk;
8250         struct mkdir *mkdir1, *mkdir2;
8251         struct jaddref *jaddref;
8252         struct mount *mp;
8253         int isindir;
8254
8255         /*
8256          * Whiteouts have no dependencies.
8257          */
8258         if (newinum == WINO) {
8259                 if (newdirbp != NULL)
8260                         bdwrite(newdirbp);
8261                 return (0);
8262         }
8263         jaddref = NULL;
8264         mkdir1 = mkdir2 = NULL;
8265         mp = UFSTOVFS(dp->i_ump);
8266         fs = dp->i_fs;
8267         lbn = lblkno(fs, diroffset);
8268         offset = blkoff(fs, diroffset);
8269         dap = malloc(sizeof(struct diradd), M_DIRADD,
8270                 M_SOFTDEP_FLAGS|M_ZERO);
8271         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8272         dap->da_offset = offset;
8273         dap->da_newinum = newinum;
8274         dap->da_state = ATTACHED;
8275         LIST_INIT(&dap->da_jwork);
8276         isindir = bp->b_lblkno >= NDADDR;
8277         newdirblk = NULL;
8278         if (isnewblk &&
8279             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8280                 newdirblk = malloc(sizeof(struct newdirblk),
8281                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8282                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8283                 LIST_INIT(&newdirblk->db_mkdir);
8284         }
8285         /*
8286          * If we're creating a new directory setup the dependencies and set
8287          * the dap state to wait for them.  Otherwise it's COMPLETE and
8288          * we can move on.
8289          */
8290         if (newdirbp == NULL) {
8291                 dap->da_state |= DEPCOMPLETE;
8292                 ACQUIRE_LOCK(&lk);
8293         } else {
8294                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8295                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8296                     &mkdir2);
8297         }
8298         /*
8299          * Link into parent directory pagedep to await its being written.
8300          */
8301         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8302 #ifdef DEBUG
8303         if (diradd_lookup(pagedep, offset) != NULL)
8304                 panic("softdep_setup_directory_add: %p already at off %d\n",
8305                     diradd_lookup(pagedep, offset), offset);
8306 #endif
8307         dap->da_pagedep = pagedep;
8308         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8309             da_pdlist);
8310         inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8311         /*
8312          * If we're journaling, link the diradd into the jaddref so it
8313          * may be completed after the journal entry is written.  Otherwise,
8314          * link the diradd into its inodedep.  If the inode is not yet
8315          * written place it on the bufwait list, otherwise do the post-inode
8316          * write processing to put it on the id_pendinghd list.
8317          */
8318         if (MOUNTEDSUJ(mp)) {
8319                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8320                     inoreflst);
8321                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8322                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8323                 jaddref->ja_diroff = diroffset;
8324                 jaddref->ja_diradd = dap;
8325                 add_to_journal(&jaddref->ja_list);
8326         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8327                 diradd_inode_written(dap, inodedep);
8328         else
8329                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8330         /*
8331          * Add the journal entries for . and .. links now that the primary
8332          * link is written.
8333          */
8334         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8335                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8336                     inoreflst, if_deps);
8337                 KASSERT(jaddref != NULL &&
8338                     jaddref->ja_ino == jaddref->ja_parent &&
8339                     (jaddref->ja_state & MKDIR_BODY),
8340                     ("softdep_setup_directory_add: bad dot jaddref %p",
8341                     jaddref));
8342                 mkdir1->md_jaddref = jaddref;
8343                 jaddref->ja_mkdir = mkdir1;
8344                 /*
8345                  * It is important that the dotdot journal entry
8346                  * is added prior to the dot entry since dot writes
8347                  * both the dot and dotdot links.  These both must
8348                  * be added after the primary link for the journal
8349                  * to remain consistent.
8350                  */
8351                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8352                 add_to_journal(&jaddref->ja_list);
8353         }
8354         /*
8355          * If we are adding a new directory remember this diradd so that if
8356          * we rename it we can keep the dot and dotdot dependencies.  If
8357          * we are adding a new name for an inode that has a mkdiradd we
8358          * must be in rename and we have to move the dot and dotdot
8359          * dependencies to this new name.  The old name is being orphaned
8360          * soon.
8361          */
8362         if (mkdir1 != NULL) {
8363                 if (inodedep->id_mkdiradd != NULL)
8364                         panic("softdep_setup_directory_add: Existing mkdir");
8365                 inodedep->id_mkdiradd = dap;
8366         } else if (inodedep->id_mkdiradd)
8367                 merge_diradd(inodedep, dap);
8368         if (newdirblk != NULL) {
8369                 /*
8370                  * There is nothing to do if we are already tracking
8371                  * this block.
8372                  */
8373                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8374                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8375                         FREE_LOCK(&lk);
8376                         return (0);
8377                 }
8378                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8379                     == 0)
8380                         panic("softdep_setup_directory_add: lost entry");
8381                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8382                 pagedep->pd_state |= NEWBLOCK;
8383                 pagedep->pd_newdirblk = newdirblk;
8384                 newdirblk->db_pagedep = pagedep;
8385                 FREE_LOCK(&lk);
8386                 /*
8387                  * If we extended into an indirect signal direnter to sync.
8388                  */
8389                 if (isindir)
8390                         return (1);
8391                 return (0);
8392         }
8393         FREE_LOCK(&lk);
8394         return (0);
8395 }
8396
8397 /*
8398  * This procedure is called to change the offset of a directory
8399  * entry when compacting a directory block which must be owned
8400  * exclusively by the caller. Note that the actual entry movement
8401  * must be done in this procedure to ensure that no I/O completions
8402  * occur while the move is in progress.
8403  */
8404 void 
8405 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8406         struct buf *bp;         /* Buffer holding directory block. */
8407         struct inode *dp;       /* inode for directory */
8408         caddr_t base;           /* address of dp->i_offset */
8409         caddr_t oldloc;         /* address of old directory location */
8410         caddr_t newloc;         /* address of new directory location */
8411         int entrysize;          /* size of directory entry */
8412 {
8413         int offset, oldoffset, newoffset;
8414         struct pagedep *pagedep;
8415         struct jmvref *jmvref;
8416         struct diradd *dap;
8417         struct direct *de;
8418         struct mount *mp;
8419         ufs_lbn_t lbn;
8420         int flags;
8421
8422         mp = UFSTOVFS(dp->i_ump);
8423         de = (struct direct *)oldloc;
8424         jmvref = NULL;
8425         flags = 0;
8426         /*
8427          * Moves are always journaled as it would be too complex to
8428          * determine if any affected adds or removes are present in the
8429          * journal.
8430          */
8431         if (MOUNTEDSUJ(mp)) {
8432                 flags = DEPALLOC;
8433                 jmvref = newjmvref(dp, de->d_ino,
8434                     dp->i_offset + (oldloc - base),
8435                     dp->i_offset + (newloc - base));
8436         }
8437         lbn = lblkno(dp->i_fs, dp->i_offset);
8438         offset = blkoff(dp->i_fs, dp->i_offset);
8439         oldoffset = offset + (oldloc - base);
8440         newoffset = offset + (newloc - base);
8441         ACQUIRE_LOCK(&lk);
8442         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8443                 goto done;
8444         dap = diradd_lookup(pagedep, oldoffset);
8445         if (dap) {
8446                 dap->da_offset = newoffset;
8447                 newoffset = DIRADDHASH(newoffset);
8448                 oldoffset = DIRADDHASH(oldoffset);
8449                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8450                     newoffset != oldoffset) {
8451                         LIST_REMOVE(dap, da_pdlist);
8452                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8453                             dap, da_pdlist);
8454                 }
8455         }
8456 done:
8457         if (jmvref) {
8458                 jmvref->jm_pagedep = pagedep;
8459                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8460                 add_to_journal(&jmvref->jm_list);
8461         }
8462         bcopy(oldloc, newloc, entrysize);
8463         FREE_LOCK(&lk);
8464 }
8465
8466 /*
8467  * Move the mkdir dependencies and journal work from one diradd to another
8468  * when renaming a directory.  The new name must depend on the mkdir deps
8469  * completing as the old name did.  Directories can only have one valid link
8470  * at a time so one must be canonical.
8471  */
8472 static void
8473 merge_diradd(inodedep, newdap)
8474         struct inodedep *inodedep;
8475         struct diradd *newdap;
8476 {
8477         struct diradd *olddap;
8478         struct mkdir *mkdir, *nextmd;
8479         short state;
8480
8481         olddap = inodedep->id_mkdiradd;
8482         inodedep->id_mkdiradd = newdap;
8483         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8484                 newdap->da_state &= ~DEPCOMPLETE;
8485                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8486                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8487                         if (mkdir->md_diradd != olddap)
8488                                 continue;
8489                         mkdir->md_diradd = newdap;
8490                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8491                         newdap->da_state |= state;
8492                         olddap->da_state &= ~state;
8493                         if ((olddap->da_state &
8494                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8495                                 break;
8496                 }
8497                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8498                         panic("merge_diradd: unfound ref");
8499         }
8500         /*
8501          * Any mkdir related journal items are not safe to be freed until
8502          * the new name is stable.
8503          */
8504         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8505         olddap->da_state |= DEPCOMPLETE;
8506         complete_diradd(olddap);
8507 }
8508
8509 /*
8510  * Move the diradd to the pending list when all diradd dependencies are
8511  * complete.
8512  */
8513 static void
8514 complete_diradd(dap)
8515         struct diradd *dap;
8516 {
8517         struct pagedep *pagedep;
8518
8519         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8520                 if (dap->da_state & DIRCHG)
8521                         pagedep = dap->da_previous->dm_pagedep;
8522                 else
8523                         pagedep = dap->da_pagedep;
8524                 LIST_REMOVE(dap, da_pdlist);
8525                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8526         }
8527 }
8528
8529 /*
8530  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8531  * add entries and conditonally journal the remove.
8532  */
8533 static void
8534 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8535         struct diradd *dap;
8536         struct dirrem *dirrem;
8537         struct jremref *jremref;
8538         struct jremref *dotremref;
8539         struct jremref *dotdotremref;
8540 {
8541         struct inodedep *inodedep;
8542         struct jaddref *jaddref;
8543         struct inoref *inoref;
8544         struct mkdir *mkdir;
8545
8546         /*
8547          * If no remove references were allocated we're on a non-journaled
8548          * filesystem and can skip the cancel step.
8549          */
8550         if (jremref == NULL) {
8551                 free_diradd(dap, NULL);
8552                 return;
8553         }
8554         /*
8555          * Cancel the primary name an free it if it does not require
8556          * journaling.
8557          */
8558         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8559             0, &inodedep) != 0) {
8560                 /* Abort the addref that reference this diradd.  */
8561                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8562                         if (inoref->if_list.wk_type != D_JADDREF)
8563                                 continue;
8564                         jaddref = (struct jaddref *)inoref;
8565                         if (jaddref->ja_diradd != dap)
8566                                 continue;
8567                         if (cancel_jaddref(jaddref, inodedep,
8568                             &dirrem->dm_jwork) == 0) {
8569                                 free_jremref(jremref);
8570                                 jremref = NULL;
8571                         }
8572                         break;
8573                 }
8574         }
8575         /*
8576          * Cancel subordinate names and free them if they do not require
8577          * journaling.
8578          */
8579         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8580                 LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
8581                         if (mkdir->md_diradd != dap)
8582                                 continue;
8583                         if ((jaddref = mkdir->md_jaddref) == NULL)
8584                                 continue;
8585                         mkdir->md_jaddref = NULL;
8586                         if (mkdir->md_state & MKDIR_PARENT) {
8587                                 if (cancel_jaddref(jaddref, NULL,
8588                                     &dirrem->dm_jwork) == 0) {
8589                                         free_jremref(dotdotremref);
8590                                         dotdotremref = NULL;
8591                                 }
8592                         } else {
8593                                 if (cancel_jaddref(jaddref, inodedep,
8594                                     &dirrem->dm_jwork) == 0) {
8595                                         free_jremref(dotremref);
8596                                         dotremref = NULL;
8597                                 }
8598                         }
8599                 }
8600         }
8601
8602         if (jremref)
8603                 journal_jremref(dirrem, jremref, inodedep);
8604         if (dotremref)
8605                 journal_jremref(dirrem, dotremref, inodedep);
8606         if (dotdotremref)
8607                 journal_jremref(dirrem, dotdotremref, NULL);
8608         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8609         free_diradd(dap, &dirrem->dm_jwork);
8610 }
8611
8612 /*
8613  * Free a diradd dependency structure. This routine must be called
8614  * with splbio interrupts blocked.
8615  */
8616 static void
8617 free_diradd(dap, wkhd)
8618         struct diradd *dap;
8619         struct workhead *wkhd;
8620 {
8621         struct dirrem *dirrem;
8622         struct pagedep *pagedep;
8623         struct inodedep *inodedep;
8624         struct mkdir *mkdir, *nextmd;
8625
8626         mtx_assert(&lk, MA_OWNED);
8627         LIST_REMOVE(dap, da_pdlist);
8628         if (dap->da_state & ONWORKLIST)
8629                 WORKLIST_REMOVE(&dap->da_list);
8630         if ((dap->da_state & DIRCHG) == 0) {
8631                 pagedep = dap->da_pagedep;
8632         } else {
8633                 dirrem = dap->da_previous;
8634                 pagedep = dirrem->dm_pagedep;
8635                 dirrem->dm_dirinum = pagedep->pd_ino;
8636                 dirrem->dm_state |= COMPLETE;
8637                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8638                         add_to_worklist(&dirrem->dm_list, 0);
8639         }
8640         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8641             0, &inodedep) != 0)
8642                 if (inodedep->id_mkdiradd == dap)
8643                         inodedep->id_mkdiradd = NULL;
8644         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8645                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8646                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8647                         if (mkdir->md_diradd != dap)
8648                                 continue;
8649                         dap->da_state &=
8650                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8651                         LIST_REMOVE(mkdir, md_mkdirs);
8652                         if (mkdir->md_state & ONWORKLIST)
8653                                 WORKLIST_REMOVE(&mkdir->md_list);
8654                         if (mkdir->md_jaddref != NULL)
8655                                 panic("free_diradd: Unexpected jaddref");
8656                         WORKITEM_FREE(mkdir, D_MKDIR);
8657                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8658                                 break;
8659                 }
8660                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8661                         panic("free_diradd: unfound ref");
8662         }
8663         if (inodedep)
8664                 free_inodedep(inodedep);
8665         /*
8666          * Free any journal segments waiting for the directory write.
8667          */
8668         handle_jwork(&dap->da_jwork);
8669         WORKITEM_FREE(dap, D_DIRADD);
8670 }
8671
8672 /*
8673  * Directory entry removal dependencies.
8674  * 
8675  * When removing a directory entry, the entry's inode pointer must be
8676  * zero'ed on disk before the corresponding inode's link count is decremented
8677  * (possibly freeing the inode for re-use). This dependency is handled by
8678  * updating the directory entry but delaying the inode count reduction until
8679  * after the directory block has been written to disk. After this point, the
8680  * inode count can be decremented whenever it is convenient.
8681  */
8682
8683 /*
8684  * This routine should be called immediately after removing
8685  * a directory entry.  The inode's link count should not be
8686  * decremented by the calling procedure -- the soft updates
8687  * code will do this task when it is safe.
8688  */
8689 void 
8690 softdep_setup_remove(bp, dp, ip, isrmdir)
8691         struct buf *bp;         /* buffer containing directory block */
8692         struct inode *dp;       /* inode for the directory being modified */
8693         struct inode *ip;       /* inode for directory entry being removed */
8694         int isrmdir;            /* indicates if doing RMDIR */
8695 {
8696         struct dirrem *dirrem, *prevdirrem;
8697         struct inodedep *inodedep;
8698         int direct;
8699
8700         /*
8701          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8702          * newdirrem() to setup the full directory remove which requires
8703          * isrmdir > 1.
8704          */
8705         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8706         /*
8707          * Add the dirrem to the inodedep's pending remove list for quick
8708          * discovery later.
8709          */
8710         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8711             &inodedep) == 0)
8712                 panic("softdep_setup_remove: Lost inodedep.");
8713         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8714         dirrem->dm_state |= ONDEPLIST;
8715         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8716
8717         /*
8718          * If the COMPLETE flag is clear, then there were no active
8719          * entries and we want to roll back to a zeroed entry until
8720          * the new inode is committed to disk. If the COMPLETE flag is
8721          * set then we have deleted an entry that never made it to
8722          * disk. If the entry we deleted resulted from a name change,
8723          * then the old name still resides on disk. We cannot delete
8724          * its inode (returned to us in prevdirrem) until the zeroed
8725          * directory entry gets to disk. The new inode has never been
8726          * referenced on the disk, so can be deleted immediately.
8727          */
8728         if ((dirrem->dm_state & COMPLETE) == 0) {
8729                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8730                     dm_next);
8731                 FREE_LOCK(&lk);
8732         } else {
8733                 if (prevdirrem != NULL)
8734                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8735                             prevdirrem, dm_next);
8736                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8737                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8738                 FREE_LOCK(&lk);
8739                 if (direct)
8740                         handle_workitem_remove(dirrem, 0);
8741         }
8742 }
8743
8744 /*
8745  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8746  * pd_pendinghd list of a pagedep.
8747  */
8748 static struct diradd *
8749 diradd_lookup(pagedep, offset)
8750         struct pagedep *pagedep;
8751         int offset;
8752 {
8753         struct diradd *dap;
8754
8755         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8756                 if (dap->da_offset == offset)
8757                         return (dap);
8758         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8759                 if (dap->da_offset == offset)
8760                         return (dap);
8761         return (NULL);
8762 }
8763
8764 /*
8765  * Search for a .. diradd dependency in a directory that is being removed.
8766  * If the directory was renamed to a new parent we have a diradd rather
8767  * than a mkdir for the .. entry.  We need to cancel it now before
8768  * it is found in truncate().
8769  */
8770 static struct jremref *
8771 cancel_diradd_dotdot(ip, dirrem, jremref)
8772         struct inode *ip;
8773         struct dirrem *dirrem;
8774         struct jremref *jremref;
8775 {
8776         struct pagedep *pagedep;
8777         struct diradd *dap;
8778         struct worklist *wk;
8779
8780         if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8781             &pagedep) == 0)
8782                 return (jremref);
8783         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8784         if (dap == NULL)
8785                 return (jremref);
8786         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8787         /*
8788          * Mark any journal work as belonging to the parent so it is freed
8789          * with the .. reference.
8790          */
8791         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8792                 wk->wk_state |= MKDIR_PARENT;
8793         return (NULL);
8794 }
8795
8796 /*
8797  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8798  * replace it with a dirrem/diradd pair as a result of re-parenting a
8799  * directory.  This ensures that we don't simultaneously have a mkdir and
8800  * a diradd for the same .. entry.
8801  */
8802 static struct jremref *
8803 cancel_mkdir_dotdot(ip, dirrem, jremref)
8804         struct inode *ip;
8805         struct dirrem *dirrem;
8806         struct jremref *jremref;
8807 {
8808         struct inodedep *inodedep;
8809         struct jaddref *jaddref;
8810         struct mkdir *mkdir;
8811         struct diradd *dap;
8812
8813         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8814             &inodedep) == 0)
8815                 return (jremref);
8816         dap = inodedep->id_mkdiradd;
8817         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
8818                 return (jremref);
8819         for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir;
8820             mkdir = LIST_NEXT(mkdir, md_mkdirs))
8821                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
8822                         break;
8823         if (mkdir == NULL)
8824                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
8825         if ((jaddref = mkdir->md_jaddref) != NULL) {
8826                 mkdir->md_jaddref = NULL;
8827                 jaddref->ja_state &= ~MKDIR_PARENT;
8828                 if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
8829                     &inodedep) == 0)
8830                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
8831                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
8832                         journal_jremref(dirrem, jremref, inodedep);
8833                         jremref = NULL;
8834                 }
8835         }
8836         if (mkdir->md_state & ONWORKLIST)
8837                 WORKLIST_REMOVE(&mkdir->md_list);
8838         mkdir->md_state |= ALLCOMPLETE;
8839         complete_mkdir(mkdir);
8840         return (jremref);
8841 }
8842
8843 static void
8844 journal_jremref(dirrem, jremref, inodedep)
8845         struct dirrem *dirrem;
8846         struct jremref *jremref;
8847         struct inodedep *inodedep;
8848 {
8849
8850         if (inodedep == NULL)
8851                 if (inodedep_lookup(jremref->jr_list.wk_mp,
8852                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
8853                         panic("journal_jremref: Lost inodedep");
8854         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
8855         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
8856         add_to_journal(&jremref->jr_list);
8857 }
8858
8859 static void
8860 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
8861         struct dirrem *dirrem;
8862         struct jremref *jremref;
8863         struct jremref *dotremref;
8864         struct jremref *dotdotremref;
8865 {
8866         struct inodedep *inodedep;
8867
8868
8869         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
8870             &inodedep) == 0)
8871                 panic("dirrem_journal: Lost inodedep");
8872         journal_jremref(dirrem, jremref, inodedep);
8873         if (dotremref)
8874                 journal_jremref(dirrem, dotremref, inodedep);
8875         if (dotdotremref)
8876                 journal_jremref(dirrem, dotdotremref, NULL);
8877 }
8878
8879 /*
8880  * Allocate a new dirrem if appropriate and return it along with
8881  * its associated pagedep. Called without a lock, returns with lock.
8882  */
8883 static struct dirrem *
8884 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
8885         struct buf *bp;         /* buffer containing directory block */
8886         struct inode *dp;       /* inode for the directory being modified */
8887         struct inode *ip;       /* inode for directory entry being removed */
8888         int isrmdir;            /* indicates if doing RMDIR */
8889         struct dirrem **prevdirremp; /* previously referenced inode, if any */
8890 {
8891         int offset;
8892         ufs_lbn_t lbn;
8893         struct diradd *dap;
8894         struct dirrem *dirrem;
8895         struct pagedep *pagedep;
8896         struct jremref *jremref;
8897         struct jremref *dotremref;
8898         struct jremref *dotdotremref;
8899         struct vnode *dvp;
8900
8901         /*
8902          * Whiteouts have no deletion dependencies.
8903          */
8904         if (ip == NULL)
8905                 panic("newdirrem: whiteout");
8906         dvp = ITOV(dp);
8907         /*
8908          * If we are over our limit, try to improve the situation.
8909          * Limiting the number of dirrem structures will also limit
8910          * the number of freefile and freeblks structures.
8911          */
8912         ACQUIRE_LOCK(&lk);
8913         if (!IS_SNAPSHOT(ip) && dep_current[D_DIRREM] > max_softdeps / 2)
8914                 (void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
8915         FREE_LOCK(&lk);
8916         dirrem = malloc(sizeof(struct dirrem),
8917                 M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
8918         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
8919         LIST_INIT(&dirrem->dm_jremrefhd);
8920         LIST_INIT(&dirrem->dm_jwork);
8921         dirrem->dm_state = isrmdir ? RMDIR : 0;
8922         dirrem->dm_oldinum = ip->i_number;
8923         *prevdirremp = NULL;
8924         /*
8925          * Allocate remove reference structures to track journal write
8926          * dependencies.  We will always have one for the link and
8927          * when doing directories we will always have one more for dot.
8928          * When renaming a directory we skip the dotdot link change so
8929          * this is not needed.
8930          */
8931         jremref = dotremref = dotdotremref = NULL;
8932         if (DOINGSUJ(dvp)) {
8933                 if (isrmdir) {
8934                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8935                             ip->i_effnlink + 2);
8936                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
8937                             ip->i_effnlink + 1);
8938                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
8939                             dp->i_effnlink + 1);
8940                         dotdotremref->jr_state |= MKDIR_PARENT;
8941                 } else
8942                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8943                             ip->i_effnlink + 1);
8944         }
8945         ACQUIRE_LOCK(&lk);
8946         lbn = lblkno(dp->i_fs, dp->i_offset);
8947         offset = blkoff(dp->i_fs, dp->i_offset);
8948         pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
8949             &pagedep);
8950         dirrem->dm_pagedep = pagedep;
8951         dirrem->dm_offset = offset;
8952         /*
8953          * If we're renaming a .. link to a new directory, cancel any
8954          * existing MKDIR_PARENT mkdir.  If it has already been canceled
8955          * the jremref is preserved for any potential diradd in this
8956          * location.  This can not coincide with a rmdir.
8957          */
8958         if (dp->i_offset == DOTDOT_OFFSET) {
8959                 if (isrmdir)
8960                         panic("newdirrem: .. directory change during remove?");
8961                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
8962         }
8963         /*
8964          * If we're removing a directory search for the .. dependency now and
8965          * cancel it.  Any pending journal work will be added to the dirrem
8966          * to be completed when the workitem remove completes.
8967          */
8968         if (isrmdir)
8969                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
8970         /*
8971          * Check for a diradd dependency for the same directory entry.
8972          * If present, then both dependencies become obsolete and can
8973          * be de-allocated.
8974          */
8975         dap = diradd_lookup(pagedep, offset);
8976         if (dap == NULL) {
8977                 /*
8978                  * Link the jremref structures into the dirrem so they are
8979                  * written prior to the pagedep.
8980                  */
8981                 if (jremref)
8982                         dirrem_journal(dirrem, jremref, dotremref,
8983                             dotdotremref);
8984                 return (dirrem);
8985         }
8986         /*
8987          * Must be ATTACHED at this point.
8988          */
8989         if ((dap->da_state & ATTACHED) == 0)
8990                 panic("newdirrem: not ATTACHED");
8991         if (dap->da_newinum != ip->i_number)
8992                 panic("newdirrem: inum %d should be %d",
8993                     ip->i_number, dap->da_newinum);
8994         /*
8995          * If we are deleting a changed name that never made it to disk,
8996          * then return the dirrem describing the previous inode (which
8997          * represents the inode currently referenced from this entry on disk).
8998          */
8999         if ((dap->da_state & DIRCHG) != 0) {
9000                 *prevdirremp = dap->da_previous;
9001                 dap->da_state &= ~DIRCHG;
9002                 dap->da_pagedep = pagedep;
9003         }
9004         /*
9005          * We are deleting an entry that never made it to disk.
9006          * Mark it COMPLETE so we can delete its inode immediately.
9007          */
9008         dirrem->dm_state |= COMPLETE;
9009         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9010 #ifdef SUJ_DEBUG
9011         if (isrmdir == 0) {
9012                 struct worklist *wk;
9013
9014                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9015                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9016                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9017         }
9018 #endif
9019
9020         return (dirrem);
9021 }
9022
9023 /*
9024  * Directory entry change dependencies.
9025  * 
9026  * Changing an existing directory entry requires that an add operation
9027  * be completed first followed by a deletion. The semantics for the addition
9028  * are identical to the description of adding a new entry above except
9029  * that the rollback is to the old inode number rather than zero. Once
9030  * the addition dependency is completed, the removal is done as described
9031  * in the removal routine above.
9032  */
9033
9034 /*
9035  * This routine should be called immediately after changing
9036  * a directory entry.  The inode's link count should not be
9037  * decremented by the calling procedure -- the soft updates
9038  * code will perform this task when it is safe.
9039  */
9040 void 
9041 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9042         struct buf *bp;         /* buffer containing directory block */
9043         struct inode *dp;       /* inode for the directory being modified */
9044         struct inode *ip;       /* inode for directory entry being removed */
9045         ino_t newinum;          /* new inode number for changed entry */
9046         int isrmdir;            /* indicates if doing RMDIR */
9047 {
9048         int offset;
9049         struct diradd *dap = NULL;
9050         struct dirrem *dirrem, *prevdirrem;
9051         struct pagedep *pagedep;
9052         struct inodedep *inodedep;
9053         struct jaddref *jaddref;
9054         struct mount *mp;
9055
9056         offset = blkoff(dp->i_fs, dp->i_offset);
9057         mp = UFSTOVFS(dp->i_ump);
9058
9059         /*
9060          * Whiteouts do not need diradd dependencies.
9061          */
9062         if (newinum != WINO) {
9063                 dap = malloc(sizeof(struct diradd),
9064                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9065                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9066                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9067                 dap->da_offset = offset;
9068                 dap->da_newinum = newinum;
9069                 LIST_INIT(&dap->da_jwork);
9070         }
9071
9072         /*
9073          * Allocate a new dirrem and ACQUIRE_LOCK.
9074          */
9075         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9076         pagedep = dirrem->dm_pagedep;
9077         /*
9078          * The possible values for isrmdir:
9079          *      0 - non-directory file rename
9080          *      1 - directory rename within same directory
9081          *   inum - directory rename to new directory of given inode number
9082          * When renaming to a new directory, we are both deleting and
9083          * creating a new directory entry, so the link count on the new
9084          * directory should not change. Thus we do not need the followup
9085          * dirrem which is usually done in handle_workitem_remove. We set
9086          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9087          * followup dirrem.
9088          */
9089         if (isrmdir > 1)
9090                 dirrem->dm_state |= DIRCHG;
9091
9092         /*
9093          * Whiteouts have no additional dependencies,
9094          * so just put the dirrem on the correct list.
9095          */
9096         if (newinum == WINO) {
9097                 if ((dirrem->dm_state & COMPLETE) == 0) {
9098                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9099                             dm_next);
9100                 } else {
9101                         dirrem->dm_dirinum = pagedep->pd_ino;
9102                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9103                                 add_to_worklist(&dirrem->dm_list, 0);
9104                 }
9105                 FREE_LOCK(&lk);
9106                 return;
9107         }
9108         /*
9109          * Add the dirrem to the inodedep's pending remove list for quick
9110          * discovery later.  A valid nlinkdelta ensures that this lookup
9111          * will not fail.
9112          */
9113         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9114                 panic("softdep_setup_directory_change: Lost inodedep.");
9115         dirrem->dm_state |= ONDEPLIST;
9116         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9117
9118         /*
9119          * If the COMPLETE flag is clear, then there were no active
9120          * entries and we want to roll back to the previous inode until
9121          * the new inode is committed to disk. If the COMPLETE flag is
9122          * set, then we have deleted an entry that never made it to disk.
9123          * If the entry we deleted resulted from a name change, then the old
9124          * inode reference still resides on disk. Any rollback that we do
9125          * needs to be to that old inode (returned to us in prevdirrem). If
9126          * the entry we deleted resulted from a create, then there is
9127          * no entry on the disk, so we want to roll back to zero rather
9128          * than the uncommitted inode. In either of the COMPLETE cases we
9129          * want to immediately free the unwritten and unreferenced inode.
9130          */
9131         if ((dirrem->dm_state & COMPLETE) == 0) {
9132                 dap->da_previous = dirrem;
9133         } else {
9134                 if (prevdirrem != NULL) {
9135                         dap->da_previous = prevdirrem;
9136                 } else {
9137                         dap->da_state &= ~DIRCHG;
9138                         dap->da_pagedep = pagedep;
9139                 }
9140                 dirrem->dm_dirinum = pagedep->pd_ino;
9141                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9142                         add_to_worklist(&dirrem->dm_list, 0);
9143         }
9144         /*
9145          * Lookup the jaddref for this journal entry.  We must finish
9146          * initializing it and make the diradd write dependent on it.
9147          * If we're not journaling, put it on the id_bufwait list if the
9148          * inode is not yet written. If it is written, do the post-inode
9149          * write processing to put it on the id_pendinghd list.
9150          */
9151         inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
9152         if (MOUNTEDSUJ(mp)) {
9153                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9154                     inoreflst);
9155                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9156                     ("softdep_setup_directory_change: bad jaddref %p",
9157                     jaddref));
9158                 jaddref->ja_diroff = dp->i_offset;
9159                 jaddref->ja_diradd = dap;
9160                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9161                     dap, da_pdlist);
9162                 add_to_journal(&jaddref->ja_list);
9163         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9164                 dap->da_state |= COMPLETE;
9165                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9166                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9167         } else {
9168                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9169                     dap, da_pdlist);
9170                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9171         }
9172         /*
9173          * If we're making a new name for a directory that has not been
9174          * committed when need to move the dot and dotdot references to
9175          * this new name.
9176          */
9177         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9178                 merge_diradd(inodedep, dap);
9179         FREE_LOCK(&lk);
9180 }
9181
9182 /*
9183  * Called whenever the link count on an inode is changed.
9184  * It creates an inode dependency so that the new reference(s)
9185  * to the inode cannot be committed to disk until the updated
9186  * inode has been written.
9187  */
9188 void
9189 softdep_change_linkcnt(ip)
9190         struct inode *ip;       /* the inode with the increased link count */
9191 {
9192         struct inodedep *inodedep;
9193         int dflags;
9194
9195         ACQUIRE_LOCK(&lk);
9196         dflags = DEPALLOC;
9197         if (IS_SNAPSHOT(ip))
9198                 dflags |= NODELAY;
9199         inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
9200         if (ip->i_nlink < ip->i_effnlink)
9201                 panic("softdep_change_linkcnt: bad delta");
9202         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9203         FREE_LOCK(&lk);
9204 }
9205
9206 /*
9207  * Attach a sbdep dependency to the superblock buf so that we can keep
9208  * track of the head of the linked list of referenced but unlinked inodes.
9209  */
9210 void
9211 softdep_setup_sbupdate(ump, fs, bp)
9212         struct ufsmount *ump;
9213         struct fs *fs;
9214         struct buf *bp;
9215 {
9216         struct sbdep *sbdep;
9217         struct worklist *wk;
9218
9219         if (MOUNTEDSUJ(UFSTOVFS(ump)) == 0)
9220                 return;
9221         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9222                 if (wk->wk_type == D_SBDEP)
9223                         break;
9224         if (wk != NULL)
9225                 return;
9226         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9227         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9228         sbdep->sb_fs = fs;
9229         sbdep->sb_ump = ump;
9230         ACQUIRE_LOCK(&lk);
9231         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9232         FREE_LOCK(&lk);
9233 }
9234
9235 /*
9236  * Return the first unlinked inodedep which is ready to be the head of the
9237  * list.  The inodedep and all those after it must have valid next pointers.
9238  */
9239 static struct inodedep *
9240 first_unlinked_inodedep(ump)
9241         struct ufsmount *ump;
9242 {
9243         struct inodedep *inodedep;
9244         struct inodedep *idp;
9245
9246         mtx_assert(&lk, MA_OWNED);
9247         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9248             inodedep; inodedep = idp) {
9249                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9250                         return (NULL);
9251                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9252                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9253                         break;
9254                 if ((inodedep->id_state & UNLINKPREV) == 0)
9255                         break;
9256         }
9257         return (inodedep);
9258 }
9259
9260 /*
9261  * Set the sujfree unlinked head pointer prior to writing a superblock.
9262  */
9263 static void
9264 initiate_write_sbdep(sbdep)
9265         struct sbdep *sbdep;
9266 {
9267         struct inodedep *inodedep;
9268         struct fs *bpfs;
9269         struct fs *fs;
9270
9271         bpfs = sbdep->sb_fs;
9272         fs = sbdep->sb_ump->um_fs;
9273         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9274         if (inodedep) {
9275                 fs->fs_sujfree = inodedep->id_ino;
9276                 inodedep->id_state |= UNLINKPREV;
9277         } else
9278                 fs->fs_sujfree = 0;
9279         bpfs->fs_sujfree = fs->fs_sujfree;
9280 }
9281
9282 /*
9283  * After a superblock is written determine whether it must be written again
9284  * due to a changing unlinked list head.
9285  */
9286 static int
9287 handle_written_sbdep(sbdep, bp)
9288         struct sbdep *sbdep;
9289         struct buf *bp;
9290 {
9291         struct inodedep *inodedep;
9292         struct mount *mp;
9293         struct fs *fs;
9294
9295         mtx_assert(&lk, MA_OWNED);
9296         fs = sbdep->sb_fs;
9297         mp = UFSTOVFS(sbdep->sb_ump);
9298         /*
9299          * If the superblock doesn't match the in-memory list start over.
9300          */
9301         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9302         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9303             (inodedep == NULL && fs->fs_sujfree != 0)) {
9304                 bdirty(bp);
9305                 return (1);
9306         }
9307         WORKITEM_FREE(sbdep, D_SBDEP);
9308         if (fs->fs_sujfree == 0)
9309                 return (0);
9310         /*
9311          * Now that we have a record of this inode in stable store allow it
9312          * to be written to free up pending work.  Inodes may see a lot of
9313          * write activity after they are unlinked which we must not hold up.
9314          */
9315         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9316                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9317                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9318                             inodedep, inodedep->id_state);
9319                 if (inodedep->id_state & UNLINKONLIST)
9320                         break;
9321                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9322         }
9323
9324         return (0);
9325 }
9326
9327 /*
9328  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9329  */
9330 static void
9331 unlinked_inodedep(mp, inodedep)
9332         struct mount *mp;
9333         struct inodedep *inodedep;
9334 {
9335         struct ufsmount *ump;
9336
9337         mtx_assert(&lk, MA_OWNED);
9338         if (MOUNTEDSUJ(mp) == 0)
9339                 return;
9340         ump = VFSTOUFS(mp);
9341         ump->um_fs->fs_fmod = 1;
9342         if (inodedep->id_state & UNLINKED)
9343                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9344         inodedep->id_state |= UNLINKED;
9345         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9346 }
9347
9348 /*
9349  * Remove an inodedep from the unlinked inodedep list.  This may require
9350  * disk writes if the inode has made it that far.
9351  */
9352 static void
9353 clear_unlinked_inodedep(inodedep)
9354         struct inodedep *inodedep;
9355 {
9356         struct ufsmount *ump;
9357         struct inodedep *idp;
9358         struct inodedep *idn;
9359         struct fs *fs;
9360         struct buf *bp;
9361         ino_t ino;
9362         ino_t nino;
9363         ino_t pino;
9364         int error;
9365
9366         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9367         fs = ump->um_fs;
9368         ino = inodedep->id_ino;
9369         error = 0;
9370         for (;;) {
9371                 mtx_assert(&lk, MA_OWNED);
9372                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9373                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9374                     inodedep));
9375                 /*
9376                  * If nothing has yet been written simply remove us from
9377                  * the in memory list and return.  This is the most common
9378                  * case where handle_workitem_remove() loses the final
9379                  * reference.
9380                  */
9381                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9382                         break;
9383                 /*
9384                  * If we have a NEXT pointer and no PREV pointer we can simply
9385                  * clear NEXT's PREV and remove ourselves from the list.  Be
9386                  * careful not to clear PREV if the superblock points at
9387                  * next as well.
9388                  */
9389                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9390                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9391                         if (idn && fs->fs_sujfree != idn->id_ino)
9392                                 idn->id_state &= ~UNLINKPREV;
9393                         break;
9394                 }
9395                 /*
9396                  * Here we have an inodedep which is actually linked into
9397                  * the list.  We must remove it by forcing a write to the
9398                  * link before us, whether it be the superblock or an inode.
9399                  * Unfortunately the list may change while we're waiting
9400                  * on the buf lock for either resource so we must loop until
9401                  * we lock the right one.  If both the superblock and an
9402                  * inode point to this inode we must clear the inode first
9403                  * followed by the superblock.
9404                  */
9405                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9406                 pino = 0;
9407                 if (idp && (idp->id_state & UNLINKNEXT))
9408                         pino = idp->id_ino;
9409                 FREE_LOCK(&lk);
9410                 if (pino == 0) {
9411                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9412                             (int)fs->fs_sbsize, 0, 0, 0);
9413                 } else {
9414                         error = bread(ump->um_devvp,
9415                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9416                             (int)fs->fs_bsize, NOCRED, &bp);
9417                         if (error)
9418                                 brelse(bp);
9419                 }
9420                 ACQUIRE_LOCK(&lk);
9421                 if (error)
9422                         break;
9423                 /* If the list has changed restart the loop. */
9424                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9425                 nino = 0;
9426                 if (idp && (idp->id_state & UNLINKNEXT))
9427                         nino = idp->id_ino;
9428                 if (nino != pino ||
9429                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9430                         FREE_LOCK(&lk);
9431                         brelse(bp);
9432                         ACQUIRE_LOCK(&lk);
9433                         continue;
9434                 }
9435                 nino = 0;
9436                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9437                 if (idn)
9438                         nino = idn->id_ino;
9439                 /*
9440                  * Remove us from the in memory list.  After this we cannot
9441                  * access the inodedep.
9442                  */
9443                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9444                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9445                     inodedep));
9446                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9447                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9448                 FREE_LOCK(&lk);
9449                 /*
9450                  * The predecessor's next pointer is manually updated here
9451                  * so that the NEXT flag is never cleared for an element
9452                  * that is in the list.
9453                  */
9454                 if (pino == 0) {
9455                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9456                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9457                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9458                             bp);
9459                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9460                         ((struct ufs1_dinode *)bp->b_data +
9461                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9462                 else
9463                         ((struct ufs2_dinode *)bp->b_data +
9464                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9465                 /*
9466                  * If the bwrite fails we have no recourse to recover.  The
9467                  * filesystem is corrupted already.
9468                  */
9469                 bwrite(bp);
9470                 ACQUIRE_LOCK(&lk);
9471                 /*
9472                  * If the superblock pointer still needs to be cleared force
9473                  * a write here.
9474                  */
9475                 if (fs->fs_sujfree == ino) {
9476                         FREE_LOCK(&lk);
9477                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9478                             (int)fs->fs_sbsize, 0, 0, 0);
9479                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9480                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9481                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9482                             bp);
9483                         bwrite(bp);
9484                         ACQUIRE_LOCK(&lk);
9485                 }
9486
9487                 if (fs->fs_sujfree != ino)
9488                         return;
9489                 panic("clear_unlinked_inodedep: Failed to clear free head");
9490         }
9491         if (inodedep->id_ino == fs->fs_sujfree)
9492                 panic("clear_unlinked_inodedep: Freeing head of free list");
9493         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9494         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9495         return;
9496 }
9497
9498 /*
9499  * This workitem decrements the inode's link count.
9500  * If the link count reaches zero, the file is removed.
9501  */
9502 static int
9503 handle_workitem_remove(dirrem, flags)
9504         struct dirrem *dirrem;
9505         int flags;
9506 {
9507         struct inodedep *inodedep;
9508         struct workhead dotdotwk;
9509         struct worklist *wk;
9510         struct ufsmount *ump;
9511         struct mount *mp;
9512         struct vnode *vp;
9513         struct inode *ip;
9514         ino_t oldinum;
9515
9516         if (dirrem->dm_state & ONWORKLIST)
9517                 panic("handle_workitem_remove: dirrem %p still on worklist",
9518                     dirrem);
9519         oldinum = dirrem->dm_oldinum;
9520         mp = dirrem->dm_list.wk_mp;
9521         ump = VFSTOUFS(mp);
9522         flags |= LK_EXCLUSIVE;
9523         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9524                 return (EBUSY);
9525         ip = VTOI(vp);
9526         ACQUIRE_LOCK(&lk);
9527         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9528                 panic("handle_workitem_remove: lost inodedep");
9529         if (dirrem->dm_state & ONDEPLIST)
9530                 LIST_REMOVE(dirrem, dm_inonext);
9531         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9532             ("handle_workitem_remove:  Journal entries not written."));
9533
9534         /*
9535          * Move all dependencies waiting on the remove to complete
9536          * from the dirrem to the inode inowait list to be completed
9537          * after the inode has been updated and written to disk.  Any
9538          * marked MKDIR_PARENT are saved to be completed when the .. ref
9539          * is removed.
9540          */
9541         LIST_INIT(&dotdotwk);
9542         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9543                 WORKLIST_REMOVE(wk);
9544                 if (wk->wk_state & MKDIR_PARENT) {
9545                         wk->wk_state &= ~MKDIR_PARENT;
9546                         WORKLIST_INSERT(&dotdotwk, wk);
9547                         continue;
9548                 }
9549                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9550         }
9551         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9552         /*
9553          * Normal file deletion.
9554          */
9555         if ((dirrem->dm_state & RMDIR) == 0) {
9556                 ip->i_nlink--;
9557                 DIP_SET(ip, i_nlink, ip->i_nlink);
9558                 ip->i_flag |= IN_CHANGE;
9559                 if (ip->i_nlink < ip->i_effnlink)
9560                         panic("handle_workitem_remove: bad file delta");
9561                 if (ip->i_nlink == 0) 
9562                         unlinked_inodedep(mp, inodedep);
9563                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9564                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9565                     ("handle_workitem_remove: worklist not empty. %s",
9566                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9567                 WORKITEM_FREE(dirrem, D_DIRREM);
9568                 FREE_LOCK(&lk);
9569                 goto out;
9570         }
9571         /*
9572          * Directory deletion. Decrement reference count for both the
9573          * just deleted parent directory entry and the reference for ".".
9574          * Arrange to have the reference count on the parent decremented
9575          * to account for the loss of "..".
9576          */
9577         ip->i_nlink -= 2;
9578         DIP_SET(ip, i_nlink, ip->i_nlink);
9579         ip->i_flag |= IN_CHANGE;
9580         if (ip->i_nlink < ip->i_effnlink)
9581                 panic("handle_workitem_remove: bad dir delta");
9582         if (ip->i_nlink == 0)
9583                 unlinked_inodedep(mp, inodedep);
9584         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9585         /*
9586          * Rename a directory to a new parent. Since, we are both deleting
9587          * and creating a new directory entry, the link count on the new
9588          * directory should not change. Thus we skip the followup dirrem.
9589          */
9590         if (dirrem->dm_state & DIRCHG) {
9591                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9592                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9593                 WORKITEM_FREE(dirrem, D_DIRREM);
9594                 FREE_LOCK(&lk);
9595                 goto out;
9596         }
9597         dirrem->dm_state = ONDEPLIST;
9598         dirrem->dm_oldinum = dirrem->dm_dirinum;
9599         /*
9600          * Place the dirrem on the parent's diremhd list.
9601          */
9602         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9603                 panic("handle_workitem_remove: lost dir inodedep");
9604         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9605         /*
9606          * If the allocated inode has never been written to disk, then
9607          * the on-disk inode is zero'ed and we can remove the file
9608          * immediately.  When journaling if the inode has been marked
9609          * unlinked and not DEPCOMPLETE we know it can never be written.
9610          */
9611         inodedep_lookup(mp, oldinum, 0, &inodedep);
9612         if (inodedep == NULL ||
9613             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9614             check_inode_unwritten(inodedep)) {
9615                 FREE_LOCK(&lk);
9616                 vput(vp);
9617                 return handle_workitem_remove(dirrem, flags);
9618         }
9619         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9620         FREE_LOCK(&lk);
9621         ip->i_flag |= IN_CHANGE;
9622 out:
9623         ffs_update(vp, 0);
9624         vput(vp);
9625         return (0);
9626 }
9627
9628 /*
9629  * Inode de-allocation dependencies.
9630  * 
9631  * When an inode's link count is reduced to zero, it can be de-allocated. We
9632  * found it convenient to postpone de-allocation until after the inode is
9633  * written to disk with its new link count (zero).  At this point, all of the
9634  * on-disk inode's block pointers are nullified and, with careful dependency
9635  * list ordering, all dependencies related to the inode will be satisfied and
9636  * the corresponding dependency structures de-allocated.  So, if/when the
9637  * inode is reused, there will be no mixing of old dependencies with new
9638  * ones.  This artificial dependency is set up by the block de-allocation
9639  * procedure above (softdep_setup_freeblocks) and completed by the
9640  * following procedure.
9641  */
9642 static void 
9643 handle_workitem_freefile(freefile)
9644         struct freefile *freefile;
9645 {
9646         struct workhead wkhd;
9647         struct fs *fs;
9648         struct inodedep *idp;
9649         struct ufsmount *ump;
9650         int error;
9651
9652         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9653         fs = ump->um_fs;
9654 #ifdef DEBUG
9655         ACQUIRE_LOCK(&lk);
9656         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9657         FREE_LOCK(&lk);
9658         if (error)
9659                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9660 #endif
9661         UFS_LOCK(ump);
9662         fs->fs_pendinginodes -= 1;
9663         UFS_UNLOCK(ump);
9664         LIST_INIT(&wkhd);
9665         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9666         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9667             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9668                 softdep_error("handle_workitem_freefile", error);
9669         ACQUIRE_LOCK(&lk);
9670         WORKITEM_FREE(freefile, D_FREEFILE);
9671         FREE_LOCK(&lk);
9672 }
9673
9674
9675 /*
9676  * Helper function which unlinks marker element from work list and returns
9677  * the next element on the list.
9678  */
9679 static __inline struct worklist *
9680 markernext(struct worklist *marker)
9681 {
9682         struct worklist *next;
9683         
9684         next = LIST_NEXT(marker, wk_list);
9685         LIST_REMOVE(marker, wk_list);
9686         return next;
9687 }
9688
9689 /*
9690  * Disk writes.
9691  * 
9692  * The dependency structures constructed above are most actively used when file
9693  * system blocks are written to disk.  No constraints are placed on when a
9694  * block can be written, but unsatisfied update dependencies are made safe by
9695  * modifying (or replacing) the source memory for the duration of the disk
9696  * write.  When the disk write completes, the memory block is again brought
9697  * up-to-date.
9698  *
9699  * In-core inode structure reclamation.
9700  * 
9701  * Because there are a finite number of "in-core" inode structures, they are
9702  * reused regularly.  By transferring all inode-related dependencies to the
9703  * in-memory inode block and indexing them separately (via "inodedep"s), we
9704  * can allow "in-core" inode structures to be reused at any time and avoid
9705  * any increase in contention.
9706  *
9707  * Called just before entering the device driver to initiate a new disk I/O.
9708  * The buffer must be locked, thus, no I/O completion operations can occur
9709  * while we are manipulating its associated dependencies.
9710  */
9711 static void 
9712 softdep_disk_io_initiation(bp)
9713         struct buf *bp;         /* structure describing disk write to occur */
9714 {
9715         struct worklist *wk;
9716         struct worklist marker;
9717         struct inodedep *inodedep;
9718         struct freeblks *freeblks;
9719         struct jblkdep *jblkdep;
9720         struct newblk *newblk;
9721
9722         /*
9723          * We only care about write operations. There should never
9724          * be dependencies for reads.
9725          */
9726         if (bp->b_iocmd != BIO_WRITE)
9727                 panic("softdep_disk_io_initiation: not write");
9728
9729         if (bp->b_vflags & BV_BKGRDINPROG)
9730                 panic("softdep_disk_io_initiation: Writing buffer with "
9731                     "background write in progress: %p", bp);
9732
9733         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
9734         PHOLD(curproc);                 /* Don't swap out kernel stack */
9735
9736         ACQUIRE_LOCK(&lk);
9737         /*
9738          * Do any necessary pre-I/O processing.
9739          */
9740         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9741              wk = markernext(&marker)) {
9742                 LIST_INSERT_AFTER(wk, &marker, wk_list);
9743                 switch (wk->wk_type) {
9744
9745                 case D_PAGEDEP:
9746                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
9747                         continue;
9748
9749                 case D_INODEDEP:
9750                         inodedep = WK_INODEDEP(wk);
9751                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9752                                 initiate_write_inodeblock_ufs1(inodedep, bp);
9753                         else
9754                                 initiate_write_inodeblock_ufs2(inodedep, bp);
9755                         continue;
9756
9757                 case D_INDIRDEP:
9758                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9759                         continue;
9760
9761                 case D_BMSAFEMAP:
9762                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9763                         continue;
9764
9765                 case D_JSEG:
9766                         WK_JSEG(wk)->js_buf = NULL;
9767                         continue;
9768
9769                 case D_FREEBLKS:
9770                         freeblks = WK_FREEBLKS(wk);
9771                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9772                         /*
9773                          * We have to wait for the freeblks to be journaled
9774                          * before we can write an inodeblock with updated
9775                          * pointers.  Be careful to arrange the marker so
9776                          * we revisit the freeblks if it's not removed by
9777                          * the first jwait().
9778                          */
9779                         if (jblkdep != NULL) {
9780                                 LIST_REMOVE(&marker, wk_list);
9781                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
9782                                 jwait(&jblkdep->jb_list, MNT_WAIT);
9783                         }
9784                         continue;
9785                 case D_ALLOCDIRECT:
9786                 case D_ALLOCINDIR:
9787                         /*
9788                          * We have to wait for the jnewblk to be journaled
9789                          * before we can write to a block if the contents
9790                          * may be confused with an earlier file's indirect
9791                          * at recovery time.  Handle the marker as described
9792                          * above.
9793                          */
9794                         newblk = WK_NEWBLK(wk);
9795                         if (newblk->nb_jnewblk != NULL &&
9796                             indirblk_lookup(newblk->nb_list.wk_mp,
9797                             newblk->nb_newblkno)) {
9798                                 LIST_REMOVE(&marker, wk_list);
9799                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
9800                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
9801                         }
9802                         continue;
9803
9804                 case D_SBDEP:
9805                         initiate_write_sbdep(WK_SBDEP(wk));
9806                         continue;
9807
9808                 case D_MKDIR:
9809                 case D_FREEWORK:
9810                 case D_FREEDEP:
9811                 case D_JSEGDEP:
9812                         continue;
9813
9814                 default:
9815                         panic("handle_disk_io_initiation: Unexpected type %s",
9816                             TYPENAME(wk->wk_type));
9817                         /* NOTREACHED */
9818                 }
9819         }
9820         FREE_LOCK(&lk);
9821         PRELE(curproc);                 /* Allow swapout of kernel stack */
9822 }
9823
9824 /*
9825  * Called from within the procedure above to deal with unsatisfied
9826  * allocation dependencies in a directory. The buffer must be locked,
9827  * thus, no I/O completion operations can occur while we are
9828  * manipulating its associated dependencies.
9829  */
9830 static void
9831 initiate_write_filepage(pagedep, bp)
9832         struct pagedep *pagedep;
9833         struct buf *bp;
9834 {
9835         struct jremref *jremref;
9836         struct jmvref *jmvref;
9837         struct dirrem *dirrem;
9838         struct diradd *dap;
9839         struct direct *ep;
9840         int i;
9841
9842         if (pagedep->pd_state & IOSTARTED) {
9843                 /*
9844                  * This can only happen if there is a driver that does not
9845                  * understand chaining. Here biodone will reissue the call
9846                  * to strategy for the incomplete buffers.
9847                  */
9848                 printf("initiate_write_filepage: already started\n");
9849                 return;
9850         }
9851         pagedep->pd_state |= IOSTARTED;
9852         /*
9853          * Wait for all journal remove dependencies to hit the disk.
9854          * We can not allow any potentially conflicting directory adds
9855          * to be visible before removes and rollback is too difficult.
9856          * lk may be dropped and re-acquired, however we hold the buf
9857          * locked so the dependency can not go away.
9858          */
9859         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
9860                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
9861                         jwait(&jremref->jr_list, MNT_WAIT);
9862         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
9863                 jwait(&jmvref->jm_list, MNT_WAIT);
9864         for (i = 0; i < DAHASHSZ; i++) {
9865                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
9866                         ep = (struct direct *)
9867                             ((char *)bp->b_data + dap->da_offset);
9868                         if (ep->d_ino != dap->da_newinum)
9869                                 panic("%s: dir inum %d != new %d",
9870                                     "initiate_write_filepage",
9871                                     ep->d_ino, dap->da_newinum);
9872                         if (dap->da_state & DIRCHG)
9873                                 ep->d_ino = dap->da_previous->dm_oldinum;
9874                         else
9875                                 ep->d_ino = 0;
9876                         dap->da_state &= ~ATTACHED;
9877                         dap->da_state |= UNDONE;
9878                 }
9879         }
9880 }
9881
9882 /*
9883  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
9884  * Note that any bug fixes made to this routine must be done in the
9885  * version found below.
9886  *
9887  * Called from within the procedure above to deal with unsatisfied
9888  * allocation dependencies in an inodeblock. The buffer must be
9889  * locked, thus, no I/O completion operations can occur while we
9890  * are manipulating its associated dependencies.
9891  */
9892 static void 
9893 initiate_write_inodeblock_ufs1(inodedep, bp)
9894         struct inodedep *inodedep;
9895         struct buf *bp;                 /* The inode block */
9896 {
9897         struct allocdirect *adp, *lastadp;
9898         struct ufs1_dinode *dp;
9899         struct ufs1_dinode *sip;
9900         struct inoref *inoref;
9901         struct fs *fs;
9902         ufs_lbn_t i;
9903 #ifdef INVARIANTS
9904         ufs_lbn_t prevlbn = 0;
9905 #endif
9906         int deplist;
9907
9908         if (inodedep->id_state & IOSTARTED)
9909                 panic("initiate_write_inodeblock_ufs1: already started");
9910         inodedep->id_state |= IOSTARTED;
9911         fs = inodedep->id_fs;
9912         dp = (struct ufs1_dinode *)bp->b_data +
9913             ino_to_fsbo(fs, inodedep->id_ino);
9914
9915         /*
9916          * If we're on the unlinked list but have not yet written our
9917          * next pointer initialize it here.
9918          */
9919         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9920                 struct inodedep *inon;
9921
9922                 inon = TAILQ_NEXT(inodedep, id_unlinked);
9923                 dp->di_freelink = inon ? inon->id_ino : 0;
9924         }
9925         /*
9926          * If the bitmap is not yet written, then the allocated
9927          * inode cannot be written to disk.
9928          */
9929         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9930                 if (inodedep->id_savedino1 != NULL)
9931                         panic("initiate_write_inodeblock_ufs1: I/O underway");
9932                 FREE_LOCK(&lk);
9933                 sip = malloc(sizeof(struct ufs1_dinode),
9934                     M_SAVEDINO, M_SOFTDEP_FLAGS);
9935                 ACQUIRE_LOCK(&lk);
9936                 inodedep->id_savedino1 = sip;
9937                 *inodedep->id_savedino1 = *dp;
9938                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
9939                 dp->di_gen = inodedep->id_savedino1->di_gen;
9940                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
9941                 return;
9942         }
9943         /*
9944          * If no dependencies, then there is nothing to roll back.
9945          */
9946         inodedep->id_savedsize = dp->di_size;
9947         inodedep->id_savedextsize = 0;
9948         inodedep->id_savednlink = dp->di_nlink;
9949         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9950             TAILQ_EMPTY(&inodedep->id_inoreflst))
9951                 return;
9952         /*
9953          * Revert the link count to that of the first unwritten journal entry.
9954          */
9955         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9956         if (inoref)
9957                 dp->di_nlink = inoref->if_nlink;
9958         /*
9959          * Set the dependencies to busy.
9960          */
9961         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9962              adp = TAILQ_NEXT(adp, ad_next)) {
9963 #ifdef INVARIANTS
9964                 if (deplist != 0 && prevlbn >= adp->ad_offset)
9965                         panic("softdep_write_inodeblock: lbn order");
9966                 prevlbn = adp->ad_offset;
9967                 if (adp->ad_offset < NDADDR &&
9968                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9969                         panic("%s: direct pointer #%jd mismatch %d != %jd",
9970                             "softdep_write_inodeblock",
9971                             (intmax_t)adp->ad_offset,
9972                             dp->di_db[adp->ad_offset],
9973                             (intmax_t)adp->ad_newblkno);
9974                 if (adp->ad_offset >= NDADDR &&
9975                     dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9976                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
9977                             "softdep_write_inodeblock",
9978                             (intmax_t)adp->ad_offset - NDADDR,
9979                             dp->di_ib[adp->ad_offset - NDADDR],
9980                             (intmax_t)adp->ad_newblkno);
9981                 deplist |= 1 << adp->ad_offset;
9982                 if ((adp->ad_state & ATTACHED) == 0)
9983                         panic("softdep_write_inodeblock: Unknown state 0x%x",
9984                             adp->ad_state);
9985 #endif /* INVARIANTS */
9986                 adp->ad_state &= ~ATTACHED;
9987                 adp->ad_state |= UNDONE;
9988         }
9989         /*
9990          * The on-disk inode cannot claim to be any larger than the last
9991          * fragment that has been written. Otherwise, the on-disk inode
9992          * might have fragments that were not the last block in the file
9993          * which would corrupt the filesystem.
9994          */
9995         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9996              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9997                 if (adp->ad_offset >= NDADDR)
9998                         break;
9999                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10000                 /* keep going until hitting a rollback to a frag */
10001                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10002                         continue;
10003                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10004                 for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10005 #ifdef INVARIANTS
10006                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10007                                 panic("softdep_write_inodeblock: lost dep1");
10008 #endif /* INVARIANTS */
10009                         dp->di_db[i] = 0;
10010                 }
10011                 for (i = 0; i < NIADDR; i++) {
10012 #ifdef INVARIANTS
10013                         if (dp->di_ib[i] != 0 &&
10014                             (deplist & ((1 << NDADDR) << i)) == 0)
10015                                 panic("softdep_write_inodeblock: lost dep2");
10016 #endif /* INVARIANTS */
10017                         dp->di_ib[i] = 0;
10018                 }
10019                 return;
10020         }
10021         /*
10022          * If we have zero'ed out the last allocated block of the file,
10023          * roll back the size to the last currently allocated block.
10024          * We know that this last allocated block is a full-sized as
10025          * we already checked for fragments in the loop above.
10026          */
10027         if (lastadp != NULL &&
10028             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10029                 for (i = lastadp->ad_offset; i >= 0; i--)
10030                         if (dp->di_db[i] != 0)
10031                                 break;
10032                 dp->di_size = (i + 1) * fs->fs_bsize;
10033         }
10034         /*
10035          * The only dependencies are for indirect blocks.
10036          *
10037          * The file size for indirect block additions is not guaranteed.
10038          * Such a guarantee would be non-trivial to achieve. The conventional
10039          * synchronous write implementation also does not make this guarantee.
10040          * Fsck should catch and fix discrepancies. Arguably, the file size
10041          * can be over-estimated without destroying integrity when the file
10042          * moves into the indirect blocks (i.e., is large). If we want to
10043          * postpone fsck, we are stuck with this argument.
10044          */
10045         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10046                 dp->di_ib[adp->ad_offset - NDADDR] = 0;
10047 }
10048                 
10049 /*
10050  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10051  * Note that any bug fixes made to this routine must be done in the
10052  * version found above.
10053  *
10054  * Called from within the procedure above to deal with unsatisfied
10055  * allocation dependencies in an inodeblock. The buffer must be
10056  * locked, thus, no I/O completion operations can occur while we
10057  * are manipulating its associated dependencies.
10058  */
10059 static void 
10060 initiate_write_inodeblock_ufs2(inodedep, bp)
10061         struct inodedep *inodedep;
10062         struct buf *bp;                 /* The inode block */
10063 {
10064         struct allocdirect *adp, *lastadp;
10065         struct ufs2_dinode *dp;
10066         struct ufs2_dinode *sip;
10067         struct inoref *inoref;
10068         struct fs *fs;
10069         ufs_lbn_t i;
10070 #ifdef INVARIANTS
10071         ufs_lbn_t prevlbn = 0;
10072 #endif
10073         int deplist;
10074
10075         if (inodedep->id_state & IOSTARTED)
10076                 panic("initiate_write_inodeblock_ufs2: already started");
10077         inodedep->id_state |= IOSTARTED;
10078         fs = inodedep->id_fs;
10079         dp = (struct ufs2_dinode *)bp->b_data +
10080             ino_to_fsbo(fs, inodedep->id_ino);
10081
10082         /*
10083          * If we're on the unlinked list but have not yet written our
10084          * next pointer initialize it here.
10085          */
10086         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10087                 struct inodedep *inon;
10088
10089                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10090                 dp->di_freelink = inon ? inon->id_ino : 0;
10091         }
10092         /*
10093          * If the bitmap is not yet written, then the allocated
10094          * inode cannot be written to disk.
10095          */
10096         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10097                 if (inodedep->id_savedino2 != NULL)
10098                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10099                 FREE_LOCK(&lk);
10100                 sip = malloc(sizeof(struct ufs2_dinode),
10101                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10102                 ACQUIRE_LOCK(&lk);
10103                 inodedep->id_savedino2 = sip;
10104                 *inodedep->id_savedino2 = *dp;
10105                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10106                 dp->di_gen = inodedep->id_savedino2->di_gen;
10107                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10108                 return;
10109         }
10110         /*
10111          * If no dependencies, then there is nothing to roll back.
10112          */
10113         inodedep->id_savedsize = dp->di_size;
10114         inodedep->id_savedextsize = dp->di_extsize;
10115         inodedep->id_savednlink = dp->di_nlink;
10116         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10117             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10118             TAILQ_EMPTY(&inodedep->id_inoreflst))
10119                 return;
10120         /*
10121          * Revert the link count to that of the first unwritten journal entry.
10122          */
10123         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10124         if (inoref)
10125                 dp->di_nlink = inoref->if_nlink;
10126
10127         /*
10128          * Set the ext data dependencies to busy.
10129          */
10130         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10131              adp = TAILQ_NEXT(adp, ad_next)) {
10132 #ifdef INVARIANTS
10133                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10134                         panic("softdep_write_inodeblock: lbn order");
10135                 prevlbn = adp->ad_offset;
10136                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10137                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10138                             "softdep_write_inodeblock",
10139                             (intmax_t)adp->ad_offset,
10140                             (intmax_t)dp->di_extb[adp->ad_offset],
10141                             (intmax_t)adp->ad_newblkno);
10142                 deplist |= 1 << adp->ad_offset;
10143                 if ((adp->ad_state & ATTACHED) == 0)
10144                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10145                             adp->ad_state);
10146 #endif /* INVARIANTS */
10147                 adp->ad_state &= ~ATTACHED;
10148                 adp->ad_state |= UNDONE;
10149         }
10150         /*
10151          * The on-disk inode cannot claim to be any larger than the last
10152          * fragment that has been written. Otherwise, the on-disk inode
10153          * might have fragments that were not the last block in the ext
10154          * data which would corrupt the filesystem.
10155          */
10156         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10157              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10158                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10159                 /* keep going until hitting a rollback to a frag */
10160                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10161                         continue;
10162                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10163                 for (i = adp->ad_offset + 1; i < NXADDR; i++) {
10164 #ifdef INVARIANTS
10165                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10166                                 panic("softdep_write_inodeblock: lost dep1");
10167 #endif /* INVARIANTS */
10168                         dp->di_extb[i] = 0;
10169                 }
10170                 lastadp = NULL;
10171                 break;
10172         }
10173         /*
10174          * If we have zero'ed out the last allocated block of the ext
10175          * data, roll back the size to the last currently allocated block.
10176          * We know that this last allocated block is a full-sized as
10177          * we already checked for fragments in the loop above.
10178          */
10179         if (lastadp != NULL &&
10180             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10181                 for (i = lastadp->ad_offset; i >= 0; i--)
10182                         if (dp->di_extb[i] != 0)
10183                                 break;
10184                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10185         }
10186         /*
10187          * Set the file data dependencies to busy.
10188          */
10189         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10190              adp = TAILQ_NEXT(adp, ad_next)) {
10191 #ifdef INVARIANTS
10192                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10193                         panic("softdep_write_inodeblock: lbn order");
10194                 if ((adp->ad_state & ATTACHED) == 0)
10195                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10196                 prevlbn = adp->ad_offset;
10197                 if (adp->ad_offset < NDADDR &&
10198                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10199                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10200                             "softdep_write_inodeblock",
10201                             (intmax_t)adp->ad_offset,
10202                             (intmax_t)dp->di_db[adp->ad_offset],
10203                             (intmax_t)adp->ad_newblkno);
10204                 if (adp->ad_offset >= NDADDR &&
10205                     dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10206                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
10207                             "softdep_write_inodeblock:",
10208                             (intmax_t)adp->ad_offset - NDADDR,
10209                             (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
10210                             (intmax_t)adp->ad_newblkno);
10211                 deplist |= 1 << adp->ad_offset;
10212                 if ((adp->ad_state & ATTACHED) == 0)
10213                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10214                             adp->ad_state);
10215 #endif /* INVARIANTS */
10216                 adp->ad_state &= ~ATTACHED;
10217                 adp->ad_state |= UNDONE;
10218         }
10219         /*
10220          * The on-disk inode cannot claim to be any larger than the last
10221          * fragment that has been written. Otherwise, the on-disk inode
10222          * might have fragments that were not the last block in the file
10223          * which would corrupt the filesystem.
10224          */
10225         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10226              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10227                 if (adp->ad_offset >= NDADDR)
10228                         break;
10229                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10230                 /* keep going until hitting a rollback to a frag */
10231                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10232                         continue;
10233                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10234                 for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10235 #ifdef INVARIANTS
10236                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10237                                 panic("softdep_write_inodeblock: lost dep2");
10238 #endif /* INVARIANTS */
10239                         dp->di_db[i] = 0;
10240                 }
10241                 for (i = 0; i < NIADDR; i++) {
10242 #ifdef INVARIANTS
10243                         if (dp->di_ib[i] != 0 &&
10244                             (deplist & ((1 << NDADDR) << i)) == 0)
10245                                 panic("softdep_write_inodeblock: lost dep3");
10246 #endif /* INVARIANTS */
10247                         dp->di_ib[i] = 0;
10248                 }
10249                 return;
10250         }
10251         /*
10252          * If we have zero'ed out the last allocated block of the file,
10253          * roll back the size to the last currently allocated block.
10254          * We know that this last allocated block is a full-sized as
10255          * we already checked for fragments in the loop above.
10256          */
10257         if (lastadp != NULL &&
10258             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10259                 for (i = lastadp->ad_offset; i >= 0; i--)
10260                         if (dp->di_db[i] != 0)
10261                                 break;
10262                 dp->di_size = (i + 1) * fs->fs_bsize;
10263         }
10264         /*
10265          * The only dependencies are for indirect blocks.
10266          *
10267          * The file size for indirect block additions is not guaranteed.
10268          * Such a guarantee would be non-trivial to achieve. The conventional
10269          * synchronous write implementation also does not make this guarantee.
10270          * Fsck should catch and fix discrepancies. Arguably, the file size
10271          * can be over-estimated without destroying integrity when the file
10272          * moves into the indirect blocks (i.e., is large). If we want to
10273          * postpone fsck, we are stuck with this argument.
10274          */
10275         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10276                 dp->di_ib[adp->ad_offset - NDADDR] = 0;
10277 }
10278
10279 /*
10280  * Cancel an indirdep as a result of truncation.  Release all of the
10281  * children allocindirs and place their journal work on the appropriate
10282  * list.
10283  */
10284 static void
10285 cancel_indirdep(indirdep, bp, freeblks)
10286         struct indirdep *indirdep;
10287         struct buf *bp;
10288         struct freeblks *freeblks;
10289 {
10290         struct allocindir *aip;
10291
10292         /*
10293          * None of the indirect pointers will ever be visible,
10294          * so they can simply be tossed. GOINGAWAY ensures
10295          * that allocated pointers will be saved in the buffer
10296          * cache until they are freed. Note that they will
10297          * only be able to be found by their physical address
10298          * since the inode mapping the logical address will
10299          * be gone. The save buffer used for the safe copy
10300          * was allocated in setup_allocindir_phase2 using
10301          * the physical address so it could be used for this
10302          * purpose. Hence we swap the safe copy with the real
10303          * copy, allowing the safe copy to be freed and holding
10304          * on to the real copy for later use in indir_trunc.
10305          */
10306         if (indirdep->ir_state & GOINGAWAY)
10307                 panic("cancel_indirdep: already gone");
10308         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10309                 indirdep->ir_state |= DEPCOMPLETE;
10310                 LIST_REMOVE(indirdep, ir_next);
10311         }
10312         indirdep->ir_state |= GOINGAWAY;
10313         VFSTOUFS(indirdep->ir_list.wk_mp)->um_numindirdeps += 1;
10314         /*
10315          * Pass in bp for blocks still have journal writes
10316          * pending so we can cancel them on their own.
10317          */
10318         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10319                 cancel_allocindir(aip, bp, freeblks, 0);
10320         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10321                 cancel_allocindir(aip, NULL, freeblks, 0);
10322         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10323                 cancel_allocindir(aip, NULL, freeblks, 0);
10324         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10325                 cancel_allocindir(aip, NULL, freeblks, 0);
10326         /*
10327          * If there are pending partial truncations we need to keep the
10328          * old block copy around until they complete.  This is because
10329          * the current b_data is not a perfect superset of the available
10330          * blocks.
10331          */
10332         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10333                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10334         else
10335                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10336         WORKLIST_REMOVE(&indirdep->ir_list);
10337         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10338         indirdep->ir_bp = NULL;
10339         indirdep->ir_freeblks = freeblks;
10340 }
10341
10342 /*
10343  * Free an indirdep once it no longer has new pointers to track.
10344  */
10345 static void
10346 free_indirdep(indirdep)
10347         struct indirdep *indirdep;
10348 {
10349
10350         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10351             ("free_indirdep: Indir trunc list not empty."));
10352         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10353             ("free_indirdep: Complete head not empty."));
10354         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10355             ("free_indirdep: write head not empty."));
10356         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10357             ("free_indirdep: done head not empty."));
10358         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10359             ("free_indirdep: deplist head not empty."));
10360         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10361             ("free_indirdep: %p still on newblk list.", indirdep));
10362         KASSERT(indirdep->ir_saveddata == NULL,
10363             ("free_indirdep: %p still has saved data.", indirdep));
10364         if (indirdep->ir_state & ONWORKLIST)
10365                 WORKLIST_REMOVE(&indirdep->ir_list);
10366         WORKITEM_FREE(indirdep, D_INDIRDEP);
10367 }
10368
10369 /*
10370  * Called before a write to an indirdep.  This routine is responsible for
10371  * rolling back pointers to a safe state which includes only those
10372  * allocindirs which have been completed.
10373  */
10374 static void
10375 initiate_write_indirdep(indirdep, bp)
10376         struct indirdep *indirdep;
10377         struct buf *bp;
10378 {
10379
10380         indirdep->ir_state |= IOSTARTED;
10381         if (indirdep->ir_state & GOINGAWAY)
10382                 panic("disk_io_initiation: indirdep gone");
10383         /*
10384          * If there are no remaining dependencies, this will be writing
10385          * the real pointers.
10386          */
10387         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10388             TAILQ_EMPTY(&indirdep->ir_trunc))
10389                 return;
10390         /*
10391          * Replace up-to-date version with safe version.
10392          */
10393         if (indirdep->ir_saveddata == NULL) {
10394                 FREE_LOCK(&lk);
10395                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10396                     M_SOFTDEP_FLAGS);
10397                 ACQUIRE_LOCK(&lk);
10398         }
10399         indirdep->ir_state &= ~ATTACHED;
10400         indirdep->ir_state |= UNDONE;
10401         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10402         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10403             bp->b_bcount);
10404 }
10405
10406 /*
10407  * Called when an inode has been cleared in a cg bitmap.  This finally
10408  * eliminates any canceled jaddrefs
10409  */
10410 void
10411 softdep_setup_inofree(mp, bp, ino, wkhd)
10412         struct mount *mp;
10413         struct buf *bp;
10414         ino_t ino;
10415         struct workhead *wkhd;
10416 {
10417         struct worklist *wk, *wkn;
10418         struct inodedep *inodedep;
10419         uint8_t *inosused;
10420         struct cg *cgp;
10421         struct fs *fs;
10422
10423         ACQUIRE_LOCK(&lk);
10424         fs = VFSTOUFS(mp)->um_fs;
10425         cgp = (struct cg *)bp->b_data;
10426         inosused = cg_inosused(cgp);
10427         if (isset(inosused, ino % fs->fs_ipg))
10428                 panic("softdep_setup_inofree: inode %d not freed.", ino);
10429         if (inodedep_lookup(mp, ino, 0, &inodedep))
10430                 panic("softdep_setup_inofree: ino %d has existing inodedep %p",
10431                     ino, inodedep);
10432         if (wkhd) {
10433                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10434                         if (wk->wk_type != D_JADDREF)
10435                                 continue;
10436                         WORKLIST_REMOVE(wk);
10437                         /*
10438                          * We can free immediately even if the jaddref
10439                          * isn't attached in a background write as now
10440                          * the bitmaps are reconciled.
10441                          */
10442                         wk->wk_state |= COMPLETE | ATTACHED;
10443                         free_jaddref(WK_JADDREF(wk));
10444                 }
10445                 jwork_move(&bp->b_dep, wkhd);
10446         }
10447         FREE_LOCK(&lk);
10448 }
10449
10450
10451 /*
10452  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10453  * map.  Any dependencies waiting for the write to clear are added to the
10454  * buf's list and any jnewblks that are being canceled are discarded
10455  * immediately.
10456  */
10457 void
10458 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10459         struct mount *mp;
10460         struct buf *bp;
10461         ufs2_daddr_t blkno;
10462         int frags;
10463         struct workhead *wkhd;
10464 {
10465         struct bmsafemap *bmsafemap;
10466         struct jnewblk *jnewblk;
10467         struct worklist *wk;
10468         struct fs *fs;
10469 #ifdef SUJ_DEBUG
10470         uint8_t *blksfree;
10471         struct cg *cgp;
10472         ufs2_daddr_t jstart;
10473         ufs2_daddr_t jend;
10474         ufs2_daddr_t end;
10475         long bno;
10476         int i;
10477 #endif
10478
10479         CTR3(KTR_SUJ,
10480             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10481             blkno, frags, wkhd);
10482
10483         ACQUIRE_LOCK(&lk);
10484         /* Lookup the bmsafemap so we track when it is dirty. */
10485         fs = VFSTOUFS(mp)->um_fs;
10486         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10487         /*
10488          * Detach any jnewblks which have been canceled.  They must linger
10489          * until the bitmap is cleared again by ffs_blkfree() to prevent
10490          * an unjournaled allocation from hitting the disk.
10491          */
10492         if (wkhd) {
10493                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10494                         CTR2(KTR_SUJ,
10495                             "softdep_setup_blkfree: blkno %jd wk type %d",
10496                             blkno, wk->wk_type);
10497                         WORKLIST_REMOVE(wk);
10498                         if (wk->wk_type != D_JNEWBLK) {
10499                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10500                                 continue;
10501                         }
10502                         jnewblk = WK_JNEWBLK(wk);
10503                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10504                             ("softdep_setup_blkfree: jnewblk not canceled."));
10505 #ifdef SUJ_DEBUG
10506                         /*
10507                          * Assert that this block is free in the bitmap
10508                          * before we discard the jnewblk.
10509                          */
10510                         cgp = (struct cg *)bp->b_data;
10511                         blksfree = cg_blksfree(cgp);
10512                         bno = dtogd(fs, jnewblk->jn_blkno);
10513                         for (i = jnewblk->jn_oldfrags;
10514                             i < jnewblk->jn_frags; i++) {
10515                                 if (isset(blksfree, bno + i))
10516                                         continue;
10517                                 panic("softdep_setup_blkfree: not free");
10518                         }
10519 #endif
10520                         /*
10521                          * Even if it's not attached we can free immediately
10522                          * as the new bitmap is correct.
10523                          */
10524                         wk->wk_state |= COMPLETE | ATTACHED;
10525                         free_jnewblk(jnewblk);
10526                 }
10527         }
10528
10529 #ifdef SUJ_DEBUG
10530         /*
10531          * Assert that we are not freeing a block which has an outstanding
10532          * allocation dependency.
10533          */
10534         fs = VFSTOUFS(mp)->um_fs;
10535         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10536         end = blkno + frags;
10537         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10538                 /*
10539                  * Don't match against blocks that will be freed when the
10540                  * background write is done.
10541                  */
10542                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10543                     (COMPLETE | DEPCOMPLETE))
10544                         continue;
10545                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10546                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10547                 if ((blkno >= jstart && blkno < jend) ||
10548                     (end > jstart && end <= jend)) {
10549                         printf("state 0x%X %jd - %d %d dep %p\n",
10550                             jnewblk->jn_state, jnewblk->jn_blkno,
10551                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10552                             jnewblk->jn_dep);
10553                         panic("softdep_setup_blkfree: "
10554                             "%jd-%jd(%d) overlaps with %jd-%jd",
10555                             blkno, end, frags, jstart, jend);
10556                 }
10557         }
10558 #endif
10559         FREE_LOCK(&lk);
10560 }
10561
10562 /*
10563  * Revert a block allocation when the journal record that describes it
10564  * is not yet written.
10565  */
10566 int
10567 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10568         struct jnewblk *jnewblk;
10569         struct fs *fs;
10570         struct cg *cgp;
10571         uint8_t *blksfree;
10572 {
10573         ufs1_daddr_t fragno;
10574         long cgbno, bbase;
10575         int frags, blk;
10576         int i;
10577
10578         frags = 0;
10579         cgbno = dtogd(fs, jnewblk->jn_blkno);
10580         /*
10581          * We have to test which frags need to be rolled back.  We may
10582          * be operating on a stale copy when doing background writes.
10583          */
10584         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10585                 if (isclr(blksfree, cgbno + i))
10586                         frags++;
10587         if (frags == 0)
10588                 return (0);
10589         /*
10590          * This is mostly ffs_blkfree() sans some validation and
10591          * superblock updates.
10592          */
10593         if (frags == fs->fs_frag) {
10594                 fragno = fragstoblks(fs, cgbno);
10595                 ffs_setblock(fs, blksfree, fragno);
10596                 ffs_clusteracct(fs, cgp, fragno, 1);
10597                 cgp->cg_cs.cs_nbfree++;
10598         } else {
10599                 cgbno += jnewblk->jn_oldfrags;
10600                 bbase = cgbno - fragnum(fs, cgbno);
10601                 /* Decrement the old frags.  */
10602                 blk = blkmap(fs, blksfree, bbase);
10603                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10604                 /* Deallocate the fragment */
10605                 for (i = 0; i < frags; i++)
10606                         setbit(blksfree, cgbno + i);
10607                 cgp->cg_cs.cs_nffree += frags;
10608                 /* Add back in counts associated with the new frags */
10609                 blk = blkmap(fs, blksfree, bbase);
10610                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10611                 /* If a complete block has been reassembled, account for it. */
10612                 fragno = fragstoblks(fs, bbase);
10613                 if (ffs_isblock(fs, blksfree, fragno)) {
10614                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10615                         ffs_clusteracct(fs, cgp, fragno, 1);
10616                         cgp->cg_cs.cs_nbfree++;
10617                 }
10618         }
10619         stat_jnewblk++;
10620         jnewblk->jn_state &= ~ATTACHED;
10621         jnewblk->jn_state |= UNDONE;
10622
10623         return (frags);
10624 }
10625
10626 static void
10627 initiate_write_bmsafemap(bmsafemap, bp)
10628         struct bmsafemap *bmsafemap;
10629         struct buf *bp;                 /* The cg block. */
10630 {
10631         struct jaddref *jaddref;
10632         struct jnewblk *jnewblk;
10633         uint8_t *inosused;
10634         uint8_t *blksfree;
10635         struct cg *cgp;
10636         struct fs *fs;
10637         ino_t ino;
10638
10639         if (bmsafemap->sm_state & IOSTARTED)
10640                 return;
10641         bmsafemap->sm_state |= IOSTARTED;
10642         /*
10643          * Clear any inode allocations which are pending journal writes.
10644          */
10645         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10646                 cgp = (struct cg *)bp->b_data;
10647                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10648                 inosused = cg_inosused(cgp);
10649                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10650                         ino = jaddref->ja_ino % fs->fs_ipg;
10651                         if (isset(inosused, ino)) {
10652                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10653                                         cgp->cg_cs.cs_ndir--;
10654                                 cgp->cg_cs.cs_nifree++;
10655                                 clrbit(inosused, ino);
10656                                 jaddref->ja_state &= ~ATTACHED;
10657                                 jaddref->ja_state |= UNDONE;
10658                                 stat_jaddref++;
10659                         } else
10660                                 panic("initiate_write_bmsafemap: inode %d "
10661                                     "marked free", jaddref->ja_ino);
10662                 }
10663         }
10664         /*
10665          * Clear any block allocations which are pending journal writes.
10666          */
10667         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10668                 cgp = (struct cg *)bp->b_data;
10669                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10670                 blksfree = cg_blksfree(cgp);
10671                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10672                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10673                                 continue;
10674                         panic("initiate_write_bmsafemap: block %jd "
10675                             "marked free", jnewblk->jn_blkno);
10676                 }
10677         }
10678         /*
10679          * Move allocation lists to the written lists so they can be
10680          * cleared once the block write is complete.
10681          */
10682         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10683             inodedep, id_deps);
10684         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10685             newblk, nb_deps);
10686         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10687             wk_list);
10688 }
10689
10690 /*
10691  * This routine is called during the completion interrupt
10692  * service routine for a disk write (from the procedure called
10693  * by the device driver to inform the filesystem caches of
10694  * a request completion).  It should be called early in this
10695  * procedure, before the block is made available to other
10696  * processes or other routines are called.
10697  *
10698  */
10699 static void 
10700 softdep_disk_write_complete(bp)
10701         struct buf *bp;         /* describes the completed disk write */
10702 {
10703         struct worklist *wk;
10704         struct worklist *owk;
10705         struct workhead reattach;
10706         struct freeblks *freeblks;
10707         struct buf *sbp;
10708
10709         /*
10710          * If an error occurred while doing the write, then the data
10711          * has not hit the disk and the dependencies cannot be unrolled.
10712          */
10713         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10714                 return;
10715         LIST_INIT(&reattach);
10716         /*
10717          * This lock must not be released anywhere in this code segment.
10718          */
10719         sbp = NULL;
10720         owk = NULL;
10721         ACQUIRE_LOCK(&lk);
10722         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10723                 WORKLIST_REMOVE(wk);
10724                 dep_write[wk->wk_type]++;
10725                 if (wk == owk)
10726                         panic("duplicate worklist: %p\n", wk);
10727                 owk = wk;
10728                 switch (wk->wk_type) {
10729
10730                 case D_PAGEDEP:
10731                         if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10732                                 WORKLIST_INSERT(&reattach, wk);
10733                         continue;
10734
10735                 case D_INODEDEP:
10736                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10737                                 WORKLIST_INSERT(&reattach, wk);
10738                         continue;
10739
10740                 case D_BMSAFEMAP:
10741                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10742                                 WORKLIST_INSERT(&reattach, wk);
10743                         continue;
10744
10745                 case D_MKDIR:
10746                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10747                         continue;
10748
10749                 case D_ALLOCDIRECT:
10750                         wk->wk_state |= COMPLETE;
10751                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10752                         continue;
10753
10754                 case D_ALLOCINDIR:
10755                         wk->wk_state |= COMPLETE;
10756                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10757                         continue;
10758
10759                 case D_INDIRDEP:
10760                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10761                                 WORKLIST_INSERT(&reattach, wk);
10762                         continue;
10763
10764                 case D_FREEBLKS:
10765                         wk->wk_state |= COMPLETE;
10766                         freeblks = WK_FREEBLKS(wk);
10767                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10768                             LIST_EMPTY(&freeblks->fb_jblkdephd))
10769                                 add_to_worklist(wk, WK_NODELAY);
10770                         continue;
10771
10772                 case D_FREEWORK:
10773                         handle_written_freework(WK_FREEWORK(wk));
10774                         break;
10775
10776                 case D_JSEGDEP:
10777                         free_jsegdep(WK_JSEGDEP(wk));
10778                         continue;
10779
10780                 case D_JSEG:
10781                         handle_written_jseg(WK_JSEG(wk), bp);
10782                         continue;
10783
10784                 case D_SBDEP:
10785                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
10786                                 WORKLIST_INSERT(&reattach, wk);
10787                         continue;
10788
10789                 case D_FREEDEP:
10790                         free_freedep(WK_FREEDEP(wk));
10791                         continue;
10792
10793                 default:
10794                         panic("handle_disk_write_complete: Unknown type %s",
10795                             TYPENAME(wk->wk_type));
10796                         /* NOTREACHED */
10797                 }
10798         }
10799         /*
10800          * Reattach any requests that must be redone.
10801          */
10802         while ((wk = LIST_FIRST(&reattach)) != NULL) {
10803                 WORKLIST_REMOVE(wk);
10804                 WORKLIST_INSERT(&bp->b_dep, wk);
10805         }
10806         FREE_LOCK(&lk);
10807         if (sbp)
10808                 brelse(sbp);
10809 }
10810
10811 /*
10812  * Called from within softdep_disk_write_complete above. Note that
10813  * this routine is always called from interrupt level with further
10814  * splbio interrupts blocked.
10815  */
10816 static void 
10817 handle_allocdirect_partdone(adp, wkhd)
10818         struct allocdirect *adp;        /* the completed allocdirect */
10819         struct workhead *wkhd;          /* Work to do when inode is writtne. */
10820 {
10821         struct allocdirectlst *listhead;
10822         struct allocdirect *listadp;
10823         struct inodedep *inodedep;
10824         long bsize;
10825
10826         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10827                 return;
10828         /*
10829          * The on-disk inode cannot claim to be any larger than the last
10830          * fragment that has been written. Otherwise, the on-disk inode
10831          * might have fragments that were not the last block in the file
10832          * which would corrupt the filesystem. Thus, we cannot free any
10833          * allocdirects after one whose ad_oldblkno claims a fragment as
10834          * these blocks must be rolled back to zero before writing the inode.
10835          * We check the currently active set of allocdirects in id_inoupdt
10836          * or id_extupdt as appropriate.
10837          */
10838         inodedep = adp->ad_inodedep;
10839         bsize = inodedep->id_fs->fs_bsize;
10840         if (adp->ad_state & EXTDATA)
10841                 listhead = &inodedep->id_extupdt;
10842         else
10843                 listhead = &inodedep->id_inoupdt;
10844         TAILQ_FOREACH(listadp, listhead, ad_next) {
10845                 /* found our block */
10846                 if (listadp == adp)
10847                         break;
10848                 /* continue if ad_oldlbn is not a fragment */
10849                 if (listadp->ad_oldsize == 0 ||
10850                     listadp->ad_oldsize == bsize)
10851                         continue;
10852                 /* hit a fragment */
10853                 return;
10854         }
10855         /*
10856          * If we have reached the end of the current list without
10857          * finding the just finished dependency, then it must be
10858          * on the future dependency list. Future dependencies cannot
10859          * be freed until they are moved to the current list.
10860          */
10861         if (listadp == NULL) {
10862 #ifdef DEBUG
10863                 if (adp->ad_state & EXTDATA)
10864                         listhead = &inodedep->id_newextupdt;
10865                 else
10866                         listhead = &inodedep->id_newinoupdt;
10867                 TAILQ_FOREACH(listadp, listhead, ad_next)
10868                         /* found our block */
10869                         if (listadp == adp)
10870                                 break;
10871                 if (listadp == NULL)
10872                         panic("handle_allocdirect_partdone: lost dep");
10873 #endif /* DEBUG */
10874                 return;
10875         }
10876         /*
10877          * If we have found the just finished dependency, then queue
10878          * it along with anything that follows it that is complete.
10879          * Since the pointer has not yet been written in the inode
10880          * as the dependency prevents it, place the allocdirect on the
10881          * bufwait list where it will be freed once the pointer is
10882          * valid.
10883          */
10884         if (wkhd == NULL)
10885                 wkhd = &inodedep->id_bufwait;
10886         for (; adp; adp = listadp) {
10887                 listadp = TAILQ_NEXT(adp, ad_next);
10888                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10889                         return;
10890                 TAILQ_REMOVE(listhead, adp, ad_next);
10891                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
10892         }
10893 }
10894
10895 /*
10896  * Called from within softdep_disk_write_complete above.  This routine
10897  * completes successfully written allocindirs.
10898  */
10899 static void
10900 handle_allocindir_partdone(aip)
10901         struct allocindir *aip;         /* the completed allocindir */
10902 {
10903         struct indirdep *indirdep;
10904
10905         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
10906                 return;
10907         indirdep = aip->ai_indirdep;
10908         LIST_REMOVE(aip, ai_next);
10909         /*
10910          * Don't set a pointer while the buffer is undergoing IO or while
10911          * we have active truncations.
10912          */
10913         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
10914                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
10915                 return;
10916         }
10917         if (indirdep->ir_state & UFS1FMT)
10918                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10919                     aip->ai_newblkno;
10920         else
10921                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10922                     aip->ai_newblkno;
10923         /*
10924          * Await the pointer write before freeing the allocindir.
10925          */
10926         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
10927 }
10928
10929 /*
10930  * Release segments held on a jwork list.
10931  */
10932 static void
10933 handle_jwork(wkhd)
10934         struct workhead *wkhd;
10935 {
10936         struct worklist *wk;
10937
10938         while ((wk = LIST_FIRST(wkhd)) != NULL) {
10939                 WORKLIST_REMOVE(wk);
10940                 switch (wk->wk_type) {
10941                 case D_JSEGDEP:
10942                         free_jsegdep(WK_JSEGDEP(wk));
10943                         continue;
10944                 case D_FREEDEP:
10945                         free_freedep(WK_FREEDEP(wk));
10946                         continue;
10947                 case D_FREEFRAG:
10948                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
10949                         WORKITEM_FREE(wk, D_FREEFRAG);
10950                         continue;
10951                 case D_FREEWORK:
10952                         handle_written_freework(WK_FREEWORK(wk));
10953                         continue;
10954                 default:
10955                         panic("handle_jwork: Unknown type %s\n",
10956                             TYPENAME(wk->wk_type));
10957                 }
10958         }
10959 }
10960
10961 /*
10962  * Handle the bufwait list on an inode when it is safe to release items
10963  * held there.  This normally happens after an inode block is written but
10964  * may be delayed and handled later if there are pending journal items that
10965  * are not yet safe to be released.
10966  */
10967 static struct freefile *
10968 handle_bufwait(inodedep, refhd)
10969         struct inodedep *inodedep;
10970         struct workhead *refhd;
10971 {
10972         struct jaddref *jaddref;
10973         struct freefile *freefile;
10974         struct worklist *wk;
10975
10976         freefile = NULL;
10977         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
10978                 WORKLIST_REMOVE(wk);
10979                 switch (wk->wk_type) {
10980                 case D_FREEFILE:
10981                         /*
10982                          * We defer adding freefile to the worklist
10983                          * until all other additions have been made to
10984                          * ensure that it will be done after all the
10985                          * old blocks have been freed.
10986                          */
10987                         if (freefile != NULL)
10988                                 panic("handle_bufwait: freefile");
10989                         freefile = WK_FREEFILE(wk);
10990                         continue;
10991
10992                 case D_MKDIR:
10993                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
10994                         continue;
10995
10996                 case D_DIRADD:
10997                         diradd_inode_written(WK_DIRADD(wk), inodedep);
10998                         continue;
10999
11000                 case D_FREEFRAG:
11001                         wk->wk_state |= COMPLETE;
11002                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11003                                 add_to_worklist(wk, 0);
11004                         continue;
11005
11006                 case D_DIRREM:
11007                         wk->wk_state |= COMPLETE;
11008                         add_to_worklist(wk, 0);
11009                         continue;
11010
11011                 case D_ALLOCDIRECT:
11012                 case D_ALLOCINDIR:
11013                         free_newblk(WK_NEWBLK(wk));
11014                         continue;
11015
11016                 case D_JNEWBLK:
11017                         wk->wk_state |= COMPLETE;
11018                         free_jnewblk(WK_JNEWBLK(wk));
11019                         continue;
11020
11021                 /*
11022                  * Save freed journal segments and add references on
11023                  * the supplied list which will delay their release
11024                  * until the cg bitmap is cleared on disk.
11025                  */
11026                 case D_JSEGDEP:
11027                         if (refhd == NULL)
11028                                 free_jsegdep(WK_JSEGDEP(wk));
11029                         else
11030                                 WORKLIST_INSERT(refhd, wk);
11031                         continue;
11032
11033                 case D_JADDREF:
11034                         jaddref = WK_JADDREF(wk);
11035                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11036                             if_deps);
11037                         /*
11038                          * Transfer any jaddrefs to the list to be freed with
11039                          * the bitmap if we're handling a removed file.
11040                          */
11041                         if (refhd == NULL) {
11042                                 wk->wk_state |= COMPLETE;
11043                                 free_jaddref(jaddref);
11044                         } else
11045                                 WORKLIST_INSERT(refhd, wk);
11046                         continue;
11047
11048                 default:
11049                         panic("handle_bufwait: Unknown type %p(%s)",
11050                             wk, TYPENAME(wk->wk_type));
11051                         /* NOTREACHED */
11052                 }
11053         }
11054         return (freefile);
11055 }
11056 /*
11057  * Called from within softdep_disk_write_complete above to restore
11058  * in-memory inode block contents to their most up-to-date state. Note
11059  * that this routine is always called from interrupt level with further
11060  * splbio interrupts blocked.
11061  */
11062 static int 
11063 handle_written_inodeblock(inodedep, bp)
11064         struct inodedep *inodedep;
11065         struct buf *bp;         /* buffer containing the inode block */
11066 {
11067         struct freefile *freefile;
11068         struct allocdirect *adp, *nextadp;
11069         struct ufs1_dinode *dp1 = NULL;
11070         struct ufs2_dinode *dp2 = NULL;
11071         struct workhead wkhd;
11072         int hadchanges, fstype;
11073         ino_t freelink;
11074
11075         LIST_INIT(&wkhd);
11076         hadchanges = 0;
11077         freefile = NULL;
11078         if ((inodedep->id_state & IOSTARTED) == 0)
11079                 panic("handle_written_inodeblock: not started");
11080         inodedep->id_state &= ~IOSTARTED;
11081         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11082                 fstype = UFS1;
11083                 dp1 = (struct ufs1_dinode *)bp->b_data +
11084                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11085                 freelink = dp1->di_freelink;
11086         } else {
11087                 fstype = UFS2;
11088                 dp2 = (struct ufs2_dinode *)bp->b_data +
11089                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11090                 freelink = dp2->di_freelink;
11091         }
11092         /*
11093          * Leave this inodeblock dirty until it's in the list.
11094          */
11095         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
11096                 struct inodedep *inon;
11097
11098                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11099                 if ((inon == NULL && freelink == 0) ||
11100                     (inon && inon->id_ino == freelink)) {
11101                         if (inon)
11102                                 inon->id_state |= UNLINKPREV;
11103                         inodedep->id_state |= UNLINKNEXT;
11104                 }
11105                 hadchanges = 1;
11106         }
11107         /*
11108          * If we had to rollback the inode allocation because of
11109          * bitmaps being incomplete, then simply restore it.
11110          * Keep the block dirty so that it will not be reclaimed until
11111          * all associated dependencies have been cleared and the
11112          * corresponding updates written to disk.
11113          */
11114         if (inodedep->id_savedino1 != NULL) {
11115                 hadchanges = 1;
11116                 if (fstype == UFS1)
11117                         *dp1 = *inodedep->id_savedino1;
11118                 else
11119                         *dp2 = *inodedep->id_savedino2;
11120                 free(inodedep->id_savedino1, M_SAVEDINO);
11121                 inodedep->id_savedino1 = NULL;
11122                 if ((bp->b_flags & B_DELWRI) == 0)
11123                         stat_inode_bitmap++;
11124                 bdirty(bp);
11125                 /*
11126                  * If the inode is clear here and GOINGAWAY it will never
11127                  * be written.  Process the bufwait and clear any pending
11128                  * work which may include the freefile.
11129                  */
11130                 if (inodedep->id_state & GOINGAWAY)
11131                         goto bufwait;
11132                 return (1);
11133         }
11134         inodedep->id_state |= COMPLETE;
11135         /*
11136          * Roll forward anything that had to be rolled back before 
11137          * the inode could be updated.
11138          */
11139         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11140                 nextadp = TAILQ_NEXT(adp, ad_next);
11141                 if (adp->ad_state & ATTACHED)
11142                         panic("handle_written_inodeblock: new entry");
11143                 if (fstype == UFS1) {
11144                         if (adp->ad_offset < NDADDR) {
11145                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11146                                         panic("%s %s #%jd mismatch %d != %jd",
11147                                             "handle_written_inodeblock:",
11148                                             "direct pointer",
11149                                             (intmax_t)adp->ad_offset,
11150                                             dp1->di_db[adp->ad_offset],
11151                                             (intmax_t)adp->ad_oldblkno);
11152                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11153                         } else {
11154                                 if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
11155                                         panic("%s: %s #%jd allocated as %d",
11156                                             "handle_written_inodeblock",
11157                                             "indirect pointer",
11158                                             (intmax_t)adp->ad_offset - NDADDR,
11159                                             dp1->di_ib[adp->ad_offset - NDADDR]);
11160                                 dp1->di_ib[adp->ad_offset - NDADDR] =
11161                                     adp->ad_newblkno;
11162                         }
11163                 } else {
11164                         if (adp->ad_offset < NDADDR) {
11165                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11166                                         panic("%s: %s #%jd %s %jd != %jd",
11167                                             "handle_written_inodeblock",
11168                                             "direct pointer",
11169                                             (intmax_t)adp->ad_offset, "mismatch",
11170                                             (intmax_t)dp2->di_db[adp->ad_offset],
11171                                             (intmax_t)adp->ad_oldblkno);
11172                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11173                         } else {
11174                                 if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
11175                                         panic("%s: %s #%jd allocated as %jd",
11176                                             "handle_written_inodeblock",
11177                                             "indirect pointer",
11178                                             (intmax_t)adp->ad_offset - NDADDR,
11179                                             (intmax_t)
11180                                             dp2->di_ib[adp->ad_offset - NDADDR]);
11181                                 dp2->di_ib[adp->ad_offset - NDADDR] =
11182                                     adp->ad_newblkno;
11183                         }
11184                 }
11185                 adp->ad_state &= ~UNDONE;
11186                 adp->ad_state |= ATTACHED;
11187                 hadchanges = 1;
11188         }
11189         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11190                 nextadp = TAILQ_NEXT(adp, ad_next);
11191                 if (adp->ad_state & ATTACHED)
11192                         panic("handle_written_inodeblock: new entry");
11193                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11194                         panic("%s: direct pointers #%jd %s %jd != %jd",
11195                             "handle_written_inodeblock",
11196                             (intmax_t)adp->ad_offset, "mismatch",
11197                             (intmax_t)dp2->di_extb[adp->ad_offset],
11198                             (intmax_t)adp->ad_oldblkno);
11199                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11200                 adp->ad_state &= ~UNDONE;
11201                 adp->ad_state |= ATTACHED;
11202                 hadchanges = 1;
11203         }
11204         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11205                 stat_direct_blk_ptrs++;
11206         /*
11207          * Reset the file size to its most up-to-date value.
11208          */
11209         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11210                 panic("handle_written_inodeblock: bad size");
11211         if (inodedep->id_savednlink > LINK_MAX)
11212                 panic("handle_written_inodeblock: Invalid link count "
11213                     "%d for inodedep %p", inodedep->id_savednlink, inodedep);
11214         if (fstype == UFS1) {
11215                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11216                         dp1->di_nlink = inodedep->id_savednlink;
11217                         hadchanges = 1;
11218                 }
11219                 if (dp1->di_size != inodedep->id_savedsize) {
11220                         dp1->di_size = inodedep->id_savedsize;
11221                         hadchanges = 1;
11222                 }
11223         } else {
11224                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11225                         dp2->di_nlink = inodedep->id_savednlink;
11226                         hadchanges = 1;
11227                 }
11228                 if (dp2->di_size != inodedep->id_savedsize) {
11229                         dp2->di_size = inodedep->id_savedsize;
11230                         hadchanges = 1;
11231                 }
11232                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11233                         dp2->di_extsize = inodedep->id_savedextsize;
11234                         hadchanges = 1;
11235                 }
11236         }
11237         inodedep->id_savedsize = -1;
11238         inodedep->id_savedextsize = -1;
11239         inodedep->id_savednlink = -1;
11240         /*
11241          * If there were any rollbacks in the inode block, then it must be
11242          * marked dirty so that its will eventually get written back in
11243          * its correct form.
11244          */
11245         if (hadchanges)
11246                 bdirty(bp);
11247 bufwait:
11248         /*
11249          * Process any allocdirects that completed during the update.
11250          */
11251         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11252                 handle_allocdirect_partdone(adp, &wkhd);
11253         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11254                 handle_allocdirect_partdone(adp, &wkhd);
11255         /*
11256          * Process deallocations that were held pending until the
11257          * inode had been written to disk. Freeing of the inode
11258          * is delayed until after all blocks have been freed to
11259          * avoid creation of new <vfsid, inum, lbn> triples
11260          * before the old ones have been deleted.  Completely
11261          * unlinked inodes are not processed until the unlinked
11262          * inode list is written or the last reference is removed.
11263          */
11264         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11265                 freefile = handle_bufwait(inodedep, NULL);
11266                 if (freefile && !LIST_EMPTY(&wkhd)) {
11267                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11268                         freefile = NULL;
11269                 }
11270         }
11271         /*
11272          * Move rolled forward dependency completions to the bufwait list
11273          * now that those that were already written have been processed.
11274          */
11275         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11276                 panic("handle_written_inodeblock: bufwait but no changes");
11277         jwork_move(&inodedep->id_bufwait, &wkhd);
11278
11279         if (freefile != NULL) {
11280                 /*
11281                  * If the inode is goingaway it was never written.  Fake up
11282                  * the state here so free_inodedep() can succeed.
11283                  */
11284                 if (inodedep->id_state & GOINGAWAY)
11285                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11286                 if (free_inodedep(inodedep) == 0)
11287                         panic("handle_written_inodeblock: live inodedep %p",
11288                             inodedep);
11289                 add_to_worklist(&freefile->fx_list, 0);
11290                 return (0);
11291         }
11292
11293         /*
11294          * If no outstanding dependencies, free it.
11295          */
11296         if (free_inodedep(inodedep) ||
11297             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11298              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11299              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11300              LIST_FIRST(&inodedep->id_bufwait) == 0))
11301                 return (0);
11302         return (hadchanges);
11303 }
11304
11305 static int
11306 handle_written_indirdep(indirdep, bp, bpp)
11307         struct indirdep *indirdep;
11308         struct buf *bp;
11309         struct buf **bpp;
11310 {
11311         struct allocindir *aip;
11312         struct buf *sbp;
11313         int chgs;
11314
11315         if (indirdep->ir_state & GOINGAWAY)
11316                 panic("handle_written_indirdep: indirdep gone");
11317         if ((indirdep->ir_state & IOSTARTED) == 0)
11318                 panic("handle_written_indirdep: IO not started");
11319         chgs = 0;
11320         /*
11321          * If there were rollbacks revert them here.
11322          */
11323         if (indirdep->ir_saveddata) {
11324                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11325                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11326                         free(indirdep->ir_saveddata, M_INDIRDEP);
11327                         indirdep->ir_saveddata = NULL;
11328                 }
11329                 chgs = 1;
11330         }
11331         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11332         indirdep->ir_state |= ATTACHED;
11333         /*
11334          * Move allocindirs with written pointers to the completehd if
11335          * the indirdep's pointer is not yet written.  Otherwise
11336          * free them here.
11337          */
11338         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11339                 LIST_REMOVE(aip, ai_next);
11340                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11341                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11342                             ai_next);
11343                         newblk_freefrag(&aip->ai_block);
11344                         continue;
11345                 }
11346                 free_newblk(&aip->ai_block);
11347         }
11348         /*
11349          * Move allocindirs that have finished dependency processing from
11350          * the done list to the write list after updating the pointers.
11351          */
11352         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11353                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11354                         handle_allocindir_partdone(aip);
11355                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11356                                 panic("disk_write_complete: not gone");
11357                         chgs = 1;
11358                 }
11359         }
11360         /*
11361          * Preserve the indirdep if there were any changes or if it is not
11362          * yet valid on disk.
11363          */
11364         if (chgs) {
11365                 stat_indir_blk_ptrs++;
11366                 bdirty(bp);
11367                 return (1);
11368         }
11369         /*
11370          * If there were no changes we can discard the savedbp and detach
11371          * ourselves from the buf.  We are only carrying completed pointers
11372          * in this case.
11373          */
11374         sbp = indirdep->ir_savebp;
11375         sbp->b_flags |= B_INVAL | B_NOCACHE;
11376         indirdep->ir_savebp = NULL;
11377         indirdep->ir_bp = NULL;
11378         if (*bpp != NULL)
11379                 panic("handle_written_indirdep: bp already exists.");
11380         *bpp = sbp;
11381         /*
11382          * The indirdep may not be freed until its parent points at it.
11383          */
11384         if (indirdep->ir_state & DEPCOMPLETE)
11385                 free_indirdep(indirdep);
11386
11387         return (0);
11388 }
11389
11390 /*
11391  * Process a diradd entry after its dependent inode has been written.
11392  * This routine must be called with splbio interrupts blocked.
11393  */
11394 static void
11395 diradd_inode_written(dap, inodedep)
11396         struct diradd *dap;
11397         struct inodedep *inodedep;
11398 {
11399
11400         dap->da_state |= COMPLETE;
11401         complete_diradd(dap);
11402         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11403 }
11404
11405 /*
11406  * Returns true if the bmsafemap will have rollbacks when written.  Must
11407  * only be called with lk and the buf lock on the cg held.
11408  */
11409 static int
11410 bmsafemap_backgroundwrite(bmsafemap, bp)
11411         struct bmsafemap *bmsafemap;
11412         struct buf *bp;
11413 {
11414         int dirty;
11415
11416         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11417             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11418         /*
11419          * If we're initiating a background write we need to process the
11420          * rollbacks as they exist now, not as they exist when IO starts.
11421          * No other consumers will look at the contents of the shadowed
11422          * buf so this is safe to do here.
11423          */
11424         if (bp->b_xflags & BX_BKGRDMARKER)
11425                 initiate_write_bmsafemap(bmsafemap, bp);
11426
11427         return (dirty);
11428 }
11429
11430 /*
11431  * Re-apply an allocation when a cg write is complete.
11432  */
11433 static int
11434 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11435         struct jnewblk *jnewblk;
11436         struct fs *fs;
11437         struct cg *cgp;
11438         uint8_t *blksfree;
11439 {
11440         ufs1_daddr_t fragno;
11441         ufs2_daddr_t blkno;
11442         long cgbno, bbase;
11443         int frags, blk;
11444         int i;
11445
11446         frags = 0;
11447         cgbno = dtogd(fs, jnewblk->jn_blkno);
11448         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11449                 if (isclr(blksfree, cgbno + i))
11450                         panic("jnewblk_rollforward: re-allocated fragment");
11451                 frags++;
11452         }
11453         if (frags == fs->fs_frag) {
11454                 blkno = fragstoblks(fs, cgbno);
11455                 ffs_clrblock(fs, blksfree, (long)blkno);
11456                 ffs_clusteracct(fs, cgp, blkno, -1);
11457                 cgp->cg_cs.cs_nbfree--;
11458         } else {
11459                 bbase = cgbno - fragnum(fs, cgbno);
11460                 cgbno += jnewblk->jn_oldfrags;
11461                 /* If a complete block had been reassembled, account for it. */
11462                 fragno = fragstoblks(fs, bbase);
11463                 if (ffs_isblock(fs, blksfree, fragno)) {
11464                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11465                         ffs_clusteracct(fs, cgp, fragno, -1);
11466                         cgp->cg_cs.cs_nbfree--;
11467                 }
11468                 /* Decrement the old frags.  */
11469                 blk = blkmap(fs, blksfree, bbase);
11470                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11471                 /* Allocate the fragment */
11472                 for (i = 0; i < frags; i++)
11473                         clrbit(blksfree, cgbno + i);
11474                 cgp->cg_cs.cs_nffree -= frags;
11475                 /* Add back in counts associated with the new frags */
11476                 blk = blkmap(fs, blksfree, bbase);
11477                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11478         }
11479         return (frags);
11480 }
11481
11482 /*
11483  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11484  * changes if it's not a background write.  Set all written dependencies 
11485  * to DEPCOMPLETE and free the structure if possible.
11486  */
11487 static int
11488 handle_written_bmsafemap(bmsafemap, bp)
11489         struct bmsafemap *bmsafemap;
11490         struct buf *bp;
11491 {
11492         struct newblk *newblk;
11493         struct inodedep *inodedep;
11494         struct jaddref *jaddref, *jatmp;
11495         struct jnewblk *jnewblk, *jntmp;
11496         struct ufsmount *ump;
11497         uint8_t *inosused;
11498         uint8_t *blksfree;
11499         struct cg *cgp;
11500         struct fs *fs;
11501         ino_t ino;
11502         int chgs;
11503
11504         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11505                 panic("initiate_write_bmsafemap: Not started\n");
11506         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11507         chgs = 0;
11508         bmsafemap->sm_state &= ~IOSTARTED;
11509         /*
11510          * Release journal work that was waiting on the write.
11511          */
11512         handle_jwork(&bmsafemap->sm_freewr);
11513
11514         /*
11515          * Restore unwritten inode allocation pending jaddref writes.
11516          */
11517         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11518                 cgp = (struct cg *)bp->b_data;
11519                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11520                 inosused = cg_inosused(cgp);
11521                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11522                     ja_bmdeps, jatmp) {
11523                         if ((jaddref->ja_state & UNDONE) == 0)
11524                                 continue;
11525                         ino = jaddref->ja_ino % fs->fs_ipg;
11526                         if (isset(inosused, ino))
11527                                 panic("handle_written_bmsafemap: "
11528                                     "re-allocated inode");
11529                         if ((bp->b_xflags & BX_BKGRDMARKER) == 0) {
11530                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11531                                         cgp->cg_cs.cs_ndir++;
11532                                 cgp->cg_cs.cs_nifree--;
11533                                 setbit(inosused, ino);
11534                                 chgs = 1;
11535                         }
11536                         jaddref->ja_state &= ~UNDONE;
11537                         jaddref->ja_state |= ATTACHED;
11538                         free_jaddref(jaddref);
11539                 }
11540         }
11541         /*
11542          * Restore any block allocations which are pending journal writes.
11543          */
11544         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11545                 cgp = (struct cg *)bp->b_data;
11546                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11547                 blksfree = cg_blksfree(cgp);
11548                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11549                     jntmp) {
11550                         if ((jnewblk->jn_state & UNDONE) == 0)
11551                                 continue;
11552                         if ((bp->b_xflags & BX_BKGRDMARKER) == 0 &&
11553                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11554                                 chgs = 1;
11555                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11556                         jnewblk->jn_state |= ATTACHED;
11557                         free_jnewblk(jnewblk);
11558                 }
11559         }
11560         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11561                 newblk->nb_state |= DEPCOMPLETE;
11562                 newblk->nb_state &= ~ONDEPLIST;
11563                 newblk->nb_bmsafemap = NULL;
11564                 LIST_REMOVE(newblk, nb_deps);
11565                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11566                         handle_allocdirect_partdone(
11567                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11568                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11569                         handle_allocindir_partdone(
11570                             WK_ALLOCINDIR(&newblk->nb_list));
11571                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11572                         panic("handle_written_bmsafemap: Unexpected type: %s",
11573                             TYPENAME(newblk->nb_list.wk_type));
11574         }
11575         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11576                 inodedep->id_state |= DEPCOMPLETE;
11577                 inodedep->id_state &= ~ONDEPLIST;
11578                 LIST_REMOVE(inodedep, id_deps);
11579                 inodedep->id_bmsafemap = NULL;
11580         }
11581         LIST_REMOVE(bmsafemap, sm_next);
11582         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11583             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11584             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11585             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11586             LIST_EMPTY(&bmsafemap->sm_freehd)) {
11587                 LIST_REMOVE(bmsafemap, sm_hash);
11588                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11589                 return (0);
11590         }
11591         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11592         bdirty(bp);
11593         return (1);
11594 }
11595
11596 /*
11597  * Try to free a mkdir dependency.
11598  */
11599 static void
11600 complete_mkdir(mkdir)
11601         struct mkdir *mkdir;
11602 {
11603         struct diradd *dap;
11604
11605         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11606                 return;
11607         LIST_REMOVE(mkdir, md_mkdirs);
11608         dap = mkdir->md_diradd;
11609         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11610         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11611                 dap->da_state |= DEPCOMPLETE;
11612                 complete_diradd(dap);
11613         }
11614         WORKITEM_FREE(mkdir, D_MKDIR);
11615 }
11616
11617 /*
11618  * Handle the completion of a mkdir dependency.
11619  */
11620 static void
11621 handle_written_mkdir(mkdir, type)
11622         struct mkdir *mkdir;
11623         int type;
11624 {
11625
11626         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11627                 panic("handle_written_mkdir: bad type");
11628         mkdir->md_state |= COMPLETE;
11629         complete_mkdir(mkdir);
11630 }
11631
11632 static int
11633 free_pagedep(pagedep)
11634         struct pagedep *pagedep;
11635 {
11636         int i;
11637
11638         if (pagedep->pd_state & NEWBLOCK)
11639                 return (0);
11640         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11641                 return (0);
11642         for (i = 0; i < DAHASHSZ; i++)
11643                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11644                         return (0);
11645         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11646                 return (0);
11647         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11648                 return (0);
11649         if (pagedep->pd_state & ONWORKLIST)
11650                 WORKLIST_REMOVE(&pagedep->pd_list);
11651         LIST_REMOVE(pagedep, pd_hash);
11652         WORKITEM_FREE(pagedep, D_PAGEDEP);
11653
11654         return (1);
11655 }
11656
11657 /*
11658  * Called from within softdep_disk_write_complete above.
11659  * A write operation was just completed. Removed inodes can
11660  * now be freed and associated block pointers may be committed.
11661  * Note that this routine is always called from interrupt level
11662  * with further splbio interrupts blocked.
11663  */
11664 static int 
11665 handle_written_filepage(pagedep, bp)
11666         struct pagedep *pagedep;
11667         struct buf *bp;         /* buffer containing the written page */
11668 {
11669         struct dirrem *dirrem;
11670         struct diradd *dap, *nextdap;
11671         struct direct *ep;
11672         int i, chgs;
11673
11674         if ((pagedep->pd_state & IOSTARTED) == 0)
11675                 panic("handle_written_filepage: not started");
11676         pagedep->pd_state &= ~IOSTARTED;
11677         /*
11678          * Process any directory removals that have been committed.
11679          */
11680         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11681                 LIST_REMOVE(dirrem, dm_next);
11682                 dirrem->dm_state |= COMPLETE;
11683                 dirrem->dm_dirinum = pagedep->pd_ino;
11684                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11685                     ("handle_written_filepage: Journal entries not written."));
11686                 add_to_worklist(&dirrem->dm_list, 0);
11687         }
11688         /*
11689          * Free any directory additions that have been committed.
11690          * If it is a newly allocated block, we have to wait until
11691          * the on-disk directory inode claims the new block.
11692          */
11693         if ((pagedep->pd_state & NEWBLOCK) == 0)
11694                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11695                         free_diradd(dap, NULL);
11696         /*
11697          * Uncommitted directory entries must be restored.
11698          */
11699         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11700                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11701                      dap = nextdap) {
11702                         nextdap = LIST_NEXT(dap, da_pdlist);
11703                         if (dap->da_state & ATTACHED)
11704                                 panic("handle_written_filepage: attached");
11705                         ep = (struct direct *)
11706                             ((char *)bp->b_data + dap->da_offset);
11707                         ep->d_ino = dap->da_newinum;
11708                         dap->da_state &= ~UNDONE;
11709                         dap->da_state |= ATTACHED;
11710                         chgs = 1;
11711                         /*
11712                          * If the inode referenced by the directory has
11713                          * been written out, then the dependency can be
11714                          * moved to the pending list.
11715                          */
11716                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11717                                 LIST_REMOVE(dap, da_pdlist);
11718                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11719                                     da_pdlist);
11720                         }
11721                 }
11722         }
11723         /*
11724          * If there were any rollbacks in the directory, then it must be
11725          * marked dirty so that its will eventually get written back in
11726          * its correct form.
11727          */
11728         if (chgs) {
11729                 if ((bp->b_flags & B_DELWRI) == 0)
11730                         stat_dir_entry++;
11731                 bdirty(bp);
11732                 return (1);
11733         }
11734         /*
11735          * If we are not waiting for a new directory block to be
11736          * claimed by its inode, then the pagedep will be freed.
11737          * Otherwise it will remain to track any new entries on
11738          * the page in case they are fsync'ed.
11739          */
11740         free_pagedep(pagedep);
11741         return (0);
11742 }
11743
11744 /*
11745  * Writing back in-core inode structures.
11746  * 
11747  * The filesystem only accesses an inode's contents when it occupies an
11748  * "in-core" inode structure.  These "in-core" structures are separate from
11749  * the page frames used to cache inode blocks.  Only the latter are
11750  * transferred to/from the disk.  So, when the updated contents of the
11751  * "in-core" inode structure are copied to the corresponding in-memory inode
11752  * block, the dependencies are also transferred.  The following procedure is
11753  * called when copying a dirty "in-core" inode to a cached inode block.
11754  */
11755
11756 /*
11757  * Called when an inode is loaded from disk. If the effective link count
11758  * differed from the actual link count when it was last flushed, then we
11759  * need to ensure that the correct effective link count is put back.
11760  */
11761 void 
11762 softdep_load_inodeblock(ip)
11763         struct inode *ip;       /* the "in_core" copy of the inode */
11764 {
11765         struct inodedep *inodedep;
11766
11767         /*
11768          * Check for alternate nlink count.
11769          */
11770         ip->i_effnlink = ip->i_nlink;
11771         ACQUIRE_LOCK(&lk);
11772         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
11773             &inodedep) == 0) {
11774                 FREE_LOCK(&lk);
11775                 return;
11776         }
11777         ip->i_effnlink -= inodedep->id_nlinkdelta;
11778         FREE_LOCK(&lk);
11779 }
11780
11781 /*
11782  * This routine is called just before the "in-core" inode
11783  * information is to be copied to the in-memory inode block.
11784  * Recall that an inode block contains several inodes. If
11785  * the force flag is set, then the dependencies will be
11786  * cleared so that the update can always be made. Note that
11787  * the buffer is locked when this routine is called, so we
11788  * will never be in the middle of writing the inode block 
11789  * to disk.
11790  */
11791 void 
11792 softdep_update_inodeblock(ip, bp, waitfor)
11793         struct inode *ip;       /* the "in_core" copy of the inode */
11794         struct buf *bp;         /* the buffer containing the inode block */
11795         int waitfor;            /* nonzero => update must be allowed */
11796 {
11797         struct inodedep *inodedep;
11798         struct inoref *inoref;
11799         struct worklist *wk;
11800         struct mount *mp;
11801         struct buf *ibp;
11802         struct fs *fs;
11803         int error;
11804
11805         mp = UFSTOVFS(ip->i_ump);
11806         fs = ip->i_fs;
11807         /*
11808          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
11809          * does not have access to the in-core ip so must write directly into
11810          * the inode block buffer when setting freelink.
11811          */
11812         if (fs->fs_magic == FS_UFS1_MAGIC)
11813                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
11814                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
11815         else
11816                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
11817                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
11818         /*
11819          * If the effective link count is not equal to the actual link
11820          * count, then we must track the difference in an inodedep while
11821          * the inode is (potentially) tossed out of the cache. Otherwise,
11822          * if there is no existing inodedep, then there are no dependencies
11823          * to track.
11824          */
11825         ACQUIRE_LOCK(&lk);
11826 again:
11827         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11828                 FREE_LOCK(&lk);
11829                 if (ip->i_effnlink != ip->i_nlink)
11830                         panic("softdep_update_inodeblock: bad link count");
11831                 return;
11832         }
11833         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
11834                 panic("softdep_update_inodeblock: bad delta");
11835         /*
11836          * If we're flushing all dependencies we must also move any waiting
11837          * for journal writes onto the bufwait list prior to I/O.
11838          */
11839         if (waitfor) {
11840                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11841                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11842                             == DEPCOMPLETE) {
11843                                 jwait(&inoref->if_list, MNT_WAIT);
11844                                 goto again;
11845                         }
11846                 }
11847         }
11848         /*
11849          * Changes have been initiated. Anything depending on these
11850          * changes cannot occur until this inode has been written.
11851          */
11852         inodedep->id_state &= ~COMPLETE;
11853         if ((inodedep->id_state & ONWORKLIST) == 0)
11854                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
11855         /*
11856          * Any new dependencies associated with the incore inode must 
11857          * now be moved to the list associated with the buffer holding
11858          * the in-memory copy of the inode. Once merged process any
11859          * allocdirects that are completed by the merger.
11860          */
11861         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
11862         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
11863                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
11864                     NULL);
11865         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
11866         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
11867                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
11868                     NULL);
11869         /*
11870          * Now that the inode has been pushed into the buffer, the
11871          * operations dependent on the inode being written to disk
11872          * can be moved to the id_bufwait so that they will be
11873          * processed when the buffer I/O completes.
11874          */
11875         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
11876                 WORKLIST_REMOVE(wk);
11877                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
11878         }
11879         /*
11880          * Newly allocated inodes cannot be written until the bitmap
11881          * that allocates them have been written (indicated by
11882          * DEPCOMPLETE being set in id_state). If we are doing a
11883          * forced sync (e.g., an fsync on a file), we force the bitmap
11884          * to be written so that the update can be done.
11885          */
11886         if (waitfor == 0) {
11887                 FREE_LOCK(&lk);
11888                 return;
11889         }
11890 retry:
11891         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
11892                 FREE_LOCK(&lk);
11893                 return;
11894         }
11895         ibp = inodedep->id_bmsafemap->sm_buf;
11896         ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
11897         if (ibp == NULL) {
11898                 /*
11899                  * If ibp came back as NULL, the dependency could have been
11900                  * freed while we slept.  Look it up again, and check to see
11901                  * that it has completed.
11902                  */
11903                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
11904                         goto retry;
11905                 FREE_LOCK(&lk);
11906                 return;
11907         }
11908         FREE_LOCK(&lk);
11909         if ((error = bwrite(ibp)) != 0)
11910                 softdep_error("softdep_update_inodeblock: bwrite", error);
11911 }
11912
11913 /*
11914  * Merge the a new inode dependency list (such as id_newinoupdt) into an
11915  * old inode dependency list (such as id_inoupdt). This routine must be
11916  * called with splbio interrupts blocked.
11917  */
11918 static void
11919 merge_inode_lists(newlisthead, oldlisthead)
11920         struct allocdirectlst *newlisthead;
11921         struct allocdirectlst *oldlisthead;
11922 {
11923         struct allocdirect *listadp, *newadp;
11924
11925         newadp = TAILQ_FIRST(newlisthead);
11926         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
11927                 if (listadp->ad_offset < newadp->ad_offset) {
11928                         listadp = TAILQ_NEXT(listadp, ad_next);
11929                         continue;
11930                 }
11931                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
11932                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
11933                 if (listadp->ad_offset == newadp->ad_offset) {
11934                         allocdirect_merge(oldlisthead, newadp,
11935                             listadp);
11936                         listadp = newadp;
11937                 }
11938                 newadp = TAILQ_FIRST(newlisthead);
11939         }
11940         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
11941                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
11942                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
11943         }
11944 }
11945
11946 /*
11947  * If we are doing an fsync, then we must ensure that any directory
11948  * entries for the inode have been written after the inode gets to disk.
11949  */
11950 int
11951 softdep_fsync(vp)
11952         struct vnode *vp;       /* the "in_core" copy of the inode */
11953 {
11954         struct inodedep *inodedep;
11955         struct pagedep *pagedep;
11956         struct inoref *inoref;
11957         struct worklist *wk;
11958         struct diradd *dap;
11959         struct mount *mp;
11960         struct vnode *pvp;
11961         struct inode *ip;
11962         struct buf *bp;
11963         struct fs *fs;
11964         struct thread *td = curthread;
11965         int error, flushparent, pagedep_new_block;
11966         ino_t parentino;
11967         ufs_lbn_t lbn;
11968
11969         ip = VTOI(vp);
11970         fs = ip->i_fs;
11971         mp = vp->v_mount;
11972         ACQUIRE_LOCK(&lk);
11973 restart:
11974         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11975                 FREE_LOCK(&lk);
11976                 return (0);
11977         }
11978         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11979                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11980                     == DEPCOMPLETE) {
11981                         jwait(&inoref->if_list, MNT_WAIT);
11982                         goto restart;
11983                 }
11984         }
11985         if (!LIST_EMPTY(&inodedep->id_inowait) ||
11986             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
11987             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
11988             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
11989             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
11990                 panic("softdep_fsync: pending ops %p", inodedep);
11991         for (error = 0, flushparent = 0; ; ) {
11992                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
11993                         break;
11994                 if (wk->wk_type != D_DIRADD)
11995                         panic("softdep_fsync: Unexpected type %s",
11996                             TYPENAME(wk->wk_type));
11997                 dap = WK_DIRADD(wk);
11998                 /*
11999                  * Flush our parent if this directory entry has a MKDIR_PARENT
12000                  * dependency or is contained in a newly allocated block.
12001                  */
12002                 if (dap->da_state & DIRCHG)
12003                         pagedep = dap->da_previous->dm_pagedep;
12004                 else
12005                         pagedep = dap->da_pagedep;
12006                 parentino = pagedep->pd_ino;
12007                 lbn = pagedep->pd_lbn;
12008                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12009                         panic("softdep_fsync: dirty");
12010                 if ((dap->da_state & MKDIR_PARENT) ||
12011                     (pagedep->pd_state & NEWBLOCK))
12012                         flushparent = 1;
12013                 else
12014                         flushparent = 0;
12015                 /*
12016                  * If we are being fsync'ed as part of vgone'ing this vnode,
12017                  * then we will not be able to release and recover the
12018                  * vnode below, so we just have to give up on writing its
12019                  * directory entry out. It will eventually be written, just
12020                  * not now, but then the user was not asking to have it
12021                  * written, so we are not breaking any promises.
12022                  */
12023                 if (vp->v_iflag & VI_DOOMED)
12024                         break;
12025                 /*
12026                  * We prevent deadlock by always fetching inodes from the
12027                  * root, moving down the directory tree. Thus, when fetching
12028                  * our parent directory, we first try to get the lock. If
12029                  * that fails, we must unlock ourselves before requesting
12030                  * the lock on our parent. See the comment in ufs_lookup
12031                  * for details on possible races.
12032                  */
12033                 FREE_LOCK(&lk);
12034                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12035                     FFSV_FORCEINSMQ)) {
12036                         error = vfs_busy(mp, MBF_NOWAIT);
12037                         if (error != 0) {
12038                                 vfs_ref(mp);
12039                                 VOP_UNLOCK(vp, 0);
12040                                 error = vfs_busy(mp, 0);
12041                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12042                                 vfs_rel(mp);
12043                                 if (error != 0)
12044                                         return (ENOENT);
12045                                 if (vp->v_iflag & VI_DOOMED) {
12046                                         vfs_unbusy(mp);
12047                                         return (ENOENT);
12048                                 }
12049                         }
12050                         VOP_UNLOCK(vp, 0);
12051                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12052                             &pvp, FFSV_FORCEINSMQ);
12053                         vfs_unbusy(mp);
12054                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12055                         if (vp->v_iflag & VI_DOOMED) {
12056                                 if (error == 0)
12057                                         vput(pvp);
12058                                 error = ENOENT;
12059                         }
12060                         if (error != 0)
12061                                 return (error);
12062                 }
12063                 /*
12064                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12065                  * that are contained in direct blocks will be resolved by 
12066                  * doing a ffs_update. Pagedeps contained in indirect blocks
12067                  * may require a complete sync'ing of the directory. So, we
12068                  * try the cheap and fast ffs_update first, and if that fails,
12069                  * then we do the slower ffs_syncvnode of the directory.
12070                  */
12071                 if (flushparent) {
12072                         int locked;
12073
12074                         if ((error = ffs_update(pvp, 1)) != 0) {
12075                                 vput(pvp);
12076                                 return (error);
12077                         }
12078                         ACQUIRE_LOCK(&lk);
12079                         locked = 1;
12080                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12081                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12082                                         if (wk->wk_type != D_DIRADD)
12083                                                 panic("softdep_fsync: Unexpected type %s",
12084                                                       TYPENAME(wk->wk_type));
12085                                         dap = WK_DIRADD(wk);
12086                                         if (dap->da_state & DIRCHG)
12087                                                 pagedep = dap->da_previous->dm_pagedep;
12088                                         else
12089                                                 pagedep = dap->da_pagedep;
12090                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12091                                         FREE_LOCK(&lk);
12092                                         locked = 0;
12093                                         if (pagedep_new_block && (error =
12094                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12095                                                 vput(pvp);
12096                                                 return (error);
12097                                         }
12098                                 }
12099                         }
12100                         if (locked)
12101                                 FREE_LOCK(&lk);
12102                 }
12103                 /*
12104                  * Flush directory page containing the inode's name.
12105                  */
12106                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12107                     &bp);
12108                 if (error == 0)
12109                         error = bwrite(bp);
12110                 else
12111                         brelse(bp);
12112                 vput(pvp);
12113                 if (error != 0)
12114                         return (error);
12115                 ACQUIRE_LOCK(&lk);
12116                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12117                         break;
12118         }
12119         FREE_LOCK(&lk);
12120         return (0);
12121 }
12122
12123 /*
12124  * Flush all the dirty bitmaps associated with the block device
12125  * before flushing the rest of the dirty blocks so as to reduce
12126  * the number of dependencies that will have to be rolled back.
12127  *
12128  * XXX Unused?
12129  */
12130 void
12131 softdep_fsync_mountdev(vp)
12132         struct vnode *vp;
12133 {
12134         struct buf *bp, *nbp;
12135         struct worklist *wk;
12136         struct bufobj *bo;
12137
12138         if (!vn_isdisk(vp, NULL))
12139                 panic("softdep_fsync_mountdev: vnode not a disk");
12140         bo = &vp->v_bufobj;
12141 restart:
12142         BO_LOCK(bo);
12143         ACQUIRE_LOCK(&lk);
12144         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12145                 /* 
12146                  * If it is already scheduled, skip to the next buffer.
12147                  */
12148                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12149                         continue;
12150
12151                 if ((bp->b_flags & B_DELWRI) == 0)
12152                         panic("softdep_fsync_mountdev: not dirty");
12153                 /*
12154                  * We are only interested in bitmaps with outstanding
12155                  * dependencies.
12156                  */
12157                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12158                     wk->wk_type != D_BMSAFEMAP ||
12159                     (bp->b_vflags & BV_BKGRDINPROG)) {
12160                         BUF_UNLOCK(bp);
12161                         continue;
12162                 }
12163                 FREE_LOCK(&lk);
12164                 BO_UNLOCK(bo);
12165                 bremfree(bp);
12166                 (void) bawrite(bp);
12167                 goto restart;
12168         }
12169         FREE_LOCK(&lk);
12170         drain_output(vp);
12171         BO_UNLOCK(bo);
12172 }
12173
12174 /*
12175  * Sync all cylinder groups that were dirty at the time this function is
12176  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12177  * is used to flush freedep activity that may be holding up writes to a
12178  * indirect block.
12179  */
12180 static int
12181 sync_cgs(mp, waitfor)
12182         struct mount *mp;
12183         int waitfor;
12184 {
12185         struct bmsafemap *bmsafemap;
12186         struct bmsafemap *sentinel;
12187         struct ufsmount *ump;
12188         struct buf *bp;
12189         int error;
12190
12191         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12192         sentinel->sm_cg = -1;
12193         ump = VFSTOUFS(mp);
12194         error = 0;
12195         ACQUIRE_LOCK(&lk);
12196         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12197         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12198             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12199                 /* Skip sentinels and cgs with no work to release. */
12200                 if (bmsafemap->sm_cg == -1 ||
12201                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12202                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12203                         LIST_REMOVE(sentinel, sm_next);
12204                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12205                         continue;
12206                 }
12207                 /*
12208                  * If we don't get the lock and we're waiting try again, if
12209                  * not move on to the next buf and try to sync it.
12210                  */
12211                 bp = getdirtybuf(bmsafemap->sm_buf, &lk, waitfor);
12212                 if (bp == NULL && waitfor == MNT_WAIT)
12213                         continue;
12214                 LIST_REMOVE(sentinel, sm_next);
12215                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12216                 if (bp == NULL)
12217                         continue;
12218                 FREE_LOCK(&lk);
12219                 if (waitfor == MNT_NOWAIT)
12220                         bawrite(bp);
12221                 else
12222                         error = bwrite(bp);
12223                 ACQUIRE_LOCK(&lk);
12224                 if (error)
12225                         break;
12226         }
12227         LIST_REMOVE(sentinel, sm_next);
12228         FREE_LOCK(&lk);
12229         free(sentinel, M_BMSAFEMAP);
12230         return (error);
12231 }
12232
12233 /*
12234  * This routine is called when we are trying to synchronously flush a
12235  * file. This routine must eliminate any filesystem metadata dependencies
12236  * so that the syncing routine can succeed.
12237  */
12238 int
12239 softdep_sync_metadata(struct vnode *vp)
12240 {
12241         int error;
12242
12243         /*
12244          * Ensure that any direct block dependencies have been cleared,
12245          * truncations are started, and inode references are journaled.
12246          */
12247         ACQUIRE_LOCK(&lk);
12248         /*
12249          * Write all journal records to prevent rollbacks on devvp.
12250          */
12251         if (vp->v_type == VCHR)
12252                 softdep_flushjournal(vp->v_mount);
12253         error = flush_inodedep_deps(vp, vp->v_mount, VTOI(vp)->i_number);
12254         /*
12255          * Ensure that all truncates are written so we won't find deps on
12256          * indirect blocks.
12257          */
12258         process_truncates(vp);
12259         FREE_LOCK(&lk);
12260
12261         return (error);
12262 }
12263
12264 /*
12265  * This routine is called when we are attempting to sync a buf with
12266  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12267  * other IO it can but returns EBUSY if the buffer is not yet able to
12268  * be written.  Dependencies which will not cause rollbacks will always
12269  * return 0.
12270  */
12271 int
12272 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12273 {
12274         struct indirdep *indirdep;
12275         struct pagedep *pagedep;
12276         struct allocindir *aip;
12277         struct newblk *newblk;
12278         struct buf *nbp;
12279         struct worklist *wk;
12280         int i, error;
12281
12282         /*
12283          * For VCHR we just don't want to force flush any dependencies that
12284          * will cause rollbacks.
12285          */
12286         if (vp->v_type == VCHR) {
12287                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12288                         return (EBUSY);
12289                 return (0);
12290         }
12291         ACQUIRE_LOCK(&lk);
12292         /*
12293          * As we hold the buffer locked, none of its dependencies
12294          * will disappear.
12295          */
12296         error = 0;
12297 top:
12298         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12299                 switch (wk->wk_type) {
12300
12301                 case D_ALLOCDIRECT:
12302                 case D_ALLOCINDIR:
12303                         newblk = WK_NEWBLK(wk);
12304                         if (newblk->nb_jnewblk != NULL) {
12305                                 if (waitfor == MNT_NOWAIT) {
12306                                         error = EBUSY;
12307                                         goto out_unlock;
12308                                 }
12309                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12310                                 goto top;
12311                         }
12312                         if (newblk->nb_state & DEPCOMPLETE ||
12313                             waitfor == MNT_NOWAIT)
12314                                 continue;
12315                         nbp = newblk->nb_bmsafemap->sm_buf;
12316                         nbp = getdirtybuf(nbp, &lk, waitfor);
12317                         if (nbp == NULL)
12318                                 goto top;
12319                         FREE_LOCK(&lk);
12320                         if ((error = bwrite(nbp)) != 0)
12321                                 goto out;
12322                         ACQUIRE_LOCK(&lk);
12323                         continue;
12324
12325                 case D_INDIRDEP:
12326                         indirdep = WK_INDIRDEP(wk);
12327                         if (waitfor == MNT_NOWAIT) {
12328                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12329                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12330                                         error = EBUSY;
12331                                         goto out_unlock;
12332                                 }
12333                         }
12334                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12335                                 panic("softdep_sync_buf: truncation pending.");
12336                 restart:
12337                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12338                                 newblk = (struct newblk *)aip;
12339                                 if (newblk->nb_jnewblk != NULL) {
12340                                         jwait(&newblk->nb_jnewblk->jn_list,
12341                                             waitfor);
12342                                         goto restart;
12343                                 }
12344                                 if (newblk->nb_state & DEPCOMPLETE)
12345                                         continue;
12346                                 nbp = newblk->nb_bmsafemap->sm_buf;
12347                                 nbp = getdirtybuf(nbp, &lk, waitfor);
12348                                 if (nbp == NULL)
12349                                         goto restart;
12350                                 FREE_LOCK(&lk);
12351                                 if ((error = bwrite(nbp)) != 0)
12352                                         goto out;
12353                                 ACQUIRE_LOCK(&lk);
12354                                 goto restart;
12355                         }
12356                         continue;
12357
12358                 case D_PAGEDEP:
12359                         /*
12360                          * Only flush directory entries in synchronous passes.
12361                          */
12362                         if (waitfor != MNT_WAIT) {
12363                                 error = EBUSY;
12364                                 goto out_unlock;
12365                         }
12366                         /*
12367                          * While syncing snapshots, we must allow recursive
12368                          * lookups.
12369                          */
12370                         BUF_AREC(bp);
12371                         /*
12372                          * We are trying to sync a directory that may
12373                          * have dependencies on both its own metadata
12374                          * and/or dependencies on the inodes of any
12375                          * recently allocated files. We walk its diradd
12376                          * lists pushing out the associated inode.
12377                          */
12378                         pagedep = WK_PAGEDEP(wk);
12379                         for (i = 0; i < DAHASHSZ; i++) {
12380                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12381                                         continue;
12382                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12383                                     &pagedep->pd_diraddhd[i]))) {
12384                                         BUF_NOREC(bp);
12385                                         goto out_unlock;
12386                                 }
12387                         }
12388                         BUF_NOREC(bp);
12389                         continue;
12390
12391                 case D_FREEWORK:
12392                 case D_FREEDEP:
12393                 case D_JSEGDEP:
12394                 case D_JNEWBLK:
12395                         continue;
12396
12397                 default:
12398                         panic("softdep_sync_buf: Unknown type %s",
12399                             TYPENAME(wk->wk_type));
12400                         /* NOTREACHED */
12401                 }
12402         }
12403 out_unlock:
12404         FREE_LOCK(&lk);
12405 out:
12406         return (error);
12407 }
12408
12409 /*
12410  * Flush the dependencies associated with an inodedep.
12411  * Called with splbio blocked.
12412  */
12413 static int
12414 flush_inodedep_deps(vp, mp, ino)
12415         struct vnode *vp;
12416         struct mount *mp;
12417         ino_t ino;
12418 {
12419         struct inodedep *inodedep;
12420         struct inoref *inoref;
12421         int error, waitfor;
12422
12423         /*
12424          * This work is done in two passes. The first pass grabs most
12425          * of the buffers and begins asynchronously writing them. The
12426          * only way to wait for these asynchronous writes is to sleep
12427          * on the filesystem vnode which may stay busy for a long time
12428          * if the filesystem is active. So, instead, we make a second
12429          * pass over the dependencies blocking on each write. In the
12430          * usual case we will be blocking against a write that we
12431          * initiated, so when it is done the dependency will have been
12432          * resolved. Thus the second pass is expected to end quickly.
12433          * We give a brief window at the top of the loop to allow
12434          * any pending I/O to complete.
12435          */
12436         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12437                 if (error)
12438                         return (error);
12439                 FREE_LOCK(&lk);
12440                 ACQUIRE_LOCK(&lk);
12441 restart:
12442                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12443                         return (0);
12444                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12445                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12446                             == DEPCOMPLETE) {
12447                                 jwait(&inoref->if_list, MNT_WAIT);
12448                                 goto restart;
12449                         }
12450                 }
12451                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12452                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12453                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12454                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12455                         continue;
12456                 /*
12457                  * If pass2, we are done, otherwise do pass 2.
12458                  */
12459                 if (waitfor == MNT_WAIT)
12460                         break;
12461                 waitfor = MNT_WAIT;
12462         }
12463         /*
12464          * Try freeing inodedep in case all dependencies have been removed.
12465          */
12466         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12467                 (void) free_inodedep(inodedep);
12468         return (0);
12469 }
12470
12471 /*
12472  * Flush an inode dependency list.
12473  * Called with splbio blocked.
12474  */
12475 static int
12476 flush_deplist(listhead, waitfor, errorp)
12477         struct allocdirectlst *listhead;
12478         int waitfor;
12479         int *errorp;
12480 {
12481         struct allocdirect *adp;
12482         struct newblk *newblk;
12483         struct buf *bp;
12484
12485         mtx_assert(&lk, MA_OWNED);
12486         TAILQ_FOREACH(adp, listhead, ad_next) {
12487                 newblk = (struct newblk *)adp;
12488                 if (newblk->nb_jnewblk != NULL) {
12489                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12490                         return (1);
12491                 }
12492                 if (newblk->nb_state & DEPCOMPLETE)
12493                         continue;
12494                 bp = newblk->nb_bmsafemap->sm_buf;
12495                 bp = getdirtybuf(bp, &lk, waitfor);
12496                 if (bp == NULL) {
12497                         if (waitfor == MNT_NOWAIT)
12498                                 continue;
12499                         return (1);
12500                 }
12501                 FREE_LOCK(&lk);
12502                 if (waitfor == MNT_NOWAIT)
12503                         bawrite(bp);
12504                 else 
12505                         *errorp = bwrite(bp);
12506                 ACQUIRE_LOCK(&lk);
12507                 return (1);
12508         }
12509         return (0);
12510 }
12511
12512 /*
12513  * Flush dependencies associated with an allocdirect block.
12514  */
12515 static int
12516 flush_newblk_dep(vp, mp, lbn)
12517         struct vnode *vp;
12518         struct mount *mp;
12519         ufs_lbn_t lbn;
12520 {
12521         struct newblk *newblk;
12522         struct bufobj *bo;
12523         struct inode *ip;
12524         struct buf *bp;
12525         ufs2_daddr_t blkno;
12526         int error;
12527
12528         error = 0;
12529         bo = &vp->v_bufobj;
12530         ip = VTOI(vp);
12531         blkno = DIP(ip, i_db[lbn]);
12532         if (blkno == 0)
12533                 panic("flush_newblk_dep: Missing block");
12534         ACQUIRE_LOCK(&lk);
12535         /*
12536          * Loop until all dependencies related to this block are satisfied.
12537          * We must be careful to restart after each sleep in case a write
12538          * completes some part of this process for us.
12539          */
12540         for (;;) {
12541                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12542                         FREE_LOCK(&lk);
12543                         break;
12544                 }
12545                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12546                         panic("flush_newblk_deps: Bad newblk %p", newblk);
12547                 /*
12548                  * Flush the journal.
12549                  */
12550                 if (newblk->nb_jnewblk != NULL) {
12551                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12552                         continue;
12553                 }
12554                 /*
12555                  * Write the bitmap dependency.
12556                  */
12557                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12558                         bp = newblk->nb_bmsafemap->sm_buf;
12559                         bp = getdirtybuf(bp, &lk, MNT_WAIT);
12560                         if (bp == NULL)
12561                                 continue;
12562                         FREE_LOCK(&lk);
12563                         error = bwrite(bp);
12564                         if (error)
12565                                 break;
12566                         ACQUIRE_LOCK(&lk);
12567                         continue;
12568                 }
12569                 /*
12570                  * Write the buffer.
12571                  */
12572                 FREE_LOCK(&lk);
12573                 BO_LOCK(bo);
12574                 bp = gbincore(bo, lbn);
12575                 if (bp != NULL) {
12576                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12577                             LK_INTERLOCK, BO_MTX(bo));
12578                         if (error == ENOLCK) {
12579                                 ACQUIRE_LOCK(&lk);
12580                                 error = 0;
12581                                 continue; /* Slept, retry */
12582                         }
12583                         if (error != 0)
12584                                 break;  /* Failed */
12585                         if (bp->b_flags & B_DELWRI) {
12586                                 bremfree(bp);
12587                                 error = bwrite(bp);
12588                                 if (error)
12589                                         break;
12590                         } else
12591                                 BUF_UNLOCK(bp);
12592                 } else
12593                         BO_UNLOCK(bo);
12594                 /*
12595                  * We have to wait for the direct pointers to
12596                  * point at the newdirblk before the dependency
12597                  * will go away.
12598                  */
12599                 error = ffs_update(vp, 1);
12600                 if (error)
12601                         break;
12602                 ACQUIRE_LOCK(&lk);
12603         }
12604         return (error);
12605 }
12606
12607 /*
12608  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12609  * Called with splbio blocked.
12610  */
12611 static int
12612 flush_pagedep_deps(pvp, mp, diraddhdp)
12613         struct vnode *pvp;
12614         struct mount *mp;
12615         struct diraddhd *diraddhdp;
12616 {
12617         struct inodedep *inodedep;
12618         struct inoref *inoref;
12619         struct ufsmount *ump;
12620         struct diradd *dap;
12621         struct vnode *vp;
12622         int error = 0;
12623         struct buf *bp;
12624         ino_t inum;
12625         struct diraddhd unfinished;
12626
12627         LIST_INIT(&unfinished);
12628         ump = VFSTOUFS(mp);
12629 restart:
12630         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12631                 /*
12632                  * Flush ourselves if this directory entry
12633                  * has a MKDIR_PARENT dependency.
12634                  */
12635                 if (dap->da_state & MKDIR_PARENT) {
12636                         FREE_LOCK(&lk);
12637                         if ((error = ffs_update(pvp, 1)) != 0)
12638                                 break;
12639                         ACQUIRE_LOCK(&lk);
12640                         /*
12641                          * If that cleared dependencies, go on to next.
12642                          */
12643                         if (dap != LIST_FIRST(diraddhdp))
12644                                 continue;
12645                         /*
12646                          * All MKDIR_PARENT dependencies and all the
12647                          * NEWBLOCK pagedeps that are contained in direct
12648                          * blocks were resolved by doing above ffs_update.
12649                          * Pagedeps contained in indirect blocks may
12650                          * require a complete sync'ing of the directory.
12651                          * We are in the midst of doing a complete sync,
12652                          * so if they are not resolved in this pass we
12653                          * defer them for now as they will be sync'ed by
12654                          * our caller shortly.
12655                          */
12656                         LIST_REMOVE(dap, da_pdlist);
12657                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
12658                         continue;
12659                 }
12660                 /*
12661                  * A newly allocated directory must have its "." and
12662                  * ".." entries written out before its name can be
12663                  * committed in its parent. 
12664                  */
12665                 inum = dap->da_newinum;
12666                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12667                         panic("flush_pagedep_deps: lost inode1");
12668                 /*
12669                  * Wait for any pending journal adds to complete so we don't
12670                  * cause rollbacks while syncing.
12671                  */
12672                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12673                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12674                             == DEPCOMPLETE) {
12675                                 jwait(&inoref->if_list, MNT_WAIT);
12676                                 goto restart;
12677                         }
12678                 }
12679                 if (dap->da_state & MKDIR_BODY) {
12680                         FREE_LOCK(&lk);
12681                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12682                             FFSV_FORCEINSMQ)))
12683                                 break;
12684                         error = flush_newblk_dep(vp, mp, 0);
12685                         /*
12686                          * If we still have the dependency we might need to
12687                          * update the vnode to sync the new link count to
12688                          * disk.
12689                          */
12690                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
12691                                 error = ffs_update(vp, 1);
12692                         vput(vp);
12693                         if (error != 0)
12694                                 break;
12695                         ACQUIRE_LOCK(&lk);
12696                         /*
12697                          * If that cleared dependencies, go on to next.
12698                          */
12699                         if (dap != LIST_FIRST(diraddhdp))
12700                                 continue;
12701                         if (dap->da_state & MKDIR_BODY) {
12702                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
12703                                     &inodedep);
12704                                 panic("flush_pagedep_deps: MKDIR_BODY "
12705                                     "inodedep %p dap %p vp %p",
12706                                     inodedep, dap, vp);
12707                         }
12708                 }
12709                 /*
12710                  * Flush the inode on which the directory entry depends.
12711                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12712                  * the only remaining dependency is that the updated inode
12713                  * count must get pushed to disk. The inode has already
12714                  * been pushed into its inode buffer (via VOP_UPDATE) at
12715                  * the time of the reference count change. So we need only
12716                  * locate that buffer, ensure that there will be no rollback
12717                  * caused by a bitmap dependency, then write the inode buffer.
12718                  */
12719 retry:
12720                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12721                         panic("flush_pagedep_deps: lost inode");
12722                 /*
12723                  * If the inode still has bitmap dependencies,
12724                  * push them to disk.
12725                  */
12726                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12727                         bp = inodedep->id_bmsafemap->sm_buf;
12728                         bp = getdirtybuf(bp, &lk, MNT_WAIT);
12729                         if (bp == NULL)
12730                                 goto retry;
12731                         FREE_LOCK(&lk);
12732                         if ((error = bwrite(bp)) != 0)
12733                                 break;
12734                         ACQUIRE_LOCK(&lk);
12735                         if (dap != LIST_FIRST(diraddhdp))
12736                                 continue;
12737                 }
12738                 /*
12739                  * If the inode is still sitting in a buffer waiting
12740                  * to be written or waiting for the link count to be
12741                  * adjusted update it here to flush it to disk.
12742                  */
12743                 if (dap == LIST_FIRST(diraddhdp)) {
12744                         FREE_LOCK(&lk);
12745                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12746                             FFSV_FORCEINSMQ)))
12747                                 break;
12748                         error = ffs_update(vp, 1);
12749                         vput(vp);
12750                         if (error)
12751                                 break;
12752                         ACQUIRE_LOCK(&lk);
12753                 }
12754                 /*
12755                  * If we have failed to get rid of all the dependencies
12756                  * then something is seriously wrong.
12757                  */
12758                 if (dap == LIST_FIRST(diraddhdp)) {
12759                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
12760                         panic("flush_pagedep_deps: failed to flush " 
12761                             "inodedep %p ino %d dap %p", inodedep, inum, dap);
12762                 }
12763         }
12764         if (error)
12765                 ACQUIRE_LOCK(&lk);
12766         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
12767                 LIST_REMOVE(dap, da_pdlist);
12768                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
12769         }
12770         return (error);
12771 }
12772
12773 /*
12774  * A large burst of file addition or deletion activity can drive the
12775  * memory load excessively high. First attempt to slow things down
12776  * using the techniques below. If that fails, this routine requests
12777  * the offending operations to fall back to running synchronously
12778  * until the memory load returns to a reasonable level.
12779  */
12780 int
12781 softdep_slowdown(vp)
12782         struct vnode *vp;
12783 {
12784         struct ufsmount *ump;
12785         int jlow;
12786         int max_softdeps_hard;
12787
12788         ACQUIRE_LOCK(&lk);
12789         jlow = 0;
12790         /*
12791          * Check for journal space if needed.
12792          */
12793         if (DOINGSUJ(vp)) {
12794                 ump = VFSTOUFS(vp->v_mount);
12795                 if (journal_space(ump, 0) == 0)
12796                         jlow = 1;
12797         }
12798         max_softdeps_hard = max_softdeps * 11 / 10;
12799         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
12800             dep_current[D_INODEDEP] < max_softdeps_hard &&
12801             VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps &&
12802             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0) {
12803                 FREE_LOCK(&lk);
12804                 return (0);
12805         }
12806         if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps || jlow)
12807                 softdep_speedup();
12808         stat_sync_limit_hit += 1;
12809         FREE_LOCK(&lk);
12810         if (DOINGSUJ(vp))
12811                 return (0);
12812         return (1);
12813 }
12814
12815 /*
12816  * Called by the allocation routines when they are about to fail
12817  * in the hope that we can free up the requested resource (inodes
12818  * or disk space).
12819  * 
12820  * First check to see if the work list has anything on it. If it has,
12821  * clean up entries until we successfully free the requested resource.
12822  * Because this process holds inodes locked, we cannot handle any remove
12823  * requests that might block on a locked inode as that could lead to
12824  * deadlock. If the worklist yields none of the requested resource,
12825  * start syncing out vnodes to free up the needed space.
12826  */
12827 int
12828 softdep_request_cleanup(fs, vp, cred, resource)
12829         struct fs *fs;
12830         struct vnode *vp;
12831         struct ucred *cred;
12832         int resource;
12833 {
12834         struct ufsmount *ump;
12835         struct mount *mp;
12836         struct vnode *lvp, *mvp;
12837         long starttime;
12838         ufs2_daddr_t needed;
12839         int error;
12840
12841         /*
12842          * If we are being called because of a process doing a
12843          * copy-on-write, then it is not safe to process any
12844          * worklist items as we will recurse into the copyonwrite
12845          * routine.  This will result in an incoherent snapshot.
12846          * If the vnode that we hold is a snapshot, we must avoid
12847          * handling other resources that could cause deadlock.
12848          */
12849         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
12850                 return (0);
12851
12852         if (resource == FLUSH_BLOCKS_WAIT)
12853                 stat_cleanup_blkrequests += 1;
12854         else
12855                 stat_cleanup_inorequests += 1;
12856
12857         mp = vp->v_mount;
12858         ump = VFSTOUFS(mp);
12859         mtx_assert(UFS_MTX(ump), MA_OWNED);
12860         UFS_UNLOCK(ump);
12861         error = ffs_update(vp, 1);
12862         if (error != 0) {
12863                 UFS_LOCK(ump);
12864                 return (0);
12865         }
12866         /*
12867          * If we are in need of resources, consider pausing for
12868          * tickdelay to give ourselves some breathing room.
12869          */
12870         ACQUIRE_LOCK(&lk);
12871         process_removes(vp);
12872         process_truncates(vp);
12873         request_cleanup(UFSTOVFS(ump), resource);
12874         FREE_LOCK(&lk);
12875         /*
12876          * Now clean up at least as many resources as we will need.
12877          *
12878          * When requested to clean up inodes, the number that are needed
12879          * is set by the number of simultaneous writers (mnt_writeopcount)
12880          * plus a bit of slop (2) in case some more writers show up while
12881          * we are cleaning.
12882          *
12883          * When requested to free up space, the amount of space that
12884          * we need is enough blocks to allocate a full-sized segment
12885          * (fs_contigsumsize). The number of such segments that will
12886          * be needed is set by the number of simultaneous writers
12887          * (mnt_writeopcount) plus a bit of slop (2) in case some more
12888          * writers show up while we are cleaning.
12889          *
12890          * Additionally, if we are unpriviledged and allocating space,
12891          * we need to ensure that we clean up enough blocks to get the
12892          * needed number of blocks over the threshhold of the minimum
12893          * number of blocks required to be kept free by the filesystem
12894          * (fs_minfree).
12895          */
12896         if (resource == FLUSH_INODES_WAIT) {
12897                 needed = vp->v_mount->mnt_writeopcount + 2;
12898         } else if (resource == FLUSH_BLOCKS_WAIT) {
12899                 needed = (vp->v_mount->mnt_writeopcount + 2) *
12900                     fs->fs_contigsumsize;
12901                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
12902                         needed += fragstoblks(fs,
12903                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
12904                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
12905         } else {
12906                 UFS_LOCK(ump);
12907                 printf("softdep_request_cleanup: Unknown resource type %d\n",
12908                     resource);
12909                 return (0);
12910         }
12911         starttime = time_second;
12912 retry:
12913         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
12914             fs->fs_cstotal.cs_nbfree <= needed) ||
12915             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12916             fs->fs_cstotal.cs_nifree <= needed)) {
12917                 ACQUIRE_LOCK(&lk);
12918                 if (ump->softdep_on_worklist > 0 &&
12919                     process_worklist_item(UFSTOVFS(ump),
12920                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
12921                         stat_worklist_push += 1;
12922                 FREE_LOCK(&lk);
12923         }
12924         /*
12925          * If we still need resources and there are no more worklist
12926          * entries to process to obtain them, we have to start flushing
12927          * the dirty vnodes to force the release of additional requests
12928          * to the worklist that we can then process to reap addition
12929          * resources. We walk the vnodes associated with the mount point
12930          * until we get the needed worklist requests that we can reap.
12931          */
12932         if ((resource == FLUSH_BLOCKS_WAIT && 
12933              fs->fs_cstotal.cs_nbfree <= needed) ||
12934             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12935              fs->fs_cstotal.cs_nifree <= needed)) {
12936                 MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
12937                         if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
12938                                 VI_UNLOCK(lvp);
12939                                 continue;
12940                         }
12941                         if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
12942                             curthread))
12943                                 continue;
12944                         if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
12945                                 vput(lvp);
12946                                 continue;
12947                         }
12948                         (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
12949                         vput(lvp);
12950                 }
12951                 lvp = ump->um_devvp;
12952                 if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
12953                         VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
12954                         VOP_UNLOCK(lvp, 0);
12955                 }
12956                 if (ump->softdep_on_worklist > 0) {
12957                         stat_cleanup_retries += 1;
12958                         goto retry;
12959                 }
12960                 stat_cleanup_failures += 1;
12961         }
12962         if (time_second - starttime > stat_cleanup_high_delay)
12963                 stat_cleanup_high_delay = time_second - starttime;
12964         UFS_LOCK(ump);
12965         return (1);
12966 }
12967
12968 /*
12969  * If memory utilization has gotten too high, deliberately slow things
12970  * down and speed up the I/O processing.
12971  */
12972 extern struct thread *syncertd;
12973 static int
12974 request_cleanup(mp, resource)
12975         struct mount *mp;
12976         int resource;
12977 {
12978         struct thread *td = curthread;
12979         struct ufsmount *ump;
12980
12981         mtx_assert(&lk, MA_OWNED);
12982         /*
12983          * We never hold up the filesystem syncer or buf daemon.
12984          */
12985         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
12986                 return (0);
12987         ump = VFSTOUFS(mp);
12988         /*
12989          * First check to see if the work list has gotten backlogged.
12990          * If it has, co-opt this process to help clean up two entries.
12991          * Because this process may hold inodes locked, we cannot
12992          * handle any remove requests that might block on a locked
12993          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
12994          * to avoid recursively processing the worklist.
12995          */
12996         if (ump->softdep_on_worklist > max_softdeps / 10) {
12997                 td->td_pflags |= TDP_SOFTDEP;
12998                 process_worklist_item(mp, 2, LK_NOWAIT);
12999                 td->td_pflags &= ~TDP_SOFTDEP;
13000                 stat_worklist_push += 2;
13001                 return(1);
13002         }
13003         /*
13004          * Next, we attempt to speed up the syncer process. If that
13005          * is successful, then we allow the process to continue.
13006          */
13007         if (softdep_speedup() &&
13008             resource != FLUSH_BLOCKS_WAIT &&
13009             resource != FLUSH_INODES_WAIT)
13010                 return(0);
13011         /*
13012          * If we are resource constrained on inode dependencies, try
13013          * flushing some dirty inodes. Otherwise, we are constrained
13014          * by file deletions, so try accelerating flushes of directories
13015          * with removal dependencies. We would like to do the cleanup
13016          * here, but we probably hold an inode locked at this point and 
13017          * that might deadlock against one that we try to clean. So,
13018          * the best that we can do is request the syncer daemon to do
13019          * the cleanup for us.
13020          */
13021         switch (resource) {
13022
13023         case FLUSH_INODES:
13024         case FLUSH_INODES_WAIT:
13025                 stat_ino_limit_push += 1;
13026                 req_clear_inodedeps += 1;
13027                 stat_countp = &stat_ino_limit_hit;
13028                 break;
13029
13030         case FLUSH_BLOCKS:
13031         case FLUSH_BLOCKS_WAIT:
13032                 stat_blk_limit_push += 1;
13033                 req_clear_remove += 1;
13034                 stat_countp = &stat_blk_limit_hit;
13035                 break;
13036
13037         default:
13038                 panic("request_cleanup: unknown type");
13039         }
13040         /*
13041          * Hopefully the syncer daemon will catch up and awaken us.
13042          * We wait at most tickdelay before proceeding in any case.
13043          */
13044         proc_waiting += 1;
13045         if (callout_pending(&softdep_callout) == FALSE)
13046                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13047                     pause_timer, 0);
13048
13049         msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13050         proc_waiting -= 1;
13051         return (1);
13052 }
13053
13054 /*
13055  * Awaken processes pausing in request_cleanup and clear proc_waiting
13056  * to indicate that there is no longer a timer running.
13057  */
13058 static void
13059 pause_timer(arg)
13060         void *arg;
13061 {
13062
13063         /*
13064          * The callout_ API has acquired mtx and will hold it around this
13065          * function call.
13066          */
13067         *stat_countp += 1;
13068         wakeup_one(&proc_waiting);
13069         if (proc_waiting > 0)
13070                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13071                     pause_timer, 0);
13072 }
13073
13074 /*
13075  * Flush out a directory with at least one removal dependency in an effort to
13076  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13077  */
13078 static void
13079 clear_remove(td)
13080         struct thread *td;
13081 {
13082         struct pagedep_hashhead *pagedephd;
13083         struct pagedep *pagedep;
13084         static int next = 0;
13085         struct mount *mp;
13086         struct vnode *vp;
13087         struct bufobj *bo;
13088         int error, cnt;
13089         ino_t ino;
13090
13091         mtx_assert(&lk, MA_OWNED);
13092
13093         for (cnt = 0; cnt <= pagedep_hash; cnt++) {
13094                 pagedephd = &pagedep_hashtbl[next++];
13095                 if (next > pagedep_hash)
13096                         next = 0;
13097                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13098                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13099                                 continue;
13100                         mp = pagedep->pd_list.wk_mp;
13101                         ino = pagedep->pd_ino;
13102                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13103                                 continue;
13104                         FREE_LOCK(&lk);
13105
13106                         /*
13107                          * Let unmount clear deps
13108                          */
13109                         error = vfs_busy(mp, MBF_NOWAIT);
13110                         if (error != 0)
13111                                 goto finish_write;
13112                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13113                              FFSV_FORCEINSMQ);
13114                         vfs_unbusy(mp);
13115                         if (error != 0) {
13116                                 softdep_error("clear_remove: vget", error);
13117                                 goto finish_write;
13118                         }
13119                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13120                                 softdep_error("clear_remove: fsync", error);
13121                         bo = &vp->v_bufobj;
13122                         BO_LOCK(bo);
13123                         drain_output(vp);
13124                         BO_UNLOCK(bo);
13125                         vput(vp);
13126                 finish_write:
13127                         vn_finished_write(mp);
13128                         ACQUIRE_LOCK(&lk);
13129                         return;
13130                 }
13131         }
13132 }
13133
13134 /*
13135  * Clear out a block of dirty inodes in an effort to reduce
13136  * the number of inodedep dependency structures.
13137  */
13138 static void
13139 clear_inodedeps(td)
13140         struct thread *td;
13141 {
13142         struct inodedep_hashhead *inodedephd;
13143         struct inodedep *inodedep;
13144         static int next = 0;
13145         struct mount *mp;
13146         struct vnode *vp;
13147         struct fs *fs;
13148         int error, cnt;
13149         ino_t firstino, lastino, ino;
13150
13151         mtx_assert(&lk, MA_OWNED);
13152         /*
13153          * Pick a random inode dependency to be cleared.
13154          * We will then gather up all the inodes in its block 
13155          * that have dependencies and flush them out.
13156          */
13157         for (cnt = 0; cnt <= inodedep_hash; cnt++) {
13158                 inodedephd = &inodedep_hashtbl[next++];
13159                 if (next > inodedep_hash)
13160                         next = 0;
13161                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13162                         break;
13163         }
13164         if (inodedep == NULL)
13165                 return;
13166         fs = inodedep->id_fs;
13167         mp = inodedep->id_list.wk_mp;
13168         /*
13169          * Find the last inode in the block with dependencies.
13170          */
13171         firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
13172         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13173                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13174                         break;
13175         /*
13176          * Asynchronously push all but the last inode with dependencies.
13177          * Synchronously push the last inode with dependencies to ensure
13178          * that the inode block gets written to free up the inodedeps.
13179          */
13180         for (ino = firstino; ino <= lastino; ino++) {
13181                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13182                         continue;
13183                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13184                         continue;
13185                 FREE_LOCK(&lk);
13186                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13187                 if (error != 0) {
13188                         vn_finished_write(mp);
13189                         ACQUIRE_LOCK(&lk);
13190                         return;
13191                 }
13192                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13193                     FFSV_FORCEINSMQ)) != 0) {
13194                         softdep_error("clear_inodedeps: vget", error);
13195                         vfs_unbusy(mp);
13196                         vn_finished_write(mp);
13197                         ACQUIRE_LOCK(&lk);
13198                         return;
13199                 }
13200                 vfs_unbusy(mp);
13201                 if (ino == lastino) {
13202                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13203                                 softdep_error("clear_inodedeps: fsync1", error);
13204                 } else {
13205                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13206                                 softdep_error("clear_inodedeps: fsync2", error);
13207                         BO_LOCK(&vp->v_bufobj);
13208                         drain_output(vp);
13209                         BO_UNLOCK(&vp->v_bufobj);
13210                 }
13211                 vput(vp);
13212                 vn_finished_write(mp);
13213                 ACQUIRE_LOCK(&lk);
13214         }
13215 }
13216
13217 void
13218 softdep_buf_append(bp, wkhd)
13219         struct buf *bp;
13220         struct workhead *wkhd;
13221 {
13222         struct worklist *wk;
13223
13224         ACQUIRE_LOCK(&lk);
13225         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13226                 WORKLIST_REMOVE(wk);
13227                 WORKLIST_INSERT(&bp->b_dep, wk);
13228         }
13229         FREE_LOCK(&lk);
13230
13231 }
13232
13233 void
13234 softdep_inode_append(ip, cred, wkhd)
13235         struct inode *ip;
13236         struct ucred *cred;
13237         struct workhead *wkhd;
13238 {
13239         struct buf *bp;
13240         struct fs *fs;
13241         int error;
13242
13243         fs = ip->i_fs;
13244         error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13245             (int)fs->fs_bsize, cred, &bp);
13246         if (error) {
13247                 bqrelse(bp);
13248                 softdep_freework(wkhd);
13249                 return;
13250         }
13251         softdep_buf_append(bp, wkhd);
13252         bqrelse(bp);
13253 }
13254
13255 void
13256 softdep_freework(wkhd)
13257         struct workhead *wkhd;
13258 {
13259
13260         ACQUIRE_LOCK(&lk);
13261         handle_jwork(wkhd);
13262         FREE_LOCK(&lk);
13263 }
13264
13265 /*
13266  * Function to determine if the buffer has outstanding dependencies
13267  * that will cause a roll-back if the buffer is written. If wantcount
13268  * is set, return number of dependencies, otherwise just yes or no.
13269  */
13270 static int
13271 softdep_count_dependencies(bp, wantcount)
13272         struct buf *bp;
13273         int wantcount;
13274 {
13275         struct worklist *wk;
13276         struct bmsafemap *bmsafemap;
13277         struct freework *freework;
13278         struct inodedep *inodedep;
13279         struct indirdep *indirdep;
13280         struct freeblks *freeblks;
13281         struct allocindir *aip;
13282         struct pagedep *pagedep;
13283         struct dirrem *dirrem;
13284         struct newblk *newblk;
13285         struct mkdir *mkdir;
13286         struct diradd *dap;
13287         int i, retval;
13288
13289         retval = 0;
13290         ACQUIRE_LOCK(&lk);
13291         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13292                 switch (wk->wk_type) {
13293
13294                 case D_INODEDEP:
13295                         inodedep = WK_INODEDEP(wk);
13296                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13297                                 /* bitmap allocation dependency */
13298                                 retval += 1;
13299                                 if (!wantcount)
13300                                         goto out;
13301                         }
13302                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13303                                 /* direct block pointer dependency */
13304                                 retval += 1;
13305                                 if (!wantcount)
13306                                         goto out;
13307                         }
13308                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13309                                 /* direct block pointer dependency */
13310                                 retval += 1;
13311                                 if (!wantcount)
13312                                         goto out;
13313                         }
13314                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13315                                 /* Add reference dependency. */
13316                                 retval += 1;
13317                                 if (!wantcount)
13318                                         goto out;
13319                         }
13320                         continue;
13321
13322                 case D_INDIRDEP:
13323                         indirdep = WK_INDIRDEP(wk);
13324
13325                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13326                                 /* indirect truncation dependency */
13327                                 retval += 1;
13328                                 if (!wantcount)
13329                                         goto out;
13330                         }
13331
13332                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13333                                 /* indirect block pointer dependency */
13334                                 retval += 1;
13335                                 if (!wantcount)
13336                                         goto out;
13337                         }
13338                         continue;
13339
13340                 case D_PAGEDEP:
13341                         pagedep = WK_PAGEDEP(wk);
13342                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13343                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13344                                         /* Journal remove ref dependency. */
13345                                         retval += 1;
13346                                         if (!wantcount)
13347                                                 goto out;
13348                                 }
13349                         }
13350                         for (i = 0; i < DAHASHSZ; i++) {
13351
13352                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13353                                         /* directory entry dependency */
13354                                         retval += 1;
13355                                         if (!wantcount)
13356                                                 goto out;
13357                                 }
13358                         }
13359                         continue;
13360
13361                 case D_BMSAFEMAP:
13362                         bmsafemap = WK_BMSAFEMAP(wk);
13363                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13364                                 /* Add reference dependency. */
13365                                 retval += 1;
13366                                 if (!wantcount)
13367                                         goto out;
13368                         }
13369                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13370                                 /* Allocate block dependency. */
13371                                 retval += 1;
13372                                 if (!wantcount)
13373                                         goto out;
13374                         }
13375                         continue;
13376
13377                 case D_FREEBLKS:
13378                         freeblks = WK_FREEBLKS(wk);
13379                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13380                                 /* Freeblk journal dependency. */
13381                                 retval += 1;
13382                                 if (!wantcount)
13383                                         goto out;
13384                         }
13385                         continue;
13386
13387                 case D_ALLOCDIRECT:
13388                 case D_ALLOCINDIR:
13389                         newblk = WK_NEWBLK(wk);
13390                         if (newblk->nb_jnewblk) {
13391                                 /* Journal allocate dependency. */
13392                                 retval += 1;
13393                                 if (!wantcount)
13394                                         goto out;
13395                         }
13396                         continue;
13397
13398                 case D_MKDIR:
13399                         mkdir = WK_MKDIR(wk);
13400                         if (mkdir->md_jaddref) {
13401                                 /* Journal reference dependency. */
13402                                 retval += 1;
13403                                 if (!wantcount)
13404                                         goto out;
13405                         }
13406                         continue;
13407
13408                 case D_FREEWORK:
13409                 case D_FREEDEP:
13410                 case D_JSEGDEP:
13411                 case D_JSEG:
13412                 case D_SBDEP:
13413                         /* never a dependency on these blocks */
13414                         continue;
13415
13416                 default:
13417                         panic("softdep_count_dependencies: Unexpected type %s",
13418                             TYPENAME(wk->wk_type));
13419                         /* NOTREACHED */
13420                 }
13421         }
13422 out:
13423         FREE_LOCK(&lk);
13424         return retval;
13425 }
13426
13427 /*
13428  * Acquire exclusive access to a buffer.
13429  * Must be called with a locked mtx parameter.
13430  * Return acquired buffer or NULL on failure.
13431  */
13432 static struct buf *
13433 getdirtybuf(bp, mtx, waitfor)
13434         struct buf *bp;
13435         struct mtx *mtx;
13436         int waitfor;
13437 {
13438         int error;
13439
13440         mtx_assert(mtx, MA_OWNED);
13441         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13442                 if (waitfor != MNT_WAIT)
13443                         return (NULL);
13444                 error = BUF_LOCK(bp,
13445                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
13446                 /*
13447                  * Even if we sucessfully acquire bp here, we have dropped
13448                  * mtx, which may violates our guarantee.
13449                  */
13450                 if (error == 0)
13451                         BUF_UNLOCK(bp);
13452                 else if (error != ENOLCK)
13453                         panic("getdirtybuf: inconsistent lock: %d", error);
13454                 mtx_lock(mtx);
13455                 return (NULL);
13456         }
13457         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13458                 if (mtx == &lk && waitfor == MNT_WAIT) {
13459                         mtx_unlock(mtx);
13460                         BO_LOCK(bp->b_bufobj);
13461                         BUF_UNLOCK(bp);
13462                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13463                                 bp->b_vflags |= BV_BKGRDWAIT;
13464                                 msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
13465                                        PRIBIO | PDROP, "getbuf", 0);
13466                         } else
13467                                 BO_UNLOCK(bp->b_bufobj);
13468                         mtx_lock(mtx);
13469                         return (NULL);
13470                 }
13471                 BUF_UNLOCK(bp);
13472                 if (waitfor != MNT_WAIT)
13473                         return (NULL);
13474                 /*
13475                  * The mtx argument must be bp->b_vp's mutex in
13476                  * this case.
13477                  */
13478 #ifdef  DEBUG_VFS_LOCKS
13479                 if (bp->b_vp->v_type != VCHR)
13480                         ASSERT_BO_LOCKED(bp->b_bufobj);
13481 #endif
13482                 bp->b_vflags |= BV_BKGRDWAIT;
13483                 msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
13484                 return (NULL);
13485         }
13486         if ((bp->b_flags & B_DELWRI) == 0) {
13487                 BUF_UNLOCK(bp);
13488                 return (NULL);
13489         }
13490         bremfree(bp);
13491         return (bp);
13492 }
13493
13494
13495 /*
13496  * Check if it is safe to suspend the file system now.  On entry,
13497  * the vnode interlock for devvp should be held.  Return 0 with
13498  * the mount interlock held if the file system can be suspended now,
13499  * otherwise return EAGAIN with the mount interlock held.
13500  */
13501 int
13502 softdep_check_suspend(struct mount *mp,
13503                       struct vnode *devvp,
13504                       int softdep_deps,
13505                       int softdep_accdeps,
13506                       int secondary_writes,
13507                       int secondary_accwrites)
13508 {
13509         struct bufobj *bo;
13510         struct ufsmount *ump;
13511         int error;
13512
13513         ump = VFSTOUFS(mp);
13514         bo = &devvp->v_bufobj;
13515         ASSERT_BO_LOCKED(bo);
13516
13517         for (;;) {
13518                 if (!TRY_ACQUIRE_LOCK(&lk)) {
13519                         BO_UNLOCK(bo);
13520                         ACQUIRE_LOCK(&lk);
13521                         FREE_LOCK(&lk);
13522                         BO_LOCK(bo);
13523                         continue;
13524                 }
13525                 MNT_ILOCK(mp);
13526                 if (mp->mnt_secondary_writes != 0) {
13527                         FREE_LOCK(&lk);
13528                         BO_UNLOCK(bo);
13529                         msleep(&mp->mnt_secondary_writes,
13530                                MNT_MTX(mp),
13531                                (PUSER - 1) | PDROP, "secwr", 0);
13532                         BO_LOCK(bo);
13533                         continue;
13534                 }
13535                 break;
13536         }
13537
13538         /*
13539          * Reasons for needing more work before suspend:
13540          * - Dirty buffers on devvp.
13541          * - Softdep activity occurred after start of vnode sync loop
13542          * - Secondary writes occurred after start of vnode sync loop
13543          */
13544         error = 0;
13545         if (bo->bo_numoutput > 0 ||
13546             bo->bo_dirty.bv_cnt > 0 ||
13547             softdep_deps != 0 ||
13548             ump->softdep_deps != 0 ||
13549             softdep_accdeps != ump->softdep_accdeps ||
13550             secondary_writes != 0 ||
13551             mp->mnt_secondary_writes != 0 ||
13552             secondary_accwrites != mp->mnt_secondary_accwrites)
13553                 error = EAGAIN;
13554         FREE_LOCK(&lk);
13555         BO_UNLOCK(bo);
13556         return (error);
13557 }
13558
13559
13560 /*
13561  * Get the number of dependency structures for the file system, both
13562  * the current number and the total number allocated.  These will
13563  * later be used to detect that softdep processing has occurred.
13564  */
13565 void
13566 softdep_get_depcounts(struct mount *mp,
13567                       int *softdep_depsp,
13568                       int *softdep_accdepsp)
13569 {
13570         struct ufsmount *ump;
13571
13572         ump = VFSTOUFS(mp);
13573         ACQUIRE_LOCK(&lk);
13574         *softdep_depsp = ump->softdep_deps;
13575         *softdep_accdepsp = ump->softdep_accdeps;
13576         FREE_LOCK(&lk);
13577 }
13578
13579 /*
13580  * Wait for pending output on a vnode to complete.
13581  * Must be called with vnode lock and interlock locked.
13582  *
13583  * XXX: Should just be a call to bufobj_wwait().
13584  */
13585 static void
13586 drain_output(vp)
13587         struct vnode *vp;
13588 {
13589         struct bufobj *bo;
13590
13591         bo = &vp->v_bufobj;
13592         ASSERT_VOP_LOCKED(vp, "drain_output");
13593         ASSERT_BO_LOCKED(bo);
13594
13595         while (bo->bo_numoutput) {
13596                 bo->bo_flag |= BO_WWAIT;
13597                 msleep((caddr_t)&bo->bo_numoutput,
13598                     BO_MTX(bo), PRIBIO + 1, "drainvp", 0);
13599         }
13600 }
13601
13602 /*
13603  * Called whenever a buffer that is being invalidated or reallocated
13604  * contains dependencies. This should only happen if an I/O error has
13605  * occurred. The routine is called with the buffer locked.
13606  */ 
13607 static void
13608 softdep_deallocate_dependencies(bp)
13609         struct buf *bp;
13610 {
13611
13612         if ((bp->b_ioflags & BIO_ERROR) == 0)
13613                 panic("softdep_deallocate_dependencies: dangling deps");
13614         softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
13615         panic("softdep_deallocate_dependencies: unrecovered I/O error");
13616 }
13617
13618 /*
13619  * Function to handle asynchronous write errors in the filesystem.
13620  */
13621 static void
13622 softdep_error(func, error)
13623         char *func;
13624         int error;
13625 {
13626
13627         /* XXX should do something better! */
13628         printf("%s: got error %d while accessing filesystem\n", func, error);
13629 }
13630
13631 #ifdef DDB
13632
13633 static void
13634 inodedep_print(struct inodedep *inodedep, int verbose)
13635 {
13636         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
13637             " saveino %p\n",
13638             inodedep, inodedep->id_fs, inodedep->id_state,
13639             (intmax_t)inodedep->id_ino,
13640             (intmax_t)fsbtodb(inodedep->id_fs,
13641             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
13642             inodedep->id_nlinkdelta, inodedep->id_savednlink,
13643             inodedep->id_savedino1);
13644
13645         if (verbose == 0)
13646                 return;
13647
13648         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
13649             "mkdiradd %p\n",
13650             LIST_FIRST(&inodedep->id_pendinghd),
13651             LIST_FIRST(&inodedep->id_bufwait),
13652             LIST_FIRST(&inodedep->id_inowait),
13653             TAILQ_FIRST(&inodedep->id_inoreflst),
13654             inodedep->id_mkdiradd);
13655         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
13656             TAILQ_FIRST(&inodedep->id_inoupdt),
13657             TAILQ_FIRST(&inodedep->id_newinoupdt),
13658             TAILQ_FIRST(&inodedep->id_extupdt),
13659             TAILQ_FIRST(&inodedep->id_newextupdt));
13660 }
13661
13662 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
13663 {
13664
13665         if (have_addr == 0) {
13666                 db_printf("Address required\n");
13667                 return;
13668         }
13669         inodedep_print((struct inodedep*)addr, 1);
13670 }
13671
13672 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
13673 {
13674         struct inodedep_hashhead *inodedephd;
13675         struct inodedep *inodedep;
13676         struct fs *fs;
13677         int cnt;
13678
13679         fs = have_addr ? (struct fs *)addr : NULL;
13680         for (cnt = 0; cnt < inodedep_hash; cnt++) {
13681                 inodedephd = &inodedep_hashtbl[cnt];
13682                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
13683                         if (fs != NULL && fs != inodedep->id_fs)
13684                                 continue;
13685                         inodedep_print(inodedep, 0);
13686                 }
13687         }
13688 }
13689
13690 DB_SHOW_COMMAND(worklist, db_show_worklist)
13691 {
13692         struct worklist *wk;
13693
13694         if (have_addr == 0) {
13695                 db_printf("Address required\n");
13696                 return;
13697         }
13698         wk = (struct worklist *)addr;
13699         printf("worklist: %p type %s state 0x%X\n",
13700             wk, TYPENAME(wk->wk_type), wk->wk_state);
13701 }
13702
13703 DB_SHOW_COMMAND(workhead, db_show_workhead)
13704 {
13705         struct workhead *wkhd;
13706         struct worklist *wk;
13707         int i;
13708
13709         if (have_addr == 0) {
13710                 db_printf("Address required\n");
13711                 return;
13712         }
13713         wkhd = (struct workhead *)addr;
13714         wk = LIST_FIRST(wkhd);
13715         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
13716                 db_printf("worklist: %p type %s state 0x%X",
13717                     wk, TYPENAME(wk->wk_type), wk->wk_state);
13718         if (i == 100)
13719                 db_printf("workhead overflow");
13720         printf("\n");
13721 }
13722
13723
13724 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
13725 {
13726         struct jaddref *jaddref;
13727         struct diradd *diradd;
13728         struct mkdir *mkdir;
13729
13730         LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
13731                 diradd = mkdir->md_diradd;
13732                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
13733                     mkdir, mkdir->md_state, diradd, diradd->da_state);
13734                 if ((jaddref = mkdir->md_jaddref) != NULL)
13735                         db_printf(" jaddref %p jaddref state 0x%X",
13736                             jaddref, jaddref->ja_state);
13737                 db_printf("\n");
13738         }
13739 }
13740
13741 #endif /* DDB */
13742
13743 #endif /* SOFTUPDATES */