]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
Import DTS files from Linux 5.4
[FreeBSD/FreeBSD.git] / sys / ufs / ffs / ffs_softdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *      Marshall Kirk McKusick          http://www.mckusick.com/softdep/
16  *      1614 Oxford Street              mckusick@mckusick.com
17  *      Berkeley, CA 94709-1608         +1-510-843-9542
18  *      USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *      from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
42  */
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88
89 #include <geom/geom.h>
90
91 #include <ddb/ddb.h>
92
93 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
94
95 #ifndef SOFTUPDATES
96
97 int
98 softdep_flushfiles(oldmnt, flags, td)
99         struct mount *oldmnt;
100         int flags;
101         struct thread *td;
102 {
103
104         panic("softdep_flushfiles called");
105 }
106
107 int
108 softdep_mount(devvp, mp, fs, cred)
109         struct vnode *devvp;
110         struct mount *mp;
111         struct fs *fs;
112         struct ucred *cred;
113 {
114
115         return (0);
116 }
117
118 void
119 softdep_initialize()
120 {
121
122         return;
123 }
124
125 void
126 softdep_uninitialize()
127 {
128
129         return;
130 }
131
132 void
133 softdep_unmount(mp)
134         struct mount *mp;
135 {
136
137         panic("softdep_unmount called");
138 }
139
140 void
141 softdep_setup_sbupdate(ump, fs, bp)
142         struct ufsmount *ump;
143         struct fs *fs;
144         struct buf *bp;
145 {
146
147         panic("softdep_setup_sbupdate called");
148 }
149
150 void
151 softdep_setup_inomapdep(bp, ip, newinum, mode)
152         struct buf *bp;
153         struct inode *ip;
154         ino_t newinum;
155         int mode;
156 {
157
158         panic("softdep_setup_inomapdep called");
159 }
160
161 void
162 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
163         struct buf *bp;
164         struct mount *mp;
165         ufs2_daddr_t newblkno;
166         int frags;
167         int oldfrags;
168 {
169
170         panic("softdep_setup_blkmapdep called");
171 }
172
173 void
174 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
175         struct inode *ip;
176         ufs_lbn_t lbn;
177         ufs2_daddr_t newblkno;
178         ufs2_daddr_t oldblkno;
179         long newsize;
180         long oldsize;
181         struct buf *bp;
182 {
183         
184         panic("softdep_setup_allocdirect called");
185 }
186
187 void
188 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
189         struct inode *ip;
190         ufs_lbn_t lbn;
191         ufs2_daddr_t newblkno;
192         ufs2_daddr_t oldblkno;
193         long newsize;
194         long oldsize;
195         struct buf *bp;
196 {
197         
198         panic("softdep_setup_allocext called");
199 }
200
201 void
202 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
203         struct inode *ip;
204         ufs_lbn_t lbn;
205         struct buf *bp;
206         int ptrno;
207         ufs2_daddr_t newblkno;
208         ufs2_daddr_t oldblkno;
209         struct buf *nbp;
210 {
211
212         panic("softdep_setup_allocindir_page called");
213 }
214
215 void
216 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
217         struct buf *nbp;
218         struct inode *ip;
219         struct buf *bp;
220         int ptrno;
221         ufs2_daddr_t newblkno;
222 {
223
224         panic("softdep_setup_allocindir_meta called");
225 }
226
227 void
228 softdep_journal_freeblocks(ip, cred, length, flags)
229         struct inode *ip;
230         struct ucred *cred;
231         off_t length;
232         int flags;
233 {
234         
235         panic("softdep_journal_freeblocks called");
236 }
237
238 void
239 softdep_journal_fsync(ip)
240         struct inode *ip;
241 {
242
243         panic("softdep_journal_fsync called");
244 }
245
246 void
247 softdep_setup_freeblocks(ip, length, flags)
248         struct inode *ip;
249         off_t length;
250         int flags;
251 {
252         
253         panic("softdep_setup_freeblocks called");
254 }
255
256 void
257 softdep_freefile(pvp, ino, mode)
258                 struct vnode *pvp;
259                 ino_t ino;
260                 int mode;
261 {
262
263         panic("softdep_freefile called");
264 }
265
266 int
267 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
268         struct buf *bp;
269         struct inode *dp;
270         off_t diroffset;
271         ino_t newinum;
272         struct buf *newdirbp;
273         int isnewblk;
274 {
275
276         panic("softdep_setup_directory_add called");
277 }
278
279 void
280 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
281         struct buf *bp;
282         struct inode *dp;
283         caddr_t base;
284         caddr_t oldloc;
285         caddr_t newloc;
286         int entrysize;
287 {
288
289         panic("softdep_change_directoryentry_offset called");
290 }
291
292 void
293 softdep_setup_remove(bp, dp, ip, isrmdir)
294         struct buf *bp;
295         struct inode *dp;
296         struct inode *ip;
297         int isrmdir;
298 {
299         
300         panic("softdep_setup_remove called");
301 }
302
303 void
304 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
305         struct buf *bp;
306         struct inode *dp;
307         struct inode *ip;
308         ino_t newinum;
309         int isrmdir;
310 {
311
312         panic("softdep_setup_directory_change called");
313 }
314
315 void
316 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
317         struct mount *mp;
318         struct buf *bp;
319         ufs2_daddr_t blkno;
320         int frags;
321         struct workhead *wkhd;
322 {
323
324         panic("%s called", __FUNCTION__);
325 }
326
327 void
328 softdep_setup_inofree(mp, bp, ino, wkhd)
329         struct mount *mp;
330         struct buf *bp;
331         ino_t ino;
332         struct workhead *wkhd;
333 {
334
335         panic("%s called", __FUNCTION__);
336 }
337
338 void
339 softdep_setup_unlink(dp, ip)
340         struct inode *dp;
341         struct inode *ip;
342 {
343
344         panic("%s called", __FUNCTION__);
345 }
346
347 void
348 softdep_setup_link(dp, ip)
349         struct inode *dp;
350         struct inode *ip;
351 {
352
353         panic("%s called", __FUNCTION__);
354 }
355
356 void
357 softdep_revert_link(dp, ip)
358         struct inode *dp;
359         struct inode *ip;
360 {
361
362         panic("%s called", __FUNCTION__);
363 }
364
365 void
366 softdep_setup_rmdir(dp, ip)
367         struct inode *dp;
368         struct inode *ip;
369 {
370
371         panic("%s called", __FUNCTION__);
372 }
373
374 void
375 softdep_revert_rmdir(dp, ip)
376         struct inode *dp;
377         struct inode *ip;
378 {
379
380         panic("%s called", __FUNCTION__);
381 }
382
383 void
384 softdep_setup_create(dp, ip)
385         struct inode *dp;
386         struct inode *ip;
387 {
388
389         panic("%s called", __FUNCTION__);
390 }
391
392 void
393 softdep_revert_create(dp, ip)
394         struct inode *dp;
395         struct inode *ip;
396 {
397
398         panic("%s called", __FUNCTION__);
399 }
400
401 void
402 softdep_setup_mkdir(dp, ip)
403         struct inode *dp;
404         struct inode *ip;
405 {
406
407         panic("%s called", __FUNCTION__);
408 }
409
410 void
411 softdep_revert_mkdir(dp, ip)
412         struct inode *dp;
413         struct inode *ip;
414 {
415
416         panic("%s called", __FUNCTION__);
417 }
418
419 void
420 softdep_setup_dotdot_link(dp, ip)
421         struct inode *dp;
422         struct inode *ip;
423 {
424
425         panic("%s called", __FUNCTION__);
426 }
427
428 int
429 softdep_prealloc(vp, waitok)
430         struct vnode *vp;
431         int waitok;
432 {
433
434         panic("%s called", __FUNCTION__);
435 }
436
437 int
438 softdep_journal_lookup(mp, vpp)
439         struct mount *mp;
440         struct vnode **vpp;
441 {
442
443         return (ENOENT);
444 }
445
446 void
447 softdep_change_linkcnt(ip)
448         struct inode *ip;
449 {
450
451         panic("softdep_change_linkcnt called");
452 }
453
454 void 
455 softdep_load_inodeblock(ip)
456         struct inode *ip;
457 {
458
459         panic("softdep_load_inodeblock called");
460 }
461
462 void
463 softdep_update_inodeblock(ip, bp, waitfor)
464         struct inode *ip;
465         struct buf *bp;
466         int waitfor;
467 {
468
469         panic("softdep_update_inodeblock called");
470 }
471
472 int
473 softdep_fsync(vp)
474         struct vnode *vp;       /* the "in_core" copy of the inode */
475 {
476
477         return (0);
478 }
479
480 void
481 softdep_fsync_mountdev(vp)
482         struct vnode *vp;
483 {
484
485         return;
486 }
487
488 int
489 softdep_flushworklist(oldmnt, countp, td)
490         struct mount *oldmnt;
491         int *countp;
492         struct thread *td;
493 {
494
495         *countp = 0;
496         return (0);
497 }
498
499 int
500 softdep_sync_metadata(struct vnode *vp)
501 {
502
503         panic("softdep_sync_metadata called");
504 }
505
506 int
507 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
508 {
509
510         panic("softdep_sync_buf called");
511 }
512
513 int
514 softdep_slowdown(vp)
515         struct vnode *vp;
516 {
517
518         panic("softdep_slowdown called");
519 }
520
521 int
522 softdep_request_cleanup(fs, vp, cred, resource)
523         struct fs *fs;
524         struct vnode *vp;
525         struct ucred *cred;
526         int resource;
527 {
528
529         return (0);
530 }
531
532 int
533 softdep_check_suspend(struct mount *mp,
534                       struct vnode *devvp,
535                       int softdep_depcnt,
536                       int softdep_accdepcnt,
537                       int secondary_writes,
538                       int secondary_accwrites)
539 {
540         struct bufobj *bo;
541         int error;
542         
543         (void) softdep_depcnt,
544         (void) softdep_accdepcnt;
545
546         bo = &devvp->v_bufobj;
547         ASSERT_BO_WLOCKED(bo);
548
549         MNT_ILOCK(mp);
550         while (mp->mnt_secondary_writes != 0) {
551                 BO_UNLOCK(bo);
552                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
553                     (PUSER - 1) | PDROP, "secwr", 0);
554                 BO_LOCK(bo);
555                 MNT_ILOCK(mp);
556         }
557
558         /*
559          * Reasons for needing more work before suspend:
560          * - Dirty buffers on devvp.
561          * - Secondary writes occurred after start of vnode sync loop
562          */
563         error = 0;
564         if (bo->bo_numoutput > 0 ||
565             bo->bo_dirty.bv_cnt > 0 ||
566             secondary_writes != 0 ||
567             mp->mnt_secondary_writes != 0 ||
568             secondary_accwrites != mp->mnt_secondary_accwrites)
569                 error = EAGAIN;
570         BO_UNLOCK(bo);
571         return (error);
572 }
573
574 void
575 softdep_get_depcounts(struct mount *mp,
576                       int *softdepactivep,
577                       int *softdepactiveaccp)
578 {
579         (void) mp;
580         *softdepactivep = 0;
581         *softdepactiveaccp = 0;
582 }
583
584 void
585 softdep_buf_append(bp, wkhd)
586         struct buf *bp;
587         struct workhead *wkhd;
588 {
589
590         panic("softdep_buf_appendwork called");
591 }
592
593 void
594 softdep_inode_append(ip, cred, wkhd)
595         struct inode *ip;
596         struct ucred *cred;
597         struct workhead *wkhd;
598 {
599
600         panic("softdep_inode_appendwork called");
601 }
602
603 void
604 softdep_freework(wkhd)
605         struct workhead *wkhd;
606 {
607
608         panic("softdep_freework called");
609 }
610
611 #else
612
613 FEATURE(softupdates, "FFS soft-updates support");
614
615 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
616     "soft updates stats");
617 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
618     "total dependencies allocated");
619 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
620     "high use dependencies allocated");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
622     "current dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
624     "current dependencies written");
625
626 unsigned long dep_current[D_LAST + 1];
627 unsigned long dep_highuse[D_LAST + 1];
628 unsigned long dep_total[D_LAST + 1];
629 unsigned long dep_write[D_LAST + 1];
630
631 #define SOFTDEP_TYPE(type, str, long)                                   \
632     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
633     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
634         &dep_total[D_ ## type], 0, "");                                 \
635     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
636         &dep_current[D_ ## type], 0, "");                               \
637     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
638         &dep_highuse[D_ ## type], 0, "");                               \
639     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
640         &dep_write[D_ ## type], 0, "");
641
642 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
643 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
644 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
645     "Block or frag allocated from cyl group map");
646 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
647 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
648 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
649 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
650 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
651 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
652 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
653 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
654 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
655 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
656 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
657 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
658 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
659 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
660 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
661 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
662 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
663 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
664 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
665 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
666 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
667 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
668 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
669 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
670
671 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
672
673 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
674 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
675 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
676
677 #define M_SOFTDEP_FLAGS (M_WAITOK)
678
679 /* 
680  * translate from workitem type to memory type
681  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
682  */
683 static struct malloc_type *memtype[] = {
684         NULL,
685         M_PAGEDEP,
686         M_INODEDEP,
687         M_BMSAFEMAP,
688         M_NEWBLK,
689         M_ALLOCDIRECT,
690         M_INDIRDEP,
691         M_ALLOCINDIR,
692         M_FREEFRAG,
693         M_FREEBLKS,
694         M_FREEFILE,
695         M_DIRADD,
696         M_MKDIR,
697         M_DIRREM,
698         M_NEWDIRBLK,
699         M_FREEWORK,
700         M_FREEDEP,
701         M_JADDREF,
702         M_JREMREF,
703         M_JMVREF,
704         M_JNEWBLK,
705         M_JFREEBLK,
706         M_JFREEFRAG,
707         M_JSEG,
708         M_JSEGDEP,
709         M_SBDEP,
710         M_JTRUNC,
711         M_JFSYNC,
712         M_SENTINEL
713 };
714
715 #define DtoM(type) (memtype[type])
716
717 /*
718  * Names of malloc types.
719  */
720 #define TYPENAME(type)  \
721         ((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
722         memtype[type]->ks_shortdesc : "???")
723 /*
724  * End system adaptation definitions.
725  */
726
727 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
728 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
729
730 /*
731  * Internal function prototypes.
732  */
733 static  void check_clear_deps(struct mount *);
734 static  void softdep_error(char *, int);
735 static  int softdep_process_worklist(struct mount *, int);
736 static  int softdep_waitidle(struct mount *, int);
737 static  void drain_output(struct vnode *);
738 static  struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
739 static  int check_inodedep_free(struct inodedep *);
740 static  void clear_remove(struct mount *);
741 static  void clear_inodedeps(struct mount *);
742 static  void unlinked_inodedep(struct mount *, struct inodedep *);
743 static  void clear_unlinked_inodedep(struct inodedep *);
744 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
745 static  int flush_pagedep_deps(struct vnode *, struct mount *,
746             struct diraddhd *);
747 static  int free_pagedep(struct pagedep *);
748 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
749 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
750 static  int flush_deplist(struct allocdirectlst *, int, int *);
751 static  int sync_cgs(struct mount *, int);
752 static  int handle_written_filepage(struct pagedep *, struct buf *, int);
753 static  int handle_written_sbdep(struct sbdep *, struct buf *);
754 static  void initiate_write_sbdep(struct sbdep *);
755 static  void diradd_inode_written(struct diradd *, struct inodedep *);
756 static  int handle_written_indirdep(struct indirdep *, struct buf *,
757             struct buf**, int);
758 static  int handle_written_inodeblock(struct inodedep *, struct buf *, int);
759 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
760             uint8_t *);
761 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
762 static  void handle_written_jaddref(struct jaddref *);
763 static  void handle_written_jremref(struct jremref *);
764 static  void handle_written_jseg(struct jseg *, struct buf *);
765 static  void handle_written_jnewblk(struct jnewblk *);
766 static  void handle_written_jblkdep(struct jblkdep *);
767 static  void handle_written_jfreefrag(struct jfreefrag *);
768 static  void complete_jseg(struct jseg *);
769 static  void complete_jsegs(struct jseg *);
770 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
771 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
772 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
773 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
774 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
775 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
776 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
777 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
778 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
779 static  inline void inoref_write(struct inoref *, struct jseg *,
780             struct jrefrec *);
781 static  void handle_allocdirect_partdone(struct allocdirect *,
782             struct workhead *);
783 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
784             struct workhead *);
785 static  void indirdep_complete(struct indirdep *);
786 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
787 static  void indirblk_insert(struct freework *);
788 static  void indirblk_remove(struct freework *);
789 static  void handle_allocindir_partdone(struct allocindir *);
790 static  void initiate_write_filepage(struct pagedep *, struct buf *);
791 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
792 static  void handle_written_mkdir(struct mkdir *, int);
793 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
794             uint8_t *);
795 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
796 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
797 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
798 static  void handle_workitem_freefile(struct freefile *);
799 static  int handle_workitem_remove(struct dirrem *, int);
800 static  struct dirrem *newdirrem(struct buf *, struct inode *,
801             struct inode *, int, struct dirrem **);
802 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
803             struct buf *);
804 static  void cancel_indirdep(struct indirdep *, struct buf *,
805             struct freeblks *);
806 static  void free_indirdep(struct indirdep *);
807 static  void free_diradd(struct diradd *, struct workhead *);
808 static  void merge_diradd(struct inodedep *, struct diradd *);
809 static  void complete_diradd(struct diradd *);
810 static  struct diradd *diradd_lookup(struct pagedep *, int);
811 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
812             struct jremref *);
813 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
814             struct jremref *);
815 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
816             struct jremref *, struct jremref *);
817 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
818             struct jremref *);
819 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
820             struct freeblks *, int);
821 static  int setup_trunc_indir(struct freeblks *, struct inode *,
822             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
823 static  void complete_trunc_indir(struct freework *);
824 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
825             int);
826 static  void complete_mkdir(struct mkdir *);
827 static  void free_newdirblk(struct newdirblk *);
828 static  void free_jremref(struct jremref *);
829 static  void free_jaddref(struct jaddref *);
830 static  void free_jsegdep(struct jsegdep *);
831 static  void free_jsegs(struct jblocks *);
832 static  void rele_jseg(struct jseg *);
833 static  void free_jseg(struct jseg *, struct jblocks *);
834 static  void free_jnewblk(struct jnewblk *);
835 static  void free_jblkdep(struct jblkdep *);
836 static  void free_jfreefrag(struct jfreefrag *);
837 static  void free_freedep(struct freedep *);
838 static  void journal_jremref(struct dirrem *, struct jremref *,
839             struct inodedep *);
840 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
841 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
842             struct workhead *);
843 static  void cancel_jfreefrag(struct jfreefrag *);
844 static  inline void setup_freedirect(struct freeblks *, struct inode *,
845             int, int);
846 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
847 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
848             ufs_lbn_t, int);
849 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
850 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
851 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
852 static  ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
853 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
854 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
855             int, int);
856 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
857 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
858 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
859 static  void newblk_freefrag(struct newblk*);
860 static  void free_newblk(struct newblk *);
861 static  void cancel_allocdirect(struct allocdirectlst *,
862             struct allocdirect *, struct freeblks *);
863 static  int check_inode_unwritten(struct inodedep *);
864 static  int free_inodedep(struct inodedep *);
865 static  void freework_freeblock(struct freework *, u_long);
866 static  void freework_enqueue(struct freework *);
867 static  int handle_workitem_freeblocks(struct freeblks *, int);
868 static  int handle_complete_freeblocks(struct freeblks *, int);
869 static  void handle_workitem_indirblk(struct freework *);
870 static  void handle_written_freework(struct freework *);
871 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
872 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
873             struct workhead *);
874 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
875             struct inodedep *, struct allocindir *, ufs_lbn_t);
876 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
877             ufs2_daddr_t, ufs_lbn_t);
878 static  void handle_workitem_freefrag(struct freefrag *);
879 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
880             ufs_lbn_t, u_long);
881 static  void allocdirect_merge(struct allocdirectlst *,
882             struct allocdirect *, struct allocdirect *);
883 static  struct freefrag *allocindir_merge(struct allocindir *,
884             struct allocindir *);
885 static  int bmsafemap_find(struct bmsafemap_hashhead *, int,
886             struct bmsafemap **);
887 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
888             int cg, struct bmsafemap *);
889 static  int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
890             struct newblk **);
891 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
892 static  int inodedep_find(struct inodedep_hashhead *, ino_t,
893             struct inodedep **);
894 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
895 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
896             int, struct pagedep **);
897 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
898             struct pagedep **);
899 static  void pause_timer(void *);
900 static  int request_cleanup(struct mount *, int);
901 static  int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
902 static  void schedule_cleanup(struct mount *);
903 static void softdep_ast_cleanup_proc(struct thread *);
904 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
905 static  int process_worklist_item(struct mount *, int, int);
906 static  void process_removes(struct vnode *);
907 static  void process_truncates(struct vnode *);
908 static  void jwork_move(struct workhead *, struct workhead *);
909 static  void jwork_insert(struct workhead *, struct jsegdep *);
910 static  void add_to_worklist(struct worklist *, int);
911 static  void wake_worklist(struct worklist *);
912 static  void wait_worklist(struct worklist *, char *);
913 static  void remove_from_worklist(struct worklist *);
914 static  void softdep_flush(void *);
915 static  void softdep_flushjournal(struct mount *);
916 static  int softdep_speedup(struct ufsmount *);
917 static  void worklist_speedup(struct mount *);
918 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
919 static  void journal_unmount(struct ufsmount *);
920 static  int journal_space(struct ufsmount *, int);
921 static  void journal_suspend(struct ufsmount *);
922 static  int journal_unsuspend(struct ufsmount *ump);
923 static  void softdep_prelink(struct vnode *, struct vnode *);
924 static  void add_to_journal(struct worklist *);
925 static  void remove_from_journal(struct worklist *);
926 static  bool softdep_excess_items(struct ufsmount *, int);
927 static  void softdep_process_journal(struct mount *, struct worklist *, int);
928 static  struct jremref *newjremref(struct dirrem *, struct inode *,
929             struct inode *ip, off_t, nlink_t);
930 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
931             uint16_t);
932 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
933             uint16_t);
934 static  inline struct jsegdep *inoref_jseg(struct inoref *);
935 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
936 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
937             ufs2_daddr_t, int);
938 static  void adjust_newfreework(struct freeblks *, int);
939 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
940 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
941 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
942 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
943             ufs2_daddr_t, long, ufs_lbn_t);
944 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
945             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
946 static  int jwait(struct worklist *, int);
947 static  struct inodedep *inodedep_lookup_ip(struct inode *);
948 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
949 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
950 static  void handle_jwork(struct workhead *);
951 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
952             struct mkdir **);
953 static  struct jblocks *jblocks_create(void);
954 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
955 static  void jblocks_free(struct jblocks *, struct mount *, int);
956 static  void jblocks_destroy(struct jblocks *);
957 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
958
959 /*
960  * Exported softdep operations.
961  */
962 static  void softdep_disk_io_initiation(struct buf *);
963 static  void softdep_disk_write_complete(struct buf *);
964 static  void softdep_deallocate_dependencies(struct buf *);
965 static  int softdep_count_dependencies(struct buf *bp, int);
966
967 /*
968  * Global lock over all of soft updates.
969  */
970 static struct mtx lk;
971 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
972
973 #define ACQUIRE_GBLLOCK(lk)     mtx_lock(lk)
974 #define FREE_GBLLOCK(lk)        mtx_unlock(lk)
975 #define GBLLOCK_OWNED(lk)       mtx_assert((lk), MA_OWNED)
976
977 /*
978  * Per-filesystem soft-updates locking.
979  */
980 #define LOCK_PTR(ump)           (&(ump)->um_softdep->sd_fslock)
981 #define TRY_ACQUIRE_LOCK(ump)   rw_try_wlock(&(ump)->um_softdep->sd_fslock)
982 #define ACQUIRE_LOCK(ump)       rw_wlock(&(ump)->um_softdep->sd_fslock)
983 #define FREE_LOCK(ump)          rw_wunlock(&(ump)->um_softdep->sd_fslock)
984 #define LOCK_OWNED(ump)         rw_assert(&(ump)->um_softdep->sd_fslock, \
985                                     RA_WLOCKED)
986
987 #define BUF_AREC(bp)            lockallowrecurse(&(bp)->b_lock)
988 #define BUF_NOREC(bp)           lockdisablerecurse(&(bp)->b_lock)
989
990 /*
991  * Worklist queue management.
992  * These routines require that the lock be held.
993  */
994 #ifndef /* NOT */ INVARIANTS
995 #define WORKLIST_INSERT(head, item) do {        \
996         (item)->wk_state |= ONWORKLIST;         \
997         LIST_INSERT_HEAD(head, item, wk_list);  \
998 } while (0)
999 #define WORKLIST_REMOVE(item) do {              \
1000         (item)->wk_state &= ~ONWORKLIST;        \
1001         LIST_REMOVE(item, wk_list);             \
1002 } while (0)
1003 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1004 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1005
1006 #else /* INVARIANTS */
1007 static  void worklist_insert(struct workhead *, struct worklist *, int,
1008         const char *, int);
1009 static  void worklist_remove(struct worklist *, int, const char *, int);
1010
1011 #define WORKLIST_INSERT(head, item) \
1012         worklist_insert(head, item, 1, __func__, __LINE__)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1014         worklist_insert(head, item, 0, __func__, __LINE__)
1015 #define WORKLIST_REMOVE(item)\
1016         worklist_remove(item, 1, __func__, __LINE__)
1017 #define WORKLIST_REMOVE_UNLOCKED(item)\
1018         worklist_remove(item, 0, __func__, __LINE__)
1019
1020 static void
1021 worklist_insert(head, item, locked, func, line)
1022         struct workhead *head;
1023         struct worklist *item;
1024         int locked;
1025         const char *func;
1026         int line;
1027 {
1028
1029         if (locked)
1030                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031         if (item->wk_state & ONWORKLIST)
1032                 panic("worklist_insert: %p %s(0x%X) already on list, "
1033                     "added in function %s at line %d",
1034                     item, TYPENAME(item->wk_type), item->wk_state,
1035                     item->wk_func, item->wk_line);
1036         item->wk_state |= ONWORKLIST;
1037         item->wk_func = func;
1038         item->wk_line = line;
1039         LIST_INSERT_HEAD(head, item, wk_list);
1040 }
1041
1042 static void
1043 worklist_remove(item, locked, func, line)
1044         struct worklist *item;
1045         int locked;
1046         const char *func;
1047         int line;
1048 {
1049
1050         if (locked)
1051                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1052         if ((item->wk_state & ONWORKLIST) == 0)
1053                 panic("worklist_remove: %p %s(0x%X) not on list, "
1054                     "removed in function %s at line %d",
1055                     item, TYPENAME(item->wk_type), item->wk_state,
1056                     item->wk_func, item->wk_line);
1057         item->wk_state &= ~ONWORKLIST;
1058         item->wk_func = func;
1059         item->wk_line = line;
1060         LIST_REMOVE(item, wk_list);
1061 }
1062 #endif /* INVARIANTS */
1063
1064 /*
1065  * Merge two jsegdeps keeping only the oldest one as newer references
1066  * can't be discarded until after older references.
1067  */
1068 static inline struct jsegdep *
1069 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1070 {
1071         struct jsegdep *swp;
1072
1073         if (two == NULL)
1074                 return (one);
1075
1076         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1077                 swp = one;
1078                 one = two;
1079                 two = swp;
1080         }
1081         WORKLIST_REMOVE(&two->jd_list);
1082         free_jsegdep(two);
1083
1084         return (one);
1085 }
1086
1087 /*
1088  * If two freedeps are compatible free one to reduce list size.
1089  */
1090 static inline struct freedep *
1091 freedep_merge(struct freedep *one, struct freedep *two)
1092 {
1093         if (two == NULL)
1094                 return (one);
1095
1096         if (one->fd_freework == two->fd_freework) {
1097                 WORKLIST_REMOVE(&two->fd_list);
1098                 free_freedep(two);
1099         }
1100         return (one);
1101 }
1102
1103 /*
1104  * Move journal work from one list to another.  Duplicate freedeps and
1105  * jsegdeps are coalesced to keep the lists as small as possible.
1106  */
1107 static void
1108 jwork_move(dst, src)
1109         struct workhead *dst;
1110         struct workhead *src;
1111 {
1112         struct freedep *freedep;
1113         struct jsegdep *jsegdep;
1114         struct worklist *wkn;
1115         struct worklist *wk;
1116
1117         KASSERT(dst != src,
1118             ("jwork_move: dst == src"));
1119         freedep = NULL;
1120         jsegdep = NULL;
1121         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1122                 if (wk->wk_type == D_JSEGDEP)
1123                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1124                 else if (wk->wk_type == D_FREEDEP)
1125                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1126         }
1127
1128         while ((wk = LIST_FIRST(src)) != NULL) {
1129                 WORKLIST_REMOVE(wk);
1130                 WORKLIST_INSERT(dst, wk);
1131                 if (wk->wk_type == D_JSEGDEP) {
1132                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1133                         continue;
1134                 }
1135                 if (wk->wk_type == D_FREEDEP)
1136                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1137         }
1138 }
1139
1140 static void
1141 jwork_insert(dst, jsegdep)
1142         struct workhead *dst;
1143         struct jsegdep *jsegdep;
1144 {
1145         struct jsegdep *jsegdepn;
1146         struct worklist *wk;
1147
1148         LIST_FOREACH(wk, dst, wk_list)
1149                 if (wk->wk_type == D_JSEGDEP)
1150                         break;
1151         if (wk == NULL) {
1152                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1153                 return;
1154         }
1155         jsegdepn = WK_JSEGDEP(wk);
1156         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1157                 WORKLIST_REMOVE(wk);
1158                 free_jsegdep(jsegdepn);
1159                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1160         } else
1161                 free_jsegdep(jsegdep);
1162 }
1163
1164 /*
1165  * Routines for tracking and managing workitems.
1166  */
1167 static  void workitem_free(struct worklist *, int);
1168 static  void workitem_alloc(struct worklist *, int, struct mount *);
1169 static  void workitem_reassign(struct worklist *, int);
1170
1171 #define WORKITEM_FREE(item, type) \
1172         workitem_free((struct worklist *)(item), (type))
1173 #define WORKITEM_REASSIGN(item, type) \
1174         workitem_reassign((struct worklist *)(item), (type))
1175
1176 static void
1177 workitem_free(item, type)
1178         struct worklist *item;
1179         int type;
1180 {
1181         struct ufsmount *ump;
1182
1183 #ifdef INVARIANTS
1184         if (item->wk_state & ONWORKLIST)
1185                 panic("workitem_free: %s(0x%X) still on list, "
1186                     "added in function %s at line %d",
1187                     TYPENAME(item->wk_type), item->wk_state,
1188                     item->wk_func, item->wk_line);
1189         if (item->wk_type != type && type != D_NEWBLK)
1190                 panic("workitem_free: type mismatch %s != %s",
1191                     TYPENAME(item->wk_type), TYPENAME(type));
1192 #endif
1193         if (item->wk_state & IOWAITING)
1194                 wakeup(item);
1195         ump = VFSTOUFS(item->wk_mp);
1196         LOCK_OWNED(ump);
1197         KASSERT(ump->softdep_deps > 0,
1198             ("workitem_free: %s: softdep_deps going negative",
1199             ump->um_fs->fs_fsmnt));
1200         if (--ump->softdep_deps == 0 && ump->softdep_req)
1201                 wakeup(&ump->softdep_deps);
1202         KASSERT(dep_current[item->wk_type] > 0,
1203             ("workitem_free: %s: dep_current[%s] going negative",
1204             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1205         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1206             ("workitem_free: %s: softdep_curdeps[%s] going negative",
1207             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1208         atomic_subtract_long(&dep_current[item->wk_type], 1);
1209         ump->softdep_curdeps[item->wk_type] -= 1;
1210         free(item, DtoM(type));
1211 }
1212
1213 static void
1214 workitem_alloc(item, type, mp)
1215         struct worklist *item;
1216         int type;
1217         struct mount *mp;
1218 {
1219         struct ufsmount *ump;
1220
1221         item->wk_type = type;
1222         item->wk_mp = mp;
1223         item->wk_state = 0;
1224
1225         ump = VFSTOUFS(mp);
1226         ACQUIRE_GBLLOCK(&lk);
1227         dep_current[type]++;
1228         if (dep_current[type] > dep_highuse[type])
1229                 dep_highuse[type] = dep_current[type];
1230         dep_total[type]++;
1231         FREE_GBLLOCK(&lk);
1232         ACQUIRE_LOCK(ump);
1233         ump->softdep_curdeps[type] += 1;
1234         ump->softdep_deps++;
1235         ump->softdep_accdeps++;
1236         FREE_LOCK(ump);
1237 }
1238
1239 static void
1240 workitem_reassign(item, newtype)
1241         struct worklist *item;
1242         int newtype;
1243 {
1244         struct ufsmount *ump;
1245
1246         ump = VFSTOUFS(item->wk_mp);
1247         LOCK_OWNED(ump);
1248         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1249             ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1250             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1251         ump->softdep_curdeps[item->wk_type] -= 1;
1252         ump->softdep_curdeps[newtype] += 1;
1253         KASSERT(dep_current[item->wk_type] > 0,
1254             ("workitem_reassign: %s: dep_current[%s] going negative",
1255             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1256         ACQUIRE_GBLLOCK(&lk);
1257         dep_current[newtype]++;
1258         dep_current[item->wk_type]--;
1259         if (dep_current[newtype] > dep_highuse[newtype])
1260                 dep_highuse[newtype] = dep_current[newtype];
1261         dep_total[newtype]++;
1262         FREE_GBLLOCK(&lk);
1263         item->wk_type = newtype;
1264 }
1265
1266 /*
1267  * Workitem queue management
1268  */
1269 static int max_softdeps;        /* maximum number of structs before slowdown */
1270 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1271 static int proc_waiting;        /* tracks whether we have a timeout posted */
1272 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1273 static struct callout softdep_callout;
1274 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1275 static int req_clear_remove;    /* syncer process flush some freeblks */
1276 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1277
1278 /*
1279  * runtime statistics
1280  */
1281 static int stat_flush_threads;  /* number of softdep flushing threads */
1282 static int stat_worklist_push;  /* number of worklist cleanups */
1283 static int stat_blk_limit_push; /* number of times block limit neared */
1284 static int stat_ino_limit_push; /* number of times inode limit neared */
1285 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1286 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1287 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1288 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1289 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1290 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1291 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1292 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1293 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1294 static int stat_journal_min;    /* Times hit journal min threshold */
1295 static int stat_journal_low;    /* Times hit journal low threshold */
1296 static int stat_journal_wait;   /* Times blocked in jwait(). */
1297 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1298 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1299 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1300 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1301 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1302 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1303 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1304 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1305 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1306 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1307
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1309     &max_softdeps, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1311     &tickdelay, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1313     &stat_flush_threads, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1315     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1317     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1319     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1321     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1323     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1325     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1327     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1329     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1331     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1333     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1335     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1337     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1339     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1341     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1343     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1345     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1347     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1349     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1351     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1353     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1355     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1357     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1359     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1361     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1362
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1364     &softdep_flushcache, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1366     &stat_emptyjblocks, 0, "");
1367
1368 SYSCTL_DECL(_vfs_ffs);
1369
1370 /* Whether to recompute the summary at mount time */
1371 static int compute_summary_at_mount = 0;
1372 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1373            &compute_summary_at_mount, 0, "Recompute summary at mount");
1374 static int print_threads = 0;
1375 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1376     &print_threads, 0, "Notify flusher thread start/stop");
1377
1378 /* List of all filesystems mounted with soft updates */
1379 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1380
1381 /*
1382  * This function cleans the worklist for a filesystem.
1383  * Each filesystem running with soft dependencies gets its own
1384  * thread to run in this function. The thread is started up in
1385  * softdep_mount and shutdown in softdep_unmount. They show up
1386  * as part of the kernel "bufdaemon" process whose process
1387  * entry is available in bufdaemonproc.
1388  */
1389 static int searchfailed;
1390 extern struct proc *bufdaemonproc;
1391 static void
1392 softdep_flush(addr)
1393         void *addr;
1394 {
1395         struct mount *mp;
1396         struct thread *td;
1397         struct ufsmount *ump;
1398
1399         td = curthread;
1400         td->td_pflags |= TDP_NORUNNINGBUF;
1401         mp = (struct mount *)addr;
1402         ump = VFSTOUFS(mp);
1403         atomic_add_int(&stat_flush_threads, 1);
1404         ACQUIRE_LOCK(ump);
1405         ump->softdep_flags &= ~FLUSH_STARTING;
1406         wakeup(&ump->softdep_flushtd);
1407         FREE_LOCK(ump);
1408         if (print_threads) {
1409                 if (stat_flush_threads == 1)
1410                         printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1411                             bufdaemonproc->p_pid);
1412                 printf("Start thread %s\n", td->td_name);
1413         }
1414         for (;;) {      
1415                 while (softdep_process_worklist(mp, 0) > 0 ||
1416                     (MOUNTEDSUJ(mp) &&
1417                     VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1418                         kthread_suspend_check();
1419                 ACQUIRE_LOCK(ump);
1420                 if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1421                         msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1422                             "sdflush", hz / 2);
1423                 ump->softdep_flags &= ~FLUSH_CLEANUP;
1424                 /*
1425                  * Check to see if we are done and need to exit.
1426                  */
1427                 if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1428                         FREE_LOCK(ump);
1429                         continue;
1430                 }
1431                 ump->softdep_flags &= ~FLUSH_EXIT;
1432                 FREE_LOCK(ump);
1433                 wakeup(&ump->softdep_flags);
1434                 if (print_threads)
1435                         printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1436                 atomic_subtract_int(&stat_flush_threads, 1);
1437                 kthread_exit();
1438                 panic("kthread_exit failed\n");
1439         }
1440 }
1441
1442 static void
1443 worklist_speedup(mp)
1444         struct mount *mp;
1445 {
1446         struct ufsmount *ump;
1447
1448         ump = VFSTOUFS(mp);
1449         LOCK_OWNED(ump);
1450         if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1451                 ump->softdep_flags |= FLUSH_CLEANUP;
1452         wakeup(&ump->softdep_flushtd);
1453 }
1454
1455 static int
1456 softdep_speedup(ump)
1457         struct ufsmount *ump;
1458 {
1459         struct ufsmount *altump;
1460         struct mount_softdeps *sdp;
1461
1462         LOCK_OWNED(ump);
1463         worklist_speedup(ump->um_mountp);
1464         bd_speedup();
1465         /*
1466          * If we have global shortages, then we need other
1467          * filesystems to help with the cleanup. Here we wakeup a
1468          * flusher thread for a filesystem that is over its fair
1469          * share of resources.
1470          */
1471         if (req_clear_inodedeps || req_clear_remove) {
1472                 ACQUIRE_GBLLOCK(&lk);
1473                 TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1474                         if ((altump = sdp->sd_ump) == ump)
1475                                 continue;
1476                         if (((req_clear_inodedeps &&
1477                             altump->softdep_curdeps[D_INODEDEP] >
1478                             max_softdeps / stat_flush_threads) ||
1479                             (req_clear_remove &&
1480                             altump->softdep_curdeps[D_DIRREM] >
1481                             (max_softdeps / 2) / stat_flush_threads)) &&
1482                             TRY_ACQUIRE_LOCK(altump))
1483                                 break;
1484                 }
1485                 if (sdp == NULL) {
1486                         searchfailed++;
1487                         FREE_GBLLOCK(&lk);
1488                 } else {
1489                         /*
1490                          * Move to the end of the list so we pick a
1491                          * different one on out next try.
1492                          */
1493                         TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1494                         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1495                         FREE_GBLLOCK(&lk);
1496                         if ((altump->softdep_flags &
1497                             (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1498                                 altump->softdep_flags |= FLUSH_CLEANUP;
1499                         altump->um_softdep->sd_cleanups++;
1500                         wakeup(&altump->softdep_flushtd);
1501                         FREE_LOCK(altump);
1502                 }
1503         }
1504         return (speedup_syncer());
1505 }
1506
1507 /*
1508  * Add an item to the end of the work queue.
1509  * This routine requires that the lock be held.
1510  * This is the only routine that adds items to the list.
1511  * The following routine is the only one that removes items
1512  * and does so in order from first to last.
1513  */
1514
1515 #define WK_HEAD         0x0001  /* Add to HEAD. */
1516 #define WK_NODELAY      0x0002  /* Process immediately. */
1517
1518 static void
1519 add_to_worklist(wk, flags)
1520         struct worklist *wk;
1521         int flags;
1522 {
1523         struct ufsmount *ump;
1524
1525         ump = VFSTOUFS(wk->wk_mp);
1526         LOCK_OWNED(ump);
1527         if (wk->wk_state & ONWORKLIST)
1528                 panic("add_to_worklist: %s(0x%X) already on list",
1529                     TYPENAME(wk->wk_type), wk->wk_state);
1530         wk->wk_state |= ONWORKLIST;
1531         if (ump->softdep_on_worklist == 0) {
1532                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1533                 ump->softdep_worklist_tail = wk;
1534         } else if (flags & WK_HEAD) {
1535                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1536         } else {
1537                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1538                 ump->softdep_worklist_tail = wk;
1539         }
1540         ump->softdep_on_worklist += 1;
1541         if (flags & WK_NODELAY)
1542                 worklist_speedup(wk->wk_mp);
1543 }
1544
1545 /*
1546  * Remove the item to be processed. If we are removing the last
1547  * item on the list, we need to recalculate the tail pointer.
1548  */
1549 static void
1550 remove_from_worklist(wk)
1551         struct worklist *wk;
1552 {
1553         struct ufsmount *ump;
1554
1555         ump = VFSTOUFS(wk->wk_mp);
1556         if (ump->softdep_worklist_tail == wk)
1557                 ump->softdep_worklist_tail =
1558                     (struct worklist *)wk->wk_list.le_prev;
1559         WORKLIST_REMOVE(wk);
1560         ump->softdep_on_worklist -= 1;
1561 }
1562
1563 static void
1564 wake_worklist(wk)
1565         struct worklist *wk;
1566 {
1567         if (wk->wk_state & IOWAITING) {
1568                 wk->wk_state &= ~IOWAITING;
1569                 wakeup(wk);
1570         }
1571 }
1572
1573 static void
1574 wait_worklist(wk, wmesg)
1575         struct worklist *wk;
1576         char *wmesg;
1577 {
1578         struct ufsmount *ump;
1579
1580         ump = VFSTOUFS(wk->wk_mp);
1581         wk->wk_state |= IOWAITING;
1582         msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1583 }
1584
1585 /*
1586  * Process that runs once per second to handle items in the background queue.
1587  *
1588  * Note that we ensure that everything is done in the order in which they
1589  * appear in the queue. The code below depends on this property to ensure
1590  * that blocks of a file are freed before the inode itself is freed. This
1591  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1592  * until all the old ones have been purged from the dependency lists.
1593  */
1594 static int 
1595 softdep_process_worklist(mp, full)
1596         struct mount *mp;
1597         int full;
1598 {
1599         int cnt, matchcnt;
1600         struct ufsmount *ump;
1601         long starttime;
1602
1603         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1604         if (MOUNTEDSOFTDEP(mp) == 0)
1605                 return (0);
1606         matchcnt = 0;
1607         ump = VFSTOUFS(mp);
1608         ACQUIRE_LOCK(ump);
1609         starttime = time_second;
1610         softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1611         check_clear_deps(mp);
1612         while (ump->softdep_on_worklist > 0) {
1613                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1614                         break;
1615                 else
1616                         matchcnt += cnt;
1617                 check_clear_deps(mp);
1618                 /*
1619                  * We do not generally want to stop for buffer space, but if
1620                  * we are really being a buffer hog, we will stop and wait.
1621                  */
1622                 if (should_yield()) {
1623                         FREE_LOCK(ump);
1624                         kern_yield(PRI_USER);
1625                         bwillwrite();
1626                         ACQUIRE_LOCK(ump);
1627                 }
1628                 /*
1629                  * Never allow processing to run for more than one
1630                  * second. This gives the syncer thread the opportunity
1631                  * to pause if appropriate.
1632                  */
1633                 if (!full && starttime != time_second)
1634                         break;
1635         }
1636         if (full == 0)
1637                 journal_unsuspend(ump);
1638         FREE_LOCK(ump);
1639         return (matchcnt);
1640 }
1641
1642 /*
1643  * Process all removes associated with a vnode if we are running out of
1644  * journal space.  Any other process which attempts to flush these will
1645  * be unable as we have the vnodes locked.
1646  */
1647 static void
1648 process_removes(vp)
1649         struct vnode *vp;
1650 {
1651         struct inodedep *inodedep;
1652         struct dirrem *dirrem;
1653         struct ufsmount *ump;
1654         struct mount *mp;
1655         ino_t inum;
1656
1657         mp = vp->v_mount;
1658         ump = VFSTOUFS(mp);
1659         LOCK_OWNED(ump);
1660         inum = VTOI(vp)->i_number;
1661         for (;;) {
1662 top:
1663                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1664                         return;
1665                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1666                         /*
1667                          * If another thread is trying to lock this vnode
1668                          * it will fail but we must wait for it to do so
1669                          * before we can proceed.
1670                          */
1671                         if (dirrem->dm_state & INPROGRESS) {
1672                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1673                                 goto top;
1674                         }
1675                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1676                             (COMPLETE | ONWORKLIST))
1677                                 break;
1678                 }
1679                 if (dirrem == NULL)
1680                         return;
1681                 remove_from_worklist(&dirrem->dm_list);
1682                 FREE_LOCK(ump);
1683                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1684                         panic("process_removes: suspended filesystem");
1685                 handle_workitem_remove(dirrem, 0);
1686                 vn_finished_secondary_write(mp);
1687                 ACQUIRE_LOCK(ump);
1688         }
1689 }
1690
1691 /*
1692  * Process all truncations associated with a vnode if we are running out
1693  * of journal space.  This is called when the vnode lock is already held
1694  * and no other process can clear the truncation.  This function returns
1695  * a value greater than zero if it did any work.
1696  */
1697 static void
1698 process_truncates(vp)
1699         struct vnode *vp;
1700 {
1701         struct inodedep *inodedep;
1702         struct freeblks *freeblks;
1703         struct ufsmount *ump;
1704         struct mount *mp;
1705         ino_t inum;
1706         int cgwait;
1707
1708         mp = vp->v_mount;
1709         ump = VFSTOUFS(mp);
1710         LOCK_OWNED(ump);
1711         inum = VTOI(vp)->i_number;
1712         for (;;) {
1713                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1714                         return;
1715                 cgwait = 0;
1716                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1717                         /* Journal entries not yet written.  */
1718                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1719                                 jwait(&LIST_FIRST(
1720                                     &freeblks->fb_jblkdephd)->jb_list,
1721                                     MNT_WAIT);
1722                                 break;
1723                         }
1724                         /* Another thread is executing this item. */
1725                         if (freeblks->fb_state & INPROGRESS) {
1726                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1727                                 break;
1728                         }
1729                         /* Freeblks is waiting on a inode write. */
1730                         if ((freeblks->fb_state & COMPLETE) == 0) {
1731                                 FREE_LOCK(ump);
1732                                 ffs_update(vp, 1);
1733                                 ACQUIRE_LOCK(ump);
1734                                 break;
1735                         }
1736                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1737                             (ALLCOMPLETE | ONWORKLIST)) {
1738                                 remove_from_worklist(&freeblks->fb_list);
1739                                 freeblks->fb_state |= INPROGRESS;
1740                                 FREE_LOCK(ump);
1741                                 if (vn_start_secondary_write(NULL, &mp,
1742                                     V_NOWAIT))
1743                                         panic("process_truncates: "
1744                                             "suspended filesystem");
1745                                 handle_workitem_freeblocks(freeblks, 0);
1746                                 vn_finished_secondary_write(mp);
1747                                 ACQUIRE_LOCK(ump);
1748                                 break;
1749                         }
1750                         if (freeblks->fb_cgwait)
1751                                 cgwait++;
1752                 }
1753                 if (cgwait) {
1754                         FREE_LOCK(ump);
1755                         sync_cgs(mp, MNT_WAIT);
1756                         ffs_sync_snap(mp, MNT_WAIT);
1757                         ACQUIRE_LOCK(ump);
1758                         continue;
1759                 }
1760                 if (freeblks == NULL)
1761                         break;
1762         }
1763         return;
1764 }
1765
1766 /*
1767  * Process one item on the worklist.
1768  */
1769 static int
1770 process_worklist_item(mp, target, flags)
1771         struct mount *mp;
1772         int target;
1773         int flags;
1774 {
1775         struct worklist sentinel;
1776         struct worklist *wk;
1777         struct ufsmount *ump;
1778         int matchcnt;
1779         int error;
1780
1781         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1782         /*
1783          * If we are being called because of a process doing a
1784          * copy-on-write, then it is not safe to write as we may
1785          * recurse into the copy-on-write routine.
1786          */
1787         if (curthread->td_pflags & TDP_COWINPROGRESS)
1788                 return (-1);
1789         PHOLD(curproc); /* Don't let the stack go away. */
1790         ump = VFSTOUFS(mp);
1791         LOCK_OWNED(ump);
1792         matchcnt = 0;
1793         sentinel.wk_mp = NULL;
1794         sentinel.wk_type = D_SENTINEL;
1795         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1796         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1797             wk = LIST_NEXT(&sentinel, wk_list)) {
1798                 if (wk->wk_type == D_SENTINEL) {
1799                         LIST_REMOVE(&sentinel, wk_list);
1800                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1801                         continue;
1802                 }
1803                 if (wk->wk_state & INPROGRESS)
1804                         panic("process_worklist_item: %p already in progress.",
1805                             wk);
1806                 wk->wk_state |= INPROGRESS;
1807                 remove_from_worklist(wk);
1808                 FREE_LOCK(ump);
1809                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1810                         panic("process_worklist_item: suspended filesystem");
1811                 switch (wk->wk_type) {
1812                 case D_DIRREM:
1813                         /* removal of a directory entry */
1814                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1815                         break;
1816
1817                 case D_FREEBLKS:
1818                         /* releasing blocks and/or fragments from a file */
1819                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1820                             flags);
1821                         break;
1822
1823                 case D_FREEFRAG:
1824                         /* releasing a fragment when replaced as a file grows */
1825                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1826                         error = 0;
1827                         break;
1828
1829                 case D_FREEFILE:
1830                         /* releasing an inode when its link count drops to 0 */
1831                         handle_workitem_freefile(WK_FREEFILE(wk));
1832                         error = 0;
1833                         break;
1834
1835                 default:
1836                         panic("%s_process_worklist: Unknown type %s",
1837                             "softdep", TYPENAME(wk->wk_type));
1838                         /* NOTREACHED */
1839                 }
1840                 vn_finished_secondary_write(mp);
1841                 ACQUIRE_LOCK(ump);
1842                 if (error == 0) {
1843                         if (++matchcnt == target)
1844                                 break;
1845                         continue;
1846                 }
1847                 /*
1848                  * We have to retry the worklist item later.  Wake up any
1849                  * waiters who may be able to complete it immediately and
1850                  * add the item back to the head so we don't try to execute
1851                  * it again.
1852                  */
1853                 wk->wk_state &= ~INPROGRESS;
1854                 wake_worklist(wk);
1855                 add_to_worklist(wk, WK_HEAD);
1856         }
1857         /* Sentinal could've become the tail from remove_from_worklist. */
1858         if (ump->softdep_worklist_tail == &sentinel)
1859                 ump->softdep_worklist_tail =
1860                     (struct worklist *)sentinel.wk_list.le_prev;
1861         LIST_REMOVE(&sentinel, wk_list);
1862         PRELE(curproc);
1863         return (matchcnt);
1864 }
1865
1866 /*
1867  * Move dependencies from one buffer to another.
1868  */
1869 int
1870 softdep_move_dependencies(oldbp, newbp)
1871         struct buf *oldbp;
1872         struct buf *newbp;
1873 {
1874         struct worklist *wk, *wktail;
1875         struct ufsmount *ump;
1876         int dirty;
1877
1878         if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1879                 return (0);
1880         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1881             ("softdep_move_dependencies called on non-softdep filesystem"));
1882         dirty = 0;
1883         wktail = NULL;
1884         ump = VFSTOUFS(wk->wk_mp);
1885         ACQUIRE_LOCK(ump);
1886         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1887                 LIST_REMOVE(wk, wk_list);
1888                 if (wk->wk_type == D_BMSAFEMAP &&
1889                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1890                         dirty = 1;
1891                 if (wktail == NULL)
1892                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1893                 else
1894                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1895                 wktail = wk;
1896         }
1897         FREE_LOCK(ump);
1898
1899         return (dirty);
1900 }
1901
1902 /*
1903  * Purge the work list of all items associated with a particular mount point.
1904  */
1905 int
1906 softdep_flushworklist(oldmnt, countp, td)
1907         struct mount *oldmnt;
1908         int *countp;
1909         struct thread *td;
1910 {
1911         struct vnode *devvp;
1912         struct ufsmount *ump;
1913         int count, error;
1914
1915         /*
1916          * Alternately flush the block device associated with the mount
1917          * point and process any dependencies that the flushing
1918          * creates. We continue until no more worklist dependencies
1919          * are found.
1920          */
1921         *countp = 0;
1922         error = 0;
1923         ump = VFSTOUFS(oldmnt);
1924         devvp = ump->um_devvp;
1925         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1926                 *countp += count;
1927                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1928                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1929                 VOP_UNLOCK(devvp, 0);
1930                 if (error != 0)
1931                         break;
1932         }
1933         return (error);
1934 }
1935
1936 #define SU_WAITIDLE_RETRIES     20
1937 static int
1938 softdep_waitidle(struct mount *mp, int flags __unused)
1939 {
1940         struct ufsmount *ump;
1941         struct vnode *devvp;
1942         struct thread *td;
1943         int error, i;
1944
1945         ump = VFSTOUFS(mp);
1946         devvp = ump->um_devvp;
1947         td = curthread;
1948         error = 0;
1949         ACQUIRE_LOCK(ump);
1950         for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1951                 ump->softdep_req = 1;
1952                 KASSERT((flags & FORCECLOSE) == 0 ||
1953                     ump->softdep_on_worklist == 0,
1954                     ("softdep_waitidle: work added after flush"));
1955                 msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1956                     "softdeps", 10 * hz);
1957                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1958                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1959                 VOP_UNLOCK(devvp, 0);
1960                 ACQUIRE_LOCK(ump);
1961                 if (error != 0)
1962                         break;
1963         }
1964         ump->softdep_req = 0;
1965         if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1966                 error = EBUSY;
1967                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1968                     mp);
1969         }
1970         FREE_LOCK(ump);
1971         return (error);
1972 }
1973
1974 /*
1975  * Flush all vnodes and worklist items associated with a specified mount point.
1976  */
1977 int
1978 softdep_flushfiles(oldmnt, flags, td)
1979         struct mount *oldmnt;
1980         int flags;
1981         struct thread *td;
1982 {
1983 #ifdef QUOTA
1984         struct ufsmount *ump;
1985         int i;
1986 #endif
1987         int error, early, depcount, loopcnt, retry_flush_count, retry;
1988         int morework;
1989
1990         KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1991             ("softdep_flushfiles called on non-softdep filesystem"));
1992         loopcnt = 10;
1993         retry_flush_count = 3;
1994 retry_flush:
1995         error = 0;
1996
1997         /*
1998          * Alternately flush the vnodes associated with the mount
1999          * point and process any dependencies that the flushing
2000          * creates. In theory, this loop can happen at most twice,
2001          * but we give it a few extra just to be sure.
2002          */
2003         for (; loopcnt > 0; loopcnt--) {
2004                 /*
2005                  * Do another flush in case any vnodes were brought in
2006                  * as part of the cleanup operations.
2007                  */
2008                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2009                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2010                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2011                         break;
2012                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2013                     depcount == 0)
2014                         break;
2015         }
2016         /*
2017          * If we are unmounting then it is an error to fail. If we
2018          * are simply trying to downgrade to read-only, then filesystem
2019          * activity can keep us busy forever, so we just fail with EBUSY.
2020          */
2021         if (loopcnt == 0) {
2022                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2023                         panic("softdep_flushfiles: looping");
2024                 error = EBUSY;
2025         }
2026         if (!error)
2027                 error = softdep_waitidle(oldmnt, flags);
2028         if (!error) {
2029                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2030                         retry = 0;
2031                         MNT_ILOCK(oldmnt);
2032                         morework = oldmnt->mnt_nvnodelistsize > 0;
2033 #ifdef QUOTA
2034                         ump = VFSTOUFS(oldmnt);
2035                         UFS_LOCK(ump);
2036                         for (i = 0; i < MAXQUOTAS; i++) {
2037                                 if (ump->um_quotas[i] != NULLVP)
2038                                         morework = 1;
2039                         }
2040                         UFS_UNLOCK(ump);
2041 #endif
2042                         if (morework) {
2043                                 if (--retry_flush_count > 0) {
2044                                         retry = 1;
2045                                         loopcnt = 3;
2046                                 } else
2047                                         error = EBUSY;
2048                         }
2049                         MNT_IUNLOCK(oldmnt);
2050                         if (retry)
2051                                 goto retry_flush;
2052                 }
2053         }
2054         return (error);
2055 }
2056
2057 /*
2058  * Structure hashing.
2059  * 
2060  * There are four types of structures that can be looked up:
2061  *      1) pagedep structures identified by mount point, inode number,
2062  *         and logical block.
2063  *      2) inodedep structures identified by mount point and inode number.
2064  *      3) newblk structures identified by mount point and
2065  *         physical block number.
2066  *      4) bmsafemap structures identified by mount point and
2067  *         cylinder group number.
2068  *
2069  * The "pagedep" and "inodedep" dependency structures are hashed
2070  * separately from the file blocks and inodes to which they correspond.
2071  * This separation helps when the in-memory copy of an inode or
2072  * file block must be replaced. It also obviates the need to access
2073  * an inode or file page when simply updating (or de-allocating)
2074  * dependency structures. Lookup of newblk structures is needed to
2075  * find newly allocated blocks when trying to associate them with
2076  * their allocdirect or allocindir structure.
2077  *
2078  * The lookup routines optionally create and hash a new instance when
2079  * an existing entry is not found. The bmsafemap lookup routine always
2080  * allocates a new structure if an existing one is not found.
2081  */
2082 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2083
2084 /*
2085  * Structures and routines associated with pagedep caching.
2086  */
2087 #define PAGEDEP_HASH(ump, inum, lbn) \
2088         (&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2089
2090 static int
2091 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2092         struct pagedep_hashhead *pagedephd;
2093         ino_t ino;
2094         ufs_lbn_t lbn;
2095         struct pagedep **pagedeppp;
2096 {
2097         struct pagedep *pagedep;
2098
2099         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2100                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2101                         *pagedeppp = pagedep;
2102                         return (1);
2103                 }
2104         }
2105         *pagedeppp = NULL;
2106         return (0);
2107 }
2108 /*
2109  * Look up a pagedep. Return 1 if found, 0 otherwise.
2110  * If not found, allocate if DEPALLOC flag is passed.
2111  * Found or allocated entry is returned in pagedeppp.
2112  */
2113 static int
2114 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2115         struct mount *mp;
2116         struct buf *bp;
2117         ino_t ino;
2118         ufs_lbn_t lbn;
2119         int flags;
2120         struct pagedep **pagedeppp;
2121 {
2122         struct pagedep *pagedep;
2123         struct pagedep_hashhead *pagedephd;
2124         struct worklist *wk;
2125         struct ufsmount *ump;
2126         int ret;
2127         int i;
2128
2129         ump = VFSTOUFS(mp);
2130         LOCK_OWNED(ump);
2131         if (bp) {
2132                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2133                         if (wk->wk_type == D_PAGEDEP) {
2134                                 *pagedeppp = WK_PAGEDEP(wk);
2135                                 return (1);
2136                         }
2137                 }
2138         }
2139         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2140         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2141         if (ret) {
2142                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2143                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2144                 return (1);
2145         }
2146         if ((flags & DEPALLOC) == 0)
2147                 return (0);
2148         FREE_LOCK(ump);
2149         pagedep = malloc(sizeof(struct pagedep),
2150             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2151         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2152         ACQUIRE_LOCK(ump);
2153         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2154         if (*pagedeppp) {
2155                 /*
2156                  * This should never happen since we only create pagedeps
2157                  * with the vnode lock held.  Could be an assert.
2158                  */
2159                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2160                 return (ret);
2161         }
2162         pagedep->pd_ino = ino;
2163         pagedep->pd_lbn = lbn;
2164         LIST_INIT(&pagedep->pd_dirremhd);
2165         LIST_INIT(&pagedep->pd_pendinghd);
2166         for (i = 0; i < DAHASHSZ; i++)
2167                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2168         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2169         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2170         *pagedeppp = pagedep;
2171         return (0);
2172 }
2173
2174 /*
2175  * Structures and routines associated with inodedep caching.
2176  */
2177 #define INODEDEP_HASH(ump, inum) \
2178       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2179
2180 static int
2181 inodedep_find(inodedephd, inum, inodedeppp)
2182         struct inodedep_hashhead *inodedephd;
2183         ino_t inum;
2184         struct inodedep **inodedeppp;
2185 {
2186         struct inodedep *inodedep;
2187
2188         LIST_FOREACH(inodedep, inodedephd, id_hash)
2189                 if (inum == inodedep->id_ino)
2190                         break;
2191         if (inodedep) {
2192                 *inodedeppp = inodedep;
2193                 return (1);
2194         }
2195         *inodedeppp = NULL;
2196
2197         return (0);
2198 }
2199 /*
2200  * Look up an inodedep. Return 1 if found, 0 if not found.
2201  * If not found, allocate if DEPALLOC flag is passed.
2202  * Found or allocated entry is returned in inodedeppp.
2203  */
2204 static int
2205 inodedep_lookup(mp, inum, flags, inodedeppp)
2206         struct mount *mp;
2207         ino_t inum;
2208         int flags;
2209         struct inodedep **inodedeppp;
2210 {
2211         struct inodedep *inodedep;
2212         struct inodedep_hashhead *inodedephd;
2213         struct ufsmount *ump;
2214         struct fs *fs;
2215
2216         ump = VFSTOUFS(mp);
2217         LOCK_OWNED(ump);
2218         fs = ump->um_fs;
2219         inodedephd = INODEDEP_HASH(ump, inum);
2220
2221         if (inodedep_find(inodedephd, inum, inodedeppp))
2222                 return (1);
2223         if ((flags & DEPALLOC) == 0)
2224                 return (0);
2225         /*
2226          * If the system is over its limit and our filesystem is
2227          * responsible for more than our share of that usage and
2228          * we are not in a rush, request some inodedep cleanup.
2229          */
2230         if (softdep_excess_items(ump, D_INODEDEP))
2231                 schedule_cleanup(mp);
2232         else
2233                 FREE_LOCK(ump);
2234         inodedep = malloc(sizeof(struct inodedep),
2235                 M_INODEDEP, M_SOFTDEP_FLAGS);
2236         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2237         ACQUIRE_LOCK(ump);
2238         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2239                 WORKITEM_FREE(inodedep, D_INODEDEP);
2240                 return (1);
2241         }
2242         inodedep->id_fs = fs;
2243         inodedep->id_ino = inum;
2244         inodedep->id_state = ALLCOMPLETE;
2245         inodedep->id_nlinkdelta = 0;
2246         inodedep->id_savedino1 = NULL;
2247         inodedep->id_savedsize = -1;
2248         inodedep->id_savedextsize = -1;
2249         inodedep->id_savednlink = -1;
2250         inodedep->id_bmsafemap = NULL;
2251         inodedep->id_mkdiradd = NULL;
2252         LIST_INIT(&inodedep->id_dirremhd);
2253         LIST_INIT(&inodedep->id_pendinghd);
2254         LIST_INIT(&inodedep->id_inowait);
2255         LIST_INIT(&inodedep->id_bufwait);
2256         TAILQ_INIT(&inodedep->id_inoreflst);
2257         TAILQ_INIT(&inodedep->id_inoupdt);
2258         TAILQ_INIT(&inodedep->id_newinoupdt);
2259         TAILQ_INIT(&inodedep->id_extupdt);
2260         TAILQ_INIT(&inodedep->id_newextupdt);
2261         TAILQ_INIT(&inodedep->id_freeblklst);
2262         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2263         *inodedeppp = inodedep;
2264         return (0);
2265 }
2266
2267 /*
2268  * Structures and routines associated with newblk caching.
2269  */
2270 #define NEWBLK_HASH(ump, inum) \
2271         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2272
2273 static int
2274 newblk_find(newblkhd, newblkno, flags, newblkpp)
2275         struct newblk_hashhead *newblkhd;
2276         ufs2_daddr_t newblkno;
2277         int flags;
2278         struct newblk **newblkpp;
2279 {
2280         struct newblk *newblk;
2281
2282         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2283                 if (newblkno != newblk->nb_newblkno)
2284                         continue;
2285                 /*
2286                  * If we're creating a new dependency don't match those that
2287                  * have already been converted to allocdirects.  This is for
2288                  * a frag extend.
2289                  */
2290                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2291                         continue;
2292                 break;
2293         }
2294         if (newblk) {
2295                 *newblkpp = newblk;
2296                 return (1);
2297         }
2298         *newblkpp = NULL;
2299         return (0);
2300 }
2301
2302 /*
2303  * Look up a newblk. Return 1 if found, 0 if not found.
2304  * If not found, allocate if DEPALLOC flag is passed.
2305  * Found or allocated entry is returned in newblkpp.
2306  */
2307 static int
2308 newblk_lookup(mp, newblkno, flags, newblkpp)
2309         struct mount *mp;
2310         ufs2_daddr_t newblkno;
2311         int flags;
2312         struct newblk **newblkpp;
2313 {
2314         struct newblk *newblk;
2315         struct newblk_hashhead *newblkhd;
2316         struct ufsmount *ump;
2317
2318         ump = VFSTOUFS(mp);
2319         LOCK_OWNED(ump);
2320         newblkhd = NEWBLK_HASH(ump, newblkno);
2321         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2322                 return (1);
2323         if ((flags & DEPALLOC) == 0)
2324                 return (0);
2325         if (softdep_excess_items(ump, D_NEWBLK) ||
2326             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2327             softdep_excess_items(ump, D_ALLOCINDIR))
2328                 schedule_cleanup(mp);
2329         else
2330                 FREE_LOCK(ump);
2331         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2332             M_SOFTDEP_FLAGS | M_ZERO);
2333         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2334         ACQUIRE_LOCK(ump);
2335         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2336                 WORKITEM_FREE(newblk, D_NEWBLK);
2337                 return (1);
2338         }
2339         newblk->nb_freefrag = NULL;
2340         LIST_INIT(&newblk->nb_indirdeps);
2341         LIST_INIT(&newblk->nb_newdirblk);
2342         LIST_INIT(&newblk->nb_jwork);
2343         newblk->nb_state = ATTACHED;
2344         newblk->nb_newblkno = newblkno;
2345         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2346         *newblkpp = newblk;
2347         return (0);
2348 }
2349
2350 /*
2351  * Structures and routines associated with freed indirect block caching.
2352  */
2353 #define INDIR_HASH(ump, blkno) \
2354         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2355
2356 /*
2357  * Lookup an indirect block in the indir hash table.  The freework is
2358  * removed and potentially freed.  The caller must do a blocking journal
2359  * write before writing to the blkno.
2360  */
2361 static int
2362 indirblk_lookup(mp, blkno)
2363         struct mount *mp;
2364         ufs2_daddr_t blkno;
2365 {
2366         struct freework *freework;
2367         struct indir_hashhead *wkhd;
2368         struct ufsmount *ump;
2369
2370         ump = VFSTOUFS(mp);
2371         wkhd = INDIR_HASH(ump, blkno);
2372         TAILQ_FOREACH(freework, wkhd, fw_next) {
2373                 if (freework->fw_blkno != blkno)
2374                         continue;
2375                 indirblk_remove(freework);
2376                 return (1);
2377         }
2378         return (0);
2379 }
2380
2381 /*
2382  * Insert an indirect block represented by freework into the indirblk
2383  * hash table so that it may prevent the block from being re-used prior
2384  * to the journal being written.
2385  */
2386 static void
2387 indirblk_insert(freework)
2388         struct freework *freework;
2389 {
2390         struct jblocks *jblocks;
2391         struct jseg *jseg;
2392         struct ufsmount *ump;
2393
2394         ump = VFSTOUFS(freework->fw_list.wk_mp);
2395         jblocks = ump->softdep_jblocks;
2396         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2397         if (jseg == NULL)
2398                 return;
2399         
2400         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2401         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2402             fw_next);
2403         freework->fw_state &= ~DEPCOMPLETE;
2404 }
2405
2406 static void
2407 indirblk_remove(freework)
2408         struct freework *freework;
2409 {
2410         struct ufsmount *ump;
2411
2412         ump = VFSTOUFS(freework->fw_list.wk_mp);
2413         LIST_REMOVE(freework, fw_segs);
2414         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2415         freework->fw_state |= DEPCOMPLETE;
2416         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2417                 WORKITEM_FREE(freework, D_FREEWORK);
2418 }
2419
2420 /*
2421  * Executed during filesystem system initialization before
2422  * mounting any filesystems.
2423  */
2424 void 
2425 softdep_initialize()
2426 {
2427
2428         TAILQ_INIT(&softdepmounts);
2429 #ifdef __LP64__
2430         max_softdeps = desiredvnodes * 4;
2431 #else
2432         max_softdeps = desiredvnodes * 2;
2433 #endif
2434
2435         /* initialise bioops hack */
2436         bioops.io_start = softdep_disk_io_initiation;
2437         bioops.io_complete = softdep_disk_write_complete;
2438         bioops.io_deallocate = softdep_deallocate_dependencies;
2439         bioops.io_countdeps = softdep_count_dependencies;
2440         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2441
2442         /* Initialize the callout with an mtx. */
2443         callout_init_mtx(&softdep_callout, &lk, 0);
2444 }
2445
2446 /*
2447  * Executed after all filesystems have been unmounted during
2448  * filesystem module unload.
2449  */
2450 void
2451 softdep_uninitialize()
2452 {
2453
2454         /* clear bioops hack */
2455         bioops.io_start = NULL;
2456         bioops.io_complete = NULL;
2457         bioops.io_deallocate = NULL;
2458         bioops.io_countdeps = NULL;
2459         softdep_ast_cleanup = NULL;
2460
2461         callout_drain(&softdep_callout);
2462 }
2463
2464 /*
2465  * Called at mount time to notify the dependency code that a
2466  * filesystem wishes to use it.
2467  */
2468 int
2469 softdep_mount(devvp, mp, fs, cred)
2470         struct vnode *devvp;
2471         struct mount *mp;
2472         struct fs *fs;
2473         struct ucred *cred;
2474 {
2475         struct csum_total cstotal;
2476         struct mount_softdeps *sdp;
2477         struct ufsmount *ump;
2478         struct cg *cgp;
2479         struct buf *bp;
2480         u_int cyl, i;
2481         int error;
2482
2483         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2484             M_WAITOK | M_ZERO);
2485         MNT_ILOCK(mp);
2486         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2487         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2488                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2489                         MNTK_SOFTDEP | MNTK_NOASYNC;
2490         }
2491         ump = VFSTOUFS(mp);
2492         ump->um_softdep = sdp;
2493         MNT_IUNLOCK(mp);
2494         rw_init(LOCK_PTR(ump), "per-fs softdep");
2495         sdp->sd_ump = ump;
2496         LIST_INIT(&ump->softdep_workitem_pending);
2497         LIST_INIT(&ump->softdep_journal_pending);
2498         TAILQ_INIT(&ump->softdep_unlinked);
2499         LIST_INIT(&ump->softdep_dirtycg);
2500         ump->softdep_worklist_tail = NULL;
2501         ump->softdep_on_worklist = 0;
2502         ump->softdep_deps = 0;
2503         LIST_INIT(&ump->softdep_mkdirlisthd);
2504         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2505             &ump->pagedep_hash_size);
2506         ump->pagedep_nextclean = 0;
2507         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2508             &ump->inodedep_hash_size);
2509         ump->inodedep_nextclean = 0;
2510         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2511             &ump->newblk_hash_size);
2512         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2513             &ump->bmsafemap_hash_size);
2514         i = 1 << (ffs(desiredvnodes / 10) - 1);
2515         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2516             M_FREEWORK, M_WAITOK);
2517         ump->indir_hash_size = i - 1;
2518         for (i = 0; i <= ump->indir_hash_size; i++)
2519                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2520         ACQUIRE_GBLLOCK(&lk);
2521         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2522         FREE_GBLLOCK(&lk);
2523         if ((fs->fs_flags & FS_SUJ) &&
2524             (error = journal_mount(mp, fs, cred)) != 0) {
2525                 printf("Failed to start journal: %d\n", error);
2526                 softdep_unmount(mp);
2527                 return (error);
2528         }
2529         /*
2530          * Start our flushing thread in the bufdaemon process.
2531          */
2532         ACQUIRE_LOCK(ump);
2533         ump->softdep_flags |= FLUSH_STARTING;
2534         FREE_LOCK(ump);
2535         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2536             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2537             mp->mnt_stat.f_mntonname);
2538         ACQUIRE_LOCK(ump);
2539         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2540                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2541                     hz / 2);
2542         }
2543         FREE_LOCK(ump);
2544         /*
2545          * When doing soft updates, the counters in the
2546          * superblock may have gotten out of sync. Recomputation
2547          * can take a long time and can be deferred for background
2548          * fsck.  However, the old behavior of scanning the cylinder
2549          * groups and recalculating them at mount time is available
2550          * by setting vfs.ffs.compute_summary_at_mount to one.
2551          */
2552         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2553                 return (0);
2554         bzero(&cstotal, sizeof cstotal);
2555         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2556                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2557                     fs->fs_cgsize, cred, &bp)) != 0) {
2558                         brelse(bp);
2559                         softdep_unmount(mp);
2560                         return (error);
2561                 }
2562                 cgp = (struct cg *)bp->b_data;
2563                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2564                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2565                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2566                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2567                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2568                 brelse(bp);
2569         }
2570 #ifdef INVARIANTS
2571         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2572                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2573 #endif
2574         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2575         return (0);
2576 }
2577
2578 void
2579 softdep_unmount(mp)
2580         struct mount *mp;
2581 {
2582         struct ufsmount *ump;
2583 #ifdef INVARIANTS
2584         int i;
2585 #endif
2586
2587         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2588             ("softdep_unmount called on non-softdep filesystem"));
2589         ump = VFSTOUFS(mp);
2590         MNT_ILOCK(mp);
2591         mp->mnt_flag &= ~MNT_SOFTDEP;
2592         if (MOUNTEDSUJ(mp) == 0) {
2593                 MNT_IUNLOCK(mp);
2594         } else {
2595                 mp->mnt_flag &= ~MNT_SUJ;
2596                 MNT_IUNLOCK(mp);
2597                 journal_unmount(ump);
2598         }
2599         /*
2600          * Shut down our flushing thread. Check for NULL is if
2601          * softdep_mount errors out before the thread has been created.
2602          */
2603         if (ump->softdep_flushtd != NULL) {
2604                 ACQUIRE_LOCK(ump);
2605                 ump->softdep_flags |= FLUSH_EXIT;
2606                 wakeup(&ump->softdep_flushtd);
2607                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2608                     "sdwait", 0);
2609                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2610                     ("Thread shutdown failed"));
2611         }
2612         /*
2613          * Free up our resources.
2614          */
2615         ACQUIRE_GBLLOCK(&lk);
2616         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2617         FREE_GBLLOCK(&lk);
2618         rw_destroy(LOCK_PTR(ump));
2619         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2620         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2621         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2622         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2623             ump->bmsafemap_hash_size);
2624         free(ump->indir_hashtbl, M_FREEWORK);
2625 #ifdef INVARIANTS
2626         for (i = 0; i <= D_LAST; i++)
2627                 KASSERT(ump->softdep_curdeps[i] == 0,
2628                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2629                     TYPENAME(i), ump->softdep_curdeps[i]));
2630 #endif
2631         free(ump->um_softdep, M_MOUNTDATA);
2632 }
2633
2634 static struct jblocks *
2635 jblocks_create(void)
2636 {
2637         struct jblocks *jblocks;
2638
2639         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2640         TAILQ_INIT(&jblocks->jb_segs);
2641         jblocks->jb_avail = 10;
2642         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2643             M_JBLOCKS, M_WAITOK | M_ZERO);
2644
2645         return (jblocks);
2646 }
2647
2648 static ufs2_daddr_t
2649 jblocks_alloc(jblocks, bytes, actual)
2650         struct jblocks *jblocks;
2651         int bytes;
2652         int *actual;
2653 {
2654         ufs2_daddr_t daddr;
2655         struct jextent *jext;
2656         int freecnt;
2657         int blocks;
2658
2659         blocks = bytes / DEV_BSIZE;
2660         jext = &jblocks->jb_extent[jblocks->jb_head];
2661         freecnt = jext->je_blocks - jblocks->jb_off;
2662         if (freecnt == 0) {
2663                 jblocks->jb_off = 0;
2664                 if (++jblocks->jb_head > jblocks->jb_used)
2665                         jblocks->jb_head = 0;
2666                 jext = &jblocks->jb_extent[jblocks->jb_head];
2667                 freecnt = jext->je_blocks;
2668         }
2669         if (freecnt > blocks)
2670                 freecnt = blocks;
2671         *actual = freecnt * DEV_BSIZE;
2672         daddr = jext->je_daddr + jblocks->jb_off;
2673         jblocks->jb_off += freecnt;
2674         jblocks->jb_free -= freecnt;
2675
2676         return (daddr);
2677 }
2678
2679 static void
2680 jblocks_free(jblocks, mp, bytes)
2681         struct jblocks *jblocks;
2682         struct mount *mp;
2683         int bytes;
2684 {
2685
2686         LOCK_OWNED(VFSTOUFS(mp));
2687         jblocks->jb_free += bytes / DEV_BSIZE;
2688         if (jblocks->jb_suspended)
2689                 worklist_speedup(mp);
2690         wakeup(jblocks);
2691 }
2692
2693 static void
2694 jblocks_destroy(jblocks)
2695         struct jblocks *jblocks;
2696 {
2697
2698         if (jblocks->jb_extent)
2699                 free(jblocks->jb_extent, M_JBLOCKS);
2700         free(jblocks, M_JBLOCKS);
2701 }
2702
2703 static void
2704 jblocks_add(jblocks, daddr, blocks)
2705         struct jblocks *jblocks;
2706         ufs2_daddr_t daddr;
2707         int blocks;
2708 {
2709         struct jextent *jext;
2710
2711         jblocks->jb_blocks += blocks;
2712         jblocks->jb_free += blocks;
2713         jext = &jblocks->jb_extent[jblocks->jb_used];
2714         /* Adding the first block. */
2715         if (jext->je_daddr == 0) {
2716                 jext->je_daddr = daddr;
2717                 jext->je_blocks = blocks;
2718                 return;
2719         }
2720         /* Extending the last extent. */
2721         if (jext->je_daddr + jext->je_blocks == daddr) {
2722                 jext->je_blocks += blocks;
2723                 return;
2724         }
2725         /* Adding a new extent. */
2726         if (++jblocks->jb_used == jblocks->jb_avail) {
2727                 jblocks->jb_avail *= 2;
2728                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2729                     M_JBLOCKS, M_WAITOK | M_ZERO);
2730                 memcpy(jext, jblocks->jb_extent,
2731                     sizeof(struct jextent) * jblocks->jb_used);
2732                 free(jblocks->jb_extent, M_JBLOCKS);
2733                 jblocks->jb_extent = jext;
2734         }
2735         jext = &jblocks->jb_extent[jblocks->jb_used];
2736         jext->je_daddr = daddr;
2737         jext->je_blocks = blocks;
2738         return;
2739 }
2740
2741 int
2742 softdep_journal_lookup(mp, vpp)
2743         struct mount *mp;
2744         struct vnode **vpp;
2745 {
2746         struct componentname cnp;
2747         struct vnode *dvp;
2748         ino_t sujournal;
2749         int error;
2750
2751         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2752         if (error)
2753                 return (error);
2754         bzero(&cnp, sizeof(cnp));
2755         cnp.cn_nameiop = LOOKUP;
2756         cnp.cn_flags = ISLASTCN;
2757         cnp.cn_thread = curthread;
2758         cnp.cn_cred = curthread->td_ucred;
2759         cnp.cn_pnbuf = SUJ_FILE;
2760         cnp.cn_nameptr = SUJ_FILE;
2761         cnp.cn_namelen = strlen(SUJ_FILE);
2762         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2763         vput(dvp);
2764         if (error != 0)
2765                 return (error);
2766         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2767         return (error);
2768 }
2769
2770 /*
2771  * Open and verify the journal file.
2772  */
2773 static int
2774 journal_mount(mp, fs, cred)
2775         struct mount *mp;
2776         struct fs *fs;
2777         struct ucred *cred;
2778 {
2779         struct jblocks *jblocks;
2780         struct ufsmount *ump;
2781         struct vnode *vp;
2782         struct inode *ip;
2783         ufs2_daddr_t blkno;
2784         int bcount;
2785         int error;
2786         int i;
2787
2788         ump = VFSTOUFS(mp);
2789         ump->softdep_journal_tail = NULL;
2790         ump->softdep_on_journal = 0;
2791         ump->softdep_accdeps = 0;
2792         ump->softdep_req = 0;
2793         ump->softdep_jblocks = NULL;
2794         error = softdep_journal_lookup(mp, &vp);
2795         if (error != 0) {
2796                 printf("Failed to find journal.  Use tunefs to create one\n");
2797                 return (error);
2798         }
2799         ip = VTOI(vp);
2800         if (ip->i_size < SUJ_MIN) {
2801                 error = ENOSPC;
2802                 goto out;
2803         }
2804         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2805         jblocks = jblocks_create();
2806         for (i = 0; i < bcount; i++) {
2807                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2808                 if (error)
2809                         break;
2810                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2811         }
2812         if (error) {
2813                 jblocks_destroy(jblocks);
2814                 goto out;
2815         }
2816         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2817         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2818         ump->softdep_jblocks = jblocks;
2819 out:
2820         if (error == 0) {
2821                 MNT_ILOCK(mp);
2822                 mp->mnt_flag |= MNT_SUJ;
2823                 mp->mnt_flag &= ~MNT_SOFTDEP;
2824                 MNT_IUNLOCK(mp);
2825                 /*
2826                  * Only validate the journal contents if the
2827                  * filesystem is clean, otherwise we write the logs
2828                  * but they'll never be used.  If the filesystem was
2829                  * still dirty when we mounted it the journal is
2830                  * invalid and a new journal can only be valid if it
2831                  * starts from a clean mount.
2832                  */
2833                 if (fs->fs_clean) {
2834                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2835                         ip->i_flags |= IN_MODIFIED;
2836                         ffs_update(vp, 1);
2837                 }
2838         }
2839         vput(vp);
2840         return (error);
2841 }
2842
2843 static void
2844 journal_unmount(ump)
2845         struct ufsmount *ump;
2846 {
2847
2848         if (ump->softdep_jblocks)
2849                 jblocks_destroy(ump->softdep_jblocks);
2850         ump->softdep_jblocks = NULL;
2851 }
2852
2853 /*
2854  * Called when a journal record is ready to be written.  Space is allocated
2855  * and the journal entry is created when the journal is flushed to stable
2856  * store.
2857  */
2858 static void
2859 add_to_journal(wk)
2860         struct worklist *wk;
2861 {
2862         struct ufsmount *ump;
2863
2864         ump = VFSTOUFS(wk->wk_mp);
2865         LOCK_OWNED(ump);
2866         if (wk->wk_state & ONWORKLIST)
2867                 panic("add_to_journal: %s(0x%X) already on list",
2868                     TYPENAME(wk->wk_type), wk->wk_state);
2869         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2870         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2871                 ump->softdep_jblocks->jb_age = ticks;
2872                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2873         } else
2874                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2875         ump->softdep_journal_tail = wk;
2876         ump->softdep_on_journal += 1;
2877 }
2878
2879 /*
2880  * Remove an arbitrary item for the journal worklist maintain the tail
2881  * pointer.  This happens when a new operation obviates the need to
2882  * journal an old operation.
2883  */
2884 static void
2885 remove_from_journal(wk)
2886         struct worklist *wk;
2887 {
2888         struct ufsmount *ump;
2889
2890         ump = VFSTOUFS(wk->wk_mp);
2891         LOCK_OWNED(ump);
2892 #ifdef INVARIANTS
2893         {
2894                 struct worklist *wkn;
2895
2896                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2897                         if (wkn == wk)
2898                                 break;
2899                 if (wkn == NULL)
2900                         panic("remove_from_journal: %p is not in journal", wk);
2901         }
2902 #endif
2903         /*
2904          * We emulate a TAILQ to save space in most structures which do not
2905          * require TAILQ semantics.  Here we must update the tail position
2906          * when removing the tail which is not the final entry. This works
2907          * only if the worklist linkage are at the beginning of the structure.
2908          */
2909         if (ump->softdep_journal_tail == wk)
2910                 ump->softdep_journal_tail =
2911                     (struct worklist *)wk->wk_list.le_prev;
2912         WORKLIST_REMOVE(wk);
2913         ump->softdep_on_journal -= 1;
2914 }
2915
2916 /*
2917  * Check for journal space as well as dependency limits so the prelink
2918  * code can throttle both journaled and non-journaled filesystems.
2919  * Threshold is 0 for low and 1 for min.
2920  */
2921 static int
2922 journal_space(ump, thresh)
2923         struct ufsmount *ump;
2924         int thresh;
2925 {
2926         struct jblocks *jblocks;
2927         int limit, avail;
2928
2929         jblocks = ump->softdep_jblocks;
2930         if (jblocks == NULL)
2931                 return (1);
2932         /*
2933          * We use a tighter restriction here to prevent request_cleanup()
2934          * running in threads from running into locks we currently hold.
2935          * We have to be over the limit and our filesystem has to be
2936          * responsible for more than our share of that usage.
2937          */
2938         limit = (max_softdeps / 10) * 9;
2939         if (dep_current[D_INODEDEP] > limit &&
2940             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2941                 return (0);
2942         if (thresh)
2943                 thresh = jblocks->jb_min;
2944         else
2945                 thresh = jblocks->jb_low;
2946         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2947         avail = jblocks->jb_free - avail;
2948
2949         return (avail > thresh);
2950 }
2951
2952 static void
2953 journal_suspend(ump)
2954         struct ufsmount *ump;
2955 {
2956         struct jblocks *jblocks;
2957         struct mount *mp;
2958         bool set;
2959
2960         mp = UFSTOVFS(ump);
2961         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2962                 return;
2963
2964         jblocks = ump->softdep_jblocks;
2965         vfs_op_enter(mp);
2966         set = false;
2967         MNT_ILOCK(mp);
2968         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2969                 stat_journal_min++;
2970                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2971                 mp->mnt_susp_owner = ump->softdep_flushtd;
2972                 set = true;
2973         }
2974         jblocks->jb_suspended = 1;
2975         MNT_IUNLOCK(mp);
2976         if (!set)
2977                 vfs_op_exit(mp);
2978 }
2979
2980 static int
2981 journal_unsuspend(struct ufsmount *ump)
2982 {
2983         struct jblocks *jblocks;
2984         struct mount *mp;
2985
2986         mp = UFSTOVFS(ump);
2987         jblocks = ump->softdep_jblocks;
2988
2989         if (jblocks != NULL && jblocks->jb_suspended &&
2990             journal_space(ump, jblocks->jb_min)) {
2991                 jblocks->jb_suspended = 0;
2992                 FREE_LOCK(ump);
2993                 mp->mnt_susp_owner = curthread;
2994                 vfs_write_resume(mp, 0);
2995                 ACQUIRE_LOCK(ump);
2996                 return (1);
2997         }
2998         return (0);
2999 }
3000
3001 /*
3002  * Called before any allocation function to be certain that there is
3003  * sufficient space in the journal prior to creating any new records.
3004  * Since in the case of block allocation we may have multiple locked
3005  * buffers at the time of the actual allocation we can not block
3006  * when the journal records are created.  Doing so would create a deadlock
3007  * if any of these buffers needed to be flushed to reclaim space.  Instead
3008  * we require a sufficiently large amount of available space such that
3009  * each thread in the system could have passed this allocation check and
3010  * still have sufficient free space.  With 20% of a minimum journal size
3011  * of 1MB we have 6553 records available.
3012  */
3013 int
3014 softdep_prealloc(vp, waitok)
3015         struct vnode *vp;
3016         int waitok;
3017 {
3018         struct ufsmount *ump;
3019
3020         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3021             ("softdep_prealloc called on non-softdep filesystem"));
3022         /*
3023          * Nothing to do if we are not running journaled soft updates.
3024          * If we currently hold the snapshot lock, we must avoid
3025          * handling other resources that could cause deadlock.  Do not
3026          * touch quotas vnode since it is typically recursed with
3027          * other vnode locks held.
3028          */
3029         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3030             (vp->v_vflag & VV_SYSTEM) != 0)
3031                 return (0);
3032         ump = VFSTOUFS(vp->v_mount);
3033         ACQUIRE_LOCK(ump);
3034         if (journal_space(ump, 0)) {
3035                 FREE_LOCK(ump);
3036                 return (0);
3037         }
3038         stat_journal_low++;
3039         FREE_LOCK(ump);
3040         if (waitok == MNT_NOWAIT)
3041                 return (ENOSPC);
3042         /*
3043          * Attempt to sync this vnode once to flush any journal
3044          * work attached to it.
3045          */
3046         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3047                 ffs_syncvnode(vp, waitok, 0);
3048         ACQUIRE_LOCK(ump);
3049         process_removes(vp);
3050         process_truncates(vp);
3051         if (journal_space(ump, 0) == 0) {
3052                 softdep_speedup(ump);
3053                 if (journal_space(ump, 1) == 0)
3054                         journal_suspend(ump);
3055         }
3056         FREE_LOCK(ump);
3057
3058         return (0);
3059 }
3060
3061 /*
3062  * Before adjusting a link count on a vnode verify that we have sufficient
3063  * journal space.  If not, process operations that depend on the currently
3064  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3065  * and softdep flush threads can not acquire these locks to reclaim space.
3066  */
3067 static void
3068 softdep_prelink(dvp, vp)
3069         struct vnode *dvp;
3070         struct vnode *vp;
3071 {
3072         struct ufsmount *ump;
3073
3074         ump = VFSTOUFS(dvp->v_mount);
3075         LOCK_OWNED(ump);
3076         /*
3077          * Nothing to do if we have sufficient journal space.
3078          * If we currently hold the snapshot lock, we must avoid
3079          * handling other resources that could cause deadlock.
3080          */
3081         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3082                 return;
3083         stat_journal_low++;
3084         FREE_LOCK(ump);
3085         if (vp)
3086                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3087         ffs_syncvnode(dvp, MNT_WAIT, 0);
3088         ACQUIRE_LOCK(ump);
3089         /* Process vp before dvp as it may create .. removes. */
3090         if (vp) {
3091                 process_removes(vp);
3092                 process_truncates(vp);
3093         }
3094         process_removes(dvp);
3095         process_truncates(dvp);
3096         softdep_speedup(ump);
3097         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3098         if (journal_space(ump, 0) == 0) {
3099                 softdep_speedup(ump);
3100                 if (journal_space(ump, 1) == 0)
3101                         journal_suspend(ump);
3102         }
3103 }
3104
3105 static void
3106 jseg_write(ump, jseg, data)
3107         struct ufsmount *ump;
3108         struct jseg *jseg;
3109         uint8_t *data;
3110 {
3111         struct jsegrec *rec;
3112
3113         rec = (struct jsegrec *)data;
3114         rec->jsr_seq = jseg->js_seq;
3115         rec->jsr_oldest = jseg->js_oldseq;
3116         rec->jsr_cnt = jseg->js_cnt;
3117         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3118         rec->jsr_crc = 0;
3119         rec->jsr_time = ump->um_fs->fs_mtime;
3120 }
3121
3122 static inline void
3123 inoref_write(inoref, jseg, rec)
3124         struct inoref *inoref;
3125         struct jseg *jseg;
3126         struct jrefrec *rec;
3127 {
3128
3129         inoref->if_jsegdep->jd_seg = jseg;
3130         rec->jr_ino = inoref->if_ino;
3131         rec->jr_parent = inoref->if_parent;
3132         rec->jr_nlink = inoref->if_nlink;
3133         rec->jr_mode = inoref->if_mode;
3134         rec->jr_diroff = inoref->if_diroff;
3135 }
3136
3137 static void
3138 jaddref_write(jaddref, jseg, data)
3139         struct jaddref *jaddref;
3140         struct jseg *jseg;
3141         uint8_t *data;
3142 {
3143         struct jrefrec *rec;
3144
3145         rec = (struct jrefrec *)data;
3146         rec->jr_op = JOP_ADDREF;
3147         inoref_write(&jaddref->ja_ref, jseg, rec);
3148 }
3149
3150 static void
3151 jremref_write(jremref, jseg, data)
3152         struct jremref *jremref;
3153         struct jseg *jseg;
3154         uint8_t *data;
3155 {
3156         struct jrefrec *rec;
3157
3158         rec = (struct jrefrec *)data;
3159         rec->jr_op = JOP_REMREF;
3160         inoref_write(&jremref->jr_ref, jseg, rec);
3161 }
3162
3163 static void
3164 jmvref_write(jmvref, jseg, data)
3165         struct jmvref *jmvref;
3166         struct jseg *jseg;
3167         uint8_t *data;
3168 {
3169         struct jmvrec *rec;
3170
3171         rec = (struct jmvrec *)data;
3172         rec->jm_op = JOP_MVREF;
3173         rec->jm_ino = jmvref->jm_ino;
3174         rec->jm_parent = jmvref->jm_parent;
3175         rec->jm_oldoff = jmvref->jm_oldoff;
3176         rec->jm_newoff = jmvref->jm_newoff;
3177 }
3178
3179 static void
3180 jnewblk_write(jnewblk, jseg, data)
3181         struct jnewblk *jnewblk;
3182         struct jseg *jseg;
3183         uint8_t *data;
3184 {
3185         struct jblkrec *rec;
3186
3187         jnewblk->jn_jsegdep->jd_seg = jseg;
3188         rec = (struct jblkrec *)data;
3189         rec->jb_op = JOP_NEWBLK;
3190         rec->jb_ino = jnewblk->jn_ino;
3191         rec->jb_blkno = jnewblk->jn_blkno;
3192         rec->jb_lbn = jnewblk->jn_lbn;
3193         rec->jb_frags = jnewblk->jn_frags;
3194         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3195 }
3196
3197 static void
3198 jfreeblk_write(jfreeblk, jseg, data)
3199         struct jfreeblk *jfreeblk;
3200         struct jseg *jseg;
3201         uint8_t *data;
3202 {
3203         struct jblkrec *rec;
3204
3205         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3206         rec = (struct jblkrec *)data;
3207         rec->jb_op = JOP_FREEBLK;
3208         rec->jb_ino = jfreeblk->jf_ino;
3209         rec->jb_blkno = jfreeblk->jf_blkno;
3210         rec->jb_lbn = jfreeblk->jf_lbn;
3211         rec->jb_frags = jfreeblk->jf_frags;
3212         rec->jb_oldfrags = 0;
3213 }
3214
3215 static void
3216 jfreefrag_write(jfreefrag, jseg, data)
3217         struct jfreefrag *jfreefrag;
3218         struct jseg *jseg;
3219         uint8_t *data;
3220 {
3221         struct jblkrec *rec;
3222
3223         jfreefrag->fr_jsegdep->jd_seg = jseg;
3224         rec = (struct jblkrec *)data;
3225         rec->jb_op = JOP_FREEBLK;
3226         rec->jb_ino = jfreefrag->fr_ino;
3227         rec->jb_blkno = jfreefrag->fr_blkno;
3228         rec->jb_lbn = jfreefrag->fr_lbn;
3229         rec->jb_frags = jfreefrag->fr_frags;
3230         rec->jb_oldfrags = 0;
3231 }
3232
3233 static void
3234 jtrunc_write(jtrunc, jseg, data)
3235         struct jtrunc *jtrunc;
3236         struct jseg *jseg;
3237         uint8_t *data;
3238 {
3239         struct jtrncrec *rec;
3240
3241         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3242         rec = (struct jtrncrec *)data;
3243         rec->jt_op = JOP_TRUNC;
3244         rec->jt_ino = jtrunc->jt_ino;
3245         rec->jt_size = jtrunc->jt_size;
3246         rec->jt_extsize = jtrunc->jt_extsize;
3247 }
3248
3249 static void
3250 jfsync_write(jfsync, jseg, data)
3251         struct jfsync *jfsync;
3252         struct jseg *jseg;
3253         uint8_t *data;
3254 {
3255         struct jtrncrec *rec;
3256
3257         rec = (struct jtrncrec *)data;
3258         rec->jt_op = JOP_SYNC;
3259         rec->jt_ino = jfsync->jfs_ino;
3260         rec->jt_size = jfsync->jfs_size;
3261         rec->jt_extsize = jfsync->jfs_extsize;
3262 }
3263
3264 static void
3265 softdep_flushjournal(mp)
3266         struct mount *mp;
3267 {
3268         struct jblocks *jblocks;
3269         struct ufsmount *ump;
3270
3271         if (MOUNTEDSUJ(mp) == 0)
3272                 return;
3273         ump = VFSTOUFS(mp);
3274         jblocks = ump->softdep_jblocks;
3275         ACQUIRE_LOCK(ump);
3276         while (ump->softdep_on_journal) {
3277                 jblocks->jb_needseg = 1;
3278                 softdep_process_journal(mp, NULL, MNT_WAIT);
3279         }
3280         FREE_LOCK(ump);
3281 }
3282
3283 static void softdep_synchronize_completed(struct bio *);
3284 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3285
3286 static void
3287 softdep_synchronize_completed(bp)
3288         struct bio *bp;
3289 {
3290         struct jseg *oldest;
3291         struct jseg *jseg;
3292         struct ufsmount *ump;
3293
3294         /*
3295          * caller1 marks the last segment written before we issued the
3296          * synchronize cache.
3297          */
3298         jseg = bp->bio_caller1;
3299         if (jseg == NULL) {
3300                 g_destroy_bio(bp);
3301                 return;
3302         }
3303         ump = VFSTOUFS(jseg->js_list.wk_mp);
3304         ACQUIRE_LOCK(ump);
3305         oldest = NULL;
3306         /*
3307          * Mark all the journal entries waiting on the synchronize cache
3308          * as completed so they may continue on.
3309          */
3310         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3311                 jseg->js_state |= COMPLETE;
3312                 oldest = jseg;
3313                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3314         }
3315         /*
3316          * Restart deferred journal entry processing from the oldest
3317          * completed jseg.
3318          */
3319         if (oldest)
3320                 complete_jsegs(oldest);
3321
3322         FREE_LOCK(ump);
3323         g_destroy_bio(bp);
3324 }
3325
3326 /*
3327  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3328  * barriers.  The journal must be written prior to any blocks that depend
3329  * on it and the journal can not be released until the blocks have be
3330  * written.  This code handles both barriers simultaneously.
3331  */
3332 static void
3333 softdep_synchronize(bp, ump, caller1)
3334         struct bio *bp;
3335         struct ufsmount *ump;
3336         void *caller1;
3337 {
3338
3339         bp->bio_cmd = BIO_FLUSH;
3340         bp->bio_flags |= BIO_ORDERED;
3341         bp->bio_data = NULL;
3342         bp->bio_offset = ump->um_cp->provider->mediasize;
3343         bp->bio_length = 0;
3344         bp->bio_done = softdep_synchronize_completed;
3345         bp->bio_caller1 = caller1;
3346         g_io_request(bp,
3347             (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3348 }
3349
3350 /*
3351  * Flush some journal records to disk.
3352  */
3353 static void
3354 softdep_process_journal(mp, needwk, flags)
3355         struct mount *mp;
3356         struct worklist *needwk;
3357         int flags;
3358 {
3359         struct jblocks *jblocks;
3360         struct ufsmount *ump;
3361         struct worklist *wk;
3362         struct jseg *jseg;
3363         struct buf *bp;
3364         struct bio *bio;
3365         uint8_t *data;
3366         struct fs *fs;
3367         int shouldflush;
3368         int segwritten;
3369         int jrecmin;    /* Minimum records per block. */
3370         int jrecmax;    /* Maximum records per block. */
3371         int size;
3372         int cnt;
3373         int off;
3374         int devbsize;
3375
3376         if (MOUNTEDSUJ(mp) == 0)
3377                 return;
3378         shouldflush = softdep_flushcache;
3379         bio = NULL;
3380         jseg = NULL;
3381         ump = VFSTOUFS(mp);
3382         LOCK_OWNED(ump);
3383         fs = ump->um_fs;
3384         jblocks = ump->softdep_jblocks;
3385         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3386         /*
3387          * We write anywhere between a disk block and fs block.  The upper
3388          * bound is picked to prevent buffer cache fragmentation and limit
3389          * processing time per I/O.
3390          */
3391         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3392         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3393         segwritten = 0;
3394         for (;;) {
3395                 cnt = ump->softdep_on_journal;
3396                 /*
3397                  * Criteria for writing a segment:
3398                  * 1) We have a full block.
3399                  * 2) We're called from jwait() and haven't found the
3400                  *    journal item yet.
3401                  * 3) Always write if needseg is set.
3402                  * 4) If we are called from process_worklist and have
3403                  *    not yet written anything we write a partial block
3404                  *    to enforce a 1 second maximum latency on journal
3405                  *    entries.
3406                  */
3407                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3408                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3409                         break;
3410                 cnt++;
3411                 /*
3412                  * Verify some free journal space.  softdep_prealloc() should
3413                  * guarantee that we don't run out so this is indicative of
3414                  * a problem with the flow control.  Try to recover
3415                  * gracefully in any event.
3416                  */
3417                 while (jblocks->jb_free == 0) {
3418                         if (flags != MNT_WAIT)
3419                                 break;
3420                         printf("softdep: Out of journal space!\n");
3421                         softdep_speedup(ump);
3422                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3423                 }
3424                 FREE_LOCK(ump);
3425                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3426                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3427                 LIST_INIT(&jseg->js_entries);
3428                 LIST_INIT(&jseg->js_indirs);
3429                 jseg->js_state = ATTACHED;
3430                 if (shouldflush == 0)
3431                         jseg->js_state |= COMPLETE;
3432                 else if (bio == NULL)
3433                         bio = g_alloc_bio();
3434                 jseg->js_jblocks = jblocks;
3435                 bp = geteblk(fs->fs_bsize, 0);
3436                 ACQUIRE_LOCK(ump);
3437                 /*
3438                  * If there was a race while we were allocating the block
3439                  * and jseg the entry we care about was likely written.
3440                  * We bail out in both the WAIT and NOWAIT case and assume
3441                  * the caller will loop if the entry it cares about is
3442                  * not written.
3443                  */
3444                 cnt = ump->softdep_on_journal;
3445                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3446                         bp->b_flags |= B_INVAL | B_NOCACHE;
3447                         WORKITEM_FREE(jseg, D_JSEG);
3448                         FREE_LOCK(ump);
3449                         brelse(bp);
3450                         ACQUIRE_LOCK(ump);
3451                         break;
3452                 }
3453                 /*
3454                  * Calculate the disk block size required for the available
3455                  * records rounded to the min size.
3456                  */
3457                 if (cnt == 0)
3458                         size = devbsize;
3459                 else if (cnt < jrecmax)
3460                         size = howmany(cnt, jrecmin) * devbsize;
3461                 else
3462                         size = fs->fs_bsize;
3463                 /*
3464                  * Allocate a disk block for this journal data and account
3465                  * for truncation of the requested size if enough contiguous
3466                  * space was not available.
3467                  */
3468                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3469                 bp->b_lblkno = bp->b_blkno;
3470                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3471                 bp->b_bcount = size;
3472                 bp->b_flags &= ~B_INVAL;
3473                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3474                 /*
3475                  * Initialize our jseg with cnt records.  Assign the next
3476                  * sequence number to it and link it in-order.
3477                  */
3478                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3479                 jseg->js_buf = bp;
3480                 jseg->js_cnt = cnt;
3481                 jseg->js_refs = cnt + 1;        /* Self ref. */
3482                 jseg->js_size = size;
3483                 jseg->js_seq = jblocks->jb_nextseq++;
3484                 if (jblocks->jb_oldestseg == NULL)
3485                         jblocks->jb_oldestseg = jseg;
3486                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3487                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3488                 if (jblocks->jb_writeseg == NULL)
3489                         jblocks->jb_writeseg = jseg;
3490                 /*
3491                  * Start filling in records from the pending list.
3492                  */
3493                 data = bp->b_data;
3494                 off = 0;
3495
3496                 /*
3497                  * Always put a header on the first block.
3498                  * XXX As with below, there might not be a chance to get
3499                  * into the loop.  Ensure that something valid is written.
3500                  */
3501                 jseg_write(ump, jseg, data);
3502                 off += JREC_SIZE;
3503                 data = bp->b_data + off;
3504
3505                 /*
3506                  * XXX Something is wrong here.  There's no work to do,
3507                  * but we need to perform and I/O and allow it to complete
3508                  * anyways.
3509                  */
3510                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3511                         stat_emptyjblocks++;
3512
3513                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3514                     != NULL) {
3515                         if (cnt == 0)
3516                                 break;
3517                         /* Place a segment header on every device block. */
3518                         if ((off % devbsize) == 0) {
3519                                 jseg_write(ump, jseg, data);
3520                                 off += JREC_SIZE;
3521                                 data = bp->b_data + off;
3522                         }
3523                         if (wk == needwk)
3524                                 needwk = NULL;
3525                         remove_from_journal(wk);
3526                         wk->wk_state |= INPROGRESS;
3527                         WORKLIST_INSERT(&jseg->js_entries, wk);
3528                         switch (wk->wk_type) {
3529                         case D_JADDREF:
3530                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3531                                 break;
3532                         case D_JREMREF:
3533                                 jremref_write(WK_JREMREF(wk), jseg, data);
3534                                 break;
3535                         case D_JMVREF:
3536                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3537                                 break;
3538                         case D_JNEWBLK:
3539                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3540                                 break;
3541                         case D_JFREEBLK:
3542                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3543                                 break;
3544                         case D_JFREEFRAG:
3545                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3546                                 break;
3547                         case D_JTRUNC:
3548                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3549                                 break;
3550                         case D_JFSYNC:
3551                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3552                                 break;
3553                         default:
3554                                 panic("process_journal: Unknown type %s",
3555                                     TYPENAME(wk->wk_type));
3556                                 /* NOTREACHED */
3557                         }
3558                         off += JREC_SIZE;
3559                         data = bp->b_data + off;
3560                         cnt--;
3561                 }
3562
3563                 /* Clear any remaining space so we don't leak kernel data */
3564                 if (size > off)
3565                         bzero(data, size - off);
3566
3567                 /*
3568                  * Write this one buffer and continue.
3569                  */
3570                 segwritten = 1;
3571                 jblocks->jb_needseg = 0;
3572                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3573                 FREE_LOCK(ump);
3574                 pbgetvp(ump->um_devvp, bp);
3575                 /*
3576                  * We only do the blocking wait once we find the journal
3577                  * entry we're looking for.
3578                  */
3579                 if (needwk == NULL && flags == MNT_WAIT)
3580                         bwrite(bp);
3581                 else
3582                         bawrite(bp);
3583                 ACQUIRE_LOCK(ump);
3584         }
3585         /*
3586          * If we wrote a segment issue a synchronize cache so the journal
3587          * is reflected on disk before the data is written.  Since reclaiming
3588          * journal space also requires writing a journal record this
3589          * process also enforces a barrier before reclamation.
3590          */
3591         if (segwritten && shouldflush) {
3592                 softdep_synchronize(bio, ump, 
3593                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3594         } else if (bio)
3595                 g_destroy_bio(bio);
3596         /*
3597          * If we've suspended the filesystem because we ran out of journal
3598          * space either try to sync it here to make some progress or
3599          * unsuspend it if we already have.
3600          */
3601         if (flags == 0 && jblocks->jb_suspended) {
3602                 if (journal_unsuspend(ump))
3603                         return;
3604                 FREE_LOCK(ump);
3605                 VFS_SYNC(mp, MNT_NOWAIT);
3606                 ffs_sbupdate(ump, MNT_WAIT, 0);
3607                 ACQUIRE_LOCK(ump);
3608         }
3609 }
3610
3611 /*
3612  * Complete a jseg, allowing all dependencies awaiting journal writes
3613  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3614  * structures so that the journal segment can be freed to reclaim space.
3615  */
3616 static void
3617 complete_jseg(jseg)
3618         struct jseg *jseg;
3619 {
3620         struct worklist *wk;
3621         struct jmvref *jmvref;
3622 #ifdef INVARIANTS
3623         int i = 0;
3624 #endif
3625
3626         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3627                 WORKLIST_REMOVE(wk);
3628                 wk->wk_state &= ~INPROGRESS;
3629                 wk->wk_state |= COMPLETE;
3630                 KASSERT(i++ < jseg->js_cnt,
3631                     ("handle_written_jseg: overflow %d >= %d",
3632                     i - 1, jseg->js_cnt));
3633                 switch (wk->wk_type) {
3634                 case D_JADDREF:
3635                         handle_written_jaddref(WK_JADDREF(wk));
3636                         break;
3637                 case D_JREMREF:
3638                         handle_written_jremref(WK_JREMREF(wk));
3639                         break;
3640                 case D_JMVREF:
3641                         rele_jseg(jseg);        /* No jsegdep. */
3642                         jmvref = WK_JMVREF(wk);
3643                         LIST_REMOVE(jmvref, jm_deps);
3644                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3645                                 free_pagedep(jmvref->jm_pagedep);
3646                         WORKITEM_FREE(jmvref, D_JMVREF);
3647                         break;
3648                 case D_JNEWBLK:
3649                         handle_written_jnewblk(WK_JNEWBLK(wk));
3650                         break;
3651                 case D_JFREEBLK:
3652                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3653                         break;
3654                 case D_JTRUNC:
3655                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3656                         break;
3657                 case D_JFSYNC:
3658                         rele_jseg(jseg);        /* No jsegdep. */
3659                         WORKITEM_FREE(wk, D_JFSYNC);
3660                         break;
3661                 case D_JFREEFRAG:
3662                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3663                         break;
3664                 default:
3665                         panic("handle_written_jseg: Unknown type %s",
3666                             TYPENAME(wk->wk_type));
3667                         /* NOTREACHED */
3668                 }
3669         }
3670         /* Release the self reference so the structure may be freed. */
3671         rele_jseg(jseg);
3672 }
3673
3674 /*
3675  * Determine which jsegs are ready for completion processing.  Waits for
3676  * synchronize cache to complete as well as forcing in-order completion
3677  * of journal entries.
3678  */
3679 static void
3680 complete_jsegs(jseg)
3681         struct jseg *jseg;
3682 {
3683         struct jblocks *jblocks;
3684         struct jseg *jsegn;
3685
3686         jblocks = jseg->js_jblocks;
3687         /*
3688          * Don't allow out of order completions.  If this isn't the first
3689          * block wait for it to write before we're done.
3690          */
3691         if (jseg != jblocks->jb_writeseg)
3692                 return;
3693         /* Iterate through available jsegs processing their entries. */
3694         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3695                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3696                 jsegn = TAILQ_NEXT(jseg, js_next);
3697                 complete_jseg(jseg);
3698                 jseg = jsegn;
3699         }
3700         jblocks->jb_writeseg = jseg;
3701         /*
3702          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3703          */
3704         free_jsegs(jblocks);
3705 }
3706
3707 /*
3708  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3709  * the final completions.
3710  */
3711 static void
3712 handle_written_jseg(jseg, bp)
3713         struct jseg *jseg;
3714         struct buf *bp;
3715 {
3716
3717         if (jseg->js_refs == 0)
3718                 panic("handle_written_jseg: No self-reference on %p", jseg);
3719         jseg->js_state |= DEPCOMPLETE;
3720         /*
3721          * We'll never need this buffer again, set flags so it will be
3722          * discarded.
3723          */
3724         bp->b_flags |= B_INVAL | B_NOCACHE;
3725         pbrelvp(bp);
3726         complete_jsegs(jseg);
3727 }
3728
3729 static inline struct jsegdep *
3730 inoref_jseg(inoref)
3731         struct inoref *inoref;
3732 {
3733         struct jsegdep *jsegdep;
3734
3735         jsegdep = inoref->if_jsegdep;
3736         inoref->if_jsegdep = NULL;
3737
3738         return (jsegdep);
3739 }
3740
3741 /*
3742  * Called once a jremref has made it to stable store.  The jremref is marked
3743  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3744  * for the jremref to complete will be awoken by free_jremref.
3745  */
3746 static void
3747 handle_written_jremref(jremref)
3748         struct jremref *jremref;
3749 {
3750         struct inodedep *inodedep;
3751         struct jsegdep *jsegdep;
3752         struct dirrem *dirrem;
3753
3754         /* Grab the jsegdep. */
3755         jsegdep = inoref_jseg(&jremref->jr_ref);
3756         /*
3757          * Remove us from the inoref list.
3758          */
3759         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3760             0, &inodedep) == 0)
3761                 panic("handle_written_jremref: Lost inodedep");
3762         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3763         /*
3764          * Complete the dirrem.
3765          */
3766         dirrem = jremref->jr_dirrem;
3767         jremref->jr_dirrem = NULL;
3768         LIST_REMOVE(jremref, jr_deps);
3769         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3770         jwork_insert(&dirrem->dm_jwork, jsegdep);
3771         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3772             (dirrem->dm_state & COMPLETE) != 0)
3773                 add_to_worklist(&dirrem->dm_list, 0);
3774         free_jremref(jremref);
3775 }
3776
3777 /*
3778  * Called once a jaddref has made it to stable store.  The dependency is
3779  * marked complete and any dependent structures are added to the inode
3780  * bufwait list to be completed as soon as it is written.  If a bitmap write
3781  * depends on this entry we move the inode into the inodedephd of the
3782  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3783  */
3784 static void
3785 handle_written_jaddref(jaddref)
3786         struct jaddref *jaddref;
3787 {
3788         struct jsegdep *jsegdep;
3789         struct inodedep *inodedep;
3790         struct diradd *diradd;
3791         struct mkdir *mkdir;
3792
3793         /* Grab the jsegdep. */
3794         jsegdep = inoref_jseg(&jaddref->ja_ref);
3795         mkdir = NULL;
3796         diradd = NULL;
3797         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3798             0, &inodedep) == 0)
3799                 panic("handle_written_jaddref: Lost inodedep.");
3800         if (jaddref->ja_diradd == NULL)
3801                 panic("handle_written_jaddref: No dependency");
3802         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3803                 diradd = jaddref->ja_diradd;
3804                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3805         } else if (jaddref->ja_state & MKDIR_PARENT) {
3806                 mkdir = jaddref->ja_mkdir;
3807                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3808         } else if (jaddref->ja_state & MKDIR_BODY)
3809                 mkdir = jaddref->ja_mkdir;
3810         else
3811                 panic("handle_written_jaddref: Unknown dependency %p",
3812                     jaddref->ja_diradd);
3813         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3814         /*
3815          * Remove us from the inode list.
3816          */
3817         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3818         /*
3819          * The mkdir may be waiting on the jaddref to clear before freeing.
3820          */
3821         if (mkdir) {
3822                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3823                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3824                     TYPENAME(mkdir->md_list.wk_type)));
3825                 mkdir->md_jaddref = NULL;
3826                 diradd = mkdir->md_diradd;
3827                 mkdir->md_state |= DEPCOMPLETE;
3828                 complete_mkdir(mkdir);
3829         }
3830         jwork_insert(&diradd->da_jwork, jsegdep);
3831         if (jaddref->ja_state & NEWBLOCK) {
3832                 inodedep->id_state |= ONDEPLIST;
3833                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3834                     inodedep, id_deps);
3835         }
3836         free_jaddref(jaddref);
3837 }
3838
3839 /*
3840  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3841  * is placed in the bmsafemap to await notification of a written bitmap.  If
3842  * the operation was canceled we add the segdep to the appropriate
3843  * dependency to free the journal space once the canceling operation
3844  * completes.
3845  */
3846 static void
3847 handle_written_jnewblk(jnewblk)
3848         struct jnewblk *jnewblk;
3849 {
3850         struct bmsafemap *bmsafemap;
3851         struct freefrag *freefrag;
3852         struct freework *freework;
3853         struct jsegdep *jsegdep;
3854         struct newblk *newblk;
3855
3856         /* Grab the jsegdep. */
3857         jsegdep = jnewblk->jn_jsegdep;
3858         jnewblk->jn_jsegdep = NULL;
3859         if (jnewblk->jn_dep == NULL) 
3860                 panic("handle_written_jnewblk: No dependency for the segdep.");
3861         switch (jnewblk->jn_dep->wk_type) {
3862         case D_NEWBLK:
3863         case D_ALLOCDIRECT:
3864         case D_ALLOCINDIR:
3865                 /*
3866                  * Add the written block to the bmsafemap so it can
3867                  * be notified when the bitmap is on disk.
3868                  */
3869                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3870                 newblk->nb_jnewblk = NULL;
3871                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3872                         bmsafemap = newblk->nb_bmsafemap;
3873                         newblk->nb_state |= ONDEPLIST;
3874                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3875                             nb_deps);
3876                 }
3877                 jwork_insert(&newblk->nb_jwork, jsegdep);
3878                 break;
3879         case D_FREEFRAG:
3880                 /*
3881                  * A newblock being removed by a freefrag when replaced by
3882                  * frag extension.
3883                  */
3884                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3885                 freefrag->ff_jdep = NULL;
3886                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3887                 break;
3888         case D_FREEWORK:
3889                 /*
3890                  * A direct block was removed by truncate.
3891                  */
3892                 freework = WK_FREEWORK(jnewblk->jn_dep);
3893                 freework->fw_jnewblk = NULL;
3894                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3895                 break;
3896         default:
3897                 panic("handle_written_jnewblk: Unknown type %d.",
3898                     jnewblk->jn_dep->wk_type);
3899         }
3900         jnewblk->jn_dep = NULL;
3901         free_jnewblk(jnewblk);
3902 }
3903
3904 /*
3905  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3906  * an in-flight allocation that has not yet been committed.  Divorce us
3907  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3908  * to the worklist.
3909  */
3910 static void
3911 cancel_jfreefrag(jfreefrag)
3912         struct jfreefrag *jfreefrag;
3913 {
3914         struct freefrag *freefrag;
3915
3916         if (jfreefrag->fr_jsegdep) {
3917                 free_jsegdep(jfreefrag->fr_jsegdep);
3918                 jfreefrag->fr_jsegdep = NULL;
3919         }
3920         freefrag = jfreefrag->fr_freefrag;
3921         jfreefrag->fr_freefrag = NULL;
3922         free_jfreefrag(jfreefrag);
3923         freefrag->ff_state |= DEPCOMPLETE;
3924         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3925 }
3926
3927 /*
3928  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3929  */
3930 static void
3931 free_jfreefrag(jfreefrag)
3932         struct jfreefrag *jfreefrag;
3933 {
3934
3935         if (jfreefrag->fr_state & INPROGRESS)
3936                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3937         else if (jfreefrag->fr_state & ONWORKLIST)
3938                 remove_from_journal(&jfreefrag->fr_list);
3939         if (jfreefrag->fr_freefrag != NULL)
3940                 panic("free_jfreefrag:  Still attached to a freefrag.");
3941         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3942 }
3943
3944 /*
3945  * Called when the journal write for a jfreefrag completes.  The parent
3946  * freefrag is added to the worklist if this completes its dependencies.
3947  */
3948 static void
3949 handle_written_jfreefrag(jfreefrag)
3950         struct jfreefrag *jfreefrag;
3951 {
3952         struct jsegdep *jsegdep;
3953         struct freefrag *freefrag;
3954
3955         /* Grab the jsegdep. */
3956         jsegdep = jfreefrag->fr_jsegdep;
3957         jfreefrag->fr_jsegdep = NULL;
3958         freefrag = jfreefrag->fr_freefrag;
3959         if (freefrag == NULL)
3960                 panic("handle_written_jfreefrag: No freefrag.");
3961         freefrag->ff_state |= DEPCOMPLETE;
3962         freefrag->ff_jdep = NULL;
3963         jwork_insert(&freefrag->ff_jwork, jsegdep);
3964         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3965                 add_to_worklist(&freefrag->ff_list, 0);
3966         jfreefrag->fr_freefrag = NULL;
3967         free_jfreefrag(jfreefrag);
3968 }
3969
3970 /*
3971  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3972  * is removed from the freeblks list of pending journal writes and the
3973  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3974  * have been reclaimed.
3975  */
3976 static void
3977 handle_written_jblkdep(jblkdep)
3978         struct jblkdep *jblkdep;
3979 {
3980         struct freeblks *freeblks;
3981         struct jsegdep *jsegdep;
3982
3983         /* Grab the jsegdep. */
3984         jsegdep = jblkdep->jb_jsegdep;
3985         jblkdep->jb_jsegdep = NULL;
3986         freeblks = jblkdep->jb_freeblks;
3987         LIST_REMOVE(jblkdep, jb_deps);
3988         jwork_insert(&freeblks->fb_jwork, jsegdep);
3989         /*
3990          * If the freeblks is all journaled, we can add it to the worklist.
3991          */
3992         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3993             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3994                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3995
3996         free_jblkdep(jblkdep);
3997 }
3998
3999 static struct jsegdep *
4000 newjsegdep(struct worklist *wk)
4001 {
4002         struct jsegdep *jsegdep;
4003
4004         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4005         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4006         jsegdep->jd_seg = NULL;
4007
4008         return (jsegdep);
4009 }
4010
4011 static struct jmvref *
4012 newjmvref(dp, ino, oldoff, newoff)
4013         struct inode *dp;
4014         ino_t ino;
4015         off_t oldoff;
4016         off_t newoff;
4017 {
4018         struct jmvref *jmvref;
4019
4020         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4021         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4022         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4023         jmvref->jm_parent = dp->i_number;
4024         jmvref->jm_ino = ino;
4025         jmvref->jm_oldoff = oldoff;
4026         jmvref->jm_newoff = newoff;
4027
4028         return (jmvref);
4029 }
4030
4031 /*
4032  * Allocate a new jremref that tracks the removal of ip from dp with the
4033  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4034  * DEPCOMPLETE as we have all the information required for the journal write
4035  * and the directory has already been removed from the buffer.  The caller
4036  * is responsible for linking the jremref into the pagedep and adding it
4037  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4038  * a DOTDOT addition so handle_workitem_remove() can properly assign
4039  * the jsegdep when we're done.
4040  */
4041 static struct jremref *
4042 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4043     off_t diroff, nlink_t nlink)
4044 {
4045         struct jremref *jremref;
4046
4047         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4048         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4049         jremref->jr_state = ATTACHED;
4050         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4051            nlink, ip->i_mode);
4052         jremref->jr_dirrem = dirrem;
4053
4054         return (jremref);
4055 }
4056
4057 static inline void
4058 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4059     nlink_t nlink, uint16_t mode)
4060 {
4061
4062         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4063         inoref->if_diroff = diroff;
4064         inoref->if_ino = ino;
4065         inoref->if_parent = parent;
4066         inoref->if_nlink = nlink;
4067         inoref->if_mode = mode;
4068 }
4069
4070 /*
4071  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4072  * directory offset may not be known until later.  The caller is responsible
4073  * adding the entry to the journal when this information is available.  nlink
4074  * should be the link count prior to the addition and mode is only required
4075  * to have the correct FMT.
4076  */
4077 static struct jaddref *
4078 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4079     uint16_t mode)
4080 {
4081         struct jaddref *jaddref;
4082
4083         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4084         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4085         jaddref->ja_state = ATTACHED;
4086         jaddref->ja_mkdir = NULL;
4087         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4088
4089         return (jaddref);
4090 }
4091
4092 /*
4093  * Create a new free dependency for a freework.  The caller is responsible
4094  * for adjusting the reference count when it has the lock held.  The freedep
4095  * will track an outstanding bitmap write that will ultimately clear the
4096  * freework to continue.
4097  */
4098 static struct freedep *
4099 newfreedep(struct freework *freework)
4100 {
4101         struct freedep *freedep;
4102
4103         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4104         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4105         freedep->fd_freework = freework;
4106
4107         return (freedep);
4108 }
4109
4110 /*
4111  * Free a freedep structure once the buffer it is linked to is written.  If
4112  * this is the last reference to the freework schedule it for completion.
4113  */
4114 static void
4115 free_freedep(freedep)
4116         struct freedep *freedep;
4117 {
4118         struct freework *freework;
4119
4120         freework = freedep->fd_freework;
4121         freework->fw_freeblks->fb_cgwait--;
4122         if (--freework->fw_ref == 0)
4123                 freework_enqueue(freework);
4124         WORKITEM_FREE(freedep, D_FREEDEP);
4125 }
4126
4127 /*
4128  * Allocate a new freework structure that may be a level in an indirect
4129  * when parent is not NULL or a top level block when it is.  The top level
4130  * freework structures are allocated without the per-filesystem lock held
4131  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4132  */
4133 static struct freework *
4134 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4135         struct ufsmount *ump;
4136         struct freeblks *freeblks;
4137         struct freework *parent;
4138         ufs_lbn_t lbn;
4139         ufs2_daddr_t nb;
4140         int frags;
4141         int off;
4142         int journal;
4143 {
4144         struct freework *freework;
4145
4146         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4147         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4148         freework->fw_state = ATTACHED;
4149         freework->fw_jnewblk = NULL;
4150         freework->fw_freeblks = freeblks;
4151         freework->fw_parent = parent;
4152         freework->fw_lbn = lbn;
4153         freework->fw_blkno = nb;
4154         freework->fw_frags = frags;
4155         freework->fw_indir = NULL;
4156         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4157             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4158         freework->fw_start = freework->fw_off = off;
4159         if (journal)
4160                 newjfreeblk(freeblks, lbn, nb, frags);
4161         if (parent == NULL) {
4162                 ACQUIRE_LOCK(ump);
4163                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4164                 freeblks->fb_ref++;
4165                 FREE_LOCK(ump);
4166         }
4167
4168         return (freework);
4169 }
4170
4171 /*
4172  * Eliminate a jfreeblk for a block that does not need journaling.
4173  */
4174 static void
4175 cancel_jfreeblk(freeblks, blkno)
4176         struct freeblks *freeblks;
4177         ufs2_daddr_t blkno;
4178 {
4179         struct jfreeblk *jfreeblk;
4180         struct jblkdep *jblkdep;
4181
4182         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4183                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4184                         continue;
4185                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4186                 if (jfreeblk->jf_blkno == blkno)
4187                         break;
4188         }
4189         if (jblkdep == NULL)
4190                 return;
4191         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4192         free_jsegdep(jblkdep->jb_jsegdep);
4193         LIST_REMOVE(jblkdep, jb_deps);
4194         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4195 }
4196
4197 /*
4198  * Allocate a new jfreeblk to journal top level block pointer when truncating
4199  * a file.  The caller must add this to the worklist when the per-filesystem
4200  * lock is held.
4201  */
4202 static struct jfreeblk *
4203 newjfreeblk(freeblks, lbn, blkno, frags)
4204         struct freeblks *freeblks;
4205         ufs_lbn_t lbn;
4206         ufs2_daddr_t blkno;
4207         int frags;
4208 {
4209         struct jfreeblk *jfreeblk;
4210
4211         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4212         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4213             freeblks->fb_list.wk_mp);
4214         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4215         jfreeblk->jf_dep.jb_freeblks = freeblks;
4216         jfreeblk->jf_ino = freeblks->fb_inum;
4217         jfreeblk->jf_lbn = lbn;
4218         jfreeblk->jf_blkno = blkno;
4219         jfreeblk->jf_frags = frags;
4220         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4221
4222         return (jfreeblk);
4223 }
4224
4225 /*
4226  * The journal is only prepared to handle full-size block numbers, so we
4227  * have to adjust the record to reflect the change to a full-size block.
4228  * For example, suppose we have a block made up of fragments 8-15 and
4229  * want to free its last two fragments. We are given a request that says:
4230  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4231  * where frags are the number of fragments to free and oldfrags are the
4232  * number of fragments to keep. To block align it, we have to change it to
4233  * have a valid full-size blkno, so it becomes:
4234  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4235  */
4236 static void
4237 adjust_newfreework(freeblks, frag_offset)
4238         struct freeblks *freeblks;
4239         int frag_offset;
4240 {
4241         struct jfreeblk *jfreeblk;
4242
4243         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4244             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4245             ("adjust_newfreework: Missing freeblks dependency"));
4246
4247         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4248         jfreeblk->jf_blkno -= frag_offset;
4249         jfreeblk->jf_frags += frag_offset;
4250 }
4251
4252 /*
4253  * Allocate a new jtrunc to track a partial truncation.
4254  */
4255 static struct jtrunc *
4256 newjtrunc(freeblks, size, extsize)
4257         struct freeblks *freeblks;
4258         off_t size;
4259         int extsize;
4260 {
4261         struct jtrunc *jtrunc;
4262
4263         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4264         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4265             freeblks->fb_list.wk_mp);
4266         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4267         jtrunc->jt_dep.jb_freeblks = freeblks;
4268         jtrunc->jt_ino = freeblks->fb_inum;
4269         jtrunc->jt_size = size;
4270         jtrunc->jt_extsize = extsize;
4271         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4272
4273         return (jtrunc);
4274 }
4275
4276 /*
4277  * If we're canceling a new bitmap we have to search for another ref
4278  * to move into the bmsafemap dep.  This might be better expressed
4279  * with another structure.
4280  */
4281 static void
4282 move_newblock_dep(jaddref, inodedep)
4283         struct jaddref *jaddref;
4284         struct inodedep *inodedep;
4285 {
4286         struct inoref *inoref;
4287         struct jaddref *jaddrefn;
4288
4289         jaddrefn = NULL;
4290         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4291             inoref = TAILQ_NEXT(inoref, if_deps)) {
4292                 if ((jaddref->ja_state & NEWBLOCK) &&
4293                     inoref->if_list.wk_type == D_JADDREF) {
4294                         jaddrefn = (struct jaddref *)inoref;
4295                         break;
4296                 }
4297         }
4298         if (jaddrefn == NULL)
4299                 return;
4300         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4301         jaddrefn->ja_state |= jaddref->ja_state &
4302             (ATTACHED | UNDONE | NEWBLOCK);
4303         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4304         jaddref->ja_state |= ATTACHED;
4305         LIST_REMOVE(jaddref, ja_bmdeps);
4306         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4307             ja_bmdeps);
4308 }
4309
4310 /*
4311  * Cancel a jaddref either before it has been written or while it is being
4312  * written.  This happens when a link is removed before the add reaches
4313  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4314  * and inode to prevent the link count or bitmap from reaching the disk
4315  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4316  * required.
4317  *
4318  * Returns 1 if the canceled addref requires journaling of the remove and
4319  * 0 otherwise.
4320  */
4321 static int
4322 cancel_jaddref(jaddref, inodedep, wkhd)
4323         struct jaddref *jaddref;
4324         struct inodedep *inodedep;
4325         struct workhead *wkhd;
4326 {
4327         struct inoref *inoref;
4328         struct jsegdep *jsegdep;
4329         int needsj;
4330
4331         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4332             ("cancel_jaddref: Canceling complete jaddref"));
4333         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4334                 needsj = 1;
4335         else
4336                 needsj = 0;
4337         if (inodedep == NULL)
4338                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4339                     0, &inodedep) == 0)
4340                         panic("cancel_jaddref: Lost inodedep");
4341         /*
4342          * We must adjust the nlink of any reference operation that follows
4343          * us so that it is consistent with the in-memory reference.  This
4344          * ensures that inode nlink rollbacks always have the correct link.
4345          */
4346         if (needsj == 0) {
4347                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4348                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4349                         if (inoref->if_state & GOINGAWAY)
4350                                 break;
4351                         inoref->if_nlink--;
4352                 }
4353         }
4354         jsegdep = inoref_jseg(&jaddref->ja_ref);
4355         if (jaddref->ja_state & NEWBLOCK)
4356                 move_newblock_dep(jaddref, inodedep);
4357         wake_worklist(&jaddref->ja_list);
4358         jaddref->ja_mkdir = NULL;
4359         if (jaddref->ja_state & INPROGRESS) {
4360                 jaddref->ja_state &= ~INPROGRESS;
4361                 WORKLIST_REMOVE(&jaddref->ja_list);
4362                 jwork_insert(wkhd, jsegdep);
4363         } else {
4364                 free_jsegdep(jsegdep);
4365                 if (jaddref->ja_state & DEPCOMPLETE)
4366                         remove_from_journal(&jaddref->ja_list);
4367         }
4368         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4369         /*
4370          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4371          * can arrange for them to be freed with the bitmap.  Otherwise we
4372          * no longer need this addref attached to the inoreflst and it
4373          * will incorrectly adjust nlink if we leave it.
4374          */
4375         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4376                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4377                     if_deps);
4378                 jaddref->ja_state |= COMPLETE;
4379                 free_jaddref(jaddref);
4380                 return (needsj);
4381         }
4382         /*
4383          * Leave the head of the list for jsegdeps for fast merging.
4384          */
4385         if (LIST_FIRST(wkhd) != NULL) {
4386                 jaddref->ja_state |= ONWORKLIST;
4387                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4388         } else
4389                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4390
4391         return (needsj);
4392 }
4393
4394 /* 
4395  * Attempt to free a jaddref structure when some work completes.  This
4396  * should only succeed once the entry is written and all dependencies have
4397  * been notified.
4398  */
4399 static void
4400 free_jaddref(jaddref)
4401         struct jaddref *jaddref;
4402 {
4403
4404         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4405                 return;
4406         if (jaddref->ja_ref.if_jsegdep)
4407                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4408                     jaddref, jaddref->ja_state);
4409         if (jaddref->ja_state & NEWBLOCK)
4410                 LIST_REMOVE(jaddref, ja_bmdeps);
4411         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4412                 panic("free_jaddref: Bad state %p(0x%X)",
4413                     jaddref, jaddref->ja_state);
4414         if (jaddref->ja_mkdir != NULL)
4415                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4416         WORKITEM_FREE(jaddref, D_JADDREF);
4417 }
4418
4419 /*
4420  * Free a jremref structure once it has been written or discarded.
4421  */
4422 static void
4423 free_jremref(jremref)
4424         struct jremref *jremref;
4425 {
4426
4427         if (jremref->jr_ref.if_jsegdep)
4428                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4429         if (jremref->jr_state & INPROGRESS)
4430                 panic("free_jremref: IO still pending");
4431         WORKITEM_FREE(jremref, D_JREMREF);
4432 }
4433
4434 /*
4435  * Free a jnewblk structure.
4436  */
4437 static void
4438 free_jnewblk(jnewblk)
4439         struct jnewblk *jnewblk;
4440 {
4441
4442         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4443                 return;
4444         LIST_REMOVE(jnewblk, jn_deps);
4445         if (jnewblk->jn_dep != NULL)
4446                 panic("free_jnewblk: Dependency still attached.");
4447         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4448 }
4449
4450 /*
4451  * Cancel a jnewblk which has been been made redundant by frag extension.
4452  */
4453 static void
4454 cancel_jnewblk(jnewblk, wkhd)
4455         struct jnewblk *jnewblk;
4456         struct workhead *wkhd;
4457 {
4458         struct jsegdep *jsegdep;
4459
4460         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4461         jsegdep = jnewblk->jn_jsegdep;
4462         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4463                 panic("cancel_jnewblk: Invalid state");
4464         jnewblk->jn_jsegdep  = NULL;
4465         jnewblk->jn_dep = NULL;
4466         jnewblk->jn_state |= GOINGAWAY;
4467         if (jnewblk->jn_state & INPROGRESS) {
4468                 jnewblk->jn_state &= ~INPROGRESS;
4469                 WORKLIST_REMOVE(&jnewblk->jn_list);
4470                 jwork_insert(wkhd, jsegdep);
4471         } else {
4472                 free_jsegdep(jsegdep);
4473                 remove_from_journal(&jnewblk->jn_list);
4474         }
4475         wake_worklist(&jnewblk->jn_list);
4476         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4477 }
4478
4479 static void
4480 free_jblkdep(jblkdep)
4481         struct jblkdep *jblkdep;
4482 {
4483
4484         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4485                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4486         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4487                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4488         else
4489                 panic("free_jblkdep: Unexpected type %s",
4490                     TYPENAME(jblkdep->jb_list.wk_type));
4491 }
4492
4493 /*
4494  * Free a single jseg once it is no longer referenced in memory or on
4495  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4496  * to disappear.
4497  */
4498 static void
4499 free_jseg(jseg, jblocks)
4500         struct jseg *jseg;
4501         struct jblocks *jblocks;
4502 {
4503         struct freework *freework;
4504
4505         /*
4506          * Free freework structures that were lingering to indicate freed
4507          * indirect blocks that forced journal write ordering on reallocate.
4508          */
4509         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4510                 indirblk_remove(freework);
4511         if (jblocks->jb_oldestseg == jseg)
4512                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4513         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4514         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4515         KASSERT(LIST_EMPTY(&jseg->js_entries),
4516             ("free_jseg: Freed jseg has valid entries."));
4517         WORKITEM_FREE(jseg, D_JSEG);
4518 }
4519
4520 /*
4521  * Free all jsegs that meet the criteria for being reclaimed and update
4522  * oldestseg.
4523  */
4524 static void
4525 free_jsegs(jblocks)
4526         struct jblocks *jblocks;
4527 {
4528         struct jseg *jseg;
4529
4530         /*
4531          * Free only those jsegs which have none allocated before them to
4532          * preserve the journal space ordering.
4533          */
4534         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4535                 /*
4536                  * Only reclaim space when nothing depends on this journal
4537                  * set and another set has written that it is no longer
4538                  * valid.
4539                  */
4540                 if (jseg->js_refs != 0) {
4541                         jblocks->jb_oldestseg = jseg;
4542                         return;
4543                 }
4544                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4545                         break;
4546                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4547                         break;
4548                 /*
4549                  * We can free jsegs that didn't write entries when
4550                  * oldestwrseq == js_seq.
4551                  */
4552                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4553                     jseg->js_cnt != 0)
4554                         break;
4555                 free_jseg(jseg, jblocks);
4556         }
4557         /*
4558          * If we exited the loop above we still must discover the
4559          * oldest valid segment.
4560          */
4561         if (jseg)
4562                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4563                      jseg = TAILQ_NEXT(jseg, js_next))
4564                         if (jseg->js_refs != 0)
4565                                 break;
4566         jblocks->jb_oldestseg = jseg;
4567         /*
4568          * The journal has no valid records but some jsegs may still be
4569          * waiting on oldestwrseq to advance.  We force a small record
4570          * out to permit these lingering records to be reclaimed.
4571          */
4572         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4573                 jblocks->jb_needseg = 1;
4574 }
4575
4576 /*
4577  * Release one reference to a jseg and free it if the count reaches 0.  This
4578  * should eventually reclaim journal space as well.
4579  */
4580 static void
4581 rele_jseg(jseg)
4582         struct jseg *jseg;
4583 {
4584
4585         KASSERT(jseg->js_refs > 0,
4586             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4587         if (--jseg->js_refs != 0)
4588                 return;
4589         free_jsegs(jseg->js_jblocks);
4590 }
4591
4592 /*
4593  * Release a jsegdep and decrement the jseg count.
4594  */
4595 static void
4596 free_jsegdep(jsegdep)
4597         struct jsegdep *jsegdep;
4598 {
4599
4600         if (jsegdep->jd_seg)
4601                 rele_jseg(jsegdep->jd_seg);
4602         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4603 }
4604
4605 /*
4606  * Wait for a journal item to make it to disk.  Initiate journal processing
4607  * if required.
4608  */
4609 static int
4610 jwait(wk, waitfor)
4611         struct worklist *wk;
4612         int waitfor;
4613 {
4614
4615         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4616         /*
4617          * Blocking journal waits cause slow synchronous behavior.  Record
4618          * stats on the frequency of these blocking operations.
4619          */
4620         if (waitfor == MNT_WAIT) {
4621                 stat_journal_wait++;
4622                 switch (wk->wk_type) {
4623                 case D_JREMREF:
4624                 case D_JMVREF:
4625                         stat_jwait_filepage++;
4626                         break;
4627                 case D_JTRUNC:
4628                 case D_JFREEBLK:
4629                         stat_jwait_freeblks++;
4630                         break;
4631                 case D_JNEWBLK:
4632                         stat_jwait_newblk++;
4633                         break;
4634                 case D_JADDREF:
4635                         stat_jwait_inode++;
4636                         break;
4637                 default:
4638                         break;
4639                 }
4640         }
4641         /*
4642          * If IO has not started we process the journal.  We can't mark the
4643          * worklist item as IOWAITING because we drop the lock while
4644          * processing the journal and the worklist entry may be freed after
4645          * this point.  The caller may call back in and re-issue the request.
4646          */
4647         if ((wk->wk_state & INPROGRESS) == 0) {
4648                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4649                 if (waitfor != MNT_WAIT)
4650                         return (EBUSY);
4651                 return (0);
4652         }
4653         if (waitfor != MNT_WAIT)
4654                 return (EBUSY);
4655         wait_worklist(wk, "jwait");
4656         return (0);
4657 }
4658
4659 /*
4660  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4661  * appropriate.  This is a convenience function to reduce duplicate code
4662  * for the setup and revert functions below.
4663  */
4664 static struct inodedep *
4665 inodedep_lookup_ip(ip)
4666         struct inode *ip;
4667 {
4668         struct inodedep *inodedep;
4669
4670         KASSERT(ip->i_nlink >= ip->i_effnlink,
4671             ("inodedep_lookup_ip: bad delta"));
4672         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4673             &inodedep);
4674         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4675         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4676
4677         return (inodedep);
4678 }
4679
4680 /*
4681  * Called prior to creating a new inode and linking it to a directory.  The
4682  * jaddref structure must already be allocated by softdep_setup_inomapdep
4683  * and it is discovered here so we can initialize the mode and update
4684  * nlinkdelta.
4685  */
4686 void
4687 softdep_setup_create(dp, ip)
4688         struct inode *dp;
4689         struct inode *ip;
4690 {
4691         struct inodedep *inodedep;
4692         struct jaddref *jaddref;
4693         struct vnode *dvp;
4694
4695         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4696             ("softdep_setup_create called on non-softdep filesystem"));
4697         KASSERT(ip->i_nlink == 1,
4698             ("softdep_setup_create: Invalid link count."));
4699         dvp = ITOV(dp);
4700         ACQUIRE_LOCK(ITOUMP(dp));
4701         inodedep = inodedep_lookup_ip(ip);
4702         if (DOINGSUJ(dvp)) {
4703                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4704                     inoreflst);
4705                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4706                     ("softdep_setup_create: No addref structure present."));
4707         }
4708         softdep_prelink(dvp, NULL);
4709         FREE_LOCK(ITOUMP(dp));
4710 }
4711
4712 /*
4713  * Create a jaddref structure to track the addition of a DOTDOT link when
4714  * we are reparenting an inode as part of a rename.  This jaddref will be
4715  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4716  * non-journaling softdep.
4717  */
4718 void
4719 softdep_setup_dotdot_link(dp, ip)
4720         struct inode *dp;
4721         struct inode *ip;
4722 {
4723         struct inodedep *inodedep;
4724         struct jaddref *jaddref;
4725         struct vnode *dvp;
4726
4727         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4728             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4729         dvp = ITOV(dp);
4730         jaddref = NULL;
4731         /*
4732          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4733          * is used as a normal link would be.
4734          */
4735         if (DOINGSUJ(dvp))
4736                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4737                     dp->i_effnlink - 1, dp->i_mode);
4738         ACQUIRE_LOCK(ITOUMP(dp));
4739         inodedep = inodedep_lookup_ip(dp);
4740         if (jaddref)
4741                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4742                     if_deps);
4743         softdep_prelink(dvp, ITOV(ip));
4744         FREE_LOCK(ITOUMP(dp));
4745 }
4746
4747 /*
4748  * Create a jaddref structure to track a new link to an inode.  The directory
4749  * offset is not known until softdep_setup_directory_add or
4750  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4751  * softdep.
4752  */
4753 void
4754 softdep_setup_link(dp, ip)
4755         struct inode *dp;
4756         struct inode *ip;
4757 {
4758         struct inodedep *inodedep;
4759         struct jaddref *jaddref;
4760         struct vnode *dvp;
4761
4762         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4763             ("softdep_setup_link called on non-softdep filesystem"));
4764         dvp = ITOV(dp);
4765         jaddref = NULL;
4766         if (DOINGSUJ(dvp))
4767                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4768                     ip->i_mode);
4769         ACQUIRE_LOCK(ITOUMP(dp));
4770         inodedep = inodedep_lookup_ip(ip);
4771         if (jaddref)
4772                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4773                     if_deps);
4774         softdep_prelink(dvp, ITOV(ip));
4775         FREE_LOCK(ITOUMP(dp));
4776 }
4777
4778 /*
4779  * Called to create the jaddref structures to track . and .. references as
4780  * well as lookup and further initialize the incomplete jaddref created
4781  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4782  * nlinkdelta for non-journaling softdep.
4783  */
4784 void
4785 softdep_setup_mkdir(dp, ip)
4786         struct inode *dp;
4787         struct inode *ip;
4788 {
4789         struct inodedep *inodedep;
4790         struct jaddref *dotdotaddref;
4791         struct jaddref *dotaddref;
4792         struct jaddref *jaddref;
4793         struct vnode *dvp;
4794
4795         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4796             ("softdep_setup_mkdir called on non-softdep filesystem"));
4797         dvp = ITOV(dp);
4798         dotaddref = dotdotaddref = NULL;
4799         if (DOINGSUJ(dvp)) {
4800                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4801                     ip->i_mode);
4802                 dotaddref->ja_state |= MKDIR_BODY;
4803                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4804                     dp->i_effnlink - 1, dp->i_mode);
4805                 dotdotaddref->ja_state |= MKDIR_PARENT;
4806         }
4807         ACQUIRE_LOCK(ITOUMP(dp));
4808         inodedep = inodedep_lookup_ip(ip);
4809         if (DOINGSUJ(dvp)) {
4810                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4811                     inoreflst);
4812                 KASSERT(jaddref != NULL,
4813                     ("softdep_setup_mkdir: No addref structure present."));
4814                 KASSERT(jaddref->ja_parent == dp->i_number, 
4815                     ("softdep_setup_mkdir: bad parent %ju",
4816                     (uintmax_t)jaddref->ja_parent));
4817                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4818                     if_deps);
4819         }
4820         inodedep = inodedep_lookup_ip(dp);
4821         if (DOINGSUJ(dvp))
4822                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4823                     &dotdotaddref->ja_ref, if_deps);
4824         softdep_prelink(ITOV(dp), NULL);
4825         FREE_LOCK(ITOUMP(dp));
4826 }
4827
4828 /*
4829  * Called to track nlinkdelta of the inode and parent directories prior to
4830  * unlinking a directory.
4831  */
4832 void
4833 softdep_setup_rmdir(dp, ip)
4834         struct inode *dp;
4835         struct inode *ip;
4836 {
4837         struct vnode *dvp;
4838
4839         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4840             ("softdep_setup_rmdir called on non-softdep filesystem"));
4841         dvp = ITOV(dp);
4842         ACQUIRE_LOCK(ITOUMP(dp));
4843         (void) inodedep_lookup_ip(ip);
4844         (void) inodedep_lookup_ip(dp);
4845         softdep_prelink(dvp, ITOV(ip));
4846         FREE_LOCK(ITOUMP(dp));
4847 }
4848
4849 /*
4850  * Called to track nlinkdelta of the inode and parent directories prior to
4851  * unlink.
4852  */
4853 void
4854 softdep_setup_unlink(dp, ip)
4855         struct inode *dp;
4856         struct inode *ip;
4857 {
4858         struct vnode *dvp;
4859
4860         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4861             ("softdep_setup_unlink called on non-softdep filesystem"));
4862         dvp = ITOV(dp);
4863         ACQUIRE_LOCK(ITOUMP(dp));
4864         (void) inodedep_lookup_ip(ip);
4865         (void) inodedep_lookup_ip(dp);
4866         softdep_prelink(dvp, ITOV(ip));
4867         FREE_LOCK(ITOUMP(dp));
4868 }
4869
4870 /*
4871  * Called to release the journal structures created by a failed non-directory
4872  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4873  */
4874 void
4875 softdep_revert_create(dp, ip)
4876         struct inode *dp;
4877         struct inode *ip;
4878 {
4879         struct inodedep *inodedep;
4880         struct jaddref *jaddref;
4881         struct vnode *dvp;
4882
4883         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4884             ("softdep_revert_create called on non-softdep filesystem"));
4885         dvp = ITOV(dp);
4886         ACQUIRE_LOCK(ITOUMP(dp));
4887         inodedep = inodedep_lookup_ip(ip);
4888         if (DOINGSUJ(dvp)) {
4889                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4890                     inoreflst);
4891                 KASSERT(jaddref->ja_parent == dp->i_number,
4892                     ("softdep_revert_create: addref parent mismatch"));
4893                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4894         }
4895         FREE_LOCK(ITOUMP(dp));
4896 }
4897
4898 /*
4899  * Called to release the journal structures created by a failed link
4900  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4901  */
4902 void
4903 softdep_revert_link(dp, ip)
4904         struct inode *dp;
4905         struct inode *ip;
4906 {
4907         struct inodedep *inodedep;
4908         struct jaddref *jaddref;
4909         struct vnode *dvp;
4910
4911         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4912             ("softdep_revert_link called on non-softdep filesystem"));
4913         dvp = ITOV(dp);
4914         ACQUIRE_LOCK(ITOUMP(dp));
4915         inodedep = inodedep_lookup_ip(ip);
4916         if (DOINGSUJ(dvp)) {
4917                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4918                     inoreflst);
4919                 KASSERT(jaddref->ja_parent == dp->i_number,
4920                     ("softdep_revert_link: addref parent mismatch"));
4921                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4922         }
4923         FREE_LOCK(ITOUMP(dp));
4924 }
4925
4926 /*
4927  * Called to release the journal structures created by a failed mkdir
4928  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4929  */
4930 void
4931 softdep_revert_mkdir(dp, ip)
4932         struct inode *dp;
4933         struct inode *ip;
4934 {
4935         struct inodedep *inodedep;
4936         struct jaddref *jaddref;
4937         struct jaddref *dotaddref;
4938         struct vnode *dvp;
4939
4940         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4941             ("softdep_revert_mkdir called on non-softdep filesystem"));
4942         dvp = ITOV(dp);
4943
4944         ACQUIRE_LOCK(ITOUMP(dp));
4945         inodedep = inodedep_lookup_ip(dp);
4946         if (DOINGSUJ(dvp)) {
4947                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4948                     inoreflst);
4949                 KASSERT(jaddref->ja_parent == ip->i_number,
4950                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4951                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4952         }
4953         inodedep = inodedep_lookup_ip(ip);
4954         if (DOINGSUJ(dvp)) {
4955                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4956                     inoreflst);
4957                 KASSERT(jaddref->ja_parent == dp->i_number,
4958                     ("softdep_revert_mkdir: addref parent mismatch"));
4959                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4960                     inoreflst, if_deps);
4961                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4962                 KASSERT(dotaddref->ja_parent == ip->i_number,
4963                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4964                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4965         }
4966         FREE_LOCK(ITOUMP(dp));
4967 }
4968
4969 /* 
4970  * Called to correct nlinkdelta after a failed rmdir.
4971  */
4972 void
4973 softdep_revert_rmdir(dp, ip)
4974         struct inode *dp;
4975         struct inode *ip;
4976 {
4977
4978         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4979             ("softdep_revert_rmdir called on non-softdep filesystem"));
4980         ACQUIRE_LOCK(ITOUMP(dp));
4981         (void) inodedep_lookup_ip(ip);
4982         (void) inodedep_lookup_ip(dp);
4983         FREE_LOCK(ITOUMP(dp));
4984 }
4985
4986 /*
4987  * Protecting the freemaps (or bitmaps).
4988  * 
4989  * To eliminate the need to execute fsck before mounting a filesystem
4990  * after a power failure, one must (conservatively) guarantee that the
4991  * on-disk copy of the bitmaps never indicate that a live inode or block is
4992  * free.  So, when a block or inode is allocated, the bitmap should be
4993  * updated (on disk) before any new pointers.  When a block or inode is
4994  * freed, the bitmap should not be updated until all pointers have been
4995  * reset.  The latter dependency is handled by the delayed de-allocation
4996  * approach described below for block and inode de-allocation.  The former
4997  * dependency is handled by calling the following procedure when a block or
4998  * inode is allocated. When an inode is allocated an "inodedep" is created
4999  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5000  * Each "inodedep" is also inserted into the hash indexing structure so
5001  * that any additional link additions can be made dependent on the inode
5002  * allocation.
5003  * 
5004  * The ufs filesystem maintains a number of free block counts (e.g., per
5005  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5006  * in addition to the bitmaps.  These counts are used to improve efficiency
5007  * during allocation and therefore must be consistent with the bitmaps.
5008  * There is no convenient way to guarantee post-crash consistency of these
5009  * counts with simple update ordering, for two main reasons: (1) The counts
5010  * and bitmaps for a single cylinder group block are not in the same disk
5011  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5012  * be written and the other not.  (2) Some of the counts are located in the
5013  * superblock rather than the cylinder group block. So, we focus our soft
5014  * updates implementation on protecting the bitmaps. When mounting a
5015  * filesystem, we recompute the auxiliary counts from the bitmaps.
5016  */
5017
5018 /*
5019  * Called just after updating the cylinder group block to allocate an inode.
5020  */
5021 void
5022 softdep_setup_inomapdep(bp, ip, newinum, mode)
5023         struct buf *bp;         /* buffer for cylgroup block with inode map */
5024         struct inode *ip;       /* inode related to allocation */
5025         ino_t newinum;          /* new inode number being allocated */
5026         int mode;
5027 {
5028         struct inodedep *inodedep;
5029         struct bmsafemap *bmsafemap;
5030         struct jaddref *jaddref;
5031         struct mount *mp;
5032         struct fs *fs;
5033
5034         mp = ITOVFS(ip);
5035         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5036             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5037         fs = VFSTOUFS(mp)->um_fs;
5038         jaddref = NULL;
5039
5040         /*
5041          * Allocate the journal reference add structure so that the bitmap
5042          * can be dependent on it.
5043          */
5044         if (MOUNTEDSUJ(mp)) {
5045                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5046                 jaddref->ja_state |= NEWBLOCK;
5047         }
5048
5049         /*
5050          * Create a dependency for the newly allocated inode.
5051          * Panic if it already exists as something is seriously wrong.
5052          * Otherwise add it to the dependency list for the buffer holding
5053          * the cylinder group map from which it was allocated.
5054          *
5055          * We have to preallocate a bmsafemap entry in case it is needed
5056          * in bmsafemap_lookup since once we allocate the inodedep, we
5057          * have to finish initializing it before we can FREE_LOCK().
5058          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5059          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5060          * creating the inodedep as it can be freed during the time
5061          * that we FREE_LOCK() while allocating the inodedep. We must
5062          * call workitem_alloc() before entering the locked section as
5063          * it also acquires the lock and we must avoid trying doing so
5064          * recursively.
5065          */
5066         bmsafemap = malloc(sizeof(struct bmsafemap),
5067             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5068         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5069         ACQUIRE_LOCK(ITOUMP(ip));
5070         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5071                 panic("softdep_setup_inomapdep: dependency %p for new"
5072                     "inode already exists", inodedep);
5073         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5074         if (jaddref) {
5075                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5076                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5077                     if_deps);
5078         } else {
5079                 inodedep->id_state |= ONDEPLIST;
5080                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5081         }
5082         inodedep->id_bmsafemap = bmsafemap;
5083         inodedep->id_state &= ~DEPCOMPLETE;
5084         FREE_LOCK(ITOUMP(ip));
5085 }
5086
5087 /*
5088  * Called just after updating the cylinder group block to
5089  * allocate block or fragment.
5090  */
5091 void
5092 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5093         struct buf *bp;         /* buffer for cylgroup block with block map */
5094         struct mount *mp;       /* filesystem doing allocation */
5095         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5096         int frags;              /* Number of fragments. */
5097         int oldfrags;           /* Previous number of fragments for extend. */
5098 {
5099         struct newblk *newblk;
5100         struct bmsafemap *bmsafemap;
5101         struct jnewblk *jnewblk;
5102         struct ufsmount *ump;
5103         struct fs *fs;
5104
5105         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5106             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5107         ump = VFSTOUFS(mp);
5108         fs = ump->um_fs;
5109         jnewblk = NULL;
5110         /*
5111          * Create a dependency for the newly allocated block.
5112          * Add it to the dependency list for the buffer holding
5113          * the cylinder group map from which it was allocated.
5114          */
5115         if (MOUNTEDSUJ(mp)) {
5116                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5117                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5118                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5119                 jnewblk->jn_state = ATTACHED;
5120                 jnewblk->jn_blkno = newblkno;
5121                 jnewblk->jn_frags = frags;
5122                 jnewblk->jn_oldfrags = oldfrags;
5123 #ifdef INVARIANTS
5124                 {
5125                         struct cg *cgp;
5126                         uint8_t *blksfree;
5127                         long bno;
5128                         int i;
5129         
5130                         cgp = (struct cg *)bp->b_data;
5131                         blksfree = cg_blksfree(cgp);
5132                         bno = dtogd(fs, jnewblk->jn_blkno);
5133                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5134                             i++) {
5135                                 if (isset(blksfree, bno + i))
5136                                         panic("softdep_setup_blkmapdep: "
5137                                             "free fragment %d from %d-%d "
5138                                             "state 0x%X dep %p", i,
5139                                             jnewblk->jn_oldfrags,
5140                                             jnewblk->jn_frags,
5141                                             jnewblk->jn_state,
5142                                             jnewblk->jn_dep);
5143                         }
5144                 }
5145 #endif
5146         }
5147
5148         CTR3(KTR_SUJ,
5149             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5150             newblkno, frags, oldfrags);
5151         ACQUIRE_LOCK(ump);
5152         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5153                 panic("softdep_setup_blkmapdep: found block");
5154         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5155             dtog(fs, newblkno), NULL);
5156         if (jnewblk) {
5157                 jnewblk->jn_dep = (struct worklist *)newblk;
5158                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5159         } else {
5160                 newblk->nb_state |= ONDEPLIST;
5161                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5162         }
5163         newblk->nb_bmsafemap = bmsafemap;
5164         newblk->nb_jnewblk = jnewblk;
5165         FREE_LOCK(ump);
5166 }
5167
5168 #define BMSAFEMAP_HASH(ump, cg) \
5169       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5170
5171 static int
5172 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5173         struct bmsafemap_hashhead *bmsafemaphd;
5174         int cg;
5175         struct bmsafemap **bmsafemapp;
5176 {
5177         struct bmsafemap *bmsafemap;
5178
5179         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5180                 if (bmsafemap->sm_cg == cg)
5181                         break;
5182         if (bmsafemap) {
5183                 *bmsafemapp = bmsafemap;
5184                 return (1);
5185         }
5186         *bmsafemapp = NULL;
5187
5188         return (0);
5189 }
5190
5191 /*
5192  * Find the bmsafemap associated with a cylinder group buffer.
5193  * If none exists, create one. The buffer must be locked when
5194  * this routine is called and this routine must be called with
5195  * the softdep lock held. To avoid giving up the lock while
5196  * allocating a new bmsafemap, a preallocated bmsafemap may be
5197  * provided. If it is provided but not needed, it is freed.
5198  */
5199 static struct bmsafemap *
5200 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5201         struct mount *mp;
5202         struct buf *bp;
5203         int cg;
5204         struct bmsafemap *newbmsafemap;
5205 {
5206         struct bmsafemap_hashhead *bmsafemaphd;
5207         struct bmsafemap *bmsafemap, *collision;
5208         struct worklist *wk;
5209         struct ufsmount *ump;
5210
5211         ump = VFSTOUFS(mp);
5212         LOCK_OWNED(ump);
5213         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5214         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5215                 if (wk->wk_type == D_BMSAFEMAP) {
5216                         if (newbmsafemap)
5217                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5218                         return (WK_BMSAFEMAP(wk));
5219                 }
5220         }
5221         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5222         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5223                 if (newbmsafemap)
5224                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5225                 return (bmsafemap);
5226         }
5227         if (newbmsafemap) {
5228                 bmsafemap = newbmsafemap;
5229         } else {
5230                 FREE_LOCK(ump);
5231                 bmsafemap = malloc(sizeof(struct bmsafemap),
5232                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5233                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5234                 ACQUIRE_LOCK(ump);
5235         }
5236         bmsafemap->sm_buf = bp;
5237         LIST_INIT(&bmsafemap->sm_inodedephd);
5238         LIST_INIT(&bmsafemap->sm_inodedepwr);
5239         LIST_INIT(&bmsafemap->sm_newblkhd);
5240         LIST_INIT(&bmsafemap->sm_newblkwr);
5241         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5242         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5243         LIST_INIT(&bmsafemap->sm_freehd);
5244         LIST_INIT(&bmsafemap->sm_freewr);
5245         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5246                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5247                 return (collision);
5248         }
5249         bmsafemap->sm_cg = cg;
5250         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5251         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5252         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5253         return (bmsafemap);
5254 }
5255
5256 /*
5257  * Direct block allocation dependencies.
5258  * 
5259  * When a new block is allocated, the corresponding disk locations must be
5260  * initialized (with zeros or new data) before the on-disk inode points to
5261  * them.  Also, the freemap from which the block was allocated must be
5262  * updated (on disk) before the inode's pointer. These two dependencies are
5263  * independent of each other and are needed for all file blocks and indirect
5264  * blocks that are pointed to directly by the inode.  Just before the
5265  * "in-core" version of the inode is updated with a newly allocated block
5266  * number, a procedure (below) is called to setup allocation dependency
5267  * structures.  These structures are removed when the corresponding
5268  * dependencies are satisfied or when the block allocation becomes obsolete
5269  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5270  * fragment that gets upgraded).  All of these cases are handled in
5271  * procedures described later.
5272  * 
5273  * When a file extension causes a fragment to be upgraded, either to a larger
5274  * fragment or to a full block, the on-disk location may change (if the
5275  * previous fragment could not simply be extended). In this case, the old
5276  * fragment must be de-allocated, but not until after the inode's pointer has
5277  * been updated. In most cases, this is handled by later procedures, which
5278  * will construct a "freefrag" structure to be added to the workitem queue
5279  * when the inode update is complete (or obsolete).  The main exception to
5280  * this is when an allocation occurs while a pending allocation dependency
5281  * (for the same block pointer) remains.  This case is handled in the main
5282  * allocation dependency setup procedure by immediately freeing the
5283  * unreferenced fragments.
5284  */ 
5285 void 
5286 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5287         struct inode *ip;       /* inode to which block is being added */
5288         ufs_lbn_t off;          /* block pointer within inode */
5289         ufs2_daddr_t newblkno;  /* disk block number being added */
5290         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5291         long newsize;           /* size of new block */
5292         long oldsize;           /* size of new block */
5293         struct buf *bp;         /* bp for allocated block */
5294 {
5295         struct allocdirect *adp, *oldadp;
5296         struct allocdirectlst *adphead;
5297         struct freefrag *freefrag;
5298         struct inodedep *inodedep;
5299         struct pagedep *pagedep;
5300         struct jnewblk *jnewblk;
5301         struct newblk *newblk;
5302         struct mount *mp;
5303         ufs_lbn_t lbn;
5304
5305         lbn = bp->b_lblkno;
5306         mp = ITOVFS(ip);
5307         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5308             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5309         if (oldblkno && oldblkno != newblkno)
5310                 /*
5311                  * The usual case is that a smaller fragment that
5312                  * was just allocated has been replaced with a bigger
5313                  * fragment or a full-size block. If it is marked as
5314                  * B_DELWRI, the current contents have not been written
5315                  * to disk. It is possible that the block was written
5316                  * earlier, but very uncommon. If the block has never
5317                  * been written, there is no need to send a BIO_DELETE
5318                  * for it when it is freed. The gain from avoiding the
5319                  * TRIMs for the common case of unwritten blocks far
5320                  * exceeds the cost of the write amplification for the
5321                  * uncommon case of failing to send a TRIM for a block
5322                  * that had been written.
5323                  */
5324                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5325                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5326         else
5327                 freefrag = NULL;
5328
5329         CTR6(KTR_SUJ,
5330             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5331             "off %jd newsize %ld oldsize %d",
5332             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5333         ACQUIRE_LOCK(ITOUMP(ip));
5334         if (off >= UFS_NDADDR) {
5335                 if (lbn > 0)
5336                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5337                             lbn, off);
5338                 /* allocating an indirect block */
5339                 if (oldblkno != 0)
5340                         panic("softdep_setup_allocdirect: non-zero indir");
5341         } else {
5342                 if (off != lbn)
5343                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5344                             lbn, off);
5345                 /*
5346                  * Allocating a direct block.
5347                  *
5348                  * If we are allocating a directory block, then we must
5349                  * allocate an associated pagedep to track additions and
5350                  * deletions.
5351                  */
5352                 if ((ip->i_mode & IFMT) == IFDIR)
5353                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5354                             &pagedep);
5355         }
5356         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5357                 panic("softdep_setup_allocdirect: lost block");
5358         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5359             ("softdep_setup_allocdirect: newblk already initialized"));
5360         /*
5361          * Convert the newblk to an allocdirect.
5362          */
5363         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5364         adp = (struct allocdirect *)newblk;
5365         newblk->nb_freefrag = freefrag;
5366         adp->ad_offset = off;
5367         adp->ad_oldblkno = oldblkno;
5368         adp->ad_newsize = newsize;
5369         adp->ad_oldsize = oldsize;
5370
5371         /*
5372          * Finish initializing the journal.
5373          */
5374         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5375                 jnewblk->jn_ino = ip->i_number;
5376                 jnewblk->jn_lbn = lbn;
5377                 add_to_journal(&jnewblk->jn_list);
5378         }
5379         if (freefrag && freefrag->ff_jdep != NULL &&
5380             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5381                 add_to_journal(freefrag->ff_jdep);
5382         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5383         adp->ad_inodedep = inodedep;
5384
5385         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5386         /*
5387          * The list of allocdirects must be kept in sorted and ascending
5388          * order so that the rollback routines can quickly determine the
5389          * first uncommitted block (the size of the file stored on disk
5390          * ends at the end of the lowest committed fragment, or if there
5391          * are no fragments, at the end of the highest committed block).
5392          * Since files generally grow, the typical case is that the new
5393          * block is to be added at the end of the list. We speed this
5394          * special case by checking against the last allocdirect in the
5395          * list before laboriously traversing the list looking for the
5396          * insertion point.
5397          */
5398         adphead = &inodedep->id_newinoupdt;
5399         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5400         if (oldadp == NULL || oldadp->ad_offset <= off) {
5401                 /* insert at end of list */
5402                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5403                 if (oldadp != NULL && oldadp->ad_offset == off)
5404                         allocdirect_merge(adphead, adp, oldadp);
5405                 FREE_LOCK(ITOUMP(ip));
5406                 return;
5407         }
5408         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5409                 if (oldadp->ad_offset >= off)
5410                         break;
5411         }
5412         if (oldadp == NULL)
5413                 panic("softdep_setup_allocdirect: lost entry");
5414         /* insert in middle of list */
5415         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5416         if (oldadp->ad_offset == off)
5417                 allocdirect_merge(adphead, adp, oldadp);
5418
5419         FREE_LOCK(ITOUMP(ip));
5420 }
5421
5422 /*
5423  * Merge a newer and older journal record to be stored either in a
5424  * newblock or freefrag.  This handles aggregating journal records for
5425  * fragment allocation into a second record as well as replacing a
5426  * journal free with an aborted journal allocation.  A segment for the
5427  * oldest record will be placed on wkhd if it has been written.  If not
5428  * the segment for the newer record will suffice.
5429  */
5430 static struct worklist *
5431 jnewblk_merge(new, old, wkhd)
5432         struct worklist *new;
5433         struct worklist *old;
5434         struct workhead *wkhd;
5435 {
5436         struct jnewblk *njnewblk;
5437         struct jnewblk *jnewblk;
5438
5439         /* Handle NULLs to simplify callers. */
5440         if (new == NULL)
5441                 return (old);
5442         if (old == NULL)
5443                 return (new);
5444         /* Replace a jfreefrag with a jnewblk. */
5445         if (new->wk_type == D_JFREEFRAG) {
5446                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5447                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5448                             old, new);
5449                 cancel_jfreefrag(WK_JFREEFRAG(new));
5450                 return (old);
5451         }
5452         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5453                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5454                     old->wk_type, new->wk_type);
5455         /*
5456          * Handle merging of two jnewblk records that describe
5457          * different sets of fragments in the same block.
5458          */
5459         jnewblk = WK_JNEWBLK(old);
5460         njnewblk = WK_JNEWBLK(new);
5461         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5462                 panic("jnewblk_merge: Merging disparate blocks.");
5463         /*
5464          * The record may be rolled back in the cg.
5465          */
5466         if (jnewblk->jn_state & UNDONE) {
5467                 jnewblk->jn_state &= ~UNDONE;
5468                 njnewblk->jn_state |= UNDONE;
5469                 njnewblk->jn_state &= ~ATTACHED;
5470         }
5471         /*
5472          * We modify the newer addref and free the older so that if neither
5473          * has been written the most up-to-date copy will be on disk.  If
5474          * both have been written but rolled back we only temporarily need
5475          * one of them to fix the bits when the cg write completes.
5476          */
5477         jnewblk->jn_state |= ATTACHED | COMPLETE;
5478         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5479         cancel_jnewblk(jnewblk, wkhd);
5480         WORKLIST_REMOVE(&jnewblk->jn_list);
5481         free_jnewblk(jnewblk);
5482         return (new);
5483 }
5484
5485 /*
5486  * Replace an old allocdirect dependency with a newer one.
5487  */
5488 static void
5489 allocdirect_merge(adphead, newadp, oldadp)
5490         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5491         struct allocdirect *newadp;     /* allocdirect being added */
5492         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5493 {
5494         struct worklist *wk;
5495         struct freefrag *freefrag;
5496
5497         freefrag = NULL;
5498         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5499         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5500             newadp->ad_oldsize != oldadp->ad_newsize ||
5501             newadp->ad_offset >= UFS_NDADDR)
5502                 panic("%s %jd != new %jd || old size %ld != new %ld",
5503                     "allocdirect_merge: old blkno",
5504                     (intmax_t)newadp->ad_oldblkno,
5505                     (intmax_t)oldadp->ad_newblkno,
5506                     newadp->ad_oldsize, oldadp->ad_newsize);
5507         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5508         newadp->ad_oldsize = oldadp->ad_oldsize;
5509         /*
5510          * If the old dependency had a fragment to free or had never
5511          * previously had a block allocated, then the new dependency
5512          * can immediately post its freefrag and adopt the old freefrag.
5513          * This action is done by swapping the freefrag dependencies.
5514          * The new dependency gains the old one's freefrag, and the
5515          * old one gets the new one and then immediately puts it on
5516          * the worklist when it is freed by free_newblk. It is
5517          * not possible to do this swap when the old dependency had a
5518          * non-zero size but no previous fragment to free. This condition
5519          * arises when the new block is an extension of the old block.
5520          * Here, the first part of the fragment allocated to the new
5521          * dependency is part of the block currently claimed on disk by
5522          * the old dependency, so cannot legitimately be freed until the
5523          * conditions for the new dependency are fulfilled.
5524          */
5525         freefrag = newadp->ad_freefrag;
5526         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5527                 newadp->ad_freefrag = oldadp->ad_freefrag;
5528                 oldadp->ad_freefrag = freefrag;
5529         }
5530         /*
5531          * If we are tracking a new directory-block allocation,
5532          * move it from the old allocdirect to the new allocdirect.
5533          */
5534         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5535                 WORKLIST_REMOVE(wk);
5536                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5537                         panic("allocdirect_merge: extra newdirblk");
5538                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5539         }
5540         TAILQ_REMOVE(adphead, oldadp, ad_next);
5541         /*
5542          * We need to move any journal dependencies over to the freefrag
5543          * that releases this block if it exists.  Otherwise we are
5544          * extending an existing block and we'll wait until that is
5545          * complete to release the journal space and extend the
5546          * new journal to cover this old space as well.
5547          */
5548         if (freefrag == NULL) {
5549                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5550                         panic("allocdirect_merge: %jd != %jd",
5551                             oldadp->ad_newblkno, newadp->ad_newblkno);
5552                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5553                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5554                     &oldadp->ad_block.nb_jnewblk->jn_list,
5555                     &newadp->ad_block.nb_jwork);
5556                 oldadp->ad_block.nb_jnewblk = NULL;
5557                 cancel_newblk(&oldadp->ad_block, NULL,
5558                     &newadp->ad_block.nb_jwork);
5559         } else {
5560                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5561                     &freefrag->ff_list, &freefrag->ff_jwork);
5562                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5563                     &freefrag->ff_jwork);
5564         }
5565         free_newblk(&oldadp->ad_block);
5566 }
5567
5568 /*
5569  * Allocate a jfreefrag structure to journal a single block free.
5570  */
5571 static struct jfreefrag *
5572 newjfreefrag(freefrag, ip, blkno, size, lbn)
5573         struct freefrag *freefrag;
5574         struct inode *ip;
5575         ufs2_daddr_t blkno;
5576         long size;
5577         ufs_lbn_t lbn;
5578 {
5579         struct jfreefrag *jfreefrag;
5580         struct fs *fs;
5581
5582         fs = ITOFS(ip);
5583         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5584             M_SOFTDEP_FLAGS);
5585         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5586         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5587         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5588         jfreefrag->fr_ino = ip->i_number;
5589         jfreefrag->fr_lbn = lbn;
5590         jfreefrag->fr_blkno = blkno;
5591         jfreefrag->fr_frags = numfrags(fs, size);
5592         jfreefrag->fr_freefrag = freefrag;
5593
5594         return (jfreefrag);
5595 }
5596
5597 /*
5598  * Allocate a new freefrag structure.
5599  */
5600 static struct freefrag *
5601 newfreefrag(ip, blkno, size, lbn, key)
5602         struct inode *ip;
5603         ufs2_daddr_t blkno;
5604         long size;
5605         ufs_lbn_t lbn;
5606         u_long key;
5607 {
5608         struct freefrag *freefrag;
5609         struct ufsmount *ump;
5610         struct fs *fs;
5611
5612         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5613             ip->i_number, blkno, size, lbn);
5614         ump = ITOUMP(ip);
5615         fs = ump->um_fs;
5616         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5617                 panic("newfreefrag: frag size");
5618         freefrag = malloc(sizeof(struct freefrag),
5619             M_FREEFRAG, M_SOFTDEP_FLAGS);
5620         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5621         freefrag->ff_state = ATTACHED;
5622         LIST_INIT(&freefrag->ff_jwork);
5623         freefrag->ff_inum = ip->i_number;
5624         freefrag->ff_vtype = ITOV(ip)->v_type;
5625         freefrag->ff_blkno = blkno;
5626         freefrag->ff_fragsize = size;
5627         freefrag->ff_key = key;
5628
5629         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5630                 freefrag->ff_jdep = (struct worklist *)
5631                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5632         } else {
5633                 freefrag->ff_state |= DEPCOMPLETE;
5634                 freefrag->ff_jdep = NULL;
5635         }
5636
5637         return (freefrag);
5638 }
5639
5640 /*
5641  * This workitem de-allocates fragments that were replaced during
5642  * file block allocation.
5643  */
5644 static void 
5645 handle_workitem_freefrag(freefrag)
5646         struct freefrag *freefrag;
5647 {
5648         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5649         struct workhead wkhd;
5650
5651         CTR3(KTR_SUJ,
5652             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5653             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5654         /*
5655          * It would be illegal to add new completion items to the
5656          * freefrag after it was schedule to be done so it must be
5657          * safe to modify the list head here.
5658          */
5659         LIST_INIT(&wkhd);
5660         ACQUIRE_LOCK(ump);
5661         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5662         /*
5663          * If the journal has not been written we must cancel it here.
5664          */
5665         if (freefrag->ff_jdep) {
5666                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5667                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5668                             freefrag->ff_jdep->wk_type);
5669                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5670         }
5671         FREE_LOCK(ump);
5672         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5673            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5674            &wkhd, freefrag->ff_key);
5675         ACQUIRE_LOCK(ump);
5676         WORKITEM_FREE(freefrag, D_FREEFRAG);
5677         FREE_LOCK(ump);
5678 }
5679
5680 /*
5681  * Set up a dependency structure for an external attributes data block.
5682  * This routine follows much of the structure of softdep_setup_allocdirect.
5683  * See the description of softdep_setup_allocdirect above for details.
5684  */
5685 void 
5686 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5687         struct inode *ip;
5688         ufs_lbn_t off;
5689         ufs2_daddr_t newblkno;
5690         ufs2_daddr_t oldblkno;
5691         long newsize;
5692         long oldsize;
5693         struct buf *bp;
5694 {
5695         struct allocdirect *adp, *oldadp;
5696         struct allocdirectlst *adphead;
5697         struct freefrag *freefrag;
5698         struct inodedep *inodedep;
5699         struct jnewblk *jnewblk;
5700         struct newblk *newblk;
5701         struct mount *mp;
5702         struct ufsmount *ump;
5703         ufs_lbn_t lbn;
5704
5705         mp = ITOVFS(ip);
5706         ump = VFSTOUFS(mp);
5707         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5708             ("softdep_setup_allocext called on non-softdep filesystem"));
5709         KASSERT(off < UFS_NXADDR,
5710             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5711
5712         lbn = bp->b_lblkno;
5713         if (oldblkno && oldblkno != newblkno)
5714                 /*
5715                  * The usual case is that a smaller fragment that
5716                  * was just allocated has been replaced with a bigger
5717                  * fragment or a full-size block. If it is marked as
5718                  * B_DELWRI, the current contents have not been written
5719                  * to disk. It is possible that the block was written
5720                  * earlier, but very uncommon. If the block has never
5721                  * been written, there is no need to send a BIO_DELETE
5722                  * for it when it is freed. The gain from avoiding the
5723                  * TRIMs for the common case of unwritten blocks far
5724                  * exceeds the cost of the write amplification for the
5725                  * uncommon case of failing to send a TRIM for a block
5726                  * that had been written.
5727                  */
5728                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5729                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5730         else
5731                 freefrag = NULL;
5732
5733         ACQUIRE_LOCK(ump);
5734         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5735                 panic("softdep_setup_allocext: lost block");
5736         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5737             ("softdep_setup_allocext: newblk already initialized"));
5738         /*
5739          * Convert the newblk to an allocdirect.
5740          */
5741         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5742         adp = (struct allocdirect *)newblk;
5743         newblk->nb_freefrag = freefrag;
5744         adp->ad_offset = off;
5745         adp->ad_oldblkno = oldblkno;
5746         adp->ad_newsize = newsize;
5747         adp->ad_oldsize = oldsize;
5748         adp->ad_state |=  EXTDATA;
5749
5750         /*
5751          * Finish initializing the journal.
5752          */
5753         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5754                 jnewblk->jn_ino = ip->i_number;
5755                 jnewblk->jn_lbn = lbn;
5756                 add_to_journal(&jnewblk->jn_list);
5757         }
5758         if (freefrag && freefrag->ff_jdep != NULL &&
5759             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5760                 add_to_journal(freefrag->ff_jdep);
5761         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5762         adp->ad_inodedep = inodedep;
5763
5764         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5765         /*
5766          * The list of allocdirects must be kept in sorted and ascending
5767          * order so that the rollback routines can quickly determine the
5768          * first uncommitted block (the size of the file stored on disk
5769          * ends at the end of the lowest committed fragment, or if there
5770          * are no fragments, at the end of the highest committed block).
5771          * Since files generally grow, the typical case is that the new
5772          * block is to be added at the end of the list. We speed this
5773          * special case by checking against the last allocdirect in the
5774          * list before laboriously traversing the list looking for the
5775          * insertion point.
5776          */
5777         adphead = &inodedep->id_newextupdt;
5778         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5779         if (oldadp == NULL || oldadp->ad_offset <= off) {
5780                 /* insert at end of list */
5781                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5782                 if (oldadp != NULL && oldadp->ad_offset == off)
5783                         allocdirect_merge(adphead, adp, oldadp);
5784                 FREE_LOCK(ump);
5785                 return;
5786         }
5787         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5788                 if (oldadp->ad_offset >= off)
5789                         break;
5790         }
5791         if (oldadp == NULL)
5792                 panic("softdep_setup_allocext: lost entry");
5793         /* insert in middle of list */
5794         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5795         if (oldadp->ad_offset == off)
5796                 allocdirect_merge(adphead, adp, oldadp);
5797         FREE_LOCK(ump);
5798 }
5799
5800 /*
5801  * Indirect block allocation dependencies.
5802  * 
5803  * The same dependencies that exist for a direct block also exist when
5804  * a new block is allocated and pointed to by an entry in a block of
5805  * indirect pointers. The undo/redo states described above are also
5806  * used here. Because an indirect block contains many pointers that
5807  * may have dependencies, a second copy of the entire in-memory indirect
5808  * block is kept. The buffer cache copy is always completely up-to-date.
5809  * The second copy, which is used only as a source for disk writes,
5810  * contains only the safe pointers (i.e., those that have no remaining
5811  * update dependencies). The second copy is freed when all pointers
5812  * are safe. The cache is not allowed to replace indirect blocks with
5813  * pending update dependencies. If a buffer containing an indirect
5814  * block with dependencies is written, these routines will mark it
5815  * dirty again. It can only be successfully written once all the
5816  * dependencies are removed. The ffs_fsync routine in conjunction with
5817  * softdep_sync_metadata work together to get all the dependencies
5818  * removed so that a file can be successfully written to disk. Three
5819  * procedures are used when setting up indirect block pointer
5820  * dependencies. The division is necessary because of the organization
5821  * of the "balloc" routine and because of the distinction between file
5822  * pages and file metadata blocks.
5823  */
5824
5825 /*
5826  * Allocate a new allocindir structure.
5827  */
5828 static struct allocindir *
5829 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5830         struct inode *ip;       /* inode for file being extended */
5831         int ptrno;              /* offset of pointer in indirect block */
5832         ufs2_daddr_t newblkno;  /* disk block number being added */
5833         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5834         ufs_lbn_t lbn;
5835 {
5836         struct newblk *newblk;
5837         struct allocindir *aip;
5838         struct freefrag *freefrag;
5839         struct jnewblk *jnewblk;
5840
5841         if (oldblkno)
5842                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5843                     SINGLETON_KEY);
5844         else
5845                 freefrag = NULL;
5846         ACQUIRE_LOCK(ITOUMP(ip));
5847         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5848                 panic("new_allocindir: lost block");
5849         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5850             ("newallocindir: newblk already initialized"));
5851         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5852         newblk->nb_freefrag = freefrag;
5853         aip = (struct allocindir *)newblk;
5854         aip->ai_offset = ptrno;
5855         aip->ai_oldblkno = oldblkno;
5856         aip->ai_lbn = lbn;
5857         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5858                 jnewblk->jn_ino = ip->i_number;
5859                 jnewblk->jn_lbn = lbn;
5860                 add_to_journal(&jnewblk->jn_list);
5861         }
5862         if (freefrag && freefrag->ff_jdep != NULL &&
5863             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5864                 add_to_journal(freefrag->ff_jdep);
5865         return (aip);
5866 }
5867
5868 /*
5869  * Called just before setting an indirect block pointer
5870  * to a newly allocated file page.
5871  */
5872 void
5873 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5874         struct inode *ip;       /* inode for file being extended */
5875         ufs_lbn_t lbn;          /* allocated block number within file */
5876         struct buf *bp;         /* buffer with indirect blk referencing page */
5877         int ptrno;              /* offset of pointer in indirect block */
5878         ufs2_daddr_t newblkno;  /* disk block number being added */
5879         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5880         struct buf *nbp;        /* buffer holding allocated page */
5881 {
5882         struct inodedep *inodedep;
5883         struct freefrag *freefrag;
5884         struct allocindir *aip;
5885         struct pagedep *pagedep;
5886         struct mount *mp;
5887         struct ufsmount *ump;
5888
5889         mp = ITOVFS(ip);
5890         ump = VFSTOUFS(mp);
5891         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5892             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5893         KASSERT(lbn == nbp->b_lblkno,
5894             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5895             lbn, bp->b_lblkno));
5896         CTR4(KTR_SUJ,
5897             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5898             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5899         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5900         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5901         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5902         /*
5903          * If we are allocating a directory page, then we must
5904          * allocate an associated pagedep to track additions and
5905          * deletions.
5906          */
5907         if ((ip->i_mode & IFMT) == IFDIR)
5908                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5909         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5910         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5911         FREE_LOCK(ump);
5912         if (freefrag)
5913                 handle_workitem_freefrag(freefrag);
5914 }
5915
5916 /*
5917  * Called just before setting an indirect block pointer to a
5918  * newly allocated indirect block.
5919  */
5920 void
5921 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5922         struct buf *nbp;        /* newly allocated indirect block */
5923         struct inode *ip;       /* inode for file being extended */
5924         struct buf *bp;         /* indirect block referencing allocated block */
5925         int ptrno;              /* offset of pointer in indirect block */
5926         ufs2_daddr_t newblkno;  /* disk block number being added */
5927 {
5928         struct inodedep *inodedep;
5929         struct allocindir *aip;
5930         struct ufsmount *ump;
5931         ufs_lbn_t lbn;
5932
5933         ump = ITOUMP(ip);
5934         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5935             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5936         CTR3(KTR_SUJ,
5937             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5938             ip->i_number, newblkno, ptrno);
5939         lbn = nbp->b_lblkno;
5940         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5941         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5942         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5943         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5944         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5945                 panic("softdep_setup_allocindir_meta: Block already existed");
5946         FREE_LOCK(ump);
5947 }
5948
5949 static void
5950 indirdep_complete(indirdep)
5951         struct indirdep *indirdep;
5952 {
5953         struct allocindir *aip;
5954
5955         LIST_REMOVE(indirdep, ir_next);
5956         indirdep->ir_state |= DEPCOMPLETE;
5957
5958         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5959                 LIST_REMOVE(aip, ai_next);
5960                 free_newblk(&aip->ai_block);
5961         }
5962         /*
5963          * If this indirdep is not attached to a buf it was simply waiting
5964          * on completion to clear completehd.  free_indirdep() asserts
5965          * that nothing is dangling.
5966          */
5967         if ((indirdep->ir_state & ONWORKLIST) == 0)
5968                 free_indirdep(indirdep);
5969 }
5970
5971 static struct indirdep *
5972 indirdep_lookup(mp, ip, bp)
5973         struct mount *mp;
5974         struct inode *ip;
5975         struct buf *bp;
5976 {
5977         struct indirdep *indirdep, *newindirdep;
5978         struct newblk *newblk;
5979         struct ufsmount *ump;
5980         struct worklist *wk;
5981         struct fs *fs;
5982         ufs2_daddr_t blkno;
5983
5984         ump = VFSTOUFS(mp);
5985         LOCK_OWNED(ump);
5986         indirdep = NULL;
5987         newindirdep = NULL;
5988         fs = ump->um_fs;
5989         for (;;) {
5990                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5991                         if (wk->wk_type != D_INDIRDEP)
5992                                 continue;
5993                         indirdep = WK_INDIRDEP(wk);
5994                         break;
5995                 }
5996                 /* Found on the buffer worklist, no new structure to free. */
5997                 if (indirdep != NULL && newindirdep == NULL)
5998                         return (indirdep);
5999                 if (indirdep != NULL && newindirdep != NULL)
6000                         panic("indirdep_lookup: simultaneous create");
6001                 /* None found on the buffer and a new structure is ready. */
6002                 if (indirdep == NULL && newindirdep != NULL)
6003                         break;
6004                 /* None found and no new structure available. */
6005                 FREE_LOCK(ump);
6006                 newindirdep = malloc(sizeof(struct indirdep),
6007                     M_INDIRDEP, M_SOFTDEP_FLAGS);
6008                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6009                 newindirdep->ir_state = ATTACHED;
6010                 if (I_IS_UFS1(ip))
6011                         newindirdep->ir_state |= UFS1FMT;
6012                 TAILQ_INIT(&newindirdep->ir_trunc);
6013                 newindirdep->ir_saveddata = NULL;
6014                 LIST_INIT(&newindirdep->ir_deplisthd);
6015                 LIST_INIT(&newindirdep->ir_donehd);
6016                 LIST_INIT(&newindirdep->ir_writehd);
6017                 LIST_INIT(&newindirdep->ir_completehd);
6018                 if (bp->b_blkno == bp->b_lblkno) {
6019                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6020                             NULL, NULL);
6021                         bp->b_blkno = blkno;
6022                 }
6023                 newindirdep->ir_freeblks = NULL;
6024                 newindirdep->ir_savebp =
6025                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6026                 newindirdep->ir_bp = bp;
6027                 BUF_KERNPROC(newindirdep->ir_savebp);
6028                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6029                 ACQUIRE_LOCK(ump);
6030         }
6031         indirdep = newindirdep;
6032         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6033         /*
6034          * If the block is not yet allocated we don't set DEPCOMPLETE so
6035          * that we don't free dependencies until the pointers are valid.
6036          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6037          * than using the hash.
6038          */
6039         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6040                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6041         else
6042                 indirdep->ir_state |= DEPCOMPLETE;
6043         return (indirdep);
6044 }
6045
6046 /*
6047  * Called to finish the allocation of the "aip" allocated
6048  * by one of the two routines above.
6049  */
6050 static struct freefrag *
6051 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6052         struct buf *bp;         /* in-memory copy of the indirect block */
6053         struct inode *ip;       /* inode for file being extended */
6054         struct inodedep *inodedep; /* Inodedep for ip */
6055         struct allocindir *aip; /* allocindir allocated by the above routines */
6056         ufs_lbn_t lbn;          /* Logical block number for this block. */
6057 {
6058         struct fs *fs;
6059         struct indirdep *indirdep;
6060         struct allocindir *oldaip;
6061         struct freefrag *freefrag;
6062         struct mount *mp;
6063         struct ufsmount *ump;
6064
6065         mp = ITOVFS(ip);
6066         ump = VFSTOUFS(mp);
6067         LOCK_OWNED(ump);
6068         fs = ump->um_fs;
6069         if (bp->b_lblkno >= 0)
6070                 panic("setup_allocindir_phase2: not indir blk");
6071         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6072             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6073         indirdep = indirdep_lookup(mp, ip, bp);
6074         KASSERT(indirdep->ir_savebp != NULL,
6075             ("setup_allocindir_phase2 NULL ir_savebp"));
6076         aip->ai_indirdep = indirdep;
6077         /*
6078          * Check for an unwritten dependency for this indirect offset.  If
6079          * there is, merge the old dependency into the new one.  This happens
6080          * as a result of reallocblk only.
6081          */
6082         freefrag = NULL;
6083         if (aip->ai_oldblkno != 0) {
6084                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6085                         if (oldaip->ai_offset == aip->ai_offset) {
6086                                 freefrag = allocindir_merge(aip, oldaip);
6087                                 goto done;
6088                         }
6089                 }
6090                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6091                         if (oldaip->ai_offset == aip->ai_offset) {
6092                                 freefrag = allocindir_merge(aip, oldaip);
6093                                 goto done;
6094                         }
6095                 }
6096         }
6097 done:
6098         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6099         return (freefrag);
6100 }
6101
6102 /*
6103  * Merge two allocindirs which refer to the same block.  Move newblock
6104  * dependencies and setup the freefrags appropriately.
6105  */
6106 static struct freefrag *
6107 allocindir_merge(aip, oldaip)
6108         struct allocindir *aip;
6109         struct allocindir *oldaip;
6110 {
6111         struct freefrag *freefrag;
6112         struct worklist *wk;
6113
6114         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6115                 panic("allocindir_merge: blkno");
6116         aip->ai_oldblkno = oldaip->ai_oldblkno;
6117         freefrag = aip->ai_freefrag;
6118         aip->ai_freefrag = oldaip->ai_freefrag;
6119         oldaip->ai_freefrag = NULL;
6120         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6121         /*
6122          * If we are tracking a new directory-block allocation,
6123          * move it from the old allocindir to the new allocindir.
6124          */
6125         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6126                 WORKLIST_REMOVE(wk);
6127                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6128                         panic("allocindir_merge: extra newdirblk");
6129                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6130         }
6131         /*
6132          * We can skip journaling for this freefrag and just complete
6133          * any pending journal work for the allocindir that is being
6134          * removed after the freefrag completes.
6135          */
6136         if (freefrag->ff_jdep)
6137                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6138         LIST_REMOVE(oldaip, ai_next);
6139         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6140             &freefrag->ff_list, &freefrag->ff_jwork);
6141         free_newblk(&oldaip->ai_block);
6142
6143         return (freefrag);
6144 }
6145
6146 static inline void
6147 setup_freedirect(freeblks, ip, i, needj)
6148         struct freeblks *freeblks;
6149         struct inode *ip;
6150         int i;
6151         int needj;
6152 {
6153         struct ufsmount *ump;
6154         ufs2_daddr_t blkno;
6155         int frags;
6156
6157         blkno = DIP(ip, i_db[i]);
6158         if (blkno == 0)
6159                 return;
6160         DIP_SET(ip, i_db[i], 0);
6161         ump = ITOUMP(ip);
6162         frags = sblksize(ump->um_fs, ip->i_size, i);
6163         frags = numfrags(ump->um_fs, frags);
6164         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6165 }
6166
6167 static inline void
6168 setup_freeext(freeblks, ip, i, needj)
6169         struct freeblks *freeblks;
6170         struct inode *ip;
6171         int i;
6172         int needj;
6173 {
6174         struct ufsmount *ump;
6175         ufs2_daddr_t blkno;
6176         int frags;
6177
6178         blkno = ip->i_din2->di_extb[i];
6179         if (blkno == 0)
6180                 return;
6181         ip->i_din2->di_extb[i] = 0;
6182         ump = ITOUMP(ip);
6183         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6184         frags = numfrags(ump->um_fs, frags);
6185         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6186 }
6187
6188 static inline void
6189 setup_freeindir(freeblks, ip, i, lbn, needj)
6190         struct freeblks *freeblks;
6191         struct inode *ip;
6192         int i;
6193         ufs_lbn_t lbn;
6194         int needj;
6195 {
6196         struct ufsmount *ump;
6197         ufs2_daddr_t blkno;
6198
6199         blkno = DIP(ip, i_ib[i]);
6200         if (blkno == 0)
6201                 return;
6202         DIP_SET(ip, i_ib[i], 0);
6203         ump = ITOUMP(ip);
6204         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6205             0, needj);
6206 }
6207
6208 static inline struct freeblks *
6209 newfreeblks(mp, ip)
6210         struct mount *mp;
6211         struct inode *ip;
6212 {
6213         struct freeblks *freeblks;
6214
6215         freeblks = malloc(sizeof(struct freeblks),
6216                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6217         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6218         LIST_INIT(&freeblks->fb_jblkdephd);
6219         LIST_INIT(&freeblks->fb_jwork);
6220         freeblks->fb_ref = 0;
6221         freeblks->fb_cgwait = 0;
6222         freeblks->fb_state = ATTACHED;
6223         freeblks->fb_uid = ip->i_uid;
6224         freeblks->fb_inum = ip->i_number;
6225         freeblks->fb_vtype = ITOV(ip)->v_type;
6226         freeblks->fb_modrev = DIP(ip, i_modrev);
6227         freeblks->fb_devvp = ITODEVVP(ip);
6228         freeblks->fb_chkcnt = 0;
6229         freeblks->fb_len = 0;
6230
6231         return (freeblks);
6232 }
6233
6234 static void
6235 trunc_indirdep(indirdep, freeblks, bp, off)
6236         struct indirdep *indirdep;
6237         struct freeblks *freeblks;
6238         struct buf *bp;
6239         int off;
6240 {
6241         struct allocindir *aip, *aipn;
6242
6243         /*
6244          * The first set of allocindirs won't be in savedbp.
6245          */
6246         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6247                 if (aip->ai_offset > off)
6248                         cancel_allocindir(aip, bp, freeblks, 1);
6249         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6250                 if (aip->ai_offset > off)
6251                         cancel_allocindir(aip, bp, freeblks, 1);
6252         /*
6253          * These will exist in savedbp.
6254          */
6255         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6256                 if (aip->ai_offset > off)
6257                         cancel_allocindir(aip, NULL, freeblks, 0);
6258         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6259                 if (aip->ai_offset > off)
6260                         cancel_allocindir(aip, NULL, freeblks, 0);
6261 }
6262
6263 /*
6264  * Follow the chain of indirects down to lastlbn creating a freework
6265  * structure for each.  This will be used to start indir_trunc() at
6266  * the right offset and create the journal records for the parrtial
6267  * truncation.  A second step will handle the truncated dependencies.
6268  */
6269 static int
6270 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6271         struct freeblks *freeblks;
6272         struct inode *ip;
6273         ufs_lbn_t lbn;
6274         ufs_lbn_t lastlbn;
6275         ufs2_daddr_t blkno;
6276 {
6277         struct indirdep *indirdep;
6278         struct indirdep *indirn;
6279         struct freework *freework;
6280         struct newblk *newblk;
6281         struct mount *mp;
6282         struct ufsmount *ump;
6283         struct buf *bp;
6284         uint8_t *start;
6285         uint8_t *end;
6286         ufs_lbn_t lbnadd;
6287         int level;
6288         int error;
6289         int off;
6290
6291
6292         freework = NULL;
6293         if (blkno == 0)
6294                 return (0);
6295         mp = freeblks->fb_list.wk_mp;
6296         ump = VFSTOUFS(mp);
6297         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6298         if ((bp->b_flags & B_CACHE) == 0) {
6299                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6300                 bp->b_iocmd = BIO_READ;
6301                 bp->b_flags &= ~B_INVAL;
6302                 bp->b_ioflags &= ~BIO_ERROR;
6303                 vfs_busy_pages(bp, 0);
6304                 bp->b_iooffset = dbtob(bp->b_blkno);
6305                 bstrategy(bp);
6306 #ifdef RACCT
6307                 if (racct_enable) {
6308                         PROC_LOCK(curproc);
6309                         racct_add_buf(curproc, bp, 0);
6310                         PROC_UNLOCK(curproc);
6311                 }
6312 #endif /* RACCT */
6313                 curthread->td_ru.ru_inblock++;
6314                 error = bufwait(bp);
6315                 if (error) {
6316                         brelse(bp);
6317                         return (error);
6318                 }
6319         }
6320         level = lbn_level(lbn);
6321         lbnadd = lbn_offset(ump->um_fs, level);
6322         /*
6323          * Compute the offset of the last block we want to keep.  Store
6324          * in the freework the first block we want to completely free.
6325          */
6326         off = (lastlbn - -(lbn + level)) / lbnadd;
6327         if (off + 1 == NINDIR(ump->um_fs))
6328                 goto nowork;
6329         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6330         /*
6331          * Link the freework into the indirdep.  This will prevent any new
6332          * allocations from proceeding until we are finished with the
6333          * truncate and the block is written.
6334          */
6335         ACQUIRE_LOCK(ump);
6336         indirdep = indirdep_lookup(mp, ip, bp);
6337         if (indirdep->ir_freeblks)
6338                 panic("setup_trunc_indir: indirdep already truncated.");
6339         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6340         freework->fw_indir = indirdep;
6341         /*
6342          * Cancel any allocindirs that will not make it to disk.
6343          * We have to do this for all copies of the indirdep that
6344          * live on this newblk.
6345          */
6346         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6347                 if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6348                     &newblk) == 0)
6349                         panic("setup_trunc_indir: lost block");
6350                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6351                         trunc_indirdep(indirn, freeblks, bp, off);
6352         } else
6353                 trunc_indirdep(indirdep, freeblks, bp, off);
6354         FREE_LOCK(ump);
6355         /*
6356          * Creation is protected by the buf lock. The saveddata is only
6357          * needed if a full truncation follows a partial truncation but it
6358          * is difficult to allocate in that case so we fetch it anyway.
6359          */
6360         if (indirdep->ir_saveddata == NULL)
6361                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6362                     M_SOFTDEP_FLAGS);
6363 nowork:
6364         /* Fetch the blkno of the child and the zero start offset. */
6365         if (I_IS_UFS1(ip)) {
6366                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6367                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6368         } else {
6369                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6370                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6371         }
6372         if (freework) {
6373                 /* Zero the truncated pointers. */
6374                 end = bp->b_data + bp->b_bcount;
6375                 bzero(start, end - start);
6376                 bdwrite(bp);
6377         } else
6378                 bqrelse(bp);
6379         if (level == 0)
6380                 return (0);
6381         lbn++; /* adjust level */
6382         lbn -= (off * lbnadd);
6383         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6384 }
6385
6386 /*
6387  * Complete the partial truncation of an indirect block setup by
6388  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6389  * copy and writes them to disk before the freeblks is allowed to complete.
6390  */
6391 static void
6392 complete_trunc_indir(freework)
6393         struct freework *freework;
6394 {
6395         struct freework *fwn;
6396         struct indirdep *indirdep;
6397         struct ufsmount *ump;
6398         struct buf *bp;
6399         uintptr_t start;
6400         int count;
6401
6402         ump = VFSTOUFS(freework->fw_list.wk_mp);
6403         LOCK_OWNED(ump);
6404         indirdep = freework->fw_indir;
6405         for (;;) {
6406                 bp = indirdep->ir_bp;
6407                 /* See if the block was discarded. */
6408                 if (bp == NULL)
6409                         break;
6410                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6411                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6412                         break;
6413                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6414                     LOCK_PTR(ump)) == 0)
6415                         BUF_UNLOCK(bp);
6416                 ACQUIRE_LOCK(ump);
6417         }
6418         freework->fw_state |= DEPCOMPLETE;
6419         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6420         /*
6421          * Zero the pointers in the saved copy.
6422          */
6423         if (indirdep->ir_state & UFS1FMT)
6424                 start = sizeof(ufs1_daddr_t);
6425         else
6426                 start = sizeof(ufs2_daddr_t);
6427         start *= freework->fw_start;
6428         count = indirdep->ir_savebp->b_bcount - start;
6429         start += (uintptr_t)indirdep->ir_savebp->b_data;
6430         bzero((char *)start, count);
6431         /*
6432          * We need to start the next truncation in the list if it has not
6433          * been started yet.
6434          */
6435         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6436         if (fwn != NULL) {
6437                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6438                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6439                 if ((fwn->fw_state & ONWORKLIST) == 0)
6440                         freework_enqueue(fwn);
6441         }
6442         /*
6443          * If bp is NULL the block was fully truncated, restore
6444          * the saved block list otherwise free it if it is no
6445          * longer needed.
6446          */
6447         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6448                 if (bp == NULL)
6449                         bcopy(indirdep->ir_saveddata,
6450                             indirdep->ir_savebp->b_data,
6451                             indirdep->ir_savebp->b_bcount);
6452                 free(indirdep->ir_saveddata, M_INDIRDEP);
6453                 indirdep->ir_saveddata = NULL;
6454         }
6455         /*
6456          * When bp is NULL there is a full truncation pending.  We
6457          * must wait for this full truncation to be journaled before
6458          * we can release this freework because the disk pointers will
6459          * never be written as zero.
6460          */
6461         if (bp == NULL)  {
6462                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6463                         handle_written_freework(freework);
6464                 else
6465                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6466                            &freework->fw_list);
6467         } else {
6468                 /* Complete when the real copy is written. */
6469                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6470                 BUF_UNLOCK(bp);
6471         }
6472 }
6473
6474 /*
6475  * Calculate the number of blocks we are going to release where datablocks
6476  * is the current total and length is the new file size.
6477  */
6478 static ufs2_daddr_t
6479 blkcount(fs, datablocks, length)
6480         struct fs *fs;
6481         ufs2_daddr_t datablocks;
6482         off_t length;
6483 {
6484         off_t totblks, numblks;
6485
6486         totblks = 0;
6487         numblks = howmany(length, fs->fs_bsize);
6488         if (numblks <= UFS_NDADDR) {
6489                 totblks = howmany(length, fs->fs_fsize);
6490                 goto out;
6491         }
6492         totblks = blkstofrags(fs, numblks);
6493         numblks -= UFS_NDADDR;
6494         /*
6495          * Count all single, then double, then triple indirects required.
6496          * Subtracting one indirects worth of blocks for each pass
6497          * acknowledges one of each pointed to by the inode.
6498          */
6499         for (;;) {
6500                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6501                 numblks -= NINDIR(fs);
6502                 if (numblks <= 0)
6503                         break;
6504                 numblks = howmany(numblks, NINDIR(fs));
6505         }
6506 out:
6507         totblks = fsbtodb(fs, totblks);
6508         /*
6509          * Handle sparse files.  We can't reclaim more blocks than the inode
6510          * references.  We will correct it later in handle_complete_freeblks()
6511          * when we know the real count.
6512          */
6513         if (totblks > datablocks)
6514                 return (0);
6515         return (datablocks - totblks);
6516 }
6517
6518 /*
6519  * Handle freeblocks for journaled softupdate filesystems.
6520  *
6521  * Contrary to normal softupdates, we must preserve the block pointers in
6522  * indirects until their subordinates are free.  This is to avoid journaling
6523  * every block that is freed which may consume more space than the journal
6524  * itself.  The recovery program will see the free block journals at the
6525  * base of the truncated area and traverse them to reclaim space.  The
6526  * pointers in the inode may be cleared immediately after the journal
6527  * records are written because each direct and indirect pointer in the
6528  * inode is recorded in a journal.  This permits full truncation to proceed
6529  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6530  *
6531  * The algorithm is as follows:
6532  * 1) Traverse the in-memory state and create journal entries to release
6533  *    the relevant blocks and full indirect trees.
6534  * 2) Traverse the indirect block chain adding partial truncation freework
6535  *    records to indirects in the path to lastlbn.  The freework will
6536  *    prevent new allocation dependencies from being satisfied in this
6537  *    indirect until the truncation completes.
6538  * 3) Read and lock the inode block, performing an update with the new size
6539  *    and pointers.  This prevents truncated data from becoming valid on
6540  *    disk through step 4.
6541  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6542  *    eliminate journal work for those records that do not require it.
6543  * 5) Schedule the journal records to be written followed by the inode block.
6544  * 6) Allocate any necessary frags for the end of file.
6545  * 7) Zero any partially truncated blocks.
6546  *
6547  * From this truncation proceeds asynchronously using the freework and
6548  * indir_trunc machinery.  The file will not be extended again into a
6549  * partially truncated indirect block until all work is completed but
6550  * the normal dependency mechanism ensures that it is rolled back/forward
6551  * as appropriate.  Further truncation may occur without delay and is
6552  * serialized in indir_trunc().
6553  */
6554 void
6555 softdep_journal_freeblocks(ip, cred, length, flags)
6556         struct inode *ip;       /* The inode whose length is to be reduced */
6557         struct ucred *cred;
6558         off_t length;           /* The new length for the file */
6559         int flags;              /* IO_EXT and/or IO_NORMAL */
6560 {
6561         struct freeblks *freeblks, *fbn;
6562         struct worklist *wk, *wkn;
6563         struct inodedep *inodedep;
6564         struct jblkdep *jblkdep;
6565         struct allocdirect *adp, *adpn;
6566         struct ufsmount *ump;
6567         struct fs *fs;
6568         struct buf *bp;
6569         struct vnode *vp;
6570         struct mount *mp;
6571         ufs2_daddr_t extblocks, datablocks;
6572         ufs_lbn_t tmpval, lbn, lastlbn;
6573         int frags, lastoff, iboff, allocblock, needj, error, i;
6574
6575         ump = ITOUMP(ip);
6576         mp = UFSTOVFS(ump);
6577         fs = ump->um_fs;
6578         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6579             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6580         vp = ITOV(ip);
6581         needj = 1;
6582         iboff = -1;
6583         allocblock = 0;
6584         extblocks = 0;
6585         datablocks = 0;
6586         frags = 0;
6587         freeblks = newfreeblks(mp, ip);
6588         ACQUIRE_LOCK(ump);
6589         /*
6590          * If we're truncating a removed file that will never be written
6591          * we don't need to journal the block frees.  The canceled journals
6592          * for the allocations will suffice.
6593          */
6594         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6595         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6596             length == 0)
6597                 needj = 0;
6598         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6599             ip->i_number, length, needj);
6600         FREE_LOCK(ump);
6601         /*
6602          * Calculate the lbn that we are truncating to.  This results in -1
6603          * if we're truncating the 0 bytes.  So it is the last lbn we want
6604          * to keep, not the first lbn we want to truncate.
6605          */
6606         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6607         lastoff = blkoff(fs, length);
6608         /*
6609          * Compute frags we are keeping in lastlbn.  0 means all.
6610          */
6611         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6612                 frags = fragroundup(fs, lastoff);
6613                 /* adp offset of last valid allocdirect. */
6614                 iboff = lastlbn;
6615         } else if (lastlbn > 0)
6616                 iboff = UFS_NDADDR;
6617         if (fs->fs_magic == FS_UFS2_MAGIC)
6618                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6619         /*
6620          * Handle normal data blocks and indirects.  This section saves
6621          * values used after the inode update to complete frag and indirect
6622          * truncation.
6623          */
6624         if ((flags & IO_NORMAL) != 0) {
6625                 /*
6626                  * Handle truncation of whole direct and indirect blocks.
6627                  */
6628                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6629                         setup_freedirect(freeblks, ip, i, needj);
6630                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6631                     i < UFS_NIADDR;
6632                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6633                         /* Release a whole indirect tree. */
6634                         if (lbn > lastlbn) {
6635                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6636                                     needj);
6637                                 continue;
6638                         }
6639                         iboff = i + UFS_NDADDR;
6640                         /*
6641                          * Traverse partially truncated indirect tree.
6642                          */
6643                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6644                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6645                                     lastlbn, DIP(ip, i_ib[i]));
6646                 }
6647                 /*
6648                  * Handle partial truncation to a frag boundary.
6649                  */
6650                 if (frags) {
6651                         ufs2_daddr_t blkno;
6652                         long oldfrags;
6653
6654                         oldfrags = blksize(fs, ip, lastlbn);
6655                         blkno = DIP(ip, i_db[lastlbn]);
6656                         if (blkno && oldfrags != frags) {
6657                                 oldfrags -= frags;
6658                                 oldfrags = numfrags(fs, oldfrags);
6659                                 blkno += numfrags(fs, frags);
6660                                 newfreework(ump, freeblks, NULL, lastlbn,
6661                                     blkno, oldfrags, 0, needj);
6662                                 if (needj)
6663                                         adjust_newfreework(freeblks,
6664                                             numfrags(fs, frags));
6665                         } else if (blkno == 0)
6666                                 allocblock = 1;
6667                 }
6668                 /*
6669                  * Add a journal record for partial truncate if we are
6670                  * handling indirect blocks.  Non-indirects need no extra
6671                  * journaling.
6672                  */
6673                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6674                         ip->i_flag |= IN_TRUNCATED;
6675                         newjtrunc(freeblks, length, 0);
6676                 }
6677                 ip->i_size = length;
6678                 DIP_SET(ip, i_size, ip->i_size);
6679                 datablocks = DIP(ip, i_blocks) - extblocks;
6680                 if (length != 0)
6681                         datablocks = blkcount(fs, datablocks, length);
6682                 freeblks->fb_len = length;
6683         }
6684         if ((flags & IO_EXT) != 0) {
6685                 for (i = 0; i < UFS_NXADDR; i++)
6686                         setup_freeext(freeblks, ip, i, needj);
6687                 ip->i_din2->di_extsize = 0;
6688                 datablocks += extblocks;
6689         }
6690 #ifdef QUOTA
6691         /* Reference the quotas in case the block count is wrong in the end. */
6692         quotaref(vp, freeblks->fb_quota);
6693         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6694 #endif
6695         freeblks->fb_chkcnt = -datablocks;
6696         UFS_LOCK(ump);
6697         fs->fs_pendingblocks += datablocks;
6698         UFS_UNLOCK(ump);
6699         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6700         /*
6701          * Handle truncation of incomplete alloc direct dependencies.  We
6702          * hold the inode block locked to prevent incomplete dependencies
6703          * from reaching the disk while we are eliminating those that
6704          * have been truncated.  This is a partially inlined ffs_update().
6705          */
6706         ufs_itimes(vp);
6707         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6708         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6709             (int)fs->fs_bsize, cred, &bp);
6710         if (error) {
6711                 softdep_error("softdep_journal_freeblocks", error);
6712                 return;
6713         }
6714         if (bp->b_bufsize == fs->fs_bsize)
6715                 bp->b_flags |= B_CLUSTEROK;
6716         softdep_update_inodeblock(ip, bp, 0);
6717         if (ump->um_fstype == UFS1) {
6718                 *((struct ufs1_dinode *)bp->b_data +
6719                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6720         } else {
6721                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6722                 *((struct ufs2_dinode *)bp->b_data +
6723                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6724         }
6725         ACQUIRE_LOCK(ump);
6726         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6727         if ((inodedep->id_state & IOSTARTED) != 0)
6728                 panic("softdep_setup_freeblocks: inode busy");
6729         /*
6730          * Add the freeblks structure to the list of operations that
6731          * must await the zero'ed inode being written to disk. If we
6732          * still have a bitmap dependency (needj), then the inode
6733          * has never been written to disk, so we can process the
6734          * freeblks below once we have deleted the dependencies.
6735          */
6736         if (needj)
6737                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6738         else
6739                 freeblks->fb_state |= COMPLETE;
6740         if ((flags & IO_NORMAL) != 0) {
6741                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6742                         if (adp->ad_offset > iboff)
6743                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6744                                     freeblks);
6745                         /*
6746                          * Truncate the allocdirect.  We could eliminate
6747                          * or modify journal records as well.
6748                          */
6749                         else if (adp->ad_offset == iboff && frags)
6750                                 adp->ad_newsize = frags;
6751                 }
6752         }
6753         if ((flags & IO_EXT) != 0)
6754                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6755                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6756                             freeblks);
6757         /*
6758          * Scan the bufwait list for newblock dependencies that will never
6759          * make it to disk.
6760          */
6761         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6762                 if (wk->wk_type != D_ALLOCDIRECT)
6763                         continue;
6764                 adp = WK_ALLOCDIRECT(wk);
6765                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6766                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6767                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6768                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6769                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6770                 }
6771         }
6772         /*
6773          * Add journal work.
6774          */
6775         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6776                 add_to_journal(&jblkdep->jb_list);
6777         FREE_LOCK(ump);
6778         bdwrite(bp);
6779         /*
6780          * Truncate dependency structures beyond length.
6781          */
6782         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6783         /*
6784          * This is only set when we need to allocate a fragment because
6785          * none existed at the end of a frag-sized file.  It handles only
6786          * allocating a new, zero filled block.
6787          */
6788         if (allocblock) {
6789                 ip->i_size = length - lastoff;
6790                 DIP_SET(ip, i_size, ip->i_size);
6791                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6792                 if (error != 0) {
6793                         softdep_error("softdep_journal_freeblks", error);
6794                         return;
6795                 }
6796                 ip->i_size = length;
6797                 DIP_SET(ip, i_size, length);
6798                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6799                 allocbuf(bp, frags);
6800                 ffs_update(vp, 0);
6801                 bawrite(bp);
6802         } else if (lastoff != 0 && vp->v_type != VDIR) {
6803                 int size;
6804
6805                 /*
6806                  * Zero the end of a truncated frag or block.
6807                  */
6808                 size = sblksize(fs, length, lastlbn);
6809                 error = bread(vp, lastlbn, size, cred, &bp);
6810                 if (error) {
6811                         softdep_error("softdep_journal_freeblks", error);
6812                         return;
6813                 }
6814                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6815                 bawrite(bp);
6816
6817         }
6818         ACQUIRE_LOCK(ump);
6819         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6820         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6821         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6822         /*
6823          * We zero earlier truncations so they don't erroneously
6824          * update i_blocks.
6825          */
6826         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6827                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6828                         fbn->fb_len = 0;
6829         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6830             LIST_EMPTY(&freeblks->fb_jblkdephd))
6831                 freeblks->fb_state |= INPROGRESS;
6832         else
6833                 freeblks = NULL;
6834         FREE_LOCK(ump);
6835         if (freeblks)
6836                 handle_workitem_freeblocks(freeblks, 0);
6837         trunc_pages(ip, length, extblocks, flags);
6838
6839 }
6840
6841 /*
6842  * Flush a JOP_SYNC to the journal.
6843  */
6844 void
6845 softdep_journal_fsync(ip)
6846         struct inode *ip;
6847 {
6848         struct jfsync *jfsync;
6849         struct ufsmount *ump;
6850
6851         ump = ITOUMP(ip);
6852         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6853             ("softdep_journal_fsync called on non-softdep filesystem"));
6854         if ((ip->i_flag & IN_TRUNCATED) == 0)
6855                 return;
6856         ip->i_flag &= ~IN_TRUNCATED;
6857         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6858         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6859         jfsync->jfs_size = ip->i_size;
6860         jfsync->jfs_ino = ip->i_number;
6861         ACQUIRE_LOCK(ump);
6862         add_to_journal(&jfsync->jfs_list);
6863         jwait(&jfsync->jfs_list, MNT_WAIT);
6864         FREE_LOCK(ump);
6865 }
6866
6867 /*
6868  * Block de-allocation dependencies.
6869  * 
6870  * When blocks are de-allocated, the on-disk pointers must be nullified before
6871  * the blocks are made available for use by other files.  (The true
6872  * requirement is that old pointers must be nullified before new on-disk
6873  * pointers are set.  We chose this slightly more stringent requirement to
6874  * reduce complexity.) Our implementation handles this dependency by updating
6875  * the inode (or indirect block) appropriately but delaying the actual block
6876  * de-allocation (i.e., freemap and free space count manipulation) until
6877  * after the updated versions reach stable storage.  After the disk is
6878  * updated, the blocks can be safely de-allocated whenever it is convenient.
6879  * This implementation handles only the common case of reducing a file's
6880  * length to zero. Other cases are handled by the conventional synchronous
6881  * write approach.
6882  *
6883  * The ffs implementation with which we worked double-checks
6884  * the state of the block pointers and file size as it reduces
6885  * a file's length.  Some of this code is replicated here in our
6886  * soft updates implementation.  The freeblks->fb_chkcnt field is
6887  * used to transfer a part of this information to the procedure
6888  * that eventually de-allocates the blocks.
6889  *
6890  * This routine should be called from the routine that shortens
6891  * a file's length, before the inode's size or block pointers
6892  * are modified. It will save the block pointer information for
6893  * later release and zero the inode so that the calling routine
6894  * can release it.
6895  */
6896 void
6897 softdep_setup_freeblocks(ip, length, flags)
6898         struct inode *ip;       /* The inode whose length is to be reduced */
6899         off_t length;           /* The new length for the file */
6900         int flags;              /* IO_EXT and/or IO_NORMAL */
6901 {
6902         struct ufs1_dinode *dp1;
6903         struct ufs2_dinode *dp2;
6904         struct freeblks *freeblks;
6905         struct inodedep *inodedep;
6906         struct allocdirect *adp;
6907         struct ufsmount *ump;
6908         struct buf *bp;
6909         struct fs *fs;
6910         ufs2_daddr_t extblocks, datablocks;
6911         struct mount *mp;
6912         int i, delay, error;
6913         ufs_lbn_t tmpval;
6914         ufs_lbn_t lbn;
6915
6916         ump = ITOUMP(ip);
6917         mp = UFSTOVFS(ump);
6918         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6919             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6920         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6921             ip->i_number, length);
6922         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6923         fs = ump->um_fs;
6924         if ((error = bread(ump->um_devvp,
6925             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6926             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6927                 brelse(bp);
6928                 softdep_error("softdep_setup_freeblocks", error);
6929                 return;
6930         }
6931         freeblks = newfreeblks(mp, ip);
6932         extblocks = 0;
6933         datablocks = 0;
6934         if (fs->fs_magic == FS_UFS2_MAGIC)
6935                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6936         if ((flags & IO_NORMAL) != 0) {
6937                 for (i = 0; i < UFS_NDADDR; i++)
6938                         setup_freedirect(freeblks, ip, i, 0);
6939                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6940                     i < UFS_NIADDR;
6941                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6942                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6943                 ip->i_size = 0;
6944                 DIP_SET(ip, i_size, 0);
6945                 datablocks = DIP(ip, i_blocks) - extblocks;
6946         }
6947         if ((flags & IO_EXT) != 0) {
6948                 for (i = 0; i < UFS_NXADDR; i++)
6949                         setup_freeext(freeblks, ip, i, 0);
6950                 ip->i_din2->di_extsize = 0;
6951                 datablocks += extblocks;
6952         }
6953 #ifdef QUOTA
6954         /* Reference the quotas in case the block count is wrong in the end. */
6955         quotaref(ITOV(ip), freeblks->fb_quota);
6956         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6957 #endif
6958         freeblks->fb_chkcnt = -datablocks;
6959         UFS_LOCK(ump);
6960         fs->fs_pendingblocks += datablocks;
6961         UFS_UNLOCK(ump);
6962         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6963         /*
6964          * Push the zero'ed inode to its disk buffer so that we are free
6965          * to delete its dependencies below. Once the dependencies are gone
6966          * the buffer can be safely released.
6967          */
6968         if (ump->um_fstype == UFS1) {
6969                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6970                     ino_to_fsbo(fs, ip->i_number));
6971                 ip->i_din1->di_freelink = dp1->di_freelink;
6972                 *dp1 = *ip->i_din1;
6973         } else {
6974                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6975                     ino_to_fsbo(fs, ip->i_number));
6976                 ip->i_din2->di_freelink = dp2->di_freelink;
6977                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6978                 *dp2 = *ip->i_din2;
6979         }
6980         /*
6981          * Find and eliminate any inode dependencies.
6982          */
6983         ACQUIRE_LOCK(ump);
6984         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6985         if ((inodedep->id_state & IOSTARTED) != 0)
6986                 panic("softdep_setup_freeblocks: inode busy");
6987         /*
6988          * Add the freeblks structure to the list of operations that
6989          * must await the zero'ed inode being written to disk. If we
6990          * still have a bitmap dependency (delay == 0), then the inode
6991          * has never been written to disk, so we can process the
6992          * freeblks below once we have deleted the dependencies.
6993          */
6994         delay = (inodedep->id_state & DEPCOMPLETE);
6995         if (delay)
6996                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6997         else
6998                 freeblks->fb_state |= COMPLETE;
6999         /*
7000          * Because the file length has been truncated to zero, any
7001          * pending block allocation dependency structures associated
7002          * with this inode are obsolete and can simply be de-allocated.
7003          * We must first merge the two dependency lists to get rid of
7004          * any duplicate freefrag structures, then purge the merged list.
7005          * If we still have a bitmap dependency, then the inode has never
7006          * been written to disk, so we can free any fragments without delay.
7007          */
7008         if (flags & IO_NORMAL) {
7009                 merge_inode_lists(&inodedep->id_newinoupdt,
7010                     &inodedep->id_inoupdt);
7011                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7012                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
7013                             freeblks);
7014         }
7015         if (flags & IO_EXT) {
7016                 merge_inode_lists(&inodedep->id_newextupdt,
7017                     &inodedep->id_extupdt);
7018                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7019                         cancel_allocdirect(&inodedep->id_extupdt, adp,
7020                             freeblks);
7021         }
7022         FREE_LOCK(ump);
7023         bdwrite(bp);
7024         trunc_dependencies(ip, freeblks, -1, 0, flags);
7025         ACQUIRE_LOCK(ump);
7026         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7027                 (void) free_inodedep(inodedep);
7028         freeblks->fb_state |= DEPCOMPLETE;
7029         /*
7030          * If the inode with zeroed block pointers is now on disk
7031          * we can start freeing blocks.
7032          */  
7033         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7034                 freeblks->fb_state |= INPROGRESS;
7035         else
7036                 freeblks = NULL;
7037         FREE_LOCK(ump);
7038         if (freeblks)
7039                 handle_workitem_freeblocks(freeblks, 0);
7040         trunc_pages(ip, length, extblocks, flags);
7041 }
7042
7043 /*
7044  * Eliminate pages from the page cache that back parts of this inode and
7045  * adjust the vnode pager's idea of our size.  This prevents stale data
7046  * from hanging around in the page cache.
7047  */
7048 static void
7049 trunc_pages(ip, length, extblocks, flags)
7050         struct inode *ip;
7051         off_t length;
7052         ufs2_daddr_t extblocks;
7053         int flags;
7054 {
7055         struct vnode *vp;
7056         struct fs *fs;
7057         ufs_lbn_t lbn;
7058         off_t end, extend;
7059
7060         vp = ITOV(ip);
7061         fs = ITOFS(ip);
7062         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7063         if ((flags & IO_EXT) != 0)
7064                 vn_pages_remove(vp, extend, 0);
7065         if ((flags & IO_NORMAL) == 0)
7066                 return;
7067         BO_LOCK(&vp->v_bufobj);
7068         drain_output(vp);
7069         BO_UNLOCK(&vp->v_bufobj);
7070         /*
7071          * The vnode pager eliminates file pages we eliminate indirects
7072          * below.
7073          */
7074         vnode_pager_setsize(vp, length);
7075         /*
7076          * Calculate the end based on the last indirect we want to keep.  If
7077          * the block extends into indirects we can just use the negative of
7078          * its lbn.  Doubles and triples exist at lower numbers so we must
7079          * be careful not to remove those, if they exist.  double and triple
7080          * indirect lbns do not overlap with others so it is not important
7081          * to verify how many levels are required.
7082          */
7083         lbn = lblkno(fs, length);
7084         if (lbn >= UFS_NDADDR) {
7085                 /* Calculate the virtual lbn of the triple indirect. */
7086                 lbn = -lbn - (UFS_NIADDR - 1);
7087                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7088         } else
7089                 end = extend;
7090         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7091 }
7092
7093 /*
7094  * See if the buf bp is in the range eliminated by truncation.
7095  */
7096 static int
7097 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7098         struct buf *bp;
7099         int *blkoffp;
7100         ufs_lbn_t lastlbn;
7101         int lastoff;
7102         int flags;
7103 {
7104         ufs_lbn_t lbn;
7105
7106         *blkoffp = 0;
7107         /* Only match ext/normal blocks as appropriate. */
7108         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7109             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7110                 return (0);
7111         /* ALTDATA is always a full truncation. */
7112         if ((bp->b_xflags & BX_ALTDATA) != 0)
7113                 return (1);
7114         /* -1 is full truncation. */
7115         if (lastlbn == -1)
7116                 return (1);
7117         /*
7118          * If this is a partial truncate we only want those
7119          * blocks and indirect blocks that cover the range
7120          * we're after.
7121          */
7122         lbn = bp->b_lblkno;
7123         if (lbn < 0)
7124                 lbn = -(lbn + lbn_level(lbn));
7125         if (lbn < lastlbn)
7126                 return (0);
7127         /* Here we only truncate lblkno if it's partial. */
7128         if (lbn == lastlbn) {
7129                 if (lastoff == 0)
7130                         return (0);
7131                 *blkoffp = lastoff;
7132         }
7133         return (1);
7134 }
7135
7136 /*
7137  * Eliminate any dependencies that exist in memory beyond lblkno:off
7138  */
7139 static void
7140 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7141         struct inode *ip;
7142         struct freeblks *freeblks;
7143         ufs_lbn_t lastlbn;
7144         int lastoff;
7145         int flags;
7146 {
7147         struct bufobj *bo;
7148         struct vnode *vp;
7149         struct buf *bp;
7150         int blkoff;
7151
7152         /*
7153          * We must wait for any I/O in progress to finish so that
7154          * all potential buffers on the dirty list will be visible.
7155          * Once they are all there, walk the list and get rid of
7156          * any dependencies.
7157          */
7158         vp = ITOV(ip);
7159         bo = &vp->v_bufobj;
7160         BO_LOCK(bo);
7161         drain_output(vp);
7162         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7163                 bp->b_vflags &= ~BV_SCANNED;
7164 restart:
7165         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7166                 if (bp->b_vflags & BV_SCANNED)
7167                         continue;
7168                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7169                         bp->b_vflags |= BV_SCANNED;
7170                         continue;
7171                 }
7172                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7173                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7174                         goto restart;
7175                 BO_UNLOCK(bo);
7176                 if (deallocate_dependencies(bp, freeblks, blkoff))
7177                         bqrelse(bp);
7178                 else
7179                         brelse(bp);
7180                 BO_LOCK(bo);
7181                 goto restart;
7182         }
7183         /*
7184          * Now do the work of vtruncbuf while also matching indirect blocks.
7185          */
7186         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7187                 bp->b_vflags &= ~BV_SCANNED;
7188 cleanrestart:
7189         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7190                 if (bp->b_vflags & BV_SCANNED)
7191                         continue;
7192                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7193                         bp->b_vflags |= BV_SCANNED;
7194                         continue;
7195                 }
7196                 if (BUF_LOCK(bp,
7197                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7198                     BO_LOCKPTR(bo)) == ENOLCK) {
7199                         BO_LOCK(bo);
7200                         goto cleanrestart;
7201                 }
7202                 bp->b_vflags |= BV_SCANNED;
7203                 bremfree(bp);
7204                 if (blkoff != 0) {
7205                         allocbuf(bp, blkoff);
7206                         bqrelse(bp);
7207                 } else {
7208                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7209                         brelse(bp);
7210                 }
7211                 BO_LOCK(bo);
7212                 goto cleanrestart;
7213         }
7214         drain_output(vp);
7215         BO_UNLOCK(bo);
7216 }
7217
7218 static int
7219 cancel_pagedep(pagedep, freeblks, blkoff)
7220         struct pagedep *pagedep;
7221         struct freeblks *freeblks;
7222         int blkoff;
7223 {
7224         struct jremref *jremref;
7225         struct jmvref *jmvref;
7226         struct dirrem *dirrem, *tmp;
7227         int i;
7228
7229         /*
7230          * Copy any directory remove dependencies to the list
7231          * to be processed after the freeblks proceeds.  If
7232          * directory entry never made it to disk they
7233          * can be dumped directly onto the work list.
7234          */
7235         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7236                 /* Skip this directory removal if it is intended to remain. */
7237                 if (dirrem->dm_offset < blkoff)
7238                         continue;
7239                 /*
7240                  * If there are any dirrems we wait for the journal write
7241                  * to complete and then restart the buf scan as the lock
7242                  * has been dropped.
7243                  */
7244                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7245                         jwait(&jremref->jr_list, MNT_WAIT);
7246                         return (ERESTART);
7247                 }
7248                 LIST_REMOVE(dirrem, dm_next);
7249                 dirrem->dm_dirinum = pagedep->pd_ino;
7250                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7251         }
7252         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7253                 jwait(&jmvref->jm_list, MNT_WAIT);
7254                 return (ERESTART);
7255         }
7256         /*
7257          * When we're partially truncating a pagedep we just want to flush
7258          * journal entries and return.  There can not be any adds in the
7259          * truncated portion of the directory and newblk must remain if
7260          * part of the block remains.
7261          */
7262         if (blkoff != 0) {
7263                 struct diradd *dap;
7264
7265                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7266                         if (dap->da_offset > blkoff)
7267                                 panic("cancel_pagedep: diradd %p off %d > %d",
7268                                     dap, dap->da_offset, blkoff);
7269                 for (i = 0; i < DAHASHSZ; i++)
7270                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7271                                 if (dap->da_offset > blkoff)
7272                                         panic("cancel_pagedep: diradd %p off %d > %d",
7273                                             dap, dap->da_offset, blkoff);
7274                 return (0);
7275         }
7276         /*
7277          * There should be no directory add dependencies present
7278          * as the directory could not be truncated until all
7279          * children were removed.
7280          */
7281         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7282             ("deallocate_dependencies: pendinghd != NULL"));
7283         for (i = 0; i < DAHASHSZ; i++)
7284                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7285                     ("deallocate_dependencies: diraddhd != NULL"));
7286         if ((pagedep->pd_state & NEWBLOCK) != 0)
7287                 free_newdirblk(pagedep->pd_newdirblk);
7288         if (free_pagedep(pagedep) == 0)
7289                 panic("Failed to free pagedep %p", pagedep);
7290         return (0);
7291 }
7292
7293 /*
7294  * Reclaim any dependency structures from a buffer that is about to
7295  * be reallocated to a new vnode. The buffer must be locked, thus,
7296  * no I/O completion operations can occur while we are manipulating
7297  * its associated dependencies. The mutex is held so that other I/O's
7298  * associated with related dependencies do not occur.
7299  */
7300 static int
7301 deallocate_dependencies(bp, freeblks, off)
7302         struct buf *bp;
7303         struct freeblks *freeblks;
7304         int off;
7305 {
7306         struct indirdep *indirdep;
7307         struct pagedep *pagedep;
7308         struct worklist *wk, *wkn;
7309         struct ufsmount *ump;
7310
7311         ump = softdep_bp_to_mp(bp);
7312         if (ump == NULL)
7313                 goto done;
7314         ACQUIRE_LOCK(ump);
7315         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7316                 switch (wk->wk_type) {
7317                 case D_INDIRDEP:
7318                         indirdep = WK_INDIRDEP(wk);
7319                         if (bp->b_lblkno >= 0 ||
7320                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7321                                 panic("deallocate_dependencies: not indir");
7322                         cancel_indirdep(indirdep, bp, freeblks);
7323                         continue;
7324
7325                 case D_PAGEDEP:
7326                         pagedep = WK_PAGEDEP(wk);
7327                         if (cancel_pagedep(pagedep, freeblks, off)) {
7328                                 FREE_LOCK(ump);
7329                                 return (ERESTART);
7330                         }
7331                         continue;
7332
7333                 case D_ALLOCINDIR:
7334                         /*
7335                          * Simply remove the allocindir, we'll find it via
7336                          * the indirdep where we can clear pointers if
7337                          * needed.
7338                          */
7339                         WORKLIST_REMOVE(wk);
7340                         continue;
7341
7342                 case D_FREEWORK:
7343                         /*
7344                          * A truncation is waiting for the zero'd pointers
7345                          * to be written.  It can be freed when the freeblks
7346                          * is journaled.
7347                          */
7348                         WORKLIST_REMOVE(wk);
7349                         wk->wk_state |= ONDEPLIST;
7350                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7351                         break;
7352
7353                 case D_ALLOCDIRECT:
7354                         if (off != 0)
7355                                 continue;
7356                         /* FALLTHROUGH */
7357                 default:
7358                         panic("deallocate_dependencies: Unexpected type %s",
7359                             TYPENAME(wk->wk_type));
7360                         /* NOTREACHED */
7361                 }
7362         }
7363         FREE_LOCK(ump);
7364 done:
7365         /*
7366          * Don't throw away this buf, we were partially truncating and
7367          * some deps may always remain.
7368          */
7369         if (off) {
7370                 allocbuf(bp, off);
7371                 bp->b_vflags |= BV_SCANNED;
7372                 return (EBUSY);
7373         }
7374         bp->b_flags |= B_INVAL | B_NOCACHE;
7375
7376         return (0);
7377 }
7378
7379 /*
7380  * An allocdirect is being canceled due to a truncate.  We must make sure
7381  * the journal entry is released in concert with the blkfree that releases
7382  * the storage.  Completed journal entries must not be released until the
7383  * space is no longer pointed to by the inode or in the bitmap.
7384  */
7385 static void
7386 cancel_allocdirect(adphead, adp, freeblks)
7387         struct allocdirectlst *adphead;
7388         struct allocdirect *adp;
7389         struct freeblks *freeblks;
7390 {
7391         struct freework *freework;
7392         struct newblk *newblk;
7393         struct worklist *wk;
7394
7395         TAILQ_REMOVE(adphead, adp, ad_next);
7396         newblk = (struct newblk *)adp;
7397         freework = NULL;
7398         /*
7399          * Find the correct freework structure.
7400          */
7401         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7402                 if (wk->wk_type != D_FREEWORK)
7403                         continue;
7404                 freework = WK_FREEWORK(wk);
7405                 if (freework->fw_blkno == newblk->nb_newblkno)
7406                         break;
7407         }
7408         if (freework == NULL)
7409                 panic("cancel_allocdirect: Freework not found");
7410         /*
7411          * If a newblk exists at all we still have the journal entry that
7412          * initiated the allocation so we do not need to journal the free.
7413          */
7414         cancel_jfreeblk(freeblks, freework->fw_blkno);
7415         /*
7416          * If the journal hasn't been written the jnewblk must be passed
7417          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7418          * this by linking the journal dependency into the freework to be
7419          * freed when freework_freeblock() is called.  If the journal has
7420          * been written we can simply reclaim the journal space when the
7421          * freeblks work is complete.
7422          */
7423         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7424             &freeblks->fb_jwork);
7425         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7426 }
7427
7428
7429 /*
7430  * Cancel a new block allocation.  May be an indirect or direct block.  We
7431  * remove it from various lists and return any journal record that needs to
7432  * be resolved by the caller.
7433  *
7434  * A special consideration is made for indirects which were never pointed
7435  * at on disk and will never be found once this block is released.
7436  */
7437 static struct jnewblk *
7438 cancel_newblk(newblk, wk, wkhd)
7439         struct newblk *newblk;
7440         struct worklist *wk;
7441         struct workhead *wkhd;
7442 {
7443         struct jnewblk *jnewblk;
7444
7445         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7446             
7447         newblk->nb_state |= GOINGAWAY;
7448         /*
7449          * Previously we traversed the completedhd on each indirdep
7450          * attached to this newblk to cancel them and gather journal
7451          * work.  Since we need only the oldest journal segment and
7452          * the lowest point on the tree will always have the oldest
7453          * journal segment we are free to release the segments
7454          * of any subordinates and may leave the indirdep list to
7455          * indirdep_complete() when this newblk is freed.
7456          */
7457         if (newblk->nb_state & ONDEPLIST) {
7458                 newblk->nb_state &= ~ONDEPLIST;
7459                 LIST_REMOVE(newblk, nb_deps);
7460         }
7461         if (newblk->nb_state & ONWORKLIST)
7462                 WORKLIST_REMOVE(&newblk->nb_list);
7463         /*
7464          * If the journal entry hasn't been written we save a pointer to
7465          * the dependency that frees it until it is written or the
7466          * superseding operation completes.
7467          */
7468         jnewblk = newblk->nb_jnewblk;
7469         if (jnewblk != NULL && wk != NULL) {
7470                 newblk->nb_jnewblk = NULL;
7471                 jnewblk->jn_dep = wk;
7472         }
7473         if (!LIST_EMPTY(&newblk->nb_jwork))
7474                 jwork_move(wkhd, &newblk->nb_jwork);
7475         /*
7476          * When truncating we must free the newdirblk early to remove
7477          * the pagedep from the hash before returning.
7478          */
7479         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7480                 free_newdirblk(WK_NEWDIRBLK(wk));
7481         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7482                 panic("cancel_newblk: extra newdirblk");
7483
7484         return (jnewblk);
7485 }
7486
7487 /*
7488  * Schedule the freefrag associated with a newblk to be released once
7489  * the pointers are written and the previous block is no longer needed.
7490  */
7491 static void
7492 newblk_freefrag(newblk)
7493         struct newblk *newblk;
7494 {
7495         struct freefrag *freefrag;
7496
7497         if (newblk->nb_freefrag == NULL)
7498                 return;
7499         freefrag = newblk->nb_freefrag;
7500         newblk->nb_freefrag = NULL;
7501         freefrag->ff_state |= COMPLETE;
7502         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7503                 add_to_worklist(&freefrag->ff_list, 0);
7504 }
7505
7506 /*
7507  * Free a newblk. Generate a new freefrag work request if appropriate.
7508  * This must be called after the inode pointer and any direct block pointers
7509  * are valid or fully removed via truncate or frag extension.
7510  */
7511 static void
7512 free_newblk(newblk)
7513         struct newblk *newblk;
7514 {
7515         struct indirdep *indirdep;
7516         struct worklist *wk;
7517
7518         KASSERT(newblk->nb_jnewblk == NULL,
7519             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7520         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7521             ("free_newblk: unclaimed newblk"));
7522         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7523         newblk_freefrag(newblk);
7524         if (newblk->nb_state & ONDEPLIST)
7525                 LIST_REMOVE(newblk, nb_deps);
7526         if (newblk->nb_state & ONWORKLIST)
7527                 WORKLIST_REMOVE(&newblk->nb_list);
7528         LIST_REMOVE(newblk, nb_hash);
7529         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7530                 free_newdirblk(WK_NEWDIRBLK(wk));
7531         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7532                 panic("free_newblk: extra newdirblk");
7533         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7534                 indirdep_complete(indirdep);
7535         handle_jwork(&newblk->nb_jwork);
7536         WORKITEM_FREE(newblk, D_NEWBLK);
7537 }
7538
7539 /*
7540  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7541  */
7542 static void
7543 free_newdirblk(newdirblk)
7544         struct newdirblk *newdirblk;
7545 {
7546         struct pagedep *pagedep;
7547         struct diradd *dap;
7548         struct worklist *wk;
7549
7550         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7551         WORKLIST_REMOVE(&newdirblk->db_list);
7552         /*
7553          * If the pagedep is still linked onto the directory buffer
7554          * dependency chain, then some of the entries on the
7555          * pd_pendinghd list may not be committed to disk yet. In
7556          * this case, we will simply clear the NEWBLOCK flag and
7557          * let the pd_pendinghd list be processed when the pagedep
7558          * is next written. If the pagedep is no longer on the buffer
7559          * dependency chain, then all the entries on the pd_pending
7560          * list are committed to disk and we can free them here.
7561          */
7562         pagedep = newdirblk->db_pagedep;
7563         pagedep->pd_state &= ~NEWBLOCK;
7564         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7565                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7566                         free_diradd(dap, NULL);
7567                 /*
7568                  * If no dependencies remain, the pagedep will be freed.
7569                  */
7570                 free_pagedep(pagedep);
7571         }
7572         /* Should only ever be one item in the list. */
7573         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7574                 WORKLIST_REMOVE(wk);
7575                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7576         }
7577         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7578 }
7579
7580 /*
7581  * Prepare an inode to be freed. The actual free operation is not
7582  * done until the zero'ed inode has been written to disk.
7583  */
7584 void
7585 softdep_freefile(pvp, ino, mode)
7586         struct vnode *pvp;
7587         ino_t ino;
7588         int mode;
7589 {
7590         struct inode *ip = VTOI(pvp);
7591         struct inodedep *inodedep;
7592         struct freefile *freefile;
7593         struct freeblks *freeblks;
7594         struct ufsmount *ump;
7595
7596         ump = ITOUMP(ip);
7597         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7598             ("softdep_freefile called on non-softdep filesystem"));
7599         /*
7600          * This sets up the inode de-allocation dependency.
7601          */
7602         freefile = malloc(sizeof(struct freefile),
7603                 M_FREEFILE, M_SOFTDEP_FLAGS);
7604         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7605         freefile->fx_mode = mode;
7606         freefile->fx_oldinum = ino;
7607         freefile->fx_devvp = ump->um_devvp;
7608         LIST_INIT(&freefile->fx_jwork);
7609         UFS_LOCK(ump);
7610         ump->um_fs->fs_pendinginodes += 1;
7611         UFS_UNLOCK(ump);
7612
7613         /*
7614          * If the inodedep does not exist, then the zero'ed inode has
7615          * been written to disk. If the allocated inode has never been
7616          * written to disk, then the on-disk inode is zero'ed. In either
7617          * case we can free the file immediately.  If the journal was
7618          * canceled before being written the inode will never make it to
7619          * disk and we must send the canceled journal entrys to
7620          * ffs_freefile() to be cleared in conjunction with the bitmap.
7621          * Any blocks waiting on the inode to write can be safely freed
7622          * here as it will never been written.
7623          */
7624         ACQUIRE_LOCK(ump);
7625         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7626         if (inodedep) {
7627                 /*
7628                  * Clear out freeblks that no longer need to reference
7629                  * this inode.
7630                  */
7631                 while ((freeblks =
7632                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7633                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7634                             fb_next);
7635                         freeblks->fb_state &= ~ONDEPLIST;
7636                 }
7637                 /*
7638                  * Remove this inode from the unlinked list.
7639                  */
7640                 if (inodedep->id_state & UNLINKED) {
7641                         /*
7642                          * Save the journal work to be freed with the bitmap
7643                          * before we clear UNLINKED.  Otherwise it can be lost
7644                          * if the inode block is written.
7645                          */
7646                         handle_bufwait(inodedep, &freefile->fx_jwork);
7647                         clear_unlinked_inodedep(inodedep);
7648                         /*
7649                          * Re-acquire inodedep as we've dropped the
7650                          * per-filesystem lock in clear_unlinked_inodedep().
7651                          */
7652                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7653                 }
7654         }
7655         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7656                 FREE_LOCK(ump);
7657                 handle_workitem_freefile(freefile);
7658                 return;
7659         }
7660         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7661                 inodedep->id_state |= GOINGAWAY;
7662         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7663         FREE_LOCK(ump);
7664         if (ip->i_number == ino)
7665                 ip->i_flag |= IN_MODIFIED;
7666 }
7667
7668 /*
7669  * Check to see if an inode has never been written to disk. If
7670  * so free the inodedep and return success, otherwise return failure.
7671  *
7672  * If we still have a bitmap dependency, then the inode has never
7673  * been written to disk. Drop the dependency as it is no longer
7674  * necessary since the inode is being deallocated. We set the
7675  * ALLCOMPLETE flags since the bitmap now properly shows that the
7676  * inode is not allocated. Even if the inode is actively being
7677  * written, it has been rolled back to its zero'ed state, so we
7678  * are ensured that a zero inode is what is on the disk. For short
7679  * lived files, this change will usually result in removing all the
7680  * dependencies from the inode so that it can be freed immediately.
7681  */
7682 static int
7683 check_inode_unwritten(inodedep)
7684         struct inodedep *inodedep;
7685 {
7686
7687         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7688
7689         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7690             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7691             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7692             !LIST_EMPTY(&inodedep->id_bufwait) ||
7693             !LIST_EMPTY(&inodedep->id_inowait) ||
7694             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7695             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7696             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7697             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7698             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7699             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7700             inodedep->id_mkdiradd != NULL || 
7701             inodedep->id_nlinkdelta != 0)
7702                 return (0);
7703         /*
7704          * Another process might be in initiate_write_inodeblock_ufs[12]
7705          * trying to allocate memory without holding "Softdep Lock".
7706          */
7707         if ((inodedep->id_state & IOSTARTED) != 0 &&
7708             inodedep->id_savedino1 == NULL)
7709                 return (0);
7710
7711         if (inodedep->id_state & ONDEPLIST)
7712                 LIST_REMOVE(inodedep, id_deps);
7713         inodedep->id_state &= ~ONDEPLIST;
7714         inodedep->id_state |= ALLCOMPLETE;
7715         inodedep->id_bmsafemap = NULL;
7716         if (inodedep->id_state & ONWORKLIST)
7717                 WORKLIST_REMOVE(&inodedep->id_list);
7718         if (inodedep->id_savedino1 != NULL) {
7719                 free(inodedep->id_savedino1, M_SAVEDINO);
7720                 inodedep->id_savedino1 = NULL;
7721         }
7722         if (free_inodedep(inodedep) == 0)
7723                 panic("check_inode_unwritten: busy inode");
7724         return (1);
7725 }
7726
7727 static int
7728 check_inodedep_free(inodedep)
7729         struct inodedep *inodedep;
7730 {
7731
7732         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7733         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7734             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7735             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7736             !LIST_EMPTY(&inodedep->id_bufwait) ||
7737             !LIST_EMPTY(&inodedep->id_inowait) ||
7738             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7739             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7740             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7741             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7742             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7743             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7744             inodedep->id_mkdiradd != NULL ||
7745             inodedep->id_nlinkdelta != 0 ||
7746             inodedep->id_savedino1 != NULL)
7747                 return (0);
7748         return (1);
7749 }
7750
7751 /*
7752  * Try to free an inodedep structure. Return 1 if it could be freed.
7753  */
7754 static int
7755 free_inodedep(inodedep)
7756         struct inodedep *inodedep;
7757 {
7758
7759         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7760         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7761             !check_inodedep_free(inodedep))
7762                 return (0);
7763         if (inodedep->id_state & ONDEPLIST)
7764                 LIST_REMOVE(inodedep, id_deps);
7765         LIST_REMOVE(inodedep, id_hash);
7766         WORKITEM_FREE(inodedep, D_INODEDEP);
7767         return (1);
7768 }
7769
7770 /*
7771  * Free the block referenced by a freework structure.  The parent freeblks
7772  * structure is released and completed when the final cg bitmap reaches
7773  * the disk.  This routine may be freeing a jnewblk which never made it to
7774  * disk in which case we do not have to wait as the operation is undone
7775  * in memory immediately.
7776  */
7777 static void
7778 freework_freeblock(freework, key)
7779         struct freework *freework;
7780         u_long key;
7781 {
7782         struct freeblks *freeblks;
7783         struct jnewblk *jnewblk;
7784         struct ufsmount *ump;
7785         struct workhead wkhd;
7786         struct fs *fs;
7787         int bsize;
7788         int needj;
7789
7790         ump = VFSTOUFS(freework->fw_list.wk_mp);
7791         LOCK_OWNED(ump);
7792         /*
7793          * Handle partial truncate separately.
7794          */
7795         if (freework->fw_indir) {
7796                 complete_trunc_indir(freework);
7797                 return;
7798         }
7799         freeblks = freework->fw_freeblks;
7800         fs = ump->um_fs;
7801         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7802         bsize = lfragtosize(fs, freework->fw_frags);
7803         LIST_INIT(&wkhd);
7804         /*
7805          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7806          * on the indirblk hashtable and prevents premature freeing.
7807          */
7808         freework->fw_state |= DEPCOMPLETE;
7809         /*
7810          * SUJ needs to wait for the segment referencing freed indirect
7811          * blocks to expire so that we know the checker will not confuse
7812          * a re-allocated indirect block with its old contents.
7813          */
7814         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7815                 indirblk_insert(freework);
7816         /*
7817          * If we are canceling an existing jnewblk pass it to the free
7818          * routine, otherwise pass the freeblk which will ultimately
7819          * release the freeblks.  If we're not journaling, we can just
7820          * free the freeblks immediately.
7821          */
7822         jnewblk = freework->fw_jnewblk;
7823         if (jnewblk != NULL) {
7824                 cancel_jnewblk(jnewblk, &wkhd);
7825                 needj = 0;
7826         } else if (needj) {
7827                 freework->fw_state |= DELAYEDFREE;
7828                 freeblks->fb_cgwait++;
7829                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7830         }
7831         FREE_LOCK(ump);
7832         freeblks_free(ump, freeblks, btodb(bsize));
7833         CTR4(KTR_SUJ,
7834             "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7835             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7836         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7837             freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7838         ACQUIRE_LOCK(ump);
7839         /*
7840          * The jnewblk will be discarded and the bits in the map never
7841          * made it to disk.  We can immediately free the freeblk.
7842          */
7843         if (needj == 0)
7844                 handle_written_freework(freework);
7845 }
7846
7847 /*
7848  * We enqueue freework items that need processing back on the freeblks and
7849  * add the freeblks to the worklist.  This makes it easier to find all work
7850  * required to flush a truncation in process_truncates().
7851  */
7852 static void
7853 freework_enqueue(freework)
7854         struct freework *freework;
7855 {
7856         struct freeblks *freeblks;
7857
7858         freeblks = freework->fw_freeblks;
7859         if ((freework->fw_state & INPROGRESS) == 0)
7860                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7861         if ((freeblks->fb_state &
7862             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7863             LIST_EMPTY(&freeblks->fb_jblkdephd))
7864                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7865 }
7866
7867 /*
7868  * Start, continue, or finish the process of freeing an indirect block tree.
7869  * The free operation may be paused at any point with fw_off containing the
7870  * offset to restart from.  This enables us to implement some flow control
7871  * for large truncates which may fan out and generate a huge number of
7872  * dependencies.
7873  */
7874 static void
7875 handle_workitem_indirblk(freework)
7876         struct freework *freework;
7877 {
7878         struct freeblks *freeblks;
7879         struct ufsmount *ump;
7880         struct fs *fs;
7881
7882         freeblks = freework->fw_freeblks;
7883         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7884         fs = ump->um_fs;
7885         if (freework->fw_state & DEPCOMPLETE) {
7886                 handle_written_freework(freework);
7887                 return;
7888         }
7889         if (freework->fw_off == NINDIR(fs)) {
7890                 freework_freeblock(freework, SINGLETON_KEY);
7891                 return;
7892         }
7893         freework->fw_state |= INPROGRESS;
7894         FREE_LOCK(ump);
7895         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7896             freework->fw_lbn);
7897         ACQUIRE_LOCK(ump);
7898 }
7899
7900 /*
7901  * Called when a freework structure attached to a cg buf is written.  The
7902  * ref on either the parent or the freeblks structure is released and
7903  * the freeblks is added back to the worklist if there is more work to do.
7904  */
7905 static void
7906 handle_written_freework(freework)
7907         struct freework *freework;
7908 {
7909         struct freeblks *freeblks;
7910         struct freework *parent;
7911
7912         freeblks = freework->fw_freeblks;
7913         parent = freework->fw_parent;
7914         if (freework->fw_state & DELAYEDFREE)
7915                 freeblks->fb_cgwait--;
7916         freework->fw_state |= COMPLETE;
7917         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7918                 WORKITEM_FREE(freework, D_FREEWORK);
7919         if (parent) {
7920                 if (--parent->fw_ref == 0)
7921                         freework_enqueue(parent);
7922                 return;
7923         }
7924         if (--freeblks->fb_ref != 0)
7925                 return;
7926         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7927             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7928                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7929 }
7930
7931 /*
7932  * This workitem routine performs the block de-allocation.
7933  * The workitem is added to the pending list after the updated
7934  * inode block has been written to disk.  As mentioned above,
7935  * checks regarding the number of blocks de-allocated (compared
7936  * to the number of blocks allocated for the file) are also
7937  * performed in this function.
7938  */
7939 static int
7940 handle_workitem_freeblocks(freeblks, flags)
7941         struct freeblks *freeblks;
7942         int flags;
7943 {
7944         struct freework *freework;
7945         struct newblk *newblk;
7946         struct allocindir *aip;
7947         struct ufsmount *ump;
7948         struct worklist *wk;
7949         u_long key;
7950
7951         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7952             ("handle_workitem_freeblocks: Journal entries not written."));
7953         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7954         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7955         ACQUIRE_LOCK(ump);
7956         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7957                 WORKLIST_REMOVE(wk);
7958                 switch (wk->wk_type) {
7959                 case D_DIRREM:
7960                         wk->wk_state |= COMPLETE;
7961                         add_to_worklist(wk, 0);
7962                         continue;
7963
7964                 case D_ALLOCDIRECT:
7965                         free_newblk(WK_NEWBLK(wk));
7966                         continue;
7967
7968                 case D_ALLOCINDIR:
7969                         aip = WK_ALLOCINDIR(wk);
7970                         freework = NULL;
7971                         if (aip->ai_state & DELAYEDFREE) {
7972                                 FREE_LOCK(ump);
7973                                 freework = newfreework(ump, freeblks, NULL,
7974                                     aip->ai_lbn, aip->ai_newblkno,
7975                                     ump->um_fs->fs_frag, 0, 0);
7976                                 ACQUIRE_LOCK(ump);
7977                         }
7978                         newblk = WK_NEWBLK(wk);
7979                         if (newblk->nb_jnewblk) {
7980                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7981                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7982                                 newblk->nb_jnewblk = NULL;
7983                         }
7984                         free_newblk(newblk);
7985                         continue;
7986
7987                 case D_FREEWORK:
7988                         freework = WK_FREEWORK(wk);
7989                         if (freework->fw_lbn <= -UFS_NDADDR)
7990                                 handle_workitem_indirblk(freework);
7991                         else
7992                                 freework_freeblock(freework, key);
7993                         continue;
7994                 default:
7995                         panic("handle_workitem_freeblocks: Unknown type %s",
7996                             TYPENAME(wk->wk_type));
7997                 }
7998         }
7999         if (freeblks->fb_ref != 0) {
8000                 freeblks->fb_state &= ~INPROGRESS;
8001                 wake_worklist(&freeblks->fb_list);
8002                 freeblks = NULL;
8003         }
8004         FREE_LOCK(ump);
8005         ffs_blkrelease_finish(ump, key);
8006         if (freeblks)
8007                 return handle_complete_freeblocks(freeblks, flags);
8008         return (0);
8009 }
8010
8011 /*
8012  * Handle completion of block free via truncate.  This allows fs_pending
8013  * to track the actual free block count more closely than if we only updated
8014  * it at the end.  We must be careful to handle cases where the block count
8015  * on free was incorrect.
8016  */
8017 static void
8018 freeblks_free(ump, freeblks, blocks)
8019         struct ufsmount *ump;
8020         struct freeblks *freeblks;
8021         int blocks;
8022 {
8023         struct fs *fs;
8024         ufs2_daddr_t remain;
8025
8026         UFS_LOCK(ump);
8027         remain = -freeblks->fb_chkcnt;
8028         freeblks->fb_chkcnt += blocks;
8029         if (remain > 0) {
8030                 if (remain < blocks)
8031                         blocks = remain;
8032                 fs = ump->um_fs;
8033                 fs->fs_pendingblocks -= blocks;
8034         }
8035         UFS_UNLOCK(ump);
8036 }
8037
8038 /*
8039  * Once all of the freework workitems are complete we can retire the
8040  * freeblocks dependency and any journal work awaiting completion.  This
8041  * can not be called until all other dependencies are stable on disk.
8042  */
8043 static int
8044 handle_complete_freeblocks(freeblks, flags)
8045         struct freeblks *freeblks;
8046         int flags;
8047 {
8048         struct inodedep *inodedep;
8049         struct inode *ip;
8050         struct vnode *vp;
8051         struct fs *fs;
8052         struct ufsmount *ump;
8053         ufs2_daddr_t spare;
8054
8055         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8056         fs = ump->um_fs;
8057         flags = LK_EXCLUSIVE | flags;
8058         spare = freeblks->fb_chkcnt;
8059
8060         /*
8061          * If we did not release the expected number of blocks we may have
8062          * to adjust the inode block count here.  Only do so if it wasn't
8063          * a truncation to zero and the modrev still matches.
8064          */
8065         if (spare && freeblks->fb_len != 0) {
8066                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8067                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8068                         return (EBUSY);
8069                 ip = VTOI(vp);
8070                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8071                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8072                         ip->i_flag |= IN_CHANGE;
8073                         /*
8074                          * We must wait so this happens before the
8075                          * journal is reclaimed.
8076                          */
8077                         ffs_update(vp, 1);
8078                 }
8079                 vput(vp);
8080         }
8081         if (spare < 0) {
8082                 UFS_LOCK(ump);
8083                 fs->fs_pendingblocks += spare;
8084                 UFS_UNLOCK(ump);
8085         }
8086 #ifdef QUOTA
8087         /* Handle spare. */
8088         if (spare)
8089                 quotaadj(freeblks->fb_quota, ump, -spare);
8090         quotarele(freeblks->fb_quota);
8091 #endif
8092         ACQUIRE_LOCK(ump);
8093         if (freeblks->fb_state & ONDEPLIST) {
8094                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8095                     0, &inodedep);
8096                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8097                 freeblks->fb_state &= ~ONDEPLIST;
8098                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8099                         free_inodedep(inodedep);
8100         }
8101         /*
8102          * All of the freeblock deps must be complete prior to this call
8103          * so it's now safe to complete earlier outstanding journal entries.
8104          */
8105         handle_jwork(&freeblks->fb_jwork);
8106         WORKITEM_FREE(freeblks, D_FREEBLKS);
8107         FREE_LOCK(ump);
8108         return (0);
8109 }
8110
8111 /*
8112  * Release blocks associated with the freeblks and stored in the indirect
8113  * block dbn. If level is greater than SINGLE, the block is an indirect block
8114  * and recursive calls to indirtrunc must be used to cleanse other indirect
8115  * blocks.
8116  *
8117  * This handles partial and complete truncation of blocks.  Partial is noted
8118  * with goingaway == 0.  In this case the freework is completed after the
8119  * zero'd indirects are written to disk.  For full truncation the freework
8120  * is completed after the block is freed.
8121  */
8122 static void
8123 indir_trunc(freework, dbn, lbn)
8124         struct freework *freework;
8125         ufs2_daddr_t dbn;
8126         ufs_lbn_t lbn;
8127 {
8128         struct freework *nfreework;
8129         struct workhead wkhd;
8130         struct freeblks *freeblks;
8131         struct buf *bp;
8132         struct fs *fs;
8133         struct indirdep *indirdep;
8134         struct mount *mp;
8135         struct ufsmount *ump;
8136         ufs1_daddr_t *bap1;
8137         ufs2_daddr_t nb, nnb, *bap2;
8138         ufs_lbn_t lbnadd, nlbn;
8139         u_long key;
8140         int nblocks, ufs1fmt, freedblocks;
8141         int goingaway, freedeps, needj, level, cnt, i;
8142
8143         freeblks = freework->fw_freeblks;
8144         mp = freeblks->fb_list.wk_mp;
8145         ump = VFSTOUFS(mp);
8146         fs = ump->um_fs;
8147         /*
8148          * Get buffer of block pointers to be freed.  There are three cases:
8149          * 
8150          * 1) Partial truncate caches the indirdep pointer in the freework
8151          *    which provides us a back copy to the save bp which holds the
8152          *    pointers we want to clear.  When this completes the zero
8153          *    pointers are written to the real copy.
8154          * 2) The indirect is being completely truncated, cancel_indirdep()
8155          *    eliminated the real copy and placed the indirdep on the saved
8156          *    copy.  The indirdep and buf are discarded when this completes.
8157          * 3) The indirect was not in memory, we read a copy off of the disk
8158          *    using the devvp and drop and invalidate the buffer when we're
8159          *    done.
8160          */
8161         goingaway = 1;
8162         indirdep = NULL;
8163         if (freework->fw_indir != NULL) {
8164                 goingaway = 0;
8165                 indirdep = freework->fw_indir;
8166                 bp = indirdep->ir_savebp;
8167                 if (bp == NULL || bp->b_blkno != dbn)
8168                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8169                             bp, (intmax_t)dbn);
8170         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8171                 /*
8172                  * The lock prevents the buf dep list from changing and
8173                  * indirects on devvp should only ever have one dependency.
8174                  */
8175                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8176                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8177                         panic("indir_trunc: Bad indirdep %p from buf %p",
8178                             indirdep, bp);
8179         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8180             NOCRED, &bp) != 0) {
8181                 brelse(bp);
8182                 return;
8183         }
8184         ACQUIRE_LOCK(ump);
8185         /* Protects against a race with complete_trunc_indir(). */
8186         freework->fw_state &= ~INPROGRESS;
8187         /*
8188          * If we have an indirdep we need to enforce the truncation order
8189          * and discard it when it is complete.
8190          */
8191         if (indirdep) {
8192                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8193                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8194                         /*
8195                          * Add the complete truncate to the list on the
8196                          * indirdep to enforce in-order processing.
8197                          */
8198                         if (freework->fw_indir == NULL)
8199                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8200                                     freework, fw_next);
8201                         FREE_LOCK(ump);
8202                         return;
8203                 }
8204                 /*
8205                  * If we're goingaway, free the indirdep.  Otherwise it will
8206                  * linger until the write completes.
8207                  */
8208                 if (goingaway)
8209                         free_indirdep(indirdep);
8210         }
8211         FREE_LOCK(ump);
8212         /* Initialize pointers depending on block size. */
8213         if (ump->um_fstype == UFS1) {
8214                 bap1 = (ufs1_daddr_t *)bp->b_data;
8215                 nb = bap1[freework->fw_off];
8216                 ufs1fmt = 1;
8217                 bap2 = NULL;
8218         } else {
8219                 bap2 = (ufs2_daddr_t *)bp->b_data;
8220                 nb = bap2[freework->fw_off];
8221                 ufs1fmt = 0;
8222                 bap1 = NULL;
8223         }
8224         level = lbn_level(lbn);
8225         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8226         lbnadd = lbn_offset(fs, level);
8227         nblocks = btodb(fs->fs_bsize);
8228         nfreework = freework;
8229         freedeps = 0;
8230         cnt = 0;
8231         /*
8232          * Reclaim blocks.  Traverses into nested indirect levels and
8233          * arranges for the current level to be freed when subordinates
8234          * are free when journaling.
8235          */
8236         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8237         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8238                 if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8239                     fs->fs_bsize) != 0)
8240                         nb = 0;
8241                 if (i != NINDIR(fs) - 1) {
8242                         if (ufs1fmt)
8243                                 nnb = bap1[i+1];
8244                         else
8245                                 nnb = bap2[i+1];
8246                 } else
8247                         nnb = 0;
8248                 if (nb == 0)
8249                         continue;
8250                 cnt++;
8251                 if (level != 0) {
8252                         nlbn = (lbn + 1) - (i * lbnadd);
8253                         if (needj != 0) {
8254                                 nfreework = newfreework(ump, freeblks, freework,
8255                                     nlbn, nb, fs->fs_frag, 0, 0);
8256                                 freedeps++;
8257                         }
8258                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8259                 } else {
8260                         struct freedep *freedep;
8261
8262                         /*
8263                          * Attempt to aggregate freedep dependencies for
8264                          * all blocks being released to the same CG.
8265                          */
8266                         LIST_INIT(&wkhd);
8267                         if (needj != 0 &&
8268                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8269                                 freedep = newfreedep(freework);
8270                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8271                                     &freedep->fd_list);
8272                                 freedeps++;
8273                         }
8274                         CTR3(KTR_SUJ,
8275                             "indir_trunc: ino %jd blkno %jd size %d",
8276                             freeblks->fb_inum, nb, fs->fs_bsize);
8277                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8278                             fs->fs_bsize, freeblks->fb_inum,
8279                             freeblks->fb_vtype, &wkhd, key);
8280                 }
8281         }
8282         ffs_blkrelease_finish(ump, key);
8283         if (goingaway) {
8284                 bp->b_flags |= B_INVAL | B_NOCACHE;
8285                 brelse(bp);
8286         }
8287         freedblocks = 0;
8288         if (level == 0)
8289                 freedblocks = (nblocks * cnt);
8290         if (needj == 0)
8291                 freedblocks += nblocks;
8292         freeblks_free(ump, freeblks, freedblocks);
8293         /*
8294          * If we are journaling set up the ref counts and offset so this
8295          * indirect can be completed when its children are free.
8296          */
8297         if (needj) {
8298                 ACQUIRE_LOCK(ump);
8299                 freework->fw_off = i;
8300                 freework->fw_ref += freedeps;
8301                 freework->fw_ref -= NINDIR(fs) + 1;
8302                 if (level == 0)
8303                         freeblks->fb_cgwait += freedeps;
8304                 if (freework->fw_ref == 0)
8305                         freework_freeblock(freework, SINGLETON_KEY);
8306                 FREE_LOCK(ump);
8307                 return;
8308         }
8309         /*
8310          * If we're not journaling we can free the indirect now.
8311          */
8312         dbn = dbtofsb(fs, dbn);
8313         CTR3(KTR_SUJ,
8314             "indir_trunc 2: ino %jd blkno %jd size %d",
8315             freeblks->fb_inum, dbn, fs->fs_bsize);
8316         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8317             freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8318         /* Non SUJ softdep does single-threaded truncations. */
8319         if (freework->fw_blkno == dbn) {
8320                 freework->fw_state |= ALLCOMPLETE;
8321                 ACQUIRE_LOCK(ump);
8322                 handle_written_freework(freework);
8323                 FREE_LOCK(ump);
8324         }
8325         return;
8326 }
8327
8328 /*
8329  * Cancel an allocindir when it is removed via truncation.  When bp is not
8330  * NULL the indirect never appeared on disk and is scheduled to be freed
8331  * independently of the indir so we can more easily track journal work.
8332  */
8333 static void
8334 cancel_allocindir(aip, bp, freeblks, trunc)
8335         struct allocindir *aip;
8336         struct buf *bp;
8337         struct freeblks *freeblks;
8338         int trunc;
8339 {
8340         struct indirdep *indirdep;
8341         struct freefrag *freefrag;
8342         struct newblk *newblk;
8343
8344         newblk = (struct newblk *)aip;
8345         LIST_REMOVE(aip, ai_next);
8346         /*
8347          * We must eliminate the pointer in bp if it must be freed on its
8348          * own due to partial truncate or pending journal work.
8349          */
8350         if (bp && (trunc || newblk->nb_jnewblk)) {
8351                 /*
8352                  * Clear the pointer and mark the aip to be freed
8353                  * directly if it never existed on disk.
8354                  */
8355                 aip->ai_state |= DELAYEDFREE;
8356                 indirdep = aip->ai_indirdep;
8357                 if (indirdep->ir_state & UFS1FMT)
8358                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8359                 else
8360                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8361         }
8362         /*
8363          * When truncating the previous pointer will be freed via
8364          * savedbp.  Eliminate the freefrag which would dup free.
8365          */
8366         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8367                 newblk->nb_freefrag = NULL;
8368                 if (freefrag->ff_jdep)
8369                         cancel_jfreefrag(
8370                             WK_JFREEFRAG(freefrag->ff_jdep));
8371                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8372                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8373         }
8374         /*
8375          * If the journal hasn't been written the jnewblk must be passed
8376          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8377          * this by leaving the journal dependency on the newblk to be freed
8378          * when a freework is created in handle_workitem_freeblocks().
8379          */
8380         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8381         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8382 }
8383
8384 /*
8385  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8386  * in to a newdirblk so any subsequent additions are tracked properly.  The
8387  * caller is responsible for adding the mkdir1 dependency to the journal
8388  * and updating id_mkdiradd.  This function returns with the per-filesystem
8389  * lock held.
8390  */
8391 static struct mkdir *
8392 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8393         struct diradd *dap;
8394         ino_t newinum;
8395         ino_t dinum;
8396         struct buf *newdirbp;
8397         struct mkdir **mkdirp;
8398 {
8399         struct newblk *newblk;
8400         struct pagedep *pagedep;
8401         struct inodedep *inodedep;
8402         struct newdirblk *newdirblk;
8403         struct mkdir *mkdir1, *mkdir2;
8404         struct worklist *wk;
8405         struct jaddref *jaddref;
8406         struct ufsmount *ump;
8407         struct mount *mp;
8408
8409         mp = dap->da_list.wk_mp;
8410         ump = VFSTOUFS(mp);
8411         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8412             M_SOFTDEP_FLAGS);
8413         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8414         LIST_INIT(&newdirblk->db_mkdir);
8415         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8416         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8417         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8418         mkdir1->md_diradd = dap;
8419         mkdir1->md_jaddref = NULL;
8420         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8421         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8422         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8423         mkdir2->md_diradd = dap;
8424         mkdir2->md_jaddref = NULL;
8425         if (MOUNTEDSUJ(mp) == 0) {
8426                 mkdir1->md_state |= DEPCOMPLETE;
8427                 mkdir2->md_state |= DEPCOMPLETE;
8428         }
8429         /*
8430          * Dependency on "." and ".." being written to disk.
8431          */
8432         mkdir1->md_buf = newdirbp;
8433         ACQUIRE_LOCK(VFSTOUFS(mp));
8434         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8435         /*
8436          * We must link the pagedep, allocdirect, and newdirblk for
8437          * the initial file page so the pointer to the new directory
8438          * is not written until the directory contents are live and
8439          * any subsequent additions are not marked live until the
8440          * block is reachable via the inode.
8441          */
8442         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8443                 panic("setup_newdir: lost pagedep");
8444         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8445                 if (wk->wk_type == D_ALLOCDIRECT)
8446                         break;
8447         if (wk == NULL)
8448                 panic("setup_newdir: lost allocdirect");
8449         if (pagedep->pd_state & NEWBLOCK)
8450                 panic("setup_newdir: NEWBLOCK already set");
8451         newblk = WK_NEWBLK(wk);
8452         pagedep->pd_state |= NEWBLOCK;
8453         pagedep->pd_newdirblk = newdirblk;
8454         newdirblk->db_pagedep = pagedep;
8455         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8456         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8457         /*
8458          * Look up the inodedep for the parent directory so that we
8459          * can link mkdir2 into the pending dotdot jaddref or
8460          * the inode write if there is none.  If the inode is
8461          * ALLCOMPLETE and no jaddref is present all dependencies have
8462          * been satisfied and mkdir2 can be freed.
8463          */
8464         inodedep_lookup(mp, dinum, 0, &inodedep);
8465         if (MOUNTEDSUJ(mp)) {
8466                 if (inodedep == NULL)
8467                         panic("setup_newdir: Lost parent.");
8468                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8469                     inoreflst);
8470                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8471                     (jaddref->ja_state & MKDIR_PARENT),
8472                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8473                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8474                 mkdir2->md_jaddref = jaddref;
8475                 jaddref->ja_mkdir = mkdir2;
8476         } else if (inodedep == NULL ||
8477             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8478                 dap->da_state &= ~MKDIR_PARENT;
8479                 WORKITEM_FREE(mkdir2, D_MKDIR);
8480                 mkdir2 = NULL;
8481         } else {
8482                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8483                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8484         }
8485         *mkdirp = mkdir2;
8486
8487         return (mkdir1);
8488 }
8489
8490 /*
8491  * Directory entry addition dependencies.
8492  * 
8493  * When adding a new directory entry, the inode (with its incremented link
8494  * count) must be written to disk before the directory entry's pointer to it.
8495  * Also, if the inode is newly allocated, the corresponding freemap must be
8496  * updated (on disk) before the directory entry's pointer. These requirements
8497  * are met via undo/redo on the directory entry's pointer, which consists
8498  * simply of the inode number.
8499  * 
8500  * As directory entries are added and deleted, the free space within a
8501  * directory block can become fragmented.  The ufs filesystem will compact
8502  * a fragmented directory block to make space for a new entry. When this
8503  * occurs, the offsets of previously added entries change. Any "diradd"
8504  * dependency structures corresponding to these entries must be updated with
8505  * the new offsets.
8506  */
8507
8508 /*
8509  * This routine is called after the in-memory inode's link
8510  * count has been incremented, but before the directory entry's
8511  * pointer to the inode has been set.
8512  */
8513 int
8514 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8515         struct buf *bp;         /* buffer containing directory block */
8516         struct inode *dp;       /* inode for directory */
8517         off_t diroffset;        /* offset of new entry in directory */
8518         ino_t newinum;          /* inode referenced by new directory entry */
8519         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8520         int isnewblk;           /* entry is in a newly allocated block */
8521 {
8522         int offset;             /* offset of new entry within directory block */
8523         ufs_lbn_t lbn;          /* block in directory containing new entry */
8524         struct fs *fs;
8525         struct diradd *dap;
8526         struct newblk *newblk;
8527         struct pagedep *pagedep;
8528         struct inodedep *inodedep;
8529         struct newdirblk *newdirblk;
8530         struct mkdir *mkdir1, *mkdir2;
8531         struct jaddref *jaddref;
8532         struct ufsmount *ump;
8533         struct mount *mp;
8534         int isindir;
8535
8536         mp = ITOVFS(dp);
8537         ump = VFSTOUFS(mp);
8538         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8539             ("softdep_setup_directory_add called on non-softdep filesystem"));
8540         /*
8541          * Whiteouts have no dependencies.
8542          */
8543         if (newinum == UFS_WINO) {
8544                 if (newdirbp != NULL)
8545                         bdwrite(newdirbp);
8546                 return (0);
8547         }
8548         jaddref = NULL;
8549         mkdir1 = mkdir2 = NULL;
8550         fs = ump->um_fs;
8551         lbn = lblkno(fs, diroffset);
8552         offset = blkoff(fs, diroffset);
8553         dap = malloc(sizeof(struct diradd), M_DIRADD,
8554                 M_SOFTDEP_FLAGS|M_ZERO);
8555         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8556         dap->da_offset = offset;
8557         dap->da_newinum = newinum;
8558         dap->da_state = ATTACHED;
8559         LIST_INIT(&dap->da_jwork);
8560         isindir = bp->b_lblkno >= UFS_NDADDR;
8561         newdirblk = NULL;
8562         if (isnewblk &&
8563             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8564                 newdirblk = malloc(sizeof(struct newdirblk),
8565                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8566                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8567                 LIST_INIT(&newdirblk->db_mkdir);
8568         }
8569         /*
8570          * If we're creating a new directory setup the dependencies and set
8571          * the dap state to wait for them.  Otherwise it's COMPLETE and
8572          * we can move on.
8573          */
8574         if (newdirbp == NULL) {
8575                 dap->da_state |= DEPCOMPLETE;
8576                 ACQUIRE_LOCK(ump);
8577         } else {
8578                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8579                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8580                     &mkdir2);
8581         }
8582         /*
8583          * Link into parent directory pagedep to await its being written.
8584          */
8585         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8586 #ifdef INVARIANTS
8587         if (diradd_lookup(pagedep, offset) != NULL)
8588                 panic("softdep_setup_directory_add: %p already at off %d\n",
8589                     diradd_lookup(pagedep, offset), offset);
8590 #endif
8591         dap->da_pagedep = pagedep;
8592         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8593             da_pdlist);
8594         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8595         /*
8596          * If we're journaling, link the diradd into the jaddref so it
8597          * may be completed after the journal entry is written.  Otherwise,
8598          * link the diradd into its inodedep.  If the inode is not yet
8599          * written place it on the bufwait list, otherwise do the post-inode
8600          * write processing to put it on the id_pendinghd list.
8601          */
8602         if (MOUNTEDSUJ(mp)) {
8603                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8604                     inoreflst);
8605                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8606                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8607                 jaddref->ja_diroff = diroffset;
8608                 jaddref->ja_diradd = dap;
8609                 add_to_journal(&jaddref->ja_list);
8610         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8611                 diradd_inode_written(dap, inodedep);
8612         else
8613                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8614         /*
8615          * Add the journal entries for . and .. links now that the primary
8616          * link is written.
8617          */
8618         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8619                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8620                     inoreflst, if_deps);
8621                 KASSERT(jaddref != NULL &&
8622                     jaddref->ja_ino == jaddref->ja_parent &&
8623                     (jaddref->ja_state & MKDIR_BODY),
8624                     ("softdep_setup_directory_add: bad dot jaddref %p",
8625                     jaddref));
8626                 mkdir1->md_jaddref = jaddref;
8627                 jaddref->ja_mkdir = mkdir1;
8628                 /*
8629                  * It is important that the dotdot journal entry
8630                  * is added prior to the dot entry since dot writes
8631                  * both the dot and dotdot links.  These both must
8632                  * be added after the primary link for the journal
8633                  * to remain consistent.
8634                  */
8635                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8636                 add_to_journal(&jaddref->ja_list);
8637         }
8638         /*
8639          * If we are adding a new directory remember this diradd so that if
8640          * we rename it we can keep the dot and dotdot dependencies.  If
8641          * we are adding a new name for an inode that has a mkdiradd we
8642          * must be in rename and we have to move the dot and dotdot
8643          * dependencies to this new name.  The old name is being orphaned
8644          * soon.
8645          */
8646         if (mkdir1 != NULL) {
8647                 if (inodedep->id_mkdiradd != NULL)
8648                         panic("softdep_setup_directory_add: Existing mkdir");
8649                 inodedep->id_mkdiradd = dap;
8650         } else if (inodedep->id_mkdiradd)
8651                 merge_diradd(inodedep, dap);
8652         if (newdirblk != NULL) {
8653                 /*
8654                  * There is nothing to do if we are already tracking
8655                  * this block.
8656                  */
8657                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8658                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8659                         FREE_LOCK(ump);
8660                         return (0);
8661                 }
8662                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8663                     == 0)
8664                         panic("softdep_setup_directory_add: lost entry");
8665                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8666                 pagedep->pd_state |= NEWBLOCK;
8667                 pagedep->pd_newdirblk = newdirblk;
8668                 newdirblk->db_pagedep = pagedep;
8669                 FREE_LOCK(ump);
8670                 /*
8671                  * If we extended into an indirect signal direnter to sync.
8672                  */
8673                 if (isindir)
8674                         return (1);
8675                 return (0);
8676         }
8677         FREE_LOCK(ump);
8678         return (0);
8679 }
8680
8681 /*
8682  * This procedure is called to change the offset of a directory
8683  * entry when compacting a directory block which must be owned
8684  * exclusively by the caller. Note that the actual entry movement
8685  * must be done in this procedure to ensure that no I/O completions
8686  * occur while the move is in progress.
8687  */
8688 void 
8689 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8690         struct buf *bp;         /* Buffer holding directory block. */
8691         struct inode *dp;       /* inode for directory */
8692         caddr_t base;           /* address of dp->i_offset */
8693         caddr_t oldloc;         /* address of old directory location */
8694         caddr_t newloc;         /* address of new directory location */
8695         int entrysize;          /* size of directory entry */
8696 {
8697         int offset, oldoffset, newoffset;
8698         struct pagedep *pagedep;
8699         struct jmvref *jmvref;
8700         struct diradd *dap;
8701         struct direct *de;
8702         struct mount *mp;
8703         struct ufsmount *ump;
8704         ufs_lbn_t lbn;
8705         int flags;
8706
8707         mp = ITOVFS(dp);
8708         ump = VFSTOUFS(mp);
8709         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8710             ("softdep_change_directoryentry_offset called on "
8711              "non-softdep filesystem"));
8712         de = (struct direct *)oldloc;
8713         jmvref = NULL;
8714         flags = 0;
8715         /*
8716          * Moves are always journaled as it would be too complex to
8717          * determine if any affected adds or removes are present in the
8718          * journal.
8719          */
8720         if (MOUNTEDSUJ(mp)) {
8721                 flags = DEPALLOC;
8722                 jmvref = newjmvref(dp, de->d_ino,
8723                     dp->i_offset + (oldloc - base),
8724                     dp->i_offset + (newloc - base));
8725         }
8726         lbn = lblkno(ump->um_fs, dp->i_offset);
8727         offset = blkoff(ump->um_fs, dp->i_offset);
8728         oldoffset = offset + (oldloc - base);
8729         newoffset = offset + (newloc - base);
8730         ACQUIRE_LOCK(ump);
8731         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8732                 goto done;
8733         dap = diradd_lookup(pagedep, oldoffset);
8734         if (dap) {
8735                 dap->da_offset = newoffset;
8736                 newoffset = DIRADDHASH(newoffset);
8737                 oldoffset = DIRADDHASH(oldoffset);
8738                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8739                     newoffset != oldoffset) {
8740                         LIST_REMOVE(dap, da_pdlist);
8741                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8742                             dap, da_pdlist);
8743                 }
8744         }
8745 done:
8746         if (jmvref) {
8747                 jmvref->jm_pagedep = pagedep;
8748                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8749                 add_to_journal(&jmvref->jm_list);
8750         }
8751         bcopy(oldloc, newloc, entrysize);
8752         FREE_LOCK(ump);
8753 }
8754
8755 /*
8756  * Move the mkdir dependencies and journal work from one diradd to another
8757  * when renaming a directory.  The new name must depend on the mkdir deps
8758  * completing as the old name did.  Directories can only have one valid link
8759  * at a time so one must be canonical.
8760  */
8761 static void
8762 merge_diradd(inodedep, newdap)
8763         struct inodedep *inodedep;
8764         struct diradd *newdap;
8765 {
8766         struct diradd *olddap;
8767         struct mkdir *mkdir, *nextmd;
8768         struct ufsmount *ump;
8769         short state;
8770
8771         olddap = inodedep->id_mkdiradd;
8772         inodedep->id_mkdiradd = newdap;
8773         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8774                 newdap->da_state &= ~DEPCOMPLETE;
8775                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8776                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8777                      mkdir = nextmd) {
8778                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8779                         if (mkdir->md_diradd != olddap)
8780                                 continue;
8781                         mkdir->md_diradd = newdap;
8782                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8783                         newdap->da_state |= state;
8784                         olddap->da_state &= ~state;
8785                         if ((olddap->da_state &
8786                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8787                                 break;
8788                 }
8789                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8790                         panic("merge_diradd: unfound ref");
8791         }
8792         /*
8793          * Any mkdir related journal items are not safe to be freed until
8794          * the new name is stable.
8795          */
8796         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8797         olddap->da_state |= DEPCOMPLETE;
8798         complete_diradd(olddap);
8799 }
8800
8801 /*
8802  * Move the diradd to the pending list when all diradd dependencies are
8803  * complete.
8804  */
8805 static void
8806 complete_diradd(dap)
8807         struct diradd *dap;
8808 {
8809         struct pagedep *pagedep;
8810
8811         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8812                 if (dap->da_state & DIRCHG)
8813                         pagedep = dap->da_previous->dm_pagedep;
8814                 else
8815                         pagedep = dap->da_pagedep;
8816                 LIST_REMOVE(dap, da_pdlist);
8817                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8818         }
8819 }
8820
8821 /*
8822  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8823  * add entries and conditonally journal the remove.
8824  */
8825 static void
8826 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8827         struct diradd *dap;
8828         struct dirrem *dirrem;
8829         struct jremref *jremref;
8830         struct jremref *dotremref;
8831         struct jremref *dotdotremref;
8832 {
8833         struct inodedep *inodedep;
8834         struct jaddref *jaddref;
8835         struct inoref *inoref;
8836         struct ufsmount *ump;
8837         struct mkdir *mkdir;
8838
8839         /*
8840          * If no remove references were allocated we're on a non-journaled
8841          * filesystem and can skip the cancel step.
8842          */
8843         if (jremref == NULL) {
8844                 free_diradd(dap, NULL);
8845                 return;
8846         }
8847         /*
8848          * Cancel the primary name an free it if it does not require
8849          * journaling.
8850          */
8851         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8852             0, &inodedep) != 0) {
8853                 /* Abort the addref that reference this diradd.  */
8854                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8855                         if (inoref->if_list.wk_type != D_JADDREF)
8856                                 continue;
8857                         jaddref = (struct jaddref *)inoref;
8858                         if (jaddref->ja_diradd != dap)
8859                                 continue;
8860                         if (cancel_jaddref(jaddref, inodedep,
8861                             &dirrem->dm_jwork) == 0) {
8862                                 free_jremref(jremref);
8863                                 jremref = NULL;
8864                         }
8865                         break;
8866                 }
8867         }
8868         /*
8869          * Cancel subordinate names and free them if they do not require
8870          * journaling.
8871          */
8872         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8873                 ump = VFSTOUFS(dap->da_list.wk_mp);
8874                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8875                         if (mkdir->md_diradd != dap)
8876                                 continue;
8877                         if ((jaddref = mkdir->md_jaddref) == NULL)
8878                                 continue;
8879                         mkdir->md_jaddref = NULL;
8880                         if (mkdir->md_state & MKDIR_PARENT) {
8881                                 if (cancel_jaddref(jaddref, NULL,
8882                                     &dirrem->dm_jwork) == 0) {
8883                                         free_jremref(dotdotremref);
8884                                         dotdotremref = NULL;
8885                                 }
8886                         } else {
8887                                 if (cancel_jaddref(jaddref, inodedep,
8888                                     &dirrem->dm_jwork) == 0) {
8889                                         free_jremref(dotremref);
8890                                         dotremref = NULL;
8891                                 }
8892                         }
8893                 }
8894         }
8895
8896         if (jremref)
8897                 journal_jremref(dirrem, jremref, inodedep);
8898         if (dotremref)
8899                 journal_jremref(dirrem, dotremref, inodedep);
8900         if (dotdotremref)
8901                 journal_jremref(dirrem, dotdotremref, NULL);
8902         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8903         free_diradd(dap, &dirrem->dm_jwork);
8904 }
8905
8906 /*
8907  * Free a diradd dependency structure.
8908  */
8909 static void
8910 free_diradd(dap, wkhd)
8911         struct diradd *dap;
8912         struct workhead *wkhd;
8913 {
8914         struct dirrem *dirrem;
8915         struct pagedep *pagedep;
8916         struct inodedep *inodedep;
8917         struct mkdir *mkdir, *nextmd;
8918         struct ufsmount *ump;
8919
8920         ump = VFSTOUFS(dap->da_list.wk_mp);
8921         LOCK_OWNED(ump);
8922         LIST_REMOVE(dap, da_pdlist);
8923         if (dap->da_state & ONWORKLIST)
8924                 WORKLIST_REMOVE(&dap->da_list);
8925         if ((dap->da_state & DIRCHG) == 0) {
8926                 pagedep = dap->da_pagedep;
8927         } else {
8928                 dirrem = dap->da_previous;
8929                 pagedep = dirrem->dm_pagedep;
8930                 dirrem->dm_dirinum = pagedep->pd_ino;
8931                 dirrem->dm_state |= COMPLETE;
8932                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8933                         add_to_worklist(&dirrem->dm_list, 0);
8934         }
8935         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8936             0, &inodedep) != 0)
8937                 if (inodedep->id_mkdiradd == dap)
8938                         inodedep->id_mkdiradd = NULL;
8939         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8940                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8941                      mkdir = nextmd) {
8942                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8943                         if (mkdir->md_diradd != dap)
8944                                 continue;
8945                         dap->da_state &=
8946                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8947                         LIST_REMOVE(mkdir, md_mkdirs);
8948                         if (mkdir->md_state & ONWORKLIST)
8949                                 WORKLIST_REMOVE(&mkdir->md_list);
8950                         if (mkdir->md_jaddref != NULL)
8951                                 panic("free_diradd: Unexpected jaddref");
8952                         WORKITEM_FREE(mkdir, D_MKDIR);
8953                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8954                                 break;
8955                 }
8956                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8957                         panic("free_diradd: unfound ref");
8958         }
8959         if (inodedep)
8960                 free_inodedep(inodedep);
8961         /*
8962          * Free any journal segments waiting for the directory write.
8963          */
8964         handle_jwork(&dap->da_jwork);
8965         WORKITEM_FREE(dap, D_DIRADD);
8966 }
8967
8968 /*
8969  * Directory entry removal dependencies.
8970  * 
8971  * When removing a directory entry, the entry's inode pointer must be
8972  * zero'ed on disk before the corresponding inode's link count is decremented
8973  * (possibly freeing the inode for re-use). This dependency is handled by
8974  * updating the directory entry but delaying the inode count reduction until
8975  * after the directory block has been written to disk. After this point, the
8976  * inode count can be decremented whenever it is convenient.
8977  */
8978
8979 /*
8980  * This routine should be called immediately after removing
8981  * a directory entry.  The inode's link count should not be
8982  * decremented by the calling procedure -- the soft updates
8983  * code will do this task when it is safe.
8984  */
8985 void 
8986 softdep_setup_remove(bp, dp, ip, isrmdir)
8987         struct buf *bp;         /* buffer containing directory block */
8988         struct inode *dp;       /* inode for the directory being modified */
8989         struct inode *ip;       /* inode for directory entry being removed */
8990         int isrmdir;            /* indicates if doing RMDIR */
8991 {
8992         struct dirrem *dirrem, *prevdirrem;
8993         struct inodedep *inodedep;
8994         struct ufsmount *ump;
8995         int direct;
8996
8997         ump = ITOUMP(ip);
8998         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8999             ("softdep_setup_remove called on non-softdep filesystem"));
9000         /*
9001          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9002          * newdirrem() to setup the full directory remove which requires
9003          * isrmdir > 1.
9004          */
9005         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9006         /*
9007          * Add the dirrem to the inodedep's pending remove list for quick
9008          * discovery later.
9009          */
9010         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9011                 panic("softdep_setup_remove: Lost inodedep.");
9012         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9013         dirrem->dm_state |= ONDEPLIST;
9014         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9015
9016         /*
9017          * If the COMPLETE flag is clear, then there were no active
9018          * entries and we want to roll back to a zeroed entry until
9019          * the new inode is committed to disk. If the COMPLETE flag is
9020          * set then we have deleted an entry that never made it to
9021          * disk. If the entry we deleted resulted from a name change,
9022          * then the old name still resides on disk. We cannot delete
9023          * its inode (returned to us in prevdirrem) until the zeroed
9024          * directory entry gets to disk. The new inode has never been
9025          * referenced on the disk, so can be deleted immediately.
9026          */
9027         if ((dirrem->dm_state & COMPLETE) == 0) {
9028                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9029                     dm_next);
9030                 FREE_LOCK(ump);
9031         } else {
9032                 if (prevdirrem != NULL)
9033                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9034                             prevdirrem, dm_next);
9035                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9036                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9037                 FREE_LOCK(ump);
9038                 if (direct)
9039                         handle_workitem_remove(dirrem, 0);
9040         }
9041 }
9042
9043 /*
9044  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9045  * pd_pendinghd list of a pagedep.
9046  */
9047 static struct diradd *
9048 diradd_lookup(pagedep, offset)
9049         struct pagedep *pagedep;
9050         int offset;
9051 {
9052         struct diradd *dap;
9053
9054         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9055                 if (dap->da_offset == offset)
9056                         return (dap);
9057         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9058                 if (dap->da_offset == offset)
9059                         return (dap);
9060         return (NULL);
9061 }
9062
9063 /*
9064  * Search for a .. diradd dependency in a directory that is being removed.
9065  * If the directory was renamed to a new parent we have a diradd rather
9066  * than a mkdir for the .. entry.  We need to cancel it now before
9067  * it is found in truncate().
9068  */
9069 static struct jremref *
9070 cancel_diradd_dotdot(ip, dirrem, jremref)
9071         struct inode *ip;
9072         struct dirrem *dirrem;
9073         struct jremref *jremref;
9074 {
9075         struct pagedep *pagedep;
9076         struct diradd *dap;
9077         struct worklist *wk;
9078
9079         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9080                 return (jremref);
9081         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9082         if (dap == NULL)
9083                 return (jremref);
9084         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9085         /*
9086          * Mark any journal work as belonging to the parent so it is freed
9087          * with the .. reference.
9088          */
9089         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9090                 wk->wk_state |= MKDIR_PARENT;
9091         return (NULL);
9092 }
9093
9094 /*
9095  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9096  * replace it with a dirrem/diradd pair as a result of re-parenting a
9097  * directory.  This ensures that we don't simultaneously have a mkdir and
9098  * a diradd for the same .. entry.
9099  */
9100 static struct jremref *
9101 cancel_mkdir_dotdot(ip, dirrem, jremref)
9102         struct inode *ip;
9103         struct dirrem *dirrem;
9104         struct jremref *jremref;
9105 {
9106         struct inodedep *inodedep;
9107         struct jaddref *jaddref;
9108         struct ufsmount *ump;
9109         struct mkdir *mkdir;
9110         struct diradd *dap;
9111         struct mount *mp;
9112
9113         mp = ITOVFS(ip);
9114         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9115                 return (jremref);
9116         dap = inodedep->id_mkdiradd;
9117         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9118                 return (jremref);
9119         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9120         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9121             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9122                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9123                         break;
9124         if (mkdir == NULL)
9125                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9126         if ((jaddref = mkdir->md_jaddref) != NULL) {
9127                 mkdir->md_jaddref = NULL;
9128                 jaddref->ja_state &= ~MKDIR_PARENT;
9129                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9130                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9131                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9132                         journal_jremref(dirrem, jremref, inodedep);
9133                         jremref = NULL;
9134                 }
9135         }
9136         if (mkdir->md_state & ONWORKLIST)
9137                 WORKLIST_REMOVE(&mkdir->md_list);
9138         mkdir->md_state |= ALLCOMPLETE;
9139         complete_mkdir(mkdir);
9140         return (jremref);
9141 }
9142
9143 static void
9144 journal_jremref(dirrem, jremref, inodedep)
9145         struct dirrem *dirrem;
9146         struct jremref *jremref;
9147         struct inodedep *inodedep;
9148 {
9149
9150         if (inodedep == NULL)
9151                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9152                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9153                         panic("journal_jremref: Lost inodedep");
9154         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9155         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9156         add_to_journal(&jremref->jr_list);
9157 }
9158
9159 static void
9160 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9161         struct dirrem *dirrem;
9162         struct jremref *jremref;
9163         struct jremref *dotremref;
9164         struct jremref *dotdotremref;
9165 {
9166         struct inodedep *inodedep;
9167
9168
9169         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9170             &inodedep) == 0)
9171                 panic("dirrem_journal: Lost inodedep");
9172         journal_jremref(dirrem, jremref, inodedep);
9173         if (dotremref)
9174                 journal_jremref(dirrem, dotremref, inodedep);
9175         if (dotdotremref)
9176                 journal_jremref(dirrem, dotdotremref, NULL);
9177 }
9178
9179 /*
9180  * Allocate a new dirrem if appropriate and return it along with
9181  * its associated pagedep. Called without a lock, returns with lock.
9182  */
9183 static struct dirrem *
9184 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9185         struct buf *bp;         /* buffer containing directory block */
9186         struct inode *dp;       /* inode for the directory being modified */
9187         struct inode *ip;       /* inode for directory entry being removed */
9188         int isrmdir;            /* indicates if doing RMDIR */
9189         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9190 {
9191         int offset;
9192         ufs_lbn_t lbn;
9193         struct diradd *dap;
9194         struct dirrem *dirrem;
9195         struct pagedep *pagedep;
9196         struct jremref *jremref;
9197         struct jremref *dotremref;
9198         struct jremref *dotdotremref;
9199         struct vnode *dvp;
9200         struct ufsmount *ump;
9201
9202         /*
9203          * Whiteouts have no deletion dependencies.
9204          */
9205         if (ip == NULL)
9206                 panic("newdirrem: whiteout");
9207         dvp = ITOV(dp);
9208         ump = ITOUMP(dp);
9209
9210         /*
9211          * If the system is over its limit and our filesystem is
9212          * responsible for more than our share of that usage and
9213          * we are not a snapshot, request some inodedep cleanup.
9214          * Limiting the number of dirrem structures will also limit
9215          * the number of freefile and freeblks structures.
9216          */
9217         ACQUIRE_LOCK(ump);
9218         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9219                 schedule_cleanup(UFSTOVFS(ump));
9220         else
9221                 FREE_LOCK(ump);
9222         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9223             M_ZERO);
9224         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9225         LIST_INIT(&dirrem->dm_jremrefhd);
9226         LIST_INIT(&dirrem->dm_jwork);
9227         dirrem->dm_state = isrmdir ? RMDIR : 0;
9228         dirrem->dm_oldinum = ip->i_number;
9229         *prevdirremp = NULL;
9230         /*
9231          * Allocate remove reference structures to track journal write
9232          * dependencies.  We will always have one for the link and
9233          * when doing directories we will always have one more for dot.
9234          * When renaming a directory we skip the dotdot link change so
9235          * this is not needed.
9236          */
9237         jremref = dotremref = dotdotremref = NULL;
9238         if (DOINGSUJ(dvp)) {
9239                 if (isrmdir) {
9240                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9241                             ip->i_effnlink + 2);
9242                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9243                             ip->i_effnlink + 1);
9244                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9245                             dp->i_effnlink + 1);
9246                         dotdotremref->jr_state |= MKDIR_PARENT;
9247                 } else
9248                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9249                             ip->i_effnlink + 1);
9250         }
9251         ACQUIRE_LOCK(ump);
9252         lbn = lblkno(ump->um_fs, dp->i_offset);
9253         offset = blkoff(ump->um_fs, dp->i_offset);
9254         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9255             &pagedep);
9256         dirrem->dm_pagedep = pagedep;
9257         dirrem->dm_offset = offset;
9258         /*
9259          * If we're renaming a .. link to a new directory, cancel any
9260          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9261          * the jremref is preserved for any potential diradd in this
9262          * location.  This can not coincide with a rmdir.
9263          */
9264         if (dp->i_offset == DOTDOT_OFFSET) {
9265                 if (isrmdir)
9266                         panic("newdirrem: .. directory change during remove?");
9267                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9268         }
9269         /*
9270          * If we're removing a directory search for the .. dependency now and
9271          * cancel it.  Any pending journal work will be added to the dirrem
9272          * to be completed when the workitem remove completes.
9273          */
9274         if (isrmdir)
9275                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9276         /*
9277          * Check for a diradd dependency for the same directory entry.
9278          * If present, then both dependencies become obsolete and can
9279          * be de-allocated.
9280          */
9281         dap = diradd_lookup(pagedep, offset);
9282         if (dap == NULL) {
9283                 /*
9284                  * Link the jremref structures into the dirrem so they are
9285                  * written prior to the pagedep.
9286                  */
9287                 if (jremref)
9288                         dirrem_journal(dirrem, jremref, dotremref,
9289                             dotdotremref);
9290                 return (dirrem);
9291         }
9292         /*
9293          * Must be ATTACHED at this point.
9294          */
9295         if ((dap->da_state & ATTACHED) == 0)
9296                 panic("newdirrem: not ATTACHED");
9297         if (dap->da_newinum != ip->i_number)
9298                 panic("newdirrem: inum %ju should be %ju",
9299                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9300         /*
9301          * If we are deleting a changed name that never made it to disk,
9302          * then return the dirrem describing the previous inode (which
9303          * represents the inode currently referenced from this entry on disk).
9304          */
9305         if ((dap->da_state & DIRCHG) != 0) {
9306                 *prevdirremp = dap->da_previous;
9307                 dap->da_state &= ~DIRCHG;
9308                 dap->da_pagedep = pagedep;
9309         }
9310         /*
9311          * We are deleting an entry that never made it to disk.
9312          * Mark it COMPLETE so we can delete its inode immediately.
9313          */
9314         dirrem->dm_state |= COMPLETE;
9315         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9316 #ifdef INVARIANTS
9317         if (isrmdir == 0) {
9318                 struct worklist *wk;
9319
9320                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9321                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9322                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9323         }
9324 #endif
9325
9326         return (dirrem);
9327 }
9328
9329 /*
9330  * Directory entry change dependencies.
9331  * 
9332  * Changing an existing directory entry requires that an add operation
9333  * be completed first followed by a deletion. The semantics for the addition
9334  * are identical to the description of adding a new entry above except
9335  * that the rollback is to the old inode number rather than zero. Once
9336  * the addition dependency is completed, the removal is done as described
9337  * in the removal routine above.
9338  */
9339
9340 /*
9341  * This routine should be called immediately after changing
9342  * a directory entry.  The inode's link count should not be
9343  * decremented by the calling procedure -- the soft updates
9344  * code will perform this task when it is safe.
9345  */
9346 void 
9347 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9348         struct buf *bp;         /* buffer containing directory block */
9349         struct inode *dp;       /* inode for the directory being modified */
9350         struct inode *ip;       /* inode for directory entry being removed */
9351         ino_t newinum;          /* new inode number for changed entry */
9352         int isrmdir;            /* indicates if doing RMDIR */
9353 {
9354         int offset;
9355         struct diradd *dap = NULL;
9356         struct dirrem *dirrem, *prevdirrem;
9357         struct pagedep *pagedep;
9358         struct inodedep *inodedep;
9359         struct jaddref *jaddref;
9360         struct mount *mp;
9361         struct ufsmount *ump;
9362
9363         mp = ITOVFS(dp);
9364         ump = VFSTOUFS(mp);
9365         offset = blkoff(ump->um_fs, dp->i_offset);
9366         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9367            ("softdep_setup_directory_change called on non-softdep filesystem"));
9368
9369         /*
9370          * Whiteouts do not need diradd dependencies.
9371          */
9372         if (newinum != UFS_WINO) {
9373                 dap = malloc(sizeof(struct diradd),
9374                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9375                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9376                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9377                 dap->da_offset = offset;
9378                 dap->da_newinum = newinum;
9379                 LIST_INIT(&dap->da_jwork);
9380         }
9381
9382         /*
9383          * Allocate a new dirrem and ACQUIRE_LOCK.
9384          */
9385         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9386         pagedep = dirrem->dm_pagedep;
9387         /*
9388          * The possible values for isrmdir:
9389          *      0 - non-directory file rename
9390          *      1 - directory rename within same directory
9391          *   inum - directory rename to new directory of given inode number
9392          * When renaming to a new directory, we are both deleting and
9393          * creating a new directory entry, so the link count on the new
9394          * directory should not change. Thus we do not need the followup
9395          * dirrem which is usually done in handle_workitem_remove. We set
9396          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9397          * followup dirrem.
9398          */
9399         if (isrmdir > 1)
9400                 dirrem->dm_state |= DIRCHG;
9401
9402         /*
9403          * Whiteouts have no additional dependencies,
9404          * so just put the dirrem on the correct list.
9405          */
9406         if (newinum == UFS_WINO) {
9407                 if ((dirrem->dm_state & COMPLETE) == 0) {
9408                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9409                             dm_next);
9410                 } else {
9411                         dirrem->dm_dirinum = pagedep->pd_ino;
9412                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9413                                 add_to_worklist(&dirrem->dm_list, 0);
9414                 }
9415                 FREE_LOCK(ump);
9416                 return;
9417         }
9418         /*
9419          * Add the dirrem to the inodedep's pending remove list for quick
9420          * discovery later.  A valid nlinkdelta ensures that this lookup
9421          * will not fail.
9422          */
9423         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9424                 panic("softdep_setup_directory_change: Lost inodedep.");
9425         dirrem->dm_state |= ONDEPLIST;
9426         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9427
9428         /*
9429          * If the COMPLETE flag is clear, then there were no active
9430          * entries and we want to roll back to the previous inode until
9431          * the new inode is committed to disk. If the COMPLETE flag is
9432          * set, then we have deleted an entry that never made it to disk.
9433          * If the entry we deleted resulted from a name change, then the old
9434          * inode reference still resides on disk. Any rollback that we do
9435          * needs to be to that old inode (returned to us in prevdirrem). If
9436          * the entry we deleted resulted from a create, then there is
9437          * no entry on the disk, so we want to roll back to zero rather
9438          * than the uncommitted inode. In either of the COMPLETE cases we
9439          * want to immediately free the unwritten and unreferenced inode.
9440          */
9441         if ((dirrem->dm_state & COMPLETE) == 0) {
9442                 dap->da_previous = dirrem;
9443         } else {
9444                 if (prevdirrem != NULL) {
9445                         dap->da_previous = prevdirrem;
9446                 } else {
9447                         dap->da_state &= ~DIRCHG;
9448                         dap->da_pagedep = pagedep;
9449                 }
9450                 dirrem->dm_dirinum = pagedep->pd_ino;
9451                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9452                         add_to_worklist(&dirrem->dm_list, 0);
9453         }
9454         /*
9455          * Lookup the jaddref for this journal entry.  We must finish
9456          * initializing it and make the diradd write dependent on it.
9457          * If we're not journaling, put it on the id_bufwait list if the
9458          * inode is not yet written. If it is written, do the post-inode
9459          * write processing to put it on the id_pendinghd list.
9460          */
9461         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9462         if (MOUNTEDSUJ(mp)) {
9463                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9464                     inoreflst);
9465                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9466                     ("softdep_setup_directory_change: bad jaddref %p",
9467                     jaddref));
9468                 jaddref->ja_diroff = dp->i_offset;
9469                 jaddref->ja_diradd = dap;
9470                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9471                     dap, da_pdlist);
9472                 add_to_journal(&jaddref->ja_list);
9473         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9474                 dap->da_state |= COMPLETE;
9475                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9476                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9477         } else {
9478                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9479                     dap, da_pdlist);
9480                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9481         }
9482         /*
9483          * If we're making a new name for a directory that has not been
9484          * committed when need to move the dot and dotdot references to
9485          * this new name.
9486          */
9487         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9488                 merge_diradd(inodedep, dap);
9489         FREE_LOCK(ump);
9490 }
9491
9492 /*
9493  * Called whenever the link count on an inode is changed.
9494  * It creates an inode dependency so that the new reference(s)
9495  * to the inode cannot be committed to disk until the updated
9496  * inode has been written.
9497  */
9498 void
9499 softdep_change_linkcnt(ip)
9500         struct inode *ip;       /* the inode with the increased link count */
9501 {
9502         struct inodedep *inodedep;
9503         struct ufsmount *ump;
9504
9505         ump = ITOUMP(ip);
9506         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9507             ("softdep_change_linkcnt called on non-softdep filesystem"));
9508         ACQUIRE_LOCK(ump);
9509         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9510         if (ip->i_nlink < ip->i_effnlink)
9511                 panic("softdep_change_linkcnt: bad delta");
9512         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9513         FREE_LOCK(ump);
9514 }
9515
9516 /*
9517  * Attach a sbdep dependency to the superblock buf so that we can keep
9518  * track of the head of the linked list of referenced but unlinked inodes.
9519  */
9520 void
9521 softdep_setup_sbupdate(ump, fs, bp)
9522         struct ufsmount *ump;
9523         struct fs *fs;
9524         struct buf *bp;
9525 {
9526         struct sbdep *sbdep;
9527         struct worklist *wk;
9528
9529         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9530             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9531         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9532                 if (wk->wk_type == D_SBDEP)
9533                         break;
9534         if (wk != NULL)
9535                 return;
9536         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9537         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9538         sbdep->sb_fs = fs;
9539         sbdep->sb_ump = ump;
9540         ACQUIRE_LOCK(ump);
9541         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9542         FREE_LOCK(ump);
9543 }
9544
9545 /*
9546  * Return the first unlinked inodedep which is ready to be the head of the
9547  * list.  The inodedep and all those after it must have valid next pointers.
9548  */
9549 static struct inodedep *
9550 first_unlinked_inodedep(ump)
9551         struct ufsmount *ump;
9552 {
9553         struct inodedep *inodedep;
9554         struct inodedep *idp;
9555
9556         LOCK_OWNED(ump);
9557         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9558             inodedep; inodedep = idp) {
9559                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9560                         return (NULL);
9561                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9562                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9563                         break;
9564                 if ((inodedep->id_state & UNLINKPREV) == 0)
9565                         break;
9566         }
9567         return (inodedep);
9568 }
9569
9570 /*
9571  * Set the sujfree unlinked head pointer prior to writing a superblock.
9572  */
9573 static void
9574 initiate_write_sbdep(sbdep)
9575         struct sbdep *sbdep;
9576 {
9577         struct inodedep *inodedep;
9578         struct fs *bpfs;
9579         struct fs *fs;
9580
9581         bpfs = sbdep->sb_fs;
9582         fs = sbdep->sb_ump->um_fs;
9583         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9584         if (inodedep) {
9585                 fs->fs_sujfree = inodedep->id_ino;
9586                 inodedep->id_state |= UNLINKPREV;
9587         } else
9588                 fs->fs_sujfree = 0;
9589         bpfs->fs_sujfree = fs->fs_sujfree;
9590         /*
9591          * Because we have made changes to the superblock, we need to
9592          * recompute its check-hash.
9593          */
9594         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9595 }
9596
9597 /*
9598  * After a superblock is written determine whether it must be written again
9599  * due to a changing unlinked list head.
9600  */
9601 static int
9602 handle_written_sbdep(sbdep, bp)
9603         struct sbdep *sbdep;
9604         struct buf *bp;
9605 {
9606         struct inodedep *inodedep;
9607         struct fs *fs;
9608
9609         LOCK_OWNED(sbdep->sb_ump);
9610         fs = sbdep->sb_fs;
9611         /*
9612          * If the superblock doesn't match the in-memory list start over.
9613          */
9614         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9615         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9616             (inodedep == NULL && fs->fs_sujfree != 0)) {
9617                 bdirty(bp);
9618                 return (1);
9619         }
9620         WORKITEM_FREE(sbdep, D_SBDEP);
9621         if (fs->fs_sujfree == 0)
9622                 return (0);
9623         /*
9624          * Now that we have a record of this inode in stable store allow it
9625          * to be written to free up pending work.  Inodes may see a lot of
9626          * write activity after they are unlinked which we must not hold up.
9627          */
9628         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9629                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9630                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9631                             inodedep, inodedep->id_state);
9632                 if (inodedep->id_state & UNLINKONLIST)
9633                         break;
9634                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9635         }
9636
9637         return (0);
9638 }
9639
9640 /*
9641  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9642  */
9643 static void
9644 unlinked_inodedep(mp, inodedep)
9645         struct mount *mp;
9646         struct inodedep *inodedep;
9647 {
9648         struct ufsmount *ump;
9649
9650         ump = VFSTOUFS(mp);
9651         LOCK_OWNED(ump);
9652         if (MOUNTEDSUJ(mp) == 0)
9653                 return;
9654         ump->um_fs->fs_fmod = 1;
9655         if (inodedep->id_state & UNLINKED)
9656                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9657         inodedep->id_state |= UNLINKED;
9658         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9659 }
9660
9661 /*
9662  * Remove an inodedep from the unlinked inodedep list.  This may require
9663  * disk writes if the inode has made it that far.
9664  */
9665 static void
9666 clear_unlinked_inodedep(inodedep)
9667         struct inodedep *inodedep;
9668 {
9669         struct ufs2_dinode *dip;
9670         struct ufsmount *ump;
9671         struct inodedep *idp;
9672         struct inodedep *idn;
9673         struct fs *fs, *bpfs;
9674         struct buf *bp;
9675         ino_t ino;
9676         ino_t nino;
9677         ino_t pino;
9678         int error;
9679
9680         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9681         fs = ump->um_fs;
9682         ino = inodedep->id_ino;
9683         error = 0;
9684         for (;;) {
9685                 LOCK_OWNED(ump);
9686                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9687                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9688                     inodedep));
9689                 /*
9690                  * If nothing has yet been written simply remove us from
9691                  * the in memory list and return.  This is the most common
9692                  * case where handle_workitem_remove() loses the final
9693                  * reference.
9694                  */
9695                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9696                         break;
9697                 /*
9698                  * If we have a NEXT pointer and no PREV pointer we can simply
9699                  * clear NEXT's PREV and remove ourselves from the list.  Be
9700                  * careful not to clear PREV if the superblock points at
9701                  * next as well.
9702                  */
9703                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9704                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9705                         if (idn && fs->fs_sujfree != idn->id_ino)
9706                                 idn->id_state &= ~UNLINKPREV;
9707                         break;
9708                 }
9709                 /*
9710                  * Here we have an inodedep which is actually linked into
9711                  * the list.  We must remove it by forcing a write to the
9712                  * link before us, whether it be the superblock or an inode.
9713                  * Unfortunately the list may change while we're waiting
9714                  * on the buf lock for either resource so we must loop until
9715                  * we lock the right one.  If both the superblock and an
9716                  * inode point to this inode we must clear the inode first
9717                  * followed by the superblock.
9718                  */
9719                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9720                 pino = 0;
9721                 if (idp && (idp->id_state & UNLINKNEXT))
9722                         pino = idp->id_ino;
9723                 FREE_LOCK(ump);
9724                 if (pino == 0) {
9725                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9726                             (int)fs->fs_sbsize, 0, 0, 0);
9727                 } else {
9728                         error = bread(ump->um_devvp,
9729                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9730                             (int)fs->fs_bsize, NOCRED, &bp);
9731                         if (error)
9732                                 brelse(bp);
9733                 }
9734                 ACQUIRE_LOCK(ump);
9735                 if (error)
9736                         break;
9737                 /* If the list has changed restart the loop. */
9738                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9739                 nino = 0;
9740                 if (idp && (idp->id_state & UNLINKNEXT))
9741                         nino = idp->id_ino;
9742                 if (nino != pino ||
9743                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9744                         FREE_LOCK(ump);
9745                         brelse(bp);
9746                         ACQUIRE_LOCK(ump);
9747                         continue;
9748                 }
9749                 nino = 0;
9750                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9751                 if (idn)
9752                         nino = idn->id_ino;
9753                 /*
9754                  * Remove us from the in memory list.  After this we cannot
9755                  * access the inodedep.
9756                  */
9757                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9758                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9759                     inodedep));
9760                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9761                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9762                 FREE_LOCK(ump);
9763                 /*
9764                  * The predecessor's next pointer is manually updated here
9765                  * so that the NEXT flag is never cleared for an element
9766                  * that is in the list.
9767                  */
9768                 if (pino == 0) {
9769                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9770                         bpfs = (struct fs *)bp->b_data;
9771                         ffs_oldfscompat_write(bpfs, ump);
9772                         softdep_setup_sbupdate(ump, bpfs, bp);
9773                         /*
9774                          * Because we may have made changes to the superblock,
9775                          * we need to recompute its check-hash.
9776                          */
9777                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9778                 } else if (fs->fs_magic == FS_UFS1_MAGIC) {
9779                         ((struct ufs1_dinode *)bp->b_data +
9780                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9781                 } else {
9782                         dip = (struct ufs2_dinode *)bp->b_data +
9783                             ino_to_fsbo(fs, pino);
9784                         dip->di_freelink = nino;
9785                         ffs_update_dinode_ckhash(fs, dip);
9786                 }
9787                 /*
9788                  * If the bwrite fails we have no recourse to recover.  The
9789                  * filesystem is corrupted already.
9790                  */
9791                 bwrite(bp);
9792                 ACQUIRE_LOCK(ump);
9793                 /*
9794                  * If the superblock pointer still needs to be cleared force
9795                  * a write here.
9796                  */
9797                 if (fs->fs_sujfree == ino) {
9798                         FREE_LOCK(ump);
9799                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9800                             (int)fs->fs_sbsize, 0, 0, 0);
9801                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9802                         bpfs = (struct fs *)bp->b_data;
9803                         ffs_oldfscompat_write(bpfs, ump);
9804                         softdep_setup_sbupdate(ump, bpfs, bp);
9805                         /*
9806                          * Because we may have made changes to the superblock,
9807                          * we need to recompute its check-hash.
9808                          */
9809                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9810                         bwrite(bp);
9811                         ACQUIRE_LOCK(ump);
9812                 }
9813
9814                 if (fs->fs_sujfree != ino)
9815                         return;
9816                 panic("clear_unlinked_inodedep: Failed to clear free head");
9817         }
9818         if (inodedep->id_ino == fs->fs_sujfree)
9819                 panic("clear_unlinked_inodedep: Freeing head of free list");
9820         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9821         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9822         return;
9823 }
9824
9825 /*
9826  * This workitem decrements the inode's link count.
9827  * If the link count reaches zero, the file is removed.
9828  */
9829 static int
9830 handle_workitem_remove(dirrem, flags)
9831         struct dirrem *dirrem;
9832         int flags;
9833 {
9834         struct inodedep *inodedep;
9835         struct workhead dotdotwk;
9836         struct worklist *wk;
9837         struct ufsmount *ump;
9838         struct mount *mp;
9839         struct vnode *vp;
9840         struct inode *ip;
9841         ino_t oldinum;
9842
9843         if (dirrem->dm_state & ONWORKLIST)
9844                 panic("handle_workitem_remove: dirrem %p still on worklist",
9845                     dirrem);
9846         oldinum = dirrem->dm_oldinum;
9847         mp = dirrem->dm_list.wk_mp;
9848         ump = VFSTOUFS(mp);
9849         flags |= LK_EXCLUSIVE;
9850         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9851                 return (EBUSY);
9852         ip = VTOI(vp);
9853         ACQUIRE_LOCK(ump);
9854         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9855                 panic("handle_workitem_remove: lost inodedep");
9856         if (dirrem->dm_state & ONDEPLIST)
9857                 LIST_REMOVE(dirrem, dm_inonext);
9858         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9859             ("handle_workitem_remove:  Journal entries not written."));
9860
9861         /*
9862          * Move all dependencies waiting on the remove to complete
9863          * from the dirrem to the inode inowait list to be completed
9864          * after the inode has been updated and written to disk.  Any
9865          * marked MKDIR_PARENT are saved to be completed when the .. ref
9866          * is removed.
9867          */
9868         LIST_INIT(&dotdotwk);
9869         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9870                 WORKLIST_REMOVE(wk);
9871                 if (wk->wk_state & MKDIR_PARENT) {
9872                         wk->wk_state &= ~MKDIR_PARENT;
9873                         WORKLIST_INSERT(&dotdotwk, wk);
9874                         continue;
9875                 }
9876                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9877         }
9878         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9879         /*
9880          * Normal file deletion.
9881          */
9882         if ((dirrem->dm_state & RMDIR) == 0) {
9883                 ip->i_nlink--;
9884                 KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
9885                     "%ju negative i_nlink %d", (intmax_t)ip->i_number,
9886                     ip->i_nlink));
9887                 DIP_SET(ip, i_nlink, ip->i_nlink);
9888                 ip->i_flag |= IN_CHANGE;
9889                 if (ip->i_nlink < ip->i_effnlink)
9890                         panic("handle_workitem_remove: bad file delta");
9891                 if (ip->i_nlink == 0) 
9892                         unlinked_inodedep(mp, inodedep);
9893                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9894                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9895                     ("handle_workitem_remove: worklist not empty. %s",
9896                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9897                 WORKITEM_FREE(dirrem, D_DIRREM);
9898                 FREE_LOCK(ump);
9899                 goto out;
9900         }
9901         /*
9902          * Directory deletion. Decrement reference count for both the
9903          * just deleted parent directory entry and the reference for ".".
9904          * Arrange to have the reference count on the parent decremented
9905          * to account for the loss of "..".
9906          */
9907         ip->i_nlink -= 2;
9908         KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
9909             "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
9910         DIP_SET(ip, i_nlink, ip->i_nlink);
9911         ip->i_flag |= IN_CHANGE;
9912         if (ip->i_nlink < ip->i_effnlink)
9913                 panic("handle_workitem_remove: bad dir delta");
9914         if (ip->i_nlink == 0)
9915                 unlinked_inodedep(mp, inodedep);
9916         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9917         /*
9918          * Rename a directory to a new parent. Since, we are both deleting
9919          * and creating a new directory entry, the link count on the new
9920          * directory should not change. Thus we skip the followup dirrem.
9921          */
9922         if (dirrem->dm_state & DIRCHG) {
9923                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9924                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9925                 WORKITEM_FREE(dirrem, D_DIRREM);
9926                 FREE_LOCK(ump);
9927                 goto out;
9928         }
9929         dirrem->dm_state = ONDEPLIST;
9930         dirrem->dm_oldinum = dirrem->dm_dirinum;
9931         /*
9932          * Place the dirrem on the parent's diremhd list.
9933          */
9934         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9935                 panic("handle_workitem_remove: lost dir inodedep");
9936         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9937         /*
9938          * If the allocated inode has never been written to disk, then
9939          * the on-disk inode is zero'ed and we can remove the file
9940          * immediately.  When journaling if the inode has been marked
9941          * unlinked and not DEPCOMPLETE we know it can never be written.
9942          */
9943         inodedep_lookup(mp, oldinum, 0, &inodedep);
9944         if (inodedep == NULL ||
9945             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9946             check_inode_unwritten(inodedep)) {
9947                 FREE_LOCK(ump);
9948                 vput(vp);
9949                 return handle_workitem_remove(dirrem, flags);
9950         }
9951         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9952         FREE_LOCK(ump);
9953         ip->i_flag |= IN_CHANGE;
9954 out:
9955         ffs_update(vp, 0);
9956         vput(vp);
9957         return (0);
9958 }
9959
9960 /*
9961  * Inode de-allocation dependencies.
9962  * 
9963  * When an inode's link count is reduced to zero, it can be de-allocated. We
9964  * found it convenient to postpone de-allocation until after the inode is
9965  * written to disk with its new link count (zero).  At this point, all of the
9966  * on-disk inode's block pointers are nullified and, with careful dependency
9967  * list ordering, all dependencies related to the inode will be satisfied and
9968  * the corresponding dependency structures de-allocated.  So, if/when the
9969  * inode is reused, there will be no mixing of old dependencies with new
9970  * ones.  This artificial dependency is set up by the block de-allocation
9971  * procedure above (softdep_setup_freeblocks) and completed by the
9972  * following procedure.
9973  */
9974 static void 
9975 handle_workitem_freefile(freefile)
9976         struct freefile *freefile;
9977 {
9978         struct workhead wkhd;
9979         struct fs *fs;
9980         struct ufsmount *ump;
9981         int error;
9982 #ifdef INVARIANTS
9983         struct inodedep *idp;
9984 #endif
9985
9986         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9987         fs = ump->um_fs;
9988 #ifdef INVARIANTS
9989         ACQUIRE_LOCK(ump);
9990         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9991         FREE_LOCK(ump);
9992         if (error)
9993                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9994 #endif
9995         UFS_LOCK(ump);
9996         fs->fs_pendinginodes -= 1;
9997         UFS_UNLOCK(ump);
9998         LIST_INIT(&wkhd);
9999         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10000         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10001             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10002                 softdep_error("handle_workitem_freefile", error);
10003         ACQUIRE_LOCK(ump);
10004         WORKITEM_FREE(freefile, D_FREEFILE);
10005         FREE_LOCK(ump);
10006 }
10007
10008
10009 /*
10010  * Helper function which unlinks marker element from work list and returns
10011  * the next element on the list.
10012  */
10013 static __inline struct worklist *
10014 markernext(struct worklist *marker)
10015 {
10016         struct worklist *next;
10017         
10018         next = LIST_NEXT(marker, wk_list);
10019         LIST_REMOVE(marker, wk_list);
10020         return next;
10021 }
10022
10023 /*
10024  * Disk writes.
10025  * 
10026  * The dependency structures constructed above are most actively used when file
10027  * system blocks are written to disk.  No constraints are placed on when a
10028  * block can be written, but unsatisfied update dependencies are made safe by
10029  * modifying (or replacing) the source memory for the duration of the disk
10030  * write.  When the disk write completes, the memory block is again brought
10031  * up-to-date.
10032  *
10033  * In-core inode structure reclamation.
10034  * 
10035  * Because there are a finite number of "in-core" inode structures, they are
10036  * reused regularly.  By transferring all inode-related dependencies to the
10037  * in-memory inode block and indexing them separately (via "inodedep"s), we
10038  * can allow "in-core" inode structures to be reused at any time and avoid
10039  * any increase in contention.
10040  *
10041  * Called just before entering the device driver to initiate a new disk I/O.
10042  * The buffer must be locked, thus, no I/O completion operations can occur
10043  * while we are manipulating its associated dependencies.
10044  */
10045 static void 
10046 softdep_disk_io_initiation(bp)
10047         struct buf *bp;         /* structure describing disk write to occur */
10048 {
10049         struct worklist *wk;
10050         struct worklist marker;
10051         struct inodedep *inodedep;
10052         struct freeblks *freeblks;
10053         struct jblkdep *jblkdep;
10054         struct newblk *newblk;
10055         struct ufsmount *ump;
10056
10057         /*
10058          * We only care about write operations. There should never
10059          * be dependencies for reads.
10060          */
10061         if (bp->b_iocmd != BIO_WRITE)
10062                 panic("softdep_disk_io_initiation: not write");
10063
10064         if (bp->b_vflags & BV_BKGRDINPROG)
10065                 panic("softdep_disk_io_initiation: Writing buffer with "
10066                     "background write in progress: %p", bp);
10067
10068         ump = softdep_bp_to_mp(bp);
10069         if (ump == NULL)
10070                 return;
10071
10072         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
10073         PHOLD(curproc);                 /* Don't swap out kernel stack */
10074         ACQUIRE_LOCK(ump);
10075         /*
10076          * Do any necessary pre-I/O processing.
10077          */
10078         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10079              wk = markernext(&marker)) {
10080                 LIST_INSERT_AFTER(wk, &marker, wk_list);
10081                 switch (wk->wk_type) {
10082
10083                 case D_PAGEDEP:
10084                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10085                         continue;
10086
10087                 case D_INODEDEP:
10088                         inodedep = WK_INODEDEP(wk);
10089                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10090                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10091                         else
10092                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10093                         continue;
10094
10095                 case D_INDIRDEP:
10096                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10097                         continue;
10098
10099                 case D_BMSAFEMAP:
10100                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10101                         continue;
10102
10103                 case D_JSEG:
10104                         WK_JSEG(wk)->js_buf = NULL;
10105                         continue;
10106
10107                 case D_FREEBLKS:
10108                         freeblks = WK_FREEBLKS(wk);
10109                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10110                         /*
10111                          * We have to wait for the freeblks to be journaled
10112                          * before we can write an inodeblock with updated
10113                          * pointers.  Be careful to arrange the marker so
10114                          * we revisit the freeblks if it's not removed by
10115                          * the first jwait().
10116                          */
10117                         if (jblkdep != NULL) {
10118                                 LIST_REMOVE(&marker, wk_list);
10119                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10120                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10121                         }
10122                         continue;
10123                 case D_ALLOCDIRECT:
10124                 case D_ALLOCINDIR:
10125                         /*
10126                          * We have to wait for the jnewblk to be journaled
10127                          * before we can write to a block if the contents
10128                          * may be confused with an earlier file's indirect
10129                          * at recovery time.  Handle the marker as described
10130                          * above.
10131                          */
10132                         newblk = WK_NEWBLK(wk);
10133                         if (newblk->nb_jnewblk != NULL &&
10134                             indirblk_lookup(newblk->nb_list.wk_mp,
10135                             newblk->nb_newblkno)) {
10136                                 LIST_REMOVE(&marker, wk_list);
10137                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10138                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10139                         }
10140                         continue;
10141
10142                 case D_SBDEP:
10143                         initiate_write_sbdep(WK_SBDEP(wk));
10144                         continue;
10145
10146                 case D_MKDIR:
10147                 case D_FREEWORK:
10148                 case D_FREEDEP:
10149                 case D_JSEGDEP:
10150                         continue;
10151
10152                 default:
10153                         panic("handle_disk_io_initiation: Unexpected type %s",
10154                             TYPENAME(wk->wk_type));
10155                         /* NOTREACHED */
10156                 }
10157         }
10158         FREE_LOCK(ump);
10159         PRELE(curproc);                 /* Allow swapout of kernel stack */
10160 }
10161
10162 /*
10163  * Called from within the procedure above to deal with unsatisfied
10164  * allocation dependencies in a directory. The buffer must be locked,
10165  * thus, no I/O completion operations can occur while we are
10166  * manipulating its associated dependencies.
10167  */
10168 static void
10169 initiate_write_filepage(pagedep, bp)
10170         struct pagedep *pagedep;
10171         struct buf *bp;
10172 {
10173         struct jremref *jremref;
10174         struct jmvref *jmvref;
10175         struct dirrem *dirrem;
10176         struct diradd *dap;
10177         struct direct *ep;
10178         int i;
10179
10180         if (pagedep->pd_state & IOSTARTED) {
10181                 /*
10182                  * This can only happen if there is a driver that does not
10183                  * understand chaining. Here biodone will reissue the call
10184                  * to strategy for the incomplete buffers.
10185                  */
10186                 printf("initiate_write_filepage: already started\n");
10187                 return;
10188         }
10189         pagedep->pd_state |= IOSTARTED;
10190         /*
10191          * Wait for all journal remove dependencies to hit the disk.
10192          * We can not allow any potentially conflicting directory adds
10193          * to be visible before removes and rollback is too difficult.
10194          * The per-filesystem lock may be dropped and re-acquired, however 
10195          * we hold the buf locked so the dependency can not go away.
10196          */
10197         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10198                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10199                         jwait(&jremref->jr_list, MNT_WAIT);
10200         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10201                 jwait(&jmvref->jm_list, MNT_WAIT);
10202         for (i = 0; i < DAHASHSZ; i++) {
10203                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10204                         ep = (struct direct *)
10205                             ((char *)bp->b_data + dap->da_offset);
10206                         if (ep->d_ino != dap->da_newinum)
10207                                 panic("%s: dir inum %ju != new %ju",
10208                                     "initiate_write_filepage",
10209                                     (uintmax_t)ep->d_ino,
10210                                     (uintmax_t)dap->da_newinum);
10211                         if (dap->da_state & DIRCHG)
10212                                 ep->d_ino = dap->da_previous->dm_oldinum;
10213                         else
10214                                 ep->d_ino = 0;
10215                         dap->da_state &= ~ATTACHED;
10216                         dap->da_state |= UNDONE;
10217                 }
10218         }
10219 }
10220
10221 /*
10222  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10223  * Note that any bug fixes made to this routine must be done in the
10224  * version found below.
10225  *
10226  * Called from within the procedure above to deal with unsatisfied
10227  * allocation dependencies in an inodeblock. The buffer must be
10228  * locked, thus, no I/O completion operations can occur while we
10229  * are manipulating its associated dependencies.
10230  */
10231 static void 
10232 initiate_write_inodeblock_ufs1(inodedep, bp)
10233         struct inodedep *inodedep;
10234         struct buf *bp;                 /* The inode block */
10235 {
10236         struct allocdirect *adp, *lastadp;
10237         struct ufs1_dinode *dp;
10238         struct ufs1_dinode *sip;
10239         struct inoref *inoref;
10240         struct ufsmount *ump;
10241         struct fs *fs;
10242         ufs_lbn_t i;
10243 #ifdef INVARIANTS
10244         ufs_lbn_t prevlbn = 0;
10245 #endif
10246         int deplist;
10247
10248         if (inodedep->id_state & IOSTARTED)
10249                 panic("initiate_write_inodeblock_ufs1: already started");
10250         inodedep->id_state |= IOSTARTED;
10251         fs = inodedep->id_fs;
10252         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10253         LOCK_OWNED(ump);
10254         dp = (struct ufs1_dinode *)bp->b_data +
10255             ino_to_fsbo(fs, inodedep->id_ino);
10256
10257         /*
10258          * If we're on the unlinked list but have not yet written our
10259          * next pointer initialize it here.
10260          */
10261         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10262                 struct inodedep *inon;
10263
10264                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10265                 dp->di_freelink = inon ? inon->id_ino : 0;
10266         }
10267         /*
10268          * If the bitmap is not yet written, then the allocated
10269          * inode cannot be written to disk.
10270          */
10271         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10272                 if (inodedep->id_savedino1 != NULL)
10273                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10274                 FREE_LOCK(ump);
10275                 sip = malloc(sizeof(struct ufs1_dinode),
10276                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10277                 ACQUIRE_LOCK(ump);
10278                 inodedep->id_savedino1 = sip;
10279                 *inodedep->id_savedino1 = *dp;
10280                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10281                 dp->di_gen = inodedep->id_savedino1->di_gen;
10282                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10283                 return;
10284         }
10285         /*
10286          * If no dependencies, then there is nothing to roll back.
10287          */
10288         inodedep->id_savedsize = dp->di_size;
10289         inodedep->id_savedextsize = 0;
10290         inodedep->id_savednlink = dp->di_nlink;
10291         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10292             TAILQ_EMPTY(&inodedep->id_inoreflst))
10293                 return;
10294         /*
10295          * Revert the link count to that of the first unwritten journal entry.
10296          */
10297         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10298         if (inoref)
10299                 dp->di_nlink = inoref->if_nlink;
10300         /*
10301          * Set the dependencies to busy.
10302          */
10303         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10304              adp = TAILQ_NEXT(adp, ad_next)) {
10305 #ifdef INVARIANTS
10306                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10307                         panic("softdep_write_inodeblock: lbn order");
10308                 prevlbn = adp->ad_offset;
10309                 if (adp->ad_offset < UFS_NDADDR &&
10310                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10311                         panic("initiate_write_inodeblock_ufs1: "
10312                             "direct pointer #%jd mismatch %d != %jd",
10313                             (intmax_t)adp->ad_offset,
10314                             dp->di_db[adp->ad_offset],
10315                             (intmax_t)adp->ad_newblkno);
10316                 if (adp->ad_offset >= UFS_NDADDR &&
10317                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10318                         panic("initiate_write_inodeblock_ufs1: "
10319                             "indirect pointer #%jd mismatch %d != %jd",
10320                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10321                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10322                             (intmax_t)adp->ad_newblkno);
10323                 deplist |= 1 << adp->ad_offset;
10324                 if ((adp->ad_state & ATTACHED) == 0)
10325                         panic("initiate_write_inodeblock_ufs1: "
10326                             "Unknown state 0x%x", adp->ad_state);
10327 #endif /* INVARIANTS */
10328                 adp->ad_state &= ~ATTACHED;
10329                 adp->ad_state |= UNDONE;
10330         }
10331         /*
10332          * The on-disk inode cannot claim to be any larger than the last
10333          * fragment that has been written. Otherwise, the on-disk inode
10334          * might have fragments that were not the last block in the file
10335          * which would corrupt the filesystem.
10336          */
10337         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10338              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10339                 if (adp->ad_offset >= UFS_NDADDR)
10340                         break;
10341                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10342                 /* keep going until hitting a rollback to a frag */
10343                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10344                         continue;
10345                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10346                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10347 #ifdef INVARIANTS
10348                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10349                                 panic("initiate_write_inodeblock_ufs1: "
10350                                     "lost dep1");
10351 #endif /* INVARIANTS */
10352                         dp->di_db[i] = 0;
10353                 }
10354                 for (i = 0; i < UFS_NIADDR; i++) {
10355 #ifdef INVARIANTS
10356                         if (dp->di_ib[i] != 0 &&
10357                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10358                                 panic("initiate_write_inodeblock_ufs1: "
10359                                     "lost dep2");
10360 #endif /* INVARIANTS */
10361                         dp->di_ib[i] = 0;
10362                 }
10363                 return;
10364         }
10365         /*
10366          * If we have zero'ed out the last allocated block of the file,
10367          * roll back the size to the last currently allocated block.
10368          * We know that this last allocated block is a full-sized as
10369          * we already checked for fragments in the loop above.
10370          */
10371         if (lastadp != NULL &&
10372             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10373                 for (i = lastadp->ad_offset; i >= 0; i--)
10374                         if (dp->di_db[i] != 0)
10375                                 break;
10376                 dp->di_size = (i + 1) * fs->fs_bsize;
10377         }
10378         /*
10379          * The only dependencies are for indirect blocks.
10380          *
10381          * The file size for indirect block additions is not guaranteed.
10382          * Such a guarantee would be non-trivial to achieve. The conventional
10383          * synchronous write implementation also does not make this guarantee.
10384          * Fsck should catch and fix discrepancies. Arguably, the file size
10385          * can be over-estimated without destroying integrity when the file
10386          * moves into the indirect blocks (i.e., is large). If we want to
10387          * postpone fsck, we are stuck with this argument.
10388          */
10389         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10390                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10391 }
10392                 
10393 /*
10394  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10395  * Note that any bug fixes made to this routine must be done in the
10396  * version found above.
10397  *
10398  * Called from within the procedure above to deal with unsatisfied
10399  * allocation dependencies in an inodeblock. The buffer must be
10400  * locked, thus, no I/O completion operations can occur while we
10401  * are manipulating its associated dependencies.
10402  */
10403 static void 
10404 initiate_write_inodeblock_ufs2(inodedep, bp)
10405         struct inodedep *inodedep;
10406         struct buf *bp;                 /* The inode block */
10407 {
10408         struct allocdirect *adp, *lastadp;
10409         struct ufs2_dinode *dp;
10410         struct ufs2_dinode *sip;
10411         struct inoref *inoref;
10412         struct ufsmount *ump;
10413         struct fs *fs;
10414         ufs_lbn_t i;
10415 #ifdef INVARIANTS
10416         ufs_lbn_t prevlbn = 0;
10417 #endif
10418         int deplist;
10419
10420         if (inodedep->id_state & IOSTARTED)
10421                 panic("initiate_write_inodeblock_ufs2: already started");
10422         inodedep->id_state |= IOSTARTED;
10423         fs = inodedep->id_fs;
10424         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10425         LOCK_OWNED(ump);
10426         dp = (struct ufs2_dinode *)bp->b_data +
10427             ino_to_fsbo(fs, inodedep->id_ino);
10428
10429         /*
10430          * If we're on the unlinked list but have not yet written our
10431          * next pointer initialize it here.
10432          */
10433         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10434                 struct inodedep *inon;
10435
10436                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10437                 dp->di_freelink = inon ? inon->id_ino : 0;
10438                 ffs_update_dinode_ckhash(fs, dp);
10439         }
10440         /*
10441          * If the bitmap is not yet written, then the allocated
10442          * inode cannot be written to disk.
10443          */
10444         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10445                 if (inodedep->id_savedino2 != NULL)
10446                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10447                 FREE_LOCK(ump);
10448                 sip = malloc(sizeof(struct ufs2_dinode),
10449                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10450                 ACQUIRE_LOCK(ump);
10451                 inodedep->id_savedino2 = sip;
10452                 *inodedep->id_savedino2 = *dp;
10453                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10454                 dp->di_gen = inodedep->id_savedino2->di_gen;
10455                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10456                 return;
10457         }
10458         /*
10459          * If no dependencies, then there is nothing to roll back.
10460          */
10461         inodedep->id_savedsize = dp->di_size;
10462         inodedep->id_savedextsize = dp->di_extsize;
10463         inodedep->id_savednlink = dp->di_nlink;
10464         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10465             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10466             TAILQ_EMPTY(&inodedep->id_inoreflst))
10467                 return;
10468         /*
10469          * Revert the link count to that of the first unwritten journal entry.
10470          */
10471         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10472         if (inoref)
10473                 dp->di_nlink = inoref->if_nlink;
10474
10475         /*
10476          * Set the ext data dependencies to busy.
10477          */
10478         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10479              adp = TAILQ_NEXT(adp, ad_next)) {
10480 #ifdef INVARIANTS
10481                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10482                         panic("initiate_write_inodeblock_ufs2: lbn order");
10483                 prevlbn = adp->ad_offset;
10484                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10485                         panic("initiate_write_inodeblock_ufs2: "
10486                             "ext pointer #%jd mismatch %jd != %jd",
10487                             (intmax_t)adp->ad_offset,
10488                             (intmax_t)dp->di_extb[adp->ad_offset],
10489                             (intmax_t)adp->ad_newblkno);
10490                 deplist |= 1 << adp->ad_offset;
10491                 if ((adp->ad_state & ATTACHED) == 0)
10492                         panic("initiate_write_inodeblock_ufs2: Unknown "
10493                             "state 0x%x", adp->ad_state);
10494 #endif /* INVARIANTS */
10495                 adp->ad_state &= ~ATTACHED;
10496                 adp->ad_state |= UNDONE;
10497         }
10498         /*
10499          * The on-disk inode cannot claim to be any larger than the last
10500          * fragment that has been written. Otherwise, the on-disk inode
10501          * might have fragments that were not the last block in the ext
10502          * data which would corrupt the filesystem.
10503          */
10504         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10505              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10506                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10507                 /* keep going until hitting a rollback to a frag */
10508                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10509                         continue;
10510                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10511                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10512 #ifdef INVARIANTS
10513                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10514                                 panic("initiate_write_inodeblock_ufs2: "
10515                                     "lost dep1");
10516 #endif /* INVARIANTS */
10517                         dp->di_extb[i] = 0;
10518                 }
10519                 lastadp = NULL;
10520                 break;
10521         }
10522         /*
10523          * If we have zero'ed out the last allocated block of the ext
10524          * data, roll back the size to the last currently allocated block.
10525          * We know that this last allocated block is a full-sized as
10526          * we already checked for fragments in the loop above.
10527          */
10528         if (lastadp != NULL &&
10529             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10530                 for (i = lastadp->ad_offset; i >= 0; i--)
10531                         if (dp->di_extb[i] != 0)
10532                                 break;
10533                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10534         }
10535         /*
10536          * Set the file data dependencies to busy.
10537          */
10538         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10539              adp = TAILQ_NEXT(adp, ad_next)) {
10540 #ifdef INVARIANTS
10541                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10542                         panic("softdep_write_inodeblock: lbn order");
10543                 if ((adp->ad_state & ATTACHED) == 0)
10544                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10545                 prevlbn = adp->ad_offset;
10546                 if (adp->ad_offset < UFS_NDADDR &&
10547                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10548                         panic("initiate_write_inodeblock_ufs2: "
10549                             "direct pointer #%jd mismatch %jd != %jd",
10550                             (intmax_t)adp->ad_offset,
10551                             (intmax_t)dp->di_db[adp->ad_offset],
10552                             (intmax_t)adp->ad_newblkno);
10553                 if (adp->ad_offset >= UFS_NDADDR &&
10554                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10555                         panic("initiate_write_inodeblock_ufs2: "
10556                             "indirect pointer #%jd mismatch %jd != %jd",
10557                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10558                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10559                             (intmax_t)adp->ad_newblkno);
10560                 deplist |= 1 << adp->ad_offset;
10561                 if ((adp->ad_state & ATTACHED) == 0)
10562                         panic("initiate_write_inodeblock_ufs2: Unknown "
10563                              "state 0x%x", adp->ad_state);
10564 #endif /* INVARIANTS */
10565                 adp->ad_state &= ~ATTACHED;
10566                 adp->ad_state |= UNDONE;
10567         }
10568         /*
10569          * The on-disk inode cannot claim to be any larger than the last
10570          * fragment that has been written. Otherwise, the on-disk inode
10571          * might have fragments that were not the last block in the file
10572          * which would corrupt the filesystem.
10573          */
10574         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10575              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10576                 if (adp->ad_offset >= UFS_NDADDR)
10577                         break;
10578                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10579                 /* keep going until hitting a rollback to a frag */
10580                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10581                         continue;
10582                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10583                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10584 #ifdef INVARIANTS
10585                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10586                                 panic("initiate_write_inodeblock_ufs2: "
10587                                     "lost dep2");
10588 #endif /* INVARIANTS */
10589                         dp->di_db[i] = 0;
10590                 }
10591                 for (i = 0; i < UFS_NIADDR; i++) {
10592 #ifdef INVARIANTS
10593                         if (dp->di_ib[i] != 0 &&
10594                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10595                                 panic("initiate_write_inodeblock_ufs2: "
10596                                     "lost dep3");
10597 #endif /* INVARIANTS */
10598                         dp->di_ib[i] = 0;
10599                 }
10600                 ffs_update_dinode_ckhash(fs, dp);
10601                 return;
10602         }
10603         /*
10604          * If we have zero'ed out the last allocated block of the file,
10605          * roll back the size to the last currently allocated block.
10606          * We know that this last allocated block is a full-sized as
10607          * we already checked for fragments in the loop above.
10608          */
10609         if (lastadp != NULL &&
10610             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10611                 for (i = lastadp->ad_offset; i >= 0; i--)
10612                         if (dp->di_db[i] != 0)
10613                                 break;
10614                 dp->di_size = (i + 1) * fs->fs_bsize;
10615         }
10616         /*
10617          * The only dependencies are for indirect blocks.
10618          *
10619          * The file size for indirect block additions is not guaranteed.
10620          * Such a guarantee would be non-trivial to achieve. The conventional
10621          * synchronous write implementation also does not make this guarantee.
10622          * Fsck should catch and fix discrepancies. Arguably, the file size
10623          * can be over-estimated without destroying integrity when the file
10624          * moves into the indirect blocks (i.e., is large). If we want to
10625          * postpone fsck, we are stuck with this argument.
10626          */
10627         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10628                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10629         ffs_update_dinode_ckhash(fs, dp);
10630 }
10631
10632 /*
10633  * Cancel an indirdep as a result of truncation.  Release all of the
10634  * children allocindirs and place their journal work on the appropriate
10635  * list.
10636  */
10637 static void
10638 cancel_indirdep(indirdep, bp, freeblks)
10639         struct indirdep *indirdep;
10640         struct buf *bp;
10641         struct freeblks *freeblks;
10642 {
10643         struct allocindir *aip;
10644
10645         /*
10646          * None of the indirect pointers will ever be visible,
10647          * so they can simply be tossed. GOINGAWAY ensures
10648          * that allocated pointers will be saved in the buffer
10649          * cache until they are freed. Note that they will
10650          * only be able to be found by their physical address
10651          * since the inode mapping the logical address will
10652          * be gone. The save buffer used for the safe copy
10653          * was allocated in setup_allocindir_phase2 using
10654          * the physical address so it could be used for this
10655          * purpose. Hence we swap the safe copy with the real
10656          * copy, allowing the safe copy to be freed and holding
10657          * on to the real copy for later use in indir_trunc.
10658          */
10659         if (indirdep->ir_state & GOINGAWAY)
10660                 panic("cancel_indirdep: already gone");
10661         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10662                 indirdep->ir_state |= DEPCOMPLETE;
10663                 LIST_REMOVE(indirdep, ir_next);
10664         }
10665         indirdep->ir_state |= GOINGAWAY;
10666         /*
10667          * Pass in bp for blocks still have journal writes
10668          * pending so we can cancel them on their own.
10669          */
10670         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10671                 cancel_allocindir(aip, bp, freeblks, 0);
10672         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10673                 cancel_allocindir(aip, NULL, freeblks, 0);
10674         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10675                 cancel_allocindir(aip, NULL, freeblks, 0);
10676         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10677                 cancel_allocindir(aip, NULL, freeblks, 0);
10678         /*
10679          * If there are pending partial truncations we need to keep the
10680          * old block copy around until they complete.  This is because
10681          * the current b_data is not a perfect superset of the available
10682          * blocks.
10683          */
10684         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10685                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10686         else
10687                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10688         WORKLIST_REMOVE(&indirdep->ir_list);
10689         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10690         indirdep->ir_bp = NULL;
10691         indirdep->ir_freeblks = freeblks;
10692 }
10693
10694 /*
10695  * Free an indirdep once it no longer has new pointers to track.
10696  */
10697 static void
10698 free_indirdep(indirdep)
10699         struct indirdep *indirdep;
10700 {
10701
10702         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10703             ("free_indirdep: Indir trunc list not empty."));
10704         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10705             ("free_indirdep: Complete head not empty."));
10706         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10707             ("free_indirdep: write head not empty."));
10708         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10709             ("free_indirdep: done head not empty."));
10710         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10711             ("free_indirdep: deplist head not empty."));
10712         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10713             ("free_indirdep: %p still on newblk list.", indirdep));
10714         KASSERT(indirdep->ir_saveddata == NULL,
10715             ("free_indirdep: %p still has saved data.", indirdep));
10716         if (indirdep->ir_state & ONWORKLIST)
10717                 WORKLIST_REMOVE(&indirdep->ir_list);
10718         WORKITEM_FREE(indirdep, D_INDIRDEP);
10719 }
10720
10721 /*
10722  * Called before a write to an indirdep.  This routine is responsible for
10723  * rolling back pointers to a safe state which includes only those
10724  * allocindirs which have been completed.
10725  */
10726 static void
10727 initiate_write_indirdep(indirdep, bp)
10728         struct indirdep *indirdep;
10729         struct buf *bp;
10730 {
10731         struct ufsmount *ump;
10732
10733         indirdep->ir_state |= IOSTARTED;
10734         if (indirdep->ir_state & GOINGAWAY)
10735                 panic("disk_io_initiation: indirdep gone");
10736         /*
10737          * If there are no remaining dependencies, this will be writing
10738          * the real pointers.
10739          */
10740         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10741             TAILQ_EMPTY(&indirdep->ir_trunc))
10742                 return;
10743         /*
10744          * Replace up-to-date version with safe version.
10745          */
10746         if (indirdep->ir_saveddata == NULL) {
10747                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10748                 LOCK_OWNED(ump);
10749                 FREE_LOCK(ump);
10750                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10751                     M_SOFTDEP_FLAGS);
10752                 ACQUIRE_LOCK(ump);
10753         }
10754         indirdep->ir_state &= ~ATTACHED;
10755         indirdep->ir_state |= UNDONE;
10756         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10757         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10758             bp->b_bcount);
10759 }
10760
10761 /*
10762  * Called when an inode has been cleared in a cg bitmap.  This finally
10763  * eliminates any canceled jaddrefs
10764  */
10765 void
10766 softdep_setup_inofree(mp, bp, ino, wkhd)
10767         struct mount *mp;
10768         struct buf *bp;
10769         ino_t ino;
10770         struct workhead *wkhd;
10771 {
10772         struct worklist *wk, *wkn;
10773         struct inodedep *inodedep;
10774         struct ufsmount *ump;
10775         uint8_t *inosused;
10776         struct cg *cgp;
10777         struct fs *fs;
10778
10779         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10780             ("softdep_setup_inofree called on non-softdep filesystem"));
10781         ump = VFSTOUFS(mp);
10782         ACQUIRE_LOCK(ump);
10783         fs = ump->um_fs;
10784         cgp = (struct cg *)bp->b_data;
10785         inosused = cg_inosused(cgp);
10786         if (isset(inosused, ino % fs->fs_ipg))
10787                 panic("softdep_setup_inofree: inode %ju not freed.",
10788                     (uintmax_t)ino);
10789         if (inodedep_lookup(mp, ino, 0, &inodedep))
10790                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10791                     (uintmax_t)ino, inodedep);
10792         if (wkhd) {
10793                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10794                         if (wk->wk_type != D_JADDREF)
10795                                 continue;
10796                         WORKLIST_REMOVE(wk);
10797                         /*
10798                          * We can free immediately even if the jaddref
10799                          * isn't attached in a background write as now
10800                          * the bitmaps are reconciled.
10801                          */
10802                         wk->wk_state |= COMPLETE | ATTACHED;
10803                         free_jaddref(WK_JADDREF(wk));
10804                 }
10805                 jwork_move(&bp->b_dep, wkhd);
10806         }
10807         FREE_LOCK(ump);
10808 }
10809
10810 /*
10811  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10812  * map.  Any dependencies waiting for the write to clear are added to the
10813  * buf's list and any jnewblks that are being canceled are discarded
10814  * immediately.
10815  */
10816 void
10817 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10818         struct mount *mp;
10819         struct buf *bp;
10820         ufs2_daddr_t blkno;
10821         int frags;
10822         struct workhead *wkhd;
10823 {
10824         struct bmsafemap *bmsafemap;
10825         struct jnewblk *jnewblk;
10826         struct ufsmount *ump;
10827         struct worklist *wk;
10828         struct fs *fs;
10829 #ifdef INVARIANTS
10830         uint8_t *blksfree;
10831         struct cg *cgp;
10832         ufs2_daddr_t jstart;
10833         ufs2_daddr_t jend;
10834         ufs2_daddr_t end;
10835         long bno;
10836         int i;
10837 #endif
10838
10839         CTR3(KTR_SUJ,
10840             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10841             blkno, frags, wkhd);
10842
10843         ump = VFSTOUFS(mp);
10844         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10845             ("softdep_setup_blkfree called on non-softdep filesystem"));
10846         ACQUIRE_LOCK(ump);
10847         /* Lookup the bmsafemap so we track when it is dirty. */
10848         fs = ump->um_fs;
10849         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10850         /*
10851          * Detach any jnewblks which have been canceled.  They must linger
10852          * until the bitmap is cleared again by ffs_blkfree() to prevent
10853          * an unjournaled allocation from hitting the disk.
10854          */
10855         if (wkhd) {
10856                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10857                         CTR2(KTR_SUJ,
10858                             "softdep_setup_blkfree: blkno %jd wk type %d",
10859                             blkno, wk->wk_type);
10860                         WORKLIST_REMOVE(wk);
10861                         if (wk->wk_type != D_JNEWBLK) {
10862                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10863                                 continue;
10864                         }
10865                         jnewblk = WK_JNEWBLK(wk);
10866                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10867                             ("softdep_setup_blkfree: jnewblk not canceled."));
10868 #ifdef INVARIANTS
10869                         /*
10870                          * Assert that this block is free in the bitmap
10871                          * before we discard the jnewblk.
10872                          */
10873                         cgp = (struct cg *)bp->b_data;
10874                         blksfree = cg_blksfree(cgp);
10875                         bno = dtogd(fs, jnewblk->jn_blkno);
10876                         for (i = jnewblk->jn_oldfrags;
10877                             i < jnewblk->jn_frags; i++) {
10878                                 if (isset(blksfree, bno + i))
10879                                         continue;
10880                                 panic("softdep_setup_blkfree: not free");
10881                         }
10882 #endif
10883                         /*
10884                          * Even if it's not attached we can free immediately
10885                          * as the new bitmap is correct.
10886                          */
10887                         wk->wk_state |= COMPLETE | ATTACHED;
10888                         free_jnewblk(jnewblk);
10889                 }
10890         }
10891
10892 #ifdef INVARIANTS
10893         /*
10894          * Assert that we are not freeing a block which has an outstanding
10895          * allocation dependency.
10896          */
10897         fs = VFSTOUFS(mp)->um_fs;
10898         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10899         end = blkno + frags;
10900         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10901                 /*
10902                  * Don't match against blocks that will be freed when the
10903                  * background write is done.
10904                  */
10905                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10906                     (COMPLETE | DEPCOMPLETE))
10907                         continue;
10908                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10909                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10910                 if ((blkno >= jstart && blkno < jend) ||
10911                     (end > jstart && end <= jend)) {
10912                         printf("state 0x%X %jd - %d %d dep %p\n",
10913                             jnewblk->jn_state, jnewblk->jn_blkno,
10914                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10915                             jnewblk->jn_dep);
10916                         panic("softdep_setup_blkfree: "
10917                             "%jd-%jd(%d) overlaps with %jd-%jd",
10918                             blkno, end, frags, jstart, jend);
10919                 }
10920         }
10921 #endif
10922         FREE_LOCK(ump);
10923 }
10924
10925 /*
10926  * Revert a block allocation when the journal record that describes it
10927  * is not yet written.
10928  */
10929 static int
10930 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10931         struct jnewblk *jnewblk;
10932         struct fs *fs;
10933         struct cg *cgp;
10934         uint8_t *blksfree;
10935 {
10936         ufs1_daddr_t fragno;
10937         long cgbno, bbase;
10938         int frags, blk;
10939         int i;
10940
10941         frags = 0;
10942         cgbno = dtogd(fs, jnewblk->jn_blkno);
10943         /*
10944          * We have to test which frags need to be rolled back.  We may
10945          * be operating on a stale copy when doing background writes.
10946          */
10947         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10948                 if (isclr(blksfree, cgbno + i))
10949                         frags++;
10950         if (frags == 0)
10951                 return (0);
10952         /*
10953          * This is mostly ffs_blkfree() sans some validation and
10954          * superblock updates.
10955          */
10956         if (frags == fs->fs_frag) {
10957                 fragno = fragstoblks(fs, cgbno);
10958                 ffs_setblock(fs, blksfree, fragno);
10959                 ffs_clusteracct(fs, cgp, fragno, 1);
10960                 cgp->cg_cs.cs_nbfree++;
10961         } else {
10962                 cgbno += jnewblk->jn_oldfrags;
10963                 bbase = cgbno - fragnum(fs, cgbno);
10964                 /* Decrement the old frags.  */
10965                 blk = blkmap(fs, blksfree, bbase);
10966                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10967                 /* Deallocate the fragment */
10968                 for (i = 0; i < frags; i++)
10969                         setbit(blksfree, cgbno + i);
10970                 cgp->cg_cs.cs_nffree += frags;
10971                 /* Add back in counts associated with the new frags */
10972                 blk = blkmap(fs, blksfree, bbase);
10973                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10974                 /* If a complete block has been reassembled, account for it. */
10975                 fragno = fragstoblks(fs, bbase);
10976                 if (ffs_isblock(fs, blksfree, fragno)) {
10977                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10978                         ffs_clusteracct(fs, cgp, fragno, 1);
10979                         cgp->cg_cs.cs_nbfree++;
10980                 }
10981         }
10982         stat_jnewblk++;
10983         jnewblk->jn_state &= ~ATTACHED;
10984         jnewblk->jn_state |= UNDONE;
10985
10986         return (frags);
10987 }
10988
10989 static void
10990 initiate_write_bmsafemap(bmsafemap, bp)
10991         struct bmsafemap *bmsafemap;
10992         struct buf *bp;                 /* The cg block. */
10993 {
10994         struct jaddref *jaddref;
10995         struct jnewblk *jnewblk;
10996         uint8_t *inosused;
10997         uint8_t *blksfree;
10998         struct cg *cgp;
10999         struct fs *fs;
11000         ino_t ino;
11001
11002         /*
11003          * If this is a background write, we did this at the time that
11004          * the copy was made, so do not need to do it again.
11005          */
11006         if (bmsafemap->sm_state & IOSTARTED)
11007                 return;
11008         bmsafemap->sm_state |= IOSTARTED;
11009         /*
11010          * Clear any inode allocations which are pending journal writes.
11011          */
11012         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11013                 cgp = (struct cg *)bp->b_data;
11014                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11015                 inosused = cg_inosused(cgp);
11016                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11017                         ino = jaddref->ja_ino % fs->fs_ipg;
11018                         if (isset(inosused, ino)) {
11019                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11020                                         cgp->cg_cs.cs_ndir--;
11021                                 cgp->cg_cs.cs_nifree++;
11022                                 clrbit(inosused, ino);
11023                                 jaddref->ja_state &= ~ATTACHED;
11024                                 jaddref->ja_state |= UNDONE;
11025                                 stat_jaddref++;
11026                         } else
11027                                 panic("initiate_write_bmsafemap: inode %ju "
11028                                     "marked free", (uintmax_t)jaddref->ja_ino);
11029                 }
11030         }
11031         /*
11032          * Clear any block allocations which are pending journal writes.
11033          */
11034         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11035                 cgp = (struct cg *)bp->b_data;
11036                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11037                 blksfree = cg_blksfree(cgp);
11038                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11039                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11040                                 continue;
11041                         panic("initiate_write_bmsafemap: block %jd "
11042                             "marked free", jnewblk->jn_blkno);
11043                 }
11044         }
11045         /*
11046          * Move allocation lists to the written lists so they can be
11047          * cleared once the block write is complete.
11048          */
11049         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11050             inodedep, id_deps);
11051         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11052             newblk, nb_deps);
11053         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11054             wk_list);
11055 }
11056
11057 /*
11058  * This routine is called during the completion interrupt
11059  * service routine for a disk write (from the procedure called
11060  * by the device driver to inform the filesystem caches of
11061  * a request completion).  It should be called early in this
11062  * procedure, before the block is made available to other
11063  * processes or other routines are called.
11064  *
11065  */
11066 static void 
11067 softdep_disk_write_complete(bp)
11068         struct buf *bp;         /* describes the completed disk write */
11069 {
11070         struct worklist *wk;
11071         struct worklist *owk;
11072         struct ufsmount *ump;
11073         struct workhead reattach;
11074         struct freeblks *freeblks;
11075         struct buf *sbp;
11076
11077         ump = softdep_bp_to_mp(bp);
11078         KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11079             ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11080              "with outstanding dependencies for buffer %p", bp));
11081         if (ump == NULL)
11082                 return;
11083         /*
11084          * If an error occurred while doing the write, then the data
11085          * has not hit the disk and the dependencies cannot be processed.
11086          * But we do have to go through and roll forward any dependencies
11087          * that were rolled back before the disk write.
11088          */
11089         sbp = NULL;
11090         ACQUIRE_LOCK(ump);
11091         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11092                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11093                         switch (wk->wk_type) {
11094
11095                         case D_PAGEDEP:
11096                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11097                                 continue;
11098
11099                         case D_INODEDEP:
11100                                 handle_written_inodeblock(WK_INODEDEP(wk),
11101                                     bp, 0);
11102                                 continue;
11103
11104                         case D_BMSAFEMAP:
11105                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11106                                     bp, 0);
11107                                 continue;
11108
11109                         case D_INDIRDEP:
11110                                 handle_written_indirdep(WK_INDIRDEP(wk),
11111                                     bp, &sbp, 0);
11112                                 continue;
11113                         default:
11114                                 /* nothing to roll forward */
11115                                 continue;
11116                         }
11117                 }
11118                 FREE_LOCK(ump);
11119                 if (sbp)
11120                         brelse(sbp);
11121                 return;
11122         }
11123         LIST_INIT(&reattach);
11124
11125         /*
11126          * Ump SU lock must not be released anywhere in this code segment.
11127          */
11128         owk = NULL;
11129         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11130                 WORKLIST_REMOVE(wk);
11131                 atomic_add_long(&dep_write[wk->wk_type], 1);
11132                 if (wk == owk)
11133                         panic("duplicate worklist: %p\n", wk);
11134                 owk = wk;
11135                 switch (wk->wk_type) {
11136
11137                 case D_PAGEDEP:
11138                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11139                             WRITESUCCEEDED))
11140                                 WORKLIST_INSERT(&reattach, wk);
11141                         continue;
11142
11143                 case D_INODEDEP:
11144                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11145                             WRITESUCCEEDED))
11146                                 WORKLIST_INSERT(&reattach, wk);
11147                         continue;
11148
11149                 case D_BMSAFEMAP:
11150                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11151                             WRITESUCCEEDED))
11152                                 WORKLIST_INSERT(&reattach, wk);
11153                         continue;
11154
11155                 case D_MKDIR:
11156                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11157                         continue;
11158
11159                 case D_ALLOCDIRECT:
11160                         wk->wk_state |= COMPLETE;
11161                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11162                         continue;
11163
11164                 case D_ALLOCINDIR:
11165                         wk->wk_state |= COMPLETE;
11166                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11167                         continue;
11168
11169                 case D_INDIRDEP:
11170                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11171                             WRITESUCCEEDED))
11172                                 WORKLIST_INSERT(&reattach, wk);
11173                         continue;
11174
11175                 case D_FREEBLKS:
11176                         wk->wk_state |= COMPLETE;
11177                         freeblks = WK_FREEBLKS(wk);
11178                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11179                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11180                                 add_to_worklist(wk, WK_NODELAY);
11181                         continue;
11182
11183                 case D_FREEWORK:
11184                         handle_written_freework(WK_FREEWORK(wk));
11185                         break;
11186
11187                 case D_JSEGDEP:
11188                         free_jsegdep(WK_JSEGDEP(wk));
11189                         continue;
11190
11191                 case D_JSEG:
11192                         handle_written_jseg(WK_JSEG(wk), bp);
11193                         continue;
11194
11195                 case D_SBDEP:
11196                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11197                                 WORKLIST_INSERT(&reattach, wk);
11198                         continue;
11199
11200                 case D_FREEDEP:
11201                         free_freedep(WK_FREEDEP(wk));
11202                         continue;
11203
11204                 default:
11205                         panic("handle_disk_write_complete: Unknown type %s",
11206                             TYPENAME(wk->wk_type));
11207                         /* NOTREACHED */
11208                 }
11209         }
11210         /*
11211          * Reattach any requests that must be redone.
11212          */
11213         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11214                 WORKLIST_REMOVE(wk);
11215                 WORKLIST_INSERT(&bp->b_dep, wk);
11216         }
11217         FREE_LOCK(ump);
11218         if (sbp)
11219                 brelse(sbp);
11220 }
11221
11222 /*
11223  * Called from within softdep_disk_write_complete above.
11224  */
11225 static void 
11226 handle_allocdirect_partdone(adp, wkhd)
11227         struct allocdirect *adp;        /* the completed allocdirect */
11228         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11229 {
11230         struct allocdirectlst *listhead;
11231         struct allocdirect *listadp;
11232         struct inodedep *inodedep;
11233         long bsize;
11234
11235         LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11236         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11237                 return;
11238         /*
11239          * The on-disk inode cannot claim to be any larger than the last
11240          * fragment that has been written. Otherwise, the on-disk inode
11241          * might have fragments that were not the last block in the file
11242          * which would corrupt the filesystem. Thus, we cannot free any
11243          * allocdirects after one whose ad_oldblkno claims a fragment as
11244          * these blocks must be rolled back to zero before writing the inode.
11245          * We check the currently active set of allocdirects in id_inoupdt
11246          * or id_extupdt as appropriate.
11247          */
11248         inodedep = adp->ad_inodedep;
11249         bsize = inodedep->id_fs->fs_bsize;
11250         if (adp->ad_state & EXTDATA)
11251                 listhead = &inodedep->id_extupdt;
11252         else
11253                 listhead = &inodedep->id_inoupdt;
11254         TAILQ_FOREACH(listadp, listhead, ad_next) {
11255                 /* found our block */
11256                 if (listadp == adp)
11257                         break;
11258                 /* continue if ad_oldlbn is not a fragment */
11259                 if (listadp->ad_oldsize == 0 ||
11260                     listadp->ad_oldsize == bsize)
11261                         continue;
11262                 /* hit a fragment */
11263                 return;
11264         }
11265         /*
11266          * If we have reached the end of the current list without
11267          * finding the just finished dependency, then it must be
11268          * on the future dependency list. Future dependencies cannot
11269          * be freed until they are moved to the current list.
11270          */
11271         if (listadp == NULL) {
11272 #ifdef INVARIANTS
11273                 if (adp->ad_state & EXTDATA)
11274                         listhead = &inodedep->id_newextupdt;
11275                 else
11276                         listhead = &inodedep->id_newinoupdt;
11277                 TAILQ_FOREACH(listadp, listhead, ad_next)
11278                         /* found our block */
11279                         if (listadp == adp)
11280                                 break;
11281                 if (listadp == NULL)
11282                         panic("handle_allocdirect_partdone: lost dep");
11283 #endif /* INVARIANTS */
11284                 return;
11285         }
11286         /*
11287          * If we have found the just finished dependency, then queue
11288          * it along with anything that follows it that is complete.
11289          * Since the pointer has not yet been written in the inode
11290          * as the dependency prevents it, place the allocdirect on the
11291          * bufwait list where it will be freed once the pointer is
11292          * valid.
11293          */
11294         if (wkhd == NULL)
11295                 wkhd = &inodedep->id_bufwait;
11296         for (; adp; adp = listadp) {
11297                 listadp = TAILQ_NEXT(adp, ad_next);
11298                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11299                         return;
11300                 TAILQ_REMOVE(listhead, adp, ad_next);
11301                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11302         }
11303 }
11304
11305 /*
11306  * Called from within softdep_disk_write_complete above.  This routine
11307  * completes successfully written allocindirs.
11308  */
11309 static void
11310 handle_allocindir_partdone(aip)
11311         struct allocindir *aip;         /* the completed allocindir */
11312 {
11313         struct indirdep *indirdep;
11314
11315         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11316                 return;
11317         indirdep = aip->ai_indirdep;
11318         LIST_REMOVE(aip, ai_next);
11319         /*
11320          * Don't set a pointer while the buffer is undergoing IO or while
11321          * we have active truncations.
11322          */
11323         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11324                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11325                 return;
11326         }
11327         if (indirdep->ir_state & UFS1FMT)
11328                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11329                     aip->ai_newblkno;
11330         else
11331                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11332                     aip->ai_newblkno;
11333         /*
11334          * Await the pointer write before freeing the allocindir.
11335          */
11336         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11337 }
11338
11339 /*
11340  * Release segments held on a jwork list.
11341  */
11342 static void
11343 handle_jwork(wkhd)
11344         struct workhead *wkhd;
11345 {
11346         struct worklist *wk;
11347
11348         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11349                 WORKLIST_REMOVE(wk);
11350                 switch (wk->wk_type) {
11351                 case D_JSEGDEP:
11352                         free_jsegdep(WK_JSEGDEP(wk));
11353                         continue;
11354                 case D_FREEDEP:
11355                         free_freedep(WK_FREEDEP(wk));
11356                         continue;
11357                 case D_FREEFRAG:
11358                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11359                         WORKITEM_FREE(wk, D_FREEFRAG);
11360                         continue;
11361                 case D_FREEWORK:
11362                         handle_written_freework(WK_FREEWORK(wk));
11363                         continue;
11364                 default:
11365                         panic("handle_jwork: Unknown type %s\n",
11366                             TYPENAME(wk->wk_type));
11367                 }
11368         }
11369 }
11370
11371 /*
11372  * Handle the bufwait list on an inode when it is safe to release items
11373  * held there.  This normally happens after an inode block is written but
11374  * may be delayed and handled later if there are pending journal items that
11375  * are not yet safe to be released.
11376  */
11377 static struct freefile *
11378 handle_bufwait(inodedep, refhd)
11379         struct inodedep *inodedep;
11380         struct workhead *refhd;
11381 {
11382         struct jaddref *jaddref;
11383         struct freefile *freefile;
11384         struct worklist *wk;
11385
11386         freefile = NULL;
11387         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11388                 WORKLIST_REMOVE(wk);
11389                 switch (wk->wk_type) {
11390                 case D_FREEFILE:
11391                         /*
11392                          * We defer adding freefile to the worklist
11393                          * until all other additions have been made to
11394                          * ensure that it will be done after all the
11395                          * old blocks have been freed.
11396                          */
11397                         if (freefile != NULL)
11398                                 panic("handle_bufwait: freefile");
11399                         freefile = WK_FREEFILE(wk);
11400                         continue;
11401
11402                 case D_MKDIR:
11403                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11404                         continue;
11405
11406                 case D_DIRADD:
11407                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11408                         continue;
11409
11410                 case D_FREEFRAG:
11411                         wk->wk_state |= COMPLETE;
11412                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11413                                 add_to_worklist(wk, 0);
11414                         continue;
11415
11416                 case D_DIRREM:
11417                         wk->wk_state |= COMPLETE;
11418                         add_to_worklist(wk, 0);
11419                         continue;
11420
11421                 case D_ALLOCDIRECT:
11422                 case D_ALLOCINDIR:
11423                         free_newblk(WK_NEWBLK(wk));
11424                         continue;
11425
11426                 case D_JNEWBLK:
11427                         wk->wk_state |= COMPLETE;
11428                         free_jnewblk(WK_JNEWBLK(wk));
11429                         continue;
11430
11431                 /*
11432                  * Save freed journal segments and add references on
11433                  * the supplied list which will delay their release
11434                  * until the cg bitmap is cleared on disk.
11435                  */
11436                 case D_JSEGDEP:
11437                         if (refhd == NULL)
11438                                 free_jsegdep(WK_JSEGDEP(wk));
11439                         else
11440                                 WORKLIST_INSERT(refhd, wk);
11441                         continue;
11442
11443                 case D_JADDREF:
11444                         jaddref = WK_JADDREF(wk);
11445                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11446                             if_deps);
11447                         /*
11448                          * Transfer any jaddrefs to the list to be freed with
11449                          * the bitmap if we're handling a removed file.
11450                          */
11451                         if (refhd == NULL) {
11452                                 wk->wk_state |= COMPLETE;
11453                                 free_jaddref(jaddref);
11454                         } else
11455                                 WORKLIST_INSERT(refhd, wk);
11456                         continue;
11457
11458                 default:
11459                         panic("handle_bufwait: Unknown type %p(%s)",
11460                             wk, TYPENAME(wk->wk_type));
11461                         /* NOTREACHED */
11462                 }
11463         }
11464         return (freefile);
11465 }
11466 /*
11467  * Called from within softdep_disk_write_complete above to restore
11468  * in-memory inode block contents to their most up-to-date state. Note
11469  * that this routine is always called from interrupt level with further
11470  * interrupts from this device blocked.
11471  *
11472  * If the write did not succeed, we will do all the roll-forward
11473  * operations, but we will not take the actions that will allow its
11474  * dependencies to be processed.
11475  */
11476 static int 
11477 handle_written_inodeblock(inodedep, bp, flags)
11478         struct inodedep *inodedep;
11479         struct buf *bp;         /* buffer containing the inode block */
11480         int flags;
11481 {
11482         struct freefile *freefile;
11483         struct allocdirect *adp, *nextadp;
11484         struct ufs1_dinode *dp1 = NULL;
11485         struct ufs2_dinode *dp2 = NULL;
11486         struct workhead wkhd;
11487         int hadchanges, fstype;
11488         ino_t freelink;
11489
11490         LIST_INIT(&wkhd);
11491         hadchanges = 0;
11492         freefile = NULL;
11493         if ((inodedep->id_state & IOSTARTED) == 0)
11494                 panic("handle_written_inodeblock: not started");
11495         inodedep->id_state &= ~IOSTARTED;
11496         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11497                 fstype = UFS1;
11498                 dp1 = (struct ufs1_dinode *)bp->b_data +
11499                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11500                 freelink = dp1->di_freelink;
11501         } else {
11502                 fstype = UFS2;
11503                 dp2 = (struct ufs2_dinode *)bp->b_data +
11504                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11505                 freelink = dp2->di_freelink;
11506         }
11507         /*
11508          * Leave this inodeblock dirty until it's in the list.
11509          */
11510         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11511             (flags & WRITESUCCEEDED)) {
11512                 struct inodedep *inon;
11513
11514                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11515                 if ((inon == NULL && freelink == 0) ||
11516                     (inon && inon->id_ino == freelink)) {
11517                         if (inon)
11518                                 inon->id_state |= UNLINKPREV;
11519                         inodedep->id_state |= UNLINKNEXT;
11520                 }
11521                 hadchanges = 1;
11522         }
11523         /*
11524          * If we had to rollback the inode allocation because of
11525          * bitmaps being incomplete, then simply restore it.
11526          * Keep the block dirty so that it will not be reclaimed until
11527          * all associated dependencies have been cleared and the
11528          * corresponding updates written to disk.
11529          */
11530         if (inodedep->id_savedino1 != NULL) {
11531                 hadchanges = 1;
11532                 if (fstype == UFS1)
11533                         *dp1 = *inodedep->id_savedino1;
11534                 else
11535                         *dp2 = *inodedep->id_savedino2;
11536                 free(inodedep->id_savedino1, M_SAVEDINO);
11537                 inodedep->id_savedino1 = NULL;
11538                 if ((bp->b_flags & B_DELWRI) == 0)
11539                         stat_inode_bitmap++;
11540                 bdirty(bp);
11541                 /*
11542                  * If the inode is clear here and GOINGAWAY it will never
11543                  * be written.  Process the bufwait and clear any pending
11544                  * work which may include the freefile.
11545                  */
11546                 if (inodedep->id_state & GOINGAWAY)
11547                         goto bufwait;
11548                 return (1);
11549         }
11550         if (flags & WRITESUCCEEDED)
11551                 inodedep->id_state |= COMPLETE;
11552         /*
11553          * Roll forward anything that had to be rolled back before 
11554          * the inode could be updated.
11555          */
11556         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11557                 nextadp = TAILQ_NEXT(adp, ad_next);
11558                 if (adp->ad_state & ATTACHED)
11559                         panic("handle_written_inodeblock: new entry");
11560                 if (fstype == UFS1) {
11561                         if (adp->ad_offset < UFS_NDADDR) {
11562                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11563                                         panic("%s %s #%jd mismatch %d != %jd",
11564                                             "handle_written_inodeblock:",
11565                                             "direct pointer",
11566                                             (intmax_t)adp->ad_offset,
11567                                             dp1->di_db[adp->ad_offset],
11568                                             (intmax_t)adp->ad_oldblkno);
11569                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11570                         } else {
11571                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11572                                     0)
11573                                         panic("%s: %s #%jd allocated as %d",
11574                                             "handle_written_inodeblock",
11575                                             "indirect pointer",
11576                                             (intmax_t)adp->ad_offset -
11577                                             UFS_NDADDR,
11578                                             dp1->di_ib[adp->ad_offset -
11579                                             UFS_NDADDR]);
11580                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11581                                     adp->ad_newblkno;
11582                         }
11583                 } else {
11584                         if (adp->ad_offset < UFS_NDADDR) {
11585                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11586                                         panic("%s: %s #%jd %s %jd != %jd",
11587                                             "handle_written_inodeblock",
11588                                             "direct pointer",
11589                                             (intmax_t)adp->ad_offset, "mismatch",
11590                                             (intmax_t)dp2->di_db[adp->ad_offset],
11591                                             (intmax_t)adp->ad_oldblkno);
11592                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11593                         } else {
11594                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11595                                     0)
11596                                         panic("%s: %s #%jd allocated as %jd",
11597                                             "handle_written_inodeblock",
11598                                             "indirect pointer",
11599                                             (intmax_t)adp->ad_offset -
11600                                             UFS_NDADDR,
11601                                             (intmax_t)
11602                                             dp2->di_ib[adp->ad_offset -
11603                                             UFS_NDADDR]);
11604                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11605                                     adp->ad_newblkno;
11606                         }
11607                 }
11608                 adp->ad_state &= ~UNDONE;
11609                 adp->ad_state |= ATTACHED;
11610                 hadchanges = 1;
11611         }
11612         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11613                 nextadp = TAILQ_NEXT(adp, ad_next);
11614                 if (adp->ad_state & ATTACHED)
11615                         panic("handle_written_inodeblock: new entry");
11616                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11617                         panic("%s: direct pointers #%jd %s %jd != %jd",
11618                             "handle_written_inodeblock",
11619                             (intmax_t)adp->ad_offset, "mismatch",
11620                             (intmax_t)dp2->di_extb[adp->ad_offset],
11621                             (intmax_t)adp->ad_oldblkno);
11622                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11623                 adp->ad_state &= ~UNDONE;
11624                 adp->ad_state |= ATTACHED;
11625                 hadchanges = 1;
11626         }
11627         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11628                 stat_direct_blk_ptrs++;
11629         /*
11630          * Reset the file size to its most up-to-date value.
11631          */
11632         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11633                 panic("handle_written_inodeblock: bad size");
11634         if (inodedep->id_savednlink > UFS_LINK_MAX)
11635                 panic("handle_written_inodeblock: Invalid link count "
11636                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11637                     inodedep);
11638         if (fstype == UFS1) {
11639                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11640                         dp1->di_nlink = inodedep->id_savednlink;
11641                         hadchanges = 1;
11642                 }
11643                 if (dp1->di_size != inodedep->id_savedsize) {
11644                         dp1->di_size = inodedep->id_savedsize;
11645                         hadchanges = 1;
11646                 }
11647         } else {
11648                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11649                         dp2->di_nlink = inodedep->id_savednlink;
11650                         hadchanges = 1;
11651                 }
11652                 if (dp2->di_size != inodedep->id_savedsize) {
11653                         dp2->di_size = inodedep->id_savedsize;
11654                         hadchanges = 1;
11655                 }
11656                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11657                         dp2->di_extsize = inodedep->id_savedextsize;
11658                         hadchanges = 1;
11659                 }
11660         }
11661         inodedep->id_savedsize = -1;
11662         inodedep->id_savedextsize = -1;
11663         inodedep->id_savednlink = -1;
11664         /*
11665          * If there were any rollbacks in the inode block, then it must be
11666          * marked dirty so that its will eventually get written back in
11667          * its correct form.
11668          */
11669         if (hadchanges) {
11670                 if (fstype == UFS2)
11671                         ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11672                 bdirty(bp);
11673         }
11674 bufwait:
11675         /*
11676          * If the write did not succeed, we have done all the roll-forward
11677          * operations, but we cannot take the actions that will allow its
11678          * dependencies to be processed.
11679          */
11680         if ((flags & WRITESUCCEEDED) == 0)
11681                 return (hadchanges);
11682         /*
11683          * Process any allocdirects that completed during the update.
11684          */
11685         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11686                 handle_allocdirect_partdone(adp, &wkhd);
11687         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11688                 handle_allocdirect_partdone(adp, &wkhd);
11689         /*
11690          * Process deallocations that were held pending until the
11691          * inode had been written to disk. Freeing of the inode
11692          * is delayed until after all blocks have been freed to
11693          * avoid creation of new <vfsid, inum, lbn> triples
11694          * before the old ones have been deleted.  Completely
11695          * unlinked inodes are not processed until the unlinked
11696          * inode list is written or the last reference is removed.
11697          */
11698         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11699                 freefile = handle_bufwait(inodedep, NULL);
11700                 if (freefile && !LIST_EMPTY(&wkhd)) {
11701                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11702                         freefile = NULL;
11703                 }
11704         }
11705         /*
11706          * Move rolled forward dependency completions to the bufwait list
11707          * now that those that were already written have been processed.
11708          */
11709         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11710                 panic("handle_written_inodeblock: bufwait but no changes");
11711         jwork_move(&inodedep->id_bufwait, &wkhd);
11712
11713         if (freefile != NULL) {
11714                 /*
11715                  * If the inode is goingaway it was never written.  Fake up
11716                  * the state here so free_inodedep() can succeed.
11717                  */
11718                 if (inodedep->id_state & GOINGAWAY)
11719                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11720                 if (free_inodedep(inodedep) == 0)
11721                         panic("handle_written_inodeblock: live inodedep %p",
11722                             inodedep);
11723                 add_to_worklist(&freefile->fx_list, 0);
11724                 return (0);
11725         }
11726
11727         /*
11728          * If no outstanding dependencies, free it.
11729          */
11730         if (free_inodedep(inodedep) ||
11731             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11732              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11733              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11734              LIST_FIRST(&inodedep->id_bufwait) == 0))
11735                 return (0);
11736         return (hadchanges);
11737 }
11738
11739 /*
11740  * Perform needed roll-forwards and kick off any dependencies that
11741  * can now be processed.
11742  *
11743  * If the write did not succeed, we will do all the roll-forward
11744  * operations, but we will not take the actions that will allow its
11745  * dependencies to be processed.
11746  */
11747 static int
11748 handle_written_indirdep(indirdep, bp, bpp, flags)
11749         struct indirdep *indirdep;
11750         struct buf *bp;
11751         struct buf **bpp;
11752         int flags;
11753 {
11754         struct allocindir *aip;
11755         struct buf *sbp;
11756         int chgs;
11757
11758         if (indirdep->ir_state & GOINGAWAY)
11759                 panic("handle_written_indirdep: indirdep gone");
11760         if ((indirdep->ir_state & IOSTARTED) == 0)
11761                 panic("handle_written_indirdep: IO not started");
11762         chgs = 0;
11763         /*
11764          * If there were rollbacks revert them here.
11765          */
11766         if (indirdep->ir_saveddata) {
11767                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11768                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11769                         free(indirdep->ir_saveddata, M_INDIRDEP);
11770                         indirdep->ir_saveddata = NULL;
11771                 }
11772                 chgs = 1;
11773         }
11774         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11775         indirdep->ir_state |= ATTACHED;
11776         /*
11777          * If the write did not succeed, we have done all the roll-forward
11778          * operations, but we cannot take the actions that will allow its
11779          * dependencies to be processed.
11780          */
11781         if ((flags & WRITESUCCEEDED) == 0) {
11782                 stat_indir_blk_ptrs++;
11783                 bdirty(bp);
11784                 return (1);
11785         }
11786         /*
11787          * Move allocindirs with written pointers to the completehd if
11788          * the indirdep's pointer is not yet written.  Otherwise
11789          * free them here.
11790          */
11791         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11792                 LIST_REMOVE(aip, ai_next);
11793                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11794                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11795                             ai_next);
11796                         newblk_freefrag(&aip->ai_block);
11797                         continue;
11798                 }
11799                 free_newblk(&aip->ai_block);
11800         }
11801         /*
11802          * Move allocindirs that have finished dependency processing from
11803          * the done list to the write list after updating the pointers.
11804          */
11805         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11806                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11807                         handle_allocindir_partdone(aip);
11808                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11809                                 panic("disk_write_complete: not gone");
11810                         chgs = 1;
11811                 }
11812         }
11813         /*
11814          * Preserve the indirdep if there were any changes or if it is not
11815          * yet valid on disk.
11816          */
11817         if (chgs) {
11818                 stat_indir_blk_ptrs++;
11819                 bdirty(bp);
11820                 return (1);
11821         }
11822         /*
11823          * If there were no changes we can discard the savedbp and detach
11824          * ourselves from the buf.  We are only carrying completed pointers
11825          * in this case.
11826          */
11827         sbp = indirdep->ir_savebp;
11828         sbp->b_flags |= B_INVAL | B_NOCACHE;
11829         indirdep->ir_savebp = NULL;
11830         indirdep->ir_bp = NULL;
11831         if (*bpp != NULL)
11832                 panic("handle_written_indirdep: bp already exists.");
11833         *bpp = sbp;
11834         /*
11835          * The indirdep may not be freed until its parent points at it.
11836          */
11837         if (indirdep->ir_state & DEPCOMPLETE)
11838                 free_indirdep(indirdep);
11839
11840         return (0);
11841 }
11842
11843 /*
11844  * Process a diradd entry after its dependent inode has been written.
11845  */
11846 static void
11847 diradd_inode_written(dap, inodedep)
11848         struct diradd *dap;
11849         struct inodedep *inodedep;
11850 {
11851
11852         LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11853         dap->da_state |= COMPLETE;
11854         complete_diradd(dap);
11855         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11856 }
11857
11858 /*
11859  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11860  * be called with the per-filesystem lock and the buf lock on the cg held.
11861  */
11862 static int
11863 bmsafemap_backgroundwrite(bmsafemap, bp)
11864         struct bmsafemap *bmsafemap;
11865         struct buf *bp;
11866 {
11867         int dirty;
11868
11869         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11870         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11871             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11872         /*
11873          * If we're initiating a background write we need to process the
11874          * rollbacks as they exist now, not as they exist when IO starts.
11875          * No other consumers will look at the contents of the shadowed
11876          * buf so this is safe to do here.
11877          */
11878         if (bp->b_xflags & BX_BKGRDMARKER)
11879                 initiate_write_bmsafemap(bmsafemap, bp);
11880
11881         return (dirty);
11882 }
11883
11884 /*
11885  * Re-apply an allocation when a cg write is complete.
11886  */
11887 static int
11888 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11889         struct jnewblk *jnewblk;
11890         struct fs *fs;
11891         struct cg *cgp;
11892         uint8_t *blksfree;
11893 {
11894         ufs1_daddr_t fragno;
11895         ufs2_daddr_t blkno;
11896         long cgbno, bbase;
11897         int frags, blk;
11898         int i;
11899
11900         frags = 0;
11901         cgbno = dtogd(fs, jnewblk->jn_blkno);
11902         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11903                 if (isclr(blksfree, cgbno + i))
11904                         panic("jnewblk_rollforward: re-allocated fragment");
11905                 frags++;
11906         }
11907         if (frags == fs->fs_frag) {
11908                 blkno = fragstoblks(fs, cgbno);
11909                 ffs_clrblock(fs, blksfree, (long)blkno);
11910                 ffs_clusteracct(fs, cgp, blkno, -1);
11911                 cgp->cg_cs.cs_nbfree--;
11912         } else {
11913                 bbase = cgbno - fragnum(fs, cgbno);
11914                 cgbno += jnewblk->jn_oldfrags;
11915                 /* If a complete block had been reassembled, account for it. */
11916                 fragno = fragstoblks(fs, bbase);
11917                 if (ffs_isblock(fs, blksfree, fragno)) {
11918                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11919                         ffs_clusteracct(fs, cgp, fragno, -1);
11920                         cgp->cg_cs.cs_nbfree--;
11921                 }
11922                 /* Decrement the old frags.  */
11923                 blk = blkmap(fs, blksfree, bbase);
11924                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11925                 /* Allocate the fragment */
11926                 for (i = 0; i < frags; i++)
11927                         clrbit(blksfree, cgbno + i);
11928                 cgp->cg_cs.cs_nffree -= frags;
11929                 /* Add back in counts associated with the new frags */
11930                 blk = blkmap(fs, blksfree, bbase);
11931                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11932         }
11933         return (frags);
11934 }
11935
11936 /*
11937  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11938  * changes if it's not a background write.  Set all written dependencies 
11939  * to DEPCOMPLETE and free the structure if possible.
11940  *
11941  * If the write did not succeed, we will do all the roll-forward
11942  * operations, but we will not take the actions that will allow its
11943  * dependencies to be processed.
11944  */
11945 static int
11946 handle_written_bmsafemap(bmsafemap, bp, flags)
11947         struct bmsafemap *bmsafemap;
11948         struct buf *bp;
11949         int flags;
11950 {
11951         struct newblk *newblk;
11952         struct inodedep *inodedep;
11953         struct jaddref *jaddref, *jatmp;
11954         struct jnewblk *jnewblk, *jntmp;
11955         struct ufsmount *ump;
11956         uint8_t *inosused;
11957         uint8_t *blksfree;
11958         struct cg *cgp;
11959         struct fs *fs;
11960         ino_t ino;
11961         int foreground;
11962         int chgs;
11963
11964         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11965                 panic("handle_written_bmsafemap: Not started\n");
11966         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11967         chgs = 0;
11968         bmsafemap->sm_state &= ~IOSTARTED;
11969         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11970         /*
11971          * If write was successful, release journal work that was waiting
11972          * on the write. Otherwise move the work back.
11973          */
11974         if (flags & WRITESUCCEEDED)
11975                 handle_jwork(&bmsafemap->sm_freewr);
11976         else
11977                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11978                     worklist, wk_list);
11979
11980         /*
11981          * Restore unwritten inode allocation pending jaddref writes.
11982          */
11983         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11984                 cgp = (struct cg *)bp->b_data;
11985                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11986                 inosused = cg_inosused(cgp);
11987                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11988                     ja_bmdeps, jatmp) {
11989                         if ((jaddref->ja_state & UNDONE) == 0)
11990                                 continue;
11991                         ino = jaddref->ja_ino % fs->fs_ipg;
11992                         if (isset(inosused, ino))
11993                                 panic("handle_written_bmsafemap: "
11994                                     "re-allocated inode");
11995                         /* Do the roll-forward only if it's a real copy. */
11996                         if (foreground) {
11997                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11998                                         cgp->cg_cs.cs_ndir++;
11999                                 cgp->cg_cs.cs_nifree--;
12000                                 setbit(inosused, ino);
12001                                 chgs = 1;
12002                         }
12003                         jaddref->ja_state &= ~UNDONE;
12004                         jaddref->ja_state |= ATTACHED;
12005                         free_jaddref(jaddref);
12006                 }
12007         }
12008         /*
12009          * Restore any block allocations which are pending journal writes.
12010          */
12011         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12012                 cgp = (struct cg *)bp->b_data;
12013                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12014                 blksfree = cg_blksfree(cgp);
12015                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12016                     jntmp) {
12017                         if ((jnewblk->jn_state & UNDONE) == 0)
12018                                 continue;
12019                         /* Do the roll-forward only if it's a real copy. */
12020                         if (foreground &&
12021                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12022                                 chgs = 1;
12023                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12024                         jnewblk->jn_state |= ATTACHED;
12025                         free_jnewblk(jnewblk);
12026                 }
12027         }
12028         /*
12029          * If the write did not succeed, we have done all the roll-forward
12030          * operations, but we cannot take the actions that will allow its
12031          * dependencies to be processed.
12032          */
12033         if ((flags & WRITESUCCEEDED) == 0) {
12034                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12035                     newblk, nb_deps);
12036                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12037                     worklist, wk_list);
12038                 if (foreground)
12039                         bdirty(bp);
12040                 return (1);
12041         }
12042         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12043                 newblk->nb_state |= DEPCOMPLETE;
12044                 newblk->nb_state &= ~ONDEPLIST;
12045                 newblk->nb_bmsafemap = NULL;
12046                 LIST_REMOVE(newblk, nb_deps);
12047                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12048                         handle_allocdirect_partdone(
12049                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12050                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12051                         handle_allocindir_partdone(
12052                             WK_ALLOCINDIR(&newblk->nb_list));
12053                 else if (newblk->nb_list.wk_type != D_NEWBLK)
12054                         panic("handle_written_bmsafemap: Unexpected type: %s",
12055                             TYPENAME(newblk->nb_list.wk_type));
12056         }
12057         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12058                 inodedep->id_state |= DEPCOMPLETE;
12059                 inodedep->id_state &= ~ONDEPLIST;
12060                 LIST_REMOVE(inodedep, id_deps);
12061                 inodedep->id_bmsafemap = NULL;
12062         }
12063         LIST_REMOVE(bmsafemap, sm_next);
12064         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12065             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12066             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12067             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12068             LIST_EMPTY(&bmsafemap->sm_freehd)) {
12069                 LIST_REMOVE(bmsafemap, sm_hash);
12070                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12071                 return (0);
12072         }
12073         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12074         if (foreground)
12075                 bdirty(bp);
12076         return (1);
12077 }
12078
12079 /*
12080  * Try to free a mkdir dependency.
12081  */
12082 static void
12083 complete_mkdir(mkdir)
12084         struct mkdir *mkdir;
12085 {
12086         struct diradd *dap;
12087
12088         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12089                 return;
12090         LIST_REMOVE(mkdir, md_mkdirs);
12091         dap = mkdir->md_diradd;
12092         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12093         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12094                 dap->da_state |= DEPCOMPLETE;
12095                 complete_diradd(dap);
12096         }
12097         WORKITEM_FREE(mkdir, D_MKDIR);
12098 }
12099
12100 /*
12101  * Handle the completion of a mkdir dependency.
12102  */
12103 static void
12104 handle_written_mkdir(mkdir, type)
12105         struct mkdir *mkdir;
12106         int type;
12107 {
12108
12109         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12110                 panic("handle_written_mkdir: bad type");
12111         mkdir->md_state |= COMPLETE;
12112         complete_mkdir(mkdir);
12113 }
12114
12115 static int
12116 free_pagedep(pagedep)
12117         struct pagedep *pagedep;
12118 {
12119         int i;
12120
12121         if (pagedep->pd_state & NEWBLOCK)
12122                 return (0);
12123         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12124                 return (0);
12125         for (i = 0; i < DAHASHSZ; i++)
12126                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12127                         return (0);
12128         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12129                 return (0);
12130         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12131                 return (0);
12132         if (pagedep->pd_state & ONWORKLIST)
12133                 WORKLIST_REMOVE(&pagedep->pd_list);
12134         LIST_REMOVE(pagedep, pd_hash);
12135         WORKITEM_FREE(pagedep, D_PAGEDEP);
12136
12137         return (1);
12138 }
12139
12140 /*
12141  * Called from within softdep_disk_write_complete above.
12142  * A write operation was just completed. Removed inodes can
12143  * now be freed and associated block pointers may be committed.
12144  * Note that this routine is always called from interrupt level
12145  * with further interrupts from this device blocked.
12146  *
12147  * If the write did not succeed, we will do all the roll-forward
12148  * operations, but we will not take the actions that will allow its
12149  * dependencies to be processed.
12150  */
12151 static int 
12152 handle_written_filepage(pagedep, bp, flags)
12153         struct pagedep *pagedep;
12154         struct buf *bp;         /* buffer containing the written page */
12155         int flags;
12156 {
12157         struct dirrem *dirrem;
12158         struct diradd *dap, *nextdap;
12159         struct direct *ep;
12160         int i, chgs;
12161
12162         if ((pagedep->pd_state & IOSTARTED) == 0)
12163                 panic("handle_written_filepage: not started");
12164         pagedep->pd_state &= ~IOSTARTED;
12165         if ((flags & WRITESUCCEEDED) == 0)
12166                 goto rollforward;
12167         /*
12168          * Process any directory removals that have been committed.
12169          */
12170         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12171                 LIST_REMOVE(dirrem, dm_next);
12172                 dirrem->dm_state |= COMPLETE;
12173                 dirrem->dm_dirinum = pagedep->pd_ino;
12174                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12175                     ("handle_written_filepage: Journal entries not written."));
12176                 add_to_worklist(&dirrem->dm_list, 0);
12177         }
12178         /*
12179          * Free any directory additions that have been committed.
12180          * If it is a newly allocated block, we have to wait until
12181          * the on-disk directory inode claims the new block.
12182          */
12183         if ((pagedep->pd_state & NEWBLOCK) == 0)
12184                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12185                         free_diradd(dap, NULL);
12186 rollforward:
12187         /*
12188          * Uncommitted directory entries must be restored.
12189          */
12190         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12191                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12192                      dap = nextdap) {
12193                         nextdap = LIST_NEXT(dap, da_pdlist);
12194                         if (dap->da_state & ATTACHED)
12195                                 panic("handle_written_filepage: attached");
12196                         ep = (struct direct *)
12197                             ((char *)bp->b_data + dap->da_offset);
12198                         ep->d_ino = dap->da_newinum;
12199                         dap->da_state &= ~UNDONE;
12200                         dap->da_state |= ATTACHED;
12201                         chgs = 1;
12202                         /*
12203                          * If the inode referenced by the directory has
12204                          * been written out, then the dependency can be
12205                          * moved to the pending list.
12206                          */
12207                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12208                                 LIST_REMOVE(dap, da_pdlist);
12209                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12210                                     da_pdlist);
12211                         }
12212                 }
12213         }
12214         /*
12215          * If there were any rollbacks in the directory, then it must be
12216          * marked dirty so that its will eventually get written back in
12217          * its correct form.
12218          */
12219         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12220                 if ((bp->b_flags & B_DELWRI) == 0)
12221                         stat_dir_entry++;
12222                 bdirty(bp);
12223                 return (1);
12224         }
12225         /*
12226          * If we are not waiting for a new directory block to be
12227          * claimed by its inode, then the pagedep will be freed.
12228          * Otherwise it will remain to track any new entries on
12229          * the page in case they are fsync'ed.
12230          */
12231         free_pagedep(pagedep);
12232         return (0);
12233 }
12234
12235 /*
12236  * Writing back in-core inode structures.
12237  * 
12238  * The filesystem only accesses an inode's contents when it occupies an
12239  * "in-core" inode structure.  These "in-core" structures are separate from
12240  * the page frames used to cache inode blocks.  Only the latter are
12241  * transferred to/from the disk.  So, when the updated contents of the
12242  * "in-core" inode structure are copied to the corresponding in-memory inode
12243  * block, the dependencies are also transferred.  The following procedure is
12244  * called when copying a dirty "in-core" inode to a cached inode block.
12245  */
12246
12247 /*
12248  * Called when an inode is loaded from disk. If the effective link count
12249  * differed from the actual link count when it was last flushed, then we
12250  * need to ensure that the correct effective link count is put back.
12251  */
12252 void 
12253 softdep_load_inodeblock(ip)
12254         struct inode *ip;       /* the "in_core" copy of the inode */
12255 {
12256         struct inodedep *inodedep;
12257         struct ufsmount *ump;
12258
12259         ump = ITOUMP(ip);
12260         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12261             ("softdep_load_inodeblock called on non-softdep filesystem"));
12262         /*
12263          * Check for alternate nlink count.
12264          */
12265         ip->i_effnlink = ip->i_nlink;
12266         ACQUIRE_LOCK(ump);
12267         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12268                 FREE_LOCK(ump);
12269                 return;
12270         }
12271         ip->i_effnlink -= inodedep->id_nlinkdelta;
12272         KASSERT(ip->i_effnlink >= 0,
12273             ("softdep_load_inodeblock: negative i_effnlink"));
12274         FREE_LOCK(ump);
12275 }
12276
12277 /*
12278  * This routine is called just before the "in-core" inode
12279  * information is to be copied to the in-memory inode block.
12280  * Recall that an inode block contains several inodes. If
12281  * the force flag is set, then the dependencies will be
12282  * cleared so that the update can always be made. Note that
12283  * the buffer is locked when this routine is called, so we
12284  * will never be in the middle of writing the inode block 
12285  * to disk.
12286  */
12287 void 
12288 softdep_update_inodeblock(ip, bp, waitfor)
12289         struct inode *ip;       /* the "in_core" copy of the inode */
12290         struct buf *bp;         /* the buffer containing the inode block */
12291         int waitfor;            /* nonzero => update must be allowed */
12292 {
12293         struct inodedep *inodedep;
12294         struct inoref *inoref;
12295         struct ufsmount *ump;
12296         struct worklist *wk;
12297         struct mount *mp;
12298         struct buf *ibp;
12299         struct fs *fs;
12300         int error;
12301
12302         ump = ITOUMP(ip);
12303         mp = UFSTOVFS(ump);
12304         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12305             ("softdep_update_inodeblock called on non-softdep filesystem"));
12306         fs = ump->um_fs;
12307         /*
12308          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12309          * does not have access to the in-core ip so must write directly into
12310          * the inode block buffer when setting freelink.
12311          */
12312         if (fs->fs_magic == FS_UFS1_MAGIC)
12313                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12314                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12315         else
12316                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12317                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12318         /*
12319          * If the effective link count is not equal to the actual link
12320          * count, then we must track the difference in an inodedep while
12321          * the inode is (potentially) tossed out of the cache. Otherwise,
12322          * if there is no existing inodedep, then there are no dependencies
12323          * to track.
12324          */
12325         ACQUIRE_LOCK(ump);
12326 again:
12327         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12328                 FREE_LOCK(ump);
12329                 if (ip->i_effnlink != ip->i_nlink)
12330                         panic("softdep_update_inodeblock: bad link count");
12331                 return;
12332         }
12333         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12334                 panic("softdep_update_inodeblock: bad delta");
12335         /*
12336          * If we're flushing all dependencies we must also move any waiting
12337          * for journal writes onto the bufwait list prior to I/O.
12338          */
12339         if (waitfor) {
12340                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12341                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12342                             == DEPCOMPLETE) {
12343                                 jwait(&inoref->if_list, MNT_WAIT);
12344                                 goto again;
12345                         }
12346                 }
12347         }
12348         /*
12349          * Changes have been initiated. Anything depending on these
12350          * changes cannot occur until this inode has been written.
12351          */
12352         inodedep->id_state &= ~COMPLETE;
12353         if ((inodedep->id_state & ONWORKLIST) == 0)
12354                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12355         /*
12356          * Any new dependencies associated with the incore inode must 
12357          * now be moved to the list associated with the buffer holding
12358          * the in-memory copy of the inode. Once merged process any
12359          * allocdirects that are completed by the merger.
12360          */
12361         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12362         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12363                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12364                     NULL);
12365         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12366         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12367                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12368                     NULL);
12369         /*
12370          * Now that the inode has been pushed into the buffer, the
12371          * operations dependent on the inode being written to disk
12372          * can be moved to the id_bufwait so that they will be
12373          * processed when the buffer I/O completes.
12374          */
12375         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12376                 WORKLIST_REMOVE(wk);
12377                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12378         }
12379         /*
12380          * Newly allocated inodes cannot be written until the bitmap
12381          * that allocates them have been written (indicated by
12382          * DEPCOMPLETE being set in id_state). If we are doing a
12383          * forced sync (e.g., an fsync on a file), we force the bitmap
12384          * to be written so that the update can be done.
12385          */
12386         if (waitfor == 0) {
12387                 FREE_LOCK(ump);
12388                 return;
12389         }
12390 retry:
12391         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12392                 FREE_LOCK(ump);
12393                 return;
12394         }
12395         ibp = inodedep->id_bmsafemap->sm_buf;
12396         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12397         if (ibp == NULL) {
12398                 /*
12399                  * If ibp came back as NULL, the dependency could have been
12400                  * freed while we slept.  Look it up again, and check to see
12401                  * that it has completed.
12402                  */
12403                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12404                         goto retry;
12405                 FREE_LOCK(ump);
12406                 return;
12407         }
12408         FREE_LOCK(ump);
12409         if ((error = bwrite(ibp)) != 0)
12410                 softdep_error("softdep_update_inodeblock: bwrite", error);
12411 }
12412
12413 /*
12414  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12415  * old inode dependency list (such as id_inoupdt).
12416  */
12417 static void
12418 merge_inode_lists(newlisthead, oldlisthead)
12419         struct allocdirectlst *newlisthead;
12420         struct allocdirectlst *oldlisthead;
12421 {
12422         struct allocdirect *listadp, *newadp;
12423
12424         newadp = TAILQ_FIRST(newlisthead);
12425         if (newadp != NULL)
12426                 LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12427         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12428                 if (listadp->ad_offset < newadp->ad_offset) {
12429                         listadp = TAILQ_NEXT(listadp, ad_next);
12430                         continue;
12431                 }
12432                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12433                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12434                 if (listadp->ad_offset == newadp->ad_offset) {
12435                         allocdirect_merge(oldlisthead, newadp,
12436                             listadp);
12437                         listadp = newadp;
12438                 }
12439                 newadp = TAILQ_FIRST(newlisthead);
12440         }
12441         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12442                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12443                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12444         }
12445 }
12446
12447 /*
12448  * If we are doing an fsync, then we must ensure that any directory
12449  * entries for the inode have been written after the inode gets to disk.
12450  */
12451 int
12452 softdep_fsync(vp)
12453         struct vnode *vp;       /* the "in_core" copy of the inode */
12454 {
12455         struct inodedep *inodedep;
12456         struct pagedep *pagedep;
12457         struct inoref *inoref;
12458         struct ufsmount *ump;
12459         struct worklist *wk;
12460         struct diradd *dap;
12461         struct mount *mp;
12462         struct vnode *pvp;
12463         struct inode *ip;
12464         struct buf *bp;
12465         struct fs *fs;
12466         struct thread *td = curthread;
12467         int error, flushparent, pagedep_new_block;
12468         ino_t parentino;
12469         ufs_lbn_t lbn;
12470
12471         ip = VTOI(vp);
12472         mp = vp->v_mount;
12473         ump = VFSTOUFS(mp);
12474         fs = ump->um_fs;
12475         if (MOUNTEDSOFTDEP(mp) == 0)
12476                 return (0);
12477         ACQUIRE_LOCK(ump);
12478 restart:
12479         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12480                 FREE_LOCK(ump);
12481                 return (0);
12482         }
12483         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12484                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12485                     == DEPCOMPLETE) {
12486                         jwait(&inoref->if_list, MNT_WAIT);
12487                         goto restart;
12488                 }
12489         }
12490         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12491             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12492             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12493             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12494             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12495                 panic("softdep_fsync: pending ops %p", inodedep);
12496         for (error = 0, flushparent = 0; ; ) {
12497                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12498                         break;
12499                 if (wk->wk_type != D_DIRADD)
12500                         panic("softdep_fsync: Unexpected type %s",
12501                             TYPENAME(wk->wk_type));
12502                 dap = WK_DIRADD(wk);
12503                 /*
12504                  * Flush our parent if this directory entry has a MKDIR_PARENT
12505                  * dependency or is contained in a newly allocated block.
12506                  */
12507                 if (dap->da_state & DIRCHG)
12508                         pagedep = dap->da_previous->dm_pagedep;
12509                 else
12510                         pagedep = dap->da_pagedep;
12511                 parentino = pagedep->pd_ino;
12512                 lbn = pagedep->pd_lbn;
12513                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12514                         panic("softdep_fsync: dirty");
12515                 if ((dap->da_state & MKDIR_PARENT) ||
12516                     (pagedep->pd_state & NEWBLOCK))
12517                         flushparent = 1;
12518                 else
12519                         flushparent = 0;
12520                 /*
12521                  * If we are being fsync'ed as part of vgone'ing this vnode,
12522                  * then we will not be able to release and recover the
12523                  * vnode below, so we just have to give up on writing its
12524                  * directory entry out. It will eventually be written, just
12525                  * not now, but then the user was not asking to have it
12526                  * written, so we are not breaking any promises.
12527                  */
12528                 if (vp->v_iflag & VI_DOOMED)
12529                         break;
12530                 /*
12531                  * We prevent deadlock by always fetching inodes from the
12532                  * root, moving down the directory tree. Thus, when fetching
12533                  * our parent directory, we first try to get the lock. If
12534                  * that fails, we must unlock ourselves before requesting
12535                  * the lock on our parent. See the comment in ufs_lookup
12536                  * for details on possible races.
12537                  */
12538                 FREE_LOCK(ump);
12539                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12540                     FFSV_FORCEINSMQ)) {
12541                         /*
12542                          * Unmount cannot proceed after unlock because
12543                          * caller must have called vn_start_write().
12544                          */
12545                         VOP_UNLOCK(vp, 0);
12546                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12547                             &pvp, FFSV_FORCEINSMQ);
12548                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12549                         if (vp->v_iflag & VI_DOOMED) {
12550                                 if (error == 0)
12551                                         vput(pvp);
12552                                 error = ENOENT;
12553                         }
12554                         if (error != 0)
12555                                 return (error);
12556                 }
12557                 /*
12558                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12559                  * that are contained in direct blocks will be resolved by 
12560                  * doing a ffs_update. Pagedeps contained in indirect blocks
12561                  * may require a complete sync'ing of the directory. So, we
12562                  * try the cheap and fast ffs_update first, and if that fails,
12563                  * then we do the slower ffs_syncvnode of the directory.
12564                  */
12565                 if (flushparent) {
12566                         int locked;
12567
12568                         if ((error = ffs_update(pvp, 1)) != 0) {
12569                                 vput(pvp);
12570                                 return (error);
12571                         }
12572                         ACQUIRE_LOCK(ump);
12573                         locked = 1;
12574                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12575                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12576                                         if (wk->wk_type != D_DIRADD)
12577                                                 panic("softdep_fsync: Unexpected type %s",
12578                                                       TYPENAME(wk->wk_type));
12579                                         dap = WK_DIRADD(wk);
12580                                         if (dap->da_state & DIRCHG)
12581                                                 pagedep = dap->da_previous->dm_pagedep;
12582                                         else
12583                                                 pagedep = dap->da_pagedep;
12584                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12585                                         FREE_LOCK(ump);
12586                                         locked = 0;
12587                                         if (pagedep_new_block && (error =
12588                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12589                                                 vput(pvp);
12590                                                 return (error);
12591                                         }
12592                                 }
12593                         }
12594                         if (locked)
12595                                 FREE_LOCK(ump);
12596                 }
12597                 /*
12598                  * Flush directory page containing the inode's name.
12599                  */
12600                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12601                     &bp);
12602                 if (error == 0)
12603                         error = bwrite(bp);
12604                 else
12605                         brelse(bp);
12606                 vput(pvp);
12607                 if (error != 0)
12608                         return (error);
12609                 ACQUIRE_LOCK(ump);
12610                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12611                         break;
12612         }
12613         FREE_LOCK(ump);
12614         return (0);
12615 }
12616
12617 /*
12618  * Flush all the dirty bitmaps associated with the block device
12619  * before flushing the rest of the dirty blocks so as to reduce
12620  * the number of dependencies that will have to be rolled back.
12621  *
12622  * XXX Unused?
12623  */
12624 void
12625 softdep_fsync_mountdev(vp)
12626         struct vnode *vp;
12627 {
12628         struct buf *bp, *nbp;
12629         struct worklist *wk;
12630         struct bufobj *bo;
12631
12632         if (!vn_isdisk(vp, NULL))
12633                 panic("softdep_fsync_mountdev: vnode not a disk");
12634         bo = &vp->v_bufobj;
12635 restart:
12636         BO_LOCK(bo);
12637         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12638                 /* 
12639                  * If it is already scheduled, skip to the next buffer.
12640                  */
12641                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12642                         continue;
12643
12644                 if ((bp->b_flags & B_DELWRI) == 0)
12645                         panic("softdep_fsync_mountdev: not dirty");
12646                 /*
12647                  * We are only interested in bitmaps with outstanding
12648                  * dependencies.
12649                  */
12650                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12651                     wk->wk_type != D_BMSAFEMAP ||
12652                     (bp->b_vflags & BV_BKGRDINPROG)) {
12653                         BUF_UNLOCK(bp);
12654                         continue;
12655                 }
12656                 BO_UNLOCK(bo);
12657                 bremfree(bp);
12658                 (void) bawrite(bp);
12659                 goto restart;
12660         }
12661         drain_output(vp);
12662         BO_UNLOCK(bo);
12663 }
12664
12665 /*
12666  * Sync all cylinder groups that were dirty at the time this function is
12667  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12668  * is used to flush freedep activity that may be holding up writes to a
12669  * indirect block.
12670  */
12671 static int
12672 sync_cgs(mp, waitfor)
12673         struct mount *mp;
12674         int waitfor;
12675 {
12676         struct bmsafemap *bmsafemap;
12677         struct bmsafemap *sentinel;
12678         struct ufsmount *ump;
12679         struct buf *bp;
12680         int error;
12681
12682         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12683         sentinel->sm_cg = -1;
12684         ump = VFSTOUFS(mp);
12685         error = 0;
12686         ACQUIRE_LOCK(ump);
12687         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12688         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12689             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12690                 /* Skip sentinels and cgs with no work to release. */
12691                 if (bmsafemap->sm_cg == -1 ||
12692                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12693                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12694                         LIST_REMOVE(sentinel, sm_next);
12695                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12696                         continue;
12697                 }
12698                 /*
12699                  * If we don't get the lock and we're waiting try again, if
12700                  * not move on to the next buf and try to sync it.
12701                  */
12702                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12703                 if (bp == NULL && waitfor == MNT_WAIT)
12704                         continue;
12705                 LIST_REMOVE(sentinel, sm_next);
12706                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12707                 if (bp == NULL)
12708                         continue;
12709                 FREE_LOCK(ump);
12710                 if (waitfor == MNT_NOWAIT)
12711                         bawrite(bp);
12712                 else
12713                         error = bwrite(bp);
12714                 ACQUIRE_LOCK(ump);
12715                 if (error)
12716                         break;
12717         }
12718         LIST_REMOVE(sentinel, sm_next);
12719         FREE_LOCK(ump);
12720         free(sentinel, M_BMSAFEMAP);
12721         return (error);
12722 }
12723
12724 /*
12725  * This routine is called when we are trying to synchronously flush a
12726  * file. This routine must eliminate any filesystem metadata dependencies
12727  * so that the syncing routine can succeed.
12728  */
12729 int
12730 softdep_sync_metadata(struct vnode *vp)
12731 {
12732         struct inode *ip;
12733         int error;
12734
12735         ip = VTOI(vp);
12736         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12737             ("softdep_sync_metadata called on non-softdep filesystem"));
12738         /*
12739          * Ensure that any direct block dependencies have been cleared,
12740          * truncations are started, and inode references are journaled.
12741          */
12742         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12743         /*
12744          * Write all journal records to prevent rollbacks on devvp.
12745          */
12746         if (vp->v_type == VCHR)
12747                 softdep_flushjournal(vp->v_mount);
12748         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12749         /*
12750          * Ensure that all truncates are written so we won't find deps on
12751          * indirect blocks.
12752          */
12753         process_truncates(vp);
12754         FREE_LOCK(VFSTOUFS(vp->v_mount));
12755
12756         return (error);
12757 }
12758
12759 /*
12760  * This routine is called when we are attempting to sync a buf with
12761  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12762  * other IO it can but returns EBUSY if the buffer is not yet able to
12763  * be written.  Dependencies which will not cause rollbacks will always
12764  * return 0.
12765  */
12766 int
12767 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12768 {
12769         struct indirdep *indirdep;
12770         struct pagedep *pagedep;
12771         struct allocindir *aip;
12772         struct newblk *newblk;
12773         struct ufsmount *ump;
12774         struct buf *nbp;
12775         struct worklist *wk;
12776         int i, error;
12777
12778         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12779             ("softdep_sync_buf called on non-softdep filesystem"));
12780         /*
12781          * For VCHR we just don't want to force flush any dependencies that
12782          * will cause rollbacks.
12783          */
12784         if (vp->v_type == VCHR) {
12785                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12786                         return (EBUSY);
12787                 return (0);
12788         }
12789         ump = VFSTOUFS(vp->v_mount);
12790         ACQUIRE_LOCK(ump);
12791         /*
12792          * As we hold the buffer locked, none of its dependencies
12793          * will disappear.
12794          */
12795         error = 0;
12796 top:
12797         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12798                 switch (wk->wk_type) {
12799
12800                 case D_ALLOCDIRECT:
12801                 case D_ALLOCINDIR:
12802                         newblk = WK_NEWBLK(wk);
12803                         if (newblk->nb_jnewblk != NULL) {
12804                                 if (waitfor == MNT_NOWAIT) {
12805                                         error = EBUSY;
12806                                         goto out_unlock;
12807                                 }
12808                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12809                                 goto top;
12810                         }
12811                         if (newblk->nb_state & DEPCOMPLETE ||
12812                             waitfor == MNT_NOWAIT)
12813                                 continue;
12814                         nbp = newblk->nb_bmsafemap->sm_buf;
12815                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12816                         if (nbp == NULL)
12817                                 goto top;
12818                         FREE_LOCK(ump);
12819                         if ((error = bwrite(nbp)) != 0)
12820                                 goto out;
12821                         ACQUIRE_LOCK(ump);
12822                         continue;
12823
12824                 case D_INDIRDEP:
12825                         indirdep = WK_INDIRDEP(wk);
12826                         if (waitfor == MNT_NOWAIT) {
12827                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12828                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12829                                         error = EBUSY;
12830                                         goto out_unlock;
12831                                 }
12832                         }
12833                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12834                                 panic("softdep_sync_buf: truncation pending.");
12835                 restart:
12836                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12837                                 newblk = (struct newblk *)aip;
12838                                 if (newblk->nb_jnewblk != NULL) {
12839                                         jwait(&newblk->nb_jnewblk->jn_list,
12840                                             waitfor);
12841                                         goto restart;
12842                                 }
12843                                 if (newblk->nb_state & DEPCOMPLETE)
12844                                         continue;
12845                                 nbp = newblk->nb_bmsafemap->sm_buf;
12846                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12847                                 if (nbp == NULL)
12848                                         goto restart;
12849                                 FREE_LOCK(ump);
12850                                 if ((error = bwrite(nbp)) != 0)
12851                                         goto out;
12852                                 ACQUIRE_LOCK(ump);
12853                                 goto restart;
12854                         }
12855                         continue;
12856
12857                 case D_PAGEDEP:
12858                         /*
12859                          * Only flush directory entries in synchronous passes.
12860                          */
12861                         if (waitfor != MNT_WAIT) {
12862                                 error = EBUSY;
12863                                 goto out_unlock;
12864                         }
12865                         /*
12866                          * While syncing snapshots, we must allow recursive
12867                          * lookups.
12868                          */
12869                         BUF_AREC(bp);
12870                         /*
12871                          * We are trying to sync a directory that may
12872                          * have dependencies on both its own metadata
12873                          * and/or dependencies on the inodes of any
12874                          * recently allocated files. We walk its diradd
12875                          * lists pushing out the associated inode.
12876                          */
12877                         pagedep = WK_PAGEDEP(wk);
12878                         for (i = 0; i < DAHASHSZ; i++) {
12879                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12880                                         continue;
12881                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12882                                     &pagedep->pd_diraddhd[i]))) {
12883                                         BUF_NOREC(bp);
12884                                         goto out_unlock;
12885                                 }
12886                         }
12887                         BUF_NOREC(bp);
12888                         continue;
12889
12890                 case D_FREEWORK:
12891                 case D_FREEDEP:
12892                 case D_JSEGDEP:
12893                 case D_JNEWBLK:
12894                         continue;
12895
12896                 default:
12897                         panic("softdep_sync_buf: Unknown type %s",
12898                             TYPENAME(wk->wk_type));
12899                         /* NOTREACHED */
12900                 }
12901         }
12902 out_unlock:
12903         FREE_LOCK(ump);
12904 out:
12905         return (error);
12906 }
12907
12908 /*
12909  * Flush the dependencies associated with an inodedep.
12910  */
12911 static int
12912 flush_inodedep_deps(vp, mp, ino)
12913         struct vnode *vp;
12914         struct mount *mp;
12915         ino_t ino;
12916 {
12917         struct inodedep *inodedep;
12918         struct inoref *inoref;
12919         struct ufsmount *ump;
12920         int error, waitfor;
12921
12922         /*
12923          * This work is done in two passes. The first pass grabs most
12924          * of the buffers and begins asynchronously writing them. The
12925          * only way to wait for these asynchronous writes is to sleep
12926          * on the filesystem vnode which may stay busy for a long time
12927          * if the filesystem is active. So, instead, we make a second
12928          * pass over the dependencies blocking on each write. In the
12929          * usual case we will be blocking against a write that we
12930          * initiated, so when it is done the dependency will have been
12931          * resolved. Thus the second pass is expected to end quickly.
12932          * We give a brief window at the top of the loop to allow
12933          * any pending I/O to complete.
12934          */
12935         ump = VFSTOUFS(mp);
12936         LOCK_OWNED(ump);
12937         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12938                 if (error)
12939                         return (error);
12940                 FREE_LOCK(ump);
12941                 ACQUIRE_LOCK(ump);
12942 restart:
12943                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12944                         return (0);
12945                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12946                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12947                             == DEPCOMPLETE) {
12948                                 jwait(&inoref->if_list, MNT_WAIT);
12949                                 goto restart;
12950                         }
12951                 }
12952                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12953                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12954                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12955                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12956                         continue;
12957                 /*
12958                  * If pass2, we are done, otherwise do pass 2.
12959                  */
12960                 if (waitfor == MNT_WAIT)
12961                         break;
12962                 waitfor = MNT_WAIT;
12963         }
12964         /*
12965          * Try freeing inodedep in case all dependencies have been removed.
12966          */
12967         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12968                 (void) free_inodedep(inodedep);
12969         return (0);
12970 }
12971
12972 /*
12973  * Flush an inode dependency list.
12974  */
12975 static int
12976 flush_deplist(listhead, waitfor, errorp)
12977         struct allocdirectlst *listhead;
12978         int waitfor;
12979         int *errorp;
12980 {
12981         struct allocdirect *adp;
12982         struct newblk *newblk;
12983         struct ufsmount *ump;
12984         struct buf *bp;
12985
12986         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12987                 return (0);
12988         ump = VFSTOUFS(adp->ad_list.wk_mp);
12989         LOCK_OWNED(ump);
12990         TAILQ_FOREACH(adp, listhead, ad_next) {
12991                 newblk = (struct newblk *)adp;
12992                 if (newblk->nb_jnewblk != NULL) {
12993                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12994                         return (1);
12995                 }
12996                 if (newblk->nb_state & DEPCOMPLETE)
12997                         continue;
12998                 bp = newblk->nb_bmsafemap->sm_buf;
12999                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13000                 if (bp == NULL) {
13001                         if (waitfor == MNT_NOWAIT)
13002                                 continue;
13003                         return (1);
13004                 }
13005                 FREE_LOCK(ump);
13006                 if (waitfor == MNT_NOWAIT)
13007                         bawrite(bp);
13008                 else 
13009                         *errorp = bwrite(bp);
13010                 ACQUIRE_LOCK(ump);
13011                 return (1);
13012         }
13013         return (0);
13014 }
13015
13016 /*
13017  * Flush dependencies associated with an allocdirect block.
13018  */
13019 static int
13020 flush_newblk_dep(vp, mp, lbn)
13021         struct vnode *vp;
13022         struct mount *mp;
13023         ufs_lbn_t lbn;
13024 {
13025         struct newblk *newblk;
13026         struct ufsmount *ump;
13027         struct bufobj *bo;
13028         struct inode *ip;
13029         struct buf *bp;
13030         ufs2_daddr_t blkno;
13031         int error;
13032
13033         error = 0;
13034         bo = &vp->v_bufobj;
13035         ip = VTOI(vp);
13036         blkno = DIP(ip, i_db[lbn]);
13037         if (blkno == 0)
13038                 panic("flush_newblk_dep: Missing block");
13039         ump = VFSTOUFS(mp);
13040         ACQUIRE_LOCK(ump);
13041         /*
13042          * Loop until all dependencies related to this block are satisfied.
13043          * We must be careful to restart after each sleep in case a write
13044          * completes some part of this process for us.
13045          */
13046         for (;;) {
13047                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13048                         FREE_LOCK(ump);
13049                         break;
13050                 }
13051                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13052                         panic("flush_newblk_dep: Bad newblk %p", newblk);
13053                 /*
13054                  * Flush the journal.
13055                  */
13056                 if (newblk->nb_jnewblk != NULL) {
13057                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13058                         continue;
13059                 }
13060                 /*
13061                  * Write the bitmap dependency.
13062                  */
13063                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13064                         bp = newblk->nb_bmsafemap->sm_buf;
13065                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13066                         if (bp == NULL)
13067                                 continue;
13068                         FREE_LOCK(ump);
13069                         error = bwrite(bp);
13070                         if (error)
13071                                 break;
13072                         ACQUIRE_LOCK(ump);
13073                         continue;
13074                 }
13075                 /*
13076                  * Write the buffer.
13077                  */
13078                 FREE_LOCK(ump);
13079                 BO_LOCK(bo);
13080                 bp = gbincore(bo, lbn);
13081                 if (bp != NULL) {
13082                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13083                             LK_INTERLOCK, BO_LOCKPTR(bo));
13084                         if (error == ENOLCK) {
13085                                 ACQUIRE_LOCK(ump);
13086                                 error = 0;
13087                                 continue; /* Slept, retry */
13088                         }
13089                         if (error != 0)
13090                                 break;  /* Failed */
13091                         if (bp->b_flags & B_DELWRI) {
13092                                 bremfree(bp);
13093                                 error = bwrite(bp);
13094                                 if (error)
13095                                         break;
13096                         } else
13097                                 BUF_UNLOCK(bp);
13098                 } else
13099                         BO_UNLOCK(bo);
13100                 /*
13101                  * We have to wait for the direct pointers to
13102                  * point at the newdirblk before the dependency
13103                  * will go away.
13104                  */
13105                 error = ffs_update(vp, 1);
13106                 if (error)
13107                         break;
13108                 ACQUIRE_LOCK(ump);
13109         }
13110         return (error);
13111 }
13112
13113 /*
13114  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13115  */
13116 static int
13117 flush_pagedep_deps(pvp, mp, diraddhdp)
13118         struct vnode *pvp;
13119         struct mount *mp;
13120         struct diraddhd *diraddhdp;
13121 {
13122         struct inodedep *inodedep;
13123         struct inoref *inoref;
13124         struct ufsmount *ump;
13125         struct diradd *dap;
13126         struct vnode *vp;
13127         int error = 0;
13128         struct buf *bp;
13129         ino_t inum;
13130         struct diraddhd unfinished;
13131
13132         LIST_INIT(&unfinished);
13133         ump = VFSTOUFS(mp);
13134         LOCK_OWNED(ump);
13135 restart:
13136         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13137                 /*
13138                  * Flush ourselves if this directory entry
13139                  * has a MKDIR_PARENT dependency.
13140                  */
13141                 if (dap->da_state & MKDIR_PARENT) {
13142                         FREE_LOCK(ump);
13143                         if ((error = ffs_update(pvp, 1)) != 0)
13144                                 break;
13145                         ACQUIRE_LOCK(ump);
13146                         /*
13147                          * If that cleared dependencies, go on to next.
13148                          */
13149                         if (dap != LIST_FIRST(diraddhdp))
13150                                 continue;
13151                         /*
13152                          * All MKDIR_PARENT dependencies and all the
13153                          * NEWBLOCK pagedeps that are contained in direct
13154                          * blocks were resolved by doing above ffs_update.
13155                          * Pagedeps contained in indirect blocks may
13156                          * require a complete sync'ing of the directory.
13157                          * We are in the midst of doing a complete sync,
13158                          * so if they are not resolved in this pass we
13159                          * defer them for now as they will be sync'ed by
13160                          * our caller shortly.
13161                          */
13162                         LIST_REMOVE(dap, da_pdlist);
13163                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13164                         continue;
13165                 }
13166                 /*
13167                  * A newly allocated directory must have its "." and
13168                  * ".." entries written out before its name can be
13169                  * committed in its parent. 
13170                  */
13171                 inum = dap->da_newinum;
13172                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13173                         panic("flush_pagedep_deps: lost inode1");
13174                 /*
13175                  * Wait for any pending journal adds to complete so we don't
13176                  * cause rollbacks while syncing.
13177                  */
13178                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13179                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13180                             == DEPCOMPLETE) {
13181                                 jwait(&inoref->if_list, MNT_WAIT);
13182                                 goto restart;
13183                         }
13184                 }
13185                 if (dap->da_state & MKDIR_BODY) {
13186                         FREE_LOCK(ump);
13187                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13188                             FFSV_FORCEINSMQ)))
13189                                 break;
13190                         error = flush_newblk_dep(vp, mp, 0);
13191                         /*
13192                          * If we still have the dependency we might need to
13193                          * update the vnode to sync the new link count to
13194                          * disk.
13195                          */
13196                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13197                                 error = ffs_update(vp, 1);
13198                         vput(vp);
13199                         if (error != 0)
13200                                 break;
13201                         ACQUIRE_LOCK(ump);
13202                         /*
13203                          * If that cleared dependencies, go on to next.
13204                          */
13205                         if (dap != LIST_FIRST(diraddhdp))
13206                                 continue;
13207                         if (dap->da_state & MKDIR_BODY) {
13208                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13209                                     &inodedep);
13210                                 panic("flush_pagedep_deps: MKDIR_BODY "
13211                                     "inodedep %p dap %p vp %p",
13212                                     inodedep, dap, vp);
13213                         }
13214                 }
13215                 /*
13216                  * Flush the inode on which the directory entry depends.
13217                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13218                  * the only remaining dependency is that the updated inode
13219                  * count must get pushed to disk. The inode has already
13220                  * been pushed into its inode buffer (via VOP_UPDATE) at
13221                  * the time of the reference count change. So we need only
13222                  * locate that buffer, ensure that there will be no rollback
13223                  * caused by a bitmap dependency, then write the inode buffer.
13224                  */
13225 retry:
13226                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13227                         panic("flush_pagedep_deps: lost inode");
13228                 /*
13229                  * If the inode still has bitmap dependencies,
13230                  * push them to disk.
13231                  */
13232                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13233                         bp = inodedep->id_bmsafemap->sm_buf;
13234                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13235                         if (bp == NULL)
13236                                 goto retry;
13237                         FREE_LOCK(ump);
13238                         if ((error = bwrite(bp)) != 0)
13239                                 break;
13240                         ACQUIRE_LOCK(ump);
13241                         if (dap != LIST_FIRST(diraddhdp))
13242                                 continue;
13243                 }
13244                 /*
13245                  * If the inode is still sitting in a buffer waiting
13246                  * to be written or waiting for the link count to be
13247                  * adjusted update it here to flush it to disk.
13248                  */
13249                 if (dap == LIST_FIRST(diraddhdp)) {
13250                         FREE_LOCK(ump);
13251                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13252                             FFSV_FORCEINSMQ)))
13253                                 break;
13254                         error = ffs_update(vp, 1);
13255                         vput(vp);
13256                         if (error)
13257                                 break;
13258                         ACQUIRE_LOCK(ump);
13259                 }
13260                 /*
13261                  * If we have failed to get rid of all the dependencies
13262                  * then something is seriously wrong.
13263                  */
13264                 if (dap == LIST_FIRST(diraddhdp)) {
13265                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13266                         panic("flush_pagedep_deps: failed to flush " 
13267                             "inodedep %p ino %ju dap %p",
13268                             inodedep, (uintmax_t)inum, dap);
13269                 }
13270         }
13271         if (error)
13272                 ACQUIRE_LOCK(ump);
13273         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13274                 LIST_REMOVE(dap, da_pdlist);
13275                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13276         }
13277         return (error);
13278 }
13279
13280 /*
13281  * A large burst of file addition or deletion activity can drive the
13282  * memory load excessively high. First attempt to slow things down
13283  * using the techniques below. If that fails, this routine requests
13284  * the offending operations to fall back to running synchronously
13285  * until the memory load returns to a reasonable level.
13286  */
13287 int
13288 softdep_slowdown(vp)
13289         struct vnode *vp;
13290 {
13291         struct ufsmount *ump;
13292         int jlow;
13293         int max_softdeps_hard;
13294
13295         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13296             ("softdep_slowdown called on non-softdep filesystem"));
13297         ump = VFSTOUFS(vp->v_mount);
13298         ACQUIRE_LOCK(ump);
13299         jlow = 0;
13300         /*
13301          * Check for journal space if needed.
13302          */
13303         if (DOINGSUJ(vp)) {
13304                 if (journal_space(ump, 0) == 0)
13305                         jlow = 1;
13306         }
13307         /*
13308          * If the system is under its limits and our filesystem is
13309          * not responsible for more than our share of the usage and
13310          * we are not low on journal space, then no need to slow down.
13311          */
13312         max_softdeps_hard = max_softdeps * 11 / 10;
13313         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13314             dep_current[D_INODEDEP] < max_softdeps_hard &&
13315             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13316             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13317             ump->softdep_curdeps[D_DIRREM] <
13318             (max_softdeps_hard / 2) / stat_flush_threads &&
13319             ump->softdep_curdeps[D_INODEDEP] <
13320             max_softdeps_hard / stat_flush_threads &&
13321             ump->softdep_curdeps[D_INDIRDEP] <
13322             (max_softdeps_hard / 1000) / stat_flush_threads &&
13323             ump->softdep_curdeps[D_FREEBLKS] <
13324             max_softdeps_hard / stat_flush_threads) {
13325                 FREE_LOCK(ump);
13326                 return (0);
13327         }
13328         /*
13329          * If the journal is low or our filesystem is over its limit
13330          * then speedup the cleanup.
13331          */
13332         if (ump->softdep_curdeps[D_INDIRDEP] <
13333             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13334                 softdep_speedup(ump);
13335         stat_sync_limit_hit += 1;
13336         FREE_LOCK(ump);
13337         /*
13338          * We only slow down the rate at which new dependencies are
13339          * generated if we are not using journaling. With journaling,
13340          * the cleanup should always be sufficient to keep things
13341          * under control.
13342          */
13343         if (DOINGSUJ(vp))
13344                 return (0);
13345         return (1);
13346 }
13347
13348 /*
13349  * Called by the allocation routines when they are about to fail
13350  * in the hope that we can free up the requested resource (inodes
13351  * or disk space).
13352  * 
13353  * First check to see if the work list has anything on it. If it has,
13354  * clean up entries until we successfully free the requested resource.
13355  * Because this process holds inodes locked, we cannot handle any remove
13356  * requests that might block on a locked inode as that could lead to
13357  * deadlock. If the worklist yields none of the requested resource,
13358  * start syncing out vnodes to free up the needed space.
13359  */
13360 int
13361 softdep_request_cleanup(fs, vp, cred, resource)
13362         struct fs *fs;
13363         struct vnode *vp;
13364         struct ucred *cred;
13365         int resource;
13366 {
13367         struct ufsmount *ump;
13368         struct mount *mp;
13369         long starttime;
13370         ufs2_daddr_t needed;
13371         int error, failed_vnode;
13372
13373         /*
13374          * If we are being called because of a process doing a
13375          * copy-on-write, then it is not safe to process any
13376          * worklist items as we will recurse into the copyonwrite
13377          * routine.  This will result in an incoherent snapshot.
13378          * If the vnode that we hold is a snapshot, we must avoid
13379          * handling other resources that could cause deadlock.
13380          */
13381         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13382                 return (0);
13383
13384         if (resource == FLUSH_BLOCKS_WAIT)
13385                 stat_cleanup_blkrequests += 1;
13386         else
13387                 stat_cleanup_inorequests += 1;
13388
13389         mp = vp->v_mount;
13390         ump = VFSTOUFS(mp);
13391         mtx_assert(UFS_MTX(ump), MA_OWNED);
13392         UFS_UNLOCK(ump);
13393         error = ffs_update(vp, 1);
13394         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13395                 UFS_LOCK(ump);
13396                 return (0);
13397         }
13398         /*
13399          * If we are in need of resources, start by cleaning up
13400          * any block removals associated with our inode.
13401          */
13402         ACQUIRE_LOCK(ump);
13403         process_removes(vp);
13404         process_truncates(vp);
13405         FREE_LOCK(ump);
13406         /*
13407          * Now clean up at least as many resources as we will need.
13408          *
13409          * When requested to clean up inodes, the number that are needed
13410          * is set by the number of simultaneous writers (mnt_writeopcount)
13411          * plus a bit of slop (2) in case some more writers show up while
13412          * we are cleaning.
13413          *
13414          * When requested to free up space, the amount of space that
13415          * we need is enough blocks to allocate a full-sized segment
13416          * (fs_contigsumsize). The number of such segments that will
13417          * be needed is set by the number of simultaneous writers
13418          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13419          * writers show up while we are cleaning.
13420          *
13421          * Additionally, if we are unpriviledged and allocating space,
13422          * we need to ensure that we clean up enough blocks to get the
13423          * needed number of blocks over the threshold of the minimum
13424          * number of blocks required to be kept free by the filesystem
13425          * (fs_minfree).
13426          */
13427         if (resource == FLUSH_INODES_WAIT) {
13428                 needed = vfs_mount_fetch_counter(vp->v_mount,
13429                     MNT_COUNT_WRITEOPCOUNT) + 2;
13430         } else if (resource == FLUSH_BLOCKS_WAIT) {
13431                 needed = (vfs_mount_fetch_counter(vp->v_mount,
13432                     MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13433                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13434                         needed += fragstoblks(fs,
13435                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13436                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13437         } else {
13438                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13439                     resource);
13440                 UFS_LOCK(ump);
13441                 return (0);
13442         }
13443         starttime = time_second;
13444 retry:
13445         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13446             fs->fs_cstotal.cs_nbfree <= needed) ||
13447             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13448             fs->fs_cstotal.cs_nifree <= needed)) {
13449                 ACQUIRE_LOCK(ump);
13450                 if (ump->softdep_on_worklist > 0 &&
13451                     process_worklist_item(UFSTOVFS(ump),
13452                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13453                         stat_worklist_push += 1;
13454                 FREE_LOCK(ump);
13455         }
13456         /*
13457          * If we still need resources and there are no more worklist
13458          * entries to process to obtain them, we have to start flushing
13459          * the dirty vnodes to force the release of additional requests
13460          * to the worklist that we can then process to reap addition
13461          * resources. We walk the vnodes associated with the mount point
13462          * until we get the needed worklist requests that we can reap.
13463          *
13464          * If there are several threads all needing to clean the same
13465          * mount point, only one is allowed to walk the mount list.
13466          * When several threads all try to walk the same mount list,
13467          * they end up competing with each other and often end up in
13468          * livelock. This approach ensures that forward progress is
13469          * made at the cost of occational ENOSPC errors being returned
13470          * that might otherwise have been avoided.
13471          */
13472         error = 1;
13473         if ((resource == FLUSH_BLOCKS_WAIT && 
13474              fs->fs_cstotal.cs_nbfree <= needed) ||
13475             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13476              fs->fs_cstotal.cs_nifree <= needed)) {
13477                 ACQUIRE_LOCK(ump);
13478                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13479                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13480                         FREE_LOCK(ump);
13481                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13482                         ACQUIRE_LOCK(ump);
13483                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13484                         FREE_LOCK(ump);
13485                         if (ump->softdep_on_worklist > 0) {
13486                                 stat_cleanup_retries += 1;
13487                                 if (!failed_vnode)
13488                                         goto retry;
13489                         }
13490                 } else {
13491                         FREE_LOCK(ump);
13492                         error = 0;
13493                 }
13494                 stat_cleanup_failures += 1;
13495         }
13496         if (time_second - starttime > stat_cleanup_high_delay)
13497                 stat_cleanup_high_delay = time_second - starttime;
13498         UFS_LOCK(ump);
13499         return (error);
13500 }
13501
13502 /*
13503  * Scan the vnodes for the specified mount point flushing out any
13504  * vnodes that can be locked without waiting. Finally, try to flush
13505  * the device associated with the mount point if it can be locked
13506  * without waiting.
13507  *
13508  * We return 0 if we were able to lock every vnode in our scan.
13509  * If we had to skip one or more vnodes, we return 1.
13510  */
13511 static int
13512 softdep_request_cleanup_flush(mp, ump)
13513         struct mount *mp;
13514         struct ufsmount *ump;
13515 {
13516         struct thread *td;
13517         struct vnode *lvp, *mvp;
13518         int failed_vnode;
13519
13520         failed_vnode = 0;
13521         td = curthread;
13522         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13523                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13524                         VI_UNLOCK(lvp);
13525                         continue;
13526                 }
13527                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13528                     td) != 0) {
13529                         failed_vnode = 1;
13530                         continue;
13531                 }
13532                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13533                         vput(lvp);
13534                         continue;
13535                 }
13536                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13537                 vput(lvp);
13538         }
13539         lvp = ump->um_devvp;
13540         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13541                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13542                 VOP_UNLOCK(lvp, 0);
13543         }
13544         return (failed_vnode);
13545 }
13546
13547 static bool
13548 softdep_excess_items(struct ufsmount *ump, int item)
13549 {
13550
13551         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13552         return (dep_current[item] > max_softdeps &&
13553             ump->softdep_curdeps[item] > max_softdeps /
13554             stat_flush_threads);
13555 }
13556
13557 static void
13558 schedule_cleanup(struct mount *mp)
13559 {
13560         struct ufsmount *ump;
13561         struct thread *td;
13562
13563         ump = VFSTOUFS(mp);
13564         LOCK_OWNED(ump);
13565         FREE_LOCK(ump);
13566         td = curthread;
13567         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13568             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13569                 /*
13570                  * No ast is delivered to kernel threads, so nobody
13571                  * would deref the mp.  Some kernel threads
13572                  * explicitely check for AST, e.g. NFS daemon does
13573                  * this in the serving loop.
13574                  */
13575                 return;
13576         }
13577         if (td->td_su != NULL)
13578                 vfs_rel(td->td_su);
13579         vfs_ref(mp);
13580         td->td_su = mp;
13581         thread_lock(td);
13582         td->td_flags |= TDF_ASTPENDING;
13583         thread_unlock(td);
13584 }
13585
13586 static void
13587 softdep_ast_cleanup_proc(struct thread *td)
13588 {
13589         struct mount *mp;
13590         struct ufsmount *ump;
13591         int error;
13592         bool req;
13593
13594         while ((mp = td->td_su) != NULL) {
13595                 td->td_su = NULL;
13596                 error = vfs_busy(mp, MBF_NOWAIT);
13597                 vfs_rel(mp);
13598                 if (error != 0)
13599                         return;
13600                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13601                         ump = VFSTOUFS(mp);
13602                         for (;;) {
13603                                 req = false;
13604                                 ACQUIRE_LOCK(ump);
13605                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13606                                         req = true;
13607                                         request_cleanup(mp, FLUSH_INODES);
13608                                 }
13609                                 if (softdep_excess_items(ump, D_DIRREM)) {
13610                                         req = true;
13611                                         request_cleanup(mp, FLUSH_BLOCKS);
13612                                 }
13613                                 FREE_LOCK(ump);
13614                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13615                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13616                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13617                                         error = vn_start_write(NULL, &mp,
13618                                             V_WAIT);
13619                                         if (error == 0) {
13620                                                 req = true;
13621                                                 VFS_SYNC(mp, MNT_WAIT);
13622                                                 vn_finished_write(mp);
13623                                         }
13624                                 }
13625                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13626                                         break;
13627                         }
13628                 }
13629                 vfs_unbusy(mp);
13630         }
13631         if ((mp = td->td_su) != NULL) {
13632                 td->td_su = NULL;
13633                 vfs_rel(mp);
13634         }
13635 }
13636
13637 /*
13638  * If memory utilization has gotten too high, deliberately slow things
13639  * down and speed up the I/O processing.
13640  */
13641 static int
13642 request_cleanup(mp, resource)
13643         struct mount *mp;
13644         int resource;
13645 {
13646         struct thread *td = curthread;
13647         struct ufsmount *ump;
13648
13649         ump = VFSTOUFS(mp);
13650         LOCK_OWNED(ump);
13651         /*
13652          * We never hold up the filesystem syncer or buf daemon.
13653          */
13654         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13655                 return (0);
13656         /*
13657          * First check to see if the work list has gotten backlogged.
13658          * If it has, co-opt this process to help clean up two entries.
13659          * Because this process may hold inodes locked, we cannot
13660          * handle any remove requests that might block on a locked
13661          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13662          * to avoid recursively processing the worklist.
13663          */
13664         if (ump->softdep_on_worklist > max_softdeps / 10) {
13665                 td->td_pflags |= TDP_SOFTDEP;
13666                 process_worklist_item(mp, 2, LK_NOWAIT);
13667                 td->td_pflags &= ~TDP_SOFTDEP;
13668                 stat_worklist_push += 2;
13669                 return(1);
13670         }
13671         /*
13672          * Next, we attempt to speed up the syncer process. If that
13673          * is successful, then we allow the process to continue.
13674          */
13675         if (softdep_speedup(ump) &&
13676             resource != FLUSH_BLOCKS_WAIT &&
13677             resource != FLUSH_INODES_WAIT)
13678                 return(0);
13679         /*
13680          * If we are resource constrained on inode dependencies, try
13681          * flushing some dirty inodes. Otherwise, we are constrained
13682          * by file deletions, so try accelerating flushes of directories
13683          * with removal dependencies. We would like to do the cleanup
13684          * here, but we probably hold an inode locked at this point and 
13685          * that might deadlock against one that we try to clean. So,
13686          * the best that we can do is request the syncer daemon to do
13687          * the cleanup for us.
13688          */
13689         switch (resource) {
13690
13691         case FLUSH_INODES:
13692         case FLUSH_INODES_WAIT:
13693                 ACQUIRE_GBLLOCK(&lk);
13694                 stat_ino_limit_push += 1;
13695                 req_clear_inodedeps += 1;
13696                 FREE_GBLLOCK(&lk);
13697                 stat_countp = &stat_ino_limit_hit;
13698                 break;
13699
13700         case FLUSH_BLOCKS:
13701         case FLUSH_BLOCKS_WAIT:
13702                 ACQUIRE_GBLLOCK(&lk);
13703                 stat_blk_limit_push += 1;
13704                 req_clear_remove += 1;
13705                 FREE_GBLLOCK(&lk);
13706                 stat_countp = &stat_blk_limit_hit;
13707                 break;
13708
13709         default:
13710                 panic("request_cleanup: unknown type");
13711         }
13712         /*
13713          * Hopefully the syncer daemon will catch up and awaken us.
13714          * We wait at most tickdelay before proceeding in any case.
13715          */
13716         ACQUIRE_GBLLOCK(&lk);
13717         FREE_LOCK(ump);
13718         proc_waiting += 1;
13719         if (callout_pending(&softdep_callout) == FALSE)
13720                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13721                     pause_timer, 0);
13722
13723         if ((td->td_pflags & TDP_KTHREAD) == 0)
13724                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13725         proc_waiting -= 1;
13726         FREE_GBLLOCK(&lk);
13727         ACQUIRE_LOCK(ump);
13728         return (1);
13729 }
13730
13731 /*
13732  * Awaken processes pausing in request_cleanup and clear proc_waiting
13733  * to indicate that there is no longer a timer running. Pause_timer
13734  * will be called with the global softdep mutex (&lk) locked.
13735  */
13736 static void
13737 pause_timer(arg)
13738         void *arg;
13739 {
13740
13741         GBLLOCK_OWNED(&lk);
13742         /*
13743          * The callout_ API has acquired mtx and will hold it around this
13744          * function call.
13745          */
13746         *stat_countp += proc_waiting;
13747         wakeup(&proc_waiting);
13748 }
13749
13750 /*
13751  * If requested, try removing inode or removal dependencies.
13752  */
13753 static void
13754 check_clear_deps(mp)
13755         struct mount *mp;
13756 {
13757
13758         /*
13759          * If we are suspended, it may be because of our using
13760          * too many inodedeps, so help clear them out.
13761          */
13762         if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13763                 clear_inodedeps(mp);
13764         /*
13765          * General requests for cleanup of backed up dependencies
13766          */
13767         ACQUIRE_GBLLOCK(&lk);
13768         if (req_clear_inodedeps) {
13769                 req_clear_inodedeps -= 1;
13770                 FREE_GBLLOCK(&lk);
13771                 clear_inodedeps(mp);
13772                 ACQUIRE_GBLLOCK(&lk);
13773                 wakeup(&proc_waiting);
13774         }
13775         if (req_clear_remove) {
13776                 req_clear_remove -= 1;
13777                 FREE_GBLLOCK(&lk);
13778                 clear_remove(mp);
13779                 ACQUIRE_GBLLOCK(&lk);
13780                 wakeup(&proc_waiting);
13781         }
13782         FREE_GBLLOCK(&lk);
13783 }
13784
13785 /*
13786  * Flush out a directory with at least one removal dependency in an effort to
13787  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13788  */
13789 static void
13790 clear_remove(mp)
13791         struct mount *mp;
13792 {
13793         struct pagedep_hashhead *pagedephd;
13794         struct pagedep *pagedep;
13795         struct ufsmount *ump;
13796         struct vnode *vp;
13797         struct bufobj *bo;
13798         int error, cnt;
13799         ino_t ino;
13800
13801         ump = VFSTOUFS(mp);
13802         LOCK_OWNED(ump);
13803
13804         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13805                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13806                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13807                         ump->pagedep_nextclean = 0;
13808                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13809                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13810                                 continue;
13811                         ino = pagedep->pd_ino;
13812                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13813                                 continue;
13814                         FREE_LOCK(ump);
13815
13816                         /*
13817                          * Let unmount clear deps
13818                          */
13819                         error = vfs_busy(mp, MBF_NOWAIT);
13820                         if (error != 0)
13821                                 goto finish_write;
13822                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13823                              FFSV_FORCEINSMQ);
13824                         vfs_unbusy(mp);
13825                         if (error != 0) {
13826                                 softdep_error("clear_remove: vget", error);
13827                                 goto finish_write;
13828                         }
13829                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13830                                 softdep_error("clear_remove: fsync", error);
13831                         bo = &vp->v_bufobj;
13832                         BO_LOCK(bo);
13833                         drain_output(vp);
13834                         BO_UNLOCK(bo);
13835                         vput(vp);
13836                 finish_write:
13837                         vn_finished_write(mp);
13838                         ACQUIRE_LOCK(ump);
13839                         return;
13840                 }
13841         }
13842 }
13843
13844 /*
13845  * Clear out a block of dirty inodes in an effort to reduce
13846  * the number of inodedep dependency structures.
13847  */
13848 static void
13849 clear_inodedeps(mp)
13850         struct mount *mp;
13851 {
13852         struct inodedep_hashhead *inodedephd;
13853         struct inodedep *inodedep;
13854         struct ufsmount *ump;
13855         struct vnode *vp;
13856         struct fs *fs;
13857         int error, cnt;
13858         ino_t firstino, lastino, ino;
13859
13860         ump = VFSTOUFS(mp);
13861         fs = ump->um_fs;
13862         LOCK_OWNED(ump);
13863         /*
13864          * Pick a random inode dependency to be cleared.
13865          * We will then gather up all the inodes in its block 
13866          * that have dependencies and flush them out.
13867          */
13868         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13869                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13870                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13871                         ump->inodedep_nextclean = 0;
13872                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13873                         break;
13874         }
13875         if (inodedep == NULL)
13876                 return;
13877         /*
13878          * Find the last inode in the block with dependencies.
13879          */
13880         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13881         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13882                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13883                         break;
13884         /*
13885          * Asynchronously push all but the last inode with dependencies.
13886          * Synchronously push the last inode with dependencies to ensure
13887          * that the inode block gets written to free up the inodedeps.
13888          */
13889         for (ino = firstino; ino <= lastino; ino++) {
13890                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13891                         continue;
13892                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13893                         continue;
13894                 FREE_LOCK(ump);
13895                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13896                 if (error != 0) {
13897                         vn_finished_write(mp);
13898                         ACQUIRE_LOCK(ump);
13899                         return;
13900                 }
13901                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13902                     FFSV_FORCEINSMQ)) != 0) {
13903                         softdep_error("clear_inodedeps: vget", error);
13904                         vfs_unbusy(mp);
13905                         vn_finished_write(mp);
13906                         ACQUIRE_LOCK(ump);
13907                         return;
13908                 }
13909                 vfs_unbusy(mp);
13910                 if (ino == lastino) {
13911                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13912                                 softdep_error("clear_inodedeps: fsync1", error);
13913                 } else {
13914                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13915                                 softdep_error("clear_inodedeps: fsync2", error);
13916                         BO_LOCK(&vp->v_bufobj);
13917                         drain_output(vp);
13918                         BO_UNLOCK(&vp->v_bufobj);
13919                 }
13920                 vput(vp);
13921                 vn_finished_write(mp);
13922                 ACQUIRE_LOCK(ump);
13923         }
13924 }
13925
13926 void
13927 softdep_buf_append(bp, wkhd)
13928         struct buf *bp;
13929         struct workhead *wkhd;
13930 {
13931         struct worklist *wk;
13932         struct ufsmount *ump;
13933
13934         if ((wk = LIST_FIRST(wkhd)) == NULL)
13935                 return;
13936         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13937             ("softdep_buf_append called on non-softdep filesystem"));
13938         ump = VFSTOUFS(wk->wk_mp);
13939         ACQUIRE_LOCK(ump);
13940         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13941                 WORKLIST_REMOVE(wk);
13942                 WORKLIST_INSERT(&bp->b_dep, wk);
13943         }
13944         FREE_LOCK(ump);
13945
13946 }
13947
13948 void
13949 softdep_inode_append(ip, cred, wkhd)
13950         struct inode *ip;
13951         struct ucred *cred;
13952         struct workhead *wkhd;
13953 {
13954         struct buf *bp;
13955         struct fs *fs;
13956         struct ufsmount *ump;
13957         int error;
13958
13959         ump = ITOUMP(ip);
13960         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13961             ("softdep_inode_append called on non-softdep filesystem"));
13962         fs = ump->um_fs;
13963         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13964             (int)fs->fs_bsize, cred, &bp);
13965         if (error) {
13966                 bqrelse(bp);
13967                 softdep_freework(wkhd);
13968                 return;
13969         }
13970         softdep_buf_append(bp, wkhd);
13971         bqrelse(bp);
13972 }
13973
13974 void
13975 softdep_freework(wkhd)
13976         struct workhead *wkhd;
13977 {
13978         struct worklist *wk;
13979         struct ufsmount *ump;
13980
13981         if ((wk = LIST_FIRST(wkhd)) == NULL)
13982                 return;
13983         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13984             ("softdep_freework called on non-softdep filesystem"));
13985         ump = VFSTOUFS(wk->wk_mp);
13986         ACQUIRE_LOCK(ump);
13987         handle_jwork(wkhd);
13988         FREE_LOCK(ump);
13989 }
13990
13991 static struct ufsmount *
13992 softdep_bp_to_mp(bp)
13993         struct buf *bp;
13994 {
13995         struct mount *mp;
13996         struct vnode *vp;
13997
13998         if (LIST_EMPTY(&bp->b_dep))
13999                 return (NULL);
14000         vp = bp->b_vp;
14001         KASSERT(vp != NULL,
14002             ("%s, buffer with dependencies lacks vnode", __func__));
14003
14004         /*
14005          * The ump mount point is stable after we get a correct
14006          * pointer, since bp is locked and this prevents unmount from
14007          * proceeding.  But to get to it, we cannot dereference bp->b_dep
14008          * head wk_mp, because we do not yet own SU ump lock and
14009          * workitem might be freed while dereferenced.
14010          */
14011 retry:
14012         switch (vp->v_type) {
14013         case VCHR:
14014                 VI_LOCK(vp);
14015                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14016                 VI_UNLOCK(vp);
14017                 if (mp == NULL)
14018                         goto retry;
14019                 break;
14020         case VREG:
14021         case VDIR:
14022         case VLNK:
14023         case VFIFO:
14024         case VSOCK:
14025                 mp = vp->v_mount;
14026                 break;
14027         case VBLK:
14028                 vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14029                 /* FALLTHROUGH */
14030         case VNON:
14031         case VBAD:
14032         case VMARKER:
14033                 mp = NULL;
14034                 break;
14035         default:
14036                 vn_printf(vp, "unknown vnode type");
14037                 mp = NULL;
14038                 break;
14039         }
14040         return (VFSTOUFS(mp));
14041 }
14042
14043 /*
14044  * Function to determine if the buffer has outstanding dependencies
14045  * that will cause a roll-back if the buffer is written. If wantcount
14046  * is set, return number of dependencies, otherwise just yes or no.
14047  */
14048 static int
14049 softdep_count_dependencies(bp, wantcount)
14050         struct buf *bp;
14051         int wantcount;
14052 {
14053         struct worklist *wk;
14054         struct ufsmount *ump;
14055         struct bmsafemap *bmsafemap;
14056         struct freework *freework;
14057         struct inodedep *inodedep;
14058         struct indirdep *indirdep;
14059         struct freeblks *freeblks;
14060         struct allocindir *aip;
14061         struct pagedep *pagedep;
14062         struct dirrem *dirrem;
14063         struct newblk *newblk;
14064         struct mkdir *mkdir;
14065         struct diradd *dap;
14066         int i, retval;
14067
14068         ump = softdep_bp_to_mp(bp);
14069         if (ump == NULL)
14070                 return (0);
14071         retval = 0;
14072         ACQUIRE_LOCK(ump);
14073         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14074                 switch (wk->wk_type) {
14075
14076                 case D_INODEDEP:
14077                         inodedep = WK_INODEDEP(wk);
14078                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14079                                 /* bitmap allocation dependency */
14080                                 retval += 1;
14081                                 if (!wantcount)
14082                                         goto out;
14083                         }
14084                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14085                                 /* direct block pointer dependency */
14086                                 retval += 1;
14087                                 if (!wantcount)
14088                                         goto out;
14089                         }
14090                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14091                                 /* direct block pointer dependency */
14092                                 retval += 1;
14093                                 if (!wantcount)
14094                                         goto out;
14095                         }
14096                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14097                                 /* Add reference dependency. */
14098                                 retval += 1;
14099                                 if (!wantcount)
14100                                         goto out;
14101                         }
14102                         continue;
14103
14104                 case D_INDIRDEP:
14105                         indirdep = WK_INDIRDEP(wk);
14106
14107                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14108                                 /* indirect truncation dependency */
14109                                 retval += 1;
14110                                 if (!wantcount)
14111                                         goto out;
14112                         }
14113
14114                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14115                                 /* indirect block pointer dependency */
14116                                 retval += 1;
14117                                 if (!wantcount)
14118                                         goto out;
14119                         }
14120                         continue;
14121
14122                 case D_PAGEDEP:
14123                         pagedep = WK_PAGEDEP(wk);
14124                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14125                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14126                                         /* Journal remove ref dependency. */
14127                                         retval += 1;
14128                                         if (!wantcount)
14129                                                 goto out;
14130                                 }
14131                         }
14132                         for (i = 0; i < DAHASHSZ; i++) {
14133
14134                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14135                                         /* directory entry dependency */
14136                                         retval += 1;
14137                                         if (!wantcount)
14138                                                 goto out;
14139                                 }
14140                         }
14141                         continue;
14142
14143                 case D_BMSAFEMAP:
14144                         bmsafemap = WK_BMSAFEMAP(wk);
14145                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14146                                 /* Add reference dependency. */
14147                                 retval += 1;
14148                                 if (!wantcount)
14149                                         goto out;
14150                         }
14151                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14152                                 /* Allocate block dependency. */
14153                                 retval += 1;
14154                                 if (!wantcount)
14155                                         goto out;
14156                         }
14157                         continue;
14158
14159                 case D_FREEBLKS:
14160                         freeblks = WK_FREEBLKS(wk);
14161                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14162                                 /* Freeblk journal dependency. */
14163                                 retval += 1;
14164                                 if (!wantcount)
14165                                         goto out;
14166                         }
14167                         continue;
14168
14169                 case D_ALLOCDIRECT:
14170                 case D_ALLOCINDIR:
14171                         newblk = WK_NEWBLK(wk);
14172                         if (newblk->nb_jnewblk) {
14173                                 /* Journal allocate dependency. */
14174                                 retval += 1;
14175                                 if (!wantcount)
14176                                         goto out;
14177                         }
14178                         continue;
14179
14180                 case D_MKDIR:
14181                         mkdir = WK_MKDIR(wk);
14182                         if (mkdir->md_jaddref) {
14183                                 /* Journal reference dependency. */
14184                                 retval += 1;
14185                                 if (!wantcount)
14186                                         goto out;
14187                         }
14188                         continue;
14189
14190                 case D_FREEWORK:
14191                 case D_FREEDEP:
14192                 case D_JSEGDEP:
14193                 case D_JSEG:
14194                 case D_SBDEP:
14195                         /* never a dependency on these blocks */
14196                         continue;
14197
14198                 default:
14199                         panic("softdep_count_dependencies: Unexpected type %s",
14200                             TYPENAME(wk->wk_type));
14201                         /* NOTREACHED */
14202                 }
14203         }
14204 out:
14205         FREE_LOCK(ump);
14206         return (retval);
14207 }
14208
14209 /*
14210  * Acquire exclusive access to a buffer.
14211  * Must be called with a locked mtx parameter.
14212  * Return acquired buffer or NULL on failure.
14213  */
14214 static struct buf *
14215 getdirtybuf(bp, lock, waitfor)
14216         struct buf *bp;
14217         struct rwlock *lock;
14218         int waitfor;
14219 {
14220         int error;
14221
14222         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14223                 if (waitfor != MNT_WAIT)
14224                         return (NULL);
14225                 error = BUF_LOCK(bp,
14226                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14227                 /*
14228                  * Even if we successfully acquire bp here, we have dropped
14229                  * lock, which may violates our guarantee.
14230                  */
14231                 if (error == 0)
14232                         BUF_UNLOCK(bp);
14233                 else if (error != ENOLCK)
14234                         panic("getdirtybuf: inconsistent lock: %d", error);
14235                 rw_wlock(lock);
14236                 return (NULL);
14237         }
14238         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14239                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14240                         rw_wunlock(lock);
14241                         BO_LOCK(bp->b_bufobj);
14242                         BUF_UNLOCK(bp);
14243                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14244                                 bp->b_vflags |= BV_BKGRDWAIT;
14245                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14246                                        PRIBIO | PDROP, "getbuf", 0);
14247                         } else
14248                                 BO_UNLOCK(bp->b_bufobj);
14249                         rw_wlock(lock);
14250                         return (NULL);
14251                 }
14252                 BUF_UNLOCK(bp);
14253                 if (waitfor != MNT_WAIT)
14254                         return (NULL);
14255 #ifdef DEBUG_VFS_LOCKS
14256                 if (bp->b_vp->v_type != VCHR)
14257                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14258 #endif
14259                 bp->b_vflags |= BV_BKGRDWAIT;
14260                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14261                 return (NULL);
14262         }
14263         if ((bp->b_flags & B_DELWRI) == 0) {
14264                 BUF_UNLOCK(bp);
14265                 return (NULL);
14266         }
14267         bremfree(bp);
14268         return (bp);
14269 }
14270
14271
14272 /*
14273  * Check if it is safe to suspend the file system now.  On entry,
14274  * the vnode interlock for devvp should be held.  Return 0 with
14275  * the mount interlock held if the file system can be suspended now,
14276  * otherwise return EAGAIN with the mount interlock held.
14277  */
14278 int
14279 softdep_check_suspend(struct mount *mp,
14280                       struct vnode *devvp,
14281                       int softdep_depcnt,
14282                       int softdep_accdepcnt,
14283                       int secondary_writes,
14284                       int secondary_accwrites)
14285 {
14286         struct bufobj *bo;
14287         struct ufsmount *ump;
14288         struct inodedep *inodedep;
14289         int error, unlinked;
14290
14291         bo = &devvp->v_bufobj;
14292         ASSERT_BO_WLOCKED(bo);
14293
14294         /*
14295          * If we are not running with soft updates, then we need only
14296          * deal with secondary writes as we try to suspend.
14297          */
14298         if (MOUNTEDSOFTDEP(mp) == 0) {
14299                 MNT_ILOCK(mp);
14300                 while (mp->mnt_secondary_writes != 0) {
14301                         BO_UNLOCK(bo);
14302                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14303                             (PUSER - 1) | PDROP, "secwr", 0);
14304                         BO_LOCK(bo);
14305                         MNT_ILOCK(mp);
14306                 }
14307
14308                 /*
14309                  * Reasons for needing more work before suspend:
14310                  * - Dirty buffers on devvp.
14311                  * - Secondary writes occurred after start of vnode sync loop
14312                  */
14313                 error = 0;
14314                 if (bo->bo_numoutput > 0 ||
14315                     bo->bo_dirty.bv_cnt > 0 ||
14316                     secondary_writes != 0 ||
14317                     mp->mnt_secondary_writes != 0 ||
14318                     secondary_accwrites != mp->mnt_secondary_accwrites)
14319                         error = EAGAIN;
14320                 BO_UNLOCK(bo);
14321                 return (error);
14322         }
14323
14324         /*
14325          * If we are running with soft updates, then we need to coordinate
14326          * with them as we try to suspend.
14327          */
14328         ump = VFSTOUFS(mp);
14329         for (;;) {
14330                 if (!TRY_ACQUIRE_LOCK(ump)) {
14331                         BO_UNLOCK(bo);
14332                         ACQUIRE_LOCK(ump);
14333                         FREE_LOCK(ump);
14334                         BO_LOCK(bo);
14335                         continue;
14336                 }
14337                 MNT_ILOCK(mp);
14338                 if (mp->mnt_secondary_writes != 0) {
14339                         FREE_LOCK(ump);
14340                         BO_UNLOCK(bo);
14341                         msleep(&mp->mnt_secondary_writes,
14342                                MNT_MTX(mp),
14343                                (PUSER - 1) | PDROP, "secwr", 0);
14344                         BO_LOCK(bo);
14345                         continue;
14346                 }
14347                 break;
14348         }
14349
14350         unlinked = 0;
14351         if (MOUNTEDSUJ(mp)) {
14352                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14353                     inodedep != NULL;
14354                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14355                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14356                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14357                             UNLINKONLIST) ||
14358                             !check_inodedep_free(inodedep))
14359                                 continue;
14360                         unlinked++;
14361                 }
14362         }
14363
14364         /*
14365          * Reasons for needing more work before suspend:
14366          * - Dirty buffers on devvp.
14367          * - Softdep activity occurred after start of vnode sync loop
14368          * - Secondary writes occurred after start of vnode sync loop
14369          */
14370         error = 0;
14371         if (bo->bo_numoutput > 0 ||
14372             bo->bo_dirty.bv_cnt > 0 ||
14373             softdep_depcnt != unlinked ||
14374             ump->softdep_deps != unlinked ||
14375             softdep_accdepcnt != ump->softdep_accdeps ||
14376             secondary_writes != 0 ||
14377             mp->mnt_secondary_writes != 0 ||
14378             secondary_accwrites != mp->mnt_secondary_accwrites)
14379                 error = EAGAIN;
14380         FREE_LOCK(ump);
14381         BO_UNLOCK(bo);
14382         return (error);
14383 }
14384
14385
14386 /*
14387  * Get the number of dependency structures for the file system, both
14388  * the current number and the total number allocated.  These will
14389  * later be used to detect that softdep processing has occurred.
14390  */
14391 void
14392 softdep_get_depcounts(struct mount *mp,
14393                       int *softdep_depsp,
14394                       int *softdep_accdepsp)
14395 {
14396         struct ufsmount *ump;
14397
14398         if (MOUNTEDSOFTDEP(mp) == 0) {
14399                 *softdep_depsp = 0;
14400                 *softdep_accdepsp = 0;
14401                 return;
14402         }
14403         ump = VFSTOUFS(mp);
14404         ACQUIRE_LOCK(ump);
14405         *softdep_depsp = ump->softdep_deps;
14406         *softdep_accdepsp = ump->softdep_accdeps;
14407         FREE_LOCK(ump);
14408 }
14409
14410 /*
14411  * Wait for pending output on a vnode to complete.
14412  */
14413 static void
14414 drain_output(vp)
14415         struct vnode *vp;
14416 {
14417
14418         ASSERT_VOP_LOCKED(vp, "drain_output");
14419         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14420 }
14421
14422 /*
14423  * Called whenever a buffer that is being invalidated or reallocated
14424  * contains dependencies. This should only happen if an I/O error has
14425  * occurred. The routine is called with the buffer locked.
14426  */ 
14427 static void
14428 softdep_deallocate_dependencies(bp)
14429         struct buf *bp;
14430 {
14431
14432         if ((bp->b_ioflags & BIO_ERROR) == 0)
14433                 panic("softdep_deallocate_dependencies: dangling deps");
14434         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14435                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14436         else
14437                 printf("softdep_deallocate_dependencies: "
14438                     "got error %d while accessing filesystem\n", bp->b_error);
14439         if (bp->b_error != ENXIO)
14440                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14441 }
14442
14443 /*
14444  * Function to handle asynchronous write errors in the filesystem.
14445  */
14446 static void
14447 softdep_error(func, error)
14448         char *func;
14449         int error;
14450 {
14451
14452         /* XXX should do something better! */
14453         printf("%s: got error %d while accessing filesystem\n", func, error);
14454 }
14455
14456 #ifdef DDB
14457
14458 /* exported to ffs_vfsops.c */
14459 extern void db_print_ffs(struct ufsmount *ump);
14460 void
14461 db_print_ffs(struct ufsmount *ump)
14462 {
14463         db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14464             ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14465         db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14466             ump->um_fs, ump->softdep_on_worklist,
14467             ump->softdep_deps, ump->softdep_req);
14468 }
14469
14470 static void
14471 worklist_print(struct worklist *wk, int verbose)
14472 {
14473
14474         if (!verbose) {
14475                 db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14476                     (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14477                 return;
14478         }
14479         db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14480             TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14481             LIST_NEXT(wk, wk_list));
14482         db_print_ffs(VFSTOUFS(wk->wk_mp));
14483 }
14484
14485 static void
14486 inodedep_print(struct inodedep *inodedep, int verbose)
14487 {
14488
14489         worklist_print(&inodedep->id_list, 0);
14490         db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14491             inodedep->id_fs,
14492             (intmax_t)inodedep->id_ino,
14493             (intmax_t)fsbtodb(inodedep->id_fs,
14494                 ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14495             (intmax_t)inodedep->id_nlinkdelta,
14496             (intmax_t)inodedep->id_savednlink);
14497
14498         if (verbose == 0)
14499                 return;
14500
14501         db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14502             inodedep->id_bmsafemap,
14503             inodedep->id_mkdiradd,
14504             TAILQ_FIRST(&inodedep->id_inoreflst));
14505         db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14506             LIST_FIRST(&inodedep->id_dirremhd),
14507             LIST_FIRST(&inodedep->id_pendinghd),
14508             LIST_FIRST(&inodedep->id_bufwait));
14509         db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14510             LIST_FIRST(&inodedep->id_inowait),
14511             TAILQ_FIRST(&inodedep->id_inoupdt),
14512             TAILQ_FIRST(&inodedep->id_newinoupdt));
14513         db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14514             TAILQ_FIRST(&inodedep->id_extupdt),
14515             TAILQ_FIRST(&inodedep->id_newextupdt),
14516             TAILQ_FIRST(&inodedep->id_freeblklst));
14517         db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14518             inodedep->id_savedino1,
14519             (intmax_t)inodedep->id_savedsize,
14520             (intmax_t)inodedep->id_savedextsize);
14521 }
14522
14523 static void
14524 newblk_print(struct newblk *nbp)
14525 {
14526
14527         worklist_print(&nbp->nb_list, 0);
14528         db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14529         db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14530             &nbp->nb_jnewblk,
14531             &nbp->nb_bmsafemap,
14532             &nbp->nb_freefrag);
14533         db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14534             LIST_FIRST(&nbp->nb_indirdeps),
14535             LIST_FIRST(&nbp->nb_newdirblk),
14536             LIST_FIRST(&nbp->nb_jwork));
14537 }
14538
14539 static void
14540 allocdirect_print(struct allocdirect *adp)
14541 {
14542
14543         newblk_print(&adp->ad_block);
14544         db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14545             adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14546         db_printf("    offset %d, inodedep %p\n",
14547             adp->ad_offset, adp->ad_inodedep);
14548 }
14549
14550 static void
14551 allocindir_print(struct allocindir *aip)
14552 {
14553
14554         newblk_print(&aip->ai_block);
14555         db_printf("    oldblkno %jd, lbn %jd\n",
14556             (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14557         db_printf("    offset %d, indirdep %p\n",
14558             aip->ai_offset, aip->ai_indirdep);
14559 }
14560
14561 static void
14562 mkdir_print(struct mkdir *mkdir)
14563 {
14564
14565         worklist_print(&mkdir->md_list, 0);
14566         db_printf("    diradd %p, jaddref %p, buf %p\n",
14567                 mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14568 }
14569
14570 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14571 {
14572
14573         if (have_addr == 0) {
14574                 db_printf("inodedep address required\n");
14575                 return;
14576         }
14577         inodedep_print((struct inodedep*)addr, 1);
14578 }
14579
14580 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14581 {
14582         struct inodedep_hashhead *inodedephd;
14583         struct inodedep *inodedep;
14584         struct ufsmount *ump;
14585         int cnt;
14586
14587         if (have_addr == 0) {
14588                 db_printf("ufsmount address required\n");
14589                 return;
14590         }
14591         ump = (struct ufsmount *)addr;
14592         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14593                 inodedephd = &ump->inodedep_hashtbl[cnt];
14594                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14595                         inodedep_print(inodedep, 0);
14596                 }
14597         }
14598 }
14599
14600 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14601 {
14602
14603         if (have_addr == 0) {
14604                 db_printf("worklist address required\n");
14605                 return;
14606         }
14607         worklist_print((struct worklist *)addr, 1);
14608 }
14609
14610 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14611 {
14612         struct worklist *wk;
14613         struct workhead *wkhd;
14614
14615         if (have_addr == 0) {
14616                 db_printf("worklist address required "
14617                     "(for example value in bp->b_dep)\n");
14618                 return;
14619         }
14620         /*
14621          * We often do not have the address of the worklist head but
14622          * instead a pointer to its first entry (e.g., we have the
14623          * contents of bp->b_dep rather than &bp->b_dep). But the back
14624          * pointer of bp->b_dep will point at the head of the list, so
14625          * we cheat and use that instead. If we are in the middle of
14626          * a list we will still get the same result, so nothing
14627          * unexpected will result.
14628          */
14629         wk = (struct worklist *)addr;
14630         if (wk == NULL)
14631                 return;
14632         wkhd = (struct workhead *)wk->wk_list.le_prev;
14633         LIST_FOREACH(wk, wkhd, wk_list) {
14634                 switch(wk->wk_type) {
14635                 case D_INODEDEP:
14636                         inodedep_print(WK_INODEDEP(wk), 0);
14637                         continue;
14638                 case D_ALLOCDIRECT:
14639                         allocdirect_print(WK_ALLOCDIRECT(wk));
14640                         continue;
14641                 case D_ALLOCINDIR:
14642                         allocindir_print(WK_ALLOCINDIR(wk));
14643                         continue;
14644                 case D_MKDIR:
14645                         mkdir_print(WK_MKDIR(wk));
14646                         continue;
14647                 default:
14648                         worklist_print(wk, 0);
14649                         continue;
14650                 }
14651         }
14652 }
14653
14654 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14655 {
14656         if (have_addr == 0) {
14657                 db_printf("mkdir address required\n");
14658                 return;
14659         }
14660         mkdir_print((struct mkdir *)addr);
14661 }
14662
14663 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14664 {
14665         struct mkdirlist *mkdirlisthd;
14666         struct mkdir *mkdir;
14667
14668         if (have_addr == 0) {
14669                 db_printf("mkdir listhead address required\n");
14670                 return;
14671         }
14672         mkdirlisthd = (struct mkdirlist *)addr;
14673         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14674                 mkdir_print(mkdir);
14675                 if (mkdir->md_diradd != NULL) {
14676                         db_printf("    ");
14677                         worklist_print(&mkdir->md_diradd->da_list, 0);
14678                 }
14679                 if (mkdir->md_jaddref != NULL) {
14680                         db_printf("    ");
14681                         worklist_print(&mkdir->md_jaddref->ja_list, 0);
14682                 }
14683         }
14684 }
14685
14686 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14687 {
14688         if (have_addr == 0) {
14689                 db_printf("allocdirect address required\n");
14690                 return;
14691         }
14692         allocdirect_print((struct allocdirect *)addr);
14693 }
14694
14695 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14696 {
14697         if (have_addr == 0) {
14698                 db_printf("allocindir address required\n");
14699                 return;
14700         }
14701         allocindir_print((struct allocindir *)addr);
14702 }
14703
14704 #endif /* DDB */
14705
14706 #endif /* SOFTUPDATES */