]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - sys/ufs/ffs/ffs_softdep.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.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_ddb.h"
47
48 /*
49  * For now we want the safety net that the DEBUG flag provides.
50  */
51 #ifndef DEBUG
52 #define DEBUG
53 #endif
54
55 #include <sys/param.h>
56 #include <sys/kernel.h>
57 #include <sys/systm.h>
58 #include <sys/bio.h>
59 #include <sys/buf.h>
60 #include <sys/kdb.h>
61 #include <sys/kthread.h>
62 #include <sys/limits.h>
63 #include <sys/lock.h>
64 #include <sys/malloc.h>
65 #include <sys/mount.h>
66 #include <sys/mutex.h>
67 #include <sys/namei.h>
68 #include <sys/priv.h>
69 #include <sys/proc.h>
70 #include <sys/stat.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/vnode.h>
74 #include <sys/conf.h>
75
76 #include <ufs/ufs/dir.h>
77 #include <ufs/ufs/extattr.h>
78 #include <ufs/ufs/quota.h>
79 #include <ufs/ufs/inode.h>
80 #include <ufs/ufs/ufsmount.h>
81 #include <ufs/ffs/fs.h>
82 #include <ufs/ffs/softdep.h>
83 #include <ufs/ffs/ffs_extern.h>
84 #include <ufs/ufs/ufs_extern.h>
85
86 #include <vm/vm.h>
87 #include <vm/vm_extern.h>
88 #include <vm/vm_object.h>
89
90 #include <ddb/ddb.h>
91
92 #ifndef SOFTUPDATES
93
94 int
95 softdep_flushfiles(oldmnt, flags, td)
96         struct mount *oldmnt;
97         int flags;
98         struct thread *td;
99 {
100
101         panic("softdep_flushfiles called");
102 }
103
104 int
105 softdep_mount(devvp, mp, fs, cred)
106         struct vnode *devvp;
107         struct mount *mp;
108         struct fs *fs;
109         struct ucred *cred;
110 {
111
112         return (0);
113 }
114
115 void 
116 softdep_initialize()
117 {
118
119         return;
120 }
121
122 void
123 softdep_uninitialize()
124 {
125
126         return;
127 }
128
129 void
130 softdep_unmount(mp)
131         struct mount *mp;
132 {
133
134 }
135
136 void
137 softdep_setup_sbupdate(ump, fs, bp)
138         struct ufsmount *ump;
139         struct fs *fs;
140         struct buf *bp;
141 {
142 }
143
144 void
145 softdep_setup_inomapdep(bp, ip, newinum, mode)
146         struct buf *bp;
147         struct inode *ip;
148         ino_t newinum;
149         int mode;
150 {
151
152         panic("softdep_setup_inomapdep called");
153 }
154
155 void
156 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
157         struct buf *bp;
158         struct mount *mp;
159         ufs2_daddr_t newblkno;
160         int frags;
161         int oldfrags;
162 {
163
164         panic("softdep_setup_blkmapdep called");
165 }
166
167 void 
168 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
169         struct inode *ip;
170         ufs_lbn_t lbn;
171         ufs2_daddr_t newblkno;
172         ufs2_daddr_t oldblkno;
173         long newsize;
174         long oldsize;
175         struct buf *bp;
176 {
177         
178         panic("softdep_setup_allocdirect called");
179 }
180
181 void 
182 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
183         struct inode *ip;
184         ufs_lbn_t lbn;
185         ufs2_daddr_t newblkno;
186         ufs2_daddr_t oldblkno;
187         long newsize;
188         long oldsize;
189         struct buf *bp;
190 {
191         
192         panic("softdep_setup_allocext called");
193 }
194
195 void
196 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
197         struct inode *ip;
198         ufs_lbn_t lbn;
199         struct buf *bp;
200         int ptrno;
201         ufs2_daddr_t newblkno;
202         ufs2_daddr_t oldblkno;
203         struct buf *nbp;
204 {
205
206         panic("softdep_setup_allocindir_page called");
207 }
208
209 void
210 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
211         struct buf *nbp;
212         struct inode *ip;
213         struct buf *bp;
214         int ptrno;
215         ufs2_daddr_t newblkno;
216 {
217
218         panic("softdep_setup_allocindir_meta called");
219 }
220
221 void
222 softdep_journal_freeblocks(ip, cred, length, flags)
223         struct inode *ip;
224         struct ucred *cred;
225         off_t length;
226         int flags;
227 {
228         
229         panic("softdep_journal_freeblocks called");
230 }
231
232 void
233 softdep_journal_fsync(ip)
234         struct inode *ip;
235 {
236
237         panic("softdep_journal_fsync called");
238 }
239
240 void
241 softdep_setup_freeblocks(ip, length, flags)
242         struct inode *ip;
243         off_t length;
244         int flags;
245 {
246         
247         panic("softdep_setup_freeblocks called");
248 }
249
250 void
251 softdep_freefile(pvp, ino, mode)
252                 struct vnode *pvp;
253                 ino_t ino;
254                 int mode;
255 {
256
257         panic("softdep_freefile called");
258 }
259
260 int 
261 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
262         struct buf *bp;
263         struct inode *dp;
264         off_t diroffset;
265         ino_t newinum;
266         struct buf *newdirbp;
267         int isnewblk;
268 {
269
270         panic("softdep_setup_directory_add called");
271 }
272
273 void 
274 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
275         struct buf *bp;
276         struct inode *dp;
277         caddr_t base;
278         caddr_t oldloc;
279         caddr_t newloc;
280         int entrysize;
281 {
282
283         panic("softdep_change_directoryentry_offset called");
284 }
285
286 void 
287 softdep_setup_remove(bp, dp, ip, isrmdir)
288         struct buf *bp;
289         struct inode *dp;
290         struct inode *ip;
291         int isrmdir;
292 {
293         
294         panic("softdep_setup_remove called");
295 }
296
297 void 
298 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
299         struct buf *bp;
300         struct inode *dp;
301         struct inode *ip;
302         ino_t newinum;
303         int isrmdir;
304 {
305
306         panic("softdep_setup_directory_change called");
307 }
308
309 void
310 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
311         struct mount *mp;
312         struct buf *bp;
313         ufs2_daddr_t blkno;
314         int frags;
315         struct workhead *wkhd;
316 {
317
318         panic("%s called", __FUNCTION__);
319 }
320
321 void
322 softdep_setup_inofree(mp, bp, ino, wkhd)
323         struct mount *mp;
324         struct buf *bp;
325         ino_t ino;
326         struct workhead *wkhd;
327 {
328
329         panic("%s called", __FUNCTION__);
330 }
331
332 void
333 softdep_setup_unlink(dp, ip)
334         struct inode *dp;
335         struct inode *ip;
336 {
337
338         panic("%s called", __FUNCTION__);
339 }
340
341 void
342 softdep_setup_link(dp, ip)
343         struct inode *dp;
344         struct inode *ip;
345 {
346
347         panic("%s called", __FUNCTION__);
348 }
349
350 void
351 softdep_revert_link(dp, ip)
352         struct inode *dp;
353         struct inode *ip;
354 {
355
356         panic("%s called", __FUNCTION__);
357 }
358
359 void
360 softdep_setup_rmdir(dp, ip)
361         struct inode *dp;
362         struct inode *ip;
363 {
364
365         panic("%s called", __FUNCTION__);
366 }
367
368 void
369 softdep_revert_rmdir(dp, ip)
370         struct inode *dp;
371         struct inode *ip;
372 {
373
374         panic("%s called", __FUNCTION__);
375 }
376
377 void
378 softdep_setup_create(dp, ip)
379         struct inode *dp;
380         struct inode *ip;
381 {
382
383         panic("%s called", __FUNCTION__);
384 }
385
386 void
387 softdep_revert_create(dp, ip)
388         struct inode *dp;
389         struct inode *ip;
390 {
391
392         panic("%s called", __FUNCTION__);
393 }
394
395 void
396 softdep_setup_mkdir(dp, ip)
397         struct inode *dp;
398         struct inode *ip;
399 {
400
401         panic("%s called", __FUNCTION__);
402 }
403
404 void
405 softdep_revert_mkdir(dp, ip)
406         struct inode *dp;
407         struct inode *ip;
408 {
409
410         panic("%s called", __FUNCTION__);
411 }
412
413 void
414 softdep_setup_dotdot_link(dp, ip)
415         struct inode *dp;
416         struct inode *ip;
417 {
418
419         panic("%s called", __FUNCTION__);
420 }
421
422 int
423 softdep_prealloc(vp, waitok)
424         struct vnode *vp;
425         int waitok;
426 {
427
428         panic("%s called", __FUNCTION__);
429
430         return (0);
431 }
432
433 int
434 softdep_journal_lookup(mp, vpp)
435         struct mount *mp;
436         struct vnode **vpp;
437 {
438
439         return (ENOENT);
440 }
441
442 void
443 softdep_change_linkcnt(ip)
444         struct inode *ip;
445 {
446
447         panic("softdep_change_linkcnt called");
448 }
449
450 void 
451 softdep_load_inodeblock(ip)
452         struct inode *ip;
453 {
454
455         panic("softdep_load_inodeblock called");
456 }
457
458 void 
459 softdep_update_inodeblock(ip, bp, waitfor)
460         struct inode *ip;
461         struct buf *bp;
462         int waitfor;
463 {
464
465         panic("softdep_update_inodeblock called");
466 }
467
468 int
469 softdep_fsync(vp)
470         struct vnode *vp;       /* the "in_core" copy of the inode */
471 {
472
473         return (0);
474 }
475
476 void
477 softdep_fsync_mountdev(vp)
478         struct vnode *vp;
479 {
480
481         return;
482 }
483
484 int
485 softdep_flushworklist(oldmnt, countp, td)
486         struct mount *oldmnt;
487         int *countp;
488         struct thread *td;
489 {
490
491         *countp = 0;
492         return (0);
493 }
494
495 int
496 softdep_sync_metadata(struct vnode *vp)
497 {
498
499         return (0);
500 }
501
502 int
503 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
504 {
505
506         return (0);
507 }
508
509 int
510 softdep_slowdown(vp)
511         struct vnode *vp;
512 {
513
514         panic("softdep_slowdown called");
515 }
516
517 void
518 softdep_releasefile(ip)
519         struct inode *ip;       /* inode with the zero effective link count */
520 {
521
522         panic("softdep_releasefile called");
523 }
524
525 int
526 softdep_request_cleanup(fs, vp, cred, resource)
527         struct fs *fs;
528         struct vnode *vp;
529         struct ucred *cred;
530         int resource;
531 {
532
533         return (0);
534 }
535
536 int
537 softdep_check_suspend(struct mount *mp,
538                       struct vnode *devvp,
539                       int softdep_deps,
540                       int softdep_accdeps,
541                       int secondary_writes,
542                       int secondary_accwrites)
543 {
544         struct bufobj *bo;
545         int error;
546         
547         (void) softdep_deps,
548         (void) softdep_accdeps;
549
550         bo = &devvp->v_bufobj;
551         ASSERT_BO_LOCKED(bo);
552
553         MNT_ILOCK(mp);
554         while (mp->mnt_secondary_writes != 0) {
555                 BO_UNLOCK(bo);
556                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
557                     (PUSER - 1) | PDROP, "secwr", 0);
558                 BO_LOCK(bo);
559                 MNT_ILOCK(mp);
560         }
561
562         /*
563          * Reasons for needing more work before suspend:
564          * - Dirty buffers on devvp.
565          * - Secondary writes occurred after start of vnode sync loop
566          */
567         error = 0;
568         if (bo->bo_numoutput > 0 ||
569             bo->bo_dirty.bv_cnt > 0 ||
570             secondary_writes != 0 ||
571             mp->mnt_secondary_writes != 0 ||
572             secondary_accwrites != mp->mnt_secondary_accwrites)
573                 error = EAGAIN;
574         BO_UNLOCK(bo);
575         return (error);
576 }
577
578 void
579 softdep_get_depcounts(struct mount *mp,
580                       int *softdepactivep,
581                       int *softdepactiveaccp)
582 {
583         (void) mp;
584         *softdepactivep = 0;
585         *softdepactiveaccp = 0;
586 }
587
588 void
589 softdep_buf_append(bp, wkhd)
590         struct buf *bp;
591         struct workhead *wkhd;
592 {
593
594         panic("softdep_buf_appendwork called");
595 }
596
597 void
598 softdep_inode_append(ip, cred, wkhd)
599         struct inode *ip;
600         struct ucred *cred;
601         struct workhead *wkhd;
602 {
603
604         panic("softdep_inode_appendwork called");
605 }
606
607 void
608 softdep_freework(wkhd)
609         struct workhead *wkhd;
610 {
611
612         panic("softdep_freework called");
613 }
614
615 #else
616
617 FEATURE(softupdates, "FFS soft-updates support");
618
619 /*
620  * These definitions need to be adapted to the system to which
621  * this file is being ported.
622  */
623
624 #define M_SOFTDEP_FLAGS (M_WAITOK)
625
626 #define D_PAGEDEP       0
627 #define D_INODEDEP      1
628 #define D_BMSAFEMAP     2
629 #define D_NEWBLK        3
630 #define D_ALLOCDIRECT   4
631 #define D_INDIRDEP      5
632 #define D_ALLOCINDIR    6
633 #define D_FREEFRAG      7
634 #define D_FREEBLKS      8
635 #define D_FREEFILE      9
636 #define D_DIRADD        10
637 #define D_MKDIR         11
638 #define D_DIRREM        12
639 #define D_NEWDIRBLK     13
640 #define D_FREEWORK      14
641 #define D_FREEDEP       15
642 #define D_JADDREF       16
643 #define D_JREMREF       17
644 #define D_JMVREF        18
645 #define D_JNEWBLK       19
646 #define D_JFREEBLK      20
647 #define D_JFREEFRAG     21
648 #define D_JSEG          22
649 #define D_JSEGDEP       23
650 #define D_SBDEP         24
651 #define D_JTRUNC        25
652 #define D_JFSYNC        26
653 #define D_SENTINAL      27
654 #define D_LAST          D_SENTINAL
655
656 unsigned long dep_current[D_LAST + 1];
657 unsigned long dep_total[D_LAST + 1];
658 unsigned long dep_write[D_LAST + 1];
659
660
661 SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0, "soft updates stats");
662 SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
663     "total dependencies allocated");
664 SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
665     "current dependencies allocated");
666 SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
667     "current dependencies written");
668
669 #define SOFTDEP_TYPE(type, str, long)                                   \
670     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
671     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
672         &dep_total[D_ ## type], 0, "");                                 \
673     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
674         &dep_current[D_ ## type], 0, "");                               \
675     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
676         &dep_write[D_ ## type], 0, "");
677
678 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
679 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
680 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
681     "Block or frag allocated from cyl group map");
682 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
683 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
684 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
685 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
686 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
687 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
688 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
689 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
690 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
691 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
692 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
693 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
694 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
695 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
696 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
697 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
698 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
699 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
700 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
701 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
702 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
703 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
704 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
705 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
706
707 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
708 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
709
710 /* 
711  * translate from workitem type to memory type
712  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
713  */
714 static struct malloc_type *memtype[] = {
715         M_PAGEDEP,
716         M_INODEDEP,
717         M_BMSAFEMAP,
718         M_NEWBLK,
719         M_ALLOCDIRECT,
720         M_INDIRDEP,
721         M_ALLOCINDIR,
722         M_FREEFRAG,
723         M_FREEBLKS,
724         M_FREEFILE,
725         M_DIRADD,
726         M_MKDIR,
727         M_DIRREM,
728         M_NEWDIRBLK,
729         M_FREEWORK,
730         M_FREEDEP,
731         M_JADDREF,
732         M_JREMREF,
733         M_JMVREF,
734         M_JNEWBLK,
735         M_JFREEBLK,
736         M_JFREEFRAG,
737         M_JSEG,
738         M_JSEGDEP,
739         M_SBDEP,
740         M_JTRUNC,
741         M_JFSYNC
742 };
743
744 static LIST_HEAD(mkdirlist, mkdir) mkdirlisthd;
745
746 #define DtoM(type) (memtype[type])
747
748 /*
749  * Names of malloc types.
750  */
751 #define TYPENAME(type)  \
752         ((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
753 /*
754  * End system adaptation definitions.
755  */
756
757 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
758 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
759
760 /*
761  * Forward declarations.
762  */
763 struct inodedep_hashhead;
764 struct newblk_hashhead;
765 struct pagedep_hashhead;
766 struct bmsafemap_hashhead;
767
768 /*
769  * Internal function prototypes.
770  */
771 static  void softdep_error(char *, int);
772 static  void drain_output(struct vnode *);
773 static  struct buf *getdirtybuf(struct buf *, struct mtx *, int);
774 static  void clear_remove(struct thread *);
775 static  void clear_inodedeps(struct thread *);
776 static  void unlinked_inodedep(struct mount *, struct inodedep *);
777 static  void clear_unlinked_inodedep(struct inodedep *);
778 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
779 static  int flush_pagedep_deps(struct vnode *, struct mount *,
780             struct diraddhd *);
781 static  int free_pagedep(struct pagedep *);
782 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
783 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
784 static  int flush_deplist(struct allocdirectlst *, int, int *);
785 static  int sync_cgs(struct mount *, int);
786 static  int handle_written_filepage(struct pagedep *, struct buf *);
787 static  int handle_written_sbdep(struct sbdep *, struct buf *);
788 static  void initiate_write_sbdep(struct sbdep *);
789 static  void diradd_inode_written(struct diradd *, struct inodedep *);
790 static  int handle_written_indirdep(struct indirdep *, struct buf *,
791             struct buf**);
792 static  int handle_written_inodeblock(struct inodedep *, struct buf *);
793 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
794             uint8_t *);
795 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
796 static  void handle_written_jaddref(struct jaddref *);
797 static  void handle_written_jremref(struct jremref *);
798 static  void handle_written_jseg(struct jseg *, struct buf *);
799 static  void handle_written_jnewblk(struct jnewblk *);
800 static  void handle_written_jblkdep(struct jblkdep *);
801 static  void handle_written_jfreefrag(struct jfreefrag *);
802 static  void complete_jseg(struct jseg *);
803 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
804 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
805 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
806 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
807 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
808 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
809 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
810 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
811 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
812 static  inline void inoref_write(struct inoref *, struct jseg *,
813             struct jrefrec *);
814 static  void handle_allocdirect_partdone(struct allocdirect *,
815             struct workhead *);
816 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
817             struct workhead *);
818 static  void indirdep_complete(struct indirdep *);
819 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
820 static  void indirblk_insert(struct freework *);
821 static  void indirblk_remove(struct freework *);
822 static  void handle_allocindir_partdone(struct allocindir *);
823 static  void initiate_write_filepage(struct pagedep *, struct buf *);
824 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
825 static  void handle_written_mkdir(struct mkdir *, int);
826 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
827             uint8_t *);
828 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
829 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
830 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
831 static  void handle_workitem_freefile(struct freefile *);
832 static  int handle_workitem_remove(struct dirrem *, int);
833 static  struct dirrem *newdirrem(struct buf *, struct inode *,
834             struct inode *, int, struct dirrem **);
835 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
836             struct buf *);
837 static  void cancel_indirdep(struct indirdep *, struct buf *,
838             struct freeblks *);
839 static  void free_indirdep(struct indirdep *);
840 static  void free_diradd(struct diradd *, struct workhead *);
841 static  void merge_diradd(struct inodedep *, struct diradd *);
842 static  void complete_diradd(struct diradd *);
843 static  struct diradd *diradd_lookup(struct pagedep *, int);
844 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
845             struct jremref *);
846 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
847             struct jremref *);
848 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
849             struct jremref *, struct jremref *);
850 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
851             struct jremref *);
852 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
853             struct freeblks *, int);
854 static  int setup_trunc_indir(struct freeblks *, struct inode *,
855             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
856 static  void complete_trunc_indir(struct freework *);
857 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
858             int);
859 static  void complete_mkdir(struct mkdir *);
860 static  void free_newdirblk(struct newdirblk *);
861 static  void free_jremref(struct jremref *);
862 static  void free_jaddref(struct jaddref *);
863 static  void free_jsegdep(struct jsegdep *);
864 static  void free_jsegs(struct jblocks *);
865 static  void rele_jseg(struct jseg *);
866 static  void free_jseg(struct jseg *, struct jblocks *);
867 static  void free_jnewblk(struct jnewblk *);
868 static  void free_jblkdep(struct jblkdep *);
869 static  void free_jfreefrag(struct jfreefrag *);
870 static  void free_freedep(struct freedep *);
871 static  void journal_jremref(struct dirrem *, struct jremref *,
872             struct inodedep *);
873 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
874 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
875             struct workhead *);
876 static  void cancel_jfreefrag(struct jfreefrag *);
877 static  inline void setup_freedirect(struct freeblks *, struct inode *,
878             int, int);
879 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
880 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
881             ufs_lbn_t, int);
882 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
883 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
884 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
885 ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
886 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
887 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
888             int, int);
889 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
890 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
891 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
892 static  void newblk_freefrag(struct newblk*);
893 static  void free_newblk(struct newblk *);
894 static  void cancel_allocdirect(struct allocdirectlst *,
895             struct allocdirect *, struct freeblks *);
896 static  int check_inode_unwritten(struct inodedep *);
897 static  int free_inodedep(struct inodedep *);
898 static  void freework_freeblock(struct freework *);
899 static  void freework_enqueue(struct freework *);
900 static  int handle_workitem_freeblocks(struct freeblks *, int);
901 static  int handle_complete_freeblocks(struct freeblks *, int);
902 static  void handle_workitem_indirblk(struct freework *);
903 static  void handle_written_freework(struct freework *);
904 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
905 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
906             struct workhead *);
907 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
908             struct inodedep *, struct allocindir *, ufs_lbn_t);
909 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
910             ufs2_daddr_t, ufs_lbn_t);
911 static  void handle_workitem_freefrag(struct freefrag *);
912 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
913             ufs_lbn_t);
914 static  void allocdirect_merge(struct allocdirectlst *,
915             struct allocdirect *, struct allocdirect *);
916 static  struct freefrag *allocindir_merge(struct allocindir *,
917             struct allocindir *);
918 static  int bmsafemap_find(struct bmsafemap_hashhead *, struct mount *, int,
919             struct bmsafemap **);
920 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
921             int cg);
922 static  int newblk_find(struct newblk_hashhead *, struct mount *, ufs2_daddr_t,
923             int, struct newblk **);
924 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
925 static  int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
926             struct inodedep **);
927 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
928 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
929             int, struct pagedep **);
930 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
931             struct mount *mp, int, struct pagedep **);
932 static  void pause_timer(void *);
933 static  int request_cleanup(struct mount *, int);
934 static  int process_worklist_item(struct mount *, int, int);
935 static  void process_removes(struct vnode *);
936 static  void process_truncates(struct vnode *);
937 static  void jwork_move(struct workhead *, struct workhead *);
938 static  void jwork_insert(struct workhead *, struct jsegdep *);
939 static  void add_to_worklist(struct worklist *, int);
940 static  void wake_worklist(struct worklist *);
941 static  void wait_worklist(struct worklist *, char *);
942 static  void remove_from_worklist(struct worklist *);
943 static  void softdep_flush(void);
944 static  void softdep_flushjournal(struct mount *);
945 static  int softdep_speedup(void);
946 static  void worklist_speedup(void);
947 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
948 static  void journal_unmount(struct mount *);
949 static  int journal_space(struct ufsmount *, int);
950 static  void journal_suspend(struct ufsmount *);
951 static  int journal_unsuspend(struct ufsmount *ump);
952 static  void softdep_prelink(struct vnode *, struct vnode *);
953 static  void add_to_journal(struct worklist *);
954 static  void remove_from_journal(struct worklist *);
955 static  void softdep_process_journal(struct mount *, struct worklist *, int);
956 static  struct jremref *newjremref(struct dirrem *, struct inode *,
957             struct inode *ip, off_t, nlink_t);
958 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
959             uint16_t);
960 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
961             uint16_t);
962 static  inline struct jsegdep *inoref_jseg(struct inoref *);
963 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
964 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
965             ufs2_daddr_t, int);
966 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
967 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
968 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
969 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
970             ufs2_daddr_t, long, ufs_lbn_t);
971 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
972             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
973 static  int jwait(struct worklist *, int);
974 static  struct inodedep *inodedep_lookup_ip(struct inode *);
975 static  int bmsafemap_rollbacks(struct bmsafemap *);
976 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
977 static  void handle_jwork(struct workhead *);
978 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
979             struct mkdir **);
980 static  struct jblocks *jblocks_create(void);
981 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
982 static  void jblocks_free(struct jblocks *, struct mount *, int);
983 static  void jblocks_destroy(struct jblocks *);
984 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
985
986 /*
987  * Exported softdep operations.
988  */
989 static  void softdep_disk_io_initiation(struct buf *);
990 static  void softdep_disk_write_complete(struct buf *);
991 static  void softdep_deallocate_dependencies(struct buf *);
992 static  int softdep_count_dependencies(struct buf *bp, int);
993
994 static struct mtx lk;
995 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
996
997 #define TRY_ACQUIRE_LOCK(lk)            mtx_trylock(lk)
998 #define ACQUIRE_LOCK(lk)                mtx_lock(lk)
999 #define FREE_LOCK(lk)                   mtx_unlock(lk)
1000
1001 #define BUF_AREC(bp)                    lockallowrecurse(&(bp)->b_lock)
1002 #define BUF_NOREC(bp)                   lockdisablerecurse(&(bp)->b_lock)
1003
1004 /*
1005  * Worklist queue management.
1006  * These routines require that the lock be held.
1007  */
1008 #ifndef /* NOT */ DEBUG
1009 #define WORKLIST_INSERT(head, item) do {        \
1010         (item)->wk_state |= ONWORKLIST;         \
1011         LIST_INSERT_HEAD(head, item, wk_list);  \
1012 } while (0)
1013 #define WORKLIST_REMOVE(item) do {              \
1014         (item)->wk_state &= ~ONWORKLIST;        \
1015         LIST_REMOVE(item, wk_list);             \
1016 } while (0)
1017 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1018 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1019
1020 #else /* DEBUG */
1021 static  void worklist_insert(struct workhead *, struct worklist *, int);
1022 static  void worklist_remove(struct worklist *, int);
1023
1024 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1025 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1026 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1027 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1028
1029 static void
1030 worklist_insert(head, item, locked)
1031         struct workhead *head;
1032         struct worklist *item;
1033         int locked;
1034 {
1035
1036         if (locked)
1037                 mtx_assert(&lk, MA_OWNED);
1038         if (item->wk_state & ONWORKLIST)
1039                 panic("worklist_insert: %p %s(0x%X) already on list",
1040                     item, TYPENAME(item->wk_type), item->wk_state);
1041         item->wk_state |= ONWORKLIST;
1042         LIST_INSERT_HEAD(head, item, wk_list);
1043 }
1044
1045 static void
1046 worklist_remove(item, locked)
1047         struct worklist *item;
1048         int locked;
1049 {
1050
1051         if (locked)
1052                 mtx_assert(&lk, MA_OWNED);
1053         if ((item->wk_state & ONWORKLIST) == 0)
1054                 panic("worklist_remove: %p %s(0x%X) not on list",
1055                     item, TYPENAME(item->wk_type), item->wk_state);
1056         item->wk_state &= ~ONWORKLIST;
1057         LIST_REMOVE(item, wk_list);
1058 }
1059 #endif /* DEBUG */
1060
1061 /*
1062  * Merge two jsegdeps keeping only the oldest one as newer references
1063  * can't be discarded until after older references.
1064  */
1065 static inline struct jsegdep *
1066 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1067 {
1068         struct jsegdep *swp;
1069
1070         if (two == NULL)
1071                 return (one);
1072
1073         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1074                 swp = one;
1075                 one = two;
1076                 two = swp;
1077         }
1078         WORKLIST_REMOVE(&two->jd_list);
1079         free_jsegdep(two);
1080
1081         return (one);
1082 }
1083
1084 /*
1085  * If two freedeps are compatible free one to reduce list size.
1086  */
1087 static inline struct freedep *
1088 freedep_merge(struct freedep *one, struct freedep *two)
1089 {
1090         if (two == NULL)
1091                 return (one);
1092
1093         if (one->fd_freework == two->fd_freework) {
1094                 WORKLIST_REMOVE(&two->fd_list);
1095                 free_freedep(two);
1096         }
1097         return (one);
1098 }
1099
1100 /*
1101  * Move journal work from one list to another.  Duplicate freedeps and
1102  * jsegdeps are coalesced to keep the lists as small as possible.
1103  */
1104 static void
1105 jwork_move(dst, src)
1106         struct workhead *dst;
1107         struct workhead *src;
1108 {
1109         struct freedep *freedep;
1110         struct jsegdep *jsegdep;
1111         struct worklist *wkn;
1112         struct worklist *wk;
1113
1114         KASSERT(dst != src,
1115             ("jwork_move: dst == src"));
1116         freedep = NULL;
1117         jsegdep = NULL;
1118         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1119                 if (wk->wk_type == D_JSEGDEP)
1120                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1121                 if (wk->wk_type == D_FREEDEP)
1122                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1123         }
1124
1125         mtx_assert(&lk, MA_OWNED);
1126         while ((wk = LIST_FIRST(src)) != NULL) {
1127                 WORKLIST_REMOVE(wk);
1128                 WORKLIST_INSERT(dst, wk);
1129                 if (wk->wk_type == D_JSEGDEP) {
1130                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1131                         continue;
1132                 }
1133                 if (wk->wk_type == D_FREEDEP)
1134                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1135         }
1136 }
1137
1138 static void
1139 jwork_insert(dst, jsegdep)
1140         struct workhead *dst;
1141         struct jsegdep *jsegdep;
1142 {
1143         struct jsegdep *jsegdepn;
1144         struct worklist *wk;
1145
1146         LIST_FOREACH(wk, dst, wk_list)
1147                 if (wk->wk_type == D_JSEGDEP)
1148                         break;
1149         if (wk == NULL) {
1150                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1151                 return;
1152         }
1153         jsegdepn = WK_JSEGDEP(wk);
1154         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1155                 WORKLIST_REMOVE(wk);
1156                 free_jsegdep(jsegdepn);
1157                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1158         } else
1159                 free_jsegdep(jsegdep);
1160 }
1161
1162 /*
1163  * Routines for tracking and managing workitems.
1164  */
1165 static  void workitem_free(struct worklist *, int);
1166 static  void workitem_alloc(struct worklist *, int, struct mount *);
1167
1168 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
1169
1170 static void
1171 workitem_free(item, type)
1172         struct worklist *item;
1173         int type;
1174 {
1175         struct ufsmount *ump;
1176         mtx_assert(&lk, MA_OWNED);
1177
1178 #ifdef DEBUG
1179         if (item->wk_state & ONWORKLIST)
1180                 panic("workitem_free: %s(0x%X) still on list",
1181                     TYPENAME(item->wk_type), item->wk_state);
1182         if (item->wk_type != type)
1183                 panic("workitem_free: type mismatch %s != %s",
1184                     TYPENAME(item->wk_type), TYPENAME(type));
1185 #endif
1186         if (item->wk_state & IOWAITING)
1187                 wakeup(item);
1188         ump = VFSTOUFS(item->wk_mp);
1189         if (--ump->softdep_deps == 0 && ump->softdep_req)
1190                 wakeup(&ump->softdep_deps);
1191         dep_current[type]--;
1192         free(item, DtoM(type));
1193 }
1194
1195 static void
1196 workitem_alloc(item, type, mp)
1197         struct worklist *item;
1198         int type;
1199         struct mount *mp;
1200 {
1201         struct ufsmount *ump;
1202
1203         item->wk_type = type;
1204         item->wk_mp = mp;
1205         item->wk_state = 0;
1206
1207         ump = VFSTOUFS(mp);
1208         ACQUIRE_LOCK(&lk);
1209         dep_current[type]++;
1210         dep_total[type]++;
1211         ump->softdep_deps++;
1212         ump->softdep_accdeps++;
1213         FREE_LOCK(&lk);
1214 }
1215
1216 /*
1217  * Workitem queue management
1218  */
1219 static int max_softdeps;        /* maximum number of structs before slowdown */
1220 static int maxindirdeps = 50;   /* max number of indirdeps before slowdown */
1221 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1222 static int proc_waiting;        /* tracks whether we have a timeout posted */
1223 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1224 static struct callout softdep_callout;
1225 static int req_pending;
1226 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1227 static int req_clear_remove;    /* syncer process flush some freeblks */
1228
1229 /*
1230  * runtime statistics
1231  */
1232 static int stat_worklist_push;  /* number of worklist cleanups */
1233 static int stat_blk_limit_push; /* number of times block limit neared */
1234 static int stat_ino_limit_push; /* number of times inode limit neared */
1235 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1236 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1237 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1238 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1239 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1240 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1241 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1242 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1243 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1244 static int stat_journal_min;    /* Times hit journal min threshold */
1245 static int stat_journal_low;    /* Times hit journal low threshold */
1246 static int stat_journal_wait;   /* Times blocked in jwait(). */
1247 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1248 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1249 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1250 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1251 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1252 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1253 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1254 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1255 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1256
1257 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1258     &max_softdeps, 0, "");
1259 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1260     &tickdelay, 0, "");
1261 SYSCTL_INT(_debug_softdep, OID_AUTO, maxindirdeps, CTLFLAG_RW,
1262     &maxindirdeps, 0, "");
1263 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1264     &stat_worklist_push, 0,"");
1265 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1266     &stat_blk_limit_push, 0,"");
1267 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1268     &stat_ino_limit_push, 0,"");
1269 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1270     &stat_blk_limit_hit, 0, "");
1271 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1272     &stat_ino_limit_hit, 0, "");
1273 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1274     &stat_sync_limit_hit, 0, "");
1275 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1276     &stat_indir_blk_ptrs, 0, "");
1277 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1278     &stat_inode_bitmap, 0, "");
1279 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1280     &stat_direct_blk_ptrs, 0, "");
1281 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1282     &stat_dir_entry, 0, "");
1283 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1284     &stat_jaddref, 0, "");
1285 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1286     &stat_jnewblk, 0, "");
1287 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1288     &stat_journal_low, 0, "");
1289 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1290     &stat_journal_min, 0, "");
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1292     &stat_journal_wait, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1294     &stat_jwait_filepage, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1296     &stat_jwait_freeblks, 0, "");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1298     &stat_jwait_inode, 0, "");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1300     &stat_jwait_newblk, 0, "");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1302     &stat_cleanup_blkrequests, 0, "");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1304     &stat_cleanup_inorequests, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1306     &stat_cleanup_high_delay, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1308     &stat_cleanup_retries, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1310     &stat_cleanup_failures, 0, "");
1311
1312 SYSCTL_DECL(_vfs_ffs);
1313
1314 LIST_HEAD(bmsafemap_hashhead, bmsafemap) *bmsafemap_hashtbl;
1315 static u_long   bmsafemap_hash; /* size of hash table - 1 */
1316
1317 static int compute_summary_at_mount = 0;        /* Whether to recompute the summary at mount time */
1318 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1319            &compute_summary_at_mount, 0, "Recompute summary at mount");
1320
1321 static struct proc *softdepproc;
1322 static struct kproc_desc softdep_kp = {
1323         "softdepflush",
1324         softdep_flush,
1325         &softdepproc
1326 };
1327 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
1328     &softdep_kp);
1329
1330 static void
1331 softdep_flush(void)
1332 {
1333         struct mount *nmp;
1334         struct mount *mp;
1335         struct ufsmount *ump;
1336         struct thread *td;
1337         int remaining;
1338         int progress;
1339         int vfslocked;
1340
1341         td = curthread;
1342         td->td_pflags |= TDP_NORUNNINGBUF;
1343
1344         for (;;) {      
1345                 kproc_suspend_check(softdepproc);
1346                 vfslocked = VFS_LOCK_GIANT((struct mount *)NULL);
1347                 ACQUIRE_LOCK(&lk);
1348                 /*
1349                  * If requested, try removing inode or removal dependencies.
1350                  */
1351                 if (req_clear_inodedeps) {
1352                         clear_inodedeps(td);
1353                         req_clear_inodedeps -= 1;
1354                         wakeup_one(&proc_waiting);
1355                 }
1356                 if (req_clear_remove) {
1357                         clear_remove(td);
1358                         req_clear_remove -= 1;
1359                         wakeup_one(&proc_waiting);
1360                 }
1361                 FREE_LOCK(&lk);
1362                 VFS_UNLOCK_GIANT(vfslocked);
1363                 remaining = progress = 0;
1364                 mtx_lock(&mountlist_mtx);
1365                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
1366                         nmp = TAILQ_NEXT(mp, mnt_list);
1367                         if (MOUNTEDSOFTDEP(mp) == 0)
1368                                 continue;
1369                         if (vfs_busy(mp, MBF_NOWAIT | MBF_MNTLSTLOCK))
1370                                 continue;
1371                         vfslocked = VFS_LOCK_GIANT(mp);
1372                         progress += softdep_process_worklist(mp, 0);
1373                         ump = VFSTOUFS(mp);
1374                         remaining += ump->softdep_on_worklist;
1375                         VFS_UNLOCK_GIANT(vfslocked);
1376                         mtx_lock(&mountlist_mtx);
1377                         nmp = TAILQ_NEXT(mp, mnt_list);
1378                         vfs_unbusy(mp);
1379                 }
1380                 mtx_unlock(&mountlist_mtx);
1381                 if (remaining && progress)
1382                         continue;
1383                 ACQUIRE_LOCK(&lk);
1384                 if (!req_pending)
1385                         msleep(&req_pending, &lk, PVM, "sdflush", hz);
1386                 req_pending = 0;
1387                 FREE_LOCK(&lk);
1388         }
1389 }
1390
1391 static void
1392 worklist_speedup(void)
1393 {
1394         mtx_assert(&lk, MA_OWNED);
1395         if (req_pending == 0) {
1396                 req_pending = 1;
1397                 wakeup(&req_pending);
1398         }
1399 }
1400
1401 static int
1402 softdep_speedup(void)
1403 {
1404
1405         worklist_speedup();
1406         bd_speedup();
1407         return speedup_syncer();
1408 }
1409
1410 /*
1411  * Add an item to the end of the work queue.
1412  * This routine requires that the lock be held.
1413  * This is the only routine that adds items to the list.
1414  * The following routine is the only one that removes items
1415  * and does so in order from first to last.
1416  */
1417
1418 #define WK_HEAD         0x0001  /* Add to HEAD. */
1419 #define WK_NODELAY      0x0002  /* Process immediately. */
1420
1421 static void
1422 add_to_worklist(wk, flags)
1423         struct worklist *wk;
1424         int flags;
1425 {
1426         struct ufsmount *ump;
1427
1428         mtx_assert(&lk, MA_OWNED);
1429         ump = VFSTOUFS(wk->wk_mp);
1430         if (wk->wk_state & ONWORKLIST)
1431                 panic("add_to_worklist: %s(0x%X) already on list",
1432                     TYPENAME(wk->wk_type), wk->wk_state);
1433         wk->wk_state |= ONWORKLIST;
1434         if (ump->softdep_on_worklist == 0) {
1435                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1436                 ump->softdep_worklist_tail = wk;
1437         } else if (flags & WK_HEAD) {
1438                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1439         } else {
1440                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1441                 ump->softdep_worklist_tail = wk;
1442         }
1443         ump->softdep_on_worklist += 1;
1444         if (flags & WK_NODELAY)
1445                 worklist_speedup();
1446 }
1447
1448 /*
1449  * Remove the item to be processed. If we are removing the last
1450  * item on the list, we need to recalculate the tail pointer.
1451  */
1452 static void
1453 remove_from_worklist(wk)
1454         struct worklist *wk;
1455 {
1456         struct ufsmount *ump;
1457
1458         ump = VFSTOUFS(wk->wk_mp);
1459         WORKLIST_REMOVE(wk);
1460         if (ump->softdep_worklist_tail == wk)
1461                 ump->softdep_worklist_tail =
1462                     (struct worklist *)wk->wk_list.le_prev;
1463         ump->softdep_on_worklist -= 1;
1464 }
1465
1466 static void
1467 wake_worklist(wk)
1468         struct worklist *wk;
1469 {
1470         if (wk->wk_state & IOWAITING) {
1471                 wk->wk_state &= ~IOWAITING;
1472                 wakeup(wk);
1473         }
1474 }
1475
1476 static void
1477 wait_worklist(wk, wmesg)
1478         struct worklist *wk;
1479         char *wmesg;
1480 {
1481
1482         wk->wk_state |= IOWAITING;
1483         msleep(wk, &lk, PVM, wmesg, 0);
1484 }
1485
1486 /*
1487  * Process that runs once per second to handle items in the background queue.
1488  *
1489  * Note that we ensure that everything is done in the order in which they
1490  * appear in the queue. The code below depends on this property to ensure
1491  * that blocks of a file are freed before the inode itself is freed. This
1492  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1493  * until all the old ones have been purged from the dependency lists.
1494  */
1495 int 
1496 softdep_process_worklist(mp, full)
1497         struct mount *mp;
1498         int full;
1499 {
1500         struct thread *td = curthread;
1501         int cnt, matchcnt;
1502         struct ufsmount *ump;
1503         long starttime;
1504
1505         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1506         /*
1507          * Record the process identifier of our caller so that we can give
1508          * this process preferential treatment in request_cleanup below.
1509          */
1510         matchcnt = 0;
1511         ump = VFSTOUFS(mp);
1512         ACQUIRE_LOCK(&lk);
1513         starttime = time_second;
1514         softdep_process_journal(mp, NULL, full?MNT_WAIT:0);
1515         while (ump->softdep_on_worklist > 0) {
1516                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1517                         break;
1518                 else
1519                         matchcnt += cnt;
1520                 /*
1521                  * If requested, try removing inode or removal dependencies.
1522                  */
1523                 if (req_clear_inodedeps) {
1524                         clear_inodedeps(td);
1525                         req_clear_inodedeps -= 1;
1526                         wakeup_one(&proc_waiting);
1527                 }
1528                 if (req_clear_remove) {
1529                         clear_remove(td);
1530                         req_clear_remove -= 1;
1531                         wakeup_one(&proc_waiting);
1532                 }
1533                 /*
1534                  * We do not generally want to stop for buffer space, but if
1535                  * we are really being a buffer hog, we will stop and wait.
1536                  */
1537                 if (should_yield()) {
1538                         FREE_LOCK(&lk);
1539                         kern_yield(PRI_UNCHANGED);
1540                         bwillwrite();
1541                         ACQUIRE_LOCK(&lk);
1542                 }
1543                 /*
1544                  * Never allow processing to run for more than one
1545                  * second. Otherwise the other mountpoints may get
1546                  * excessively backlogged.
1547                  */
1548                 if (!full && starttime != time_second)
1549                         break;
1550         }
1551         if (full == 0)
1552                 journal_unsuspend(ump);
1553         FREE_LOCK(&lk);
1554         return (matchcnt);
1555 }
1556
1557 /*
1558  * Process all removes associated with a vnode if we are running out of
1559  * journal space.  Any other process which attempts to flush these will
1560  * be unable as we have the vnodes locked.
1561  */
1562 static void
1563 process_removes(vp)
1564         struct vnode *vp;
1565 {
1566         struct inodedep *inodedep;
1567         struct dirrem *dirrem;
1568         struct mount *mp;
1569         ino_t inum;
1570
1571         mtx_assert(&lk, MA_OWNED);
1572
1573         mp = vp->v_mount;
1574         inum = VTOI(vp)->i_number;
1575         for (;;) {
1576 top:
1577                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1578                         return;
1579                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1580                         /*
1581                          * If another thread is trying to lock this vnode
1582                          * it will fail but we must wait for it to do so
1583                          * before we can proceed.
1584                          */
1585                         if (dirrem->dm_state & INPROGRESS) {
1586                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1587                                 goto top;
1588                         }
1589                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1590                             (COMPLETE | ONWORKLIST))
1591                                 break;
1592                 }
1593                 if (dirrem == NULL)
1594                         return;
1595                 remove_from_worklist(&dirrem->dm_list);
1596                 FREE_LOCK(&lk);
1597                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1598                         panic("process_removes: suspended filesystem");
1599                 handle_workitem_remove(dirrem, 0);
1600                 vn_finished_secondary_write(mp);
1601                 ACQUIRE_LOCK(&lk);
1602         }
1603 }
1604
1605 /*
1606  * Process all truncations associated with a vnode if we are running out
1607  * of journal space.  This is called when the vnode lock is already held
1608  * and no other process can clear the truncation.  This function returns
1609  * a value greater than zero if it did any work.
1610  */
1611 static void
1612 process_truncates(vp)
1613         struct vnode *vp;
1614 {
1615         struct inodedep *inodedep;
1616         struct freeblks *freeblks;
1617         struct mount *mp;
1618         ino_t inum;
1619         int cgwait;
1620
1621         mtx_assert(&lk, MA_OWNED);
1622
1623         mp = vp->v_mount;
1624         inum = VTOI(vp)->i_number;
1625         for (;;) {
1626                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1627                         return;
1628                 cgwait = 0;
1629                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1630                         /* Journal entries not yet written.  */
1631                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1632                                 jwait(&LIST_FIRST(
1633                                     &freeblks->fb_jblkdephd)->jb_list,
1634                                     MNT_WAIT);
1635                                 break;
1636                         }
1637                         /* Another thread is executing this item. */
1638                         if (freeblks->fb_state & INPROGRESS) {
1639                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1640                                 break;
1641                         }
1642                         /* Freeblks is waiting on a inode write. */
1643                         if ((freeblks->fb_state & COMPLETE) == 0) {
1644                                 FREE_LOCK(&lk);
1645                                 ffs_update(vp, 1);
1646                                 ACQUIRE_LOCK(&lk);
1647                                 break;
1648                         }
1649                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1650                             (ALLCOMPLETE | ONWORKLIST)) {
1651                                 remove_from_worklist(&freeblks->fb_list);
1652                                 freeblks->fb_state |= INPROGRESS;
1653                                 FREE_LOCK(&lk);
1654                                 if (vn_start_secondary_write(NULL, &mp,
1655                                     V_NOWAIT))
1656                                         panic("process_truncates: "
1657                                             "suspended filesystem");
1658                                 handle_workitem_freeblocks(freeblks, 0);
1659                                 vn_finished_secondary_write(mp);
1660                                 ACQUIRE_LOCK(&lk);
1661                                 break;
1662                         }
1663                         if (freeblks->fb_cgwait)
1664                                 cgwait++;
1665                 }
1666                 if (cgwait) {
1667                         FREE_LOCK(&lk);
1668                         sync_cgs(mp, MNT_WAIT);
1669                         ffs_sync_snap(mp, MNT_WAIT);
1670                         ACQUIRE_LOCK(&lk);
1671                         continue;
1672                 }
1673                 if (freeblks == NULL)
1674                         break;
1675         }
1676         return;
1677 }
1678
1679 /*
1680  * Process one item on the worklist.
1681  */
1682 static int
1683 process_worklist_item(mp, target, flags)
1684         struct mount *mp;
1685         int target;
1686         int flags;
1687 {
1688         struct worklist sintenel;
1689         struct worklist *wk;
1690         struct ufsmount *ump;
1691         int matchcnt;
1692         int error;
1693
1694         mtx_assert(&lk, MA_OWNED);
1695         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1696         /*
1697          * If we are being called because of a process doing a
1698          * copy-on-write, then it is not safe to write as we may
1699          * recurse into the copy-on-write routine.
1700          */
1701         if (curthread->td_pflags & TDP_COWINPROGRESS)
1702                 return (-1);
1703         PHOLD(curproc); /* Don't let the stack go away. */
1704         ump = VFSTOUFS(mp);
1705         matchcnt = 0;
1706         sintenel.wk_mp = NULL;
1707         sintenel.wk_type = D_SENTINAL;
1708         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sintenel, wk_list);
1709         for (wk = LIST_NEXT(&sintenel, wk_list); wk != NULL;
1710             wk = LIST_NEXT(&sintenel, wk_list)) {
1711                 if (wk->wk_type == D_SENTINAL) {
1712                         LIST_REMOVE(&sintenel, wk_list);
1713                         LIST_INSERT_AFTER(wk, &sintenel, wk_list);
1714                         continue;
1715                 }
1716                 if (wk->wk_state & INPROGRESS)
1717                         panic("process_worklist_item: %p already in progress.",
1718                             wk);
1719                 wk->wk_state |= INPROGRESS;
1720                 remove_from_worklist(wk);
1721                 FREE_LOCK(&lk);
1722                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1723                         panic("process_worklist_item: suspended filesystem");
1724                 switch (wk->wk_type) {
1725                 case D_DIRREM:
1726                         /* removal of a directory entry */
1727                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1728                         break;
1729
1730                 case D_FREEBLKS:
1731                         /* releasing blocks and/or fragments from a file */
1732                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1733                             flags);
1734                         break;
1735
1736                 case D_FREEFRAG:
1737                         /* releasing a fragment when replaced as a file grows */
1738                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1739                         error = 0;
1740                         break;
1741
1742                 case D_FREEFILE:
1743                         /* releasing an inode when its link count drops to 0 */
1744                         handle_workitem_freefile(WK_FREEFILE(wk));
1745                         error = 0;
1746                         break;
1747
1748                 default:
1749                         panic("%s_process_worklist: Unknown type %s",
1750                             "softdep", TYPENAME(wk->wk_type));
1751                         /* NOTREACHED */
1752                 }
1753                 vn_finished_secondary_write(mp);
1754                 ACQUIRE_LOCK(&lk);
1755                 if (error == 0) {
1756                         if (++matchcnt == target)
1757                                 break;
1758                         continue;
1759                 }
1760                 /*
1761                  * We have to retry the worklist item later.  Wake up any
1762                  * waiters who may be able to complete it immediately and
1763                  * add the item back to the head so we don't try to execute
1764                  * it again.
1765                  */
1766                 wk->wk_state &= ~INPROGRESS;
1767                 wake_worklist(wk);
1768                 add_to_worklist(wk, WK_HEAD);
1769         }
1770         LIST_REMOVE(&sintenel, wk_list);
1771         /* Sentinal could've become the tail from remove_from_worklist. */
1772         if (ump->softdep_worklist_tail == &sintenel)
1773                 ump->softdep_worklist_tail =
1774                     (struct worklist *)sintenel.wk_list.le_prev;
1775         PRELE(curproc);
1776         return (matchcnt);
1777 }
1778
1779 /*
1780  * Move dependencies from one buffer to another.
1781  */
1782 int
1783 softdep_move_dependencies(oldbp, newbp)
1784         struct buf *oldbp;
1785         struct buf *newbp;
1786 {
1787         struct worklist *wk, *wktail;
1788         int dirty;
1789
1790         dirty = 0;
1791         wktail = NULL;
1792         ACQUIRE_LOCK(&lk);
1793         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1794                 LIST_REMOVE(wk, wk_list);
1795                 if (wk->wk_type == D_BMSAFEMAP &&
1796                     bmsafemap_rollbacks(WK_BMSAFEMAP(wk)))
1797                         dirty = 1;
1798                 if (wktail == 0)
1799                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1800                 else
1801                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1802                 wktail = wk;
1803         }
1804         FREE_LOCK(&lk);
1805
1806         return (dirty);
1807 }
1808
1809 /*
1810  * Purge the work list of all items associated with a particular mount point.
1811  */
1812 int
1813 softdep_flushworklist(oldmnt, countp, td)
1814         struct mount *oldmnt;
1815         int *countp;
1816         struct thread *td;
1817 {
1818         struct vnode *devvp;
1819         int count, error = 0;
1820         struct ufsmount *ump;
1821
1822         /*
1823          * Alternately flush the block device associated with the mount
1824          * point and process any dependencies that the flushing
1825          * creates. We continue until no more worklist dependencies
1826          * are found.
1827          */
1828         *countp = 0;
1829         ump = VFSTOUFS(oldmnt);
1830         devvp = ump->um_devvp;
1831         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1832                 *countp += count;
1833                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1834                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1835                 VOP_UNLOCK(devvp, 0);
1836                 if (error)
1837                         break;
1838         }
1839         return (error);
1840 }
1841
1842 int
1843 softdep_waitidle(struct mount *mp)
1844 {
1845         struct ufsmount *ump;
1846         int error;
1847         int i;
1848
1849         ump = VFSTOUFS(mp);
1850         ACQUIRE_LOCK(&lk);
1851         for (i = 0; i < 10 && ump->softdep_deps; i++) {
1852                 ump->softdep_req = 1;
1853                 if (ump->softdep_on_worklist)
1854                         panic("softdep_waitidle: work added after flush.");
1855                 msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1856         }
1857         ump->softdep_req = 0;
1858         FREE_LOCK(&lk);
1859         error = 0;
1860         if (i == 10) {
1861                 error = EBUSY;
1862                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1863                     mp);
1864         }
1865
1866         return (error);
1867 }
1868
1869 /*
1870  * Flush all vnodes and worklist items associated with a specified mount point.
1871  */
1872 int
1873 softdep_flushfiles(oldmnt, flags, td)
1874         struct mount *oldmnt;
1875         int flags;
1876         struct thread *td;
1877 {
1878         int error, depcount, loopcnt, retry_flush_count, retry;
1879
1880         loopcnt = 10;
1881         retry_flush_count = 3;
1882 retry_flush:
1883         error = 0;
1884
1885         /*
1886          * Alternately flush the vnodes associated with the mount
1887          * point and process any dependencies that the flushing
1888          * creates. In theory, this loop can happen at most twice,
1889          * but we give it a few extra just to be sure.
1890          */
1891         for (; loopcnt > 0; loopcnt--) {
1892                 /*
1893                  * Do another flush in case any vnodes were brought in
1894                  * as part of the cleanup operations.
1895                  */
1896                 if ((error = ffs_flushfiles(oldmnt, flags, td)) != 0)
1897                         break;
1898                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1899                     depcount == 0)
1900                         break;
1901         }
1902         /*
1903          * If we are unmounting then it is an error to fail. If we
1904          * are simply trying to downgrade to read-only, then filesystem
1905          * activity can keep us busy forever, so we just fail with EBUSY.
1906          */
1907         if (loopcnt == 0) {
1908                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1909                         panic("softdep_flushfiles: looping");
1910                 error = EBUSY;
1911         }
1912         if (!error)
1913                 error = softdep_waitidle(oldmnt);
1914         if (!error) {
1915                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1916                         retry = 0;
1917                         MNT_ILOCK(oldmnt);
1918                         KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1919                             ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1920                         if (oldmnt->mnt_nvnodelistsize > 0) {
1921                                 if (--retry_flush_count > 0) {
1922                                         retry = 1;
1923                                         loopcnt = 3;
1924                                 } else
1925                                         error = EBUSY;
1926                         }
1927                         MNT_IUNLOCK(oldmnt);
1928                         if (retry)
1929                                 goto retry_flush;
1930                 }
1931         }
1932         return (error);
1933 }
1934
1935 /*
1936  * Structure hashing.
1937  * 
1938  * There are three types of structures that can be looked up:
1939  *      1) pagedep structures identified by mount point, inode number,
1940  *         and logical block.
1941  *      2) inodedep structures identified by mount point and inode number.
1942  *      3) newblk structures identified by mount point and
1943  *         physical block number.
1944  *
1945  * The "pagedep" and "inodedep" dependency structures are hashed
1946  * separately from the file blocks and inodes to which they correspond.
1947  * This separation helps when the in-memory copy of an inode or
1948  * file block must be replaced. It also obviates the need to access
1949  * an inode or file page when simply updating (or de-allocating)
1950  * dependency structures. Lookup of newblk structures is needed to
1951  * find newly allocated blocks when trying to associate them with
1952  * their allocdirect or allocindir structure.
1953  *
1954  * The lookup routines optionally create and hash a new instance when
1955  * an existing entry is not found.
1956  */
1957 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
1958 #define NODELAY         0x0002  /* cannot do background work */
1959
1960 /*
1961  * Structures and routines associated with pagedep caching.
1962  */
1963 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1964 u_long  pagedep_hash;           /* size of hash table - 1 */
1965 #define PAGEDEP_HASH(mp, inum, lbn) \
1966         (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
1967             pagedep_hash])
1968
1969 static int
1970 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
1971         struct pagedep_hashhead *pagedephd;
1972         ino_t ino;
1973         ufs_lbn_t lbn;
1974         struct mount *mp;
1975         int flags;
1976         struct pagedep **pagedeppp;
1977 {
1978         struct pagedep *pagedep;
1979
1980         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
1981                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn &&
1982                     mp == pagedep->pd_list.wk_mp) {
1983                         *pagedeppp = pagedep;
1984                         return (1);
1985                 }
1986         }
1987         *pagedeppp = NULL;
1988         return (0);
1989 }
1990 /*
1991  * Look up a pagedep. Return 1 if found, 0 otherwise.
1992  * If not found, allocate if DEPALLOC flag is passed.
1993  * Found or allocated entry is returned in pagedeppp.
1994  * This routine must be called with splbio interrupts blocked.
1995  */
1996 static int
1997 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
1998         struct mount *mp;
1999         struct buf *bp;
2000         ino_t ino;
2001         ufs_lbn_t lbn;
2002         int flags;
2003         struct pagedep **pagedeppp;
2004 {
2005         struct pagedep *pagedep;
2006         struct pagedep_hashhead *pagedephd;
2007         struct worklist *wk;
2008         int ret;
2009         int i;
2010
2011         mtx_assert(&lk, MA_OWNED);
2012         if (bp) {
2013                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2014                         if (wk->wk_type == D_PAGEDEP) {
2015                                 *pagedeppp = WK_PAGEDEP(wk);
2016                                 return (1);
2017                         }
2018                 }
2019         }
2020         pagedephd = PAGEDEP_HASH(mp, ino, lbn);
2021         ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2022         if (ret) {
2023                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2024                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2025                 return (1);
2026         }
2027         if ((flags & DEPALLOC) == 0)
2028                 return (0);
2029         FREE_LOCK(&lk);
2030         pagedep = malloc(sizeof(struct pagedep),
2031             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2032         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2033         ACQUIRE_LOCK(&lk);
2034         ret = pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp);
2035         if (*pagedeppp) {
2036                 /*
2037                  * This should never happen since we only create pagedeps
2038                  * with the vnode lock held.  Could be an assert.
2039                  */
2040                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2041                 return (ret);
2042         }
2043         pagedep->pd_ino = ino;
2044         pagedep->pd_lbn = lbn;
2045         LIST_INIT(&pagedep->pd_dirremhd);
2046         LIST_INIT(&pagedep->pd_pendinghd);
2047         for (i = 0; i < DAHASHSZ; i++)
2048                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2049         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2050         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2051         *pagedeppp = pagedep;
2052         return (0);
2053 }
2054
2055 /*
2056  * Structures and routines associated with inodedep caching.
2057  */
2058 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
2059 static u_long   inodedep_hash;  /* size of hash table - 1 */
2060 #define INODEDEP_HASH(fs, inum) \
2061       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
2062
2063 static int
2064 inodedep_find(inodedephd, fs, inum, inodedeppp)
2065         struct inodedep_hashhead *inodedephd;
2066         struct fs *fs;
2067         ino_t inum;
2068         struct inodedep **inodedeppp;
2069 {
2070         struct inodedep *inodedep;
2071
2072         LIST_FOREACH(inodedep, inodedephd, id_hash)
2073                 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
2074                         break;
2075         if (inodedep) {
2076                 *inodedeppp = inodedep;
2077                 return (1);
2078         }
2079         *inodedeppp = NULL;
2080
2081         return (0);
2082 }
2083 /*
2084  * Look up an inodedep. Return 1 if found, 0 if not found.
2085  * If not found, allocate if DEPALLOC flag is passed.
2086  * Found or allocated entry is returned in inodedeppp.
2087  * This routine must be called with splbio interrupts blocked.
2088  */
2089 static int
2090 inodedep_lookup(mp, inum, flags, inodedeppp)
2091         struct mount *mp;
2092         ino_t inum;
2093         int flags;
2094         struct inodedep **inodedeppp;
2095 {
2096         struct inodedep *inodedep;
2097         struct inodedep_hashhead *inodedephd;
2098         struct fs *fs;
2099
2100         mtx_assert(&lk, MA_OWNED);
2101         fs = VFSTOUFS(mp)->um_fs;
2102         inodedephd = INODEDEP_HASH(fs, inum);
2103
2104         if (inodedep_find(inodedephd, fs, inum, inodedeppp))
2105                 return (1);
2106         if ((flags & DEPALLOC) == 0)
2107                 return (0);
2108         /*
2109          * If we are over our limit, try to improve the situation.
2110          */
2111         if (dep_current[D_INODEDEP] > max_softdeps && (flags & NODELAY) == 0)
2112                 request_cleanup(mp, FLUSH_INODES);
2113         FREE_LOCK(&lk);
2114         inodedep = malloc(sizeof(struct inodedep),
2115                 M_INODEDEP, M_SOFTDEP_FLAGS);
2116         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2117         ACQUIRE_LOCK(&lk);
2118         if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
2119                 WORKITEM_FREE(inodedep, D_INODEDEP);
2120                 return (1);
2121         }
2122         inodedep->id_fs = fs;
2123         inodedep->id_ino = inum;
2124         inodedep->id_state = ALLCOMPLETE;
2125         inodedep->id_nlinkdelta = 0;
2126         inodedep->id_savedino1 = NULL;
2127         inodedep->id_savedsize = -1;
2128         inodedep->id_savedextsize = -1;
2129         inodedep->id_savednlink = -1;
2130         inodedep->id_bmsafemap = NULL;
2131         inodedep->id_mkdiradd = NULL;
2132         LIST_INIT(&inodedep->id_dirremhd);
2133         LIST_INIT(&inodedep->id_pendinghd);
2134         LIST_INIT(&inodedep->id_inowait);
2135         LIST_INIT(&inodedep->id_bufwait);
2136         TAILQ_INIT(&inodedep->id_inoreflst);
2137         TAILQ_INIT(&inodedep->id_inoupdt);
2138         TAILQ_INIT(&inodedep->id_newinoupdt);
2139         TAILQ_INIT(&inodedep->id_extupdt);
2140         TAILQ_INIT(&inodedep->id_newextupdt);
2141         TAILQ_INIT(&inodedep->id_freeblklst);
2142         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2143         *inodedeppp = inodedep;
2144         return (0);
2145 }
2146
2147 /*
2148  * Structures and routines associated with newblk caching.
2149  */
2150 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
2151 u_long  newblk_hash;            /* size of hash table - 1 */
2152 #define NEWBLK_HASH(fs, inum) \
2153         (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
2154
2155 static int
2156 newblk_find(newblkhd, mp, newblkno, flags, newblkpp)
2157         struct newblk_hashhead *newblkhd;
2158         struct mount *mp;
2159         ufs2_daddr_t newblkno;
2160         int flags;
2161         struct newblk **newblkpp;
2162 {
2163         struct newblk *newblk;
2164
2165         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2166                 if (newblkno != newblk->nb_newblkno)
2167                         continue;
2168                 if (mp != newblk->nb_list.wk_mp)
2169                         continue;
2170                 /*
2171                  * If we're creating a new dependency don't match those that
2172                  * have already been converted to allocdirects.  This is for
2173                  * a frag extend.
2174                  */
2175                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2176                         continue;
2177                 break;
2178         }
2179         if (newblk) {
2180                 *newblkpp = newblk;
2181                 return (1);
2182         }
2183         *newblkpp = NULL;
2184         return (0);
2185 }
2186
2187 /*
2188  * Look up a newblk. Return 1 if found, 0 if not found.
2189  * If not found, allocate if DEPALLOC flag is passed.
2190  * Found or allocated entry is returned in newblkpp.
2191  */
2192 static int
2193 newblk_lookup(mp, newblkno, flags, newblkpp)
2194         struct mount *mp;
2195         ufs2_daddr_t newblkno;
2196         int flags;
2197         struct newblk **newblkpp;
2198 {
2199         struct newblk *newblk;
2200         struct newblk_hashhead *newblkhd;
2201
2202         newblkhd = NEWBLK_HASH(VFSTOUFS(mp)->um_fs, newblkno);
2203         if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp))
2204                 return (1);
2205         if ((flags & DEPALLOC) == 0)
2206                 return (0);
2207         FREE_LOCK(&lk);
2208         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2209             M_SOFTDEP_FLAGS | M_ZERO);
2210         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2211         ACQUIRE_LOCK(&lk);
2212         if (newblk_find(newblkhd, mp, newblkno, flags, newblkpp)) {
2213                 WORKITEM_FREE(newblk, D_NEWBLK);
2214                 return (1);
2215         }
2216         newblk->nb_freefrag = NULL;
2217         LIST_INIT(&newblk->nb_indirdeps);
2218         LIST_INIT(&newblk->nb_newdirblk);
2219         LIST_INIT(&newblk->nb_jwork);
2220         newblk->nb_state = ATTACHED;
2221         newblk->nb_newblkno = newblkno;
2222         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2223         *newblkpp = newblk;
2224         return (0);
2225 }
2226
2227 /*
2228  * Structures and routines associated with freed indirect block caching.
2229  */
2230 struct freeworklst *indir_hashtbl;
2231 u_long  indir_hash;             /* size of hash table - 1 */
2232 #define INDIR_HASH(mp, blkno) \
2233         (&indir_hashtbl[((((register_t)(mp)) >> 13) + (blkno)) & indir_hash])
2234
2235 /*
2236  * Lookup an indirect block in the indir hash table.  The freework is
2237  * removed and potentially freed.  The caller must do a blocking journal
2238  * write before writing to the blkno.
2239  */
2240 static int
2241 indirblk_lookup(mp, blkno)
2242         struct mount *mp;
2243         ufs2_daddr_t blkno;
2244 {
2245         struct freework *freework;
2246         struct freeworklst *wkhd;
2247
2248         wkhd = INDIR_HASH(mp, blkno);
2249         TAILQ_FOREACH(freework, wkhd, fw_next) {
2250                 if (freework->fw_blkno != blkno)
2251                         continue;
2252                 if (freework->fw_list.wk_mp != mp)
2253                         continue;
2254                 indirblk_remove(freework);
2255                 return (1);
2256         }
2257         return (0);
2258 }
2259
2260 /*
2261  * Insert an indirect block represented by freework into the indirblk
2262  * hash table so that it may prevent the block from being re-used prior
2263  * to the journal being written.
2264  */
2265 static void
2266 indirblk_insert(freework)
2267         struct freework *freework;
2268 {
2269         struct freeblks *freeblks;
2270         struct jsegdep *jsegdep;
2271         struct worklist *wk;
2272
2273         freeblks = freework->fw_freeblks;
2274         LIST_FOREACH(wk, &freeblks->fb_jwork, wk_list)
2275                 if (wk->wk_type == D_JSEGDEP)
2276                         break;
2277         if (wk == NULL)
2278                 return;
2279         
2280         jsegdep = WK_JSEGDEP(wk);
2281         LIST_INSERT_HEAD(&jsegdep->jd_seg->js_indirs, freework, fw_segs);
2282         TAILQ_INSERT_HEAD(INDIR_HASH(freework->fw_list.wk_mp,
2283             freework->fw_blkno), freework, fw_next);
2284         freework->fw_state &= ~DEPCOMPLETE;
2285 }
2286
2287 static void
2288 indirblk_remove(freework)
2289         struct freework *freework;
2290 {
2291
2292         LIST_REMOVE(freework, fw_segs);
2293         TAILQ_REMOVE(INDIR_HASH(freework->fw_list.wk_mp,
2294             freework->fw_blkno), freework, fw_next);
2295         freework->fw_state |= DEPCOMPLETE;
2296         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2297                 WORKITEM_FREE(freework, D_FREEWORK);
2298 }
2299
2300 /*
2301  * Executed during filesystem system initialization before
2302  * mounting any filesystems.
2303  */
2304 void 
2305 softdep_initialize()
2306 {
2307         int i;
2308
2309         LIST_INIT(&mkdirlisthd);
2310         max_softdeps = desiredvnodes * 4;
2311         pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP, &pagedep_hash);
2312         inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
2313         newblk_hashtbl = hashinit(desiredvnodes / 5,  M_NEWBLK, &newblk_hash);
2314         bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP, &bmsafemap_hash);
2315         i = 1 << (ffs(desiredvnodes / 10) - 1);
2316         indir_hashtbl = malloc(i * sizeof(indir_hashtbl[0]), M_FREEWORK,
2317             M_WAITOK);
2318         indir_hash = i - 1;
2319         for (i = 0; i <= indir_hash; i++)
2320                 TAILQ_INIT(&indir_hashtbl[i]);
2321
2322         /* initialise bioops hack */
2323         bioops.io_start = softdep_disk_io_initiation;
2324         bioops.io_complete = softdep_disk_write_complete;
2325         bioops.io_deallocate = softdep_deallocate_dependencies;
2326         bioops.io_countdeps = softdep_count_dependencies;
2327
2328         /* Initialize the callout with an mtx. */
2329         callout_init_mtx(&softdep_callout, &lk, 0);
2330 }
2331
2332 /*
2333  * Executed after all filesystems have been unmounted during
2334  * filesystem module unload.
2335  */
2336 void
2337 softdep_uninitialize()
2338 {
2339
2340         callout_drain(&softdep_callout);
2341         hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
2342         hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
2343         hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
2344         hashdestroy(bmsafemap_hashtbl, M_BMSAFEMAP, bmsafemap_hash);
2345         free(indir_hashtbl, M_FREEWORK);
2346 }
2347
2348 /*
2349  * Called at mount time to notify the dependency code that a
2350  * filesystem wishes to use it.
2351  */
2352 int
2353 softdep_mount(devvp, mp, fs, cred)
2354         struct vnode *devvp;
2355         struct mount *mp;
2356         struct fs *fs;
2357         struct ucred *cred;
2358 {
2359         struct csum_total cstotal;
2360         struct ufsmount *ump;
2361         struct cg *cgp;
2362         struct buf *bp;
2363         int error, cyl;
2364
2365         MNT_ILOCK(mp);
2366         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2367         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2368                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2369                         MNTK_SOFTDEP;
2370                 mp->mnt_noasync++;
2371         }
2372         MNT_IUNLOCK(mp);
2373         ump = VFSTOUFS(mp);
2374         LIST_INIT(&ump->softdep_workitem_pending);
2375         LIST_INIT(&ump->softdep_journal_pending);
2376         TAILQ_INIT(&ump->softdep_unlinked);
2377         LIST_INIT(&ump->softdep_dirtycg);
2378         ump->softdep_worklist_tail = NULL;
2379         ump->softdep_on_worklist = 0;
2380         ump->softdep_deps = 0;
2381         if ((fs->fs_flags & FS_SUJ) &&
2382             (error = journal_mount(mp, fs, cred)) != 0) {
2383                 printf("Failed to start journal: %d\n", error);
2384                 return (error);
2385         }
2386         /*
2387          * When doing soft updates, the counters in the
2388          * superblock may have gotten out of sync. Recomputation
2389          * can take a long time and can be deferred for background
2390          * fsck.  However, the old behavior of scanning the cylinder
2391          * groups and recalculating them at mount time is available
2392          * by setting vfs.ffs.compute_summary_at_mount to one.
2393          */
2394         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2395                 return (0);
2396         bzero(&cstotal, sizeof cstotal);
2397         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2398                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2399                     fs->fs_cgsize, cred, &bp)) != 0) {
2400                         brelse(bp);
2401                         return (error);
2402                 }
2403                 cgp = (struct cg *)bp->b_data;
2404                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2405                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2406                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2407                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2408                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2409                 brelse(bp);
2410         }
2411 #ifdef DEBUG
2412         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2413                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2414 #endif
2415         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2416         return (0);
2417 }
2418
2419 void
2420 softdep_unmount(mp)
2421         struct mount *mp;
2422 {
2423
2424         MNT_ILOCK(mp);
2425         mp->mnt_flag &= ~MNT_SOFTDEP;
2426         if (MOUNTEDSUJ(mp) == 0) {
2427                 MNT_IUNLOCK(mp);
2428                 return;
2429         }
2430         mp->mnt_flag &= ~MNT_SUJ;
2431         MNT_IUNLOCK(mp);
2432         journal_unmount(mp);
2433 }
2434
2435 struct jblocks {
2436         struct jseglst  jb_segs;        /* TAILQ of current segments. */
2437         struct jseg     *jb_writeseg;   /* Next write to complete. */
2438         struct jseg     *jb_oldestseg;  /* Oldest segment with valid entries. */
2439         struct jextent  *jb_extent;     /* Extent array. */
2440         uint64_t        jb_nextseq;     /* Next sequence number. */
2441         uint64_t        jb_oldestwrseq; /* Oldest written sequence number. */
2442         uint8_t         jb_needseg;     /* Need a forced segment. */
2443         uint8_t         jb_suspended;   /* Did journal suspend writes? */
2444         int             jb_avail;       /* Available extents. */
2445         int             jb_used;        /* Last used extent. */
2446         int             jb_head;        /* Allocator head. */
2447         int             jb_off;         /* Allocator extent offset. */
2448         int             jb_blocks;      /* Total disk blocks covered. */
2449         int             jb_free;        /* Total disk blocks free. */
2450         int             jb_min;         /* Minimum free space. */
2451         int             jb_low;         /* Low on space. */
2452         int             jb_age;         /* Insertion time of oldest rec. */
2453 };
2454
2455 struct jextent {
2456         ufs2_daddr_t    je_daddr;       /* Disk block address. */
2457         int             je_blocks;      /* Disk block count. */
2458 };
2459
2460 static struct jblocks *
2461 jblocks_create(void)
2462 {
2463         struct jblocks *jblocks;
2464
2465         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2466         TAILQ_INIT(&jblocks->jb_segs);
2467         jblocks->jb_avail = 10;
2468         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2469             M_JBLOCKS, M_WAITOK | M_ZERO);
2470
2471         return (jblocks);
2472 }
2473
2474 static ufs2_daddr_t
2475 jblocks_alloc(jblocks, bytes, actual)
2476         struct jblocks *jblocks;
2477         int bytes;
2478         int *actual;
2479 {
2480         ufs2_daddr_t daddr;
2481         struct jextent *jext;
2482         int freecnt;
2483         int blocks;
2484
2485         blocks = bytes / DEV_BSIZE;
2486         jext = &jblocks->jb_extent[jblocks->jb_head];
2487         freecnt = jext->je_blocks - jblocks->jb_off;
2488         if (freecnt == 0) {
2489                 jblocks->jb_off = 0;
2490                 if (++jblocks->jb_head > jblocks->jb_used)
2491                         jblocks->jb_head = 0;
2492                 jext = &jblocks->jb_extent[jblocks->jb_head];
2493                 freecnt = jext->je_blocks;
2494         }
2495         if (freecnt > blocks)
2496                 freecnt = blocks;
2497         *actual = freecnt * DEV_BSIZE;
2498         daddr = jext->je_daddr + jblocks->jb_off;
2499         jblocks->jb_off += freecnt;
2500         jblocks->jb_free -= freecnt;
2501
2502         return (daddr);
2503 }
2504
2505 static void
2506 jblocks_free(jblocks, mp, bytes)
2507         struct jblocks *jblocks;
2508         struct mount *mp;
2509         int bytes;
2510 {
2511
2512         jblocks->jb_free += bytes / DEV_BSIZE;
2513         if (jblocks->jb_suspended)
2514                 worklist_speedup();
2515         wakeup(jblocks);
2516 }
2517
2518 static void
2519 jblocks_destroy(jblocks)
2520         struct jblocks *jblocks;
2521 {
2522
2523         if (jblocks->jb_extent)
2524                 free(jblocks->jb_extent, M_JBLOCKS);
2525         free(jblocks, M_JBLOCKS);
2526 }
2527
2528 static void
2529 jblocks_add(jblocks, daddr, blocks)
2530         struct jblocks *jblocks;
2531         ufs2_daddr_t daddr;
2532         int blocks;
2533 {
2534         struct jextent *jext;
2535
2536         jblocks->jb_blocks += blocks;
2537         jblocks->jb_free += blocks;
2538         jext = &jblocks->jb_extent[jblocks->jb_used];
2539         /* Adding the first block. */
2540         if (jext->je_daddr == 0) {
2541                 jext->je_daddr = daddr;
2542                 jext->je_blocks = blocks;
2543                 return;
2544         }
2545         /* Extending the last extent. */
2546         if (jext->je_daddr + jext->je_blocks == daddr) {
2547                 jext->je_blocks += blocks;
2548                 return;
2549         }
2550         /* Adding a new extent. */
2551         if (++jblocks->jb_used == jblocks->jb_avail) {
2552                 jblocks->jb_avail *= 2;
2553                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2554                     M_JBLOCKS, M_WAITOK | M_ZERO);
2555                 memcpy(jext, jblocks->jb_extent,
2556                     sizeof(struct jextent) * jblocks->jb_used);
2557                 free(jblocks->jb_extent, M_JBLOCKS);
2558                 jblocks->jb_extent = jext;
2559         }
2560         jext = &jblocks->jb_extent[jblocks->jb_used];
2561         jext->je_daddr = daddr;
2562         jext->je_blocks = blocks;
2563         return;
2564 }
2565
2566 int
2567 softdep_journal_lookup(mp, vpp)
2568         struct mount *mp;
2569         struct vnode **vpp;
2570 {
2571         struct componentname cnp;
2572         struct vnode *dvp;
2573         ino_t sujournal;
2574         int error;
2575
2576         error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2577         if (error)
2578                 return (error);
2579         bzero(&cnp, sizeof(cnp));
2580         cnp.cn_nameiop = LOOKUP;
2581         cnp.cn_flags = ISLASTCN;
2582         cnp.cn_thread = curthread;
2583         cnp.cn_cred = curthread->td_ucred;
2584         cnp.cn_pnbuf = SUJ_FILE;
2585         cnp.cn_nameptr = SUJ_FILE;
2586         cnp.cn_namelen = strlen(SUJ_FILE);
2587         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2588         vput(dvp);
2589         if (error != 0)
2590                 return (error);
2591         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2592         return (error);
2593 }
2594
2595 /*
2596  * Open and verify the journal file.
2597  */
2598 static int
2599 journal_mount(mp, fs, cred)
2600         struct mount *mp;
2601         struct fs *fs;
2602         struct ucred *cred;
2603 {
2604         struct jblocks *jblocks;
2605         struct vnode *vp;
2606         struct inode *ip;
2607         ufs2_daddr_t blkno;
2608         int bcount;
2609         int error;
2610         int i;
2611
2612         error = softdep_journal_lookup(mp, &vp);
2613         if (error != 0) {
2614                 printf("Failed to find journal.  Use tunefs to create one\n");
2615                 return (error);
2616         }
2617         ip = VTOI(vp);
2618         if (ip->i_size < SUJ_MIN) {
2619                 error = ENOSPC;
2620                 goto out;
2621         }
2622         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2623         jblocks = jblocks_create();
2624         for (i = 0; i < bcount; i++) {
2625                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2626                 if (error)
2627                         break;
2628                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2629         }
2630         if (error) {
2631                 jblocks_destroy(jblocks);
2632                 goto out;
2633         }
2634         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2635         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2636         VFSTOUFS(mp)->softdep_jblocks = jblocks;
2637 out:
2638         if (error == 0) {
2639                 MNT_ILOCK(mp);
2640                 mp->mnt_flag |= MNT_SUJ;
2641                 mp->mnt_flag &= ~MNT_SOFTDEP;
2642                 MNT_IUNLOCK(mp);
2643                 /*
2644                  * Only validate the journal contents if the
2645                  * filesystem is clean, otherwise we write the logs
2646                  * but they'll never be used.  If the filesystem was
2647                  * still dirty when we mounted it the journal is
2648                  * invalid and a new journal can only be valid if it
2649                  * starts from a clean mount.
2650                  */
2651                 if (fs->fs_clean) {
2652                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2653                         ip->i_flags |= IN_MODIFIED;
2654                         ffs_update(vp, 1);
2655                 }
2656         }
2657         vput(vp);
2658         return (error);
2659 }
2660
2661 static void
2662 journal_unmount(mp)
2663         struct mount *mp;
2664 {
2665         struct ufsmount *ump;
2666
2667         ump = VFSTOUFS(mp);
2668         if (ump->softdep_jblocks)
2669                 jblocks_destroy(ump->softdep_jblocks);
2670         ump->softdep_jblocks = NULL;
2671 }
2672
2673 /*
2674  * Called when a journal record is ready to be written.  Space is allocated
2675  * and the journal entry is created when the journal is flushed to stable
2676  * store.
2677  */
2678 static void
2679 add_to_journal(wk)
2680         struct worklist *wk;
2681 {
2682         struct ufsmount *ump;
2683
2684         mtx_assert(&lk, MA_OWNED);
2685         ump = VFSTOUFS(wk->wk_mp);
2686         if (wk->wk_state & ONWORKLIST)
2687                 panic("add_to_journal: %s(0x%X) already on list",
2688                     TYPENAME(wk->wk_type), wk->wk_state);
2689         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2690         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2691                 ump->softdep_jblocks->jb_age = ticks;
2692                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2693         } else
2694                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2695         ump->softdep_journal_tail = wk;
2696         ump->softdep_on_journal += 1;
2697 }
2698
2699 /*
2700  * Remove an arbitrary item for the journal worklist maintain the tail
2701  * pointer.  This happens when a new operation obviates the need to
2702  * journal an old operation.
2703  */
2704 static void
2705 remove_from_journal(wk)
2706         struct worklist *wk;
2707 {
2708         struct ufsmount *ump;
2709
2710         mtx_assert(&lk, MA_OWNED);
2711         ump = VFSTOUFS(wk->wk_mp);
2712 #ifdef SUJ_DEBUG
2713         {
2714                 struct worklist *wkn;
2715
2716                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2717                         if (wkn == wk)
2718                                 break;
2719                 if (wkn == NULL)
2720                         panic("remove_from_journal: %p is not in journal", wk);
2721         }
2722 #endif
2723         /*
2724          * We emulate a TAILQ to save space in most structures which do not
2725          * require TAILQ semantics.  Here we must update the tail position
2726          * when removing the tail which is not the final entry. This works
2727          * only if the worklist linkage are at the beginning of the structure.
2728          */
2729         if (ump->softdep_journal_tail == wk)
2730                 ump->softdep_journal_tail =
2731                     (struct worklist *)wk->wk_list.le_prev;
2732
2733         WORKLIST_REMOVE(wk);
2734         ump->softdep_on_journal -= 1;
2735 }
2736
2737 /*
2738  * Check for journal space as well as dependency limits so the prelink
2739  * code can throttle both journaled and non-journaled filesystems.
2740  * Threshold is 0 for low and 1 for min.
2741  */
2742 static int
2743 journal_space(ump, thresh)
2744         struct ufsmount *ump;
2745         int thresh;
2746 {
2747         struct jblocks *jblocks;
2748         int avail;
2749
2750         jblocks = ump->softdep_jblocks;
2751         if (jblocks == NULL)
2752                 return (1);
2753         /*
2754          * We use a tighter restriction here to prevent request_cleanup()
2755          * running in threads from running into locks we currently hold.
2756          */
2757         if (dep_current[D_INODEDEP] > (max_softdeps / 10) * 9)
2758                 return (0);
2759         if (thresh)
2760                 thresh = jblocks->jb_min;
2761         else
2762                 thresh = jblocks->jb_low;
2763         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2764         avail = jblocks->jb_free - avail;
2765
2766         return (avail > thresh);
2767 }
2768
2769 static void
2770 journal_suspend(ump)
2771         struct ufsmount *ump;
2772 {
2773         struct jblocks *jblocks;
2774         struct mount *mp;
2775
2776         mp = UFSTOVFS(ump);
2777         jblocks = ump->softdep_jblocks;
2778         MNT_ILOCK(mp);
2779         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2780                 stat_journal_min++;
2781                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2782                 mp->mnt_susp_owner = FIRST_THREAD_IN_PROC(softdepproc);
2783         }
2784         jblocks->jb_suspended = 1;
2785         MNT_IUNLOCK(mp);
2786 }
2787
2788 static int
2789 journal_unsuspend(struct ufsmount *ump)
2790 {
2791         struct jblocks *jblocks;
2792         struct mount *mp;
2793
2794         mp = UFSTOVFS(ump);
2795         jblocks = ump->softdep_jblocks;
2796
2797         if (jblocks != NULL && jblocks->jb_suspended &&
2798             journal_space(ump, jblocks->jb_min)) {
2799                 jblocks->jb_suspended = 0;
2800                 FREE_LOCK(&lk);
2801                 mp->mnt_susp_owner = curthread;
2802                 vfs_write_resume(mp);
2803                 ACQUIRE_LOCK(&lk);
2804                 return (1);
2805         }
2806         return (0);
2807 }
2808
2809 /*
2810  * Called before any allocation function to be certain that there is
2811  * sufficient space in the journal prior to creating any new records.
2812  * Since in the case of block allocation we may have multiple locked
2813  * buffers at the time of the actual allocation we can not block
2814  * when the journal records are created.  Doing so would create a deadlock
2815  * if any of these buffers needed to be flushed to reclaim space.  Instead
2816  * we require a sufficiently large amount of available space such that
2817  * each thread in the system could have passed this allocation check and
2818  * still have sufficient free space.  With 20% of a minimum journal size
2819  * of 1MB we have 6553 records available.
2820  */
2821 int
2822 softdep_prealloc(vp, waitok)
2823         struct vnode *vp;
2824         int waitok;
2825 {
2826         struct ufsmount *ump;
2827
2828         if (DOINGSUJ(vp) == 0)
2829                 return (0);
2830         ump = VFSTOUFS(vp->v_mount);
2831         ACQUIRE_LOCK(&lk);
2832         if (journal_space(ump, 0)) {
2833                 FREE_LOCK(&lk);
2834                 return (0);
2835         }
2836         stat_journal_low++;
2837         FREE_LOCK(&lk);
2838         if (waitok == MNT_NOWAIT)
2839                 return (ENOSPC);
2840         /*
2841          * Attempt to sync this vnode once to flush any journal
2842          * work attached to it.
2843          */
2844         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
2845                 ffs_syncvnode(vp, waitok);
2846         ACQUIRE_LOCK(&lk);
2847         process_removes(vp);
2848         process_truncates(vp);
2849         if (journal_space(ump, 0) == 0) {
2850                 softdep_speedup();
2851                 if (journal_space(ump, 1) == 0)
2852                         journal_suspend(ump);
2853         }
2854         FREE_LOCK(&lk);
2855
2856         return (0);
2857 }
2858
2859 /*
2860  * Before adjusting a link count on a vnode verify that we have sufficient
2861  * journal space.  If not, process operations that depend on the currently
2862  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
2863  * and softdep flush threads can not acquire these locks to reclaim space.
2864  */
2865 static void
2866 softdep_prelink(dvp, vp)
2867         struct vnode *dvp;
2868         struct vnode *vp;
2869 {
2870         struct ufsmount *ump;
2871
2872         ump = VFSTOUFS(dvp->v_mount);
2873         mtx_assert(&lk, MA_OWNED);
2874         if (journal_space(ump, 0))
2875                 return;
2876         stat_journal_low++;
2877         FREE_LOCK(&lk);
2878         if (vp)
2879                 ffs_syncvnode(vp, MNT_NOWAIT);
2880         ffs_syncvnode(dvp, MNT_WAIT);
2881         ACQUIRE_LOCK(&lk);
2882         /* Process vp before dvp as it may create .. removes. */
2883         if (vp) {
2884                 process_removes(vp);
2885                 process_truncates(vp);
2886         }
2887         process_removes(dvp);
2888         process_truncates(dvp);
2889         softdep_speedup();
2890         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
2891         if (journal_space(ump, 0) == 0) {
2892                 softdep_speedup();
2893                 if (journal_space(ump, 1) == 0)
2894                         journal_suspend(ump);
2895         }
2896 }
2897
2898 static void
2899 jseg_write(ump, jseg, data)
2900         struct ufsmount *ump;
2901         struct jseg *jseg;
2902         uint8_t *data;
2903 {
2904         struct jsegrec *rec;
2905
2906         rec = (struct jsegrec *)data;
2907         rec->jsr_seq = jseg->js_seq;
2908         rec->jsr_oldest = jseg->js_oldseq;
2909         rec->jsr_cnt = jseg->js_cnt;
2910         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
2911         rec->jsr_crc = 0;
2912         rec->jsr_time = ump->um_fs->fs_mtime;
2913 }
2914
2915 static inline void
2916 inoref_write(inoref, jseg, rec)
2917         struct inoref *inoref;
2918         struct jseg *jseg;
2919         struct jrefrec *rec;
2920 {
2921
2922         inoref->if_jsegdep->jd_seg = jseg;
2923         rec->jr_ino = inoref->if_ino;
2924         rec->jr_parent = inoref->if_parent;
2925         rec->jr_nlink = inoref->if_nlink;
2926         rec->jr_mode = inoref->if_mode;
2927         rec->jr_diroff = inoref->if_diroff;
2928 }
2929
2930 static void
2931 jaddref_write(jaddref, jseg, data)
2932         struct jaddref *jaddref;
2933         struct jseg *jseg;
2934         uint8_t *data;
2935 {
2936         struct jrefrec *rec;
2937
2938         rec = (struct jrefrec *)data;
2939         rec->jr_op = JOP_ADDREF;
2940         inoref_write(&jaddref->ja_ref, jseg, rec);
2941 }
2942
2943 static void
2944 jremref_write(jremref, jseg, data)
2945         struct jremref *jremref;
2946         struct jseg *jseg;
2947         uint8_t *data;
2948 {
2949         struct jrefrec *rec;
2950
2951         rec = (struct jrefrec *)data;
2952         rec->jr_op = JOP_REMREF;
2953         inoref_write(&jremref->jr_ref, jseg, rec);
2954 }
2955
2956 static void
2957 jmvref_write(jmvref, jseg, data)
2958         struct jmvref *jmvref;
2959         struct jseg *jseg;
2960         uint8_t *data;
2961 {
2962         struct jmvrec *rec;
2963
2964         rec = (struct jmvrec *)data;
2965         rec->jm_op = JOP_MVREF;
2966         rec->jm_ino = jmvref->jm_ino;
2967         rec->jm_parent = jmvref->jm_parent;
2968         rec->jm_oldoff = jmvref->jm_oldoff;
2969         rec->jm_newoff = jmvref->jm_newoff;
2970 }
2971
2972 static void
2973 jnewblk_write(jnewblk, jseg, data)
2974         struct jnewblk *jnewblk;
2975         struct jseg *jseg;
2976         uint8_t *data;
2977 {
2978         struct jblkrec *rec;
2979
2980         jnewblk->jn_jsegdep->jd_seg = jseg;
2981         rec = (struct jblkrec *)data;
2982         rec->jb_op = JOP_NEWBLK;
2983         rec->jb_ino = jnewblk->jn_ino;
2984         rec->jb_blkno = jnewblk->jn_blkno;
2985         rec->jb_lbn = jnewblk->jn_lbn;
2986         rec->jb_frags = jnewblk->jn_frags;
2987         rec->jb_oldfrags = jnewblk->jn_oldfrags;
2988 }
2989
2990 static void
2991 jfreeblk_write(jfreeblk, jseg, data)
2992         struct jfreeblk *jfreeblk;
2993         struct jseg *jseg;
2994         uint8_t *data;
2995 {
2996         struct jblkrec *rec;
2997
2998         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
2999         rec = (struct jblkrec *)data;
3000         rec->jb_op = JOP_FREEBLK;
3001         rec->jb_ino = jfreeblk->jf_ino;
3002         rec->jb_blkno = jfreeblk->jf_blkno;
3003         rec->jb_lbn = jfreeblk->jf_lbn;
3004         rec->jb_frags = jfreeblk->jf_frags;
3005         rec->jb_oldfrags = 0;
3006 }
3007
3008 static void
3009 jfreefrag_write(jfreefrag, jseg, data)
3010         struct jfreefrag *jfreefrag;
3011         struct jseg *jseg;
3012         uint8_t *data;
3013 {
3014         struct jblkrec *rec;
3015
3016         jfreefrag->fr_jsegdep->jd_seg = jseg;
3017         rec = (struct jblkrec *)data;
3018         rec->jb_op = JOP_FREEBLK;
3019         rec->jb_ino = jfreefrag->fr_ino;
3020         rec->jb_blkno = jfreefrag->fr_blkno;
3021         rec->jb_lbn = jfreefrag->fr_lbn;
3022         rec->jb_frags = jfreefrag->fr_frags;
3023         rec->jb_oldfrags = 0;
3024 }
3025
3026 static void
3027 jtrunc_write(jtrunc, jseg, data)
3028         struct jtrunc *jtrunc;
3029         struct jseg *jseg;
3030         uint8_t *data;
3031 {
3032         struct jtrncrec *rec;
3033
3034         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3035         rec = (struct jtrncrec *)data;
3036         rec->jt_op = JOP_TRUNC;
3037         rec->jt_ino = jtrunc->jt_ino;
3038         rec->jt_size = jtrunc->jt_size;
3039         rec->jt_extsize = jtrunc->jt_extsize;
3040 }
3041
3042 static void
3043 jfsync_write(jfsync, jseg, data)
3044         struct jfsync *jfsync;
3045         struct jseg *jseg;
3046         uint8_t *data;
3047 {
3048         struct jtrncrec *rec;
3049
3050         rec = (struct jtrncrec *)data;
3051         rec->jt_op = JOP_SYNC;
3052         rec->jt_ino = jfsync->jfs_ino;
3053         rec->jt_size = jfsync->jfs_size;
3054         rec->jt_extsize = jfsync->jfs_extsize;
3055 }
3056
3057 static void
3058 softdep_flushjournal(mp)
3059         struct mount *mp;
3060 {
3061         struct jblocks *jblocks;
3062         struct ufsmount *ump;
3063
3064         if (MOUNTEDSUJ(mp) == 0)
3065                 return;
3066         ump = VFSTOUFS(mp);
3067         jblocks = ump->softdep_jblocks;
3068         ACQUIRE_LOCK(&lk);
3069         while (ump->softdep_on_journal) {
3070                 jblocks->jb_needseg = 1;
3071                 softdep_process_journal(mp, NULL, MNT_WAIT);
3072         }
3073         FREE_LOCK(&lk);
3074 }
3075
3076 /*
3077  * Flush some journal records to disk.
3078  */
3079 static void
3080 softdep_process_journal(mp, needwk, flags)
3081         struct mount *mp;
3082         struct worklist *needwk;
3083         int flags;
3084 {
3085         struct jblocks *jblocks;
3086         struct ufsmount *ump;
3087         struct worklist *wk;
3088         struct jseg *jseg;
3089         struct buf *bp;
3090         uint8_t *data;
3091         struct fs *fs;
3092         int segwritten;
3093         int jrecmin;    /* Minimum records per block. */
3094         int jrecmax;    /* Maximum records per block. */
3095         int size;
3096         int cnt;
3097         int off;
3098         int devbsize;
3099
3100         if (MOUNTEDSUJ(mp) == 0)
3101                 return;
3102         ump = VFSTOUFS(mp);
3103         fs = ump->um_fs;
3104         jblocks = ump->softdep_jblocks;
3105         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3106         /*
3107          * We write anywhere between a disk block and fs block.  The upper
3108          * bound is picked to prevent buffer cache fragmentation and limit
3109          * processing time per I/O.
3110          */
3111         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3112         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3113         segwritten = 0;
3114         for (;;) {
3115                 cnt = ump->softdep_on_journal;
3116                 /*
3117                  * Criteria for writing a segment:
3118                  * 1) We have a full block.
3119                  * 2) We're called from jwait() and haven't found the
3120                  *    journal item yet.
3121                  * 3) Always write if needseg is set.
3122                  * 4) If we are called from process_worklist and have
3123                  *    not yet written anything we write a partial block
3124                  *    to enforce a 1 second maximum latency on journal
3125                  *    entries.
3126                  */
3127                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3128                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3129                         break;
3130                 cnt++;
3131                 /*
3132                  * Verify some free journal space.  softdep_prealloc() should
3133                  * guarantee that we don't run out so this is indicative of
3134                  * a problem with the flow control.  Try to recover
3135                  * gracefully in any event.
3136                  */
3137                 while (jblocks->jb_free == 0) {
3138                         if (flags != MNT_WAIT)
3139                                 break;
3140                         printf("softdep: Out of journal space!\n");
3141                         softdep_speedup();
3142                         msleep(jblocks, &lk, PRIBIO, "jblocks", hz);
3143                 }
3144                 FREE_LOCK(&lk);
3145                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3146                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3147                 LIST_INIT(&jseg->js_entries);
3148                 LIST_INIT(&jseg->js_indirs);
3149                 jseg->js_state = ATTACHED;
3150                 jseg->js_jblocks = jblocks;
3151                 bp = geteblk(fs->fs_bsize, 0);
3152                 ACQUIRE_LOCK(&lk);
3153                 /*
3154                  * If there was a race while we were allocating the block
3155                  * and jseg the entry we care about was likely written.
3156                  * We bail out in both the WAIT and NOWAIT case and assume
3157                  * the caller will loop if the entry it cares about is
3158                  * not written.
3159                  */
3160                 cnt = ump->softdep_on_journal;
3161                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3162                         bp->b_flags |= B_INVAL | B_NOCACHE;
3163                         WORKITEM_FREE(jseg, D_JSEG);
3164                         FREE_LOCK(&lk);
3165                         brelse(bp);
3166                         ACQUIRE_LOCK(&lk);
3167                         break;
3168                 }
3169                 /*
3170                  * Calculate the disk block size required for the available
3171                  * records rounded to the min size.
3172                  */
3173                 if (cnt == 0)
3174                         size = devbsize;
3175                 else if (cnt < jrecmax)
3176                         size = howmany(cnt, jrecmin) * devbsize;
3177                 else
3178                         size = fs->fs_bsize;
3179                 /*
3180                  * Allocate a disk block for this journal data and account
3181                  * for truncation of the requested size if enough contiguous
3182                  * space was not available.
3183                  */
3184                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3185                 bp->b_lblkno = bp->b_blkno;
3186                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3187                 bp->b_bcount = size;
3188                 bp->b_bufobj = &ump->um_devvp->v_bufobj;
3189                 bp->b_flags &= ~B_INVAL;
3190                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3191                 /*
3192                  * Initialize our jseg with cnt records.  Assign the next
3193                  * sequence number to it and link it in-order.
3194                  */
3195                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3196                 jseg->js_buf = bp;
3197                 jseg->js_cnt = cnt;
3198                 jseg->js_refs = cnt + 1;        /* Self ref. */
3199                 jseg->js_size = size;
3200                 jseg->js_seq = jblocks->jb_nextseq++;
3201                 if (jblocks->jb_oldestseg == NULL)
3202                         jblocks->jb_oldestseg = jseg;
3203                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3204                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3205                 if (jblocks->jb_writeseg == NULL)
3206                         jblocks->jb_writeseg = jseg;
3207                 /*
3208                  * Start filling in records from the pending list.
3209                  */
3210                 data = bp->b_data;
3211                 off = 0;
3212                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3213                     != NULL) {
3214                         if (cnt == 0)
3215                                 break;
3216                         /* Place a segment header on every device block. */
3217                         if ((off % devbsize) == 0) {
3218                                 jseg_write(ump, jseg, data);
3219                                 off += JREC_SIZE;
3220                                 data = bp->b_data + off;
3221                         }
3222                         if (wk == needwk)
3223                                 needwk = NULL;
3224                         remove_from_journal(wk);
3225                         wk->wk_state |= INPROGRESS;
3226                         WORKLIST_INSERT(&jseg->js_entries, wk);
3227                         switch (wk->wk_type) {
3228                         case D_JADDREF:
3229                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3230                                 break;
3231                         case D_JREMREF:
3232                                 jremref_write(WK_JREMREF(wk), jseg, data);
3233                                 break;
3234                         case D_JMVREF:
3235                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3236                                 break;
3237                         case D_JNEWBLK:
3238                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3239                                 break;
3240                         case D_JFREEBLK:
3241                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3242                                 break;
3243                         case D_JFREEFRAG:
3244                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3245                                 break;
3246                         case D_JTRUNC:
3247                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3248                                 break;
3249                         case D_JFSYNC:
3250                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3251                                 break;
3252                         default:
3253                                 panic("process_journal: Unknown type %s",
3254                                     TYPENAME(wk->wk_type));
3255                                 /* NOTREACHED */
3256                         }
3257                         off += JREC_SIZE;
3258                         data = bp->b_data + off;
3259                         cnt--;
3260                 }
3261                 /*
3262                  * Write this one buffer and continue.
3263                  */
3264                 segwritten = 1;
3265                 jblocks->jb_needseg = 0;
3266                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3267                 FREE_LOCK(&lk);
3268                 BO_LOCK(bp->b_bufobj);
3269                 bgetvp(ump->um_devvp, bp);
3270                 BO_UNLOCK(bp->b_bufobj);
3271                 /*
3272                  * We only do the blocking wait once we find the journal
3273                  * entry we're looking for.
3274                  */
3275                 if (needwk == NULL && flags == MNT_WAIT)
3276                         bwrite(bp);
3277                 else
3278                         bawrite(bp);
3279                 ACQUIRE_LOCK(&lk);
3280         }
3281         /*
3282          * If we've suspended the filesystem because we ran out of journal
3283          * space either try to sync it here to make some progress or
3284          * unsuspend it if we already have.
3285          */
3286         if (flags == 0 && jblocks->jb_suspended) {
3287                 if (journal_unsuspend(ump))
3288                         return;
3289                 FREE_LOCK(&lk);
3290                 VFS_SYNC(mp, MNT_NOWAIT);
3291                 ffs_sbupdate(ump, MNT_WAIT, 0);
3292                 ACQUIRE_LOCK(&lk);
3293         }
3294 }
3295
3296 /*
3297  * Complete a jseg, allowing all dependencies awaiting journal writes
3298  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3299  * structures so that the journal segment can be freed to reclaim space.
3300  */
3301 static void
3302 complete_jseg(jseg)
3303         struct jseg *jseg;
3304 {
3305         struct worklist *wk;
3306         struct jmvref *jmvref;
3307         int waiting;
3308 #ifdef INVARIANTS
3309         int i = 0;
3310 #endif
3311
3312         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3313                 WORKLIST_REMOVE(wk);
3314                 waiting = wk->wk_state & IOWAITING;
3315                 wk->wk_state &= ~(INPROGRESS | IOWAITING);
3316                 wk->wk_state |= COMPLETE;
3317                 KASSERT(i++ < jseg->js_cnt,
3318                     ("handle_written_jseg: overflow %d >= %d",
3319                     i - 1, jseg->js_cnt));
3320                 switch (wk->wk_type) {
3321                 case D_JADDREF:
3322                         handle_written_jaddref(WK_JADDREF(wk));
3323                         break;
3324                 case D_JREMREF:
3325                         handle_written_jremref(WK_JREMREF(wk));
3326                         break;
3327                 case D_JMVREF:
3328                         rele_jseg(jseg);        /* No jsegdep. */
3329                         jmvref = WK_JMVREF(wk);
3330                         LIST_REMOVE(jmvref, jm_deps);
3331                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3332                                 free_pagedep(jmvref->jm_pagedep);
3333                         WORKITEM_FREE(jmvref, D_JMVREF);
3334                         break;
3335                 case D_JNEWBLK:
3336                         handle_written_jnewblk(WK_JNEWBLK(wk));
3337                         break;
3338                 case D_JFREEBLK:
3339                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3340                         break;
3341                 case D_JTRUNC:
3342                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3343                         break;
3344                 case D_JFSYNC:
3345                         rele_jseg(jseg);        /* No jsegdep. */
3346                         WORKITEM_FREE(wk, D_JFSYNC);
3347                         break;
3348                 case D_JFREEFRAG:
3349                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3350                         break;
3351                 default:
3352                         panic("handle_written_jseg: Unknown type %s",
3353                             TYPENAME(wk->wk_type));
3354                         /* NOTREACHED */
3355                 }
3356                 if (waiting)
3357                         wakeup(wk);
3358         }
3359         /* Release the self reference so the structure may be freed. */
3360         rele_jseg(jseg);
3361 }
3362
3363 /*
3364  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Handle jseg
3365  * completions in order only.
3366  */
3367 static void
3368 handle_written_jseg(jseg, bp)
3369         struct jseg *jseg;
3370         struct buf *bp;
3371 {
3372         struct jblocks *jblocks;
3373         struct jseg *jsegn;
3374
3375         if (jseg->js_refs == 0)
3376                 panic("handle_written_jseg: No self-reference on %p", jseg);
3377         jseg->js_state |= DEPCOMPLETE;
3378         /*
3379          * We'll never need this buffer again, set flags so it will be
3380          * discarded.
3381          */
3382         bp->b_flags |= B_INVAL | B_NOCACHE;
3383         jblocks = jseg->js_jblocks;
3384         /*
3385          * Don't allow out of order completions.  If this isn't the first
3386          * block wait for it to write before we're done.
3387          */
3388         if (jseg != jblocks->jb_writeseg)
3389                 return;
3390         /* Iterate through available jsegs processing their entries. */
3391         do {
3392                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3393                 jsegn = TAILQ_NEXT(jseg, js_next);
3394                 complete_jseg(jseg);
3395                 jseg = jsegn;
3396         } while (jseg && jseg->js_state & DEPCOMPLETE);
3397         jblocks->jb_writeseg = jseg;
3398         /*
3399          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3400          */
3401         free_jsegs(jblocks);
3402 }
3403
3404 static inline struct jsegdep *
3405 inoref_jseg(inoref)
3406         struct inoref *inoref;
3407 {
3408         struct jsegdep *jsegdep;
3409
3410         jsegdep = inoref->if_jsegdep;
3411         inoref->if_jsegdep = NULL;
3412
3413         return (jsegdep);
3414 }
3415
3416 /*
3417  * Called once a jremref has made it to stable store.  The jremref is marked
3418  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3419  * for the jremref to complete will be awoken by free_jremref.
3420  */
3421 static void
3422 handle_written_jremref(jremref)
3423         struct jremref *jremref;
3424 {
3425         struct inodedep *inodedep;
3426         struct jsegdep *jsegdep;
3427         struct dirrem *dirrem;
3428
3429         /* Grab the jsegdep. */
3430         jsegdep = inoref_jseg(&jremref->jr_ref);
3431         /*
3432          * Remove us from the inoref list.
3433          */
3434         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3435             0, &inodedep) == 0)
3436                 panic("handle_written_jremref: Lost inodedep");
3437         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3438         /*
3439          * Complete the dirrem.
3440          */
3441         dirrem = jremref->jr_dirrem;
3442         jremref->jr_dirrem = NULL;
3443         LIST_REMOVE(jremref, jr_deps);
3444         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3445         jwork_insert(&dirrem->dm_jwork, jsegdep);
3446         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3447             (dirrem->dm_state & COMPLETE) != 0)
3448                 add_to_worklist(&dirrem->dm_list, 0);
3449         free_jremref(jremref);
3450 }
3451
3452 /*
3453  * Called once a jaddref has made it to stable store.  The dependency is
3454  * marked complete and any dependent structures are added to the inode
3455  * bufwait list to be completed as soon as it is written.  If a bitmap write
3456  * depends on this entry we move the inode into the inodedephd of the
3457  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3458  */
3459 static void
3460 handle_written_jaddref(jaddref)
3461         struct jaddref *jaddref;
3462 {
3463         struct jsegdep *jsegdep;
3464         struct inodedep *inodedep;
3465         struct diradd *diradd;
3466         struct mkdir *mkdir;
3467
3468         /* Grab the jsegdep. */
3469         jsegdep = inoref_jseg(&jaddref->ja_ref);
3470         mkdir = NULL;
3471         diradd = NULL;
3472         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3473             0, &inodedep) == 0)
3474                 panic("handle_written_jaddref: Lost inodedep.");
3475         if (jaddref->ja_diradd == NULL)
3476                 panic("handle_written_jaddref: No dependency");
3477         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3478                 diradd = jaddref->ja_diradd;
3479                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3480         } else if (jaddref->ja_state & MKDIR_PARENT) {
3481                 mkdir = jaddref->ja_mkdir;
3482                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3483         } else if (jaddref->ja_state & MKDIR_BODY)
3484                 mkdir = jaddref->ja_mkdir;
3485         else
3486                 panic("handle_written_jaddref: Unknown dependency %p",
3487                     jaddref->ja_diradd);
3488         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3489         /*
3490          * Remove us from the inode list.
3491          */
3492         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3493         /*
3494          * The mkdir may be waiting on the jaddref to clear before freeing.
3495          */
3496         if (mkdir) {
3497                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3498                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3499                     TYPENAME(mkdir->md_list.wk_type)));
3500                 mkdir->md_jaddref = NULL;
3501                 diradd = mkdir->md_diradd;
3502                 mkdir->md_state |= DEPCOMPLETE;
3503                 complete_mkdir(mkdir);
3504         }
3505         jwork_insert(&diradd->da_jwork, jsegdep);
3506         if (jaddref->ja_state & NEWBLOCK) {
3507                 inodedep->id_state |= ONDEPLIST;
3508                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3509                     inodedep, id_deps);
3510         }
3511         free_jaddref(jaddref);
3512 }
3513
3514 /*
3515  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3516  * is placed in the bmsafemap to await notification of a written bitmap.  If
3517  * the operation was canceled we add the segdep to the appropriate
3518  * dependency to free the journal space once the canceling operation
3519  * completes.
3520  */
3521 static void
3522 handle_written_jnewblk(jnewblk)
3523         struct jnewblk *jnewblk;
3524 {
3525         struct bmsafemap *bmsafemap;
3526         struct freefrag *freefrag;
3527         struct freework *freework;
3528         struct jsegdep *jsegdep;
3529         struct newblk *newblk;
3530
3531         /* Grab the jsegdep. */
3532         jsegdep = jnewblk->jn_jsegdep;
3533         jnewblk->jn_jsegdep = NULL;
3534         if (jnewblk->jn_dep == NULL) 
3535                 panic("handle_written_jnewblk: No dependency for the segdep.");
3536         switch (jnewblk->jn_dep->wk_type) {
3537         case D_NEWBLK:
3538         case D_ALLOCDIRECT:
3539         case D_ALLOCINDIR:
3540                 /*
3541                  * Add the written block to the bmsafemap so it can
3542                  * be notified when the bitmap is on disk.
3543                  */
3544                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3545                 newblk->nb_jnewblk = NULL;
3546                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3547                         bmsafemap = newblk->nb_bmsafemap;
3548                         newblk->nb_state |= ONDEPLIST;
3549                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3550                             nb_deps);
3551                 }
3552                 jwork_insert(&newblk->nb_jwork, jsegdep);
3553                 break;
3554         case D_FREEFRAG:
3555                 /*
3556                  * A newblock being removed by a freefrag when replaced by
3557                  * frag extension.
3558                  */
3559                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3560                 freefrag->ff_jdep = NULL;
3561                 WORKLIST_INSERT(&freefrag->ff_jwork, &jsegdep->jd_list);
3562                 break;
3563         case D_FREEWORK:
3564                 /*
3565                  * A direct block was removed by truncate.
3566                  */
3567                 freework = WK_FREEWORK(jnewblk->jn_dep);
3568                 freework->fw_jnewblk = NULL;
3569                 WORKLIST_INSERT(&freework->fw_freeblks->fb_jwork,
3570                     &jsegdep->jd_list);
3571                 break;
3572         default:
3573                 panic("handle_written_jnewblk: Unknown type %d.",
3574                     jnewblk->jn_dep->wk_type);
3575         }
3576         jnewblk->jn_dep = NULL;
3577         free_jnewblk(jnewblk);
3578 }
3579
3580 /*
3581  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3582  * an in-flight allocation that has not yet been committed.  Divorce us
3583  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3584  * to the worklist.
3585  */
3586 static void
3587 cancel_jfreefrag(jfreefrag)
3588         struct jfreefrag *jfreefrag;
3589 {
3590         struct freefrag *freefrag;
3591
3592         if (jfreefrag->fr_jsegdep) {
3593                 free_jsegdep(jfreefrag->fr_jsegdep);
3594                 jfreefrag->fr_jsegdep = NULL;
3595         }
3596         freefrag = jfreefrag->fr_freefrag;
3597         jfreefrag->fr_freefrag = NULL;
3598         free_jfreefrag(jfreefrag);
3599         freefrag->ff_state |= DEPCOMPLETE;
3600 }
3601
3602 /*
3603  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3604  */
3605 static void
3606 free_jfreefrag(jfreefrag)
3607         struct jfreefrag *jfreefrag;
3608 {
3609
3610         if (jfreefrag->fr_state & INPROGRESS)
3611                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3612         else if (jfreefrag->fr_state & ONWORKLIST)
3613                 remove_from_journal(&jfreefrag->fr_list);
3614         if (jfreefrag->fr_freefrag != NULL)
3615                 panic("free_jfreefrag:  Still attached to a freefrag.");
3616         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3617 }
3618
3619 /*
3620  * Called when the journal write for a jfreefrag completes.  The parent
3621  * freefrag is added to the worklist if this completes its dependencies.
3622  */
3623 static void
3624 handle_written_jfreefrag(jfreefrag)
3625         struct jfreefrag *jfreefrag;
3626 {
3627         struct jsegdep *jsegdep;
3628         struct freefrag *freefrag;
3629
3630         /* Grab the jsegdep. */
3631         jsegdep = jfreefrag->fr_jsegdep;
3632         jfreefrag->fr_jsegdep = NULL;
3633         freefrag = jfreefrag->fr_freefrag;
3634         if (freefrag == NULL)
3635                 panic("handle_written_jfreefrag: No freefrag.");
3636         freefrag->ff_state |= DEPCOMPLETE;
3637         freefrag->ff_jdep = NULL;
3638         jwork_insert(&freefrag->ff_jwork, jsegdep);
3639         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3640                 add_to_worklist(&freefrag->ff_list, 0);
3641         jfreefrag->fr_freefrag = NULL;
3642         free_jfreefrag(jfreefrag);
3643 }
3644
3645 /*
3646  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3647  * is removed from the freeblks list of pending journal writes and the
3648  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3649  * have been reclaimed.
3650  */
3651 static void
3652 handle_written_jblkdep(jblkdep)
3653         struct jblkdep *jblkdep;
3654 {
3655         struct freeblks *freeblks;
3656         struct jsegdep *jsegdep;
3657
3658         /* Grab the jsegdep. */
3659         jsegdep = jblkdep->jb_jsegdep;
3660         jblkdep->jb_jsegdep = NULL;
3661         freeblks = jblkdep->jb_freeblks;
3662         LIST_REMOVE(jblkdep, jb_deps);
3663         WORKLIST_INSERT(&freeblks->fb_jwork, &jsegdep->jd_list);
3664         /*
3665          * If the freeblks is all journaled, we can add it to the worklist.
3666          */
3667         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3668             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3669                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3670
3671         free_jblkdep(jblkdep);
3672 }
3673
3674 static struct jsegdep *
3675 newjsegdep(struct worklist *wk)
3676 {
3677         struct jsegdep *jsegdep;
3678
3679         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3680         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3681         jsegdep->jd_seg = NULL;
3682
3683         return (jsegdep);
3684 }
3685
3686 static struct jmvref *
3687 newjmvref(dp, ino, oldoff, newoff)
3688         struct inode *dp;
3689         ino_t ino;
3690         off_t oldoff;
3691         off_t newoff;
3692 {
3693         struct jmvref *jmvref;
3694
3695         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3696         workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3697         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3698         jmvref->jm_parent = dp->i_number;
3699         jmvref->jm_ino = ino;
3700         jmvref->jm_oldoff = oldoff;
3701         jmvref->jm_newoff = newoff;
3702
3703         return (jmvref);
3704 }
3705
3706 /*
3707  * Allocate a new jremref that tracks the removal of ip from dp with the
3708  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3709  * DEPCOMPLETE as we have all the information required for the journal write
3710  * and the directory has already been removed from the buffer.  The caller
3711  * is responsible for linking the jremref into the pagedep and adding it
3712  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
3713  * a DOTDOT addition so handle_workitem_remove() can properly assign
3714  * the jsegdep when we're done.
3715  */
3716 static struct jremref *
3717 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
3718     off_t diroff, nlink_t nlink)
3719 {
3720         struct jremref *jremref;
3721
3722         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
3723         workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
3724         jremref->jr_state = ATTACHED;
3725         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
3726            nlink, ip->i_mode);
3727         jremref->jr_dirrem = dirrem;
3728
3729         return (jremref);
3730 }
3731
3732 static inline void
3733 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
3734     nlink_t nlink, uint16_t mode)
3735 {
3736
3737         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
3738         inoref->if_diroff = diroff;
3739         inoref->if_ino = ino;
3740         inoref->if_parent = parent;
3741         inoref->if_nlink = nlink;
3742         inoref->if_mode = mode;
3743 }
3744
3745 /*
3746  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
3747  * directory offset may not be known until later.  The caller is responsible
3748  * adding the entry to the journal when this information is available.  nlink
3749  * should be the link count prior to the addition and mode is only required
3750  * to have the correct FMT.
3751  */
3752 static struct jaddref *
3753 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
3754     uint16_t mode)
3755 {
3756         struct jaddref *jaddref;
3757
3758         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
3759         workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
3760         jaddref->ja_state = ATTACHED;
3761         jaddref->ja_mkdir = NULL;
3762         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
3763
3764         return (jaddref);
3765 }
3766
3767 /*
3768  * Create a new free dependency for a freework.  The caller is responsible
3769  * for adjusting the reference count when it has the lock held.  The freedep
3770  * will track an outstanding bitmap write that will ultimately clear the
3771  * freework to continue.
3772  */
3773 static struct freedep *
3774 newfreedep(struct freework *freework)
3775 {
3776         struct freedep *freedep;
3777
3778         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
3779         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
3780         freedep->fd_freework = freework;
3781
3782         return (freedep);
3783 }
3784
3785 /*
3786  * Free a freedep structure once the buffer it is linked to is written.  If
3787  * this is the last reference to the freework schedule it for completion.
3788  */
3789 static void
3790 free_freedep(freedep)
3791         struct freedep *freedep;
3792 {
3793         struct freework *freework;
3794
3795         freework = freedep->fd_freework;
3796         freework->fw_freeblks->fb_cgwait--;
3797         if (--freework->fw_ref == 0)
3798                 freework_enqueue(freework);
3799         WORKITEM_FREE(freedep, D_FREEDEP);
3800 }
3801
3802 /*
3803  * Allocate a new freework structure that may be a level in an indirect
3804  * when parent is not NULL or a top level block when it is.  The top level
3805  * freework structures are allocated without lk held and before the freeblks
3806  * is visible outside of softdep_setup_freeblocks().
3807  */
3808 static struct freework *
3809 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
3810         struct ufsmount *ump;
3811         struct freeblks *freeblks;
3812         struct freework *parent;
3813         ufs_lbn_t lbn;
3814         ufs2_daddr_t nb;
3815         int frags;
3816         int off;
3817         int journal;
3818 {
3819         struct freework *freework;
3820
3821         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
3822         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
3823         freework->fw_state = ATTACHED;
3824         freework->fw_jnewblk = NULL;
3825         freework->fw_freeblks = freeblks;
3826         freework->fw_parent = parent;
3827         freework->fw_lbn = lbn;
3828         freework->fw_blkno = nb;
3829         freework->fw_frags = frags;
3830         freework->fw_indir = NULL;
3831         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
3832                 ? 0 : NINDIR(ump->um_fs) + 1;
3833         freework->fw_start = freework->fw_off = off;
3834         if (journal)
3835                 newjfreeblk(freeblks, lbn, nb, frags);
3836         if (parent == NULL) {
3837                 ACQUIRE_LOCK(&lk);
3838                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
3839                 freeblks->fb_ref++;
3840                 FREE_LOCK(&lk);
3841         }
3842
3843         return (freework);
3844 }
3845
3846 /*
3847  * Eliminate a jfreeblk for a block that does not need journaling.
3848  */
3849 static void
3850 cancel_jfreeblk(freeblks, blkno)
3851         struct freeblks *freeblks;
3852         ufs2_daddr_t blkno;
3853 {
3854         struct jfreeblk *jfreeblk;
3855         struct jblkdep *jblkdep;
3856
3857         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
3858                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
3859                         continue;
3860                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
3861                 if (jfreeblk->jf_blkno == blkno)
3862                         break;
3863         }
3864         if (jblkdep == NULL)
3865                 return;
3866         free_jsegdep(jblkdep->jb_jsegdep);
3867         LIST_REMOVE(jblkdep, jb_deps);
3868         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
3869 }
3870
3871 /*
3872  * Allocate a new jfreeblk to journal top level block pointer when truncating
3873  * a file.  The caller must add this to the worklist when lk is held.
3874  */
3875 static struct jfreeblk *
3876 newjfreeblk(freeblks, lbn, blkno, frags)
3877         struct freeblks *freeblks;
3878         ufs_lbn_t lbn;
3879         ufs2_daddr_t blkno;
3880         int frags;
3881 {
3882         struct jfreeblk *jfreeblk;
3883
3884         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
3885         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
3886             freeblks->fb_list.wk_mp);
3887         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
3888         jfreeblk->jf_dep.jb_freeblks = freeblks;
3889         jfreeblk->jf_ino = freeblks->fb_inum;
3890         jfreeblk->jf_lbn = lbn;
3891         jfreeblk->jf_blkno = blkno;
3892         jfreeblk->jf_frags = frags;
3893         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
3894
3895         return (jfreeblk);
3896 }
3897
3898 /*
3899  * Allocate a new jtrunc to track a partial truncation.
3900  */
3901 static struct jtrunc *
3902 newjtrunc(freeblks, size, extsize)
3903         struct freeblks *freeblks;
3904         off_t size;
3905         int extsize;
3906 {
3907         struct jtrunc *jtrunc;
3908
3909         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
3910         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
3911             freeblks->fb_list.wk_mp);
3912         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
3913         jtrunc->jt_dep.jb_freeblks = freeblks;
3914         jtrunc->jt_ino = freeblks->fb_inum;
3915         jtrunc->jt_size = size;
3916         jtrunc->jt_extsize = extsize;
3917         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
3918
3919         return (jtrunc);
3920 }
3921
3922 /*
3923  * If we're canceling a new bitmap we have to search for another ref
3924  * to move into the bmsafemap dep.  This might be better expressed
3925  * with another structure.
3926  */
3927 static void
3928 move_newblock_dep(jaddref, inodedep)
3929         struct jaddref *jaddref;
3930         struct inodedep *inodedep;
3931 {
3932         struct inoref *inoref;
3933         struct jaddref *jaddrefn;
3934
3935         jaddrefn = NULL;
3936         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
3937             inoref = TAILQ_NEXT(inoref, if_deps)) {
3938                 if ((jaddref->ja_state & NEWBLOCK) &&
3939                     inoref->if_list.wk_type == D_JADDREF) {
3940                         jaddrefn = (struct jaddref *)inoref;
3941                         break;
3942                 }
3943         }
3944         if (jaddrefn == NULL)
3945                 return;
3946         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
3947         jaddrefn->ja_state |= jaddref->ja_state &
3948             (ATTACHED | UNDONE | NEWBLOCK);
3949         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
3950         jaddref->ja_state |= ATTACHED;
3951         LIST_REMOVE(jaddref, ja_bmdeps);
3952         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
3953             ja_bmdeps);
3954 }
3955
3956 /*
3957  * Cancel a jaddref either before it has been written or while it is being
3958  * written.  This happens when a link is removed before the add reaches
3959  * the disk.  The jaddref dependency is kept linked into the bmsafemap
3960  * and inode to prevent the link count or bitmap from reaching the disk
3961  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
3962  * required.
3963  *
3964  * Returns 1 if the canceled addref requires journaling of the remove and
3965  * 0 otherwise.
3966  */
3967 static int
3968 cancel_jaddref(jaddref, inodedep, wkhd)
3969         struct jaddref *jaddref;
3970         struct inodedep *inodedep;
3971         struct workhead *wkhd;
3972 {
3973         struct inoref *inoref;
3974         struct jsegdep *jsegdep;
3975         int needsj;
3976
3977         KASSERT((jaddref->ja_state & COMPLETE) == 0,
3978             ("cancel_jaddref: Canceling complete jaddref"));
3979         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
3980                 needsj = 1;
3981         else
3982                 needsj = 0;
3983         if (inodedep == NULL)
3984                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3985                     0, &inodedep) == 0)
3986                         panic("cancel_jaddref: Lost inodedep");
3987         /*
3988          * We must adjust the nlink of any reference operation that follows
3989          * us so that it is consistent with the in-memory reference.  This
3990          * ensures that inode nlink rollbacks always have the correct link.
3991          */
3992         if (needsj == 0) {
3993                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
3994                     inoref = TAILQ_NEXT(inoref, if_deps)) {
3995                         if (inoref->if_state & GOINGAWAY)
3996                                 break;
3997                         inoref->if_nlink--;
3998                 }
3999         }
4000         jsegdep = inoref_jseg(&jaddref->ja_ref);
4001         if (jaddref->ja_state & NEWBLOCK)
4002                 move_newblock_dep(jaddref, inodedep);
4003         wake_worklist(&jaddref->ja_list);
4004         jaddref->ja_mkdir = NULL;
4005         if (jaddref->ja_state & INPROGRESS) {
4006                 jaddref->ja_state &= ~INPROGRESS;
4007                 WORKLIST_REMOVE(&jaddref->ja_list);
4008                 jwork_insert(wkhd, jsegdep);
4009         } else {
4010                 free_jsegdep(jsegdep);
4011                 if (jaddref->ja_state & DEPCOMPLETE)
4012                         remove_from_journal(&jaddref->ja_list);
4013         }
4014         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4015         /*
4016          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4017          * can arrange for them to be freed with the bitmap.  Otherwise we
4018          * no longer need this addref attached to the inoreflst and it
4019          * will incorrectly adjust nlink if we leave it.
4020          */
4021         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4022                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4023                     if_deps);
4024                 jaddref->ja_state |= COMPLETE;
4025                 free_jaddref(jaddref);
4026                 return (needsj);
4027         }
4028         /*
4029          * Leave the head of the list for jsegdeps for fast merging.
4030          */
4031         if (LIST_FIRST(wkhd) != NULL) {
4032                 jaddref->ja_state |= ONWORKLIST;
4033                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4034         } else
4035                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4036
4037         return (needsj);
4038 }
4039
4040 /* 
4041  * Attempt to free a jaddref structure when some work completes.  This
4042  * should only succeed once the entry is written and all dependencies have
4043  * been notified.
4044  */
4045 static void
4046 free_jaddref(jaddref)
4047         struct jaddref *jaddref;
4048 {
4049
4050         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4051                 return;
4052         if (jaddref->ja_ref.if_jsegdep)
4053                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4054                     jaddref, jaddref->ja_state);
4055         if (jaddref->ja_state & NEWBLOCK)
4056                 LIST_REMOVE(jaddref, ja_bmdeps);
4057         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4058                 panic("free_jaddref: Bad state %p(0x%X)",
4059                     jaddref, jaddref->ja_state);
4060         if (jaddref->ja_mkdir != NULL)
4061                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4062         WORKITEM_FREE(jaddref, D_JADDREF);
4063 }
4064
4065 /*
4066  * Free a jremref structure once it has been written or discarded.
4067  */
4068 static void
4069 free_jremref(jremref)
4070         struct jremref *jremref;
4071 {
4072
4073         if (jremref->jr_ref.if_jsegdep)
4074                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4075         if (jremref->jr_state & INPROGRESS)
4076                 panic("free_jremref: IO still pending");
4077         WORKITEM_FREE(jremref, D_JREMREF);
4078 }
4079
4080 /*
4081  * Free a jnewblk structure.
4082  */
4083 static void
4084 free_jnewblk(jnewblk)
4085         struct jnewblk *jnewblk;
4086 {
4087
4088         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4089                 return;
4090         LIST_REMOVE(jnewblk, jn_deps);
4091         if (jnewblk->jn_dep != NULL)
4092                 panic("free_jnewblk: Dependency still attached.");
4093         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4094 }
4095
4096 /*
4097  * Cancel a jnewblk which has been been made redundant by frag extension.
4098  */
4099 static void
4100 cancel_jnewblk(jnewblk, wkhd)
4101         struct jnewblk *jnewblk;
4102         struct workhead *wkhd;
4103 {
4104         struct jsegdep *jsegdep;
4105
4106         jsegdep = jnewblk->jn_jsegdep;
4107         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4108                 panic("cancel_jnewblk: Invalid state");
4109         jnewblk->jn_jsegdep  = NULL;
4110         jnewblk->jn_dep = NULL;
4111         jnewblk->jn_state |= GOINGAWAY;
4112         if (jnewblk->jn_state & INPROGRESS) {
4113                 jnewblk->jn_state &= ~INPROGRESS;
4114                 WORKLIST_REMOVE(&jnewblk->jn_list);
4115                 jwork_insert(wkhd, jsegdep);
4116         } else {
4117                 free_jsegdep(jsegdep);
4118                 remove_from_journal(&jnewblk->jn_list);
4119         }
4120         wake_worklist(&jnewblk->jn_list);
4121         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4122 }
4123
4124 static void
4125 free_jblkdep(jblkdep)
4126         struct jblkdep *jblkdep;
4127 {
4128
4129         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4130                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4131         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4132                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4133         else
4134                 panic("free_jblkdep: Unexpected type %s",
4135                     TYPENAME(jblkdep->jb_list.wk_type));
4136 }
4137
4138 /*
4139  * Free a single jseg once it is no longer referenced in memory or on
4140  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4141  * to disappear.
4142  */
4143 static void
4144 free_jseg(jseg, jblocks)
4145         struct jseg *jseg;
4146         struct jblocks *jblocks;
4147 {
4148         struct freework *freework;
4149
4150         /*
4151          * Free freework structures that were lingering to indicate freed
4152          * indirect blocks that forced journal write ordering on reallocate.
4153          */
4154         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4155                 indirblk_remove(freework);
4156         if (jblocks->jb_oldestseg == jseg)
4157                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4158         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4159         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4160         KASSERT(LIST_EMPTY(&jseg->js_entries),
4161             ("free_jseg: Freed jseg has valid entries."));
4162         WORKITEM_FREE(jseg, D_JSEG);
4163 }
4164
4165 /*
4166  * Free all jsegs that meet the criteria for being reclaimed and update
4167  * oldestseg.
4168  */
4169 static void
4170 free_jsegs(jblocks)
4171         struct jblocks *jblocks;
4172 {
4173         struct jseg *jseg;
4174
4175         /*
4176          * Free only those jsegs which have none allocated before them to
4177          * preserve the journal space ordering.
4178          */
4179         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4180                 /*
4181                  * Only reclaim space when nothing depends on this journal
4182                  * set and another set has written that it is no longer
4183                  * valid.
4184                  */
4185                 if (jseg->js_refs != 0) {
4186                         jblocks->jb_oldestseg = jseg;
4187                         return;
4188                 }
4189                 if (!LIST_EMPTY(&jseg->js_indirs) &&
4190                     jseg->js_seq >= jblocks->jb_oldestwrseq)
4191                         break;
4192                 free_jseg(jseg, jblocks);
4193         }
4194         /*
4195          * If we exited the loop above we still must discover the
4196          * oldest valid segment.
4197          */
4198         if (jseg)
4199                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4200                      jseg = TAILQ_NEXT(jseg, js_next))
4201                         if (jseg->js_refs != 0)
4202                                 break;
4203         jblocks->jb_oldestseg = jseg;
4204         /*
4205          * The journal has no valid records but some jsegs may still be
4206          * waiting on oldestwrseq to advance.  We force a small record
4207          * out to permit these lingering records to be reclaimed.
4208          */
4209         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4210                 jblocks->jb_needseg = 1;
4211 }
4212
4213 /*
4214  * Release one reference to a jseg and free it if the count reaches 0.  This
4215  * should eventually reclaim journal space as well.
4216  */
4217 static void
4218 rele_jseg(jseg)
4219         struct jseg *jseg;
4220 {
4221
4222         KASSERT(jseg->js_refs > 0,
4223             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4224         if (--jseg->js_refs != 0)
4225                 return;
4226         free_jsegs(jseg->js_jblocks);
4227 }
4228
4229 /*
4230  * Release a jsegdep and decrement the jseg count.
4231  */
4232 static void
4233 free_jsegdep(jsegdep)
4234         struct jsegdep *jsegdep;
4235 {
4236
4237         if (jsegdep->jd_seg)
4238                 rele_jseg(jsegdep->jd_seg);
4239         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4240 }
4241
4242 /*
4243  * Wait for a journal item to make it to disk.  Initiate journal processing
4244  * if required.
4245  */
4246 static int
4247 jwait(wk, waitfor)
4248         struct worklist *wk;
4249         int waitfor;
4250 {
4251
4252         /*
4253          * Blocking journal waits cause slow synchronous behavior.  Record
4254          * stats on the frequency of these blocking operations.
4255          */
4256         if (waitfor == MNT_WAIT) {
4257                 stat_journal_wait++;
4258                 switch (wk->wk_type) {
4259                 case D_JREMREF:
4260                 case D_JMVREF:
4261                         stat_jwait_filepage++;
4262                         break;
4263                 case D_JTRUNC:
4264                 case D_JFREEBLK:
4265                         stat_jwait_freeblks++;
4266                         break;
4267                 case D_JNEWBLK:
4268                         stat_jwait_newblk++;
4269                         break;
4270                 case D_JADDREF:
4271                         stat_jwait_inode++;
4272                         break;
4273                 default:
4274                         break;
4275                 }
4276         }
4277         /*
4278          * If IO has not started we process the journal.  We can't mark the
4279          * worklist item as IOWAITING because we drop the lock while
4280          * processing the journal and the worklist entry may be freed after
4281          * this point.  The caller may call back in and re-issue the request.
4282          */
4283         if ((wk->wk_state & INPROGRESS) == 0) {
4284                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4285                 if (waitfor != MNT_WAIT)
4286                         return (EBUSY);
4287                 return (0);
4288         }
4289         if (waitfor != MNT_WAIT)
4290                 return (EBUSY);
4291         wait_worklist(wk, "jwait");
4292         return (0);
4293 }
4294
4295 /*
4296  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4297  * appropriate.  This is a convenience function to reduce duplicate code
4298  * for the setup and revert functions below.
4299  */
4300 static struct inodedep *
4301 inodedep_lookup_ip(ip)
4302         struct inode *ip;
4303 {
4304         struct inodedep *inodedep;
4305
4306         KASSERT(ip->i_nlink >= ip->i_effnlink,
4307             ("inodedep_lookup_ip: bad delta"));
4308         (void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number,
4309             DEPALLOC, &inodedep);
4310         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4311
4312         return (inodedep);
4313 }
4314
4315 /*
4316  * Called prior to creating a new inode and linking it to a directory.  The
4317  * jaddref structure must already be allocated by softdep_setup_inomapdep
4318  * and it is discovered here so we can initialize the mode and update
4319  * nlinkdelta.
4320  */
4321 void
4322 softdep_setup_create(dp, ip)
4323         struct inode *dp;
4324         struct inode *ip;
4325 {
4326         struct inodedep *inodedep;
4327         struct jaddref *jaddref;
4328         struct vnode *dvp;
4329
4330         KASSERT(ip->i_nlink == 1,
4331             ("softdep_setup_create: Invalid link count."));
4332         dvp = ITOV(dp);
4333         ACQUIRE_LOCK(&lk);
4334         inodedep = inodedep_lookup_ip(ip);
4335         if (DOINGSUJ(dvp)) {
4336                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4337                     inoreflst);
4338                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4339                     ("softdep_setup_create: No addref structure present."));
4340         }
4341         softdep_prelink(dvp, NULL);
4342         FREE_LOCK(&lk);
4343 }
4344
4345 /*
4346  * Create a jaddref structure to track the addition of a DOTDOT link when
4347  * we are reparenting an inode as part of a rename.  This jaddref will be
4348  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4349  * non-journaling softdep.
4350  */
4351 void
4352 softdep_setup_dotdot_link(dp, ip)
4353         struct inode *dp;
4354         struct inode *ip;
4355 {
4356         struct inodedep *inodedep;
4357         struct jaddref *jaddref;
4358         struct vnode *dvp;
4359         struct vnode *vp;
4360
4361         dvp = ITOV(dp);
4362         vp = ITOV(ip);
4363         jaddref = NULL;
4364         /*
4365          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4366          * is used as a normal link would be.
4367          */
4368         if (DOINGSUJ(dvp))
4369                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4370                     dp->i_effnlink - 1, dp->i_mode);
4371         ACQUIRE_LOCK(&lk);
4372         inodedep = inodedep_lookup_ip(dp);
4373         if (jaddref)
4374                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4375                     if_deps);
4376         softdep_prelink(dvp, ITOV(ip));
4377         FREE_LOCK(&lk);
4378 }
4379
4380 /*
4381  * Create a jaddref structure to track a new link to an inode.  The directory
4382  * offset is not known until softdep_setup_directory_add or
4383  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4384  * softdep.
4385  */
4386 void
4387 softdep_setup_link(dp, ip)
4388         struct inode *dp;
4389         struct inode *ip;
4390 {
4391         struct inodedep *inodedep;
4392         struct jaddref *jaddref;
4393         struct vnode *dvp;
4394
4395         dvp = ITOV(dp);
4396         jaddref = NULL;
4397         if (DOINGSUJ(dvp))
4398                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4399                     ip->i_mode);
4400         ACQUIRE_LOCK(&lk);
4401         inodedep = inodedep_lookup_ip(ip);
4402         if (jaddref)
4403                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4404                     if_deps);
4405         softdep_prelink(dvp, ITOV(ip));
4406         FREE_LOCK(&lk);
4407 }
4408
4409 /*
4410  * Called to create the jaddref structures to track . and .. references as
4411  * well as lookup and further initialize the incomplete jaddref created
4412  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4413  * nlinkdelta for non-journaling softdep.
4414  */
4415 void
4416 softdep_setup_mkdir(dp, ip)
4417         struct inode *dp;
4418         struct inode *ip;
4419 {
4420         struct inodedep *inodedep;
4421         struct jaddref *dotdotaddref;
4422         struct jaddref *dotaddref;
4423         struct jaddref *jaddref;
4424         struct vnode *dvp;
4425
4426         dvp = ITOV(dp);
4427         dotaddref = dotdotaddref = NULL;
4428         if (DOINGSUJ(dvp)) {
4429                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4430                     ip->i_mode);
4431                 dotaddref->ja_state |= MKDIR_BODY;
4432                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4433                     dp->i_effnlink - 1, dp->i_mode);
4434                 dotdotaddref->ja_state |= MKDIR_PARENT;
4435         }
4436         ACQUIRE_LOCK(&lk);
4437         inodedep = inodedep_lookup_ip(ip);
4438         if (DOINGSUJ(dvp)) {
4439                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4440                     inoreflst);
4441                 KASSERT(jaddref != NULL,
4442                     ("softdep_setup_mkdir: No addref structure present."));
4443                 KASSERT(jaddref->ja_parent == dp->i_number, 
4444                     ("softdep_setup_mkdir: bad parent %d",
4445                     jaddref->ja_parent));
4446                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4447                     if_deps);
4448         }
4449         inodedep = inodedep_lookup_ip(dp);
4450         if (DOINGSUJ(dvp))
4451                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4452                     &dotdotaddref->ja_ref, if_deps);
4453         softdep_prelink(ITOV(dp), NULL);
4454         FREE_LOCK(&lk);
4455 }
4456
4457 /*
4458  * Called to track nlinkdelta of the inode and parent directories prior to
4459  * unlinking a directory.
4460  */
4461 void
4462 softdep_setup_rmdir(dp, ip)
4463         struct inode *dp;
4464         struct inode *ip;
4465 {
4466         struct vnode *dvp;
4467
4468         dvp = ITOV(dp);
4469         ACQUIRE_LOCK(&lk);
4470         (void) inodedep_lookup_ip(ip);
4471         (void) inodedep_lookup_ip(dp);
4472         softdep_prelink(dvp, ITOV(ip));
4473         FREE_LOCK(&lk);
4474 }
4475
4476 /*
4477  * Called to track nlinkdelta of the inode and parent directories prior to
4478  * unlink.
4479  */
4480 void
4481 softdep_setup_unlink(dp, ip)
4482         struct inode *dp;
4483         struct inode *ip;
4484 {
4485         struct vnode *dvp;
4486
4487         dvp = ITOV(dp);
4488         ACQUIRE_LOCK(&lk);
4489         (void) inodedep_lookup_ip(ip);
4490         (void) inodedep_lookup_ip(dp);
4491         softdep_prelink(dvp, ITOV(ip));
4492         FREE_LOCK(&lk);
4493 }
4494
4495 /*
4496  * Called to release the journal structures created by a failed non-directory
4497  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4498  */
4499 void
4500 softdep_revert_create(dp, ip)
4501         struct inode *dp;
4502         struct inode *ip;
4503 {
4504         struct inodedep *inodedep;
4505         struct jaddref *jaddref;
4506         struct vnode *dvp;
4507
4508         dvp = ITOV(dp);
4509         ACQUIRE_LOCK(&lk);
4510         inodedep = inodedep_lookup_ip(ip);
4511         if (DOINGSUJ(dvp)) {
4512                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4513                     inoreflst);
4514                 KASSERT(jaddref->ja_parent == dp->i_number,
4515                     ("softdep_revert_create: addref parent mismatch"));
4516                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4517         }
4518         FREE_LOCK(&lk);
4519 }
4520
4521 /*
4522  * Called to release the journal structures created by a failed dotdot link
4523  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4524  */
4525 void
4526 softdep_revert_dotdot_link(dp, ip)
4527         struct inode *dp;
4528         struct inode *ip;
4529 {
4530         struct inodedep *inodedep;
4531         struct jaddref *jaddref;
4532         struct vnode *dvp;
4533
4534         dvp = ITOV(dp);
4535         ACQUIRE_LOCK(&lk);
4536         inodedep = inodedep_lookup_ip(dp);
4537         if (DOINGSUJ(dvp)) {
4538                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4539                     inoreflst);
4540                 KASSERT(jaddref->ja_parent == ip->i_number,
4541                     ("softdep_revert_dotdot_link: addref parent mismatch"));
4542                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4543         }
4544         FREE_LOCK(&lk);
4545 }
4546
4547 /*
4548  * Called to release the journal structures created by a failed link
4549  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4550  */
4551 void
4552 softdep_revert_link(dp, ip)
4553         struct inode *dp;
4554         struct inode *ip;
4555 {
4556         struct inodedep *inodedep;
4557         struct jaddref *jaddref;
4558         struct vnode *dvp;
4559
4560         dvp = ITOV(dp);
4561         ACQUIRE_LOCK(&lk);
4562         inodedep = inodedep_lookup_ip(ip);
4563         if (DOINGSUJ(dvp)) {
4564                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4565                     inoreflst);
4566                 KASSERT(jaddref->ja_parent == dp->i_number,
4567                     ("softdep_revert_link: addref parent mismatch"));
4568                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4569         }
4570         FREE_LOCK(&lk);
4571 }
4572
4573 /*
4574  * Called to release the journal structures created by a failed mkdir
4575  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4576  */
4577 void
4578 softdep_revert_mkdir(dp, ip)
4579         struct inode *dp;
4580         struct inode *ip;
4581 {
4582         struct inodedep *inodedep;
4583         struct jaddref *jaddref;
4584         struct jaddref *dotaddref;
4585         struct vnode *dvp;
4586
4587         dvp = ITOV(dp);
4588
4589         ACQUIRE_LOCK(&lk);
4590         inodedep = inodedep_lookup_ip(dp);
4591         if (DOINGSUJ(dvp)) {
4592                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4593                     inoreflst);
4594                 KASSERT(jaddref->ja_parent == ip->i_number,
4595                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4596                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4597         }
4598         inodedep = inodedep_lookup_ip(ip);
4599         if (DOINGSUJ(dvp)) {
4600                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4601                     inoreflst);
4602                 KASSERT(jaddref->ja_parent == dp->i_number,
4603                     ("softdep_revert_mkdir: addref parent mismatch"));
4604                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4605                     inoreflst, if_deps);
4606                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4607                 KASSERT(dotaddref->ja_parent == ip->i_number,
4608                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4609                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4610         }
4611         FREE_LOCK(&lk);
4612 }
4613
4614 /* 
4615  * Called to correct nlinkdelta after a failed rmdir.
4616  */
4617 void
4618 softdep_revert_rmdir(dp, ip)
4619         struct inode *dp;
4620         struct inode *ip;
4621 {
4622
4623         ACQUIRE_LOCK(&lk);
4624         (void) inodedep_lookup_ip(ip);
4625         (void) inodedep_lookup_ip(dp);
4626         FREE_LOCK(&lk);
4627 }
4628
4629 /*
4630  * Protecting the freemaps (or bitmaps).
4631  * 
4632  * To eliminate the need to execute fsck before mounting a filesystem
4633  * after a power failure, one must (conservatively) guarantee that the
4634  * on-disk copy of the bitmaps never indicate that a live inode or block is
4635  * free.  So, when a block or inode is allocated, the bitmap should be
4636  * updated (on disk) before any new pointers.  When a block or inode is
4637  * freed, the bitmap should not be updated until all pointers have been
4638  * reset.  The latter dependency is handled by the delayed de-allocation
4639  * approach described below for block and inode de-allocation.  The former
4640  * dependency is handled by calling the following procedure when a block or
4641  * inode is allocated. When an inode is allocated an "inodedep" is created
4642  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4643  * Each "inodedep" is also inserted into the hash indexing structure so
4644  * that any additional link additions can be made dependent on the inode
4645  * allocation.
4646  * 
4647  * The ufs filesystem maintains a number of free block counts (e.g., per
4648  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4649  * in addition to the bitmaps.  These counts are used to improve efficiency
4650  * during allocation and therefore must be consistent with the bitmaps.
4651  * There is no convenient way to guarantee post-crash consistency of these
4652  * counts with simple update ordering, for two main reasons: (1) The counts
4653  * and bitmaps for a single cylinder group block are not in the same disk
4654  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4655  * be written and the other not.  (2) Some of the counts are located in the
4656  * superblock rather than the cylinder group block. So, we focus our soft
4657  * updates implementation on protecting the bitmaps. When mounting a
4658  * filesystem, we recompute the auxiliary counts from the bitmaps.
4659  */
4660
4661 /*
4662  * Called just after updating the cylinder group block to allocate an inode.
4663  */
4664 void
4665 softdep_setup_inomapdep(bp, ip, newinum, mode)
4666         struct buf *bp;         /* buffer for cylgroup block with inode map */
4667         struct inode *ip;       /* inode related to allocation */
4668         ino_t newinum;          /* new inode number being allocated */
4669         int mode;
4670 {
4671         struct inodedep *inodedep;
4672         struct bmsafemap *bmsafemap;
4673         struct jaddref *jaddref;
4674         struct mount *mp;
4675         struct fs *fs;
4676
4677         mp = UFSTOVFS(ip->i_ump);
4678         fs = ip->i_ump->um_fs;
4679         jaddref = NULL;
4680
4681         /*
4682          * Allocate the journal reference add structure so that the bitmap
4683          * can be dependent on it.
4684          */
4685         if (MOUNTEDSUJ(mp)) {
4686                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
4687                 jaddref->ja_state |= NEWBLOCK;
4688         }
4689
4690         /*
4691          * Create a dependency for the newly allocated inode.
4692          * Panic if it already exists as something is seriously wrong.
4693          * Otherwise add it to the dependency list for the buffer holding
4694          * the cylinder group map from which it was allocated.
4695          */
4696         ACQUIRE_LOCK(&lk);
4697         if ((inodedep_lookup(mp, newinum, DEPALLOC|NODELAY, &inodedep)))
4698                 panic("softdep_setup_inomapdep: dependency %p for new"
4699                     "inode already exists", inodedep);
4700         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum));
4701         if (jaddref) {
4702                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
4703                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4704                     if_deps);
4705         } else {
4706                 inodedep->id_state |= ONDEPLIST;
4707                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
4708         }
4709         inodedep->id_bmsafemap = bmsafemap;
4710         inodedep->id_state &= ~DEPCOMPLETE;
4711         FREE_LOCK(&lk);
4712 }
4713
4714 /*
4715  * Called just after updating the cylinder group block to
4716  * allocate block or fragment.
4717  */
4718 void
4719 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
4720         struct buf *bp;         /* buffer for cylgroup block with block map */
4721         struct mount *mp;       /* filesystem doing allocation */
4722         ufs2_daddr_t newblkno;  /* number of newly allocated block */
4723         int frags;              /* Number of fragments. */
4724         int oldfrags;           /* Previous number of fragments for extend. */
4725 {
4726         struct newblk *newblk;
4727         struct bmsafemap *bmsafemap;
4728         struct jnewblk *jnewblk;
4729         struct fs *fs;
4730
4731         fs = VFSTOUFS(mp)->um_fs;
4732         jnewblk = NULL;
4733         /*
4734          * Create a dependency for the newly allocated block.
4735          * Add it to the dependency list for the buffer holding
4736          * the cylinder group map from which it was allocated.
4737          */
4738         if (MOUNTEDSUJ(mp)) {
4739                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
4740                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
4741                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
4742                 jnewblk->jn_state = ATTACHED;
4743                 jnewblk->jn_blkno = newblkno;
4744                 jnewblk->jn_frags = frags;
4745                 jnewblk->jn_oldfrags = oldfrags;
4746 #ifdef SUJ_DEBUG
4747                 {
4748                         struct cg *cgp;
4749                         uint8_t *blksfree;
4750                         long bno;
4751                         int i;
4752         
4753                         cgp = (struct cg *)bp->b_data;
4754                         blksfree = cg_blksfree(cgp);
4755                         bno = dtogd(fs, jnewblk->jn_blkno);
4756                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
4757                             i++) {
4758                                 if (isset(blksfree, bno + i))
4759                                         panic("softdep_setup_blkmapdep: "
4760                                             "free fragment %d from %d-%d "
4761                                             "state 0x%X dep %p", i,
4762                                             jnewblk->jn_oldfrags,
4763                                             jnewblk->jn_frags,
4764                                             jnewblk->jn_state,
4765                                             jnewblk->jn_dep);
4766                         }
4767                 }
4768 #endif
4769         }
4770         ACQUIRE_LOCK(&lk);
4771         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
4772                 panic("softdep_setup_blkmapdep: found block");
4773         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
4774             dtog(fs, newblkno));
4775         if (jnewblk) {
4776                 jnewblk->jn_dep = (struct worklist *)newblk;
4777                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
4778         } else {
4779                 newblk->nb_state |= ONDEPLIST;
4780                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
4781         }
4782         newblk->nb_bmsafemap = bmsafemap;
4783         newblk->nb_jnewblk = jnewblk;
4784         FREE_LOCK(&lk);
4785 }
4786
4787 #define BMSAFEMAP_HASH(fs, cg) \
4788       (&bmsafemap_hashtbl[((((register_t)(fs)) >> 13) + (cg)) & bmsafemap_hash])
4789
4790 static int
4791 bmsafemap_find(bmsafemaphd, mp, cg, bmsafemapp)
4792         struct bmsafemap_hashhead *bmsafemaphd;
4793         struct mount *mp;
4794         int cg;
4795         struct bmsafemap **bmsafemapp;
4796 {
4797         struct bmsafemap *bmsafemap;
4798
4799         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
4800                 if (bmsafemap->sm_list.wk_mp == mp && bmsafemap->sm_cg == cg)
4801                         break;
4802         if (bmsafemap) {
4803                 *bmsafemapp = bmsafemap;
4804                 return (1);
4805         }
4806         *bmsafemapp = NULL;
4807
4808         return (0);
4809 }
4810
4811 /*
4812  * Find the bmsafemap associated with a cylinder group buffer.
4813  * If none exists, create one. The buffer must be locked when
4814  * this routine is called and this routine must be called with
4815  * splbio interrupts blocked.
4816  */
4817 static struct bmsafemap *
4818 bmsafemap_lookup(mp, bp, cg)
4819         struct mount *mp;
4820         struct buf *bp;
4821         int cg;
4822 {
4823         struct bmsafemap_hashhead *bmsafemaphd;
4824         struct bmsafemap *bmsafemap, *collision;
4825         struct worklist *wk;
4826         struct fs *fs;
4827
4828         mtx_assert(&lk, MA_OWNED);
4829         if (bp)
4830                 LIST_FOREACH(wk, &bp->b_dep, wk_list)
4831                         if (wk->wk_type == D_BMSAFEMAP)
4832                                 return (WK_BMSAFEMAP(wk));
4833         fs = VFSTOUFS(mp)->um_fs;
4834         bmsafemaphd = BMSAFEMAP_HASH(fs, cg);
4835         if (bmsafemap_find(bmsafemaphd, mp, cg, &bmsafemap) == 1)
4836                 return (bmsafemap);
4837         FREE_LOCK(&lk);
4838         bmsafemap = malloc(sizeof(struct bmsafemap),
4839                 M_BMSAFEMAP, M_SOFTDEP_FLAGS);
4840         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
4841         bmsafemap->sm_buf = bp;
4842         LIST_INIT(&bmsafemap->sm_inodedephd);
4843         LIST_INIT(&bmsafemap->sm_inodedepwr);
4844         LIST_INIT(&bmsafemap->sm_newblkhd);
4845         LIST_INIT(&bmsafemap->sm_newblkwr);
4846         LIST_INIT(&bmsafemap->sm_jaddrefhd);
4847         LIST_INIT(&bmsafemap->sm_jnewblkhd);
4848         LIST_INIT(&bmsafemap->sm_freehd);
4849         LIST_INIT(&bmsafemap->sm_freewr);
4850         ACQUIRE_LOCK(&lk);
4851         if (bmsafemap_find(bmsafemaphd, mp, cg, &collision) == 1) {
4852                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4853                 return (collision);
4854         }
4855         bmsafemap->sm_cg = cg;
4856         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
4857         LIST_INSERT_HEAD(&VFSTOUFS(mp)->softdep_dirtycg, bmsafemap, sm_next);
4858         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
4859         return (bmsafemap);
4860 }
4861
4862 /*
4863  * Direct block allocation dependencies.
4864  * 
4865  * When a new block is allocated, the corresponding disk locations must be
4866  * initialized (with zeros or new data) before the on-disk inode points to
4867  * them.  Also, the freemap from which the block was allocated must be
4868  * updated (on disk) before the inode's pointer. These two dependencies are
4869  * independent of each other and are needed for all file blocks and indirect
4870  * blocks that are pointed to directly by the inode.  Just before the
4871  * "in-core" version of the inode is updated with a newly allocated block
4872  * number, a procedure (below) is called to setup allocation dependency
4873  * structures.  These structures are removed when the corresponding
4874  * dependencies are satisfied or when the block allocation becomes obsolete
4875  * (i.e., the file is deleted, the block is de-allocated, or the block is a
4876  * fragment that gets upgraded).  All of these cases are handled in
4877  * procedures described later.
4878  * 
4879  * When a file extension causes a fragment to be upgraded, either to a larger
4880  * fragment or to a full block, the on-disk location may change (if the
4881  * previous fragment could not simply be extended). In this case, the old
4882  * fragment must be de-allocated, but not until after the inode's pointer has
4883  * been updated. In most cases, this is handled by later procedures, which
4884  * will construct a "freefrag" structure to be added to the workitem queue
4885  * when the inode update is complete (or obsolete).  The main exception to
4886  * this is when an allocation occurs while a pending allocation dependency
4887  * (for the same block pointer) remains.  This case is handled in the main
4888  * allocation dependency setup procedure by immediately freeing the
4889  * unreferenced fragments.
4890  */ 
4891 void 
4892 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
4893         struct inode *ip;       /* inode to which block is being added */
4894         ufs_lbn_t off;          /* block pointer within inode */
4895         ufs2_daddr_t newblkno;  /* disk block number being added */
4896         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
4897         long newsize;           /* size of new block */
4898         long oldsize;           /* size of new block */
4899         struct buf *bp;         /* bp for allocated block */
4900 {
4901         struct allocdirect *adp, *oldadp;
4902         struct allocdirectlst *adphead;
4903         struct freefrag *freefrag;
4904         struct inodedep *inodedep;
4905         struct pagedep *pagedep;
4906         struct jnewblk *jnewblk;
4907         struct newblk *newblk;
4908         struct mount *mp;
4909         ufs_lbn_t lbn;
4910
4911         lbn = bp->b_lblkno;
4912         mp = UFSTOVFS(ip->i_ump);
4913         if (oldblkno && oldblkno != newblkno)
4914                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
4915         else
4916                 freefrag = NULL;
4917
4918         ACQUIRE_LOCK(&lk);
4919         if (off >= NDADDR) {
4920                 if (lbn > 0)
4921                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
4922                             lbn, off);
4923                 /* allocating an indirect block */
4924                 if (oldblkno != 0)
4925                         panic("softdep_setup_allocdirect: non-zero indir");
4926         } else {
4927                 if (off != lbn)
4928                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
4929                             lbn, off);
4930                 /*
4931                  * Allocating a direct block.
4932                  *
4933                  * If we are allocating a directory block, then we must
4934                  * allocate an associated pagedep to track additions and
4935                  * deletions.
4936                  */
4937                 if ((ip->i_mode & IFMT) == IFDIR)
4938                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
4939                             &pagedep);
4940         }
4941         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
4942                 panic("softdep_setup_allocdirect: lost block");
4943         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
4944             ("softdep_setup_allocdirect: newblk already initialized"));
4945         /*
4946          * Convert the newblk to an allocdirect.
4947          */
4948         newblk->nb_list.wk_type = D_ALLOCDIRECT;
4949         adp = (struct allocdirect *)newblk;
4950         newblk->nb_freefrag = freefrag;
4951         adp->ad_offset = off;
4952         adp->ad_oldblkno = oldblkno;
4953         adp->ad_newsize = newsize;
4954         adp->ad_oldsize = oldsize;
4955
4956         /*
4957          * Finish initializing the journal.
4958          */
4959         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
4960                 jnewblk->jn_ino = ip->i_number;
4961                 jnewblk->jn_lbn = lbn;
4962                 add_to_journal(&jnewblk->jn_list);
4963         }
4964         if (freefrag && freefrag->ff_jdep != NULL &&
4965             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
4966                 add_to_journal(freefrag->ff_jdep);
4967         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
4968         adp->ad_inodedep = inodedep;
4969
4970         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
4971         /*
4972          * The list of allocdirects must be kept in sorted and ascending
4973          * order so that the rollback routines can quickly determine the
4974          * first uncommitted block (the size of the file stored on disk
4975          * ends at the end of the lowest committed fragment, or if there
4976          * are no fragments, at the end of the highest committed block).
4977          * Since files generally grow, the typical case is that the new
4978          * block is to be added at the end of the list. We speed this
4979          * special case by checking against the last allocdirect in the
4980          * list before laboriously traversing the list looking for the
4981          * insertion point.
4982          */
4983         adphead = &inodedep->id_newinoupdt;
4984         oldadp = TAILQ_LAST(adphead, allocdirectlst);
4985         if (oldadp == NULL || oldadp->ad_offset <= off) {
4986                 /* insert at end of list */
4987                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
4988                 if (oldadp != NULL && oldadp->ad_offset == off)
4989                         allocdirect_merge(adphead, adp, oldadp);
4990                 FREE_LOCK(&lk);
4991                 return;
4992         }
4993         TAILQ_FOREACH(oldadp, adphead, ad_next) {
4994                 if (oldadp->ad_offset >= off)
4995                         break;
4996         }
4997         if (oldadp == NULL)
4998                 panic("softdep_setup_allocdirect: lost entry");
4999         /* insert in middle of list */
5000         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5001         if (oldadp->ad_offset == off)
5002                 allocdirect_merge(adphead, adp, oldadp);
5003
5004         FREE_LOCK(&lk);
5005 }
5006
5007 /*
5008  * Merge a newer and older journal record to be stored either in a
5009  * newblock or freefrag.  This handles aggregating journal records for
5010  * fragment allocation into a second record as well as replacing a
5011  * journal free with an aborted journal allocation.  A segment for the
5012  * oldest record will be placed on wkhd if it has been written.  If not
5013  * the segment for the newer record will suffice.
5014  */
5015 static struct worklist *
5016 jnewblk_merge(new, old, wkhd)
5017         struct worklist *new;
5018         struct worklist *old;
5019         struct workhead *wkhd;
5020 {
5021         struct jnewblk *njnewblk;
5022         struct jnewblk *jnewblk;
5023
5024         /* Handle NULLs to simplify callers. */
5025         if (new == NULL)
5026                 return (old);
5027         if (old == NULL)
5028                 return (new);
5029         /* Replace a jfreefrag with a jnewblk. */
5030         if (new->wk_type == D_JFREEFRAG) {
5031                 cancel_jfreefrag(WK_JFREEFRAG(new));
5032                 return (old);
5033         }
5034         /*
5035          * Handle merging of two jnewblk records that describe
5036          * different sets of fragments in the same block.
5037          */
5038         jnewblk = WK_JNEWBLK(old);
5039         njnewblk = WK_JNEWBLK(new);
5040         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5041                 panic("jnewblk_merge: Merging disparate blocks.");
5042         /*
5043          * The record may be rolled back in the cg.
5044          */
5045         if (jnewblk->jn_state & UNDONE) {
5046                 jnewblk->jn_state &= ~UNDONE;
5047                 njnewblk->jn_state |= UNDONE;
5048                 njnewblk->jn_state &= ~ATTACHED;
5049         }
5050         /*
5051          * We modify the newer addref and free the older so that if neither
5052          * has been written the most up-to-date copy will be on disk.  If
5053          * both have been written but rolled back we only temporarily need
5054          * one of them to fix the bits when the cg write completes.
5055          */
5056         jnewblk->jn_state |= ATTACHED | COMPLETE;
5057         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5058         cancel_jnewblk(jnewblk, wkhd);
5059         WORKLIST_REMOVE(&jnewblk->jn_list);
5060         free_jnewblk(jnewblk);
5061         return (new);
5062 }
5063
5064 /*
5065  * Replace an old allocdirect dependency with a newer one.
5066  * This routine must be called with splbio interrupts blocked.
5067  */
5068 static void
5069 allocdirect_merge(adphead, newadp, oldadp)
5070         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5071         struct allocdirect *newadp;     /* allocdirect being added */
5072         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5073 {
5074         struct worklist *wk;
5075         struct freefrag *freefrag;
5076
5077         freefrag = NULL;
5078         mtx_assert(&lk, MA_OWNED);
5079         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5080             newadp->ad_oldsize != oldadp->ad_newsize ||
5081             newadp->ad_offset >= NDADDR)
5082                 panic("%s %jd != new %jd || old size %ld != new %ld",
5083                     "allocdirect_merge: old blkno",
5084                     (intmax_t)newadp->ad_oldblkno,
5085                     (intmax_t)oldadp->ad_newblkno,
5086                     newadp->ad_oldsize, oldadp->ad_newsize);
5087         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5088         newadp->ad_oldsize = oldadp->ad_oldsize;
5089         /*
5090          * If the old dependency had a fragment to free or had never
5091          * previously had a block allocated, then the new dependency
5092          * can immediately post its freefrag and adopt the old freefrag.
5093          * This action is done by swapping the freefrag dependencies.
5094          * The new dependency gains the old one's freefrag, and the
5095          * old one gets the new one and then immediately puts it on
5096          * the worklist when it is freed by free_newblk. It is
5097          * not possible to do this swap when the old dependency had a
5098          * non-zero size but no previous fragment to free. This condition
5099          * arises when the new block is an extension of the old block.
5100          * Here, the first part of the fragment allocated to the new
5101          * dependency is part of the block currently claimed on disk by
5102          * the old dependency, so cannot legitimately be freed until the
5103          * conditions for the new dependency are fulfilled.
5104          */
5105         freefrag = newadp->ad_freefrag;
5106         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5107                 newadp->ad_freefrag = oldadp->ad_freefrag;
5108                 oldadp->ad_freefrag = freefrag;
5109         }
5110         /*
5111          * If we are tracking a new directory-block allocation,
5112          * move it from the old allocdirect to the new allocdirect.
5113          */
5114         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5115                 WORKLIST_REMOVE(wk);
5116                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5117                         panic("allocdirect_merge: extra newdirblk");
5118                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5119         }
5120         TAILQ_REMOVE(adphead, oldadp, ad_next);
5121         /*
5122          * We need to move any journal dependencies over to the freefrag
5123          * that releases this block if it exists.  Otherwise we are
5124          * extending an existing block and we'll wait until that is
5125          * complete to release the journal space and extend the
5126          * new journal to cover this old space as well.
5127          */
5128         if (freefrag == NULL) {
5129                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5130                         panic("allocdirect_merge: %jd != %jd",
5131                             oldadp->ad_newblkno, newadp->ad_newblkno);
5132                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5133                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5134                     &oldadp->ad_block.nb_jnewblk->jn_list,
5135                     &newadp->ad_block.nb_jwork);
5136                 oldadp->ad_block.nb_jnewblk = NULL;
5137                 cancel_newblk(&oldadp->ad_block, NULL,
5138                     &newadp->ad_block.nb_jwork);
5139         } else {
5140                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5141                     &freefrag->ff_list, &freefrag->ff_jwork);
5142                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5143                     &freefrag->ff_jwork);
5144         }
5145         free_newblk(&oldadp->ad_block);
5146 }
5147
5148 /*
5149  * Allocate a jfreefrag structure to journal a single block free.
5150  */
5151 static struct jfreefrag *
5152 newjfreefrag(freefrag, ip, blkno, size, lbn)
5153         struct freefrag *freefrag;
5154         struct inode *ip;
5155         ufs2_daddr_t blkno;
5156         long size;
5157         ufs_lbn_t lbn;
5158 {
5159         struct jfreefrag *jfreefrag;
5160         struct fs *fs;
5161
5162         fs = ip->i_fs;
5163         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5164             M_SOFTDEP_FLAGS);
5165         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5166         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5167         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5168         jfreefrag->fr_ino = ip->i_number;
5169         jfreefrag->fr_lbn = lbn;
5170         jfreefrag->fr_blkno = blkno;
5171         jfreefrag->fr_frags = numfrags(fs, size);
5172         jfreefrag->fr_freefrag = freefrag;
5173
5174         return (jfreefrag);
5175 }
5176
5177 /*
5178  * Allocate a new freefrag structure.
5179  */
5180 static struct freefrag *
5181 newfreefrag(ip, blkno, size, lbn)
5182         struct inode *ip;
5183         ufs2_daddr_t blkno;
5184         long size;
5185         ufs_lbn_t lbn;
5186 {
5187         struct freefrag *freefrag;
5188         struct fs *fs;
5189
5190         fs = ip->i_fs;
5191         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5192                 panic("newfreefrag: frag size");
5193         freefrag = malloc(sizeof(struct freefrag),
5194             M_FREEFRAG, M_SOFTDEP_FLAGS);
5195         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5196         freefrag->ff_state = ATTACHED;
5197         LIST_INIT(&freefrag->ff_jwork);
5198         freefrag->ff_inum = ip->i_number;
5199         freefrag->ff_vtype = ITOV(ip)->v_type;
5200         freefrag->ff_blkno = blkno;
5201         freefrag->ff_fragsize = size;
5202
5203         if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5204                 freefrag->ff_jdep = (struct worklist *)
5205                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5206         } else {
5207                 freefrag->ff_state |= DEPCOMPLETE;
5208                 freefrag->ff_jdep = NULL;
5209         }
5210
5211         return (freefrag);
5212 }
5213
5214 /*
5215  * This workitem de-allocates fragments that were replaced during
5216  * file block allocation.
5217  */
5218 static void 
5219 handle_workitem_freefrag(freefrag)
5220         struct freefrag *freefrag;
5221 {
5222         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5223         struct workhead wkhd;
5224
5225         /*
5226          * It would be illegal to add new completion items to the
5227          * freefrag after it was schedule to be done so it must be
5228          * safe to modify the list head here.
5229          */
5230         LIST_INIT(&wkhd);
5231         ACQUIRE_LOCK(&lk);
5232         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5233         /*
5234          * If the journal has not been written we must cancel it here.
5235          */
5236         if (freefrag->ff_jdep) {
5237                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5238                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5239                             freefrag->ff_jdep->wk_type);
5240                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5241         }
5242         FREE_LOCK(&lk);
5243         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5244            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5245         ACQUIRE_LOCK(&lk);
5246         WORKITEM_FREE(freefrag, D_FREEFRAG);
5247         FREE_LOCK(&lk);
5248 }
5249
5250 /*
5251  * Set up a dependency structure for an external attributes data block.
5252  * This routine follows much of the structure of softdep_setup_allocdirect.
5253  * See the description of softdep_setup_allocdirect above for details.
5254  */
5255 void 
5256 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5257         struct inode *ip;
5258         ufs_lbn_t off;
5259         ufs2_daddr_t newblkno;
5260         ufs2_daddr_t oldblkno;
5261         long newsize;
5262         long oldsize;
5263         struct buf *bp;
5264 {
5265         struct allocdirect *adp, *oldadp;
5266         struct allocdirectlst *adphead;
5267         struct freefrag *freefrag;
5268         struct inodedep *inodedep;
5269         struct jnewblk *jnewblk;
5270         struct newblk *newblk;
5271         struct mount *mp;
5272         ufs_lbn_t lbn;
5273
5274         if (off >= NXADDR)
5275                 panic("softdep_setup_allocext: lbn %lld > NXADDR",
5276                     (long long)off);
5277
5278         lbn = bp->b_lblkno;
5279         mp = UFSTOVFS(ip->i_ump);
5280         if (oldblkno && oldblkno != newblkno)
5281                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5282         else
5283                 freefrag = NULL;
5284
5285         ACQUIRE_LOCK(&lk);
5286         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5287                 panic("softdep_setup_allocext: lost block");
5288         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5289             ("softdep_setup_allocext: newblk already initialized"));
5290         /*
5291          * Convert the newblk to an allocdirect.
5292          */
5293         newblk->nb_list.wk_type = D_ALLOCDIRECT;
5294         adp = (struct allocdirect *)newblk;
5295         newblk->nb_freefrag = freefrag;
5296         adp->ad_offset = off;
5297         adp->ad_oldblkno = oldblkno;
5298         adp->ad_newsize = newsize;
5299         adp->ad_oldsize = oldsize;
5300         adp->ad_state |=  EXTDATA;
5301
5302         /*
5303          * Finish initializing the journal.
5304          */
5305         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5306                 jnewblk->jn_ino = ip->i_number;
5307                 jnewblk->jn_lbn = lbn;
5308                 add_to_journal(&jnewblk->jn_list);
5309         }
5310         if (freefrag && freefrag->ff_jdep != NULL &&
5311             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5312                 add_to_journal(freefrag->ff_jdep);
5313         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5314         adp->ad_inodedep = inodedep;
5315
5316         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5317         /*
5318          * The list of allocdirects must be kept in sorted and ascending
5319          * order so that the rollback routines can quickly determine the
5320          * first uncommitted block (the size of the file stored on disk
5321          * ends at the end of the lowest committed fragment, or if there
5322          * are no fragments, at the end of the highest committed block).
5323          * Since files generally grow, the typical case is that the new
5324          * block is to be added at the end of the list. We speed this
5325          * special case by checking against the last allocdirect in the
5326          * list before laboriously traversing the list looking for the
5327          * insertion point.
5328          */
5329         adphead = &inodedep->id_newextupdt;
5330         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5331         if (oldadp == NULL || oldadp->ad_offset <= off) {
5332                 /* insert at end of list */
5333                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5334                 if (oldadp != NULL && oldadp->ad_offset == off)
5335                         allocdirect_merge(adphead, adp, oldadp);
5336                 FREE_LOCK(&lk);
5337                 return;
5338         }
5339         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5340                 if (oldadp->ad_offset >= off)
5341                         break;
5342         }
5343         if (oldadp == NULL)
5344                 panic("softdep_setup_allocext: lost entry");
5345         /* insert in middle of list */
5346         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5347         if (oldadp->ad_offset == off)
5348                 allocdirect_merge(adphead, adp, oldadp);
5349         FREE_LOCK(&lk);
5350 }
5351
5352 /*
5353  * Indirect block allocation dependencies.
5354  * 
5355  * The same dependencies that exist for a direct block also exist when
5356  * a new block is allocated and pointed to by an entry in a block of
5357  * indirect pointers. The undo/redo states described above are also
5358  * used here. Because an indirect block contains many pointers that
5359  * may have dependencies, a second copy of the entire in-memory indirect
5360  * block is kept. The buffer cache copy is always completely up-to-date.
5361  * The second copy, which is used only as a source for disk writes,
5362  * contains only the safe pointers (i.e., those that have no remaining
5363  * update dependencies). The second copy is freed when all pointers
5364  * are safe. The cache is not allowed to replace indirect blocks with
5365  * pending update dependencies. If a buffer containing an indirect
5366  * block with dependencies is written, these routines will mark it
5367  * dirty again. It can only be successfully written once all the
5368  * dependencies are removed. The ffs_fsync routine in conjunction with
5369  * softdep_sync_metadata work together to get all the dependencies
5370  * removed so that a file can be successfully written to disk. Three
5371  * procedures are used when setting up indirect block pointer
5372  * dependencies. The division is necessary because of the organization
5373  * of the "balloc" routine and because of the distinction between file
5374  * pages and file metadata blocks.
5375  */
5376
5377 /*
5378  * Allocate a new allocindir structure.
5379  */
5380 static struct allocindir *
5381 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5382         struct inode *ip;       /* inode for file being extended */
5383         int ptrno;              /* offset of pointer in indirect block */
5384         ufs2_daddr_t newblkno;  /* disk block number being added */
5385         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5386         ufs_lbn_t lbn;
5387 {
5388         struct newblk *newblk;
5389         struct allocindir *aip;
5390         struct freefrag *freefrag;
5391         struct jnewblk *jnewblk;
5392
5393         if (oldblkno)
5394                 freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5395         else
5396                 freefrag = NULL;
5397         ACQUIRE_LOCK(&lk);
5398         if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5399                 panic("new_allocindir: lost block");
5400         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5401             ("newallocindir: newblk already initialized"));
5402         newblk->nb_list.wk_type = D_ALLOCINDIR;
5403         newblk->nb_freefrag = freefrag;
5404         aip = (struct allocindir *)newblk;
5405         aip->ai_offset = ptrno;
5406         aip->ai_oldblkno = oldblkno;
5407         aip->ai_lbn = lbn;
5408         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5409                 jnewblk->jn_ino = ip->i_number;
5410                 jnewblk->jn_lbn = lbn;
5411                 add_to_journal(&jnewblk->jn_list);
5412         }
5413         if (freefrag && freefrag->ff_jdep != NULL &&
5414             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5415                 add_to_journal(freefrag->ff_jdep);
5416         return (aip);
5417 }
5418
5419 /*
5420  * Called just before setting an indirect block pointer
5421  * to a newly allocated file page.
5422  */
5423 void
5424 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5425         struct inode *ip;       /* inode for file being extended */
5426         ufs_lbn_t lbn;          /* allocated block number within file */
5427         struct buf *bp;         /* buffer with indirect blk referencing page */
5428         int ptrno;              /* offset of pointer in indirect block */
5429         ufs2_daddr_t newblkno;  /* disk block number being added */
5430         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5431         struct buf *nbp;        /* buffer holding allocated page */
5432 {
5433         struct inodedep *inodedep;
5434         struct freefrag *freefrag;
5435         struct allocindir *aip;
5436         struct pagedep *pagedep;
5437         struct mount *mp;
5438
5439         if (lbn != nbp->b_lblkno)
5440                 panic("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5441                     lbn, bp->b_lblkno);
5442         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5443         mp = UFSTOVFS(ip->i_ump);
5444         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5445         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5446         /*
5447          * If we are allocating a directory page, then we must
5448          * allocate an associated pagedep to track additions and
5449          * deletions.
5450          */
5451         if ((ip->i_mode & IFMT) == IFDIR)
5452                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5453         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5454         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5455         FREE_LOCK(&lk);
5456         if (freefrag)
5457                 handle_workitem_freefrag(freefrag);
5458 }
5459
5460 /*
5461  * Called just before setting an indirect block pointer to a
5462  * newly allocated indirect block.
5463  */
5464 void
5465 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5466         struct buf *nbp;        /* newly allocated indirect block */
5467         struct inode *ip;       /* inode for file being extended */
5468         struct buf *bp;         /* indirect block referencing allocated block */
5469         int ptrno;              /* offset of pointer in indirect block */
5470         ufs2_daddr_t newblkno;  /* disk block number being added */
5471 {
5472         struct inodedep *inodedep;
5473         struct allocindir *aip;
5474         ufs_lbn_t lbn;
5475
5476         lbn = nbp->b_lblkno;
5477         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5478         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5479         inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC, &inodedep);
5480         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5481         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5482                 panic("softdep_setup_allocindir_meta: Block already existed");
5483         FREE_LOCK(&lk);
5484 }
5485
5486 static void
5487 indirdep_complete(indirdep)
5488         struct indirdep *indirdep;
5489 {
5490         struct allocindir *aip;
5491
5492         LIST_REMOVE(indirdep, ir_next);
5493         indirdep->ir_state |= DEPCOMPLETE;
5494
5495         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5496                 LIST_REMOVE(aip, ai_next);
5497                 free_newblk(&aip->ai_block);
5498         }
5499         /*
5500          * If this indirdep is not attached to a buf it was simply waiting
5501          * on completion to clear completehd.  free_indirdep() asserts
5502          * that nothing is dangling.
5503          */
5504         if ((indirdep->ir_state & ONWORKLIST) == 0)
5505                 free_indirdep(indirdep);
5506 }
5507
5508 static struct indirdep *
5509 indirdep_lookup(mp, ip, bp)
5510         struct mount *mp;
5511         struct inode *ip;
5512         struct buf *bp;
5513 {
5514         struct indirdep *indirdep, *newindirdep;
5515         struct newblk *newblk;
5516         struct worklist *wk;
5517         struct fs *fs;
5518         ufs2_daddr_t blkno;
5519
5520         mtx_assert(&lk, MA_OWNED);
5521         indirdep = NULL;
5522         newindirdep = NULL;
5523         fs = ip->i_fs;
5524         for (;;) {
5525                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5526                         if (wk->wk_type != D_INDIRDEP)
5527                                 continue;
5528                         indirdep = WK_INDIRDEP(wk);
5529                         break;
5530                 }
5531                 /* Found on the buffer worklist, no new structure to free. */
5532                 if (indirdep != NULL && newindirdep == NULL)
5533                         return (indirdep);
5534                 if (indirdep != NULL && newindirdep != NULL)
5535                         panic("indirdep_lookup: simultaneous create");
5536                 /* None found on the buffer and a new structure is ready. */
5537                 if (indirdep == NULL && newindirdep != NULL)
5538                         break;
5539                 /* None found and no new structure available. */
5540                 FREE_LOCK(&lk);
5541                 newindirdep = malloc(sizeof(struct indirdep),
5542                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5543                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5544                 newindirdep->ir_state = ATTACHED;
5545                 if (ip->i_ump->um_fstype == UFS1)
5546                         newindirdep->ir_state |= UFS1FMT;
5547                 TAILQ_INIT(&newindirdep->ir_trunc);
5548                 newindirdep->ir_saveddata = NULL;
5549                 LIST_INIT(&newindirdep->ir_deplisthd);
5550                 LIST_INIT(&newindirdep->ir_donehd);
5551                 LIST_INIT(&newindirdep->ir_writehd);
5552                 LIST_INIT(&newindirdep->ir_completehd);
5553                 if (bp->b_blkno == bp->b_lblkno) {
5554                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5555                             NULL, NULL);
5556                         bp->b_blkno = blkno;
5557                 }
5558                 newindirdep->ir_freeblks = NULL;
5559                 newindirdep->ir_savebp =
5560                     getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5561                 newindirdep->ir_bp = bp;
5562                 BUF_KERNPROC(newindirdep->ir_savebp);
5563                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5564                 ACQUIRE_LOCK(&lk);
5565         }
5566         indirdep = newindirdep;
5567         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5568         /*
5569          * If the block is not yet allocated we don't set DEPCOMPLETE so
5570          * that we don't free dependencies until the pointers are valid.
5571          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5572          * than using the hash.
5573          */
5574         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5575                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5576         else
5577                 indirdep->ir_state |= DEPCOMPLETE;
5578         return (indirdep);
5579 }
5580
5581 /*
5582  * Called to finish the allocation of the "aip" allocated
5583  * by one of the two routines above.
5584  */
5585 static struct freefrag *
5586 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5587         struct buf *bp;         /* in-memory copy of the indirect block */
5588         struct inode *ip;       /* inode for file being extended */
5589         struct inodedep *inodedep; /* Inodedep for ip */
5590         struct allocindir *aip; /* allocindir allocated by the above routines */
5591         ufs_lbn_t lbn;          /* Logical block number for this block. */
5592 {
5593         struct fs *fs;
5594         struct indirdep *indirdep;
5595         struct allocindir *oldaip;
5596         struct freefrag *freefrag;
5597         struct mount *mp;
5598
5599         mtx_assert(&lk, MA_OWNED);
5600         mp = UFSTOVFS(ip->i_ump);
5601         fs = ip->i_fs;
5602         if (bp->b_lblkno >= 0)
5603                 panic("setup_allocindir_phase2: not indir blk");
5604         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
5605             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
5606         indirdep = indirdep_lookup(mp, ip, bp);
5607         KASSERT(indirdep->ir_savebp != NULL,
5608             ("setup_allocindir_phase2 NULL ir_savebp"));
5609         aip->ai_indirdep = indirdep;
5610         /*
5611          * Check for an unwritten dependency for this indirect offset.  If
5612          * there is, merge the old dependency into the new one.  This happens
5613          * as a result of reallocblk only.
5614          */
5615         freefrag = NULL;
5616         if (aip->ai_oldblkno != 0) {
5617                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
5618                         if (oldaip->ai_offset == aip->ai_offset) {
5619                                 freefrag = allocindir_merge(aip, oldaip);
5620                                 goto done;
5621                         }
5622                 }
5623                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
5624                         if (oldaip->ai_offset == aip->ai_offset) {
5625                                 freefrag = allocindir_merge(aip, oldaip);
5626                                 goto done;
5627                         }
5628                 }
5629         }
5630 done:
5631         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
5632         return (freefrag);
5633 }
5634
5635 /*
5636  * Merge two allocindirs which refer to the same block.  Move newblock
5637  * dependencies and setup the freefrags appropriately.
5638  */
5639 static struct freefrag *
5640 allocindir_merge(aip, oldaip)
5641         struct allocindir *aip;
5642         struct allocindir *oldaip;
5643 {
5644         struct freefrag *freefrag;
5645         struct worklist *wk;
5646
5647         if (oldaip->ai_newblkno != aip->ai_oldblkno)
5648                 panic("allocindir_merge: blkno");
5649         aip->ai_oldblkno = oldaip->ai_oldblkno;
5650         freefrag = aip->ai_freefrag;
5651         aip->ai_freefrag = oldaip->ai_freefrag;
5652         oldaip->ai_freefrag = NULL;
5653         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
5654         /*
5655          * If we are tracking a new directory-block allocation,
5656          * move it from the old allocindir to the new allocindir.
5657          */
5658         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
5659                 WORKLIST_REMOVE(wk);
5660                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
5661                         panic("allocindir_merge: extra newdirblk");
5662                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
5663         }
5664         /*
5665          * We can skip journaling for this freefrag and just complete
5666          * any pending journal work for the allocindir that is being
5667          * removed after the freefrag completes.
5668          */
5669         if (freefrag->ff_jdep)
5670                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
5671         LIST_REMOVE(oldaip, ai_next);
5672         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
5673             &freefrag->ff_list, &freefrag->ff_jwork);
5674         free_newblk(&oldaip->ai_block);
5675
5676         return (freefrag);
5677 }
5678
5679 static inline void
5680 setup_freedirect(freeblks, ip, i, needj)
5681         struct freeblks *freeblks;
5682         struct inode *ip;
5683         int i;
5684         int needj;
5685 {
5686         ufs2_daddr_t blkno;
5687         int frags;
5688
5689         blkno = DIP(ip, i_db[i]);
5690         if (blkno == 0)
5691                 return;
5692         DIP_SET(ip, i_db[i], 0);
5693         frags = sblksize(ip->i_fs, ip->i_size, i);
5694         frags = numfrags(ip->i_fs, frags);
5695         newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
5696 }
5697
5698 static inline void
5699 setup_freeext(freeblks, ip, i, needj)
5700         struct freeblks *freeblks;
5701         struct inode *ip;
5702         int i;
5703         int needj;
5704 {
5705         ufs2_daddr_t blkno;
5706         int frags;
5707
5708         blkno = ip->i_din2->di_extb[i];
5709         if (blkno == 0)
5710                 return;
5711         ip->i_din2->di_extb[i] = 0;
5712         frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
5713         frags = numfrags(ip->i_fs, frags);
5714         newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
5715 }
5716
5717 static inline void
5718 setup_freeindir(freeblks, ip, i, lbn, needj)
5719         struct freeblks *freeblks;
5720         struct inode *ip;
5721         int i;
5722         ufs_lbn_t lbn;
5723         int needj;
5724 {
5725         ufs2_daddr_t blkno;
5726
5727         blkno = DIP(ip, i_ib[i]);
5728         if (blkno == 0)
5729                 return;
5730         DIP_SET(ip, i_ib[i], 0);
5731         newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
5732             0, needj);
5733 }
5734
5735 static inline struct freeblks *
5736 newfreeblks(mp, ip)
5737         struct mount *mp;
5738         struct inode *ip;
5739 {
5740         struct freeblks *freeblks;
5741
5742         freeblks = malloc(sizeof(struct freeblks),
5743                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
5744         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
5745         LIST_INIT(&freeblks->fb_jblkdephd);
5746         LIST_INIT(&freeblks->fb_jwork);
5747         freeblks->fb_ref = 0;
5748         freeblks->fb_cgwait = 0;
5749         freeblks->fb_state = ATTACHED;
5750         freeblks->fb_uid = ip->i_uid;
5751         freeblks->fb_inum = ip->i_number;
5752         freeblks->fb_vtype = ITOV(ip)->v_type;
5753         freeblks->fb_modrev = DIP(ip, i_modrev);
5754         freeblks->fb_devvp = ip->i_devvp;
5755         freeblks->fb_chkcnt = 0;
5756         freeblks->fb_len = 0;
5757
5758         return (freeblks);
5759 }
5760
5761 static void
5762 trunc_indirdep(indirdep, freeblks, bp, off)
5763         struct indirdep *indirdep;
5764         struct freeblks *freeblks;
5765         struct buf *bp;
5766         int off;
5767 {
5768         struct allocindir *aip, *aipn;
5769
5770         /*
5771          * The first set of allocindirs won't be in savedbp.
5772          */
5773         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
5774                 if (aip->ai_offset > off)
5775                         cancel_allocindir(aip, bp, freeblks, 1);
5776         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
5777                 if (aip->ai_offset > off)
5778                         cancel_allocindir(aip, bp, freeblks, 1);
5779         /*
5780          * These will exist in savedbp.
5781          */
5782         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
5783                 if (aip->ai_offset > off)
5784                         cancel_allocindir(aip, NULL, freeblks, 0);
5785         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
5786                 if (aip->ai_offset > off)
5787                         cancel_allocindir(aip, NULL, freeblks, 0);
5788 }
5789
5790 /*
5791  * Follow the chain of indirects down to lastlbn creating a freework
5792  * structure for each.  This will be used to start indir_trunc() at
5793  * the right offset and create the journal records for the parrtial
5794  * truncation.  A second step will handle the truncated dependencies.
5795  */
5796 static int
5797 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
5798         struct freeblks *freeblks;
5799         struct inode *ip;
5800         ufs_lbn_t lbn;
5801         ufs_lbn_t lastlbn;
5802         ufs2_daddr_t blkno;
5803 {
5804         struct indirdep *indirdep;
5805         struct indirdep *indirn;
5806         struct freework *freework;
5807         struct newblk *newblk;
5808         struct mount *mp;
5809         struct buf *bp;
5810         uint8_t *start;
5811         uint8_t *end;
5812         ufs_lbn_t lbnadd;
5813         int level;
5814         int error;
5815         int off;
5816
5817
5818         freework = NULL;
5819         if (blkno == 0)
5820                 return (0);
5821         mp = freeblks->fb_list.wk_mp;
5822         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
5823         if ((bp->b_flags & B_CACHE) == 0) {
5824                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
5825                 bp->b_iocmd = BIO_READ;
5826                 bp->b_flags &= ~B_INVAL;
5827                 bp->b_ioflags &= ~BIO_ERROR;
5828                 vfs_busy_pages(bp, 0);
5829                 bp->b_iooffset = dbtob(bp->b_blkno);
5830                 bstrategy(bp);
5831                 curthread->td_ru.ru_inblock++;
5832                 error = bufwait(bp);
5833                 if (error) {
5834                         brelse(bp);
5835                         return (error);
5836                 }
5837         }
5838         level = lbn_level(lbn);
5839         lbnadd = lbn_offset(ip->i_fs, level);
5840         /*
5841          * Compute the offset of the last block we want to keep.  Store
5842          * in the freework the first block we want to completely free.
5843          */
5844         off = (lastlbn - -(lbn + level)) / lbnadd;
5845         if (off + 1 == NINDIR(ip->i_fs))
5846                 goto nowork;
5847         freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
5848             0);
5849         /*
5850          * Link the freework into the indirdep.  This will prevent any new
5851          * allocations from proceeding until we are finished with the
5852          * truncate and the block is written.
5853          */
5854         ACQUIRE_LOCK(&lk);
5855         indirdep = indirdep_lookup(mp, ip, bp);
5856         if (indirdep->ir_freeblks)
5857                 panic("setup_trunc_indir: indirdep already truncated.");
5858         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
5859         freework->fw_indir = indirdep;
5860         /*
5861          * Cancel any allocindirs that will not make it to disk.
5862          * We have to do this for all copies of the indirdep that
5863          * live on this newblk.
5864          */
5865         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
5866                 newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
5867                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
5868                         trunc_indirdep(indirn, freeblks, bp, off);
5869         } else
5870                 trunc_indirdep(indirdep, freeblks, bp, off);
5871         FREE_LOCK(&lk);
5872         /*
5873          * Creation is protected by the buf lock. The saveddata is only
5874          * needed if a full truncation follows a partial truncation but it
5875          * is difficult to allocate in that case so we fetch it anyway.
5876          */
5877         if (indirdep->ir_saveddata == NULL)
5878                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
5879                     M_SOFTDEP_FLAGS);
5880 nowork:
5881         /* Fetch the blkno of the child and the zero start offset. */
5882         if (ip->i_ump->um_fstype == UFS1) {
5883                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
5884                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
5885         } else {
5886                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
5887                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
5888         }
5889         if (freework) {
5890                 /* Zero the truncated pointers. */
5891                 end = bp->b_data + bp->b_bcount;
5892                 bzero(start, end - start);
5893                 bdwrite(bp);
5894         } else
5895                 bqrelse(bp);
5896         if (level == 0)
5897                 return (0);
5898         lbn++; /* adjust level */
5899         lbn -= (off * lbnadd);
5900         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
5901 }
5902
5903 /*
5904  * Complete the partial truncation of an indirect block setup by
5905  * setup_trunc_indir().  This zeros the truncated pointers in the saved
5906  * copy and writes them to disk before the freeblks is allowed to complete.
5907  */
5908 static void
5909 complete_trunc_indir(freework)
5910         struct freework *freework;
5911 {
5912         struct freework *fwn;
5913         struct indirdep *indirdep;
5914         struct buf *bp;
5915         uintptr_t start;
5916         int count;
5917
5918         indirdep = freework->fw_indir;
5919         for (;;) {
5920                 bp = indirdep->ir_bp;
5921                 /* See if the block was discarded. */
5922                 if (bp == NULL)
5923                         break;
5924                 /* Inline part of getdirtybuf().  We dont want bremfree. */
5925                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
5926                         break;
5927                 if (BUF_LOCK(bp,
5928                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, &lk) == 0)
5929                         BUF_UNLOCK(bp);
5930                 ACQUIRE_LOCK(&lk);
5931         }
5932         mtx_assert(&lk, MA_OWNED);
5933         freework->fw_state |= DEPCOMPLETE;
5934         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
5935         /*
5936          * Zero the pointers in the saved copy.
5937          */
5938         if (indirdep->ir_state & UFS1FMT)
5939                 start = sizeof(ufs1_daddr_t);
5940         else
5941                 start = sizeof(ufs2_daddr_t);
5942         start *= freework->fw_start;
5943         count = indirdep->ir_savebp->b_bcount - start;
5944         start += (uintptr_t)indirdep->ir_savebp->b_data;
5945         bzero((char *)start, count);
5946         /*
5947          * We need to start the next truncation in the list if it has not
5948          * been started yet.
5949          */
5950         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
5951         if (fwn != NULL) {
5952                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
5953                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
5954                 if ((fwn->fw_state & ONWORKLIST) == 0)
5955                         freework_enqueue(fwn);
5956         }
5957         /*
5958          * If bp is NULL the block was fully truncated, restore
5959          * the saved block list otherwise free it if it is no
5960          * longer needed.
5961          */
5962         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
5963                 if (bp == NULL)
5964                         bcopy(indirdep->ir_saveddata,
5965                             indirdep->ir_savebp->b_data,
5966                             indirdep->ir_savebp->b_bcount);
5967                 free(indirdep->ir_saveddata, M_INDIRDEP);
5968                 indirdep->ir_saveddata = NULL;
5969         }
5970         /*
5971          * When bp is NULL there is a full truncation pending.  We
5972          * must wait for this full truncation to be journaled before
5973          * we can release this freework because the disk pointers will
5974          * never be written as zero.
5975          */
5976         if (bp == NULL)  {
5977                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
5978                         handle_written_freework(freework);
5979                 else
5980                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
5981                            &freework->fw_list);
5982         } else {
5983                 /* Complete when the real copy is written. */
5984                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
5985                 BUF_UNLOCK(bp);
5986         }
5987 }
5988
5989 /*
5990  * Calculate the number of blocks we are going to release where datablocks
5991  * is the current total and length is the new file size.
5992  */
5993 ufs2_daddr_t
5994 blkcount(fs, datablocks, length)
5995         struct fs *fs;
5996         ufs2_daddr_t datablocks;
5997         off_t length;
5998 {
5999         off_t totblks, numblks;
6000
6001         totblks = 0;
6002         numblks = howmany(length, fs->fs_bsize);
6003         if (numblks <= NDADDR) {
6004                 totblks = howmany(length, fs->fs_fsize);
6005                 goto out;
6006         }
6007         totblks = blkstofrags(fs, numblks);
6008         numblks -= NDADDR;
6009         /*
6010          * Count all single, then double, then triple indirects required.
6011          * Subtracting one indirects worth of blocks for each pass
6012          * acknowledges one of each pointed to by the inode.
6013          */
6014         for (;;) {
6015                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6016                 numblks -= NINDIR(fs);
6017                 if (numblks <= 0)
6018                         break;
6019                 numblks = howmany(numblks, NINDIR(fs));
6020         }
6021 out:
6022         totblks = fsbtodb(fs, totblks);
6023         /*
6024          * Handle sparse files.  We can't reclaim more blocks than the inode
6025          * references.  We will correct it later in handle_complete_freeblks()
6026          * when we know the real count.
6027          */
6028         if (totblks > datablocks)
6029                 return (0);
6030         return (datablocks - totblks);
6031 }
6032
6033 /*
6034  * Handle freeblocks for journaled softupdate filesystems.
6035  *
6036  * Contrary to normal softupdates, we must preserve the block pointers in
6037  * indirects until their subordinates are free.  This is to avoid journaling
6038  * every block that is freed which may consume more space than the journal
6039  * itself.  The recovery program will see the free block journals at the
6040  * base of the truncated area and traverse them to reclaim space.  The
6041  * pointers in the inode may be cleared immediately after the journal
6042  * records are written because each direct and indirect pointer in the
6043  * inode is recorded in a journal.  This permits full truncation to proceed
6044  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6045  *
6046  * The algorithm is as follows:
6047  * 1) Traverse the in-memory state and create journal entries to release
6048  *    the relevant blocks and full indirect trees.
6049  * 2) Traverse the indirect block chain adding partial truncation freework
6050  *    records to indirects in the path to lastlbn.  The freework will
6051  *    prevent new allocation dependencies from being satisfied in this
6052  *    indirect until the truncation completes.
6053  * 3) Read and lock the inode block, performing an update with the new size
6054  *    and pointers.  This prevents truncated data from becoming valid on
6055  *    disk through step 4.
6056  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6057  *    eliminate journal work for those records that do not require it.
6058  * 5) Schedule the journal records to be written followed by the inode block.
6059  * 6) Allocate any necessary frags for the end of file.
6060  * 7) Zero any partially truncated blocks.
6061  *
6062  * From this truncation proceeds asynchronously using the freework and
6063  * indir_trunc machinery.  The file will not be extended again into a
6064  * partially truncated indirect block until all work is completed but
6065  * the normal dependency mechanism ensures that it is rolled back/forward
6066  * as appropriate.  Further truncation may occur without delay and is
6067  * serialized in indir_trunc().
6068  */
6069 void
6070 softdep_journal_freeblocks(ip, cred, length, flags)
6071         struct inode *ip;       /* The inode whose length is to be reduced */
6072         struct ucred *cred;
6073         off_t length;           /* The new length for the file */
6074         int flags;              /* IO_EXT and/or IO_NORMAL */
6075 {
6076         struct freeblks *freeblks, *fbn;
6077         struct inodedep *inodedep;
6078         struct jblkdep *jblkdep;
6079         struct allocdirect *adp, *adpn;
6080         struct fs *fs;
6081         struct buf *bp;
6082         struct vnode *vp;
6083         struct mount *mp;
6084         ufs2_daddr_t extblocks, datablocks;
6085         ufs_lbn_t tmpval, lbn, lastlbn;
6086         int frags;
6087         int lastoff, iboff;
6088         int allocblock;
6089         int error, i;
6090         int needj;
6091
6092         fs = ip->i_fs;
6093         mp = UFSTOVFS(ip->i_ump);
6094         vp = ITOV(ip);
6095         needj = 1;
6096         iboff = -1;
6097         allocblock = 0;
6098         extblocks = 0;
6099         datablocks = 0;
6100         frags = 0;
6101         freeblks = newfreeblks(mp, ip);
6102         ACQUIRE_LOCK(&lk);
6103         /*
6104          * If we're truncating a removed file that will never be written
6105          * we don't need to journal the block frees.  The canceled journals
6106          * for the allocations will suffice.
6107          */
6108         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6109         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6110             length == 0)
6111                 needj = 0;
6112         FREE_LOCK(&lk);
6113         /*
6114          * Calculate the lbn that we are truncating to.  This results in -1
6115          * if we're truncating the 0 bytes.  So it is the last lbn we want
6116          * to keep, not the first lbn we want to truncate.
6117          */
6118         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6119         lastoff = blkoff(fs, length);
6120         /*
6121          * Compute frags we are keeping in lastlbn.  0 means all.
6122          */
6123         if (lastlbn >= 0 && lastlbn < NDADDR) {
6124                 frags = fragroundup(fs, lastoff);
6125                 /* adp offset of last valid allocdirect. */
6126                 iboff = lastlbn;
6127         } else if (lastlbn > 0)
6128                 iboff = NDADDR;
6129         if (fs->fs_magic == FS_UFS2_MAGIC)
6130                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6131         /*
6132          * Handle normal data blocks and indirects.  This section saves
6133          * values used after the inode update to complete frag and indirect
6134          * truncation.
6135          */
6136         if ((flags & IO_NORMAL) != 0) {
6137                 /*
6138                  * Handle truncation of whole direct and indirect blocks.
6139                  */
6140                 for (i = iboff + 1; i < NDADDR; i++)
6141                         setup_freedirect(freeblks, ip, i, needj);
6142                 for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6143                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6144                         /* Release a whole indirect tree. */
6145                         if (lbn > lastlbn) {
6146                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6147                                     needj);
6148                                 continue;
6149                         }
6150                         iboff = i + NDADDR;
6151                         /*
6152                          * Traverse partially truncated indirect tree.
6153                          */
6154                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6155                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6156                                     lastlbn, DIP(ip, i_ib[i]));
6157                 }
6158                 /*
6159                  * Handle partial truncation to a frag boundary.
6160                  */
6161                 if (frags) {
6162                         ufs2_daddr_t blkno;
6163                         long oldfrags;
6164
6165                         oldfrags = blksize(fs, ip, lastlbn);
6166                         blkno = DIP(ip, i_db[lastlbn]);
6167                         if (blkno && oldfrags != frags) {
6168                                 oldfrags -= frags;
6169                                 oldfrags = numfrags(ip->i_fs, oldfrags);
6170                                 blkno += numfrags(ip->i_fs, frags);
6171                                 newfreework(ip->i_ump, freeblks, NULL, lastlbn,
6172                                     blkno, oldfrags, 0, needj);
6173                         } else if (blkno == 0)
6174                                 allocblock = 1;
6175                 }
6176                 /*
6177                  * Add a journal record for partial truncate if we are
6178                  * handling indirect blocks.  Non-indirects need no extra
6179                  * journaling.
6180                  */
6181                 if (length != 0 && lastlbn >= NDADDR) {
6182                         ip->i_flag |= IN_TRUNCATED;
6183                         newjtrunc(freeblks, length, 0);
6184                 }
6185                 ip->i_size = length;
6186                 DIP_SET(ip, i_size, ip->i_size);
6187                 datablocks = DIP(ip, i_blocks) - extblocks;
6188                 if (length != 0)
6189                         datablocks = blkcount(ip->i_fs, datablocks, length);
6190                 freeblks->fb_len = length;
6191         }
6192         if ((flags & IO_EXT) != 0) {
6193                 for (i = 0; i < NXADDR; i++)
6194                         setup_freeext(freeblks, ip, i, needj);
6195                 ip->i_din2->di_extsize = 0;
6196                 datablocks += extblocks;
6197         }
6198 #ifdef QUOTA
6199         /* Reference the quotas in case the block count is wrong in the end. */
6200         quotaref(vp, freeblks->fb_quota);
6201         (void) chkdq(ip, -datablocks, NOCRED, 0);
6202 #endif
6203         freeblks->fb_chkcnt = -datablocks;
6204         UFS_LOCK(ip->i_ump);
6205         fs->fs_pendingblocks += datablocks;
6206         UFS_UNLOCK(ip->i_ump);
6207         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6208         /*
6209          * Handle truncation of incomplete alloc direct dependencies.  We
6210          * hold the inode block locked to prevent incomplete dependencies
6211          * from reaching the disk while we are eliminating those that
6212          * have been truncated.  This is a partially inlined ffs_update().
6213          */
6214         ufs_itimes(vp);
6215         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6216         error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6217             (int)fs->fs_bsize, cred, &bp);
6218         if (error) {
6219                 brelse(bp);
6220                 softdep_error("softdep_journal_freeblocks", error);
6221                 return;
6222         }
6223         if (bp->b_bufsize == fs->fs_bsize)
6224                 bp->b_flags |= B_CLUSTEROK;
6225         softdep_update_inodeblock(ip, bp, 0);
6226         if (ip->i_ump->um_fstype == UFS1)
6227                 *((struct ufs1_dinode *)bp->b_data +
6228                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6229         else
6230                 *((struct ufs2_dinode *)bp->b_data +
6231                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6232         ACQUIRE_LOCK(&lk);
6233         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6234         if ((inodedep->id_state & IOSTARTED) != 0)
6235                 panic("softdep_setup_freeblocks: inode busy");
6236         /*
6237          * Add the freeblks structure to the list of operations that
6238          * must await the zero'ed inode being written to disk. If we
6239          * still have a bitmap dependency (needj), then the inode
6240          * has never been written to disk, so we can process the
6241          * freeblks below once we have deleted the dependencies.
6242          */
6243         if (needj)
6244                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6245         else
6246                 freeblks->fb_state |= COMPLETE;
6247         if ((flags & IO_NORMAL) != 0) {
6248                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6249                         if (adp->ad_offset > iboff)
6250                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6251                                     freeblks);
6252                         /*
6253                          * Truncate the allocdirect.  We could eliminate
6254                          * or modify journal records as well.
6255                          */
6256                         else if (adp->ad_offset == iboff && frags)
6257                                 adp->ad_newsize = frags;
6258                 }
6259         }
6260         if ((flags & IO_EXT) != 0)
6261                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6262                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6263                             freeblks);
6264         /*
6265          * Add journal work.
6266          */
6267         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6268                 add_to_journal(&jblkdep->jb_list);
6269         FREE_LOCK(&lk);
6270         bdwrite(bp);
6271         /*
6272          * Truncate dependency structures beyond length.
6273          */
6274         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6275         /*
6276          * This is only set when we need to allocate a fragment because
6277          * none existed at the end of a frag-sized file.  It handles only
6278          * allocating a new, zero filled block.
6279          */
6280         if (allocblock) {
6281                 ip->i_size = length - lastoff;
6282                 DIP_SET(ip, i_size, ip->i_size);
6283                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6284                 if (error != 0) {
6285                         softdep_error("softdep_journal_freeblks", error);
6286                         return;
6287                 }
6288                 ip->i_size = length;
6289                 DIP_SET(ip, i_size, length);
6290                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6291                 allocbuf(bp, frags);
6292                 ffs_update(vp, MNT_NOWAIT);
6293                 bawrite(bp);
6294         } else if (lastoff != 0 && vp->v_type != VDIR) {
6295                 int size;
6296
6297                 /*
6298                  * Zero the end of a truncated frag or block.
6299                  */
6300                 size = sblksize(fs, length, lastlbn);
6301                 error = bread(vp, lastlbn, size, cred, &bp);
6302                 if (error) {
6303                         softdep_error("softdep_journal_freeblks", error);
6304                         return;
6305                 }
6306                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6307                 bawrite(bp);
6308
6309         }
6310         ACQUIRE_LOCK(&lk);
6311         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6312         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6313         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6314         /*
6315          * We zero earlier truncations so they don't erroneously
6316          * update i_blocks.
6317          */
6318         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6319                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6320                         fbn->fb_len = 0;
6321         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6322             LIST_EMPTY(&freeblks->fb_jblkdephd))
6323                 freeblks->fb_state |= INPROGRESS;
6324         else
6325                 freeblks = NULL;
6326         FREE_LOCK(&lk);
6327         if (freeblks)
6328                 handle_workitem_freeblocks(freeblks, 0);
6329         trunc_pages(ip, length, extblocks, flags);
6330
6331 }
6332
6333 /*
6334  * Flush a JOP_SYNC to the journal.
6335  */
6336 void
6337 softdep_journal_fsync(ip)
6338         struct inode *ip;
6339 {
6340         struct jfsync *jfsync;
6341
6342         if ((ip->i_flag & IN_TRUNCATED) == 0)
6343                 return;
6344         ip->i_flag &= ~IN_TRUNCATED;
6345         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6346         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6347         jfsync->jfs_size = ip->i_size;
6348         jfsync->jfs_ino = ip->i_number;
6349         ACQUIRE_LOCK(&lk);
6350         add_to_journal(&jfsync->jfs_list);
6351         jwait(&jfsync->jfs_list, MNT_WAIT);
6352         FREE_LOCK(&lk);
6353 }
6354
6355 /*
6356  * Block de-allocation dependencies.
6357  * 
6358  * When blocks are de-allocated, the on-disk pointers must be nullified before
6359  * the blocks are made available for use by other files.  (The true
6360  * requirement is that old pointers must be nullified before new on-disk
6361  * pointers are set.  We chose this slightly more stringent requirement to
6362  * reduce complexity.) Our implementation handles this dependency by updating
6363  * the inode (or indirect block) appropriately but delaying the actual block
6364  * de-allocation (i.e., freemap and free space count manipulation) until
6365  * after the updated versions reach stable storage.  After the disk is
6366  * updated, the blocks can be safely de-allocated whenever it is convenient.
6367  * This implementation handles only the common case of reducing a file's
6368  * length to zero. Other cases are handled by the conventional synchronous
6369  * write approach.
6370  *
6371  * The ffs implementation with which we worked double-checks
6372  * the state of the block pointers and file size as it reduces
6373  * a file's length.  Some of this code is replicated here in our
6374  * soft updates implementation.  The freeblks->fb_chkcnt field is
6375  * used to transfer a part of this information to the procedure
6376  * that eventually de-allocates the blocks.
6377  *
6378  * This routine should be called from the routine that shortens
6379  * a file's length, before the inode's size or block pointers
6380  * are modified. It will save the block pointer information for
6381  * later release and zero the inode so that the calling routine
6382  * can release it.
6383  */
6384 void
6385 softdep_setup_freeblocks(ip, length, flags)
6386         struct inode *ip;       /* The inode whose length is to be reduced */
6387         off_t length;           /* The new length for the file */
6388         int flags;              /* IO_EXT and/or IO_NORMAL */
6389 {
6390         struct ufs1_dinode *dp1;
6391         struct ufs2_dinode *dp2;
6392         struct freeblks *freeblks;
6393         struct inodedep *inodedep;
6394         struct allocdirect *adp;
6395         struct buf *bp;
6396         struct fs *fs;
6397         ufs2_daddr_t extblocks, datablocks;
6398         struct mount *mp;
6399         int i, delay, error;
6400         ufs_lbn_t tmpval;
6401         ufs_lbn_t lbn;
6402
6403         fs = ip->i_fs;
6404         mp = UFSTOVFS(ip->i_ump);
6405         if (length != 0)
6406                 panic("softdep_setup_freeblocks: non-zero length");
6407         freeblks = newfreeblks(mp, ip);
6408         extblocks = 0;
6409         datablocks = 0;
6410         if (fs->fs_magic == FS_UFS2_MAGIC)
6411                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6412         if ((flags & IO_NORMAL) != 0) {
6413                 for (i = 0; i < NDADDR; i++)
6414                         setup_freedirect(freeblks, ip, i, 0);
6415                 for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6416                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6417                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6418                 ip->i_size = 0;
6419                 DIP_SET(ip, i_size, 0);
6420                 datablocks = DIP(ip, i_blocks) - extblocks;
6421         }
6422         if ((flags & IO_EXT) != 0) {
6423                 for (i = 0; i < NXADDR; i++)
6424                         setup_freeext(freeblks, ip, i, 0);
6425                 ip->i_din2->di_extsize = 0;
6426                 datablocks += extblocks;
6427         }
6428 #ifdef QUOTA
6429         /* Reference the quotas in case the block count is wrong in the end. */
6430         quotaref(vp, freeblks->fb_quota);
6431         (void) chkdq(ip, -datablocks, NOCRED, 0);
6432 #endif
6433         freeblks->fb_chkcnt = -datablocks;
6434         UFS_LOCK(ip->i_ump);
6435         fs->fs_pendingblocks += datablocks;
6436         UFS_UNLOCK(ip->i_ump);
6437         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6438         /*
6439          * Push the zero'ed inode to to its disk buffer so that we are free
6440          * to delete its dependencies below. Once the dependencies are gone
6441          * the buffer can be safely released.
6442          */
6443         if ((error = bread(ip->i_devvp,
6444             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6445             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6446                 brelse(bp);
6447                 softdep_error("softdep_setup_freeblocks", error);
6448         }
6449         if (ip->i_ump->um_fstype == UFS1) {
6450                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6451                     ino_to_fsbo(fs, ip->i_number));
6452                 ip->i_din1->di_freelink = dp1->di_freelink;
6453                 *dp1 = *ip->i_din1;
6454         } else {
6455                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6456                     ino_to_fsbo(fs, ip->i_number));
6457                 ip->i_din2->di_freelink = dp2->di_freelink;
6458                 *dp2 = *ip->i_din2;
6459         }
6460         /*
6461          * Find and eliminate any inode dependencies.
6462          */
6463         ACQUIRE_LOCK(&lk);
6464         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6465         if ((inodedep->id_state & IOSTARTED) != 0)
6466                 panic("softdep_setup_freeblocks: inode busy");
6467         /*
6468          * Add the freeblks structure to the list of operations that
6469          * must await the zero'ed inode being written to disk. If we
6470          * still have a bitmap dependency (delay == 0), then the inode
6471          * has never been written to disk, so we can process the
6472          * freeblks below once we have deleted the dependencies.
6473          */
6474         delay = (inodedep->id_state & DEPCOMPLETE);
6475         if (delay)
6476                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6477         else
6478                 freeblks->fb_state |= COMPLETE;
6479         /*
6480          * Because the file length has been truncated to zero, any
6481          * pending block allocation dependency structures associated
6482          * with this inode are obsolete and can simply be de-allocated.
6483          * We must first merge the two dependency lists to get rid of
6484          * any duplicate freefrag structures, then purge the merged list.
6485          * If we still have a bitmap dependency, then the inode has never
6486          * been written to disk, so we can free any fragments without delay.
6487          */
6488         if (flags & IO_NORMAL) {
6489                 merge_inode_lists(&inodedep->id_newinoupdt,
6490                     &inodedep->id_inoupdt);
6491                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6492                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6493                             freeblks);
6494         }
6495         if (flags & IO_EXT) {
6496                 merge_inode_lists(&inodedep->id_newextupdt,
6497                     &inodedep->id_extupdt);
6498                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6499                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6500                             freeblks);
6501         }
6502         FREE_LOCK(&lk);
6503         bdwrite(bp);
6504         trunc_dependencies(ip, freeblks, -1, 0, flags);
6505         ACQUIRE_LOCK(&lk);
6506         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6507                 (void) free_inodedep(inodedep);
6508         freeblks->fb_state |= DEPCOMPLETE;
6509         /*
6510          * If the inode with zeroed block pointers is now on disk
6511          * we can start freeing blocks.
6512          */  
6513         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6514                 freeblks->fb_state |= INPROGRESS;
6515         else
6516                 freeblks = NULL;
6517         FREE_LOCK(&lk);
6518         if (freeblks)
6519                 handle_workitem_freeblocks(freeblks, 0);
6520         trunc_pages(ip, length, extblocks, flags);
6521 }
6522
6523 /*
6524  * Eliminate pages from the page cache that back parts of this inode and
6525  * adjust the vnode pager's idea of our size.  This prevents stale data
6526  * from hanging around in the page cache.
6527  */
6528 static void
6529 trunc_pages(ip, length, extblocks, flags)
6530         struct inode *ip;
6531         off_t length;
6532         ufs2_daddr_t extblocks;
6533         int flags;
6534 {
6535         struct vnode *vp;
6536         struct fs *fs;
6537         ufs_lbn_t lbn;
6538         off_t end, extend;
6539
6540         vp = ITOV(ip);
6541         fs = ip->i_fs;
6542         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6543         if ((flags & IO_EXT) != 0)
6544                 vn_pages_remove(vp, extend, 0);
6545         if ((flags & IO_NORMAL) == 0)
6546                 return;
6547         BO_LOCK(&vp->v_bufobj);
6548         drain_output(vp);
6549         BO_UNLOCK(&vp->v_bufobj);
6550         /*
6551          * The vnode pager eliminates file pages we eliminate indirects
6552          * below.
6553          */
6554         vnode_pager_setsize(vp, length);
6555         /*
6556          * Calculate the end based on the last indirect we want to keep.  If
6557          * the block extends into indirects we can just use the negative of
6558          * its lbn.  Doubles and triples exist at lower numbers so we must
6559          * be careful not to remove those, if they exist.  double and triple
6560          * indirect lbns do not overlap with others so it is not important
6561          * to verify how many levels are required.
6562          */
6563         lbn = lblkno(fs, length);
6564         if (lbn >= NDADDR) {
6565                 /* Calculate the virtual lbn of the triple indirect. */
6566                 lbn = -lbn - (NIADDR - 1);
6567                 end = OFF_TO_IDX(lblktosize(fs, lbn));
6568         } else
6569                 end = extend;
6570         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
6571 }
6572
6573 /*
6574  * See if the buf bp is in the range eliminated by truncation.
6575  */
6576 static int
6577 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
6578         struct buf *bp;
6579         int *blkoffp;
6580         ufs_lbn_t lastlbn;
6581         int lastoff;
6582         int flags;
6583 {
6584         ufs_lbn_t lbn;
6585
6586         *blkoffp = 0;
6587         /* Only match ext/normal blocks as appropriate. */
6588         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
6589             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
6590                 return (0);
6591         /* ALTDATA is always a full truncation. */
6592         if ((bp->b_xflags & BX_ALTDATA) != 0)
6593                 return (1);
6594         /* -1 is full truncation. */
6595         if (lastlbn == -1)
6596                 return (1);
6597         /*
6598          * If this is a partial truncate we only want those
6599          * blocks and indirect blocks that cover the range
6600          * we're after.
6601          */
6602         lbn = bp->b_lblkno;
6603         if (lbn < 0)
6604                 lbn = -(lbn + lbn_level(lbn));
6605         if (lbn < lastlbn)
6606                 return (0);
6607         /* Here we only truncate lblkno if it's partial. */
6608         if (lbn == lastlbn) {
6609                 if (lastoff == 0)
6610                         return (0);
6611                 *blkoffp = lastoff;
6612         }
6613         return (1);
6614 }
6615
6616 /*
6617  * Eliminate any dependencies that exist in memory beyond lblkno:off
6618  */
6619 static void
6620 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
6621         struct inode *ip;
6622         struct freeblks *freeblks;
6623         ufs_lbn_t lastlbn;
6624         int lastoff;
6625         int flags;
6626 {
6627         struct bufobj *bo;
6628         struct vnode *vp;
6629         struct buf *bp;
6630         struct fs *fs;
6631         int blkoff;
6632
6633         /*
6634          * We must wait for any I/O in progress to finish so that
6635          * all potential buffers on the dirty list will be visible.
6636          * Once they are all there, walk the list and get rid of
6637          * any dependencies.
6638          */
6639         fs = ip->i_fs;
6640         vp = ITOV(ip);
6641         bo = &vp->v_bufobj;
6642         BO_LOCK(bo);
6643         drain_output(vp);
6644         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
6645                 bp->b_vflags &= ~BV_SCANNED;
6646 restart:
6647         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
6648                 if (bp->b_vflags & BV_SCANNED)
6649                         continue;
6650                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6651                         bp->b_vflags |= BV_SCANNED;
6652                         continue;
6653                 }
6654                 if ((bp = getdirtybuf(bp, BO_MTX(bo), MNT_WAIT)) == NULL)
6655                         goto restart;
6656                 BO_UNLOCK(bo);
6657                 if (deallocate_dependencies(bp, freeblks, blkoff))
6658                         bqrelse(bp);
6659                 else
6660                         brelse(bp);
6661                 BO_LOCK(bo);
6662                 goto restart;
6663         }
6664         /*
6665          * Now do the work of vtruncbuf while also matching indirect blocks.
6666          */
6667         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
6668                 bp->b_vflags &= ~BV_SCANNED;
6669 cleanrestart:
6670         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
6671                 if (bp->b_vflags & BV_SCANNED)
6672                         continue;
6673                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
6674                         bp->b_vflags |= BV_SCANNED;
6675                         continue;
6676                 }
6677                 if (BUF_LOCK(bp,
6678                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6679                     BO_MTX(bo)) == ENOLCK) {
6680                         BO_LOCK(bo);
6681                         goto cleanrestart;
6682                 }
6683                 bp->b_vflags |= BV_SCANNED;
6684                 BO_LOCK(bo);
6685                 bremfree(bp);
6686                 BO_UNLOCK(bo);
6687                 if (blkoff != 0) {
6688                         allocbuf(bp, blkoff);
6689                         bqrelse(bp);
6690                 } else {
6691                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
6692                         brelse(bp);
6693                 }
6694                 BO_LOCK(bo);
6695                 goto cleanrestart;
6696         }
6697         drain_output(vp);
6698         BO_UNLOCK(bo);
6699 }
6700
6701 static int
6702 cancel_pagedep(pagedep, freeblks, blkoff)
6703         struct pagedep *pagedep;
6704         struct freeblks *freeblks;
6705         int blkoff;
6706 {
6707         struct jremref *jremref;
6708         struct jmvref *jmvref;
6709         struct dirrem *dirrem, *tmp;
6710         int i;
6711
6712         /*
6713          * Copy any directory remove dependencies to the list
6714          * to be processed after the freeblks proceeds.  If
6715          * directory entry never made it to disk they
6716          * can be dumped directly onto the work list.
6717          */
6718         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
6719                 /* Skip this directory removal if it is intended to remain. */
6720                 if (dirrem->dm_offset < blkoff)
6721                         continue;
6722                 /*
6723                  * If there are any dirrems we wait for the journal write
6724                  * to complete and then restart the buf scan as the lock
6725                  * has been dropped.
6726                  */
6727                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
6728                         jwait(&jremref->jr_list, MNT_WAIT);
6729                         return (ERESTART);
6730                 }
6731                 LIST_REMOVE(dirrem, dm_next);
6732                 dirrem->dm_dirinum = pagedep->pd_ino;
6733                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
6734         }
6735         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
6736                 jwait(&jmvref->jm_list, MNT_WAIT);
6737                 return (ERESTART);
6738         }
6739         /*
6740          * When we're partially truncating a pagedep we just want to flush
6741          * journal entries and return.  There can not be any adds in the
6742          * truncated portion of the directory and newblk must remain if
6743          * part of the block remains.
6744          */
6745         if (blkoff != 0) {
6746                 struct diradd *dap;
6747
6748                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
6749                         if (dap->da_offset > blkoff)
6750                                 panic("cancel_pagedep: diradd %p off %d > %d",
6751                                     dap, dap->da_offset, blkoff);
6752                 for (i = 0; i < DAHASHSZ; i++)
6753                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
6754                                 if (dap->da_offset > blkoff)
6755                                         panic("cancel_pagedep: diradd %p off %d > %d",
6756                                             dap, dap->da_offset, blkoff);
6757                 return (0);
6758         }
6759         /*
6760          * There should be no directory add dependencies present
6761          * as the directory could not be truncated until all
6762          * children were removed.
6763          */
6764         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
6765             ("deallocate_dependencies: pendinghd != NULL"));
6766         for (i = 0; i < DAHASHSZ; i++)
6767                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
6768                     ("deallocate_dependencies: diraddhd != NULL"));
6769         if ((pagedep->pd_state & NEWBLOCK) != 0)
6770                 free_newdirblk(pagedep->pd_newdirblk);
6771         if (free_pagedep(pagedep) == 0)
6772                 panic("Failed to free pagedep %p", pagedep);
6773         return (0);
6774 }
6775
6776 /*
6777  * Reclaim any dependency structures from a buffer that is about to
6778  * be reallocated to a new vnode. The buffer must be locked, thus,
6779  * no I/O completion operations can occur while we are manipulating
6780  * its associated dependencies. The mutex is held so that other I/O's
6781  * associated with related dependencies do not occur.
6782  */
6783 static int
6784 deallocate_dependencies(bp, freeblks, off)
6785         struct buf *bp;
6786         struct freeblks *freeblks;
6787         int off;
6788 {
6789         struct indirdep *indirdep;
6790         struct pagedep *pagedep;
6791         struct allocdirect *adp;
6792         struct worklist *wk, *wkn;
6793
6794         ACQUIRE_LOCK(&lk);
6795         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
6796                 switch (wk->wk_type) {
6797                 case D_INDIRDEP:
6798                         indirdep = WK_INDIRDEP(wk);
6799                         if (bp->b_lblkno >= 0 ||
6800                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
6801                                 panic("deallocate_dependencies: not indir");
6802                         cancel_indirdep(indirdep, bp, freeblks);
6803                         continue;
6804
6805                 case D_PAGEDEP:
6806                         pagedep = WK_PAGEDEP(wk);
6807                         if (cancel_pagedep(pagedep, freeblks, off)) {
6808                                 FREE_LOCK(&lk);
6809                                 return (ERESTART);
6810                         }
6811                         continue;
6812
6813                 case D_ALLOCINDIR:
6814                         /*
6815                          * Simply remove the allocindir, we'll find it via
6816                          * the indirdep where we can clear pointers if
6817                          * needed.
6818                          */
6819                         WORKLIST_REMOVE(wk);
6820                         continue;
6821
6822                 case D_FREEWORK:
6823                         /*
6824                          * A truncation is waiting for the zero'd pointers
6825                          * to be written.  It can be freed when the freeblks
6826                          * is journaled.
6827                          */
6828                         WORKLIST_REMOVE(wk);
6829                         wk->wk_state |= ONDEPLIST;
6830                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6831                         break;
6832
6833                 case D_ALLOCDIRECT:
6834                         adp = WK_ALLOCDIRECT(wk);
6835                         if (off != 0)
6836                                 continue;
6837                         /* FALLTHROUGH */
6838                 default:
6839                         panic("deallocate_dependencies: Unexpected type %s",
6840                             TYPENAME(wk->wk_type));
6841                         /* NOTREACHED */
6842                 }
6843         }
6844         FREE_LOCK(&lk);
6845         /*
6846          * Don't throw away this buf, we were partially truncating and
6847          * some deps may always remain.
6848          */
6849         if (off) {
6850                 allocbuf(bp, off);
6851                 bp->b_vflags |= BV_SCANNED;
6852                 return (EBUSY);
6853         }
6854         bp->b_flags |= B_INVAL | B_NOCACHE;
6855
6856         return (0);
6857 }
6858
6859 /*
6860  * An allocdirect is being canceled due to a truncate.  We must make sure
6861  * the journal entry is released in concert with the blkfree that releases
6862  * the storage.  Completed journal entries must not be released until the
6863  * space is no longer pointed to by the inode or in the bitmap.
6864  */
6865 static void
6866 cancel_allocdirect(adphead, adp, freeblks)
6867         struct allocdirectlst *adphead;
6868         struct allocdirect *adp;
6869         struct freeblks *freeblks;
6870 {
6871         struct freework *freework;
6872         struct newblk *newblk;
6873         struct worklist *wk;
6874
6875         TAILQ_REMOVE(adphead, adp, ad_next);
6876         newblk = (struct newblk *)adp;
6877         freework = NULL;
6878         /*
6879          * Find the correct freework structure.
6880          */
6881         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
6882                 if (wk->wk_type != D_FREEWORK)
6883                         continue;
6884                 freework = WK_FREEWORK(wk);
6885                 if (freework->fw_blkno == newblk->nb_newblkno)
6886                         break;
6887         }
6888         if (freework == NULL)
6889                 panic("cancel_allocdirect: Freework not found");
6890         /*
6891          * If a newblk exists at all we still have the journal entry that
6892          * initiated the allocation so we do not need to journal the free.
6893          */
6894         cancel_jfreeblk(freeblks, freework->fw_blkno);
6895         /*
6896          * If the journal hasn't been written the jnewblk must be passed
6897          * to the call to ffs_blkfree that reclaims the space.  We accomplish
6898          * this by linking the journal dependency into the freework to be
6899          * freed when freework_freeblock() is called.  If the journal has
6900          * been written we can simply reclaim the journal space when the
6901          * freeblks work is complete.
6902          */
6903         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
6904             &freeblks->fb_jwork);
6905         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
6906 }
6907
6908
6909 /*
6910  * Cancel a new block allocation.  May be an indirect or direct block.  We
6911  * remove it from various lists and return any journal record that needs to
6912  * be resolved by the caller.
6913  *
6914  * A special consideration is made for indirects which were never pointed
6915  * at on disk and will never be found once this block is released.
6916  */
6917 static struct jnewblk *
6918 cancel_newblk(newblk, wk, wkhd)
6919         struct newblk *newblk;
6920         struct worklist *wk;
6921         struct workhead *wkhd;
6922 {
6923         struct jnewblk *jnewblk;
6924
6925         newblk->nb_state |= GOINGAWAY;
6926         /*
6927          * Previously we traversed the completedhd on each indirdep
6928          * attached to this newblk to cancel them and gather journal
6929          * work.  Since we need only the oldest journal segment and
6930          * the lowest point on the tree will always have the oldest
6931          * journal segment we are free to release the segments
6932          * of any subordinates and may leave the indirdep list to
6933          * indirdep_complete() when this newblk is freed.
6934          */
6935         if (newblk->nb_state & ONDEPLIST) {
6936                 newblk->nb_state &= ~ONDEPLIST;
6937                 LIST_REMOVE(newblk, nb_deps);
6938         }
6939         if (newblk->nb_state & ONWORKLIST)
6940                 WORKLIST_REMOVE(&newblk->nb_list);
6941         /*
6942          * If the journal entry hasn't been written we save a pointer to
6943          * the dependency that frees it until it is written or the
6944          * superseding operation completes.
6945          */
6946         jnewblk = newblk->nb_jnewblk;
6947         if (jnewblk != NULL && wk != NULL) {
6948                 newblk->nb_jnewblk = NULL;
6949                 jnewblk->jn_dep = wk;
6950         }
6951         if (!LIST_EMPTY(&newblk->nb_jwork))
6952                 jwork_move(wkhd, &newblk->nb_jwork);
6953         /*
6954          * When truncating we must free the newdirblk early to remove
6955          * the pagedep from the hash before returning.
6956          */
6957         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
6958                 free_newdirblk(WK_NEWDIRBLK(wk));
6959         if (!LIST_EMPTY(&newblk->nb_newdirblk))
6960                 panic("cancel_newblk: extra newdirblk");
6961
6962         return (jnewblk);
6963 }
6964
6965 /*
6966  * Schedule the freefrag associated with a newblk to be released once
6967  * the pointers are written and the previous block is no longer needed.
6968  */
6969 static void
6970 newblk_freefrag(newblk)
6971         struct newblk *newblk;
6972 {
6973         struct freefrag *freefrag;
6974
6975         if (newblk->nb_freefrag == NULL)
6976                 return;
6977         freefrag = newblk->nb_freefrag;
6978         newblk->nb_freefrag = NULL;
6979         freefrag->ff_state |= COMPLETE;
6980         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
6981                 add_to_worklist(&freefrag->ff_list, 0);
6982 }
6983
6984 /*
6985  * Free a newblk. Generate a new freefrag work request if appropriate.
6986  * This must be called after the inode pointer and any direct block pointers
6987  * are valid or fully removed via truncate or frag extension.
6988  */
6989 static void
6990 free_newblk(newblk)
6991         struct newblk *newblk;
6992 {
6993         struct indirdep *indirdep;
6994         struct worklist *wk;
6995
6996         KASSERT(newblk->nb_jnewblk == NULL,
6997             ("free_newblk; jnewblk %p still attached", newblk->nb_jnewblk));
6998         mtx_assert(&lk, MA_OWNED);
6999         newblk_freefrag(newblk);
7000         if (newblk->nb_state & ONDEPLIST)
7001                 LIST_REMOVE(newblk, nb_deps);
7002         if (newblk->nb_state & ONWORKLIST)
7003                 WORKLIST_REMOVE(&newblk->nb_list);
7004         LIST_REMOVE(newblk, nb_hash);
7005         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7006                 free_newdirblk(WK_NEWDIRBLK(wk));
7007         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7008                 panic("free_newblk: extra newdirblk");
7009         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7010                 indirdep_complete(indirdep);
7011         handle_jwork(&newblk->nb_jwork);
7012         newblk->nb_list.wk_type = D_NEWBLK;
7013         WORKITEM_FREE(newblk, D_NEWBLK);
7014 }
7015
7016 /*
7017  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7018  * This routine must be called with splbio interrupts blocked.
7019  */
7020 static void
7021 free_newdirblk(newdirblk)
7022         struct newdirblk *newdirblk;
7023 {
7024         struct pagedep *pagedep;
7025         struct diradd *dap;
7026         struct worklist *wk;
7027
7028         mtx_assert(&lk, MA_OWNED);
7029         WORKLIST_REMOVE(&newdirblk->db_list);
7030         /*
7031          * If the pagedep is still linked onto the directory buffer
7032          * dependency chain, then some of the entries on the
7033          * pd_pendinghd list may not be committed to disk yet. In
7034          * this case, we will simply clear the NEWBLOCK flag and
7035          * let the pd_pendinghd list be processed when the pagedep
7036          * is next written. If the pagedep is no longer on the buffer
7037          * dependency chain, then all the entries on the pd_pending
7038          * list are committed to disk and we can free them here.
7039          */
7040         pagedep = newdirblk->db_pagedep;
7041         pagedep->pd_state &= ~NEWBLOCK;
7042         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7043                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7044                         free_diradd(dap, NULL);
7045                 /*
7046                  * If no dependencies remain, the pagedep will be freed.
7047                  */
7048                 free_pagedep(pagedep);
7049         }
7050         /* Should only ever be one item in the list. */
7051         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7052                 WORKLIST_REMOVE(wk);
7053                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7054         }
7055         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7056 }
7057
7058 /*
7059  * Prepare an inode to be freed. The actual free operation is not
7060  * done until the zero'ed inode has been written to disk.
7061  */
7062 void
7063 softdep_freefile(pvp, ino, mode)
7064         struct vnode *pvp;
7065         ino_t ino;
7066         int mode;
7067 {
7068         struct inode *ip = VTOI(pvp);
7069         struct inodedep *inodedep;
7070         struct freefile *freefile;
7071         struct freeblks *freeblks;
7072
7073         /*
7074          * This sets up the inode de-allocation dependency.
7075          */
7076         freefile = malloc(sizeof(struct freefile),
7077                 M_FREEFILE, M_SOFTDEP_FLAGS);
7078         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7079         freefile->fx_mode = mode;
7080         freefile->fx_oldinum = ino;
7081         freefile->fx_devvp = ip->i_devvp;
7082         LIST_INIT(&freefile->fx_jwork);
7083         UFS_LOCK(ip->i_ump);
7084         ip->i_fs->fs_pendinginodes += 1;
7085         UFS_UNLOCK(ip->i_ump);
7086
7087         /*
7088          * If the inodedep does not exist, then the zero'ed inode has
7089          * been written to disk. If the allocated inode has never been
7090          * written to disk, then the on-disk inode is zero'ed. In either
7091          * case we can free the file immediately.  If the journal was
7092          * canceled before being written the inode will never make it to
7093          * disk and we must send the canceled journal entrys to
7094          * ffs_freefile() to be cleared in conjunction with the bitmap.
7095          * Any blocks waiting on the inode to write can be safely freed
7096          * here as it will never been written.
7097          */
7098         ACQUIRE_LOCK(&lk);
7099         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7100         if (inodedep) {
7101                 /*
7102                  * Clear out freeblks that no longer need to reference
7103                  * this inode.
7104                  */
7105                 while ((freeblks =
7106                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7107                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7108                             fb_next);
7109                         freeblks->fb_state &= ~ONDEPLIST;
7110                 }
7111                 /*
7112                  * Remove this inode from the unlinked list.
7113                  */
7114                 if (inodedep->id_state & UNLINKED) {
7115                         /*
7116                          * Save the journal work to be freed with the bitmap
7117                          * before we clear UNLINKED.  Otherwise it can be lost
7118                          * if the inode block is written.
7119                          */
7120                         handle_bufwait(inodedep, &freefile->fx_jwork);
7121                         clear_unlinked_inodedep(inodedep);
7122                         /* Re-acquire inodedep as we've dropped lk. */
7123                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7124                 }
7125         }
7126         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7127                 FREE_LOCK(&lk);
7128                 handle_workitem_freefile(freefile);
7129                 return;
7130         }
7131         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7132                 inodedep->id_state |= GOINGAWAY;
7133         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7134         FREE_LOCK(&lk);
7135         if (ip->i_number == ino)
7136                 ip->i_flag |= IN_MODIFIED;
7137 }
7138
7139 /*
7140  * Check to see if an inode has never been written to disk. If
7141  * so free the inodedep and return success, otherwise return failure.
7142  * This routine must be called with splbio interrupts blocked.
7143  *
7144  * If we still have a bitmap dependency, then the inode has never
7145  * been written to disk. Drop the dependency as it is no longer
7146  * necessary since the inode is being deallocated. We set the
7147  * ALLCOMPLETE flags since the bitmap now properly shows that the
7148  * inode is not allocated. Even if the inode is actively being
7149  * written, it has been rolled back to its zero'ed state, so we
7150  * are ensured that a zero inode is what is on the disk. For short
7151  * lived files, this change will usually result in removing all the
7152  * dependencies from the inode so that it can be freed immediately.
7153  */
7154 static int
7155 check_inode_unwritten(inodedep)
7156         struct inodedep *inodedep;
7157 {
7158
7159         mtx_assert(&lk, MA_OWNED);
7160
7161         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7162             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7163             !LIST_EMPTY(&inodedep->id_bufwait) ||
7164             !LIST_EMPTY(&inodedep->id_inowait) ||
7165             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7166             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7167             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7168             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7169             inodedep->id_mkdiradd != NULL || 
7170             inodedep->id_nlinkdelta != 0)
7171                 return (0);
7172         /*
7173          * Another process might be in initiate_write_inodeblock_ufs[12]
7174          * trying to allocate memory without holding "Softdep Lock".
7175          */
7176         if ((inodedep->id_state & IOSTARTED) != 0 &&
7177             inodedep->id_savedino1 == NULL)
7178                 return (0);
7179
7180         if (inodedep->id_state & ONDEPLIST)
7181                 LIST_REMOVE(inodedep, id_deps);
7182         inodedep->id_state &= ~ONDEPLIST;
7183         inodedep->id_state |= ALLCOMPLETE;
7184         inodedep->id_bmsafemap = NULL;
7185         if (inodedep->id_state & ONWORKLIST)
7186                 WORKLIST_REMOVE(&inodedep->id_list);
7187         if (inodedep->id_savedino1 != NULL) {
7188                 free(inodedep->id_savedino1, M_SAVEDINO);
7189                 inodedep->id_savedino1 = NULL;
7190         }
7191         if (free_inodedep(inodedep) == 0)
7192                 panic("check_inode_unwritten: busy inode");
7193         return (1);
7194 }
7195
7196 /*
7197  * Try to free an inodedep structure. Return 1 if it could be freed.
7198  */
7199 static int
7200 free_inodedep(inodedep)
7201         struct inodedep *inodedep;
7202 {
7203
7204         mtx_assert(&lk, MA_OWNED);
7205         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7206             (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7207             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7208             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7209             !LIST_EMPTY(&inodedep->id_bufwait) ||
7210             !LIST_EMPTY(&inodedep->id_inowait) ||
7211             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7212             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7213             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7214             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7215             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7216             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7217             inodedep->id_mkdiradd != NULL ||
7218             inodedep->id_nlinkdelta != 0 ||
7219             inodedep->id_savedino1 != NULL)
7220                 return (0);
7221         if (inodedep->id_state & ONDEPLIST)
7222                 LIST_REMOVE(inodedep, id_deps);
7223         LIST_REMOVE(inodedep, id_hash);
7224         WORKITEM_FREE(inodedep, D_INODEDEP);
7225         return (1);
7226 }
7227
7228 /*
7229  * Free the block referenced by a freework structure.  The parent freeblks
7230  * structure is released and completed when the final cg bitmap reaches
7231  * the disk.  This routine may be freeing a jnewblk which never made it to
7232  * disk in which case we do not have to wait as the operation is undone
7233  * in memory immediately.
7234  */
7235 static void
7236 freework_freeblock(freework)
7237         struct freework *freework;
7238 {
7239         struct freeblks *freeblks;
7240         struct jnewblk *jnewblk;
7241         struct ufsmount *ump;
7242         struct workhead wkhd;
7243         struct fs *fs;
7244         int bsize;
7245         int needj;
7246
7247         mtx_assert(&lk, MA_OWNED);
7248         /*
7249          * Handle partial truncate separately.
7250          */
7251         if (freework->fw_indir) {
7252                 complete_trunc_indir(freework);
7253                 return;
7254         }
7255         freeblks = freework->fw_freeblks;
7256         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7257         fs = ump->um_fs;
7258         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7259         bsize = lfragtosize(fs, freework->fw_frags);
7260         LIST_INIT(&wkhd);
7261         /*
7262          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7263          * on the indirblk hashtable and prevents premature freeing.
7264          */
7265         freework->fw_state |= DEPCOMPLETE;
7266         /*
7267          * SUJ needs to wait for the segment referencing freed indirect
7268          * blocks to expire so that we know the checker will not confuse
7269          * a re-allocated indirect block with its old contents.
7270          */
7271         if (needj && freework->fw_lbn <= -NDADDR)
7272                 indirblk_insert(freework);
7273         /*
7274          * If we are canceling an existing jnewblk pass it to the free
7275          * routine, otherwise pass the freeblk which will ultimately
7276          * release the freeblks.  If we're not journaling, we can just
7277          * free the freeblks immediately.
7278          */
7279         jnewblk = freework->fw_jnewblk;
7280         if (jnewblk != NULL) {
7281                 cancel_jnewblk(jnewblk, &wkhd);
7282                 needj = 0;
7283         } else if (needj) {
7284                 freework->fw_state |= DELAYEDFREE;
7285                 freeblks->fb_cgwait++;
7286                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7287         }
7288         FREE_LOCK(&lk);
7289         freeblks_free(ump, freeblks, btodb(bsize));
7290         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7291             freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7292         ACQUIRE_LOCK(&lk);
7293         /*
7294          * The jnewblk will be discarded and the bits in the map never
7295          * made it to disk.  We can immediately free the freeblk.
7296          */
7297         if (needj == 0)
7298                 handle_written_freework(freework);
7299 }
7300
7301 /*
7302  * We enqueue freework items that need processing back on the freeblks and
7303  * add the freeblks to the worklist.  This makes it easier to find all work
7304  * required to flush a truncation in process_truncates().
7305  */
7306 static void
7307 freework_enqueue(freework)
7308         struct freework *freework;
7309 {
7310         struct freeblks *freeblks;
7311
7312         freeblks = freework->fw_freeblks;
7313         if ((freework->fw_state & INPROGRESS) == 0)
7314                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7315         if ((freeblks->fb_state &
7316             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7317             LIST_EMPTY(&freeblks->fb_jblkdephd))
7318                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7319 }
7320
7321 /*
7322  * Start, continue, or finish the process of freeing an indirect block tree.
7323  * The free operation may be paused at any point with fw_off containing the
7324  * offset to restart from.  This enables us to implement some flow control
7325  * for large truncates which may fan out and generate a huge number of
7326  * dependencies.
7327  */
7328 static void
7329 handle_workitem_indirblk(freework)
7330         struct freework *freework;
7331 {
7332         struct freeblks *freeblks;
7333         struct ufsmount *ump;
7334         struct fs *fs;
7335
7336         freeblks = freework->fw_freeblks;
7337         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7338         fs = ump->um_fs;
7339         if (freework->fw_state & DEPCOMPLETE) {
7340                 handle_written_freework(freework);
7341                 return;
7342         }
7343         if (freework->fw_off == NINDIR(fs)) {
7344                 freework_freeblock(freework);
7345                 return;
7346         }
7347         freework->fw_state |= INPROGRESS;
7348         FREE_LOCK(&lk);
7349         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7350             freework->fw_lbn);
7351         ACQUIRE_LOCK(&lk);
7352 }
7353
7354 /*
7355  * Called when a freework structure attached to a cg buf is written.  The
7356  * ref on either the parent or the freeblks structure is released and
7357  * the freeblks is added back to the worklist if there is more work to do.
7358  */
7359 static void
7360 handle_written_freework(freework)
7361         struct freework *freework;
7362 {
7363         struct freeblks *freeblks;
7364         struct freework *parent;
7365
7366         freeblks = freework->fw_freeblks;
7367         parent = freework->fw_parent;
7368         if (freework->fw_state & DELAYEDFREE)
7369                 freeblks->fb_cgwait--;
7370         freework->fw_state |= COMPLETE;
7371         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7372                 WORKITEM_FREE(freework, D_FREEWORK);
7373         if (parent) {
7374                 if (--parent->fw_ref == 0)
7375                         freework_enqueue(parent);
7376                 return;
7377         }
7378         if (--freeblks->fb_ref != 0)
7379                 return;
7380         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7381             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7382                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7383 }
7384
7385 /*
7386  * This workitem routine performs the block de-allocation.
7387  * The workitem is added to the pending list after the updated
7388  * inode block has been written to disk.  As mentioned above,
7389  * checks regarding the number of blocks de-allocated (compared
7390  * to the number of blocks allocated for the file) are also
7391  * performed in this function.
7392  */
7393 static int
7394 handle_workitem_freeblocks(freeblks, flags)
7395         struct freeblks *freeblks;
7396         int flags;
7397 {
7398         struct freework *freework;
7399         struct newblk *newblk;
7400         struct allocindir *aip;
7401         struct ufsmount *ump;
7402         struct worklist *wk;
7403
7404         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7405             ("handle_workitem_freeblocks: Journal entries not written."));
7406         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7407         ACQUIRE_LOCK(&lk);
7408         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7409                 WORKLIST_REMOVE(wk);
7410                 switch (wk->wk_type) {
7411                 case D_DIRREM:
7412                         wk->wk_state |= COMPLETE;
7413                         add_to_worklist(wk, 0);
7414                         continue;
7415
7416                 case D_ALLOCDIRECT:
7417                         free_newblk(WK_NEWBLK(wk));
7418                         continue;
7419
7420                 case D_ALLOCINDIR:
7421                         aip = WK_ALLOCINDIR(wk);
7422                         freework = NULL;
7423                         if (aip->ai_state & DELAYEDFREE) {
7424                                 FREE_LOCK(&lk);
7425                                 freework = newfreework(ump, freeblks, NULL,
7426                                     aip->ai_lbn, aip->ai_newblkno,
7427                                     ump->um_fs->fs_frag, 0, 0);
7428                                 ACQUIRE_LOCK(&lk);
7429                         }
7430                         newblk = WK_NEWBLK(wk);
7431                         if (newblk->nb_jnewblk) {
7432                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7433                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7434                                 newblk->nb_jnewblk = NULL;
7435                         }
7436                         free_newblk(newblk);
7437                         continue;
7438
7439                 case D_FREEWORK:
7440                         freework = WK_FREEWORK(wk);
7441                         if (freework->fw_lbn <= -NDADDR)
7442                                 handle_workitem_indirblk(freework);
7443                         else
7444                                 freework_freeblock(freework);
7445                         continue;
7446                 default:
7447                         panic("handle_workitem_freeblocks: Unknown type %s",
7448                             TYPENAME(wk->wk_type));
7449                 }
7450         }
7451         if (freeblks->fb_ref != 0) {
7452                 freeblks->fb_state &= ~INPROGRESS;
7453                 wake_worklist(&freeblks->fb_list);
7454                 freeblks = NULL;
7455         }
7456         FREE_LOCK(&lk);
7457         if (freeblks)
7458                 return handle_complete_freeblocks(freeblks, flags);
7459         return (0);
7460 }
7461
7462 /*
7463  * Handle completion of block free via truncate.  This allows fs_pending
7464  * to track the actual free block count more closely than if we only updated
7465  * it at the end.  We must be careful to handle cases where the block count
7466  * on free was incorrect.
7467  */
7468 static void
7469 freeblks_free(ump, freeblks, blocks)
7470         struct ufsmount *ump;
7471         struct freeblks *freeblks;
7472         int blocks;
7473 {
7474         struct fs *fs;
7475         ufs2_daddr_t remain;
7476
7477         UFS_LOCK(ump);
7478         remain = -freeblks->fb_chkcnt;
7479         freeblks->fb_chkcnt += blocks;
7480         if (remain > 0) {
7481                 if (remain < blocks)
7482                         blocks = remain;
7483                 fs = ump->um_fs;
7484                 fs->fs_pendingblocks -= blocks;
7485         }
7486         UFS_UNLOCK(ump);
7487 }
7488
7489 /*
7490  * Once all of the freework workitems are complete we can retire the
7491  * freeblocks dependency and any journal work awaiting completion.  This
7492  * can not be called until all other dependencies are stable on disk.
7493  */
7494 static int
7495 handle_complete_freeblocks(freeblks, flags)
7496         struct freeblks *freeblks;
7497         int flags;
7498 {
7499         struct inodedep *inodedep;
7500         struct inode *ip;
7501         struct vnode *vp;
7502         struct fs *fs;
7503         struct ufsmount *ump;
7504         ufs2_daddr_t spare;
7505
7506         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7507         fs = ump->um_fs;
7508         flags = LK_EXCLUSIVE | flags;
7509         spare = freeblks->fb_chkcnt;
7510
7511         /*
7512          * If we did not release the expected number of blocks we may have
7513          * to adjust the inode block count here.  Only do so if it wasn't
7514          * a truncation to zero and the modrev still matches.
7515          */
7516         if (spare && freeblks->fb_len != 0) {
7517                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7518                     flags, &vp, FFSV_FORCEINSMQ) != 0)
7519                         return (EBUSY);
7520                 ip = VTOI(vp);
7521                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7522                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7523                         ip->i_flag |= IN_CHANGE;
7524                         /*
7525                          * We must wait so this happens before the
7526                          * journal is reclaimed.
7527                          */
7528                         ffs_update(vp, 1);
7529                 }
7530                 vput(vp);
7531         }
7532         if (spare < 0) {
7533                 UFS_LOCK(ump);
7534                 fs->fs_pendingblocks += spare;
7535                 UFS_UNLOCK(ump);
7536         }
7537 #ifdef QUOTA
7538         /* Handle spare. */
7539         if (spare)
7540                 quotaadj(freeblks->fb_quota, ump, -spare);
7541         quotarele(freeblks->fb_quota);
7542 #endif
7543         ACQUIRE_LOCK(&lk);
7544         if (freeblks->fb_state & ONDEPLIST) {
7545                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7546                     0, &inodedep);
7547                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
7548                 freeblks->fb_state &= ~ONDEPLIST;
7549                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
7550                         free_inodedep(inodedep);
7551         }
7552         /*
7553          * All of the freeblock deps must be complete prior to this call
7554          * so it's now safe to complete earlier outstanding journal entries.
7555          */
7556         handle_jwork(&freeblks->fb_jwork);
7557         WORKITEM_FREE(freeblks, D_FREEBLKS);
7558         FREE_LOCK(&lk);
7559         return (0);
7560 }
7561
7562 /*
7563  * Release blocks associated with the freeblks and stored in the indirect
7564  * block dbn. If level is greater than SINGLE, the block is an indirect block
7565  * and recursive calls to indirtrunc must be used to cleanse other indirect
7566  * blocks.
7567  *
7568  * This handles partial and complete truncation of blocks.  Partial is noted
7569  * with goingaway == 0.  In this case the freework is completed after the
7570  * zero'd indirects are written to disk.  For full truncation the freework
7571  * is completed after the block is freed.
7572  */
7573 static void
7574 indir_trunc(freework, dbn, lbn)
7575         struct freework *freework;
7576         ufs2_daddr_t dbn;
7577         ufs_lbn_t lbn;
7578 {
7579         struct freework *nfreework;
7580         struct workhead wkhd;
7581         struct freeblks *freeblks;
7582         struct buf *bp;
7583         struct fs *fs;
7584         struct indirdep *indirdep;
7585         struct ufsmount *ump;
7586         ufs1_daddr_t *bap1 = 0;
7587         ufs2_daddr_t nb, nnb, *bap2 = 0;
7588         ufs_lbn_t lbnadd, nlbn;
7589         int i, nblocks, ufs1fmt;
7590         int freedblocks;
7591         int goingaway;
7592         int freedeps;
7593         int needj;
7594         int level;
7595         int cnt;
7596
7597         freeblks = freework->fw_freeblks;
7598         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7599         fs = ump->um_fs;
7600         /*
7601          * Get buffer of block pointers to be freed.  There are three cases:
7602          * 
7603          * 1) Partial truncate caches the indirdep pointer in the freework
7604          *    which provides us a back copy to the save bp which holds the
7605          *    pointers we want to clear.  When this completes the zero
7606          *    pointers are written to the real copy.
7607          * 2) The indirect is being completely truncated, cancel_indirdep()
7608          *    eliminated the real copy and placed the indirdep on the saved
7609          *    copy.  The indirdep and buf are discarded when this completes.
7610          * 3) The indirect was not in memory, we read a copy off of the disk
7611          *    using the devvp and drop and invalidate the buffer when we're
7612          *    done.
7613          */
7614         goingaway = 1;
7615         indirdep = NULL;
7616         if (freework->fw_indir != NULL) {
7617                 goingaway = 0;
7618                 indirdep = freework->fw_indir;
7619                 bp = indirdep->ir_savebp;
7620                 if (bp == NULL || bp->b_blkno != dbn)
7621                         panic("indir_trunc: Bad saved buf %p blkno %jd",
7622                             bp, (intmax_t)dbn);
7623         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
7624                 /*
7625                  * The lock prevents the buf dep list from changing and
7626                  * indirects on devvp should only ever have one dependency.
7627                  */
7628                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
7629                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
7630                         panic("indir_trunc: Bad indirdep %p from buf %p",
7631                             indirdep, bp);
7632         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
7633             NOCRED, &bp) != 0) {
7634                 brelse(bp);
7635                 return;
7636         }
7637         ACQUIRE_LOCK(&lk);
7638         /* Protects against a race with complete_trunc_indir(). */
7639         freework->fw_state &= ~INPROGRESS;
7640         /*
7641          * If we have an indirdep we need to enforce the truncation order
7642          * and discard it when it is complete.
7643          */
7644         if (indirdep) {
7645                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
7646                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
7647                         /*
7648                          * Add the complete truncate to the list on the
7649                          * indirdep to enforce in-order processing.
7650                          */
7651                         if (freework->fw_indir == NULL)
7652                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
7653                                     freework, fw_next);
7654                         FREE_LOCK(&lk);
7655                         return;
7656                 }
7657                 /*
7658                  * If we're goingaway, free the indirdep.  Otherwise it will
7659                  * linger until the write completes.
7660                  */
7661                 if (goingaway) {
7662                         free_indirdep(indirdep);
7663                         ump->um_numindirdeps -= 1;
7664                 }
7665         }
7666         FREE_LOCK(&lk);
7667         /* Initialize pointers depending on block size. */
7668         if (ump->um_fstype == UFS1) {
7669                 bap1 = (ufs1_daddr_t *)bp->b_data;
7670                 nb = bap1[freework->fw_off];
7671                 ufs1fmt = 1;
7672         } else {
7673                 bap2 = (ufs2_daddr_t *)bp->b_data;
7674                 nb = bap2[freework->fw_off];
7675                 ufs1fmt = 0;
7676         }
7677         level = lbn_level(lbn);
7678         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
7679         lbnadd = lbn_offset(fs, level);
7680         nblocks = btodb(fs->fs_bsize);
7681         nfreework = freework;
7682         freedeps = 0;
7683         cnt = 0;
7684         /*
7685          * Reclaim blocks.  Traverses into nested indirect levels and
7686          * arranges for the current level to be freed when subordinates
7687          * are free when journaling.
7688          */
7689         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
7690                 if (i != NINDIR(fs) - 1) {
7691                         if (ufs1fmt)
7692                                 nnb = bap1[i+1];
7693                         else
7694                                 nnb = bap2[i+1];
7695                 } else
7696                         nnb = 0;
7697                 if (nb == 0)
7698                         continue;
7699                 cnt++;
7700                 if (level != 0) {
7701                         nlbn = (lbn + 1) - (i * lbnadd);
7702                         if (needj != 0) {
7703                                 nfreework = newfreework(ump, freeblks, freework,
7704                                     nlbn, nb, fs->fs_frag, 0, 0);
7705                                 freedeps++;
7706                         }
7707                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
7708                 } else {
7709                         struct freedep *freedep;
7710
7711                         /*
7712                          * Attempt to aggregate freedep dependencies for
7713                          * all blocks being released to the same CG.
7714                          */
7715                         LIST_INIT(&wkhd);
7716                         if (needj != 0 &&
7717                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
7718                                 freedep = newfreedep(freework);
7719                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
7720                                     &freedep->fd_list);
7721                                 freedeps++;
7722                         }
7723                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
7724                             fs->fs_bsize, freeblks->fb_inum,
7725                             freeblks->fb_vtype, &wkhd);
7726                 }
7727         }
7728         if (goingaway) {
7729                 bp->b_flags |= B_INVAL | B_NOCACHE;
7730                 brelse(bp);
7731         }
7732         freedblocks = 0;
7733         if (level == 0)
7734                 freedblocks = (nblocks * cnt);
7735         if (needj == 0)
7736                 freedblocks += nblocks;
7737         freeblks_free(ump, freeblks, freedblocks);
7738         /*
7739          * If we are journaling set up the ref counts and offset so this
7740          * indirect can be completed when its children are free.
7741          */
7742         if (needj) {
7743                 ACQUIRE_LOCK(&lk);
7744                 freework->fw_off = i;
7745                 freework->fw_ref += freedeps;
7746                 freework->fw_ref -= NINDIR(fs) + 1;
7747                 if (level == 0)
7748                         freeblks->fb_cgwait += freedeps;
7749                 if (freework->fw_ref == 0)
7750                         freework_freeblock(freework);
7751                 FREE_LOCK(&lk);
7752                 return;
7753         }
7754         /*
7755          * If we're not journaling we can free the indirect now.
7756          */
7757         dbn = dbtofsb(fs, dbn);
7758         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
7759             freeblks->fb_inum, freeblks->fb_vtype, NULL);
7760         /* Non SUJ softdep does single-threaded truncations. */
7761         if (freework->fw_blkno == dbn) {
7762                 freework->fw_state |= ALLCOMPLETE;
7763                 ACQUIRE_LOCK(&lk);
7764                 handle_written_freework(freework);
7765                 FREE_LOCK(&lk);
7766         }
7767         return;
7768 }
7769
7770 /*
7771  * Cancel an allocindir when it is removed via truncation.  When bp is not
7772  * NULL the indirect never appeared on disk and is scheduled to be freed
7773  * independently of the indir so we can more easily track journal work.
7774  */
7775 static void
7776 cancel_allocindir(aip, bp, freeblks, trunc)
7777         struct allocindir *aip;
7778         struct buf *bp;
7779         struct freeblks *freeblks;
7780         int trunc;
7781 {
7782         struct indirdep *indirdep;
7783         struct freefrag *freefrag;
7784         struct newblk *newblk;
7785
7786         newblk = (struct newblk *)aip;
7787         LIST_REMOVE(aip, ai_next);
7788         /*
7789          * We must eliminate the pointer in bp if it must be freed on its
7790          * own due to partial truncate or pending journal work.
7791          */
7792         if (bp && (trunc || newblk->nb_jnewblk)) {
7793                 /*
7794                  * Clear the pointer and mark the aip to be freed
7795                  * directly if it never existed on disk.
7796                  */
7797                 aip->ai_state |= DELAYEDFREE;
7798                 indirdep = aip->ai_indirdep;
7799                 if (indirdep->ir_state & UFS1FMT)
7800                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
7801                 else
7802                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
7803         }
7804         /*
7805          * When truncating the previous pointer will be freed via
7806          * savedbp.  Eliminate the freefrag which would dup free.
7807          */
7808         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
7809                 newblk->nb_freefrag = NULL;
7810                 if (freefrag->ff_jdep)
7811                         cancel_jfreefrag(
7812                             WK_JFREEFRAG(freefrag->ff_jdep));
7813                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
7814                 WORKITEM_FREE(freefrag, D_FREEFRAG);
7815         }
7816         /*
7817          * If the journal hasn't been written the jnewblk must be passed
7818          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7819          * this by leaving the journal dependency on the newblk to be freed
7820          * when a freework is created in handle_workitem_freeblocks().
7821          */
7822         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
7823         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7824 }
7825
7826 /*
7827  * Create the mkdir dependencies for . and .. in a new directory.  Link them
7828  * in to a newdirblk so any subsequent additions are tracked properly.  The
7829  * caller is responsible for adding the mkdir1 dependency to the journal
7830  * and updating id_mkdiradd.  This function returns with lk held.
7831  */
7832 static struct mkdir *
7833 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
7834         struct diradd *dap;
7835         ino_t newinum;
7836         ino_t dinum;
7837         struct buf *newdirbp;
7838         struct mkdir **mkdirp;
7839 {
7840         struct newblk *newblk;
7841         struct pagedep *pagedep;
7842         struct inodedep *inodedep;
7843         struct newdirblk *newdirblk = 0;
7844         struct mkdir *mkdir1, *mkdir2;
7845         struct worklist *wk;
7846         struct jaddref *jaddref;
7847         struct mount *mp;
7848
7849         mp = dap->da_list.wk_mp;
7850         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
7851             M_SOFTDEP_FLAGS);
7852         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
7853         LIST_INIT(&newdirblk->db_mkdir);
7854         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
7855         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
7856         mkdir1->md_state = ATTACHED | MKDIR_BODY;
7857         mkdir1->md_diradd = dap;
7858         mkdir1->md_jaddref = NULL;
7859         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
7860         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
7861         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
7862         mkdir2->md_diradd = dap;
7863         mkdir2->md_jaddref = NULL;
7864         if (MOUNTEDSUJ(mp) == 0) {
7865                 mkdir1->md_state |= DEPCOMPLETE;
7866                 mkdir2->md_state |= DEPCOMPLETE;
7867         }
7868         /*
7869          * Dependency on "." and ".." being written to disk.
7870          */
7871         mkdir1->md_buf = newdirbp;
7872         ACQUIRE_LOCK(&lk);
7873         LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
7874         /*
7875          * We must link the pagedep, allocdirect, and newdirblk for
7876          * the initial file page so the pointer to the new directory
7877          * is not written until the directory contents are live and
7878          * any subsequent additions are not marked live until the
7879          * block is reachable via the inode.
7880          */
7881         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
7882                 panic("setup_newdir: lost pagedep");
7883         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
7884                 if (wk->wk_type == D_ALLOCDIRECT)
7885                         break;
7886         if (wk == NULL)
7887                 panic("setup_newdir: lost allocdirect");
7888         if (pagedep->pd_state & NEWBLOCK)
7889                 panic("setup_newdir: NEWBLOCK already set");
7890         newblk = WK_NEWBLK(wk);
7891         pagedep->pd_state |= NEWBLOCK;
7892         pagedep->pd_newdirblk = newdirblk;
7893         newdirblk->db_pagedep = pagedep;
7894         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
7895         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
7896         /*
7897          * Look up the inodedep for the parent directory so that we
7898          * can link mkdir2 into the pending dotdot jaddref or
7899          * the inode write if there is none.  If the inode is
7900          * ALLCOMPLETE and no jaddref is present all dependencies have
7901          * been satisfied and mkdir2 can be freed.
7902          */
7903         inodedep_lookup(mp, dinum, 0, &inodedep);
7904         if (MOUNTEDSUJ(mp)) {
7905                 if (inodedep == NULL)
7906                         panic("setup_newdir: Lost parent.");
7907                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
7908                     inoreflst);
7909                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
7910                     (jaddref->ja_state & MKDIR_PARENT),
7911                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
7912                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
7913                 mkdir2->md_jaddref = jaddref;
7914                 jaddref->ja_mkdir = mkdir2;
7915         } else if (inodedep == NULL ||
7916             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
7917                 dap->da_state &= ~MKDIR_PARENT;
7918                 WORKITEM_FREE(mkdir2, D_MKDIR);
7919         } else {
7920                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
7921                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
7922         }
7923         *mkdirp = mkdir2;
7924
7925         return (mkdir1);
7926 }
7927
7928 /*
7929  * Directory entry addition dependencies.
7930  * 
7931  * When adding a new directory entry, the inode (with its incremented link
7932  * count) must be written to disk before the directory entry's pointer to it.
7933  * Also, if the inode is newly allocated, the corresponding freemap must be
7934  * updated (on disk) before the directory entry's pointer. These requirements
7935  * are met via undo/redo on the directory entry's pointer, which consists
7936  * simply of the inode number.
7937  * 
7938  * As directory entries are added and deleted, the free space within a
7939  * directory block can become fragmented.  The ufs filesystem will compact
7940  * a fragmented directory block to make space for a new entry. When this
7941  * occurs, the offsets of previously added entries change. Any "diradd"
7942  * dependency structures corresponding to these entries must be updated with
7943  * the new offsets.
7944  */
7945
7946 /*
7947  * This routine is called after the in-memory inode's link
7948  * count has been incremented, but before the directory entry's
7949  * pointer to the inode has been set.
7950  */
7951 int
7952 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
7953         struct buf *bp;         /* buffer containing directory block */
7954         struct inode *dp;       /* inode for directory */
7955         off_t diroffset;        /* offset of new entry in directory */
7956         ino_t newinum;          /* inode referenced by new directory entry */
7957         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
7958         int isnewblk;           /* entry is in a newly allocated block */
7959 {
7960         int offset;             /* offset of new entry within directory block */
7961         ufs_lbn_t lbn;          /* block in directory containing new entry */
7962         struct fs *fs;
7963         struct diradd *dap;
7964         struct newblk *newblk;
7965         struct pagedep *pagedep;
7966         struct inodedep *inodedep;
7967         struct newdirblk *newdirblk = 0;
7968         struct mkdir *mkdir1, *mkdir2;
7969         struct jaddref *jaddref;
7970         struct mount *mp;
7971         int isindir;
7972
7973         /*
7974          * Whiteouts have no dependencies.
7975          */
7976         if (newinum == WINO) {
7977                 if (newdirbp != NULL)
7978                         bdwrite(newdirbp);
7979                 return (0);
7980         }
7981         jaddref = NULL;
7982         mkdir1 = mkdir2 = NULL;
7983         mp = UFSTOVFS(dp->i_ump);
7984         fs = dp->i_fs;
7985         lbn = lblkno(fs, diroffset);
7986         offset = blkoff(fs, diroffset);
7987         dap = malloc(sizeof(struct diradd), M_DIRADD,
7988                 M_SOFTDEP_FLAGS|M_ZERO);
7989         workitem_alloc(&dap->da_list, D_DIRADD, mp);
7990         dap->da_offset = offset;
7991         dap->da_newinum = newinum;
7992         dap->da_state = ATTACHED;
7993         LIST_INIT(&dap->da_jwork);
7994         isindir = bp->b_lblkno >= NDADDR;
7995         if (isnewblk &&
7996             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
7997                 newdirblk = malloc(sizeof(struct newdirblk),
7998                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
7999                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8000                 LIST_INIT(&newdirblk->db_mkdir);
8001         }
8002         /*
8003          * If we're creating a new directory setup the dependencies and set
8004          * the dap state to wait for them.  Otherwise it's COMPLETE and
8005          * we can move on.
8006          */
8007         if (newdirbp == NULL) {
8008                 dap->da_state |= DEPCOMPLETE;
8009                 ACQUIRE_LOCK(&lk);
8010         } else {
8011                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8012                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8013                     &mkdir2);
8014         }
8015         /*
8016          * Link into parent directory pagedep to await its being written.
8017          */
8018         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8019 #ifdef DEBUG
8020         if (diradd_lookup(pagedep, offset) != NULL)
8021                 panic("softdep_setup_directory_add: %p already at off %d\n",
8022                     diradd_lookup(pagedep, offset), offset);
8023 #endif
8024         dap->da_pagedep = pagedep;
8025         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8026             da_pdlist);
8027         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8028         /*
8029          * If we're journaling, link the diradd into the jaddref so it
8030          * may be completed after the journal entry is written.  Otherwise,
8031          * link the diradd into its inodedep.  If the inode is not yet
8032          * written place it on the bufwait list, otherwise do the post-inode
8033          * write processing to put it on the id_pendinghd list.
8034          */
8035         if (MOUNTEDSUJ(mp)) {
8036                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8037                     inoreflst);
8038                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8039                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8040                 jaddref->ja_diroff = diroffset;
8041                 jaddref->ja_diradd = dap;
8042                 add_to_journal(&jaddref->ja_list);
8043         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8044                 diradd_inode_written(dap, inodedep);
8045         else
8046                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8047         /*
8048          * Add the journal entries for . and .. links now that the primary
8049          * link is written.
8050          */
8051         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8052                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8053                     inoreflst, if_deps);
8054                 KASSERT(jaddref != NULL &&
8055                     jaddref->ja_ino == jaddref->ja_parent &&
8056                     (jaddref->ja_state & MKDIR_BODY),
8057                     ("softdep_setup_directory_add: bad dot jaddref %p",
8058                     jaddref));
8059                 mkdir1->md_jaddref = jaddref;
8060                 jaddref->ja_mkdir = mkdir1;
8061                 /*
8062                  * It is important that the dotdot journal entry
8063                  * is added prior to the dot entry since dot writes
8064                  * both the dot and dotdot links.  These both must
8065                  * be added after the primary link for the journal
8066                  * to remain consistent.
8067                  */
8068                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8069                 add_to_journal(&jaddref->ja_list);
8070         }
8071         /*
8072          * If we are adding a new directory remember this diradd so that if
8073          * we rename it we can keep the dot and dotdot dependencies.  If
8074          * we are adding a new name for an inode that has a mkdiradd we
8075          * must be in rename and we have to move the dot and dotdot
8076          * dependencies to this new name.  The old name is being orphaned
8077          * soon.
8078          */
8079         if (mkdir1 != NULL) {
8080                 if (inodedep->id_mkdiradd != NULL)
8081                         panic("softdep_setup_directory_add: Existing mkdir");
8082                 inodedep->id_mkdiradd = dap;
8083         } else if (inodedep->id_mkdiradd)
8084                 merge_diradd(inodedep, dap);
8085         if (newdirblk) {
8086                 /*
8087                  * There is nothing to do if we are already tracking
8088                  * this block.
8089                  */
8090                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8091                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8092                         FREE_LOCK(&lk);
8093                         return (0);
8094                 }
8095                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8096                     == 0)
8097                         panic("softdep_setup_directory_add: lost entry");
8098                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8099                 pagedep->pd_state |= NEWBLOCK;
8100                 pagedep->pd_newdirblk = newdirblk;
8101                 newdirblk->db_pagedep = pagedep;
8102                 FREE_LOCK(&lk);
8103                 /*
8104                  * If we extended into an indirect signal direnter to sync.
8105                  */
8106                 if (isindir)
8107                         return (1);
8108                 return (0);
8109         }
8110         FREE_LOCK(&lk);
8111         return (0);
8112 }
8113
8114 /*
8115  * This procedure is called to change the offset of a directory
8116  * entry when compacting a directory block which must be owned
8117  * exclusively by the caller. Note that the actual entry movement
8118  * must be done in this procedure to ensure that no I/O completions
8119  * occur while the move is in progress.
8120  */
8121 void 
8122 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8123         struct buf *bp;         /* Buffer holding directory block. */
8124         struct inode *dp;       /* inode for directory */
8125         caddr_t base;           /* address of dp->i_offset */
8126         caddr_t oldloc;         /* address of old directory location */
8127         caddr_t newloc;         /* address of new directory location */
8128         int entrysize;          /* size of directory entry */
8129 {
8130         int offset, oldoffset, newoffset;
8131         struct pagedep *pagedep;
8132         struct jmvref *jmvref;
8133         struct diradd *dap;
8134         struct direct *de;
8135         struct mount *mp;
8136         ufs_lbn_t lbn;
8137         int flags;
8138
8139         mp = UFSTOVFS(dp->i_ump);
8140         de = (struct direct *)oldloc;
8141         jmvref = NULL;
8142         flags = 0;
8143         /*
8144          * Moves are always journaled as it would be too complex to
8145          * determine if any affected adds or removes are present in the
8146          * journal.
8147          */
8148         if (MOUNTEDSUJ(mp)) {
8149                 flags = DEPALLOC;
8150                 jmvref = newjmvref(dp, de->d_ino,
8151                     dp->i_offset + (oldloc - base),
8152                     dp->i_offset + (newloc - base));
8153         }
8154         lbn = lblkno(dp->i_fs, dp->i_offset);
8155         offset = blkoff(dp->i_fs, dp->i_offset);
8156         oldoffset = offset + (oldloc - base);
8157         newoffset = offset + (newloc - base);
8158         ACQUIRE_LOCK(&lk);
8159         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8160                 goto done;
8161         dap = diradd_lookup(pagedep, oldoffset);
8162         if (dap) {
8163                 dap->da_offset = newoffset;
8164                 newoffset = DIRADDHASH(newoffset);
8165                 oldoffset = DIRADDHASH(oldoffset);
8166                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8167                     newoffset != oldoffset) {
8168                         LIST_REMOVE(dap, da_pdlist);
8169                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8170                             dap, da_pdlist);
8171                 }
8172         }
8173 done:
8174         if (jmvref) {
8175                 jmvref->jm_pagedep = pagedep;
8176                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8177                 add_to_journal(&jmvref->jm_list);
8178         }
8179         bcopy(oldloc, newloc, entrysize);
8180         FREE_LOCK(&lk);
8181 }
8182
8183 /*
8184  * Move the mkdir dependencies and journal work from one diradd to another
8185  * when renaming a directory.  The new name must depend on the mkdir deps
8186  * completing as the old name did.  Directories can only have one valid link
8187  * at a time so one must be canonical.
8188  */
8189 static void
8190 merge_diradd(inodedep, newdap)
8191         struct inodedep *inodedep;
8192         struct diradd *newdap;
8193 {
8194         struct diradd *olddap;
8195         struct mkdir *mkdir, *nextmd;
8196         short state;
8197
8198         olddap = inodedep->id_mkdiradd;
8199         inodedep->id_mkdiradd = newdap;
8200         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8201                 newdap->da_state &= ~DEPCOMPLETE;
8202                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8203                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8204                         if (mkdir->md_diradd != olddap)
8205                                 continue;
8206                         mkdir->md_diradd = newdap;
8207                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8208                         newdap->da_state |= state;
8209                         olddap->da_state &= ~state;
8210                         if ((olddap->da_state &
8211                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8212                                 break;
8213                 }
8214                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8215                         panic("merge_diradd: unfound ref");
8216         }
8217         /*
8218          * Any mkdir related journal items are not safe to be freed until
8219          * the new name is stable.
8220          */
8221         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8222         olddap->da_state |= DEPCOMPLETE;
8223         complete_diradd(olddap);
8224 }
8225
8226 /*
8227  * Move the diradd to the pending list when all diradd dependencies are
8228  * complete.
8229  */
8230 static void
8231 complete_diradd(dap)
8232         struct diradd *dap;
8233 {
8234         struct pagedep *pagedep;
8235
8236         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8237                 if (dap->da_state & DIRCHG)
8238                         pagedep = dap->da_previous->dm_pagedep;
8239                 else
8240                         pagedep = dap->da_pagedep;
8241                 LIST_REMOVE(dap, da_pdlist);
8242                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8243         }
8244 }
8245
8246 /*
8247  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8248  * add entries and conditonally journal the remove.
8249  */
8250 static void
8251 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8252         struct diradd *dap;
8253         struct dirrem *dirrem;
8254         struct jremref *jremref;
8255         struct jremref *dotremref;
8256         struct jremref *dotdotremref;
8257 {
8258         struct inodedep *inodedep;
8259         struct jaddref *jaddref;
8260         struct inoref *inoref;
8261         struct mkdir *mkdir;
8262
8263         /*
8264          * If no remove references were allocated we're on a non-journaled
8265          * filesystem and can skip the cancel step.
8266          */
8267         if (jremref == NULL) {
8268                 free_diradd(dap, NULL);
8269                 return;
8270         }
8271         /*
8272          * Cancel the primary name an free it if it does not require
8273          * journaling.
8274          */
8275         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8276             0, &inodedep) != 0) {
8277                 /* Abort the addref that reference this diradd.  */
8278                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8279                         if (inoref->if_list.wk_type != D_JADDREF)
8280                                 continue;
8281                         jaddref = (struct jaddref *)inoref;
8282                         if (jaddref->ja_diradd != dap)
8283                                 continue;
8284                         if (cancel_jaddref(jaddref, inodedep,
8285                             &dirrem->dm_jwork) == 0) {
8286                                 free_jremref(jremref);
8287                                 jremref = NULL;
8288                         }
8289                         break;
8290                 }
8291         }
8292         /*
8293          * Cancel subordinate names and free them if they do not require
8294          * journaling.
8295          */
8296         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8297                 LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
8298                         if (mkdir->md_diradd != dap)
8299                                 continue;
8300                         if ((jaddref = mkdir->md_jaddref) == NULL)
8301                                 continue;
8302                         mkdir->md_jaddref = NULL;
8303                         if (mkdir->md_state & MKDIR_PARENT) {
8304                                 if (cancel_jaddref(jaddref, NULL,
8305                                     &dirrem->dm_jwork) == 0) {
8306                                         free_jremref(dotdotremref);
8307                                         dotdotremref = NULL;
8308                                 }
8309                         } else {
8310                                 if (cancel_jaddref(jaddref, inodedep,
8311                                     &dirrem->dm_jwork) == 0) {
8312                                         free_jremref(dotremref);
8313                                         dotremref = NULL;
8314                                 }
8315                         }
8316                 }
8317         }
8318
8319         if (jremref)
8320                 journal_jremref(dirrem, jremref, inodedep);
8321         if (dotremref)
8322                 journal_jremref(dirrem, dotremref, inodedep);
8323         if (dotdotremref)
8324                 journal_jremref(dirrem, dotdotremref, NULL);
8325         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8326         free_diradd(dap, &dirrem->dm_jwork);
8327 }
8328
8329 /*
8330  * Free a diradd dependency structure. This routine must be called
8331  * with splbio interrupts blocked.
8332  */
8333 static void
8334 free_diradd(dap, wkhd)
8335         struct diradd *dap;
8336         struct workhead *wkhd;
8337 {
8338         struct dirrem *dirrem;
8339         struct pagedep *pagedep;
8340         struct inodedep *inodedep;
8341         struct mkdir *mkdir, *nextmd;
8342
8343         mtx_assert(&lk, MA_OWNED);
8344         LIST_REMOVE(dap, da_pdlist);
8345         if (dap->da_state & ONWORKLIST)
8346                 WORKLIST_REMOVE(&dap->da_list);
8347         if ((dap->da_state & DIRCHG) == 0) {
8348                 pagedep = dap->da_pagedep;
8349         } else {
8350                 dirrem = dap->da_previous;
8351                 pagedep = dirrem->dm_pagedep;
8352                 dirrem->dm_dirinum = pagedep->pd_ino;
8353                 dirrem->dm_state |= COMPLETE;
8354                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8355                         add_to_worklist(&dirrem->dm_list, 0);
8356         }
8357         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8358             0, &inodedep) != 0)
8359                 if (inodedep->id_mkdiradd == dap)
8360                         inodedep->id_mkdiradd = NULL;
8361         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8362                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
8363                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8364                         if (mkdir->md_diradd != dap)
8365                                 continue;
8366                         dap->da_state &=
8367                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8368                         LIST_REMOVE(mkdir, md_mkdirs);
8369                         if (mkdir->md_state & ONWORKLIST)
8370                                 WORKLIST_REMOVE(&mkdir->md_list);
8371                         if (mkdir->md_jaddref != NULL)
8372                                 panic("free_diradd: Unexpected jaddref");
8373                         WORKITEM_FREE(mkdir, D_MKDIR);
8374                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8375                                 break;
8376                 }
8377                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8378                         panic("free_diradd: unfound ref");
8379         }
8380         if (inodedep)
8381                 free_inodedep(inodedep);
8382         /*
8383          * Free any journal segments waiting for the directory write.
8384          */
8385         handle_jwork(&dap->da_jwork);
8386         WORKITEM_FREE(dap, D_DIRADD);
8387 }
8388
8389 /*
8390  * Directory entry removal dependencies.
8391  * 
8392  * When removing a directory entry, the entry's inode pointer must be
8393  * zero'ed on disk before the corresponding inode's link count is decremented
8394  * (possibly freeing the inode for re-use). This dependency is handled by
8395  * updating the directory entry but delaying the inode count reduction until
8396  * after the directory block has been written to disk. After this point, the
8397  * inode count can be decremented whenever it is convenient.
8398  */
8399
8400 /*
8401  * This routine should be called immediately after removing
8402  * a directory entry.  The inode's link count should not be
8403  * decremented by the calling procedure -- the soft updates
8404  * code will do this task when it is safe.
8405  */
8406 void 
8407 softdep_setup_remove(bp, dp, ip, isrmdir)
8408         struct buf *bp;         /* buffer containing directory block */
8409         struct inode *dp;       /* inode for the directory being modified */
8410         struct inode *ip;       /* inode for directory entry being removed */
8411         int isrmdir;            /* indicates if doing RMDIR */
8412 {
8413         struct dirrem *dirrem, *prevdirrem;
8414         struct inodedep *inodedep;
8415         int direct;
8416
8417         /*
8418          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8419          * newdirrem() to setup the full directory remove which requires
8420          * isrmdir > 1.
8421          */
8422         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8423         /*
8424          * Add the dirrem to the inodedep's pending remove list for quick
8425          * discovery later.
8426          */
8427         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8428             &inodedep) == 0)
8429                 panic("softdep_setup_remove: Lost inodedep.");
8430         dirrem->dm_state |= ONDEPLIST;
8431         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8432
8433         /*
8434          * If the COMPLETE flag is clear, then there were no active
8435          * entries and we want to roll back to a zeroed entry until
8436          * the new inode is committed to disk. If the COMPLETE flag is
8437          * set then we have deleted an entry that never made it to
8438          * disk. If the entry we deleted resulted from a name change,
8439          * then the old name still resides on disk. We cannot delete
8440          * its inode (returned to us in prevdirrem) until the zeroed
8441          * directory entry gets to disk. The new inode has never been
8442          * referenced on the disk, so can be deleted immediately.
8443          */
8444         if ((dirrem->dm_state & COMPLETE) == 0) {
8445                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8446                     dm_next);
8447                 FREE_LOCK(&lk);
8448         } else {
8449                 if (prevdirrem != NULL)
8450                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8451                             prevdirrem, dm_next);
8452                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8453                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8454                 FREE_LOCK(&lk);
8455                 if (direct)
8456                         handle_workitem_remove(dirrem, 0);
8457         }
8458 }
8459
8460 /*
8461  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8462  * pd_pendinghd list of a pagedep.
8463  */
8464 static struct diradd *
8465 diradd_lookup(pagedep, offset)
8466         struct pagedep *pagedep;
8467         int offset;
8468 {
8469         struct diradd *dap;
8470
8471         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8472                 if (dap->da_offset == offset)
8473                         return (dap);
8474         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8475                 if (dap->da_offset == offset)
8476                         return (dap);
8477         return (NULL);
8478 }
8479
8480 /*
8481  * Search for a .. diradd dependency in a directory that is being removed.
8482  * If the directory was renamed to a new parent we have a diradd rather
8483  * than a mkdir for the .. entry.  We need to cancel it now before
8484  * it is found in truncate().
8485  */
8486 static struct jremref *
8487 cancel_diradd_dotdot(ip, dirrem, jremref)
8488         struct inode *ip;
8489         struct dirrem *dirrem;
8490         struct jremref *jremref;
8491 {
8492         struct pagedep *pagedep;
8493         struct diradd *dap;
8494         struct worklist *wk;
8495
8496         if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8497             &pagedep) == 0)
8498                 return (jremref);
8499         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8500         if (dap == NULL)
8501                 return (jremref);
8502         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8503         /*
8504          * Mark any journal work as belonging to the parent so it is freed
8505          * with the .. reference.
8506          */
8507         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8508                 wk->wk_state |= MKDIR_PARENT;
8509         return (NULL);
8510 }
8511
8512 /*
8513  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
8514  * replace it with a dirrem/diradd pair as a result of re-parenting a
8515  * directory.  This ensures that we don't simultaneously have a mkdir and
8516  * a diradd for the same .. entry.
8517  */
8518 static struct jremref *
8519 cancel_mkdir_dotdot(ip, dirrem, jremref)
8520         struct inode *ip;
8521         struct dirrem *dirrem;
8522         struct jremref *jremref;
8523 {
8524         struct inodedep *inodedep;
8525         struct jaddref *jaddref;
8526         struct mkdir *mkdir;
8527         struct diradd *dap;
8528
8529         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8530             &inodedep) == 0)
8531                 panic("cancel_mkdir_dotdot: Lost inodedep");
8532         dap = inodedep->id_mkdiradd;
8533         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
8534                 return (jremref);
8535         for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir;
8536             mkdir = LIST_NEXT(mkdir, md_mkdirs))
8537                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
8538                         break;
8539         if (mkdir == NULL)
8540                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
8541         if ((jaddref = mkdir->md_jaddref) != NULL) {
8542                 mkdir->md_jaddref = NULL;
8543                 jaddref->ja_state &= ~MKDIR_PARENT;
8544                 if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
8545                     &inodedep) == 0)
8546                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
8547                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
8548                         journal_jremref(dirrem, jremref, inodedep);
8549                         jremref = NULL;
8550                 }
8551         }
8552         if (mkdir->md_state & ONWORKLIST)
8553                 WORKLIST_REMOVE(&mkdir->md_list);
8554         mkdir->md_state |= ALLCOMPLETE;
8555         complete_mkdir(mkdir);
8556         return (jremref);
8557 }
8558
8559 static void
8560 journal_jremref(dirrem, jremref, inodedep)
8561         struct dirrem *dirrem;
8562         struct jremref *jremref;
8563         struct inodedep *inodedep;
8564 {
8565
8566         if (inodedep == NULL)
8567                 if (inodedep_lookup(jremref->jr_list.wk_mp,
8568                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
8569                         panic("journal_jremref: Lost inodedep");
8570         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
8571         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
8572         add_to_journal(&jremref->jr_list);
8573 }
8574
8575 static void
8576 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
8577         struct dirrem *dirrem;
8578         struct jremref *jremref;
8579         struct jremref *dotremref;
8580         struct jremref *dotdotremref;
8581 {
8582         struct inodedep *inodedep;
8583
8584
8585         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
8586             &inodedep) == 0)
8587                 panic("dirrem_journal: Lost inodedep");
8588         journal_jremref(dirrem, jremref, inodedep);
8589         if (dotremref)
8590                 journal_jremref(dirrem, dotremref, inodedep);
8591         if (dotdotremref)
8592                 journal_jremref(dirrem, dotdotremref, NULL);
8593 }
8594
8595 /*
8596  * Allocate a new dirrem if appropriate and return it along with
8597  * its associated pagedep. Called without a lock, returns with lock.
8598  */
8599 static struct dirrem *
8600 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
8601         struct buf *bp;         /* buffer containing directory block */
8602         struct inode *dp;       /* inode for the directory being modified */
8603         struct inode *ip;       /* inode for directory entry being removed */
8604         int isrmdir;            /* indicates if doing RMDIR */
8605         struct dirrem **prevdirremp; /* previously referenced inode, if any */
8606 {
8607         int offset;
8608         ufs_lbn_t lbn;
8609         struct diradd *dap;
8610         struct dirrem *dirrem;
8611         struct pagedep *pagedep;
8612         struct jremref *jremref;
8613         struct jremref *dotremref;
8614         struct jremref *dotdotremref;
8615         struct vnode *dvp;
8616
8617         /*
8618          * Whiteouts have no deletion dependencies.
8619          */
8620         if (ip == NULL)
8621                 panic("newdirrem: whiteout");
8622         dvp = ITOV(dp);
8623         /*
8624          * If we are over our limit, try to improve the situation.
8625          * Limiting the number of dirrem structures will also limit
8626          * the number of freefile and freeblks structures.
8627          */
8628         ACQUIRE_LOCK(&lk);
8629         if (!(ip->i_flags & SF_SNAPSHOT) &&
8630             dep_current[D_DIRREM] > max_softdeps / 2)
8631                 (void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
8632         FREE_LOCK(&lk);
8633         dirrem = malloc(sizeof(struct dirrem),
8634                 M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
8635         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
8636         LIST_INIT(&dirrem->dm_jremrefhd);
8637         LIST_INIT(&dirrem->dm_jwork);
8638         dirrem->dm_state = isrmdir ? RMDIR : 0;
8639         dirrem->dm_oldinum = ip->i_number;
8640         *prevdirremp = NULL;
8641         /*
8642          * Allocate remove reference structures to track journal write
8643          * dependencies.  We will always have one for the link and
8644          * when doing directories we will always have one more for dot.
8645          * When renaming a directory we skip the dotdot link change so
8646          * this is not needed.
8647          */
8648         jremref = dotremref = dotdotremref = NULL;
8649         if (DOINGSUJ(dvp)) {
8650                 if (isrmdir) {
8651                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8652                             ip->i_effnlink + 2);
8653                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
8654                             ip->i_effnlink + 1);
8655                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
8656                             dp->i_effnlink + 1);
8657                         dotdotremref->jr_state |= MKDIR_PARENT;
8658                 } else
8659                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
8660                             ip->i_effnlink + 1);
8661         }
8662         ACQUIRE_LOCK(&lk);
8663         lbn = lblkno(dp->i_fs, dp->i_offset);
8664         offset = blkoff(dp->i_fs, dp->i_offset);
8665         pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
8666             &pagedep);
8667         dirrem->dm_pagedep = pagedep;
8668         dirrem->dm_offset = offset;
8669         /*
8670          * If we're renaming a .. link to a new directory, cancel any
8671          * existing MKDIR_PARENT mkdir.  If it has already been canceled
8672          * the jremref is preserved for any potential diradd in this
8673          * location.  This can not coincide with a rmdir.
8674          */
8675         if (dp->i_offset == DOTDOT_OFFSET) {
8676                 if (isrmdir)
8677                         panic("newdirrem: .. directory change during remove?");
8678                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
8679         }
8680         /*
8681          * If we're removing a directory search for the .. dependency now and
8682          * cancel it.  Any pending journal work will be added to the dirrem
8683          * to be completed when the workitem remove completes.
8684          */
8685         if (isrmdir)
8686                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
8687         /*
8688          * Check for a diradd dependency for the same directory entry.
8689          * If present, then both dependencies become obsolete and can
8690          * be de-allocated.
8691          */
8692         dap = diradd_lookup(pagedep, offset);
8693         if (dap == NULL) {
8694                 /*
8695                  * Link the jremref structures into the dirrem so they are
8696                  * written prior to the pagedep.
8697                  */
8698                 if (jremref)
8699                         dirrem_journal(dirrem, jremref, dotremref,
8700                             dotdotremref);
8701                 return (dirrem);
8702         }
8703         /*
8704          * Must be ATTACHED at this point.
8705          */
8706         if ((dap->da_state & ATTACHED) == 0)
8707                 panic("newdirrem: not ATTACHED");
8708         if (dap->da_newinum != ip->i_number)
8709                 panic("newdirrem: inum %d should be %d",
8710                     ip->i_number, dap->da_newinum);
8711         /*
8712          * If we are deleting a changed name that never made it to disk,
8713          * then return the dirrem describing the previous inode (which
8714          * represents the inode currently referenced from this entry on disk).
8715          */
8716         if ((dap->da_state & DIRCHG) != 0) {
8717                 *prevdirremp = dap->da_previous;
8718                 dap->da_state &= ~DIRCHG;
8719                 dap->da_pagedep = pagedep;
8720         }
8721         /*
8722          * We are deleting an entry that never made it to disk.
8723          * Mark it COMPLETE so we can delete its inode immediately.
8724          */
8725         dirrem->dm_state |= COMPLETE;
8726         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
8727 #ifdef SUJ_DEBUG
8728         if (isrmdir == 0) {
8729                 struct worklist *wk;
8730
8731                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
8732                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
8733                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
8734         }
8735 #endif
8736
8737         return (dirrem);
8738 }
8739
8740 /*
8741  * Directory entry change dependencies.
8742  * 
8743  * Changing an existing directory entry requires that an add operation
8744  * be completed first followed by a deletion. The semantics for the addition
8745  * are identical to the description of adding a new entry above except
8746  * that the rollback is to the old inode number rather than zero. Once
8747  * the addition dependency is completed, the removal is done as described
8748  * in the removal routine above.
8749  */
8750
8751 /*
8752  * This routine should be called immediately after changing
8753  * a directory entry.  The inode's link count should not be
8754  * decremented by the calling procedure -- the soft updates
8755  * code will perform this task when it is safe.
8756  */
8757 void 
8758 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
8759         struct buf *bp;         /* buffer containing directory block */
8760         struct inode *dp;       /* inode for the directory being modified */
8761         struct inode *ip;       /* inode for directory entry being removed */
8762         ino_t newinum;          /* new inode number for changed entry */
8763         int isrmdir;            /* indicates if doing RMDIR */
8764 {
8765         int offset;
8766         struct diradd *dap = NULL;
8767         struct dirrem *dirrem, *prevdirrem;
8768         struct pagedep *pagedep;
8769         struct inodedep *inodedep;
8770         struct jaddref *jaddref;
8771         struct mount *mp;
8772
8773         offset = blkoff(dp->i_fs, dp->i_offset);
8774         mp = UFSTOVFS(dp->i_ump);
8775
8776         /*
8777          * Whiteouts do not need diradd dependencies.
8778          */
8779         if (newinum != WINO) {
8780                 dap = malloc(sizeof(struct diradd),
8781                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
8782                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
8783                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
8784                 dap->da_offset = offset;
8785                 dap->da_newinum = newinum;
8786                 LIST_INIT(&dap->da_jwork);
8787         }
8788
8789         /*
8790          * Allocate a new dirrem and ACQUIRE_LOCK.
8791          */
8792         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8793         pagedep = dirrem->dm_pagedep;
8794         /*
8795          * The possible values for isrmdir:
8796          *      0 - non-directory file rename
8797          *      1 - directory rename within same directory
8798          *   inum - directory rename to new directory of given inode number
8799          * When renaming to a new directory, we are both deleting and
8800          * creating a new directory entry, so the link count on the new
8801          * directory should not change. Thus we do not need the followup
8802          * dirrem which is usually done in handle_workitem_remove. We set
8803          * the DIRCHG flag to tell handle_workitem_remove to skip the 
8804          * followup dirrem.
8805          */
8806         if (isrmdir > 1)
8807                 dirrem->dm_state |= DIRCHG;
8808
8809         /*
8810          * Whiteouts have no additional dependencies,
8811          * so just put the dirrem on the correct list.
8812          */
8813         if (newinum == WINO) {
8814                 if ((dirrem->dm_state & COMPLETE) == 0) {
8815                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
8816                             dm_next);
8817                 } else {
8818                         dirrem->dm_dirinum = pagedep->pd_ino;
8819                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8820                                 add_to_worklist(&dirrem->dm_list, 0);
8821                 }
8822                 FREE_LOCK(&lk);
8823                 return;
8824         }
8825         /*
8826          * Add the dirrem to the inodedep's pending remove list for quick
8827          * discovery later.  A valid nlinkdelta ensures that this lookup
8828          * will not fail.
8829          */
8830         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
8831                 panic("softdep_setup_directory_change: Lost inodedep.");
8832         dirrem->dm_state |= ONDEPLIST;
8833         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8834
8835         /*
8836          * If the COMPLETE flag is clear, then there were no active
8837          * entries and we want to roll back to the previous inode until
8838          * the new inode is committed to disk. If the COMPLETE flag is
8839          * set, then we have deleted an entry that never made it to disk.
8840          * If the entry we deleted resulted from a name change, then the old
8841          * inode reference still resides on disk. Any rollback that we do
8842          * needs to be to that old inode (returned to us in prevdirrem). If
8843          * the entry we deleted resulted from a create, then there is
8844          * no entry on the disk, so we want to roll back to zero rather
8845          * than the uncommitted inode. In either of the COMPLETE cases we
8846          * want to immediately free the unwritten and unreferenced inode.
8847          */
8848         if ((dirrem->dm_state & COMPLETE) == 0) {
8849                 dap->da_previous = dirrem;
8850         } else {
8851                 if (prevdirrem != NULL) {
8852                         dap->da_previous = prevdirrem;
8853                 } else {
8854                         dap->da_state &= ~DIRCHG;
8855                         dap->da_pagedep = pagedep;
8856                 }
8857                 dirrem->dm_dirinum = pagedep->pd_ino;
8858                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8859                         add_to_worklist(&dirrem->dm_list, 0);
8860         }
8861         /*
8862          * Lookup the jaddref for this journal entry.  We must finish
8863          * initializing it and make the diradd write dependent on it.
8864          * If we're not journaling Put it on the id_bufwait list if the inode
8865          * is not yet written. If it is written, do the post-inode write
8866          * processing to put it on the id_pendinghd list.
8867          */
8868         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8869         if (MOUNTEDSUJ(mp)) {
8870                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8871                     inoreflst);
8872                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8873                     ("softdep_setup_directory_change: bad jaddref %p",
8874                     jaddref));
8875                 jaddref->ja_diroff = dp->i_offset;
8876                 jaddref->ja_diradd = dap;
8877                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
8878                     dap, da_pdlist);
8879                 add_to_journal(&jaddref->ja_list);
8880         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8881                 dap->da_state |= COMPLETE;
8882                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8883                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
8884         } else {
8885                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
8886                     dap, da_pdlist);
8887                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8888         }
8889         /*
8890          * If we're making a new name for a directory that has not been
8891          * committed when need to move the dot and dotdot references to
8892          * this new name.
8893          */
8894         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
8895                 merge_diradd(inodedep, dap);
8896         FREE_LOCK(&lk);
8897 }
8898
8899 /*
8900  * Called whenever the link count on an inode is changed.
8901  * It creates an inode dependency so that the new reference(s)
8902  * to the inode cannot be committed to disk until the updated
8903  * inode has been written.
8904  */
8905 void
8906 softdep_change_linkcnt(ip)
8907         struct inode *ip;       /* the inode with the increased link count */
8908 {
8909         struct inodedep *inodedep;
8910
8911         ACQUIRE_LOCK(&lk);
8912         inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, DEPALLOC, &inodedep);
8913         if (ip->i_nlink < ip->i_effnlink)
8914                 panic("softdep_change_linkcnt: bad delta");
8915         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
8916         FREE_LOCK(&lk);
8917 }
8918
8919 /*
8920  * Attach a sbdep dependency to the superblock buf so that we can keep
8921  * track of the head of the linked list of referenced but unlinked inodes.
8922  */
8923 void
8924 softdep_setup_sbupdate(ump, fs, bp)
8925         struct ufsmount *ump;
8926         struct fs *fs;
8927         struct buf *bp;
8928 {
8929         struct sbdep *sbdep;
8930         struct worklist *wk;
8931
8932         if (MOUNTEDSUJ(UFSTOVFS(ump)) == 0)
8933                 return;
8934         LIST_FOREACH(wk, &bp->b_dep, wk_list)
8935                 if (wk->wk_type == D_SBDEP)
8936                         break;
8937         if (wk != NULL)
8938                 return;
8939         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
8940         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
8941         sbdep->sb_fs = fs;
8942         sbdep->sb_ump = ump;
8943         ACQUIRE_LOCK(&lk);
8944         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
8945         FREE_LOCK(&lk);
8946 }
8947
8948 /*
8949  * Return the first unlinked inodedep which is ready to be the head of the
8950  * list.  The inodedep and all those after it must have valid next pointers.
8951  */
8952 static struct inodedep *
8953 first_unlinked_inodedep(ump)
8954         struct ufsmount *ump;
8955 {
8956         struct inodedep *inodedep;
8957         struct inodedep *idp;
8958
8959         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
8960             inodedep; inodedep = idp) {
8961                 if ((inodedep->id_state & UNLINKNEXT) == 0)
8962                         return (NULL);
8963                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
8964                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
8965                         break;
8966                 if ((inodedep->id_state & UNLINKPREV) == 0)
8967                         panic("first_unlinked_inodedep: prev != next");
8968         }
8969         if (inodedep == NULL)
8970                 return (NULL);
8971
8972         return (inodedep);
8973 }
8974
8975 /*
8976  * Set the sujfree unlinked head pointer prior to writing a superblock.
8977  */
8978 static void
8979 initiate_write_sbdep(sbdep)
8980         struct sbdep *sbdep;
8981 {
8982         struct inodedep *inodedep;
8983         struct fs *bpfs;
8984         struct fs *fs;
8985
8986         bpfs = sbdep->sb_fs;
8987         fs = sbdep->sb_ump->um_fs;
8988         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
8989         if (inodedep) {
8990                 fs->fs_sujfree = inodedep->id_ino;
8991                 inodedep->id_state |= UNLINKPREV;
8992         } else
8993                 fs->fs_sujfree = 0;
8994         bpfs->fs_sujfree = fs->fs_sujfree;
8995 }
8996
8997 /*
8998  * After a superblock is written determine whether it must be written again
8999  * due to a changing unlinked list head.
9000  */
9001 static int
9002 handle_written_sbdep(sbdep, bp)
9003         struct sbdep *sbdep;
9004         struct buf *bp;
9005 {
9006         struct inodedep *inodedep;
9007         struct mount *mp;
9008         struct fs *fs;
9009
9010         fs = sbdep->sb_fs;
9011         mp = UFSTOVFS(sbdep->sb_ump);
9012         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9013         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9014             (inodedep == NULL && fs->fs_sujfree != 0)) {
9015                 bdirty(bp);
9016                 return (1);
9017         }
9018         WORKITEM_FREE(sbdep, D_SBDEP);
9019         if (fs->fs_sujfree == 0)
9020                 return (0);
9021         if (inodedep_lookup(mp, fs->fs_sujfree, 0, &inodedep) == 0)
9022                 panic("handle_written_sbdep: lost inodedep");
9023         /*
9024          * Now that we have a record of this inode in stable store allow it
9025          * to be written to free up pending work.  Inodes may see a lot of
9026          * write activity after they are unlinked which we must not hold up.
9027          */
9028         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9029                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9030                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9031                             inodedep, inodedep->id_state);
9032                 if (inodedep->id_state & UNLINKONLIST)
9033                         break;
9034                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9035         }
9036
9037         return (0);
9038 }
9039
9040 /*
9041  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9042  */
9043 static void
9044 unlinked_inodedep(mp, inodedep)
9045         struct mount *mp;
9046         struct inodedep *inodedep;
9047 {
9048         struct ufsmount *ump;
9049
9050         if (MOUNTEDSUJ(mp) == 0)
9051                 return;
9052         ump = VFSTOUFS(mp);
9053         ump->um_fs->fs_fmod = 1;
9054         inodedep->id_state |= UNLINKED;
9055         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9056 }
9057
9058 /*
9059  * Remove an inodedep from the unlinked inodedep list.  This may require
9060  * disk writes if the inode has made it that far.
9061  */
9062 static void
9063 clear_unlinked_inodedep(inodedep)
9064         struct inodedep *inodedep;
9065 {
9066         struct ufsmount *ump;
9067         struct inodedep *idp;
9068         struct inodedep *idn;
9069         struct fs *fs;
9070         struct buf *bp;
9071         ino_t ino;
9072         ino_t nino;
9073         ino_t pino;
9074         int error;
9075
9076         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9077         fs = ump->um_fs;
9078         ino = inodedep->id_ino;
9079         error = 0;
9080         for (;;) {
9081                 /*
9082                  * If nothing has yet been written simply remove us from
9083                  * the in memory list and return.  This is the most common
9084                  * case where handle_workitem_remove() loses the final
9085                  * reference.
9086                  */
9087                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9088                         break;
9089                 /*
9090                  * If we have a NEXT pointer and no PREV pointer we can simply
9091                  * clear NEXT's PREV and remove ourselves from the list.  Be
9092                  * careful not to clear PREV if the superblock points at
9093                  * next as well.
9094                  */
9095                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9096                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9097                         if (idn && fs->fs_sujfree != idn->id_ino)
9098                                 idn->id_state &= ~UNLINKPREV;
9099                         break;
9100                 }
9101                 /*
9102                  * Here we have an inodedep which is actually linked into
9103                  * the list.  We must remove it by forcing a write to the
9104                  * link before us, whether it be the superblock or an inode.
9105                  * Unfortunately the list may change while we're waiting
9106                  * on the buf lock for either resource so we must loop until
9107                  * we lock the right one.  If both the superblock and an
9108                  * inode point to this inode we must clear the inode first
9109                  * followed by the superblock.
9110                  */
9111                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9112                 pino = 0;
9113                 if (idp && (idp->id_state & UNLINKNEXT))
9114                         pino = idp->id_ino;
9115                 FREE_LOCK(&lk);
9116                 if (pino == 0)
9117                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9118                             (int)fs->fs_sbsize, 0, 0, 0);
9119                 else
9120                         error = bread(ump->um_devvp,
9121                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9122                             (int)fs->fs_bsize, NOCRED, &bp);
9123                 ACQUIRE_LOCK(&lk);
9124                 if (error)
9125                         break;
9126                 /* If the list has changed restart the loop. */
9127                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9128                 nino = 0;
9129                 if (idp && (idp->id_state & UNLINKNEXT))
9130                         nino = idp->id_ino;
9131                 if (nino != pino ||
9132                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9133                         FREE_LOCK(&lk);
9134                         brelse(bp);
9135                         ACQUIRE_LOCK(&lk);
9136                         continue;
9137                 }
9138                 /*
9139                  * Remove us from the in memory list.  After this we cannot
9140                  * access the inodedep.
9141                  */
9142                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9143                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS);
9144                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9145                 /*
9146                  * Determine the next inode number.
9147                  */
9148                 nino = 0;
9149                 if (idn) {
9150                         /*
9151                          * If next isn't on the list we can just clear prev's
9152                          * state and schedule it to be fixed later.  No need
9153                          * to synchronously write if we're not in the real
9154                          * list.
9155                          */
9156                         if ((idn->id_state & UNLINKPREV) == 0 && pino != 0) {
9157                                 idp->id_state &= ~UNLINKNEXT;
9158                                 if ((idp->id_state & ONWORKLIST) == 0)
9159                                         WORKLIST_INSERT(&bp->b_dep,
9160                                             &idp->id_list);
9161                                 FREE_LOCK(&lk);
9162                                 bawrite(bp);
9163                                 ACQUIRE_LOCK(&lk);
9164                                 return;
9165                         }
9166                         nino = idn->id_ino;
9167                 }
9168                 FREE_LOCK(&lk);
9169                 /*
9170                  * The predecessor's next pointer is manually updated here
9171                  * so that the NEXT flag is never cleared for an element
9172                  * that is in the list.
9173                  */
9174                 if (pino == 0) {
9175                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9176                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9177                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9178                             bp);
9179                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9180                         ((struct ufs1_dinode *)bp->b_data +
9181                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9182                 else
9183                         ((struct ufs2_dinode *)bp->b_data +
9184                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9185                 /*
9186                  * If the bwrite fails we have no recourse to recover.  The
9187                  * filesystem is corrupted already.
9188                  */
9189                 bwrite(bp);
9190                 ACQUIRE_LOCK(&lk);
9191                 /*
9192                  * If the superblock pointer still needs to be cleared force
9193                  * a write here.
9194                  */
9195                 if (fs->fs_sujfree == ino) {
9196                         FREE_LOCK(&lk);
9197                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9198                             (int)fs->fs_sbsize, 0, 0, 0);
9199                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9200                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9201                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9202                             bp);
9203                         bwrite(bp);
9204                         ACQUIRE_LOCK(&lk);
9205                 }
9206                 if (fs->fs_sujfree != ino)
9207                         return;
9208                 panic("clear_unlinked_inodedep: Failed to clear free head");
9209         }
9210         if (inodedep->id_ino == fs->fs_sujfree)
9211                 panic("clear_unlinked_inodedep: Freeing head of free list");
9212         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS);
9213         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9214         return;
9215 }
9216
9217 /*
9218  * This workitem decrements the inode's link count.
9219  * If the link count reaches zero, the file is removed.
9220  */
9221 static int
9222 handle_workitem_remove(dirrem, flags)
9223         struct dirrem *dirrem;
9224         int flags;
9225 {
9226         struct inodedep *inodedep;
9227         struct workhead dotdotwk;
9228         struct worklist *wk;
9229         struct ufsmount *ump;
9230         struct mount *mp;
9231         struct vnode *vp;
9232         struct inode *ip;
9233         ino_t oldinum;
9234
9235         if (dirrem->dm_state & ONWORKLIST)
9236                 panic("handle_workitem_remove: dirrem %p still on worklist",
9237                     dirrem);
9238         oldinum = dirrem->dm_oldinum;
9239         mp = dirrem->dm_list.wk_mp;
9240         ump = VFSTOUFS(mp);
9241         flags |= LK_EXCLUSIVE;
9242         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9243                 return (EBUSY);
9244         ip = VTOI(vp);
9245         ACQUIRE_LOCK(&lk);
9246         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9247                 panic("handle_workitem_remove: lost inodedep");
9248         if (dirrem->dm_state & ONDEPLIST)
9249                 LIST_REMOVE(dirrem, dm_inonext);
9250         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9251             ("handle_workitem_remove:  Journal entries not written."));
9252
9253         /*
9254          * Move all dependencies waiting on the remove to complete
9255          * from the dirrem to the inode inowait list to be completed
9256          * after the inode has been updated and written to disk.  Any
9257          * marked MKDIR_PARENT are saved to be completed when the .. ref
9258          * is removed.
9259          */
9260         LIST_INIT(&dotdotwk);
9261         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9262                 WORKLIST_REMOVE(wk);
9263                 if (wk->wk_state & MKDIR_PARENT) {
9264                         wk->wk_state &= ~MKDIR_PARENT;
9265                         WORKLIST_INSERT(&dotdotwk, wk);
9266                         continue;
9267                 }
9268                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9269         }
9270         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9271         /*
9272          * Normal file deletion.
9273          */
9274         if ((dirrem->dm_state & RMDIR) == 0) {
9275                 ip->i_nlink--;
9276                 DIP_SET(ip, i_nlink, ip->i_nlink);
9277                 ip->i_flag |= IN_CHANGE;
9278                 if (ip->i_nlink < ip->i_effnlink)
9279                         panic("handle_workitem_remove: bad file delta");
9280                 if (ip->i_nlink == 0) 
9281                         unlinked_inodedep(mp, inodedep);
9282                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9283                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9284                     ("handle_workitem_remove: worklist not empty. %s",
9285                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9286                 WORKITEM_FREE(dirrem, D_DIRREM);
9287                 FREE_LOCK(&lk);
9288                 goto out;
9289         }
9290         /*
9291          * Directory deletion. Decrement reference count for both the
9292          * just deleted parent directory entry and the reference for ".".
9293          * Arrange to have the reference count on the parent decremented
9294          * to account for the loss of "..".
9295          */
9296         ip->i_nlink -= 2;
9297         DIP_SET(ip, i_nlink, ip->i_nlink);
9298         ip->i_flag |= IN_CHANGE;
9299         if (ip->i_nlink < ip->i_effnlink)
9300                 panic("handle_workitem_remove: bad dir delta");
9301         if (ip->i_nlink == 0)
9302                 unlinked_inodedep(mp, inodedep);
9303         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9304         /*
9305          * Rename a directory to a new parent. Since, we are both deleting
9306          * and creating a new directory entry, the link count on the new
9307          * directory should not change. Thus we skip the followup dirrem.
9308          */
9309         if (dirrem->dm_state & DIRCHG) {
9310                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9311                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9312                 WORKITEM_FREE(dirrem, D_DIRREM);
9313                 FREE_LOCK(&lk);
9314                 goto out;
9315         }
9316         dirrem->dm_state = ONDEPLIST;
9317         dirrem->dm_oldinum = dirrem->dm_dirinum;
9318         /*
9319          * Place the dirrem on the parent's diremhd list.
9320          */
9321         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9322                 panic("handle_workitem_remove: lost dir inodedep");
9323         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9324         /*
9325          * If the allocated inode has never been written to disk, then
9326          * the on-disk inode is zero'ed and we can remove the file
9327          * immediately.  When journaling if the inode has been marked
9328          * unlinked and not DEPCOMPLETE we know it can never be written.
9329          */
9330         inodedep_lookup(mp, oldinum, 0, &inodedep);
9331         if (inodedep == NULL ||
9332             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9333             check_inode_unwritten(inodedep)) {
9334                 FREE_LOCK(&lk);
9335                 vput(vp);
9336                 return handle_workitem_remove(dirrem, flags);
9337         }
9338         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9339         FREE_LOCK(&lk);
9340         ip->i_flag |= IN_CHANGE;
9341 out:
9342         ffs_update(vp, 0);
9343         vput(vp);
9344         return (0);
9345 }
9346
9347 /*
9348  * Inode de-allocation dependencies.
9349  * 
9350  * When an inode's link count is reduced to zero, it can be de-allocated. We
9351  * found it convenient to postpone de-allocation until after the inode is
9352  * written to disk with its new link count (zero).  At this point, all of the
9353  * on-disk inode's block pointers are nullified and, with careful dependency
9354  * list ordering, all dependencies related to the inode will be satisfied and
9355  * the corresponding dependency structures de-allocated.  So, if/when the
9356  * inode is reused, there will be no mixing of old dependencies with new
9357  * ones.  This artificial dependency is set up by the block de-allocation
9358  * procedure above (softdep_setup_freeblocks) and completed by the
9359  * following procedure.
9360  */
9361 static void 
9362 handle_workitem_freefile(freefile)
9363         struct freefile *freefile;
9364 {
9365         struct workhead wkhd;
9366         struct fs *fs;
9367         struct inodedep *idp;
9368         struct ufsmount *ump;
9369         int error;
9370
9371         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9372         fs = ump->um_fs;
9373 #ifdef DEBUG
9374         ACQUIRE_LOCK(&lk);
9375         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9376         FREE_LOCK(&lk);
9377         if (error)
9378                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9379 #endif
9380         UFS_LOCK(ump);
9381         fs->fs_pendinginodes -= 1;
9382         UFS_UNLOCK(ump);
9383         LIST_INIT(&wkhd);
9384         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9385         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9386             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9387                 softdep_error("handle_workitem_freefile", error);
9388         ACQUIRE_LOCK(&lk);
9389         WORKITEM_FREE(freefile, D_FREEFILE);
9390         FREE_LOCK(&lk);
9391 }
9392
9393
9394 /*
9395  * Helper function which unlinks marker element from work list and returns
9396  * the next element on the list.
9397  */
9398 static __inline struct worklist *
9399 markernext(struct worklist *marker)
9400 {
9401         struct worklist *next;
9402         
9403         next = LIST_NEXT(marker, wk_list);
9404         LIST_REMOVE(marker, wk_list);
9405         return next;
9406 }
9407
9408 /*
9409  * Disk writes.
9410  * 
9411  * The dependency structures constructed above are most actively used when file
9412  * system blocks are written to disk.  No constraints are placed on when a
9413  * block can be written, but unsatisfied update dependencies are made safe by
9414  * modifying (or replacing) the source memory for the duration of the disk
9415  * write.  When the disk write completes, the memory block is again brought
9416  * up-to-date.
9417  *
9418  * In-core inode structure reclamation.
9419  * 
9420  * Because there are a finite number of "in-core" inode structures, they are
9421  * reused regularly.  By transferring all inode-related dependencies to the
9422  * in-memory inode block and indexing them separately (via "inodedep"s), we
9423  * can allow "in-core" inode structures to be reused at any time and avoid
9424  * any increase in contention.
9425  *
9426  * Called just before entering the device driver to initiate a new disk I/O.
9427  * The buffer must be locked, thus, no I/O completion operations can occur
9428  * while we are manipulating its associated dependencies.
9429  */
9430 static void 
9431 softdep_disk_io_initiation(bp)
9432         struct buf *bp;         /* structure describing disk write to occur */
9433 {
9434         struct worklist *wk;
9435         struct worklist marker;
9436         struct inodedep *inodedep;
9437         struct freeblks *freeblks;
9438         struct jblkdep *jblkdep;
9439         struct newblk *newblk;
9440
9441         /*
9442          * We only care about write operations. There should never
9443          * be dependencies for reads.
9444          */
9445         if (bp->b_iocmd != BIO_WRITE)
9446                 panic("softdep_disk_io_initiation: not write");
9447
9448         if (bp->b_vflags & BV_BKGRDINPROG)
9449                 panic("softdep_disk_io_initiation: Writing buffer with "
9450                     "background write in progress: %p", bp);
9451
9452         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
9453         PHOLD(curproc);                 /* Don't swap out kernel stack */
9454
9455         ACQUIRE_LOCK(&lk);
9456         /*
9457          * Do any necessary pre-I/O processing.
9458          */
9459         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9460              wk = markernext(&marker)) {
9461                 LIST_INSERT_AFTER(wk, &marker, wk_list);
9462                 switch (wk->wk_type) {
9463
9464                 case D_PAGEDEP:
9465                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
9466                         continue;
9467
9468                 case D_INODEDEP:
9469                         inodedep = WK_INODEDEP(wk);
9470                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9471                                 initiate_write_inodeblock_ufs1(inodedep, bp);
9472                         else
9473                                 initiate_write_inodeblock_ufs2(inodedep, bp);
9474                         continue;
9475
9476                 case D_INDIRDEP:
9477                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9478                         continue;
9479
9480                 case D_BMSAFEMAP:
9481                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9482                         continue;
9483
9484                 case D_JSEG:
9485                         WK_JSEG(wk)->js_buf = NULL;
9486                         continue;
9487
9488                 case D_FREEBLKS:
9489                         freeblks = WK_FREEBLKS(wk);
9490                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9491                         /*
9492                          * We have to wait for the freeblks to be journaled
9493                          * before we can write an inodeblock with updated
9494                          * pointers.  Be careful to arrange the marker so
9495                          * we revisit the freeblks if it's not removed by
9496                          * the first jwait().
9497                          */
9498                         if (jblkdep != NULL) {
9499                                 LIST_REMOVE(&marker, wk_list);
9500                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
9501                                 jwait(&jblkdep->jb_list, MNT_WAIT);
9502                         }
9503                         continue;
9504                 case D_ALLOCDIRECT:
9505                 case D_ALLOCINDIR:
9506                         /*
9507                          * We have to wait for the jnewblk to be journaled
9508                          * before we can write to a block if the contents
9509                          * may be confused with an earlier file's indirect
9510                          * at recovery time.  Handle the marker as described
9511                          * above.
9512                          */
9513                         newblk = WK_NEWBLK(wk);
9514                         if (newblk->nb_jnewblk != NULL &&
9515                             indirblk_lookup(newblk->nb_list.wk_mp,
9516                             newblk->nb_newblkno)) {
9517                                 LIST_REMOVE(&marker, wk_list);
9518                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
9519                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
9520                         }
9521                         continue;
9522
9523                 case D_SBDEP:
9524                         initiate_write_sbdep(WK_SBDEP(wk));
9525                         continue;
9526
9527                 case D_MKDIR:
9528                 case D_FREEWORK:
9529                 case D_FREEDEP:
9530                 case D_JSEGDEP:
9531                         continue;
9532
9533                 default:
9534                         panic("handle_disk_io_initiation: Unexpected type %s",
9535                             TYPENAME(wk->wk_type));
9536                         /* NOTREACHED */
9537                 }
9538         }
9539         FREE_LOCK(&lk);
9540         PRELE(curproc);                 /* Allow swapout of kernel stack */
9541 }
9542
9543 /*
9544  * Called from within the procedure above to deal with unsatisfied
9545  * allocation dependencies in a directory. The buffer must be locked,
9546  * thus, no I/O completion operations can occur while we are
9547  * manipulating its associated dependencies.
9548  */
9549 static void
9550 initiate_write_filepage(pagedep, bp)
9551         struct pagedep *pagedep;
9552         struct buf *bp;
9553 {
9554         struct jremref *jremref;
9555         struct jmvref *jmvref;
9556         struct dirrem *dirrem;
9557         struct diradd *dap;
9558         struct direct *ep;
9559         int i;
9560
9561         if (pagedep->pd_state & IOSTARTED) {
9562                 /*
9563                  * This can only happen if there is a driver that does not
9564                  * understand chaining. Here biodone will reissue the call
9565                  * to strategy for the incomplete buffers.
9566                  */
9567                 printf("initiate_write_filepage: already started\n");
9568                 return;
9569         }
9570         pagedep->pd_state |= IOSTARTED;
9571         /*
9572          * Wait for all journal remove dependencies to hit the disk.
9573          * We can not allow any potentially conflicting directory adds
9574          * to be visible before removes and rollback is too difficult.
9575          * lk may be dropped and re-acquired, however we hold the buf
9576          * locked so the dependency can not go away.
9577          */
9578         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
9579                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
9580                         jwait(&jremref->jr_list, MNT_WAIT);
9581         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
9582                 jwait(&jmvref->jm_list, MNT_WAIT);
9583         for (i = 0; i < DAHASHSZ; i++) {
9584                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
9585                         ep = (struct direct *)
9586                             ((char *)bp->b_data + dap->da_offset);
9587                         if (ep->d_ino != dap->da_newinum)
9588                                 panic("%s: dir inum %d != new %d",
9589                                     "initiate_write_filepage",
9590                                     ep->d_ino, dap->da_newinum);
9591                         if (dap->da_state & DIRCHG)
9592                                 ep->d_ino = dap->da_previous->dm_oldinum;
9593                         else
9594                                 ep->d_ino = 0;
9595                         dap->da_state &= ~ATTACHED;
9596                         dap->da_state |= UNDONE;
9597                 }
9598         }
9599 }
9600
9601 /*
9602  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
9603  * Note that any bug fixes made to this routine must be done in the
9604  * version found below.
9605  *
9606  * Called from within the procedure above to deal with unsatisfied
9607  * allocation dependencies in an inodeblock. The buffer must be
9608  * locked, thus, no I/O completion operations can occur while we
9609  * are manipulating its associated dependencies.
9610  */
9611 static void 
9612 initiate_write_inodeblock_ufs1(inodedep, bp)
9613         struct inodedep *inodedep;
9614         struct buf *bp;                 /* The inode block */
9615 {
9616         struct allocdirect *adp, *lastadp;
9617         struct ufs1_dinode *dp;
9618         struct ufs1_dinode *sip;
9619         struct inoref *inoref;
9620         struct fs *fs;
9621         ufs_lbn_t i;
9622 #ifdef INVARIANTS
9623         ufs_lbn_t prevlbn = 0;
9624 #endif
9625         int deplist;
9626
9627         if (inodedep->id_state & IOSTARTED)
9628                 panic("initiate_write_inodeblock_ufs1: already started");
9629         inodedep->id_state |= IOSTARTED;
9630         fs = inodedep->id_fs;
9631         dp = (struct ufs1_dinode *)bp->b_data +
9632             ino_to_fsbo(fs, inodedep->id_ino);
9633
9634         /*
9635          * If we're on the unlinked list but have not yet written our
9636          * next pointer initialize it here.
9637          */
9638         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9639                 struct inodedep *inon;
9640
9641                 inon = TAILQ_NEXT(inodedep, id_unlinked);
9642                 dp->di_freelink = inon ? inon->id_ino : 0;
9643         }
9644         /*
9645          * If the bitmap is not yet written, then the allocated
9646          * inode cannot be written to disk.
9647          */
9648         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9649                 if (inodedep->id_savedino1 != NULL)
9650                         panic("initiate_write_inodeblock_ufs1: I/O underway");
9651                 FREE_LOCK(&lk);
9652                 sip = malloc(sizeof(struct ufs1_dinode),
9653                     M_SAVEDINO, M_SOFTDEP_FLAGS);
9654                 ACQUIRE_LOCK(&lk);
9655                 inodedep->id_savedino1 = sip;
9656                 *inodedep->id_savedino1 = *dp;
9657                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
9658                 dp->di_gen = inodedep->id_savedino1->di_gen;
9659                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
9660                 return;
9661         }
9662         /*
9663          * If no dependencies, then there is nothing to roll back.
9664          */
9665         inodedep->id_savedsize = dp->di_size;
9666         inodedep->id_savedextsize = 0;
9667         inodedep->id_savednlink = dp->di_nlink;
9668         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9669             TAILQ_EMPTY(&inodedep->id_inoreflst))
9670                 return;
9671         /*
9672          * Revert the link count to that of the first unwritten journal entry.
9673          */
9674         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9675         if (inoref)
9676                 dp->di_nlink = inoref->if_nlink;
9677         /*
9678          * Set the dependencies to busy.
9679          */
9680         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9681              adp = TAILQ_NEXT(adp, ad_next)) {
9682 #ifdef INVARIANTS
9683                 if (deplist != 0 && prevlbn >= adp->ad_offset)
9684                         panic("softdep_write_inodeblock: lbn order");
9685                 prevlbn = adp->ad_offset;
9686                 if (adp->ad_offset < NDADDR &&
9687                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9688                         panic("%s: direct pointer #%jd mismatch %d != %jd",
9689                             "softdep_write_inodeblock",
9690                             (intmax_t)adp->ad_offset,
9691                             dp->di_db[adp->ad_offset],
9692                             (intmax_t)adp->ad_newblkno);
9693                 if (adp->ad_offset >= NDADDR &&
9694                     dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9695                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
9696                             "softdep_write_inodeblock",
9697                             (intmax_t)adp->ad_offset - NDADDR,
9698                             dp->di_ib[adp->ad_offset - NDADDR],
9699                             (intmax_t)adp->ad_newblkno);
9700                 deplist |= 1 << adp->ad_offset;
9701                 if ((adp->ad_state & ATTACHED) == 0)
9702                         panic("softdep_write_inodeblock: Unknown state 0x%x",
9703                             adp->ad_state);
9704 #endif /* INVARIANTS */
9705                 adp->ad_state &= ~ATTACHED;
9706                 adp->ad_state |= UNDONE;
9707         }
9708         /*
9709          * The on-disk inode cannot claim to be any larger than the last
9710          * fragment that has been written. Otherwise, the on-disk inode
9711          * might have fragments that were not the last block in the file
9712          * which would corrupt the filesystem.
9713          */
9714         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9715              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9716                 if (adp->ad_offset >= NDADDR)
9717                         break;
9718                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
9719                 /* keep going until hitting a rollback to a frag */
9720                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9721                         continue;
9722                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9723                 for (i = adp->ad_offset + 1; i < NDADDR; i++) {
9724 #ifdef INVARIANTS
9725                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
9726                                 panic("softdep_write_inodeblock: lost dep1");
9727 #endif /* INVARIANTS */
9728                         dp->di_db[i] = 0;
9729                 }
9730                 for (i = 0; i < NIADDR; i++) {
9731 #ifdef INVARIANTS
9732                         if (dp->di_ib[i] != 0 &&
9733                             (deplist & ((1 << NDADDR) << i)) == 0)
9734                                 panic("softdep_write_inodeblock: lost dep2");
9735 #endif /* INVARIANTS */
9736                         dp->di_ib[i] = 0;
9737                 }
9738                 return;
9739         }
9740         /*
9741          * If we have zero'ed out the last allocated block of the file,
9742          * roll back the size to the last currently allocated block.
9743          * We know that this last allocated block is a full-sized as
9744          * we already checked for fragments in the loop above.
9745          */
9746         if (lastadp != NULL &&
9747             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9748                 for (i = lastadp->ad_offset; i >= 0; i--)
9749                         if (dp->di_db[i] != 0)
9750                                 break;
9751                 dp->di_size = (i + 1) * fs->fs_bsize;
9752         }
9753         /*
9754          * The only dependencies are for indirect blocks.
9755          *
9756          * The file size for indirect block additions is not guaranteed.
9757          * Such a guarantee would be non-trivial to achieve. The conventional
9758          * synchronous write implementation also does not make this guarantee.
9759          * Fsck should catch and fix discrepancies. Arguably, the file size
9760          * can be over-estimated without destroying integrity when the file
9761          * moves into the indirect blocks (i.e., is large). If we want to
9762          * postpone fsck, we are stuck with this argument.
9763          */
9764         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
9765                 dp->di_ib[adp->ad_offset - NDADDR] = 0;
9766 }
9767                 
9768 /*
9769  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
9770  * Note that any bug fixes made to this routine must be done in the
9771  * version found above.
9772  *
9773  * Called from within the procedure above to deal with unsatisfied
9774  * allocation dependencies in an inodeblock. The buffer must be
9775  * locked, thus, no I/O completion operations can occur while we
9776  * are manipulating its associated dependencies.
9777  */
9778 static void 
9779 initiate_write_inodeblock_ufs2(inodedep, bp)
9780         struct inodedep *inodedep;
9781         struct buf *bp;                 /* The inode block */
9782 {
9783         struct allocdirect *adp, *lastadp;
9784         struct ufs2_dinode *dp;
9785         struct ufs2_dinode *sip;
9786         struct inoref *inoref;
9787         struct fs *fs;
9788         ufs_lbn_t i;
9789 #ifdef INVARIANTS
9790         ufs_lbn_t prevlbn = 0;
9791 #endif
9792         int deplist;
9793
9794         if (inodedep->id_state & IOSTARTED)
9795                 panic("initiate_write_inodeblock_ufs2: already started");
9796         inodedep->id_state |= IOSTARTED;
9797         fs = inodedep->id_fs;
9798         dp = (struct ufs2_dinode *)bp->b_data +
9799             ino_to_fsbo(fs, inodedep->id_ino);
9800
9801         /*
9802          * If we're on the unlinked list but have not yet written our
9803          * next pointer initialize it here.
9804          */
9805         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
9806                 struct inodedep *inon;
9807
9808                 inon = TAILQ_NEXT(inodedep, id_unlinked);
9809                 dp->di_freelink = inon ? inon->id_ino : 0;
9810         }
9811         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) ==
9812             (UNLINKED | UNLINKNEXT)) {
9813                 struct inodedep *inon;
9814                 ino_t freelink;
9815
9816                 inon = TAILQ_NEXT(inodedep, id_unlinked);
9817                 freelink = inon ? inon->id_ino : 0;
9818                 if (freelink != dp->di_freelink)
9819                         panic("ino %p(0x%X) %d, %d != %d",
9820                             inodedep, inodedep->id_state, inodedep->id_ino,
9821                             freelink, dp->di_freelink);
9822         }
9823         /*
9824          * If the bitmap is not yet written, then the allocated
9825          * inode cannot be written to disk.
9826          */
9827         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
9828                 if (inodedep->id_savedino2 != NULL)
9829                         panic("initiate_write_inodeblock_ufs2: I/O underway");
9830                 FREE_LOCK(&lk);
9831                 sip = malloc(sizeof(struct ufs2_dinode),
9832                     M_SAVEDINO, M_SOFTDEP_FLAGS);
9833                 ACQUIRE_LOCK(&lk);
9834                 inodedep->id_savedino2 = sip;
9835                 *inodedep->id_savedino2 = *dp;
9836                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
9837                 dp->di_gen = inodedep->id_savedino2->di_gen;
9838                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
9839                 return;
9840         }
9841         /*
9842          * If no dependencies, then there is nothing to roll back.
9843          */
9844         inodedep->id_savedsize = dp->di_size;
9845         inodedep->id_savedextsize = dp->di_extsize;
9846         inodedep->id_savednlink = dp->di_nlink;
9847         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
9848             TAILQ_EMPTY(&inodedep->id_extupdt) &&
9849             TAILQ_EMPTY(&inodedep->id_inoreflst))
9850                 return;
9851         /*
9852          * Revert the link count to that of the first unwritten journal entry.
9853          */
9854         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
9855         if (inoref)
9856                 dp->di_nlink = inoref->if_nlink;
9857
9858         /*
9859          * Set the ext data dependencies to busy.
9860          */
9861         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
9862              adp = TAILQ_NEXT(adp, ad_next)) {
9863 #ifdef INVARIANTS
9864                 if (deplist != 0 && prevlbn >= adp->ad_offset)
9865                         panic("softdep_write_inodeblock: lbn order");
9866                 prevlbn = adp->ad_offset;
9867                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
9868                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
9869                             "softdep_write_inodeblock",
9870                             (intmax_t)adp->ad_offset,
9871                             (intmax_t)dp->di_extb[adp->ad_offset],
9872                             (intmax_t)adp->ad_newblkno);
9873                 deplist |= 1 << adp->ad_offset;
9874                 if ((adp->ad_state & ATTACHED) == 0)
9875                         panic("softdep_write_inodeblock: Unknown state 0x%x",
9876                             adp->ad_state);
9877 #endif /* INVARIANTS */
9878                 adp->ad_state &= ~ATTACHED;
9879                 adp->ad_state |= UNDONE;
9880         }
9881         /*
9882          * The on-disk inode cannot claim to be any larger than the last
9883          * fragment that has been written. Otherwise, the on-disk inode
9884          * might have fragments that were not the last block in the ext
9885          * data which would corrupt the filesystem.
9886          */
9887         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
9888              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9889                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
9890                 /* keep going until hitting a rollback to a frag */
9891                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9892                         continue;
9893                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9894                 for (i = adp->ad_offset + 1; i < NXADDR; i++) {
9895 #ifdef INVARIANTS
9896                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
9897                                 panic("softdep_write_inodeblock: lost dep1");
9898 #endif /* INVARIANTS */
9899                         dp->di_extb[i] = 0;
9900                 }
9901                 lastadp = NULL;
9902                 break;
9903         }
9904         /*
9905          * If we have zero'ed out the last allocated block of the ext
9906          * data, roll back the size to the last currently allocated block.
9907          * We know that this last allocated block is a full-sized as
9908          * we already checked for fragments in the loop above.
9909          */
9910         if (lastadp != NULL &&
9911             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9912                 for (i = lastadp->ad_offset; i >= 0; i--)
9913                         if (dp->di_extb[i] != 0)
9914                                 break;
9915                 dp->di_extsize = (i + 1) * fs->fs_bsize;
9916         }
9917         /*
9918          * Set the file data dependencies to busy.
9919          */
9920         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9921              adp = TAILQ_NEXT(adp, ad_next)) {
9922 #ifdef INVARIANTS
9923                 if (deplist != 0 && prevlbn >= adp->ad_offset)
9924                         panic("softdep_write_inodeblock: lbn order");
9925                 if ((adp->ad_state & ATTACHED) == 0)
9926                         panic("inodedep %p and adp %p not attached", inodedep, adp);
9927                 prevlbn = adp->ad_offset;
9928                 if (adp->ad_offset < NDADDR &&
9929                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
9930                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
9931                             "softdep_write_inodeblock",
9932                             (intmax_t)adp->ad_offset,
9933                             (intmax_t)dp->di_db[adp->ad_offset],
9934                             (intmax_t)adp->ad_newblkno);
9935                 if (adp->ad_offset >= NDADDR &&
9936                     dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
9937                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
9938                             "softdep_write_inodeblock:",
9939                             (intmax_t)adp->ad_offset - NDADDR,
9940                             (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
9941                             (intmax_t)adp->ad_newblkno);
9942                 deplist |= 1 << adp->ad_offset;
9943                 if ((adp->ad_state & ATTACHED) == 0)
9944                         panic("softdep_write_inodeblock: Unknown state 0x%x",
9945                             adp->ad_state);
9946 #endif /* INVARIANTS */
9947                 adp->ad_state &= ~ATTACHED;
9948                 adp->ad_state |= UNDONE;
9949         }
9950         /*
9951          * The on-disk inode cannot claim to be any larger than the last
9952          * fragment that has been written. Otherwise, the on-disk inode
9953          * might have fragments that were not the last block in the file
9954          * which would corrupt the filesystem.
9955          */
9956         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
9957              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
9958                 if (adp->ad_offset >= NDADDR)
9959                         break;
9960                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
9961                 /* keep going until hitting a rollback to a frag */
9962                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
9963                         continue;
9964                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
9965                 for (i = adp->ad_offset + 1; i < NDADDR; i++) {
9966 #ifdef INVARIANTS
9967                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
9968                                 panic("softdep_write_inodeblock: lost dep2");
9969 #endif /* INVARIANTS */
9970                         dp->di_db[i] = 0;
9971                 }
9972                 for (i = 0; i < NIADDR; i++) {
9973 #ifdef INVARIANTS
9974                         if (dp->di_ib[i] != 0 &&
9975                             (deplist & ((1 << NDADDR) << i)) == 0)
9976                                 panic("softdep_write_inodeblock: lost dep3");
9977 #endif /* INVARIANTS */
9978                         dp->di_ib[i] = 0;
9979                 }
9980                 return;
9981         }
9982         /*
9983          * If we have zero'ed out the last allocated block of the file,
9984          * roll back the size to the last currently allocated block.
9985          * We know that this last allocated block is a full-sized as
9986          * we already checked for fragments in the loop above.
9987          */
9988         if (lastadp != NULL &&
9989             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
9990                 for (i = lastadp->ad_offset; i >= 0; i--)
9991                         if (dp->di_db[i] != 0)
9992                                 break;
9993                 dp->di_size = (i + 1) * fs->fs_bsize;
9994         }
9995         /*
9996          * The only dependencies are for indirect blocks.
9997          *
9998          * The file size for indirect block additions is not guaranteed.
9999          * Such a guarantee would be non-trivial to achieve. The conventional
10000          * synchronous write implementation also does not make this guarantee.
10001          * Fsck should catch and fix discrepancies. Arguably, the file size
10002          * can be over-estimated without destroying integrity when the file
10003          * moves into the indirect blocks (i.e., is large). If we want to
10004          * postpone fsck, we are stuck with this argument.
10005          */
10006         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10007                 dp->di_ib[adp->ad_offset - NDADDR] = 0;
10008 }
10009
10010 /*
10011  * Cancel an indirdep as a result of truncation.  Release all of the
10012  * children allocindirs and place their journal work on the appropriate
10013  * list.
10014  */
10015 static void
10016 cancel_indirdep(indirdep, bp, freeblks)
10017         struct indirdep *indirdep;
10018         struct buf *bp;
10019         struct freeblks *freeblks;
10020 {
10021         struct allocindir *aip;
10022
10023         /*
10024          * None of the indirect pointers will ever be visible,
10025          * so they can simply be tossed. GOINGAWAY ensures
10026          * that allocated pointers will be saved in the buffer
10027          * cache until they are freed. Note that they will
10028          * only be able to be found by their physical address
10029          * since the inode mapping the logical address will
10030          * be gone. The save buffer used for the safe copy
10031          * was allocated in setup_allocindir_phase2 using
10032          * the physical address so it could be used for this
10033          * purpose. Hence we swap the safe copy with the real
10034          * copy, allowing the safe copy to be freed and holding
10035          * on to the real copy for later use in indir_trunc.
10036          */
10037         if (indirdep->ir_state & GOINGAWAY)
10038                 panic("cancel_indirdep: already gone");
10039         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10040                 indirdep->ir_state |= DEPCOMPLETE;
10041                 LIST_REMOVE(indirdep, ir_next);
10042         }
10043         indirdep->ir_state |= GOINGAWAY;
10044         VFSTOUFS(indirdep->ir_list.wk_mp)->um_numindirdeps += 1;
10045         /*
10046          * Pass in bp for blocks still have journal writes
10047          * pending so we can cancel them on their own.
10048          */
10049         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10050                 cancel_allocindir(aip, bp, freeblks, 0);
10051         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10052                 cancel_allocindir(aip, NULL, freeblks, 0);
10053         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10054                 cancel_allocindir(aip, NULL, freeblks, 0);
10055         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10056                 cancel_allocindir(aip, NULL, freeblks, 0);
10057         /*
10058          * If there are pending partial truncations we need to keep the
10059          * old block copy around until they complete.  This is because
10060          * the current b_data is not a perfect superset of the available
10061          * blocks.
10062          */
10063         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10064                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10065         else
10066                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10067         WORKLIST_REMOVE(&indirdep->ir_list);
10068         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10069         indirdep->ir_bp = NULL;
10070         indirdep->ir_freeblks = freeblks;
10071 }
10072
10073 /*
10074  * Free an indirdep once it no longer has new pointers to track.
10075  */
10076 static void
10077 free_indirdep(indirdep)
10078         struct indirdep *indirdep;
10079 {
10080
10081         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10082             ("free_indirdep: Indir trunc list not empty."));
10083         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10084             ("free_indirdep: Complete head not empty."));
10085         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10086             ("free_indirdep: write head not empty."));
10087         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10088             ("free_indirdep: done head not empty."));
10089         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10090             ("free_indirdep: deplist head not empty."));
10091         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10092             ("free_indirdep: %p still on newblk list.", indirdep));
10093         KASSERT(indirdep->ir_saveddata == NULL,
10094             ("free_indirdep: %p still has saved data.", indirdep));
10095         if (indirdep->ir_state & ONWORKLIST)
10096                 WORKLIST_REMOVE(&indirdep->ir_list);
10097         WORKITEM_FREE(indirdep, D_INDIRDEP);
10098 }
10099
10100 /*
10101  * Called before a write to an indirdep.  This routine is responsible for
10102  * rolling back pointers to a safe state which includes only those
10103  * allocindirs which have been completed.
10104  */
10105 static void
10106 initiate_write_indirdep(indirdep, bp)
10107         struct indirdep *indirdep;
10108         struct buf *bp;
10109 {
10110
10111         indirdep->ir_state |= IOSTARTED;
10112         if (indirdep->ir_state & GOINGAWAY)
10113                 panic("disk_io_initiation: indirdep gone");
10114         /*
10115          * If there are no remaining dependencies, this will be writing
10116          * the real pointers.
10117          */
10118         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10119             TAILQ_EMPTY(&indirdep->ir_trunc))
10120                 return;
10121         /*
10122          * Replace up-to-date version with safe version.
10123          */
10124         if (indirdep->ir_saveddata == NULL) {
10125                 FREE_LOCK(&lk);
10126                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10127                     M_SOFTDEP_FLAGS);
10128                 ACQUIRE_LOCK(&lk);
10129         }
10130         indirdep->ir_state &= ~ATTACHED;
10131         indirdep->ir_state |= UNDONE;
10132         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10133         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10134             bp->b_bcount);
10135 }
10136
10137 /*
10138  * Called when an inode has been cleared in a cg bitmap.  This finally
10139  * eliminates any canceled jaddrefs
10140  */
10141 void
10142 softdep_setup_inofree(mp, bp, ino, wkhd)
10143         struct mount *mp;
10144         struct buf *bp;
10145         ino_t ino;
10146         struct workhead *wkhd;
10147 {
10148         struct worklist *wk, *wkn;
10149         struct inodedep *inodedep;
10150         uint8_t *inosused;
10151         struct cg *cgp;
10152         struct fs *fs;
10153
10154         ACQUIRE_LOCK(&lk);
10155         fs = VFSTOUFS(mp)->um_fs;
10156         cgp = (struct cg *)bp->b_data;
10157         inosused = cg_inosused(cgp);
10158         if (isset(inosused, ino % fs->fs_ipg))
10159                 panic("softdep_setup_inofree: inode %d not freed.", ino);
10160         if (inodedep_lookup(mp, ino, 0, &inodedep))
10161                 panic("softdep_setup_inofree: ino %d has existing inodedep %p",
10162                     ino, inodedep);
10163         if (wkhd) {
10164                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10165                         if (wk->wk_type != D_JADDREF)
10166                                 continue;
10167                         WORKLIST_REMOVE(wk);
10168                         /*
10169                          * We can free immediately even if the jaddref
10170                          * isn't attached in a background write as now
10171                          * the bitmaps are reconciled.
10172                          */
10173                         wk->wk_state |= COMPLETE | ATTACHED;
10174                         free_jaddref(WK_JADDREF(wk));
10175                 }
10176                 jwork_move(&bp->b_dep, wkhd);
10177         }
10178         FREE_LOCK(&lk);
10179 }
10180
10181
10182 /*
10183  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10184  * map.  Any dependencies waiting for the write to clear are added to the
10185  * buf's list and any jnewblks that are being canceled are discarded
10186  * immediately.
10187  */
10188 void
10189 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10190         struct mount *mp;
10191         struct buf *bp;
10192         ufs2_daddr_t blkno;
10193         int frags;
10194         struct workhead *wkhd;
10195 {
10196         struct bmsafemap *bmsafemap;
10197         struct jnewblk *jnewblk;
10198         struct worklist *wk;
10199         struct fs *fs;
10200 #ifdef SUJ_DEBUG
10201         uint8_t *blksfree;
10202         struct cg *cgp;
10203         ufs2_daddr_t jstart;
10204         ufs2_daddr_t jend;
10205         ufs2_daddr_t end;
10206         long bno;
10207         int i;
10208 #endif
10209
10210         ACQUIRE_LOCK(&lk);
10211         /* Lookup the bmsafemap so we track when it is dirty. */
10212         fs = VFSTOUFS(mp)->um_fs;
10213         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno));
10214         /*
10215          * Detach any jnewblks which have been canceled.  They must linger
10216          * until the bitmap is cleared again by ffs_blkfree() to prevent
10217          * an unjournaled allocation from hitting the disk.
10218          */
10219         if (wkhd) {
10220                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10221                         WORKLIST_REMOVE(wk);
10222                         if (wk->wk_type != D_JNEWBLK) {
10223                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10224                                 continue;
10225                         }
10226                         jnewblk = WK_JNEWBLK(wk);
10227                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10228                             ("softdep_setup_blkfree: jnewblk not canceled."));
10229 #ifdef SUJ_DEBUG
10230                         /*
10231                          * Assert that this block is free in the bitmap
10232                          * before we discard the jnewblk.
10233                          */
10234                         cgp = (struct cg *)bp->b_data;
10235                         blksfree = cg_blksfree(cgp);
10236                         bno = dtogd(fs, jnewblk->jn_blkno);
10237                         for (i = jnewblk->jn_oldfrags;
10238                             i < jnewblk->jn_frags; i++) {
10239                                 if (isset(blksfree, bno + i))
10240                                         continue;
10241                                 panic("softdep_setup_blkfree: not free");
10242                         }
10243 #endif
10244                         /*
10245                          * Even if it's not attached we can free immediately
10246                          * as the new bitmap is correct.
10247                          */
10248                         wk->wk_state |= COMPLETE | ATTACHED;
10249                         free_jnewblk(jnewblk);
10250                 }
10251         }
10252
10253 #ifdef SUJ_DEBUG
10254         /*
10255          * Assert that we are not freeing a block which has an outstanding
10256          * allocation dependency.
10257          */
10258         fs = VFSTOUFS(mp)->um_fs;
10259         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno));
10260         end = blkno + frags;
10261         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10262                 /*
10263                  * Don't match against blocks that will be freed when the
10264                  * background write is done.
10265                  */
10266                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10267                     (COMPLETE | DEPCOMPLETE))
10268                         continue;
10269                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10270                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10271                 if ((blkno >= jstart && blkno < jend) ||
10272                     (end > jstart && end <= jend)) {
10273                         printf("state 0x%X %jd - %d %d dep %p\n",
10274                             jnewblk->jn_state, jnewblk->jn_blkno,
10275                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10276                             jnewblk->jn_dep);
10277                         panic("softdep_setup_blkfree: "
10278                             "%jd-%jd(%d) overlaps with %jd-%jd",
10279                             blkno, end, frags, jstart, jend);
10280                 }
10281         }
10282 #endif
10283         FREE_LOCK(&lk);
10284 }
10285
10286 /*
10287  * Revert a block allocation when the journal record that describes it
10288  * is not yet written.
10289  */
10290 int
10291 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10292         struct jnewblk *jnewblk;
10293         struct fs *fs;
10294         struct cg *cgp;
10295         uint8_t *blksfree;
10296 {
10297         ufs1_daddr_t fragno;
10298         long cgbno, bbase;
10299         int frags, blk;
10300         int i;
10301
10302         frags = 0;
10303         cgbno = dtogd(fs, jnewblk->jn_blkno);
10304         /*
10305          * We have to test which frags need to be rolled back.  We may
10306          * be operating on a stale copy when doing background writes.
10307          */
10308         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10309                 if (isclr(blksfree, cgbno + i))
10310                         frags++;
10311         if (frags == 0)
10312                 return (0);
10313         /*
10314          * This is mostly ffs_blkfree() sans some validation and
10315          * superblock updates.
10316          */
10317         if (frags == fs->fs_frag) {
10318                 fragno = fragstoblks(fs, cgbno);
10319                 ffs_setblock(fs, blksfree, fragno);
10320                 ffs_clusteracct(fs, cgp, fragno, 1);
10321                 cgp->cg_cs.cs_nbfree++;
10322         } else {
10323                 cgbno += jnewblk->jn_oldfrags;
10324                 bbase = cgbno - fragnum(fs, cgbno);
10325                 /* Decrement the old frags.  */
10326                 blk = blkmap(fs, blksfree, bbase);
10327                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10328                 /* Deallocate the fragment */
10329                 for (i = 0; i < frags; i++)
10330                         setbit(blksfree, cgbno + i);
10331                 cgp->cg_cs.cs_nffree += frags;
10332                 /* Add back in counts associated with the new frags */
10333                 blk = blkmap(fs, blksfree, bbase);
10334                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10335                 /* If a complete block has been reassembled, account for it. */
10336                 fragno = fragstoblks(fs, bbase);
10337                 if (ffs_isblock(fs, blksfree, fragno)) {
10338                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10339                         ffs_clusteracct(fs, cgp, fragno, 1);
10340                         cgp->cg_cs.cs_nbfree++;
10341                 }
10342         }
10343         stat_jnewblk++;
10344         jnewblk->jn_state &= ~ATTACHED;
10345         jnewblk->jn_state |= UNDONE;
10346
10347         return (frags);
10348 }
10349
10350 static void 
10351 initiate_write_bmsafemap(bmsafemap, bp)
10352         struct bmsafemap *bmsafemap;
10353         struct buf *bp;                 /* The cg block. */
10354 {
10355         struct jaddref *jaddref;
10356         struct jnewblk *jnewblk;
10357         uint8_t *inosused;
10358         uint8_t *blksfree;
10359         struct cg *cgp;
10360         struct fs *fs;
10361         ino_t ino;
10362
10363         if (bmsafemap->sm_state & IOSTARTED)
10364                 panic("initiate_write_bmsafemap: Already started\n");
10365         bmsafemap->sm_state |= IOSTARTED;
10366         /*
10367          * Clear any inode allocations which are pending journal writes.
10368          */
10369         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10370                 cgp = (struct cg *)bp->b_data;
10371                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10372                 inosused = cg_inosused(cgp);
10373                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10374                         ino = jaddref->ja_ino % fs->fs_ipg;
10375                         /*
10376                          * If this is a background copy the inode may not
10377                          * be marked used yet.
10378                          */
10379                         if (isset(inosused, ino)) {
10380                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10381                                         cgp->cg_cs.cs_ndir--;
10382                                 cgp->cg_cs.cs_nifree++;
10383                                 clrbit(inosused, ino);
10384                                 jaddref->ja_state &= ~ATTACHED;
10385                                 jaddref->ja_state |= UNDONE;
10386                                 stat_jaddref++;
10387                         } else if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
10388                                 panic("initiate_write_bmsafemap: inode %d "
10389                                     "marked free", jaddref->ja_ino);
10390                 }
10391         }
10392         /*
10393          * Clear any block allocations which are pending journal writes.
10394          */
10395         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10396                 cgp = (struct cg *)bp->b_data;
10397                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10398                 blksfree = cg_blksfree(cgp);
10399                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10400                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10401                                 continue;
10402                         if ((bp->b_xflags & BX_BKGRDMARKER) == 0)
10403                                 panic("initiate_write_bmsafemap: block %jd "
10404                                     "marked free", jnewblk->jn_blkno);
10405                 }
10406         }
10407         /*
10408          * Move allocation lists to the written lists so they can be
10409          * cleared once the block write is complete.
10410          */
10411         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10412             inodedep, id_deps);
10413         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10414             newblk, nb_deps);
10415         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10416             wk_list);
10417 }
10418
10419 /*
10420  * This routine is called during the completion interrupt
10421  * service routine for a disk write (from the procedure called
10422  * by the device driver to inform the filesystem caches of
10423  * a request completion).  It should be called early in this
10424  * procedure, before the block is made available to other
10425  * processes or other routines are called.
10426  *
10427  */
10428 static void 
10429 softdep_disk_write_complete(bp)
10430         struct buf *bp;         /* describes the completed disk write */
10431 {
10432         struct worklist *wk;
10433         struct worklist *owk;
10434         struct workhead reattach;
10435         struct freeblks *freeblks;
10436         struct buf *sbp;
10437
10438         /*
10439          * If an error occurred while doing the write, then the data
10440          * has not hit the disk and the dependencies cannot be unrolled.
10441          */
10442         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10443                 return;
10444         LIST_INIT(&reattach);
10445         /*
10446          * This lock must not be released anywhere in this code segment.
10447          */
10448         sbp = NULL;
10449         owk = NULL;
10450         ACQUIRE_LOCK(&lk);
10451         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10452                 WORKLIST_REMOVE(wk);
10453                 dep_write[wk->wk_type]++;
10454                 if (wk == owk)
10455                         panic("duplicate worklist: %p\n", wk);
10456                 owk = wk;
10457                 switch (wk->wk_type) {
10458
10459                 case D_PAGEDEP:
10460                         if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10461                                 WORKLIST_INSERT(&reattach, wk);
10462                         continue;
10463
10464                 case D_INODEDEP:
10465                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10466                                 WORKLIST_INSERT(&reattach, wk);
10467                         continue;
10468
10469                 case D_BMSAFEMAP:
10470                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10471                                 WORKLIST_INSERT(&reattach, wk);
10472                         continue;
10473
10474                 case D_MKDIR:
10475                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10476                         continue;
10477
10478                 case D_ALLOCDIRECT:
10479                         wk->wk_state |= COMPLETE;
10480                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
10481                         continue;
10482
10483                 case D_ALLOCINDIR:
10484                         wk->wk_state |= COMPLETE;
10485                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
10486                         continue;
10487
10488                 case D_INDIRDEP:
10489                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
10490                                 WORKLIST_INSERT(&reattach, wk);
10491                         continue;
10492
10493                 case D_FREEBLKS:
10494                         wk->wk_state |= COMPLETE;
10495                         freeblks = WK_FREEBLKS(wk);
10496                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
10497                             LIST_EMPTY(&freeblks->fb_jblkdephd))
10498                                 add_to_worklist(wk, WK_NODELAY);
10499                         continue;
10500
10501                 case D_FREEWORK:
10502                         handle_written_freework(WK_FREEWORK(wk));
10503                         break;
10504
10505                 case D_JSEGDEP:
10506                         free_jsegdep(WK_JSEGDEP(wk));
10507                         continue;
10508
10509                 case D_JSEG:
10510                         handle_written_jseg(WK_JSEG(wk), bp);
10511                         continue;
10512
10513                 case D_SBDEP:
10514                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
10515                                 WORKLIST_INSERT(&reattach, wk);
10516                         continue;
10517
10518                 case D_FREEDEP:
10519                         free_freedep(WK_FREEDEP(wk));
10520                         continue;
10521
10522                 default:
10523                         panic("handle_disk_write_complete: Unknown type %s",
10524                             TYPENAME(wk->wk_type));
10525                         /* NOTREACHED */
10526                 }
10527         }
10528         /*
10529          * Reattach any requests that must be redone.
10530          */
10531         while ((wk = LIST_FIRST(&reattach)) != NULL) {
10532                 WORKLIST_REMOVE(wk);
10533                 WORKLIST_INSERT(&bp->b_dep, wk);
10534         }
10535         FREE_LOCK(&lk);
10536         if (sbp)
10537                 brelse(sbp);
10538 }
10539
10540 /*
10541  * Called from within softdep_disk_write_complete above. Note that
10542  * this routine is always called from interrupt level with further
10543  * splbio interrupts blocked.
10544  */
10545 static void 
10546 handle_allocdirect_partdone(adp, wkhd)
10547         struct allocdirect *adp;        /* the completed allocdirect */
10548         struct workhead *wkhd;          /* Work to do when inode is writtne. */
10549 {
10550         struct allocdirectlst *listhead;
10551         struct allocdirect *listadp;
10552         struct inodedep *inodedep;
10553         long bsize;
10554
10555         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10556                 return;
10557         /*
10558          * The on-disk inode cannot claim to be any larger than the last
10559          * fragment that has been written. Otherwise, the on-disk inode
10560          * might have fragments that were not the last block in the file
10561          * which would corrupt the filesystem. Thus, we cannot free any
10562          * allocdirects after one whose ad_oldblkno claims a fragment as
10563          * these blocks must be rolled back to zero before writing the inode.
10564          * We check the currently active set of allocdirects in id_inoupdt
10565          * or id_extupdt as appropriate.
10566          */
10567         inodedep = adp->ad_inodedep;
10568         bsize = inodedep->id_fs->fs_bsize;
10569         if (adp->ad_state & EXTDATA)
10570                 listhead = &inodedep->id_extupdt;
10571         else
10572                 listhead = &inodedep->id_inoupdt;
10573         TAILQ_FOREACH(listadp, listhead, ad_next) {
10574                 /* found our block */
10575                 if (listadp == adp)
10576                         break;
10577                 /* continue if ad_oldlbn is not a fragment */
10578                 if (listadp->ad_oldsize == 0 ||
10579                     listadp->ad_oldsize == bsize)
10580                         continue;
10581                 /* hit a fragment */
10582                 return;
10583         }
10584         /*
10585          * If we have reached the end of the current list without
10586          * finding the just finished dependency, then it must be
10587          * on the future dependency list. Future dependencies cannot
10588          * be freed until they are moved to the current list.
10589          */
10590         if (listadp == NULL) {
10591 #ifdef DEBUG
10592                 if (adp->ad_state & EXTDATA)
10593                         listhead = &inodedep->id_newextupdt;
10594                 else
10595                         listhead = &inodedep->id_newinoupdt;
10596                 TAILQ_FOREACH(listadp, listhead, ad_next)
10597                         /* found our block */
10598                         if (listadp == adp)
10599                                 break;
10600                 if (listadp == NULL)
10601                         panic("handle_allocdirect_partdone: lost dep");
10602 #endif /* DEBUG */
10603                 return;
10604         }
10605         /*
10606          * If we have found the just finished dependency, then queue
10607          * it along with anything that follows it that is complete.
10608          * Since the pointer has not yet been written in the inode
10609          * as the dependency prevents it, place the allocdirect on the
10610          * bufwait list where it will be freed once the pointer is
10611          * valid.
10612          */
10613         if (wkhd == NULL)
10614                 wkhd = &inodedep->id_bufwait;
10615         for (; adp; adp = listadp) {
10616                 listadp = TAILQ_NEXT(adp, ad_next);
10617                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
10618                         return;
10619                 TAILQ_REMOVE(listhead, adp, ad_next);
10620                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
10621         }
10622 }
10623
10624 /*
10625  * Called from within softdep_disk_write_complete above.  This routine
10626  * completes successfully written allocindirs.
10627  */
10628 static void
10629 handle_allocindir_partdone(aip)
10630         struct allocindir *aip;         /* the completed allocindir */
10631 {
10632         struct indirdep *indirdep;
10633
10634         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
10635                 return;
10636         indirdep = aip->ai_indirdep;
10637         LIST_REMOVE(aip, ai_next);
10638         /*
10639          * Don't set a pointer while the buffer is undergoing IO or while
10640          * we have active truncations.
10641          */
10642         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
10643                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
10644                 return;
10645         }
10646         if (indirdep->ir_state & UFS1FMT)
10647                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10648                     aip->ai_newblkno;
10649         else
10650                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
10651                     aip->ai_newblkno;
10652         /*
10653          * Await the pointer write before freeing the allocindir.
10654          */
10655         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
10656 }
10657
10658 /*
10659  * Release segments held on a jwork list.
10660  */
10661 static void
10662 handle_jwork(wkhd)
10663         struct workhead *wkhd;
10664 {
10665         struct worklist *wk;
10666
10667         while ((wk = LIST_FIRST(wkhd)) != NULL) {
10668                 WORKLIST_REMOVE(wk);
10669                 switch (wk->wk_type) {
10670                 case D_JSEGDEP:
10671                         free_jsegdep(WK_JSEGDEP(wk));
10672                         continue;
10673                 case D_FREEDEP:
10674                         free_freedep(WK_FREEDEP(wk));
10675                         continue;
10676                 case D_FREEFRAG:
10677                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
10678                         WORKITEM_FREE(wk, D_FREEFRAG);
10679                 case D_FREEWORK:
10680                         handle_written_freework(WK_FREEWORK(wk));
10681                         continue;
10682                 default:
10683                         panic("handle_jwork: Unknown type %s\n",
10684                             TYPENAME(wk->wk_type));
10685                 }
10686         }
10687 }
10688
10689 /*
10690  * Handle the bufwait list on an inode when it is safe to release items
10691  * held there.  This normally happens after an inode block is written but
10692  * may be delayed and handled later if there are pending journal items that
10693  * are not yet safe to be released.
10694  */
10695 static struct freefile *
10696 handle_bufwait(inodedep, refhd)
10697         struct inodedep *inodedep;
10698         struct workhead *refhd;
10699 {
10700         struct jaddref *jaddref;
10701         struct freefile *freefile;
10702         struct worklist *wk;
10703
10704         freefile = NULL;
10705         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
10706                 WORKLIST_REMOVE(wk);
10707                 switch (wk->wk_type) {
10708                 case D_FREEFILE:
10709                         /*
10710                          * We defer adding freefile to the worklist
10711                          * until all other additions have been made to
10712                          * ensure that it will be done after all the
10713                          * old blocks have been freed.
10714                          */
10715                         if (freefile != NULL)
10716                                 panic("handle_bufwait: freefile");
10717                         freefile = WK_FREEFILE(wk);
10718                         continue;
10719
10720                 case D_MKDIR:
10721                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
10722                         continue;
10723
10724                 case D_DIRADD:
10725                         diradd_inode_written(WK_DIRADD(wk), inodedep);
10726                         continue;
10727
10728                 case D_FREEFRAG:
10729                         wk->wk_state |= COMPLETE;
10730                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
10731                                 add_to_worklist(wk, 0);
10732                         continue;
10733
10734                 case D_DIRREM:
10735                         wk->wk_state |= COMPLETE;
10736                         add_to_worklist(wk, 0);
10737                         continue;
10738
10739                 case D_ALLOCDIRECT:
10740                 case D_ALLOCINDIR:
10741                         free_newblk(WK_NEWBLK(wk));
10742                         continue;
10743
10744                 case D_JNEWBLK:
10745                         wk->wk_state |= COMPLETE;
10746                         free_jnewblk(WK_JNEWBLK(wk));
10747                         continue;
10748
10749                 /*
10750                  * Save freed journal segments and add references on
10751                  * the supplied list which will delay their release
10752                  * until the cg bitmap is cleared on disk.
10753                  */
10754                 case D_JSEGDEP:
10755                         if (refhd == NULL)
10756                                 free_jsegdep(WK_JSEGDEP(wk));
10757                         else
10758                                 WORKLIST_INSERT(refhd, wk);
10759                         continue;
10760
10761                 case D_JADDREF:
10762                         jaddref = WK_JADDREF(wk);
10763                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
10764                             if_deps);
10765                         /*
10766                          * Transfer any jaddrefs to the list to be freed with
10767                          * the bitmap if we're handling a removed file.
10768                          */
10769                         if (refhd == NULL) {
10770                                 wk->wk_state |= COMPLETE;
10771                                 free_jaddref(jaddref);
10772                         } else
10773                                 WORKLIST_INSERT(refhd, wk);
10774                         continue;
10775
10776                 default:
10777                         panic("handle_bufwait: Unknown type %p(%s)",
10778                             wk, TYPENAME(wk->wk_type));
10779                         /* NOTREACHED */
10780                 }
10781         }
10782         return (freefile);
10783 }
10784 /*
10785  * Called from within softdep_disk_write_complete above to restore
10786  * in-memory inode block contents to their most up-to-date state. Note
10787  * that this routine is always called from interrupt level with further
10788  * splbio interrupts blocked.
10789  */
10790 static int 
10791 handle_written_inodeblock(inodedep, bp)
10792         struct inodedep *inodedep;
10793         struct buf *bp;         /* buffer containing the inode block */
10794 {
10795         struct freefile *freefile;
10796         struct allocdirect *adp, *nextadp;
10797         struct ufs1_dinode *dp1 = NULL;
10798         struct ufs2_dinode *dp2 = NULL;
10799         struct workhead wkhd;
10800         int hadchanges, fstype;
10801         ino_t freelink;
10802
10803         LIST_INIT(&wkhd);
10804         hadchanges = 0;
10805         freefile = NULL;
10806         if ((inodedep->id_state & IOSTARTED) == 0)
10807                 panic("handle_written_inodeblock: not started");
10808         inodedep->id_state &= ~IOSTARTED;
10809         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
10810                 fstype = UFS1;
10811                 dp1 = (struct ufs1_dinode *)bp->b_data +
10812                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
10813                 freelink = dp1->di_freelink;
10814         } else {
10815                 fstype = UFS2;
10816                 dp2 = (struct ufs2_dinode *)bp->b_data +
10817                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
10818                 freelink = dp2->di_freelink;
10819         }
10820         /*
10821          * If we wrote a valid freelink pointer during the last write
10822          * record it here.
10823          */
10824         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10825                 struct inodedep *inon;
10826
10827                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10828                 if ((inon == NULL && freelink == 0) ||
10829                     (inon && inon->id_ino == freelink)) {
10830                         if (inon)
10831                                 inon->id_state |= UNLINKPREV;
10832                         inodedep->id_state |= UNLINKNEXT;
10833                 } else
10834                         hadchanges = 1;
10835         }
10836         /* Leave this inodeblock dirty until it's in the list. */
10837         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED)
10838                 hadchanges = 1;
10839         /*
10840          * If we had to rollback the inode allocation because of
10841          * bitmaps being incomplete, then simply restore it.
10842          * Keep the block dirty so that it will not be reclaimed until
10843          * all associated dependencies have been cleared and the
10844          * corresponding updates written to disk.
10845          */
10846         if (inodedep->id_savedino1 != NULL) {
10847                 hadchanges = 1;
10848                 if (fstype == UFS1)
10849                         *dp1 = *inodedep->id_savedino1;
10850                 else
10851                         *dp2 = *inodedep->id_savedino2;
10852                 free(inodedep->id_savedino1, M_SAVEDINO);
10853                 inodedep->id_savedino1 = NULL;
10854                 if ((bp->b_flags & B_DELWRI) == 0)
10855                         stat_inode_bitmap++;
10856                 bdirty(bp);
10857                 /*
10858                  * If the inode is clear here and GOINGAWAY it will never
10859                  * be written.  Process the bufwait and clear any pending
10860                  * work which may include the freefile.
10861                  */
10862                 if (inodedep->id_state & GOINGAWAY)
10863                         goto bufwait;
10864                 return (1);
10865         }
10866         inodedep->id_state |= COMPLETE;
10867         /*
10868          * Roll forward anything that had to be rolled back before 
10869          * the inode could be updated.
10870          */
10871         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
10872                 nextadp = TAILQ_NEXT(adp, ad_next);
10873                 if (adp->ad_state & ATTACHED)
10874                         panic("handle_written_inodeblock: new entry");
10875                 if (fstype == UFS1) {
10876                         if (adp->ad_offset < NDADDR) {
10877                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
10878                                         panic("%s %s #%jd mismatch %d != %jd",
10879                                             "handle_written_inodeblock:",
10880                                             "direct pointer",
10881                                             (intmax_t)adp->ad_offset,
10882                                             dp1->di_db[adp->ad_offset],
10883                                             (intmax_t)adp->ad_oldblkno);
10884                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
10885                         } else {
10886                                 if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
10887                                         panic("%s: %s #%jd allocated as %d",
10888                                             "handle_written_inodeblock",
10889                                             "indirect pointer",
10890                                             (intmax_t)adp->ad_offset - NDADDR,
10891                                             dp1->di_ib[adp->ad_offset - NDADDR]);
10892                                 dp1->di_ib[adp->ad_offset - NDADDR] =
10893                                     adp->ad_newblkno;
10894                         }
10895                 } else {
10896                         if (adp->ad_offset < NDADDR) {
10897                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
10898                                         panic("%s: %s #%jd %s %jd != %jd",
10899                                             "handle_written_inodeblock",
10900                                             "direct pointer",
10901                                             (intmax_t)adp->ad_offset, "mismatch",
10902                                             (intmax_t)dp2->di_db[adp->ad_offset],
10903                                             (intmax_t)adp->ad_oldblkno);
10904                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
10905                         } else {
10906                                 if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
10907                                         panic("%s: %s #%jd allocated as %jd",
10908                                             "handle_written_inodeblock",
10909                                             "indirect pointer",
10910                                             (intmax_t)adp->ad_offset - NDADDR,
10911                                             (intmax_t)
10912                                             dp2->di_ib[adp->ad_offset - NDADDR]);
10913                                 dp2->di_ib[adp->ad_offset - NDADDR] =
10914                                     adp->ad_newblkno;
10915                         }
10916                 }
10917                 adp->ad_state &= ~UNDONE;
10918                 adp->ad_state |= ATTACHED;
10919                 hadchanges = 1;
10920         }
10921         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
10922                 nextadp = TAILQ_NEXT(adp, ad_next);
10923                 if (adp->ad_state & ATTACHED)
10924                         panic("handle_written_inodeblock: new entry");
10925                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
10926                         panic("%s: direct pointers #%jd %s %jd != %jd",
10927                             "handle_written_inodeblock",
10928                             (intmax_t)adp->ad_offset, "mismatch",
10929                             (intmax_t)dp2->di_extb[adp->ad_offset],
10930                             (intmax_t)adp->ad_oldblkno);
10931                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
10932                 adp->ad_state &= ~UNDONE;
10933                 adp->ad_state |= ATTACHED;
10934                 hadchanges = 1;
10935         }
10936         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
10937                 stat_direct_blk_ptrs++;
10938         /*
10939          * Reset the file size to its most up-to-date value.
10940          */
10941         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
10942                 panic("handle_written_inodeblock: bad size");
10943         if (inodedep->id_savednlink > LINK_MAX)
10944                 panic("handle_written_inodeblock: Invalid link count "
10945                     "%d for inodedep %p", inodedep->id_savednlink, inodedep);
10946         if (fstype == UFS1) {
10947                 if (dp1->di_nlink != inodedep->id_savednlink) { 
10948                         dp1->di_nlink = inodedep->id_savednlink;
10949                         hadchanges = 1;
10950                 }
10951                 if (dp1->di_size != inodedep->id_savedsize) {
10952                         dp1->di_size = inodedep->id_savedsize;
10953                         hadchanges = 1;
10954                 }
10955         } else {
10956                 if (dp2->di_nlink != inodedep->id_savednlink) { 
10957                         dp2->di_nlink = inodedep->id_savednlink;
10958                         hadchanges = 1;
10959                 }
10960                 if (dp2->di_size != inodedep->id_savedsize) {
10961                         dp2->di_size = inodedep->id_savedsize;
10962                         hadchanges = 1;
10963                 }
10964                 if (dp2->di_extsize != inodedep->id_savedextsize) {
10965                         dp2->di_extsize = inodedep->id_savedextsize;
10966                         hadchanges = 1;
10967                 }
10968         }
10969         inodedep->id_savedsize = -1;
10970         inodedep->id_savedextsize = -1;
10971         inodedep->id_savednlink = -1;
10972         /*
10973          * If there were any rollbacks in the inode block, then it must be
10974          * marked dirty so that its will eventually get written back in
10975          * its correct form.
10976          */
10977         if (hadchanges)
10978                 bdirty(bp);
10979 bufwait:
10980         /*
10981          * Process any allocdirects that completed during the update.
10982          */
10983         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
10984                 handle_allocdirect_partdone(adp, &wkhd);
10985         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
10986                 handle_allocdirect_partdone(adp, &wkhd);
10987         /*
10988          * Process deallocations that were held pending until the
10989          * inode had been written to disk. Freeing of the inode
10990          * is delayed until after all blocks have been freed to
10991          * avoid creation of new <vfsid, inum, lbn> triples
10992          * before the old ones have been deleted.  Completely
10993          * unlinked inodes are not processed until the unlinked
10994          * inode list is written or the last reference is removed.
10995          */
10996         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
10997                 freefile = handle_bufwait(inodedep, NULL);
10998                 if (freefile && !LIST_EMPTY(&wkhd)) {
10999                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11000                         freefile = NULL;
11001                 }
11002         }
11003         /*
11004          * Move rolled forward dependency completions to the bufwait list
11005          * now that those that were already written have been processed.
11006          */
11007         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11008                 panic("handle_written_inodeblock: bufwait but no changes");
11009         jwork_move(&inodedep->id_bufwait, &wkhd);
11010
11011         if (freefile != NULL) {
11012                 /*
11013                  * If the inode is goingaway it was never written.  Fake up
11014                  * the state here so free_inodedep() can succeed.
11015                  */
11016                 if (inodedep->id_state & GOINGAWAY)
11017                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11018                 if (free_inodedep(inodedep) == 0)
11019                         panic("handle_written_inodeblock: live inodedep %p",
11020                             inodedep);
11021                 add_to_worklist(&freefile->fx_list, 0);
11022                 return (0);
11023         }
11024
11025         /*
11026          * If no outstanding dependencies, free it.
11027          */
11028         if (free_inodedep(inodedep) ||
11029             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11030              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11031              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11032              LIST_FIRST(&inodedep->id_bufwait) == 0))
11033                 return (0);
11034         return (hadchanges);
11035 }
11036
11037 static int
11038 handle_written_indirdep(indirdep, bp, bpp)
11039         struct indirdep *indirdep;
11040         struct buf *bp;
11041         struct buf **bpp;
11042 {
11043         struct allocindir *aip;
11044         struct buf *sbp;
11045         int chgs;
11046
11047         if (indirdep->ir_state & GOINGAWAY)
11048                 panic("handle_written_indirdep: indirdep gone");
11049         if ((indirdep->ir_state & IOSTARTED) == 0)
11050                 panic("handle_written_indirdep: IO not started");
11051         chgs = 0;
11052         /*
11053          * If there were rollbacks revert them here.
11054          */
11055         if (indirdep->ir_saveddata) {
11056                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11057                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11058                         free(indirdep->ir_saveddata, M_INDIRDEP);
11059                         indirdep->ir_saveddata = NULL;
11060                 }
11061                 chgs = 1;
11062         }
11063         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11064         indirdep->ir_state |= ATTACHED;
11065         /*
11066          * Move allocindirs with written pointers to the completehd if
11067          * the indirdep's pointer is not yet written.  Otherwise
11068          * free them here.
11069          */
11070         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11071                 LIST_REMOVE(aip, ai_next);
11072                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11073                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11074                             ai_next);
11075                         newblk_freefrag(&aip->ai_block);
11076                         continue;
11077                 }
11078                 free_newblk(&aip->ai_block);
11079         }
11080         /*
11081          * Move allocindirs that have finished dependency processing from
11082          * the done list to the write list after updating the pointers.
11083          */
11084         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11085                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11086                         handle_allocindir_partdone(aip);
11087                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11088                                 panic("disk_write_complete: not gone");
11089                         chgs = 1;
11090                 }
11091         }
11092         /*
11093          * Preserve the indirdep if there were any changes or if it is not
11094          * yet valid on disk.
11095          */
11096         if (chgs) {
11097                 stat_indir_blk_ptrs++;
11098                 bdirty(bp);
11099                 return (1);
11100         }
11101         /*
11102          * If there were no changes we can discard the savedbp and detach
11103          * ourselves from the buf.  We are only carrying completed pointers
11104          * in this case.
11105          */
11106         sbp = indirdep->ir_savebp;
11107         sbp->b_flags |= B_INVAL | B_NOCACHE;
11108         indirdep->ir_savebp = NULL;
11109         indirdep->ir_bp = NULL;
11110         if (*bpp != NULL)
11111                 panic("handle_written_indirdep: bp already exists.");
11112         *bpp = sbp;
11113         /*
11114          * The indirdep may not be freed until its parent points at it.
11115          */
11116         if (indirdep->ir_state & DEPCOMPLETE)
11117                 free_indirdep(indirdep);
11118
11119         return (0);
11120 }
11121
11122 /*
11123  * Process a diradd entry after its dependent inode has been written.
11124  * This routine must be called with splbio interrupts blocked.
11125  */
11126 static void
11127 diradd_inode_written(dap, inodedep)
11128         struct diradd *dap;
11129         struct inodedep *inodedep;
11130 {
11131
11132         dap->da_state |= COMPLETE;
11133         complete_diradd(dap);
11134         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11135 }
11136
11137 /*
11138  * Returns true if the bmsafemap will have rollbacks when written.  Must
11139  * only be called with lk and the buf lock on the cg held.
11140  */
11141 static int
11142 bmsafemap_rollbacks(bmsafemap)
11143         struct bmsafemap *bmsafemap;
11144 {
11145
11146         return (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11147             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd));
11148 }
11149
11150 /*
11151  * Re-apply an allocation when a cg write is complete.
11152  */
11153 static int
11154 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11155         struct jnewblk *jnewblk;
11156         struct fs *fs;
11157         struct cg *cgp;
11158         uint8_t *blksfree;
11159 {
11160         ufs1_daddr_t fragno;
11161         ufs2_daddr_t blkno;
11162         long cgbno, bbase;
11163         int frags, blk;
11164         int i;
11165
11166         frags = 0;
11167         cgbno = dtogd(fs, jnewblk->jn_blkno);
11168         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11169                 if (isclr(blksfree, cgbno + i))
11170                         panic("jnewblk_rollforward: re-allocated fragment");
11171                 frags++;
11172         }
11173         if (frags == fs->fs_frag) {
11174                 blkno = fragstoblks(fs, cgbno);
11175                 ffs_clrblock(fs, blksfree, (long)blkno);
11176                 ffs_clusteracct(fs, cgp, blkno, -1);
11177                 cgp->cg_cs.cs_nbfree--;
11178         } else {
11179                 bbase = cgbno - fragnum(fs, cgbno);
11180                 cgbno += jnewblk->jn_oldfrags;
11181                 /* If a complete block had been reassembled, account for it. */
11182                 fragno = fragstoblks(fs, bbase);
11183                 if (ffs_isblock(fs, blksfree, fragno)) {
11184                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11185                         ffs_clusteracct(fs, cgp, fragno, -1);
11186                         cgp->cg_cs.cs_nbfree--;
11187                 }
11188                 /* Decrement the old frags.  */
11189                 blk = blkmap(fs, blksfree, bbase);
11190                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11191                 /* Allocate the fragment */
11192                 for (i = 0; i < frags; i++)
11193                         clrbit(blksfree, cgbno + i);
11194                 cgp->cg_cs.cs_nffree -= frags;
11195                 /* Add back in counts associated with the new frags */
11196                 blk = blkmap(fs, blksfree, bbase);
11197                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11198         }
11199         return (frags);
11200 }
11201
11202 /*
11203  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11204  * changes if it's not a background write.  Set all written dependencies 
11205  * to DEPCOMPLETE and free the structure if possible.
11206  */
11207 static int
11208 handle_written_bmsafemap(bmsafemap, bp)
11209         struct bmsafemap *bmsafemap;
11210         struct buf *bp;
11211 {
11212         struct newblk *newblk;
11213         struct inodedep *inodedep;
11214         struct jaddref *jaddref, *jatmp;
11215         struct jnewblk *jnewblk, *jntmp;
11216         struct ufsmount *ump;
11217         uint8_t *inosused;
11218         uint8_t *blksfree;
11219         struct cg *cgp;
11220         struct fs *fs;
11221         ino_t ino;
11222         int chgs;
11223
11224         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11225                 panic("initiate_write_bmsafemap: Not started\n");
11226         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11227         chgs = 0;
11228         bmsafemap->sm_state &= ~IOSTARTED;
11229         /*
11230          * Release journal work that was waiting on the write.
11231          */
11232         handle_jwork(&bmsafemap->sm_freewr);
11233
11234         /*
11235          * Restore unwritten inode allocation pending jaddref writes.
11236          */
11237         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11238                 cgp = (struct cg *)bp->b_data;
11239                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11240                 inosused = cg_inosused(cgp);
11241                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11242                     ja_bmdeps, jatmp) {
11243                         if ((jaddref->ja_state & UNDONE) == 0)
11244                                 continue;
11245                         ino = jaddref->ja_ino % fs->fs_ipg;
11246                         if (isset(inosused, ino))
11247                                 panic("handle_written_bmsafemap: "
11248                                     "re-allocated inode");
11249                         if ((bp->b_xflags & BX_BKGRDMARKER) == 0) {
11250                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11251                                         cgp->cg_cs.cs_ndir++;
11252                                 cgp->cg_cs.cs_nifree--;
11253                                 setbit(inosused, ino);
11254                                 chgs = 1;
11255                         }
11256                         jaddref->ja_state &= ~UNDONE;
11257                         jaddref->ja_state |= ATTACHED;
11258                         free_jaddref(jaddref);
11259                 }
11260         }
11261         /*
11262          * Restore any block allocations which are pending journal writes.
11263          */
11264         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11265                 cgp = (struct cg *)bp->b_data;
11266                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11267                 blksfree = cg_blksfree(cgp);
11268                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11269                     jntmp) {
11270                         if ((jnewblk->jn_state & UNDONE) == 0)
11271                                 continue;
11272                         if ((bp->b_xflags & BX_BKGRDMARKER) == 0 &&
11273                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11274                                 chgs = 1;
11275                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11276                         jnewblk->jn_state |= ATTACHED;
11277                         free_jnewblk(jnewblk);
11278                 }
11279         }
11280         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11281                 newblk->nb_state |= DEPCOMPLETE;
11282                 newblk->nb_state &= ~ONDEPLIST;
11283                 newblk->nb_bmsafemap = NULL;
11284                 LIST_REMOVE(newblk, nb_deps);
11285                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11286                         handle_allocdirect_partdone(
11287                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11288                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11289                         handle_allocindir_partdone(
11290                             WK_ALLOCINDIR(&newblk->nb_list));
11291                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11292                         panic("handle_written_bmsafemap: Unexpected type: %s",
11293                             TYPENAME(newblk->nb_list.wk_type));
11294         }
11295         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11296                 inodedep->id_state |= DEPCOMPLETE;
11297                 inodedep->id_state &= ~ONDEPLIST;
11298                 LIST_REMOVE(inodedep, id_deps);
11299                 inodedep->id_bmsafemap = NULL;
11300         }
11301         LIST_REMOVE(bmsafemap, sm_next);
11302         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11303             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11304             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11305             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11306             LIST_EMPTY(&bmsafemap->sm_freehd)) {
11307                 LIST_REMOVE(bmsafemap, sm_hash);
11308                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11309                 return (0);
11310         }
11311         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11312         bdirty(bp);
11313         return (1);
11314 }
11315
11316 /*
11317  * Try to free a mkdir dependency.
11318  */
11319 static void
11320 complete_mkdir(mkdir)
11321         struct mkdir *mkdir;
11322 {
11323         struct diradd *dap;
11324
11325         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11326                 return;
11327         LIST_REMOVE(mkdir, md_mkdirs);
11328         dap = mkdir->md_diradd;
11329         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11330         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11331                 dap->da_state |= DEPCOMPLETE;
11332                 complete_diradd(dap);
11333         }
11334         WORKITEM_FREE(mkdir, D_MKDIR);
11335 }
11336
11337 /*
11338  * Handle the completion of a mkdir dependency.
11339  */
11340 static void
11341 handle_written_mkdir(mkdir, type)
11342         struct mkdir *mkdir;
11343         int type;
11344 {
11345
11346         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11347                 panic("handle_written_mkdir: bad type");
11348         mkdir->md_state |= COMPLETE;
11349         complete_mkdir(mkdir);
11350 }
11351
11352 static int
11353 free_pagedep(pagedep)
11354         struct pagedep *pagedep;
11355 {
11356         int i;
11357
11358         if (pagedep->pd_state & NEWBLOCK)
11359                 return (0);
11360         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11361                 return (0);
11362         for (i = 0; i < DAHASHSZ; i++)
11363                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11364                         return (0);
11365         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11366                 return (0);
11367         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11368                 return (0);
11369         if (pagedep->pd_state & ONWORKLIST)
11370                 WORKLIST_REMOVE(&pagedep->pd_list);
11371         LIST_REMOVE(pagedep, pd_hash);
11372         WORKITEM_FREE(pagedep, D_PAGEDEP);
11373
11374         return (1);
11375 }
11376
11377 /*
11378  * Called from within softdep_disk_write_complete above.
11379  * A write operation was just completed. Removed inodes can
11380  * now be freed and associated block pointers may be committed.
11381  * Note that this routine is always called from interrupt level
11382  * with further splbio interrupts blocked.
11383  */
11384 static int 
11385 handle_written_filepage(pagedep, bp)
11386         struct pagedep *pagedep;
11387         struct buf *bp;         /* buffer containing the written page */
11388 {
11389         struct dirrem *dirrem;
11390         struct diradd *dap, *nextdap;
11391         struct direct *ep;
11392         int i, chgs;
11393
11394         if ((pagedep->pd_state & IOSTARTED) == 0)
11395                 panic("handle_written_filepage: not started");
11396         pagedep->pd_state &= ~IOSTARTED;
11397         /*
11398          * Process any directory removals that have been committed.
11399          */
11400         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11401                 LIST_REMOVE(dirrem, dm_next);
11402                 dirrem->dm_state |= COMPLETE;
11403                 dirrem->dm_dirinum = pagedep->pd_ino;
11404                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11405                     ("handle_written_filepage: Journal entries not written."));
11406                 add_to_worklist(&dirrem->dm_list, 0);
11407         }
11408         /*
11409          * Free any directory additions that have been committed.
11410          * If it is a newly allocated block, we have to wait until
11411          * the on-disk directory inode claims the new block.
11412          */
11413         if ((pagedep->pd_state & NEWBLOCK) == 0)
11414                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11415                         free_diradd(dap, NULL);
11416         /*
11417          * Uncommitted directory entries must be restored.
11418          */
11419         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11420                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11421                      dap = nextdap) {
11422                         nextdap = LIST_NEXT(dap, da_pdlist);
11423                         if (dap->da_state & ATTACHED)
11424                                 panic("handle_written_filepage: attached");
11425                         ep = (struct direct *)
11426                             ((char *)bp->b_data + dap->da_offset);
11427                         ep->d_ino = dap->da_newinum;
11428                         dap->da_state &= ~UNDONE;
11429                         dap->da_state |= ATTACHED;
11430                         chgs = 1;
11431                         /*
11432                          * If the inode referenced by the directory has
11433                          * been written out, then the dependency can be
11434                          * moved to the pending list.
11435                          */
11436                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11437                                 LIST_REMOVE(dap, da_pdlist);
11438                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11439                                     da_pdlist);
11440                         }
11441                 }
11442         }
11443         /*
11444          * If there were any rollbacks in the directory, then it must be
11445          * marked dirty so that its will eventually get written back in
11446          * its correct form.
11447          */
11448         if (chgs) {
11449                 if ((bp->b_flags & B_DELWRI) == 0)
11450                         stat_dir_entry++;
11451                 bdirty(bp);
11452                 return (1);
11453         }
11454         /*
11455          * If we are not waiting for a new directory block to be
11456          * claimed by its inode, then the pagedep will be freed.
11457          * Otherwise it will remain to track any new entries on
11458          * the page in case they are fsync'ed.
11459          */
11460         free_pagedep(pagedep);
11461         return (0);
11462 }
11463
11464 /*
11465  * Writing back in-core inode structures.
11466  * 
11467  * The filesystem only accesses an inode's contents when it occupies an
11468  * "in-core" inode structure.  These "in-core" structures are separate from
11469  * the page frames used to cache inode blocks.  Only the latter are
11470  * transferred to/from the disk.  So, when the updated contents of the
11471  * "in-core" inode structure are copied to the corresponding in-memory inode
11472  * block, the dependencies are also transferred.  The following procedure is
11473  * called when copying a dirty "in-core" inode to a cached inode block.
11474  */
11475
11476 /*
11477  * Called when an inode is loaded from disk. If the effective link count
11478  * differed from the actual link count when it was last flushed, then we
11479  * need to ensure that the correct effective link count is put back.
11480  */
11481 void 
11482 softdep_load_inodeblock(ip)
11483         struct inode *ip;       /* the "in_core" copy of the inode */
11484 {
11485         struct inodedep *inodedep;
11486
11487         /*
11488          * Check for alternate nlink count.
11489          */
11490         ip->i_effnlink = ip->i_nlink;
11491         ACQUIRE_LOCK(&lk);
11492         if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
11493             &inodedep) == 0) {
11494                 FREE_LOCK(&lk);
11495                 return;
11496         }
11497         ip->i_effnlink -= inodedep->id_nlinkdelta;
11498         FREE_LOCK(&lk);
11499 }
11500
11501 /*
11502  * This routine is called just before the "in-core" inode
11503  * information is to be copied to the in-memory inode block.
11504  * Recall that an inode block contains several inodes. If
11505  * the force flag is set, then the dependencies will be
11506  * cleared so that the update can always be made. Note that
11507  * the buffer is locked when this routine is called, so we
11508  * will never be in the middle of writing the inode block 
11509  * to disk.
11510  */
11511 void 
11512 softdep_update_inodeblock(ip, bp, waitfor)
11513         struct inode *ip;       /* the "in_core" copy of the inode */
11514         struct buf *bp;         /* the buffer containing the inode block */
11515         int waitfor;            /* nonzero => update must be allowed */
11516 {
11517         struct inodedep *inodedep;
11518         struct inoref *inoref;
11519         struct worklist *wk;
11520         struct mount *mp;
11521         struct buf *ibp;
11522         struct fs *fs;
11523         int error;
11524
11525         mp = UFSTOVFS(ip->i_ump);
11526         fs = ip->i_fs;
11527         /*
11528          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
11529          * does not have access to the in-core ip so must write directly into
11530          * the inode block buffer when setting freelink.
11531          */
11532         if (fs->fs_magic == FS_UFS1_MAGIC)
11533                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
11534                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
11535         else
11536                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
11537                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
11538         /*
11539          * If the effective link count is not equal to the actual link
11540          * count, then we must track the difference in an inodedep while
11541          * the inode is (potentially) tossed out of the cache. Otherwise,
11542          * if there is no existing inodedep, then there are no dependencies
11543          * to track.
11544          */
11545         ACQUIRE_LOCK(&lk);
11546 again:
11547         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11548                 FREE_LOCK(&lk);
11549                 if (ip->i_effnlink != ip->i_nlink)
11550                         panic("softdep_update_inodeblock: bad link count");
11551                 return;
11552         }
11553         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
11554                 panic("softdep_update_inodeblock: bad delta");
11555         /*
11556          * If we're flushing all dependencies we must also move any waiting
11557          * for journal writes onto the bufwait list prior to I/O.
11558          */
11559         if (waitfor) {
11560                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11561                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11562                             == DEPCOMPLETE) {
11563                                 jwait(&inoref->if_list, MNT_WAIT);
11564                                 goto again;
11565                         }
11566                 }
11567         }
11568         /*
11569          * Changes have been initiated. Anything depending on these
11570          * changes cannot occur until this inode has been written.
11571          */
11572         inodedep->id_state &= ~COMPLETE;
11573         if ((inodedep->id_state & ONWORKLIST) == 0)
11574                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
11575         /*
11576          * Any new dependencies associated with the incore inode must 
11577          * now be moved to the list associated with the buffer holding
11578          * the in-memory copy of the inode. Once merged process any
11579          * allocdirects that are completed by the merger.
11580          */
11581         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
11582         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
11583                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
11584                     NULL);
11585         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
11586         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
11587                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
11588                     NULL);
11589         /*
11590          * Now that the inode has been pushed into the buffer, the
11591          * operations dependent on the inode being written to disk
11592          * can be moved to the id_bufwait so that they will be
11593          * processed when the buffer I/O completes.
11594          */
11595         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
11596                 WORKLIST_REMOVE(wk);
11597                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
11598         }
11599         /*
11600          * Newly allocated inodes cannot be written until the bitmap
11601          * that allocates them have been written (indicated by
11602          * DEPCOMPLETE being set in id_state). If we are doing a
11603          * forced sync (e.g., an fsync on a file), we force the bitmap
11604          * to be written so that the update can be done.
11605          */
11606         if (waitfor == 0) {
11607                 FREE_LOCK(&lk);
11608                 return;
11609         }
11610 retry:
11611         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
11612                 FREE_LOCK(&lk);
11613                 return;
11614         }
11615         ibp = inodedep->id_bmsafemap->sm_buf;
11616         ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
11617         if (ibp == NULL) {
11618                 /*
11619                  * If ibp came back as NULL, the dependency could have been
11620                  * freed while we slept.  Look it up again, and check to see
11621                  * that it has completed.
11622                  */
11623                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
11624                         goto retry;
11625                 FREE_LOCK(&lk);
11626                 return;
11627         }
11628         FREE_LOCK(&lk);
11629         if ((error = bwrite(ibp)) != 0)
11630                 softdep_error("softdep_update_inodeblock: bwrite", error);
11631 }
11632
11633 /*
11634  * Merge the a new inode dependency list (such as id_newinoupdt) into an
11635  * old inode dependency list (such as id_inoupdt). This routine must be
11636  * called with splbio interrupts blocked.
11637  */
11638 static void
11639 merge_inode_lists(newlisthead, oldlisthead)
11640         struct allocdirectlst *newlisthead;
11641         struct allocdirectlst *oldlisthead;
11642 {
11643         struct allocdirect *listadp, *newadp;
11644
11645         newadp = TAILQ_FIRST(newlisthead);
11646         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
11647                 if (listadp->ad_offset < newadp->ad_offset) {
11648                         listadp = TAILQ_NEXT(listadp, ad_next);
11649                         continue;
11650                 }
11651                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
11652                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
11653                 if (listadp->ad_offset == newadp->ad_offset) {
11654                         allocdirect_merge(oldlisthead, newadp,
11655                             listadp);
11656                         listadp = newadp;
11657                 }
11658                 newadp = TAILQ_FIRST(newlisthead);
11659         }
11660         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
11661                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
11662                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
11663         }
11664 }
11665
11666 /*
11667  * If we are doing an fsync, then we must ensure that any directory
11668  * entries for the inode have been written after the inode gets to disk.
11669  */
11670 int
11671 softdep_fsync(vp)
11672         struct vnode *vp;       /* the "in_core" copy of the inode */
11673 {
11674         struct inodedep *inodedep;
11675         struct pagedep *pagedep;
11676         struct inoref *inoref;
11677         struct worklist *wk;
11678         struct diradd *dap;
11679         struct mount *mp;
11680         struct vnode *pvp;
11681         struct inode *ip;
11682         struct buf *bp;
11683         struct fs *fs;
11684         struct thread *td = curthread;
11685         int error, flushparent, pagedep_new_block;
11686         ino_t parentino;
11687         ufs_lbn_t lbn;
11688
11689         ip = VTOI(vp);
11690         fs = ip->i_fs;
11691         mp = vp->v_mount;
11692         ACQUIRE_LOCK(&lk);
11693 restart:
11694         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
11695                 FREE_LOCK(&lk);
11696                 return (0);
11697         }
11698         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
11699                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
11700                     == DEPCOMPLETE) {
11701                         jwait(&inoref->if_list, MNT_WAIT);
11702                         goto restart;
11703                 }
11704         }
11705         if (!LIST_EMPTY(&inodedep->id_inowait) ||
11706             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
11707             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
11708             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
11709             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
11710                 panic("softdep_fsync: pending ops %p", inodedep);
11711         for (error = 0, flushparent = 0; ; ) {
11712                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
11713                         break;
11714                 if (wk->wk_type != D_DIRADD)
11715                         panic("softdep_fsync: Unexpected type %s",
11716                             TYPENAME(wk->wk_type));
11717                 dap = WK_DIRADD(wk);
11718                 /*
11719                  * Flush our parent if this directory entry has a MKDIR_PARENT
11720                  * dependency or is contained in a newly allocated block.
11721                  */
11722                 if (dap->da_state & DIRCHG)
11723                         pagedep = dap->da_previous->dm_pagedep;
11724                 else
11725                         pagedep = dap->da_pagedep;
11726                 parentino = pagedep->pd_ino;
11727                 lbn = pagedep->pd_lbn;
11728                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
11729                         panic("softdep_fsync: dirty");
11730                 if ((dap->da_state & MKDIR_PARENT) ||
11731                     (pagedep->pd_state & NEWBLOCK))
11732                         flushparent = 1;
11733                 else
11734                         flushparent = 0;
11735                 /*
11736                  * If we are being fsync'ed as part of vgone'ing this vnode,
11737                  * then we will not be able to release and recover the
11738                  * vnode below, so we just have to give up on writing its
11739                  * directory entry out. It will eventually be written, just
11740                  * not now, but then the user was not asking to have it
11741                  * written, so we are not breaking any promises.
11742                  */
11743                 if (vp->v_iflag & VI_DOOMED)
11744                         break;
11745                 /*
11746                  * We prevent deadlock by always fetching inodes from the
11747                  * root, moving down the directory tree. Thus, when fetching
11748                  * our parent directory, we first try to get the lock. If
11749                  * that fails, we must unlock ourselves before requesting
11750                  * the lock on our parent. See the comment in ufs_lookup
11751                  * for details on possible races.
11752                  */
11753                 FREE_LOCK(&lk);
11754                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
11755                     FFSV_FORCEINSMQ)) {
11756                         error = vfs_busy(mp, MBF_NOWAIT);
11757                         if (error != 0) {
11758                                 vfs_ref(mp);
11759                                 VOP_UNLOCK(vp, 0);
11760                                 error = vfs_busy(mp, 0);
11761                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
11762                                 vfs_rel(mp);
11763                                 if (error != 0)
11764                                         return (ENOENT);
11765                                 if (vp->v_iflag & VI_DOOMED) {
11766                                         vfs_unbusy(mp);
11767                                         return (ENOENT);
11768                                 }
11769                         }
11770                         VOP_UNLOCK(vp, 0);
11771                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
11772                             &pvp, FFSV_FORCEINSMQ);
11773                         vfs_unbusy(mp);
11774                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
11775                         if (vp->v_iflag & VI_DOOMED) {
11776                                 if (error == 0)
11777                                         vput(pvp);
11778                                 error = ENOENT;
11779                         }
11780                         if (error != 0)
11781                                 return (error);
11782                 }
11783                 /*
11784                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
11785                  * that are contained in direct blocks will be resolved by 
11786                  * doing a ffs_update. Pagedeps contained in indirect blocks
11787                  * may require a complete sync'ing of the directory. So, we
11788                  * try the cheap and fast ffs_update first, and if that fails,
11789                  * then we do the slower ffs_syncvnode of the directory.
11790                  */
11791                 if (flushparent) {
11792                         int locked;
11793
11794                         if ((error = ffs_update(pvp, 1)) != 0) {
11795                                 vput(pvp);
11796                                 return (error);
11797                         }
11798                         ACQUIRE_LOCK(&lk);
11799                         locked = 1;
11800                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
11801                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
11802                                         if (wk->wk_type != D_DIRADD)
11803                                                 panic("softdep_fsync: Unexpected type %s",
11804                                                       TYPENAME(wk->wk_type));
11805                                         dap = WK_DIRADD(wk);
11806                                         if (dap->da_state & DIRCHG)
11807                                                 pagedep = dap->da_previous->dm_pagedep;
11808                                         else
11809                                                 pagedep = dap->da_pagedep;
11810                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
11811                                         FREE_LOCK(&lk);
11812                                         locked = 0;
11813                                         if (pagedep_new_block &&
11814                                             (error = ffs_syncvnode(pvp, MNT_WAIT))) {
11815                                                 vput(pvp);
11816                                                 return (error);
11817                                         }
11818                                 }
11819                         }
11820                         if (locked)
11821                                 FREE_LOCK(&lk);
11822                 }
11823                 /*
11824                  * Flush directory page containing the inode's name.
11825                  */
11826                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
11827                     &bp);
11828                 if (error == 0)
11829                         error = bwrite(bp);
11830                 else
11831                         brelse(bp);
11832                 vput(pvp);
11833                 if (error != 0)
11834                         return (error);
11835                 ACQUIRE_LOCK(&lk);
11836                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
11837                         break;
11838         }
11839         FREE_LOCK(&lk);
11840         return (0);
11841 }
11842
11843 /*
11844  * Flush all the dirty bitmaps associated with the block device
11845  * before flushing the rest of the dirty blocks so as to reduce
11846  * the number of dependencies that will have to be rolled back.
11847  *
11848  * XXX Unused?
11849  */
11850 void
11851 softdep_fsync_mountdev(vp)
11852         struct vnode *vp;
11853 {
11854         struct buf *bp, *nbp;
11855         struct worklist *wk;
11856         struct bufobj *bo;
11857
11858         if (!vn_isdisk(vp, NULL))
11859                 panic("softdep_fsync_mountdev: vnode not a disk");
11860         bo = &vp->v_bufobj;
11861 restart:
11862         BO_LOCK(bo);
11863         ACQUIRE_LOCK(&lk);
11864         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
11865                 /* 
11866                  * If it is already scheduled, skip to the next buffer.
11867                  */
11868                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
11869                         continue;
11870
11871                 if ((bp->b_flags & B_DELWRI) == 0)
11872                         panic("softdep_fsync_mountdev: not dirty");
11873                 /*
11874                  * We are only interested in bitmaps with outstanding
11875                  * dependencies.
11876                  */
11877                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
11878                     wk->wk_type != D_BMSAFEMAP ||
11879                     (bp->b_vflags & BV_BKGRDINPROG)) {
11880                         BUF_UNLOCK(bp);
11881                         continue;
11882                 }
11883                 FREE_LOCK(&lk);
11884                 BO_UNLOCK(bo);
11885                 bremfree(bp);
11886                 (void) bawrite(bp);
11887                 goto restart;
11888         }
11889         FREE_LOCK(&lk);
11890         drain_output(vp);
11891         BO_UNLOCK(bo);
11892 }
11893
11894 /*
11895  * Sync all cylinder groups that were dirty at the time this function is
11896  * called.  Newly dirtied cgs will be inserted before the sintenel.  This
11897  * is used to flush freedep activity that may be holding up writes to a
11898  * indirect block.
11899  */
11900 static int
11901 sync_cgs(mp, waitfor)
11902         struct mount *mp;
11903         int waitfor;
11904 {
11905         struct bmsafemap *bmsafemap;
11906         struct bmsafemap *sintenel;
11907         struct ufsmount *ump;
11908         struct buf *bp;
11909         int error;
11910
11911         sintenel = malloc(sizeof(*sintenel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
11912         sintenel->sm_cg = -1;
11913         ump = VFSTOUFS(mp);
11914         error = 0;
11915         ACQUIRE_LOCK(&lk);
11916         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sintenel, sm_next);
11917         for (bmsafemap = LIST_NEXT(sintenel, sm_next); bmsafemap != NULL;
11918             bmsafemap = LIST_NEXT(sintenel, sm_next)) {
11919                 /* Skip sintenels and cgs with no work to release. */
11920                 if (bmsafemap->sm_cg == -1 ||
11921                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
11922                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
11923                         LIST_REMOVE(sintenel, sm_next);
11924                         LIST_INSERT_AFTER(bmsafemap, sintenel, sm_next);
11925                         continue;
11926                 }
11927                 /*
11928                  * If we don't get the lock and we're waiting try again, if
11929                  * not move on to the next buf and try to sync it.
11930                  */
11931                 bp = getdirtybuf(bmsafemap->sm_buf, &lk, waitfor);
11932                 if (bp == NULL && waitfor == MNT_WAIT)
11933                         continue;
11934                 LIST_REMOVE(sintenel, sm_next);
11935                 LIST_INSERT_AFTER(bmsafemap, sintenel, sm_next);
11936                 if (bp == NULL)
11937                         continue;
11938                 FREE_LOCK(&lk);
11939                 if (waitfor == MNT_NOWAIT)
11940                         bawrite(bp);
11941                 else
11942                         error = bwrite(bp);
11943                 ACQUIRE_LOCK(&lk);
11944                 if (error)
11945                         break;
11946         }
11947         LIST_REMOVE(sintenel, sm_next);
11948         FREE_LOCK(&lk);
11949         free(sintenel, M_BMSAFEMAP);
11950         return (error);
11951 }
11952
11953 /*
11954  * This routine is called when we are trying to synchronously flush a
11955  * file. This routine must eliminate any filesystem metadata dependencies
11956  * so that the syncing routine can succeed.
11957  */
11958 int
11959 softdep_sync_metadata(struct vnode *vp)
11960 {
11961         int error;
11962
11963         /*
11964          * Ensure that any direct block dependencies have been cleared,
11965          * truncations are started, and inode references are journaled.
11966          */
11967         ACQUIRE_LOCK(&lk);
11968         /*
11969          * Write all journal records to prevent rollbacks on devvp.
11970          */
11971         if (vp->v_type == VCHR)
11972                 softdep_flushjournal(vp->v_mount);
11973         error = flush_inodedep_deps(vp, vp->v_mount, VTOI(vp)->i_number);
11974         /*
11975          * Ensure that all truncates are written so we won't find deps on
11976          * indirect blocks.
11977          */
11978         process_truncates(vp);
11979         FREE_LOCK(&lk);
11980
11981         return (error);
11982 }
11983
11984 /*
11985  * This routine is called when we are attempting to sync a buf with
11986  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
11987  * other IO it can but returns EBUSY if the buffer is not yet able to
11988  * be written.  Dependencies which will not cause rollbacks will always
11989  * return 0.
11990  */
11991 int
11992 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
11993 {
11994         struct indirdep *indirdep;
11995         struct pagedep *pagedep;
11996         struct allocindir *aip;
11997         struct newblk *newblk;
11998         struct buf *nbp;
11999         struct worklist *wk;
12000         int i, error;
12001
12002         /*
12003          * For VCHR we just don't want to force flush any dependencies that
12004          * will cause rollbacks.
12005          */
12006         if (vp->v_type == VCHR) {
12007                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12008                         return (EBUSY);
12009                 return (0);
12010         }
12011         ACQUIRE_LOCK(&lk);
12012         /*
12013          * As we hold the buffer locked, none of its dependencies
12014          * will disappear.
12015          */
12016         error = 0;
12017 top:
12018         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12019                 switch (wk->wk_type) {
12020
12021                 case D_ALLOCDIRECT:
12022                 case D_ALLOCINDIR:
12023                         newblk = WK_NEWBLK(wk);
12024                         if (newblk->nb_jnewblk != NULL) {
12025                                 if (waitfor == MNT_NOWAIT) {
12026                                         error = EBUSY;
12027                                         goto out_unlock;
12028                                 }
12029                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12030                                 goto top;
12031                         }
12032                         if (newblk->nb_state & DEPCOMPLETE ||
12033                             waitfor == MNT_NOWAIT)
12034                                 continue;
12035                         nbp = newblk->nb_bmsafemap->sm_buf;
12036                         nbp = getdirtybuf(nbp, &lk, waitfor);
12037                         if (nbp == NULL)
12038                                 goto top;
12039                         FREE_LOCK(&lk);
12040                         if ((error = bwrite(nbp)) != 0)
12041                                 goto out;
12042                         ACQUIRE_LOCK(&lk);
12043                         continue;
12044
12045                 case D_INDIRDEP:
12046                         indirdep = WK_INDIRDEP(wk);
12047                         if (waitfor == MNT_NOWAIT) {
12048                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12049                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12050                                         error = EBUSY;
12051                                         goto out_unlock;
12052                                 }
12053                         }
12054                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12055                                 panic("softdep_sync_buf: truncation pending.");
12056                 restart:
12057                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12058                                 newblk = (struct newblk *)aip;
12059                                 if (newblk->nb_jnewblk != NULL) {
12060                                         jwait(&newblk->nb_jnewblk->jn_list,
12061                                             waitfor);
12062                                         goto restart;
12063                                 }
12064                                 if (newblk->nb_state & DEPCOMPLETE)
12065                                         continue;
12066                                 nbp = newblk->nb_bmsafemap->sm_buf;
12067                                 nbp = getdirtybuf(nbp, &lk, waitfor);
12068                                 if (nbp == NULL)
12069                                         goto restart;
12070                                 FREE_LOCK(&lk);
12071                                 if ((error = bwrite(nbp)) != 0)
12072                                         goto out;
12073                                 ACQUIRE_LOCK(&lk);
12074                                 goto restart;
12075                         }
12076                         continue;
12077
12078                 case D_PAGEDEP:
12079                         /*
12080                          * Only flush directory entries in synchronous passes.
12081                          */
12082                         if (waitfor != MNT_WAIT) {
12083                                 error = EBUSY;
12084                                 goto out_unlock;
12085                         }
12086                         /*
12087                          * While syncing snapshots, we must allow recursive
12088                          * lookups.
12089                          */
12090                         BUF_AREC(bp);
12091                         /*
12092                          * We are trying to sync a directory that may
12093                          * have dependencies on both its own metadata
12094                          * and/or dependencies on the inodes of any
12095                          * recently allocated files. We walk its diradd
12096                          * lists pushing out the associated inode.
12097                          */
12098                         pagedep = WK_PAGEDEP(wk);
12099                         for (i = 0; i < DAHASHSZ; i++) {
12100                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12101                                         continue;
12102                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12103                                     &pagedep->pd_diraddhd[i]))) {
12104                                         BUF_NOREC(bp);
12105                                         goto out_unlock;
12106                                 }
12107                         }
12108                         BUF_NOREC(bp);
12109                         continue;
12110
12111                 case D_FREEWORK:
12112                 case D_FREEDEP:
12113                 case D_JSEGDEP:
12114                         continue;
12115
12116                 default:
12117                         panic("softdep_sync_buf: Unknown type %s",
12118                             TYPENAME(wk->wk_type));
12119                         /* NOTREACHED */
12120                 }
12121         }
12122 out_unlock:
12123         FREE_LOCK(&lk);
12124 out:
12125         return (error);
12126 }
12127
12128 /*
12129  * Flush the dependencies associated with an inodedep.
12130  * Called with splbio blocked.
12131  */
12132 static int
12133 flush_inodedep_deps(vp, mp, ino)
12134         struct vnode *vp;
12135         struct mount *mp;
12136         ino_t ino;
12137 {
12138         struct inodedep *inodedep;
12139         struct inoref *inoref;
12140         int error, waitfor;
12141
12142         /*
12143          * This work is done in two passes. The first pass grabs most
12144          * of the buffers and begins asynchronously writing them. The
12145          * only way to wait for these asynchronous writes is to sleep
12146          * on the filesystem vnode which may stay busy for a long time
12147          * if the filesystem is active. So, instead, we make a second
12148          * pass over the dependencies blocking on each write. In the
12149          * usual case we will be blocking against a write that we
12150          * initiated, so when it is done the dependency will have been
12151          * resolved. Thus the second pass is expected to end quickly.
12152          * We give a brief window at the top of the loop to allow
12153          * any pending I/O to complete.
12154          */
12155         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12156                 if (error)
12157                         return (error);
12158                 FREE_LOCK(&lk);
12159                 ACQUIRE_LOCK(&lk);
12160 restart:
12161                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12162                         return (0);
12163                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12164                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12165                             == DEPCOMPLETE) {
12166                                 jwait(&inoref->if_list, MNT_WAIT);
12167                                 goto restart;
12168                         }
12169                 }
12170                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12171                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12172                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12173                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12174                         continue;
12175                 /*
12176                  * If pass2, we are done, otherwise do pass 2.
12177                  */
12178                 if (waitfor == MNT_WAIT)
12179                         break;
12180                 waitfor = MNT_WAIT;
12181         }
12182         /*
12183          * Try freeing inodedep in case all dependencies have been removed.
12184          */
12185         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12186                 (void) free_inodedep(inodedep);
12187         return (0);
12188 }
12189
12190 /*
12191  * Flush an inode dependency list.
12192  * Called with splbio blocked.
12193  */
12194 static int
12195 flush_deplist(listhead, waitfor, errorp)
12196         struct allocdirectlst *listhead;
12197         int waitfor;
12198         int *errorp;
12199 {
12200         struct allocdirect *adp;
12201         struct newblk *newblk;
12202         struct buf *bp;
12203
12204         mtx_assert(&lk, MA_OWNED);
12205         TAILQ_FOREACH(adp, listhead, ad_next) {
12206                 newblk = (struct newblk *)adp;
12207                 if (newblk->nb_jnewblk != NULL) {
12208                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12209                         return (1);
12210                 }
12211                 if (newblk->nb_state & DEPCOMPLETE)
12212                         continue;
12213                 bp = newblk->nb_bmsafemap->sm_buf;
12214                 bp = getdirtybuf(bp, &lk, waitfor);
12215                 if (bp == NULL) {
12216                         if (waitfor == MNT_NOWAIT)
12217                                 continue;
12218                         return (1);
12219                 }
12220                 FREE_LOCK(&lk);
12221                 if (waitfor == MNT_NOWAIT)
12222                         bawrite(bp);
12223                 else 
12224                         *errorp = bwrite(bp);
12225                 ACQUIRE_LOCK(&lk);
12226                 return (1);
12227         }
12228         return (0);
12229 }
12230
12231 /*
12232  * Flush dependencies associated with an allocdirect block.
12233  */
12234 static int
12235 flush_newblk_dep(vp, mp, lbn)
12236         struct vnode *vp;
12237         struct mount *mp;
12238         ufs_lbn_t lbn;
12239 {
12240         struct newblk *newblk;
12241         struct bufobj *bo;
12242         struct inode *ip;
12243         struct buf *bp;
12244         ufs2_daddr_t blkno;
12245         int error;
12246
12247         error = 0;
12248         bo = &vp->v_bufobj;
12249         ip = VTOI(vp);
12250         blkno = DIP(ip, i_db[lbn]);
12251         if (blkno == 0)
12252                 panic("flush_newblk_dep: Missing block");
12253         ACQUIRE_LOCK(&lk);
12254         /*
12255          * Loop until all dependencies related to this block are satisfied.
12256          * We must be careful to restart after each sleep in case a write
12257          * completes some part of this process for us.
12258          */
12259         for (;;) {
12260                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12261                         FREE_LOCK(&lk);
12262                         break;
12263                 }
12264                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12265                         panic("flush_newblk_deps: Bad newblk %p", newblk);
12266                 /*
12267                  * Flush the journal.
12268                  */
12269                 if (newblk->nb_jnewblk != NULL) {
12270                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12271                         continue;
12272                 }
12273                 /*
12274                  * Write the bitmap dependency.
12275                  */
12276                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12277                         bp = newblk->nb_bmsafemap->sm_buf;
12278                         bp = getdirtybuf(bp, &lk, MNT_WAIT);
12279                         if (bp == NULL)
12280                                 continue;
12281                         FREE_LOCK(&lk);
12282                         error = bwrite(bp);
12283                         if (error)
12284                                 break;
12285                         ACQUIRE_LOCK(&lk);
12286                         continue;
12287                 }
12288                 /*
12289                  * Write the buffer.
12290                  */
12291                 FREE_LOCK(&lk);
12292                 BO_LOCK(bo);
12293                 bp = gbincore(bo, lbn);
12294                 if (bp != NULL) {
12295                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12296                             LK_INTERLOCK, BO_MTX(bo));
12297                         if (error == ENOLCK) {
12298                                 ACQUIRE_LOCK(&lk);
12299                                 continue; /* Slept, retry */
12300                         }
12301                         if (error != 0)
12302                                 break;  /* Failed */
12303                         if (bp->b_flags & B_DELWRI) {
12304                                 bremfree(bp);
12305                                 error = bwrite(bp);
12306                                 if (error)
12307                                         break;
12308                         } else
12309                                 BUF_UNLOCK(bp);
12310                 } else
12311                         BO_UNLOCK(bo);
12312                 /*
12313                  * We have to wait for the direct pointers to
12314                  * point at the newdirblk before the dependency
12315                  * will go away.
12316                  */
12317                 error = ffs_update(vp, MNT_WAIT);
12318                 if (error)
12319                         break;
12320                 ACQUIRE_LOCK(&lk);
12321         }
12322         return (error);
12323 }
12324
12325 /*
12326  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12327  * Called with splbio blocked.
12328  */
12329 static int
12330 flush_pagedep_deps(pvp, mp, diraddhdp)
12331         struct vnode *pvp;
12332         struct mount *mp;
12333         struct diraddhd *diraddhdp;
12334 {
12335         struct inodedep *inodedep;
12336         struct inoref *inoref;
12337         struct ufsmount *ump;
12338         struct diradd *dap;
12339         struct vnode *vp;
12340         int error = 0;
12341         struct buf *bp;
12342         ino_t inum;
12343
12344         ump = VFSTOUFS(mp);
12345 restart:
12346         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12347                 /*
12348                  * Flush ourselves if this directory entry
12349                  * has a MKDIR_PARENT dependency.
12350                  */
12351                 if (dap->da_state & MKDIR_PARENT) {
12352                         FREE_LOCK(&lk);
12353                         if ((error = ffs_update(pvp, MNT_WAIT)) != 0)
12354                                 break;
12355                         ACQUIRE_LOCK(&lk);
12356                         /*
12357                          * If that cleared dependencies, go on to next.
12358                          */
12359                         if (dap != LIST_FIRST(diraddhdp))
12360                                 continue;
12361                         if (dap->da_state & MKDIR_PARENT)
12362                                 panic("flush_pagedep_deps: MKDIR_PARENT");
12363                 }
12364                 /*
12365                  * A newly allocated directory must have its "." and
12366                  * ".." entries written out before its name can be
12367                  * committed in its parent. 
12368                  */
12369                 inum = dap->da_newinum;
12370                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12371                         panic("flush_pagedep_deps: lost inode1");
12372                 /*
12373                  * Wait for any pending journal adds to complete so we don't
12374                  * cause rollbacks while syncing.
12375                  */
12376                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12377                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12378                             == DEPCOMPLETE) {
12379                                 jwait(&inoref->if_list, MNT_WAIT);
12380                                 goto restart;
12381                         }
12382                 }
12383                 if (dap->da_state & MKDIR_BODY) {
12384                         FREE_LOCK(&lk);
12385                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12386                             FFSV_FORCEINSMQ)))
12387                                 break;
12388                         error = flush_newblk_dep(vp, mp, 0);
12389                         /*
12390                          * If we still have the dependency we might need to
12391                          * update the vnode to sync the new link count to
12392                          * disk.
12393                          */
12394                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
12395                                 error = ffs_update(vp, MNT_WAIT);
12396                         vput(vp);
12397                         if (error != 0)
12398                                 break;
12399                         ACQUIRE_LOCK(&lk);
12400                         /*
12401                          * If that cleared dependencies, go on to next.
12402                          */
12403                         if (dap != LIST_FIRST(diraddhdp))
12404                                 continue;
12405                         if (dap->da_state & MKDIR_BODY) {
12406                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
12407                                     &inodedep);
12408                                 panic("flush_pagedep_deps: MKDIR_BODY "
12409                                     "inodedep %p dap %p vp %p",
12410                                     inodedep, dap, vp);
12411                         }
12412                 }
12413                 /*
12414                  * Flush the inode on which the directory entry depends.
12415                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12416                  * the only remaining dependency is that the updated inode
12417                  * count must get pushed to disk. The inode has already
12418                  * been pushed into its inode buffer (via VOP_UPDATE) at
12419                  * the time of the reference count change. So we need only
12420                  * locate that buffer, ensure that there will be no rollback
12421                  * caused by a bitmap dependency, then write the inode buffer.
12422                  */
12423 retry:
12424                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12425                         panic("flush_pagedep_deps: lost inode");
12426                 /*
12427                  * If the inode still has bitmap dependencies,
12428                  * push them to disk.
12429                  */
12430                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
12431                         bp = inodedep->id_bmsafemap->sm_buf;
12432                         bp = getdirtybuf(bp, &lk, MNT_WAIT);
12433                         if (bp == NULL)
12434                                 goto retry;
12435                         FREE_LOCK(&lk);
12436                         if ((error = bwrite(bp)) != 0)
12437                                 break;
12438                         ACQUIRE_LOCK(&lk);
12439                         if (dap != LIST_FIRST(diraddhdp))
12440                                 continue;
12441                 }
12442                 /*
12443                  * If the inode is still sitting in a buffer waiting
12444                  * to be written or waiting for the link count to be
12445                  * adjusted update it here to flush it to disk.
12446                  */
12447                 if (dap == LIST_FIRST(diraddhdp)) {
12448                         FREE_LOCK(&lk);
12449                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12450                             FFSV_FORCEINSMQ)))
12451                                 break;
12452                         error = ffs_update(vp, MNT_WAIT);
12453                         vput(vp);
12454                         if (error)
12455                                 break;
12456                         ACQUIRE_LOCK(&lk);
12457                 }
12458                 /*
12459                  * If we have failed to get rid of all the dependencies
12460                  * then something is seriously wrong.
12461                  */
12462                 if (dap == LIST_FIRST(diraddhdp)) {
12463                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
12464                         panic("flush_pagedep_deps: failed to flush " 
12465                             "inodedep %p ino %d dap %p", inodedep, inum, dap);
12466                 }
12467         }
12468         if (error)
12469                 ACQUIRE_LOCK(&lk);
12470         return (error);
12471 }
12472
12473 /*
12474  * A large burst of file addition or deletion activity can drive the
12475  * memory load excessively high. First attempt to slow things down
12476  * using the techniques below. If that fails, this routine requests
12477  * the offending operations to fall back to running synchronously
12478  * until the memory load returns to a reasonable level.
12479  */
12480 int
12481 softdep_slowdown(vp)
12482         struct vnode *vp;
12483 {
12484         struct ufsmount *ump;
12485         int jlow;
12486         int max_softdeps_hard;
12487
12488         ACQUIRE_LOCK(&lk);
12489         jlow = 0;
12490         /*
12491          * Check for journal space if needed.
12492          */
12493         if (DOINGSUJ(vp)) {
12494                 ump = VFSTOUFS(vp->v_mount);
12495                 if (journal_space(ump, 0) == 0)
12496                         jlow = 1;
12497         }
12498         max_softdeps_hard = max_softdeps * 11 / 10;
12499         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
12500             dep_current[D_INODEDEP] < max_softdeps_hard &&
12501             VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps &&
12502             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0) {
12503                 FREE_LOCK(&lk);
12504                 return (0);
12505         }
12506         if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps || jlow)
12507                 softdep_speedup();
12508         stat_sync_limit_hit += 1;
12509         FREE_LOCK(&lk);
12510         if (DOINGSUJ(vp))
12511                 return (0);
12512         return (1);
12513 }
12514
12515 /*
12516  * Called by the allocation routines when they are about to fail
12517  * in the hope that we can free up the requested resource (inodes
12518  * or disk space).
12519  * 
12520  * First check to see if the work list has anything on it. If it has,
12521  * clean up entries until we successfully free the requested resource.
12522  * Because this process holds inodes locked, we cannot handle any remove
12523  * requests that might block on a locked inode as that could lead to
12524  * deadlock. If the worklist yields none of the requested resource,
12525  * start syncing out vnodes to free up the needed space.
12526  */
12527 int
12528 softdep_request_cleanup(fs, vp, cred, resource)
12529         struct fs *fs;
12530         struct vnode *vp;
12531         struct ucred *cred;
12532         int resource;
12533 {
12534         struct ufsmount *ump;
12535         struct mount *mp;
12536         struct vnode *lvp, *mvp;
12537         long starttime;
12538         ufs2_daddr_t needed;
12539         int error;
12540
12541         mp = vp->v_mount;
12542         ump = VFSTOUFS(mp);
12543         mtx_assert(UFS_MTX(ump), MA_OWNED);
12544         if (resource == FLUSH_BLOCKS_WAIT)
12545                 stat_cleanup_blkrequests += 1;
12546         else
12547                 stat_cleanup_inorequests += 1;
12548
12549         /*
12550          * If we are being called because of a process doing a
12551          * copy-on-write, then it is not safe to process any
12552          * worklist items as we will recurse into the copyonwrite
12553          * routine.  This will result in an incoherent snapshot.
12554          */
12555         if (curthread->td_pflags & TDP_COWINPROGRESS)
12556                 return (0);
12557         UFS_UNLOCK(ump);
12558         error = ffs_update(vp, 1);
12559         if (error != 0) {
12560                 UFS_LOCK(ump);
12561                 return (0);
12562         }
12563         /*
12564          * If we are in need of resources, consider pausing for
12565          * tickdelay to give ourselves some breathing room.
12566          */
12567         ACQUIRE_LOCK(&lk);
12568         process_removes(vp);
12569         process_truncates(vp);
12570         request_cleanup(UFSTOVFS(ump), resource);
12571         FREE_LOCK(&lk);
12572         /*
12573          * Now clean up at least as many resources as we will need.
12574          *
12575          * When requested to clean up inodes, the number that are needed
12576          * is set by the number of simultaneous writers (mnt_writeopcount)
12577          * plus a bit of slop (2) in case some more writers show up while
12578          * we are cleaning.
12579          *
12580          * When requested to free up space, the amount of space that
12581          * we need is enough blocks to allocate a full-sized segment
12582          * (fs_contigsumsize). The number of such segments that will
12583          * be needed is set by the number of simultaneous writers
12584          * (mnt_writeopcount) plus a bit of slop (2) in case some more
12585          * writers show up while we are cleaning.
12586          *
12587          * Additionally, if we are unpriviledged and allocating space,
12588          * we need to ensure that we clean up enough blocks to get the
12589          * needed number of blocks over the threshhold of the minimum
12590          * number of blocks required to be kept free by the filesystem
12591          * (fs_minfree).
12592          */
12593         if (resource == FLUSH_INODES_WAIT) {
12594                 needed = vp->v_mount->mnt_writeopcount + 2;
12595         } else if (resource == FLUSH_BLOCKS_WAIT) {
12596                 needed = (vp->v_mount->mnt_writeopcount + 2) *
12597                     fs->fs_contigsumsize;
12598                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
12599                         needed += fragstoblks(fs,
12600                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
12601                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
12602         } else {
12603                 UFS_LOCK(ump);
12604                 printf("softdep_request_cleanup: Unknown resource type %d\n",
12605                     resource);
12606                 return (0);
12607         }
12608         starttime = time_second;
12609 retry:
12610         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
12611             fs->fs_cstotal.cs_nbfree <= needed) ||
12612             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12613             fs->fs_cstotal.cs_nifree <= needed)) {
12614                 ACQUIRE_LOCK(&lk);
12615                 if (ump->softdep_on_worklist > 0 &&
12616                     process_worklist_item(UFSTOVFS(ump),
12617                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
12618                         stat_worklist_push += 1;
12619                 FREE_LOCK(&lk);
12620         }
12621         /*
12622          * If we still need resources and there are no more worklist
12623          * entries to process to obtain them, we have to start flushing
12624          * the dirty vnodes to force the release of additional requests
12625          * to the worklist that we can then process to reap addition
12626          * resources. We walk the vnodes associated with the mount point
12627          * until we get the needed worklist requests that we can reap.
12628          */
12629         if ((resource == FLUSH_BLOCKS_WAIT && 
12630              fs->fs_cstotal.cs_nbfree <= needed) ||
12631             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
12632              fs->fs_cstotal.cs_nifree <= needed)) {
12633                 MNT_ILOCK(mp);
12634                 MNT_VNODE_FOREACH(lvp, mp, mvp) {
12635                         VI_LOCK(lvp);
12636                         if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
12637                                 VI_UNLOCK(lvp);
12638                                 continue;
12639                         }
12640                         MNT_IUNLOCK(mp);
12641                         if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
12642                             curthread)) {
12643                                 MNT_ILOCK(mp);
12644                                 continue;
12645                         }
12646                         if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
12647                                 vput(lvp);
12648                                 MNT_ILOCK(mp);
12649                                 continue;
12650                         }
12651                         (void) ffs_syncvnode(lvp, MNT_NOWAIT);
12652                         vput(lvp);
12653                         MNT_ILOCK(mp);
12654                 }
12655                 MNT_IUNLOCK(mp);
12656                 lvp = ump->um_devvp;
12657                 if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
12658                         VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
12659                         VOP_UNLOCK(lvp, 0);
12660                 }
12661                 if (ump->softdep_on_worklist > 0) {
12662                         stat_cleanup_retries += 1;
12663                         goto retry;
12664                 }
12665                 stat_cleanup_failures += 1;
12666         }
12667         if (time_second - starttime > stat_cleanup_high_delay)
12668                 stat_cleanup_high_delay = time_second - starttime;
12669         UFS_LOCK(ump);
12670         return (1);
12671 }
12672
12673 /*
12674  * If memory utilization has gotten too high, deliberately slow things
12675  * down and speed up the I/O processing.
12676  */
12677 extern struct thread *syncertd;
12678 static int
12679 request_cleanup(mp, resource)
12680         struct mount *mp;
12681         int resource;
12682 {
12683         struct thread *td = curthread;
12684         struct ufsmount *ump;
12685
12686         mtx_assert(&lk, MA_OWNED);
12687         /*
12688          * We never hold up the filesystem syncer or buf daemon.
12689          */
12690         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
12691                 return (0);
12692         ump = VFSTOUFS(mp);
12693         /*
12694          * First check to see if the work list has gotten backlogged.
12695          * If it has, co-opt this process to help clean up two entries.
12696          * Because this process may hold inodes locked, we cannot
12697          * handle any remove requests that might block on a locked
12698          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
12699          * to avoid recursively processing the worklist.
12700          */
12701         if (ump->softdep_on_worklist > max_softdeps / 10) {
12702                 td->td_pflags |= TDP_SOFTDEP;
12703                 process_worklist_item(mp, 2, LK_NOWAIT);
12704                 td->td_pflags &= ~TDP_SOFTDEP;
12705                 stat_worklist_push += 2;
12706                 return(1);
12707         }
12708         /*
12709          * Next, we attempt to speed up the syncer process. If that
12710          * is successful, then we allow the process to continue.
12711          */
12712         if (softdep_speedup() &&
12713             resource != FLUSH_BLOCKS_WAIT &&
12714             resource != FLUSH_INODES_WAIT)
12715                 return(0);
12716         /*
12717          * If we are resource constrained on inode dependencies, try
12718          * flushing some dirty inodes. Otherwise, we are constrained
12719          * by file deletions, so try accelerating flushes of directories
12720          * with removal dependencies. We would like to do the cleanup
12721          * here, but we probably hold an inode locked at this point and 
12722          * that might deadlock against one that we try to clean. So,
12723          * the best that we can do is request the syncer daemon to do
12724          * the cleanup for us.
12725          */
12726         switch (resource) {
12727
12728         case FLUSH_INODES:
12729         case FLUSH_INODES_WAIT:
12730                 stat_ino_limit_push += 1;
12731                 req_clear_inodedeps += 1;
12732                 stat_countp = &stat_ino_limit_hit;
12733                 break;
12734
12735         case FLUSH_BLOCKS:
12736         case FLUSH_BLOCKS_WAIT:
12737                 stat_blk_limit_push += 1;
12738                 req_clear_remove += 1;
12739                 stat_countp = &stat_blk_limit_hit;
12740                 break;
12741
12742         default:
12743                 panic("request_cleanup: unknown type");
12744         }
12745         /*
12746          * Hopefully the syncer daemon will catch up and awaken us.
12747          * We wait at most tickdelay before proceeding in any case.
12748          */
12749         proc_waiting += 1;
12750         if (callout_pending(&softdep_callout) == FALSE)
12751                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
12752                     pause_timer, 0);
12753
12754         msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
12755         proc_waiting -= 1;
12756         return (1);
12757 }
12758
12759 /*
12760  * Awaken processes pausing in request_cleanup and clear proc_waiting
12761  * to indicate that there is no longer a timer running.
12762  */
12763 static void
12764 pause_timer(arg)
12765         void *arg;
12766 {
12767
12768         /*
12769          * The callout_ API has acquired mtx and will hold it around this
12770          * function call.
12771          */
12772         *stat_countp += 1;
12773         wakeup_one(&proc_waiting);
12774         if (proc_waiting > 0)
12775                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
12776                     pause_timer, 0);
12777 }
12778
12779 /*
12780  * Flush out a directory with at least one removal dependency in an effort to
12781  * reduce the number of dirrem, freefile, and freeblks dependency structures.
12782  */
12783 static void
12784 clear_remove(td)
12785         struct thread *td;
12786 {
12787         struct pagedep_hashhead *pagedephd;
12788         struct pagedep *pagedep;
12789         static int next = 0;
12790         struct mount *mp;
12791         struct vnode *vp;
12792         struct bufobj *bo;
12793         int error, cnt;
12794         ino_t ino;
12795
12796         mtx_assert(&lk, MA_OWNED);
12797
12798         for (cnt = 0; cnt < pagedep_hash; cnt++) {
12799                 pagedephd = &pagedep_hashtbl[next++];
12800                 if (next >= pagedep_hash)
12801                         next = 0;
12802                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
12803                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
12804                                 continue;
12805                         mp = pagedep->pd_list.wk_mp;
12806                         ino = pagedep->pd_ino;
12807                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
12808                                 continue;
12809                         FREE_LOCK(&lk);
12810
12811                         /*
12812                          * Let unmount clear deps
12813                          */
12814                         error = vfs_busy(mp, MBF_NOWAIT);
12815                         if (error != 0)
12816                                 goto finish_write;
12817                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
12818                              FFSV_FORCEINSMQ);
12819                         vfs_unbusy(mp);
12820                         if (error != 0) {
12821                                 softdep_error("clear_remove: vget", error);
12822                                 goto finish_write;
12823                         }
12824                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
12825                                 softdep_error("clear_remove: fsync", error);
12826                         bo = &vp->v_bufobj;
12827                         BO_LOCK(bo);
12828                         drain_output(vp);
12829                         BO_UNLOCK(bo);
12830                         vput(vp);
12831                 finish_write:
12832                         vn_finished_write(mp);
12833                         ACQUIRE_LOCK(&lk);
12834                         return;
12835                 }
12836         }
12837 }
12838
12839 /*
12840  * Clear out a block of dirty inodes in an effort to reduce
12841  * the number of inodedep dependency structures.
12842  */
12843 static void
12844 clear_inodedeps(td)
12845         struct thread *td;
12846 {
12847         struct inodedep_hashhead *inodedephd;
12848         struct inodedep *inodedep;
12849         static int next = 0;
12850         struct mount *mp;
12851         struct vnode *vp;
12852         struct fs *fs;
12853         int error, cnt;
12854         ino_t firstino, lastino, ino;
12855
12856         mtx_assert(&lk, MA_OWNED);
12857         /*
12858          * Pick a random inode dependency to be cleared.
12859          * We will then gather up all the inodes in its block 
12860          * that have dependencies and flush them out.
12861          */
12862         for (cnt = 0; cnt < inodedep_hash; cnt++) {
12863                 inodedephd = &inodedep_hashtbl[next++];
12864                 if (next >= inodedep_hash)
12865                         next = 0;
12866                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
12867                         break;
12868         }
12869         if (inodedep == NULL)
12870                 return;
12871         fs = inodedep->id_fs;
12872         mp = inodedep->id_list.wk_mp;
12873         /*
12874          * Find the last inode in the block with dependencies.
12875          */
12876         firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
12877         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
12878                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
12879                         break;
12880         /*
12881          * Asynchronously push all but the last inode with dependencies.
12882          * Synchronously push the last inode with dependencies to ensure
12883          * that the inode block gets written to free up the inodedeps.
12884          */
12885         for (ino = firstino; ino <= lastino; ino++) {
12886                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12887                         continue;
12888                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
12889                         continue;
12890                 FREE_LOCK(&lk);
12891                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
12892                 if (error != 0) {
12893                         vn_finished_write(mp);
12894                         ACQUIRE_LOCK(&lk);
12895                         return;
12896                 }
12897                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
12898                     FFSV_FORCEINSMQ)) != 0) {
12899                         softdep_error("clear_inodedeps: vget", error);
12900                         vfs_unbusy(mp);
12901                         vn_finished_write(mp);
12902                         ACQUIRE_LOCK(&lk);
12903                         return;
12904                 }
12905                 vfs_unbusy(mp);
12906                 if (ino == lastino) {
12907                         if ((error = ffs_syncvnode(vp, MNT_WAIT)))
12908                                 softdep_error("clear_inodedeps: fsync1", error);
12909                 } else {
12910                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
12911                                 softdep_error("clear_inodedeps: fsync2", error);
12912                         BO_LOCK(&vp->v_bufobj);
12913                         drain_output(vp);
12914                         BO_UNLOCK(&vp->v_bufobj);
12915                 }
12916                 vput(vp);
12917                 vn_finished_write(mp);
12918                 ACQUIRE_LOCK(&lk);
12919         }
12920 }
12921
12922 void
12923 softdep_buf_append(bp, wkhd)
12924         struct buf *bp;
12925         struct workhead *wkhd;
12926 {
12927         struct worklist *wk;
12928
12929         ACQUIRE_LOCK(&lk);
12930         while ((wk = LIST_FIRST(wkhd)) != NULL) {
12931                 WORKLIST_REMOVE(wk);
12932                 WORKLIST_INSERT(&bp->b_dep, wk);
12933         }
12934         FREE_LOCK(&lk);
12935
12936 }
12937
12938 void
12939 softdep_inode_append(ip, cred, wkhd)
12940         struct inode *ip;
12941         struct ucred *cred;
12942         struct workhead *wkhd;
12943 {
12944         struct buf *bp;
12945         struct fs *fs;
12946         int error;
12947
12948         fs = ip->i_fs;
12949         error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
12950             (int)fs->fs_bsize, cred, &bp);
12951         if (error) {
12952                 softdep_freework(wkhd);
12953                 return;
12954         }
12955         softdep_buf_append(bp, wkhd);
12956         bqrelse(bp);
12957 }
12958
12959 void
12960 softdep_freework(wkhd)
12961         struct workhead *wkhd;
12962 {
12963
12964         ACQUIRE_LOCK(&lk);
12965         handle_jwork(wkhd);
12966         FREE_LOCK(&lk);
12967 }
12968
12969 /*
12970  * Function to determine if the buffer has outstanding dependencies
12971  * that will cause a roll-back if the buffer is written. If wantcount
12972  * is set, return number of dependencies, otherwise just yes or no.
12973  */
12974 static int
12975 softdep_count_dependencies(bp, wantcount)
12976         struct buf *bp;
12977         int wantcount;
12978 {
12979         struct worklist *wk;
12980         struct bmsafemap *bmsafemap;
12981         struct freework *freework;
12982         struct inodedep *inodedep;
12983         struct indirdep *indirdep;
12984         struct freeblks *freeblks;
12985         struct allocindir *aip;
12986         struct pagedep *pagedep;
12987         struct dirrem *dirrem;
12988         struct newblk *newblk;
12989         struct mkdir *mkdir;
12990         struct diradd *dap;
12991         int i, retval;
12992
12993         retval = 0;
12994         ACQUIRE_LOCK(&lk);
12995         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12996                 switch (wk->wk_type) {
12997
12998                 case D_INODEDEP:
12999                         inodedep = WK_INODEDEP(wk);
13000                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13001                                 /* bitmap allocation dependency */
13002                                 retval += 1;
13003                                 if (!wantcount)
13004                                         goto out;
13005                         }
13006                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13007                                 /* direct block pointer dependency */
13008                                 retval += 1;
13009                                 if (!wantcount)
13010                                         goto out;
13011                         }
13012                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13013                                 /* direct block pointer dependency */
13014                                 retval += 1;
13015                                 if (!wantcount)
13016                                         goto out;
13017                         }
13018                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13019                                 /* Add reference dependency. */
13020                                 retval += 1;
13021                                 if (!wantcount)
13022                                         goto out;
13023                         }
13024                         continue;
13025
13026                 case D_INDIRDEP:
13027                         indirdep = WK_INDIRDEP(wk);
13028
13029                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13030                                 /* indirect truncation dependency */
13031                                 retval += 1;
13032                                 if (!wantcount)
13033                                         goto out;
13034                         }
13035
13036                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13037                                 /* indirect block pointer dependency */
13038                                 retval += 1;
13039                                 if (!wantcount)
13040                                         goto out;
13041                         }
13042                         continue;
13043
13044                 case D_PAGEDEP:
13045                         pagedep = WK_PAGEDEP(wk);
13046                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13047                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13048                                         /* Journal remove ref dependency. */
13049                                         retval += 1;
13050                                         if (!wantcount)
13051                                                 goto out;
13052                                 }
13053                         }
13054                         for (i = 0; i < DAHASHSZ; i++) {
13055
13056                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13057                                         /* directory entry dependency */
13058                                         retval += 1;
13059                                         if (!wantcount)
13060                                                 goto out;
13061                                 }
13062                         }
13063                         continue;
13064
13065                 case D_BMSAFEMAP:
13066                         bmsafemap = WK_BMSAFEMAP(wk);
13067                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13068                                 /* Add reference dependency. */
13069                                 retval += 1;
13070                                 if (!wantcount)
13071                                         goto out;
13072                         }
13073                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13074                                 /* Allocate block dependency. */
13075                                 retval += 1;
13076                                 if (!wantcount)
13077                                         goto out;
13078                         }
13079                         continue;
13080
13081                 case D_FREEBLKS:
13082                         freeblks = WK_FREEBLKS(wk);
13083                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13084                                 /* Freeblk journal dependency. */
13085                                 retval += 1;
13086                                 if (!wantcount)
13087                                         goto out;
13088                         }
13089                         continue;
13090
13091                 case D_ALLOCDIRECT:
13092                 case D_ALLOCINDIR:
13093                         newblk = WK_NEWBLK(wk);
13094                         if (newblk->nb_jnewblk) {
13095                                 /* Journal allocate dependency. */
13096                                 retval += 1;
13097                                 if (!wantcount)
13098                                         goto out;
13099                         }
13100                         continue;
13101
13102                 case D_MKDIR:
13103                         mkdir = WK_MKDIR(wk);
13104                         if (mkdir->md_jaddref) {
13105                                 /* Journal reference dependency. */
13106                                 retval += 1;
13107                                 if (!wantcount)
13108                                         goto out;
13109                         }
13110                         continue;
13111
13112                 case D_FREEWORK:
13113                 case D_FREEDEP:
13114                 case D_JSEGDEP:
13115                 case D_JSEG:
13116                 case D_SBDEP:
13117                         /* never a dependency on these blocks */
13118                         continue;
13119
13120                 default:
13121                         panic("softdep_count_dependencies: Unexpected type %s",
13122                             TYPENAME(wk->wk_type));
13123                         /* NOTREACHED */
13124                 }
13125         }
13126 out:
13127         FREE_LOCK(&lk);
13128         return retval;
13129 }
13130
13131 /*
13132  * Acquire exclusive access to a buffer.
13133  * Must be called with a locked mtx parameter.
13134  * Return acquired buffer or NULL on failure.
13135  */
13136 static struct buf *
13137 getdirtybuf(bp, mtx, waitfor)
13138         struct buf *bp;
13139         struct mtx *mtx;
13140         int waitfor;
13141 {
13142         int error;
13143
13144         mtx_assert(mtx, MA_OWNED);
13145         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13146                 if (waitfor != MNT_WAIT)
13147                         return (NULL);
13148                 error = BUF_LOCK(bp,
13149                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
13150                 /*
13151                  * Even if we sucessfully acquire bp here, we have dropped
13152                  * mtx, which may violates our guarantee.
13153                  */
13154                 if (error == 0)
13155                         BUF_UNLOCK(bp);
13156                 else if (error != ENOLCK)
13157                         panic("getdirtybuf: inconsistent lock: %d", error);
13158                 mtx_lock(mtx);
13159                 return (NULL);
13160         }
13161         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13162                 if (mtx == &lk && waitfor == MNT_WAIT) {
13163                         mtx_unlock(mtx);
13164                         BO_LOCK(bp->b_bufobj);
13165                         BUF_UNLOCK(bp);
13166                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13167                                 bp->b_vflags |= BV_BKGRDWAIT;
13168                                 msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
13169                                        PRIBIO | PDROP, "getbuf", 0);
13170                         } else
13171                                 BO_UNLOCK(bp->b_bufobj);
13172                         mtx_lock(mtx);
13173                         return (NULL);
13174                 }
13175                 BUF_UNLOCK(bp);
13176                 if (waitfor != MNT_WAIT)
13177                         return (NULL);
13178                 /*
13179                  * The mtx argument must be bp->b_vp's mutex in
13180                  * this case.
13181                  */
13182 #ifdef  DEBUG_VFS_LOCKS
13183                 if (bp->b_vp->v_type != VCHR)
13184                         ASSERT_BO_LOCKED(bp->b_bufobj);
13185 #endif
13186                 bp->b_vflags |= BV_BKGRDWAIT;
13187                 msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
13188                 return (NULL);
13189         }
13190         if ((bp->b_flags & B_DELWRI) == 0) {
13191                 BUF_UNLOCK(bp);
13192                 return (NULL);
13193         }
13194         bremfree(bp);
13195         return (bp);
13196 }
13197
13198
13199 /*
13200  * Check if it is safe to suspend the file system now.  On entry,
13201  * the vnode interlock for devvp should be held.  Return 0 with
13202  * the mount interlock held if the file system can be suspended now,
13203  * otherwise return EAGAIN with the mount interlock held.
13204  */
13205 int
13206 softdep_check_suspend(struct mount *mp,
13207                       struct vnode *devvp,
13208                       int softdep_deps,
13209                       int softdep_accdeps,
13210                       int secondary_writes,
13211                       int secondary_accwrites)
13212 {
13213         struct bufobj *bo;
13214         struct ufsmount *ump;
13215         int error;
13216
13217         ump = VFSTOUFS(mp);
13218         bo = &devvp->v_bufobj;
13219         ASSERT_BO_LOCKED(bo);
13220
13221         for (;;) {
13222                 if (!TRY_ACQUIRE_LOCK(&lk)) {
13223                         BO_UNLOCK(bo);
13224                         ACQUIRE_LOCK(&lk);
13225                         FREE_LOCK(&lk);
13226                         BO_LOCK(bo);
13227                         continue;
13228                 }
13229                 MNT_ILOCK(mp);
13230                 if (mp->mnt_secondary_writes != 0) {
13231                         FREE_LOCK(&lk);
13232                         BO_UNLOCK(bo);
13233                         msleep(&mp->mnt_secondary_writes,
13234                                MNT_MTX(mp),
13235                                (PUSER - 1) | PDROP, "secwr", 0);
13236                         BO_LOCK(bo);
13237                         continue;
13238                 }
13239                 break;
13240         }
13241
13242         /*
13243          * Reasons for needing more work before suspend:
13244          * - Dirty buffers on devvp.
13245          * - Softdep activity occurred after start of vnode sync loop
13246          * - Secondary writes occurred after start of vnode sync loop
13247          */
13248         error = 0;
13249         if (bo->bo_numoutput > 0 ||
13250             bo->bo_dirty.bv_cnt > 0 ||
13251             softdep_deps != 0 ||
13252             ump->softdep_deps != 0 ||
13253             softdep_accdeps != ump->softdep_accdeps ||
13254             secondary_writes != 0 ||
13255             mp->mnt_secondary_writes != 0 ||
13256             secondary_accwrites != mp->mnt_secondary_accwrites)
13257                 error = EAGAIN;
13258         FREE_LOCK(&lk);
13259         BO_UNLOCK(bo);
13260         return (error);
13261 }
13262
13263
13264 /*
13265  * Get the number of dependency structures for the file system, both
13266  * the current number and the total number allocated.  These will
13267  * later be used to detect that softdep processing has occurred.
13268  */
13269 void
13270 softdep_get_depcounts(struct mount *mp,
13271                       int *softdep_depsp,
13272                       int *softdep_accdepsp)
13273 {
13274         struct ufsmount *ump;
13275
13276         ump = VFSTOUFS(mp);
13277         ACQUIRE_LOCK(&lk);
13278         *softdep_depsp = ump->softdep_deps;
13279         *softdep_accdepsp = ump->softdep_accdeps;
13280         FREE_LOCK(&lk);
13281 }
13282
13283 /*
13284  * Wait for pending output on a vnode to complete.
13285  * Must be called with vnode lock and interlock locked.
13286  *
13287  * XXX: Should just be a call to bufobj_wwait().
13288  */
13289 static void
13290 drain_output(vp)
13291         struct vnode *vp;
13292 {
13293         struct bufobj *bo;
13294
13295         bo = &vp->v_bufobj;
13296         ASSERT_VOP_LOCKED(vp, "drain_output");
13297         ASSERT_BO_LOCKED(bo);
13298
13299         while (bo->bo_numoutput) {
13300                 bo->bo_flag |= BO_WWAIT;
13301                 msleep((caddr_t)&bo->bo_numoutput,
13302                     BO_MTX(bo), PRIBIO + 1, "drainvp", 0);
13303         }
13304 }
13305
13306 /*
13307  * Called whenever a buffer that is being invalidated or reallocated
13308  * contains dependencies. This should only happen if an I/O error has
13309  * occurred. The routine is called with the buffer locked.
13310  */ 
13311 static void
13312 softdep_deallocate_dependencies(bp)
13313         struct buf *bp;
13314 {
13315
13316         if ((bp->b_ioflags & BIO_ERROR) == 0)
13317                 panic("softdep_deallocate_dependencies: dangling deps");
13318         softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
13319         panic("softdep_deallocate_dependencies: unrecovered I/O error");
13320 }
13321
13322 /*
13323  * Function to handle asynchronous write errors in the filesystem.
13324  */
13325 static void
13326 softdep_error(func, error)
13327         char *func;
13328         int error;
13329 {
13330
13331         /* XXX should do something better! */
13332         printf("%s: got error %d while accessing filesystem\n", func, error);
13333 }
13334
13335 #ifdef DDB
13336
13337 static void
13338 inodedep_print(struct inodedep *inodedep, int verbose)
13339 {
13340         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
13341             " saveino %p\n",
13342             inodedep, inodedep->id_fs, inodedep->id_state,
13343             (intmax_t)inodedep->id_ino,
13344             (intmax_t)fsbtodb(inodedep->id_fs,
13345             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
13346             inodedep->id_nlinkdelta, inodedep->id_savednlink,
13347             inodedep->id_savedino1);
13348
13349         if (verbose == 0)
13350                 return;
13351
13352         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
13353             "mkdiradd %p\n",
13354             LIST_FIRST(&inodedep->id_pendinghd),
13355             LIST_FIRST(&inodedep->id_bufwait),
13356             LIST_FIRST(&inodedep->id_inowait),
13357             TAILQ_FIRST(&inodedep->id_inoreflst),
13358             inodedep->id_mkdiradd);
13359         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
13360             TAILQ_FIRST(&inodedep->id_inoupdt),
13361             TAILQ_FIRST(&inodedep->id_newinoupdt),
13362             TAILQ_FIRST(&inodedep->id_extupdt),
13363             TAILQ_FIRST(&inodedep->id_newextupdt));
13364 }
13365
13366 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
13367 {
13368
13369         if (have_addr == 0) {
13370                 db_printf("Address required\n");
13371                 return;
13372         }
13373         inodedep_print((struct inodedep*)addr, 1);
13374 }
13375
13376 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
13377 {
13378         struct inodedep_hashhead *inodedephd;
13379         struct inodedep *inodedep;
13380         struct fs *fs;
13381         int cnt;
13382
13383         fs = have_addr ? (struct fs *)addr : NULL;
13384         for (cnt = 0; cnt < inodedep_hash; cnt++) {
13385                 inodedephd = &inodedep_hashtbl[cnt];
13386                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
13387                         if (fs != NULL && fs != inodedep->id_fs)
13388                                 continue;
13389                         inodedep_print(inodedep, 0);
13390                 }
13391         }
13392 }
13393
13394 DB_SHOW_COMMAND(worklist, db_show_worklist)
13395 {
13396         struct worklist *wk;
13397
13398         if (have_addr == 0) {
13399                 db_printf("Address required\n");
13400                 return;
13401         }
13402         wk = (struct worklist *)addr;
13403         printf("worklist: %p type %s state 0x%X\n",
13404             wk, TYPENAME(wk->wk_type), wk->wk_state);
13405 }
13406
13407 DB_SHOW_COMMAND(workhead, db_show_workhead)
13408 {
13409         struct workhead *wkhd;
13410         struct worklist *wk;
13411         int i;
13412
13413         if (have_addr == 0) {
13414                 db_printf("Address required\n");
13415                 return;
13416         }
13417         wkhd = (struct workhead *)addr;
13418         wk = LIST_FIRST(wkhd);
13419         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
13420                 db_printf("worklist: %p type %s state 0x%X",
13421                     wk, TYPENAME(wk->wk_type), wk->wk_state);
13422         if (i == 100)
13423                 db_printf("workhead overflow");
13424         printf("\n");
13425 }
13426
13427
13428 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
13429 {
13430         struct jaddref *jaddref;
13431         struct diradd *diradd;
13432         struct mkdir *mkdir;
13433
13434         LIST_FOREACH(mkdir, &mkdirlisthd, md_mkdirs) {
13435                 diradd = mkdir->md_diradd;
13436                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
13437                     mkdir, mkdir->md_state, diradd, diradd->da_state);
13438                 if ((jaddref = mkdir->md_jaddref) != NULL)
13439                         db_printf(" jaddref %p jaddref state 0x%X",
13440                             jaddref, jaddref->ja_state);
13441                 db_printf("\n");
13442         }
13443 }
13444
13445 #endif /* DDB */
13446
13447 #endif /* SOFTUPDATES */