]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
Merge r358034 from the clang1000-import branch:
[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 #include <geom/geom_vfs.h>
91
92 #include <ddb/ddb.h>
93
94 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
95
96 #ifndef SOFTUPDATES
97
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100         struct mount *oldmnt;
101         int flags;
102         struct thread *td;
103 {
104
105         panic("softdep_flushfiles called");
106 }
107
108 int
109 softdep_mount(devvp, mp, fs, cred)
110         struct vnode *devvp;
111         struct mount *mp;
112         struct fs *fs;
113         struct ucred *cred;
114 {
115
116         return (0);
117 }
118
119 void
120 softdep_initialize()
121 {
122
123         return;
124 }
125
126 void
127 softdep_uninitialize()
128 {
129
130         return;
131 }
132
133 void
134 softdep_unmount(mp)
135         struct mount *mp;
136 {
137
138         panic("softdep_unmount called");
139 }
140
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143         struct ufsmount *ump;
144         struct fs *fs;
145         struct buf *bp;
146 {
147
148         panic("softdep_setup_sbupdate called");
149 }
150
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153         struct buf *bp;
154         struct inode *ip;
155         ino_t newinum;
156         int mode;
157 {
158
159         panic("softdep_setup_inomapdep called");
160 }
161
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164         struct buf *bp;
165         struct mount *mp;
166         ufs2_daddr_t newblkno;
167         int frags;
168         int oldfrags;
169 {
170
171         panic("softdep_setup_blkmapdep called");
172 }
173
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176         struct inode *ip;
177         ufs_lbn_t lbn;
178         ufs2_daddr_t newblkno;
179         ufs2_daddr_t oldblkno;
180         long newsize;
181         long oldsize;
182         struct buf *bp;
183 {
184         
185         panic("softdep_setup_allocdirect called");
186 }
187
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190         struct inode *ip;
191         ufs_lbn_t lbn;
192         ufs2_daddr_t newblkno;
193         ufs2_daddr_t oldblkno;
194         long newsize;
195         long oldsize;
196         struct buf *bp;
197 {
198         
199         panic("softdep_setup_allocext called");
200 }
201
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204         struct inode *ip;
205         ufs_lbn_t lbn;
206         struct buf *bp;
207         int ptrno;
208         ufs2_daddr_t newblkno;
209         ufs2_daddr_t oldblkno;
210         struct buf *nbp;
211 {
212
213         panic("softdep_setup_allocindir_page called");
214 }
215
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218         struct buf *nbp;
219         struct inode *ip;
220         struct buf *bp;
221         int ptrno;
222         ufs2_daddr_t newblkno;
223 {
224
225         panic("softdep_setup_allocindir_meta called");
226 }
227
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230         struct inode *ip;
231         struct ucred *cred;
232         off_t length;
233         int flags;
234 {
235         
236         panic("softdep_journal_freeblocks called");
237 }
238
239 void
240 softdep_journal_fsync(ip)
241         struct inode *ip;
242 {
243
244         panic("softdep_journal_fsync called");
245 }
246
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249         struct inode *ip;
250         off_t length;
251         int flags;
252 {
253         
254         panic("softdep_setup_freeblocks called");
255 }
256
257 void
258 softdep_freefile(pvp, ino, mode)
259                 struct vnode *pvp;
260                 ino_t ino;
261                 int mode;
262 {
263
264         panic("softdep_freefile called");
265 }
266
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269         struct buf *bp;
270         struct inode *dp;
271         off_t diroffset;
272         ino_t newinum;
273         struct buf *newdirbp;
274         int isnewblk;
275 {
276
277         panic("softdep_setup_directory_add called");
278 }
279
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282         struct buf *bp;
283         struct inode *dp;
284         caddr_t base;
285         caddr_t oldloc;
286         caddr_t newloc;
287         int entrysize;
288 {
289
290         panic("softdep_change_directoryentry_offset called");
291 }
292
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295         struct buf *bp;
296         struct inode *dp;
297         struct inode *ip;
298         int isrmdir;
299 {
300         
301         panic("softdep_setup_remove called");
302 }
303
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306         struct buf *bp;
307         struct inode *dp;
308         struct inode *ip;
309         ino_t newinum;
310         int isrmdir;
311 {
312
313         panic("softdep_setup_directory_change called");
314 }
315
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318         struct mount *mp;
319         struct buf *bp;
320         ufs2_daddr_t blkno;
321         int frags;
322         struct workhead *wkhd;
323 {
324
325         panic("%s called", __FUNCTION__);
326 }
327
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330         struct mount *mp;
331         struct buf *bp;
332         ino_t ino;
333         struct workhead *wkhd;
334 {
335
336         panic("%s called", __FUNCTION__);
337 }
338
339 void
340 softdep_setup_unlink(dp, ip)
341         struct inode *dp;
342         struct inode *ip;
343 {
344
345         panic("%s called", __FUNCTION__);
346 }
347
348 void
349 softdep_setup_link(dp, ip)
350         struct inode *dp;
351         struct inode *ip;
352 {
353
354         panic("%s called", __FUNCTION__);
355 }
356
357 void
358 softdep_revert_link(dp, ip)
359         struct inode *dp;
360         struct inode *ip;
361 {
362
363         panic("%s called", __FUNCTION__);
364 }
365
366 void
367 softdep_setup_rmdir(dp, ip)
368         struct inode *dp;
369         struct inode *ip;
370 {
371
372         panic("%s called", __FUNCTION__);
373 }
374
375 void
376 softdep_revert_rmdir(dp, ip)
377         struct inode *dp;
378         struct inode *ip;
379 {
380
381         panic("%s called", __FUNCTION__);
382 }
383
384 void
385 softdep_setup_create(dp, ip)
386         struct inode *dp;
387         struct inode *ip;
388 {
389
390         panic("%s called", __FUNCTION__);
391 }
392
393 void
394 softdep_revert_create(dp, ip)
395         struct inode *dp;
396         struct inode *ip;
397 {
398
399         panic("%s called", __FUNCTION__);
400 }
401
402 void
403 softdep_setup_mkdir(dp, ip)
404         struct inode *dp;
405         struct inode *ip;
406 {
407
408         panic("%s called", __FUNCTION__);
409 }
410
411 void
412 softdep_revert_mkdir(dp, ip)
413         struct inode *dp;
414         struct inode *ip;
415 {
416
417         panic("%s called", __FUNCTION__);
418 }
419
420 void
421 softdep_setup_dotdot_link(dp, ip)
422         struct inode *dp;
423         struct inode *ip;
424 {
425
426         panic("%s called", __FUNCTION__);
427 }
428
429 int
430 softdep_prealloc(vp, waitok)
431         struct vnode *vp;
432         int waitok;
433 {
434
435         panic("%s called", __FUNCTION__);
436 }
437
438 int
439 softdep_journal_lookup(mp, vpp)
440         struct mount *mp;
441         struct vnode **vpp;
442 {
443
444         return (ENOENT);
445 }
446
447 void
448 softdep_change_linkcnt(ip)
449         struct inode *ip;
450 {
451
452         panic("softdep_change_linkcnt called");
453 }
454
455 void 
456 softdep_load_inodeblock(ip)
457         struct inode *ip;
458 {
459
460         panic("softdep_load_inodeblock called");
461 }
462
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465         struct inode *ip;
466         struct buf *bp;
467         int waitfor;
468 {
469
470         panic("softdep_update_inodeblock called");
471 }
472
473 int
474 softdep_fsync(vp)
475         struct vnode *vp;       /* the "in_core" copy of the inode */
476 {
477
478         return (0);
479 }
480
481 void
482 softdep_fsync_mountdev(vp)
483         struct vnode *vp;
484 {
485
486         return;
487 }
488
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491         struct mount *oldmnt;
492         int *countp;
493         struct thread *td;
494 {
495
496         *countp = 0;
497         return (0);
498 }
499
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503
504         panic("softdep_sync_metadata called");
505 }
506
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510
511         panic("softdep_sync_buf called");
512 }
513
514 int
515 softdep_slowdown(vp)
516         struct vnode *vp;
517 {
518
519         panic("softdep_slowdown called");
520 }
521
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524         struct fs *fs;
525         struct vnode *vp;
526         struct ucred *cred;
527         int resource;
528 {
529
530         return (0);
531 }
532
533 int
534 softdep_check_suspend(struct mount *mp,
535                       struct vnode *devvp,
536                       int softdep_depcnt,
537                       int softdep_accdepcnt,
538                       int secondary_writes,
539                       int secondary_accwrites)
540 {
541         struct bufobj *bo;
542         int error;
543         
544         (void) softdep_depcnt,
545         (void) softdep_accdepcnt;
546
547         bo = &devvp->v_bufobj;
548         ASSERT_BO_WLOCKED(bo);
549
550         MNT_ILOCK(mp);
551         while (mp->mnt_secondary_writes != 0) {
552                 BO_UNLOCK(bo);
553                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554                     (PUSER - 1) | PDROP, "secwr", 0);
555                 BO_LOCK(bo);
556                 MNT_ILOCK(mp);
557         }
558
559         /*
560          * Reasons for needing more work before suspend:
561          * - Dirty buffers on devvp.
562          * - Secondary writes occurred after start of vnode sync loop
563          */
564         error = 0;
565         if (bo->bo_numoutput > 0 ||
566             bo->bo_dirty.bv_cnt > 0 ||
567             secondary_writes != 0 ||
568             mp->mnt_secondary_writes != 0 ||
569             secondary_accwrites != mp->mnt_secondary_accwrites)
570                 error = EAGAIN;
571         BO_UNLOCK(bo);
572         return (error);
573 }
574
575 void
576 softdep_get_depcounts(struct mount *mp,
577                       int *softdepactivep,
578                       int *softdepactiveaccp)
579 {
580         (void) mp;
581         *softdepactivep = 0;
582         *softdepactiveaccp = 0;
583 }
584
585 void
586 softdep_buf_append(bp, wkhd)
587         struct buf *bp;
588         struct workhead *wkhd;
589 {
590
591         panic("softdep_buf_appendwork called");
592 }
593
594 void
595 softdep_inode_append(ip, cred, wkhd)
596         struct inode *ip;
597         struct ucred *cred;
598         struct workhead *wkhd;
599 {
600
601         panic("softdep_inode_appendwork called");
602 }
603
604 void
605 softdep_freework(wkhd)
606         struct workhead *wkhd;
607 {
608
609         panic("softdep_freework called");
610 }
611
612 #else
613
614 FEATURE(softupdates, "FFS soft-updates support");
615
616 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
617     "soft updates stats");
618 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
619     "total dependencies allocated");
620 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
621     "high use dependencies allocated");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
623     "current dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
625     "current dependencies written");
626
627 unsigned long dep_current[D_LAST + 1];
628 unsigned long dep_highuse[D_LAST + 1];
629 unsigned long dep_total[D_LAST + 1];
630 unsigned long dep_write[D_LAST + 1];
631
632 #define SOFTDEP_TYPE(type, str, long)                                   \
633     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
634     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
635         &dep_total[D_ ## type], 0, "");                                 \
636     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
637         &dep_current[D_ ## type], 0, "");                               \
638     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
639         &dep_highuse[D_ ## type], 0, "");                               \
640     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
641         &dep_write[D_ ## type], 0, "");
642
643 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
644 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
645 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
646     "Block or frag allocated from cyl group map");
647 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
648 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
649 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
650 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
651 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
652 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
653 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
654 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
655 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
656 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
657 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
658 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
659 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
660 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
661 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
662 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
663 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
664 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
665 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
666 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
667 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
668 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
669 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
670 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
671
672 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
673
674 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
675 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
676 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
677
678 #define M_SOFTDEP_FLAGS (M_WAITOK)
679
680 /* 
681  * translate from workitem type to memory type
682  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
683  */
684 static struct malloc_type *memtype[] = {
685         NULL,
686         M_PAGEDEP,
687         M_INODEDEP,
688         M_BMSAFEMAP,
689         M_NEWBLK,
690         M_ALLOCDIRECT,
691         M_INDIRDEP,
692         M_ALLOCINDIR,
693         M_FREEFRAG,
694         M_FREEBLKS,
695         M_FREEFILE,
696         M_DIRADD,
697         M_MKDIR,
698         M_DIRREM,
699         M_NEWDIRBLK,
700         M_FREEWORK,
701         M_FREEDEP,
702         M_JADDREF,
703         M_JREMREF,
704         M_JMVREF,
705         M_JNEWBLK,
706         M_JFREEBLK,
707         M_JFREEFRAG,
708         M_JSEG,
709         M_JSEGDEP,
710         M_SBDEP,
711         M_JTRUNC,
712         M_JFSYNC,
713         M_SENTINEL
714 };
715
716 #define DtoM(type) (memtype[type])
717
718 /*
719  * Names of malloc types.
720  */
721 #define TYPENAME(type)  \
722         ((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
723         memtype[type]->ks_shortdesc : "???")
724 /*
725  * End system adaptation definitions.
726  */
727
728 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
729 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
730
731 /*
732  * Internal function prototypes.
733  */
734 static  void check_clear_deps(struct mount *);
735 static  void softdep_error(char *, int);
736 static  int softdep_process_worklist(struct mount *, int);
737 static  int softdep_waitidle(struct mount *, int);
738 static  void drain_output(struct vnode *);
739 static  struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
740 static  int check_inodedep_free(struct inodedep *);
741 static  void clear_remove(struct mount *);
742 static  void clear_inodedeps(struct mount *);
743 static  void unlinked_inodedep(struct mount *, struct inodedep *);
744 static  void clear_unlinked_inodedep(struct inodedep *);
745 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
746 static  int flush_pagedep_deps(struct vnode *, struct mount *,
747             struct diraddhd *);
748 static  int free_pagedep(struct pagedep *);
749 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
750 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
751 static  int flush_deplist(struct allocdirectlst *, int, int *);
752 static  int sync_cgs(struct mount *, int);
753 static  int handle_written_filepage(struct pagedep *, struct buf *, int);
754 static  int handle_written_sbdep(struct sbdep *, struct buf *);
755 static  void initiate_write_sbdep(struct sbdep *);
756 static  void diradd_inode_written(struct diradd *, struct inodedep *);
757 static  int handle_written_indirdep(struct indirdep *, struct buf *,
758             struct buf**, int);
759 static  int handle_written_inodeblock(struct inodedep *, struct buf *, int);
760 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
761             uint8_t *);
762 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
763 static  void handle_written_jaddref(struct jaddref *);
764 static  void handle_written_jremref(struct jremref *);
765 static  void handle_written_jseg(struct jseg *, struct buf *);
766 static  void handle_written_jnewblk(struct jnewblk *);
767 static  void handle_written_jblkdep(struct jblkdep *);
768 static  void handle_written_jfreefrag(struct jfreefrag *);
769 static  void complete_jseg(struct jseg *);
770 static  void complete_jsegs(struct jseg *);
771 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
772 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
773 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
774 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
775 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
776 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
777 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
778 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
779 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
780 static  inline void inoref_write(struct inoref *, struct jseg *,
781             struct jrefrec *);
782 static  void handle_allocdirect_partdone(struct allocdirect *,
783             struct workhead *);
784 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
785             struct workhead *);
786 static  void indirdep_complete(struct indirdep *);
787 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
788 static  void indirblk_insert(struct freework *);
789 static  void indirblk_remove(struct freework *);
790 static  void handle_allocindir_partdone(struct allocindir *);
791 static  void initiate_write_filepage(struct pagedep *, struct buf *);
792 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
793 static  void handle_written_mkdir(struct mkdir *, int);
794 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
795             uint8_t *);
796 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
797 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
798 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
799 static  void handle_workitem_freefile(struct freefile *);
800 static  int handle_workitem_remove(struct dirrem *, int);
801 static  struct dirrem *newdirrem(struct buf *, struct inode *,
802             struct inode *, int, struct dirrem **);
803 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
804             struct buf *);
805 static  void cancel_indirdep(struct indirdep *, struct buf *,
806             struct freeblks *);
807 static  void free_indirdep(struct indirdep *);
808 static  void free_diradd(struct diradd *, struct workhead *);
809 static  void merge_diradd(struct inodedep *, struct diradd *);
810 static  void complete_diradd(struct diradd *);
811 static  struct diradd *diradd_lookup(struct pagedep *, int);
812 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
813             struct jremref *);
814 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
815             struct jremref *);
816 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
817             struct jremref *, struct jremref *);
818 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
819             struct jremref *);
820 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
821             struct freeblks *, int);
822 static  int setup_trunc_indir(struct freeblks *, struct inode *,
823             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
824 static  void complete_trunc_indir(struct freework *);
825 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
826             int);
827 static  void complete_mkdir(struct mkdir *);
828 static  void free_newdirblk(struct newdirblk *);
829 static  void free_jremref(struct jremref *);
830 static  void free_jaddref(struct jaddref *);
831 static  void free_jsegdep(struct jsegdep *);
832 static  void free_jsegs(struct jblocks *);
833 static  void rele_jseg(struct jseg *);
834 static  void free_jseg(struct jseg *, struct jblocks *);
835 static  void free_jnewblk(struct jnewblk *);
836 static  void free_jblkdep(struct jblkdep *);
837 static  void free_jfreefrag(struct jfreefrag *);
838 static  void free_freedep(struct freedep *);
839 static  void journal_jremref(struct dirrem *, struct jremref *,
840             struct inodedep *);
841 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
842 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
843             struct workhead *);
844 static  void cancel_jfreefrag(struct jfreefrag *);
845 static  inline void setup_freedirect(struct freeblks *, struct inode *,
846             int, int);
847 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
848 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
849             ufs_lbn_t, int);
850 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
851 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
852 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
853 static  ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
854 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
855 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
856             int, int);
857 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
858 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
859 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
860 static  void newblk_freefrag(struct newblk*);
861 static  void free_newblk(struct newblk *);
862 static  void cancel_allocdirect(struct allocdirectlst *,
863             struct allocdirect *, struct freeblks *);
864 static  int check_inode_unwritten(struct inodedep *);
865 static  int free_inodedep(struct inodedep *);
866 static  void freework_freeblock(struct freework *, u_long);
867 static  void freework_enqueue(struct freework *);
868 static  int handle_workitem_freeblocks(struct freeblks *, int);
869 static  int handle_complete_freeblocks(struct freeblks *, int);
870 static  void handle_workitem_indirblk(struct freework *);
871 static  void handle_written_freework(struct freework *);
872 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
873 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
874             struct workhead *);
875 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
876             struct inodedep *, struct allocindir *, ufs_lbn_t);
877 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
878             ufs2_daddr_t, ufs_lbn_t);
879 static  void handle_workitem_freefrag(struct freefrag *);
880 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
881             ufs_lbn_t, u_long);
882 static  void allocdirect_merge(struct allocdirectlst *,
883             struct allocdirect *, struct allocdirect *);
884 static  struct freefrag *allocindir_merge(struct allocindir *,
885             struct allocindir *);
886 static  int bmsafemap_find(struct bmsafemap_hashhead *, int,
887             struct bmsafemap **);
888 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
889             int cg, struct bmsafemap *);
890 static  int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
891             struct newblk **);
892 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
893 static  int inodedep_find(struct inodedep_hashhead *, ino_t,
894             struct inodedep **);
895 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
896 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
897             int, struct pagedep **);
898 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
899             struct pagedep **);
900 static  void pause_timer(void *);
901 static  int request_cleanup(struct mount *, int);
902 static  int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
903 static  void schedule_cleanup(struct mount *);
904 static void softdep_ast_cleanup_proc(struct thread *);
905 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
906 static  int process_worklist_item(struct mount *, int, int);
907 static  void process_removes(struct vnode *);
908 static  void process_truncates(struct vnode *);
909 static  void jwork_move(struct workhead *, struct workhead *);
910 static  void jwork_insert(struct workhead *, struct jsegdep *);
911 static  void add_to_worklist(struct worklist *, int);
912 static  void wake_worklist(struct worklist *);
913 static  void wait_worklist(struct worklist *, char *);
914 static  void remove_from_worklist(struct worklist *);
915 static  void softdep_flush(void *);
916 static  void softdep_flushjournal(struct mount *);
917 static  int softdep_speedup(struct ufsmount *);
918 static  void worklist_speedup(struct mount *);
919 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
920 static  void journal_unmount(struct ufsmount *);
921 static  int journal_space(struct ufsmount *, int);
922 static  void journal_suspend(struct ufsmount *);
923 static  int journal_unsuspend(struct ufsmount *ump);
924 static  void softdep_prelink(struct vnode *, struct vnode *);
925 static  void add_to_journal(struct worklist *);
926 static  void remove_from_journal(struct worklist *);
927 static  bool softdep_excess_items(struct ufsmount *, int);
928 static  void softdep_process_journal(struct mount *, struct worklist *, int);
929 static  struct jremref *newjremref(struct dirrem *, struct inode *,
930             struct inode *ip, off_t, nlink_t);
931 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
932             uint16_t);
933 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
934             uint16_t);
935 static  inline struct jsegdep *inoref_jseg(struct inoref *);
936 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
937 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
938             ufs2_daddr_t, int);
939 static  void adjust_newfreework(struct freeblks *, int);
940 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
941 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
942 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
943 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
944             ufs2_daddr_t, long, ufs_lbn_t);
945 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
946             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
947 static  int jwait(struct worklist *, int);
948 static  struct inodedep *inodedep_lookup_ip(struct inode *);
949 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
950 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
951 static  void handle_jwork(struct workhead *);
952 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
953             struct mkdir **);
954 static  struct jblocks *jblocks_create(void);
955 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
956 static  void jblocks_free(struct jblocks *, struct mount *, int);
957 static  void jblocks_destroy(struct jblocks *);
958 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
959
960 /*
961  * Exported softdep operations.
962  */
963 static  void softdep_disk_io_initiation(struct buf *);
964 static  void softdep_disk_write_complete(struct buf *);
965 static  void softdep_deallocate_dependencies(struct buf *);
966 static  int softdep_count_dependencies(struct buf *bp, int);
967
968 /*
969  * Global lock over all of soft updates.
970  */
971 static struct mtx lk;
972 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
973
974 #define ACQUIRE_GBLLOCK(lk)     mtx_lock(lk)
975 #define FREE_GBLLOCK(lk)        mtx_unlock(lk)
976 #define GBLLOCK_OWNED(lk)       mtx_assert((lk), MA_OWNED)
977
978 /*
979  * Per-filesystem soft-updates locking.
980  */
981 #define LOCK_PTR(ump)           (&(ump)->um_softdep->sd_fslock)
982 #define TRY_ACQUIRE_LOCK(ump)   rw_try_wlock(&(ump)->um_softdep->sd_fslock)
983 #define ACQUIRE_LOCK(ump)       rw_wlock(&(ump)->um_softdep->sd_fslock)
984 #define FREE_LOCK(ump)          rw_wunlock(&(ump)->um_softdep->sd_fslock)
985 #define LOCK_OWNED(ump)         rw_assert(&(ump)->um_softdep->sd_fslock, \
986                                     RA_WLOCKED)
987
988 #define BUF_AREC(bp)            lockallowrecurse(&(bp)->b_lock)
989 #define BUF_NOREC(bp)           lockdisablerecurse(&(bp)->b_lock)
990
991 /*
992  * Worklist queue management.
993  * These routines require that the lock be held.
994  */
995 #ifndef /* NOT */ INVARIANTS
996 #define WORKLIST_INSERT(head, item) do {        \
997         (item)->wk_state |= ONWORKLIST;         \
998         LIST_INSERT_HEAD(head, item, wk_list);  \
999 } while (0)
1000 #define WORKLIST_REMOVE(item) do {              \
1001         (item)->wk_state &= ~ONWORKLIST;        \
1002         LIST_REMOVE(item, wk_list);             \
1003 } while (0)
1004 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1005 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1006
1007 #else /* INVARIANTS */
1008 static  void worklist_insert(struct workhead *, struct worklist *, int,
1009         const char *, int);
1010 static  void worklist_remove(struct worklist *, int, const char *, int);
1011
1012 #define WORKLIST_INSERT(head, item) \
1013         worklist_insert(head, item, 1, __func__, __LINE__)
1014 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1015         worklist_insert(head, item, 0, __func__, __LINE__)
1016 #define WORKLIST_REMOVE(item)\
1017         worklist_remove(item, 1, __func__, __LINE__)
1018 #define WORKLIST_REMOVE_UNLOCKED(item)\
1019         worklist_remove(item, 0, __func__, __LINE__)
1020
1021 static void
1022 worklist_insert(head, item, locked, func, line)
1023         struct workhead *head;
1024         struct worklist *item;
1025         int locked;
1026         const char *func;
1027         int line;
1028 {
1029
1030         if (locked)
1031                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1032         if (item->wk_state & ONWORKLIST)
1033                 panic("worklist_insert: %p %s(0x%X) already on list, "
1034                     "added in function %s at line %d",
1035                     item, TYPENAME(item->wk_type), item->wk_state,
1036                     item->wk_func, item->wk_line);
1037         item->wk_state |= ONWORKLIST;
1038         item->wk_func = func;
1039         item->wk_line = line;
1040         LIST_INSERT_HEAD(head, item, wk_list);
1041 }
1042
1043 static void
1044 worklist_remove(item, locked, func, line)
1045         struct worklist *item;
1046         int locked;
1047         const char *func;
1048         int line;
1049 {
1050
1051         if (locked)
1052                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1053         if ((item->wk_state & ONWORKLIST) == 0)
1054                 panic("worklist_remove: %p %s(0x%X) not on list, "
1055                     "removed in function %s at line %d",
1056                     item, TYPENAME(item->wk_type), item->wk_state,
1057                     item->wk_func, item->wk_line);
1058         item->wk_state &= ~ONWORKLIST;
1059         item->wk_func = func;
1060         item->wk_line = line;
1061         LIST_REMOVE(item, wk_list);
1062 }
1063 #endif /* INVARIANTS */
1064
1065 /*
1066  * Merge two jsegdeps keeping only the oldest one as newer references
1067  * can't be discarded until after older references.
1068  */
1069 static inline struct jsegdep *
1070 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1071 {
1072         struct jsegdep *swp;
1073
1074         if (two == NULL)
1075                 return (one);
1076
1077         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1078                 swp = one;
1079                 one = two;
1080                 two = swp;
1081         }
1082         WORKLIST_REMOVE(&two->jd_list);
1083         free_jsegdep(two);
1084
1085         return (one);
1086 }
1087
1088 /*
1089  * If two freedeps are compatible free one to reduce list size.
1090  */
1091 static inline struct freedep *
1092 freedep_merge(struct freedep *one, struct freedep *two)
1093 {
1094         if (two == NULL)
1095                 return (one);
1096
1097         if (one->fd_freework == two->fd_freework) {
1098                 WORKLIST_REMOVE(&two->fd_list);
1099                 free_freedep(two);
1100         }
1101         return (one);
1102 }
1103
1104 /*
1105  * Move journal work from one list to another.  Duplicate freedeps and
1106  * jsegdeps are coalesced to keep the lists as small as possible.
1107  */
1108 static void
1109 jwork_move(dst, src)
1110         struct workhead *dst;
1111         struct workhead *src;
1112 {
1113         struct freedep *freedep;
1114         struct jsegdep *jsegdep;
1115         struct worklist *wkn;
1116         struct worklist *wk;
1117
1118         KASSERT(dst != src,
1119             ("jwork_move: dst == src"));
1120         freedep = NULL;
1121         jsegdep = NULL;
1122         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1123                 if (wk->wk_type == D_JSEGDEP)
1124                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1125                 else if (wk->wk_type == D_FREEDEP)
1126                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1127         }
1128
1129         while ((wk = LIST_FIRST(src)) != NULL) {
1130                 WORKLIST_REMOVE(wk);
1131                 WORKLIST_INSERT(dst, wk);
1132                 if (wk->wk_type == D_JSEGDEP) {
1133                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1134                         continue;
1135                 }
1136                 if (wk->wk_type == D_FREEDEP)
1137                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1138         }
1139 }
1140
1141 static void
1142 jwork_insert(dst, jsegdep)
1143         struct workhead *dst;
1144         struct jsegdep *jsegdep;
1145 {
1146         struct jsegdep *jsegdepn;
1147         struct worklist *wk;
1148
1149         LIST_FOREACH(wk, dst, wk_list)
1150                 if (wk->wk_type == D_JSEGDEP)
1151                         break;
1152         if (wk == NULL) {
1153                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1154                 return;
1155         }
1156         jsegdepn = WK_JSEGDEP(wk);
1157         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1158                 WORKLIST_REMOVE(wk);
1159                 free_jsegdep(jsegdepn);
1160                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1161         } else
1162                 free_jsegdep(jsegdep);
1163 }
1164
1165 /*
1166  * Routines for tracking and managing workitems.
1167  */
1168 static  void workitem_free(struct worklist *, int);
1169 static  void workitem_alloc(struct worklist *, int, struct mount *);
1170 static  void workitem_reassign(struct worklist *, int);
1171
1172 #define WORKITEM_FREE(item, type) \
1173         workitem_free((struct worklist *)(item), (type))
1174 #define WORKITEM_REASSIGN(item, type) \
1175         workitem_reassign((struct worklist *)(item), (type))
1176
1177 static void
1178 workitem_free(item, type)
1179         struct worklist *item;
1180         int type;
1181 {
1182         struct ufsmount *ump;
1183
1184 #ifdef INVARIANTS
1185         if (item->wk_state & ONWORKLIST)
1186                 panic("workitem_free: %s(0x%X) still on list, "
1187                     "added in function %s at line %d",
1188                     TYPENAME(item->wk_type), item->wk_state,
1189                     item->wk_func, item->wk_line);
1190         if (item->wk_type != type && type != D_NEWBLK)
1191                 panic("workitem_free: type mismatch %s != %s",
1192                     TYPENAME(item->wk_type), TYPENAME(type));
1193 #endif
1194         if (item->wk_state & IOWAITING)
1195                 wakeup(item);
1196         ump = VFSTOUFS(item->wk_mp);
1197         LOCK_OWNED(ump);
1198         KASSERT(ump->softdep_deps > 0,
1199             ("workitem_free: %s: softdep_deps going negative",
1200             ump->um_fs->fs_fsmnt));
1201         if (--ump->softdep_deps == 0 && ump->softdep_req)
1202                 wakeup(&ump->softdep_deps);
1203         KASSERT(dep_current[item->wk_type] > 0,
1204             ("workitem_free: %s: dep_current[%s] going negative",
1205             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1206         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1207             ("workitem_free: %s: softdep_curdeps[%s] going negative",
1208             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1209         atomic_subtract_long(&dep_current[item->wk_type], 1);
1210         ump->softdep_curdeps[item->wk_type] -= 1;
1211 #ifdef INVARIANTS
1212         LIST_REMOVE(item, wk_all);
1213 #endif
1214         free(item, DtoM(type));
1215 }
1216
1217 static void
1218 workitem_alloc(item, type, mp)
1219         struct worklist *item;
1220         int type;
1221         struct mount *mp;
1222 {
1223         struct ufsmount *ump;
1224
1225         item->wk_type = type;
1226         item->wk_mp = mp;
1227         item->wk_state = 0;
1228
1229         ump = VFSTOUFS(mp);
1230         ACQUIRE_GBLLOCK(&lk);
1231         dep_current[type]++;
1232         if (dep_current[type] > dep_highuse[type])
1233                 dep_highuse[type] = dep_current[type];
1234         dep_total[type]++;
1235         FREE_GBLLOCK(&lk);
1236         ACQUIRE_LOCK(ump);
1237         ump->softdep_curdeps[type] += 1;
1238         ump->softdep_deps++;
1239         ump->softdep_accdeps++;
1240 #ifdef INVARIANTS
1241         LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1242 #endif
1243         FREE_LOCK(ump);
1244 }
1245
1246 static void
1247 workitem_reassign(item, newtype)
1248         struct worklist *item;
1249         int newtype;
1250 {
1251         struct ufsmount *ump;
1252
1253         ump = VFSTOUFS(item->wk_mp);
1254         LOCK_OWNED(ump);
1255         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1256             ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1257             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1258         ump->softdep_curdeps[item->wk_type] -= 1;
1259         ump->softdep_curdeps[newtype] += 1;
1260         KASSERT(dep_current[item->wk_type] > 0,
1261             ("workitem_reassign: %s: dep_current[%s] going negative",
1262             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1263         ACQUIRE_GBLLOCK(&lk);
1264         dep_current[newtype]++;
1265         dep_current[item->wk_type]--;
1266         if (dep_current[newtype] > dep_highuse[newtype])
1267                 dep_highuse[newtype] = dep_current[newtype];
1268         dep_total[newtype]++;
1269         FREE_GBLLOCK(&lk);
1270         item->wk_type = newtype;
1271 }
1272
1273 /*
1274  * Workitem queue management
1275  */
1276 static int max_softdeps;        /* maximum number of structs before slowdown */
1277 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1278 static int proc_waiting;        /* tracks whether we have a timeout posted */
1279 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1280 static struct callout softdep_callout;
1281 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1282 static int req_clear_remove;    /* syncer process flush some freeblks */
1283 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1284
1285 /*
1286  * runtime statistics
1287  */
1288 static int stat_flush_threads;  /* number of softdep flushing threads */
1289 static int stat_worklist_push;  /* number of worklist cleanups */
1290 static int stat_blk_limit_push; /* number of times block limit neared */
1291 static int stat_ino_limit_push; /* number of times inode limit neared */
1292 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1293 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1294 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1295 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1296 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1297 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1298 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1299 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1300 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1301 static int stat_journal_min;    /* Times hit journal min threshold */
1302 static int stat_journal_low;    /* Times hit journal low threshold */
1303 static int stat_journal_wait;   /* Times blocked in jwait(). */
1304 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1305 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1306 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1307 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1308 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1309 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1310 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1311 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1312 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1313 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1314
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1316     &max_softdeps, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1318     &tickdelay, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1320     &stat_flush_threads, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1322     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1324     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1326     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1328     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1330     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1332     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1334     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1336     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1338     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1340     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1342     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1344     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1363 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1364     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1365 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1366     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1367 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1368     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1369
1370 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1371     &softdep_flushcache, 0, "");
1372 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1373     &stat_emptyjblocks, 0, "");
1374
1375 SYSCTL_DECL(_vfs_ffs);
1376
1377 /* Whether to recompute the summary at mount time */
1378 static int compute_summary_at_mount = 0;
1379 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1380            &compute_summary_at_mount, 0, "Recompute summary at mount");
1381 static int print_threads = 0;
1382 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1383     &print_threads, 0, "Notify flusher thread start/stop");
1384
1385 /* List of all filesystems mounted with soft updates */
1386 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1387
1388 /*
1389  * This function cleans the worklist for a filesystem.
1390  * Each filesystem running with soft dependencies gets its own
1391  * thread to run in this function. The thread is started up in
1392  * softdep_mount and shutdown in softdep_unmount. They show up
1393  * as part of the kernel "bufdaemon" process whose process
1394  * entry is available in bufdaemonproc.
1395  */
1396 static int searchfailed;
1397 extern struct proc *bufdaemonproc;
1398 static void
1399 softdep_flush(addr)
1400         void *addr;
1401 {
1402         struct mount *mp;
1403         struct thread *td;
1404         struct ufsmount *ump;
1405
1406         td = curthread;
1407         td->td_pflags |= TDP_NORUNNINGBUF;
1408         mp = (struct mount *)addr;
1409         ump = VFSTOUFS(mp);
1410         atomic_add_int(&stat_flush_threads, 1);
1411         ACQUIRE_LOCK(ump);
1412         ump->softdep_flags &= ~FLUSH_STARTING;
1413         wakeup(&ump->softdep_flushtd);
1414         FREE_LOCK(ump);
1415         if (print_threads) {
1416                 if (stat_flush_threads == 1)
1417                         printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1418                             bufdaemonproc->p_pid);
1419                 printf("Start thread %s\n", td->td_name);
1420         }
1421         for (;;) {      
1422                 while (softdep_process_worklist(mp, 0) > 0 ||
1423                     (MOUNTEDSUJ(mp) &&
1424                     VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1425                         kthread_suspend_check();
1426                 ACQUIRE_LOCK(ump);
1427                 if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1428                         msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1429                             "sdflush", hz / 2);
1430                 ump->softdep_flags &= ~FLUSH_CLEANUP;
1431                 /*
1432                  * Check to see if we are done and need to exit.
1433                  */
1434                 if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1435                         FREE_LOCK(ump);
1436                         continue;
1437                 }
1438                 ump->softdep_flags &= ~FLUSH_EXIT;
1439                 FREE_LOCK(ump);
1440                 wakeup(&ump->softdep_flags);
1441                 if (print_threads)
1442                         printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1443                 atomic_subtract_int(&stat_flush_threads, 1);
1444                 kthread_exit();
1445                 panic("kthread_exit failed\n");
1446         }
1447 }
1448
1449 static void
1450 worklist_speedup(mp)
1451         struct mount *mp;
1452 {
1453         struct ufsmount *ump;
1454
1455         ump = VFSTOUFS(mp);
1456         LOCK_OWNED(ump);
1457         if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1458                 ump->softdep_flags |= FLUSH_CLEANUP;
1459         wakeup(&ump->softdep_flushtd);
1460 }
1461
1462 static void
1463 softdep_send_speedup(struct ufsmount *ump, size_t shortage, u_int flags)
1464 {
1465         struct buf *bp;
1466
1467         if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1468                 return;
1469
1470         bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1471         bp->b_iocmd = BIO_SPEEDUP;
1472         bp->b_ioflags = flags;
1473         bp->b_bcount = shortage;
1474         g_vfs_strategy(ump->um_bo, bp);
1475         bufwait(bp);
1476         free(bp, M_TRIM);
1477 }
1478
1479 static int
1480 softdep_speedup(ump)
1481         struct ufsmount *ump;
1482 {
1483         struct ufsmount *altump;
1484         struct mount_softdeps *sdp;
1485
1486         LOCK_OWNED(ump);
1487         worklist_speedup(ump->um_mountp);
1488         bd_speedup();
1489         /*
1490          * If we have global shortages, then we need other
1491          * filesystems to help with the cleanup. Here we wakeup a
1492          * flusher thread for a filesystem that is over its fair
1493          * share of resources.
1494          */
1495         if (req_clear_inodedeps || req_clear_remove) {
1496                 ACQUIRE_GBLLOCK(&lk);
1497                 TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1498                         if ((altump = sdp->sd_ump) == ump)
1499                                 continue;
1500                         if (((req_clear_inodedeps &&
1501                             altump->softdep_curdeps[D_INODEDEP] >
1502                             max_softdeps / stat_flush_threads) ||
1503                             (req_clear_remove &&
1504                             altump->softdep_curdeps[D_DIRREM] >
1505                             (max_softdeps / 2) / stat_flush_threads)) &&
1506                             TRY_ACQUIRE_LOCK(altump))
1507                                 break;
1508                 }
1509                 if (sdp == NULL) {
1510                         searchfailed++;
1511                         FREE_GBLLOCK(&lk);
1512                 } else {
1513                         /*
1514                          * Move to the end of the list so we pick a
1515                          * different one on out next try.
1516                          */
1517                         TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1518                         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1519                         FREE_GBLLOCK(&lk);
1520                         if ((altump->softdep_flags &
1521                             (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1522                                 altump->softdep_flags |= FLUSH_CLEANUP;
1523                         altump->um_softdep->sd_cleanups++;
1524                         wakeup(&altump->softdep_flushtd);
1525                         FREE_LOCK(altump);
1526                 }
1527         }
1528         return (speedup_syncer());
1529 }
1530
1531 /*
1532  * Add an item to the end of the work queue.
1533  * This routine requires that the lock be held.
1534  * This is the only routine that adds items to the list.
1535  * The following routine is the only one that removes items
1536  * and does so in order from first to last.
1537  */
1538
1539 #define WK_HEAD         0x0001  /* Add to HEAD. */
1540 #define WK_NODELAY      0x0002  /* Process immediately. */
1541
1542 static void
1543 add_to_worklist(wk, flags)
1544         struct worklist *wk;
1545         int flags;
1546 {
1547         struct ufsmount *ump;
1548
1549         ump = VFSTOUFS(wk->wk_mp);
1550         LOCK_OWNED(ump);
1551         if (wk->wk_state & ONWORKLIST)
1552                 panic("add_to_worklist: %s(0x%X) already on list",
1553                     TYPENAME(wk->wk_type), wk->wk_state);
1554         wk->wk_state |= ONWORKLIST;
1555         if (ump->softdep_on_worklist == 0) {
1556                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1557                 ump->softdep_worklist_tail = wk;
1558         } else if (flags & WK_HEAD) {
1559                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1560         } else {
1561                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1562                 ump->softdep_worklist_tail = wk;
1563         }
1564         ump->softdep_on_worklist += 1;
1565         if (flags & WK_NODELAY)
1566                 worklist_speedup(wk->wk_mp);
1567 }
1568
1569 /*
1570  * Remove the item to be processed. If we are removing the last
1571  * item on the list, we need to recalculate the tail pointer.
1572  */
1573 static void
1574 remove_from_worklist(wk)
1575         struct worklist *wk;
1576 {
1577         struct ufsmount *ump;
1578
1579         ump = VFSTOUFS(wk->wk_mp);
1580         if (ump->softdep_worklist_tail == wk)
1581                 ump->softdep_worklist_tail =
1582                     (struct worklist *)wk->wk_list.le_prev;
1583         WORKLIST_REMOVE(wk);
1584         ump->softdep_on_worklist -= 1;
1585 }
1586
1587 static void
1588 wake_worklist(wk)
1589         struct worklist *wk;
1590 {
1591         if (wk->wk_state & IOWAITING) {
1592                 wk->wk_state &= ~IOWAITING;
1593                 wakeup(wk);
1594         }
1595 }
1596
1597 static void
1598 wait_worklist(wk, wmesg)
1599         struct worklist *wk;
1600         char *wmesg;
1601 {
1602         struct ufsmount *ump;
1603
1604         ump = VFSTOUFS(wk->wk_mp);
1605         wk->wk_state |= IOWAITING;
1606         msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1607 }
1608
1609 /*
1610  * Process that runs once per second to handle items in the background queue.
1611  *
1612  * Note that we ensure that everything is done in the order in which they
1613  * appear in the queue. The code below depends on this property to ensure
1614  * that blocks of a file are freed before the inode itself is freed. This
1615  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1616  * until all the old ones have been purged from the dependency lists.
1617  */
1618 static int 
1619 softdep_process_worklist(mp, full)
1620         struct mount *mp;
1621         int full;
1622 {
1623         int cnt, matchcnt;
1624         struct ufsmount *ump;
1625         long starttime;
1626
1627         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1628         if (MOUNTEDSOFTDEP(mp) == 0)
1629                 return (0);
1630         matchcnt = 0;
1631         ump = VFSTOUFS(mp);
1632         ACQUIRE_LOCK(ump);
1633         starttime = time_second;
1634         softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1635         check_clear_deps(mp);
1636         while (ump->softdep_on_worklist > 0) {
1637                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1638                         break;
1639                 else
1640                         matchcnt += cnt;
1641                 check_clear_deps(mp);
1642                 /*
1643                  * We do not generally want to stop for buffer space, but if
1644                  * we are really being a buffer hog, we will stop and wait.
1645                  */
1646                 if (should_yield()) {
1647                         FREE_LOCK(ump);
1648                         kern_yield(PRI_USER);
1649                         bwillwrite();
1650                         ACQUIRE_LOCK(ump);
1651                 }
1652                 /*
1653                  * Never allow processing to run for more than one
1654                  * second. This gives the syncer thread the opportunity
1655                  * to pause if appropriate.
1656                  */
1657                 if (!full && starttime != time_second)
1658                         break;
1659         }
1660         if (full == 0)
1661                 journal_unsuspend(ump);
1662         FREE_LOCK(ump);
1663         return (matchcnt);
1664 }
1665
1666 /*
1667  * Process all removes associated with a vnode if we are running out of
1668  * journal space.  Any other process which attempts to flush these will
1669  * be unable as we have the vnodes locked.
1670  */
1671 static void
1672 process_removes(vp)
1673         struct vnode *vp;
1674 {
1675         struct inodedep *inodedep;
1676         struct dirrem *dirrem;
1677         struct ufsmount *ump;
1678         struct mount *mp;
1679         ino_t inum;
1680
1681         mp = vp->v_mount;
1682         ump = VFSTOUFS(mp);
1683         LOCK_OWNED(ump);
1684         inum = VTOI(vp)->i_number;
1685         for (;;) {
1686 top:
1687                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1688                         return;
1689                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1690                         /*
1691                          * If another thread is trying to lock this vnode
1692                          * it will fail but we must wait for it to do so
1693                          * before we can proceed.
1694                          */
1695                         if (dirrem->dm_state & INPROGRESS) {
1696                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1697                                 goto top;
1698                         }
1699                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1700                             (COMPLETE | ONWORKLIST))
1701                                 break;
1702                 }
1703                 if (dirrem == NULL)
1704                         return;
1705                 remove_from_worklist(&dirrem->dm_list);
1706                 FREE_LOCK(ump);
1707                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1708                         panic("process_removes: suspended filesystem");
1709                 handle_workitem_remove(dirrem, 0);
1710                 vn_finished_secondary_write(mp);
1711                 ACQUIRE_LOCK(ump);
1712         }
1713 }
1714
1715 /*
1716  * Process all truncations associated with a vnode if we are running out
1717  * of journal space.  This is called when the vnode lock is already held
1718  * and no other process can clear the truncation.  This function returns
1719  * a value greater than zero if it did any work.
1720  */
1721 static void
1722 process_truncates(vp)
1723         struct vnode *vp;
1724 {
1725         struct inodedep *inodedep;
1726         struct freeblks *freeblks;
1727         struct ufsmount *ump;
1728         struct mount *mp;
1729         ino_t inum;
1730         int cgwait;
1731
1732         mp = vp->v_mount;
1733         ump = VFSTOUFS(mp);
1734         LOCK_OWNED(ump);
1735         inum = VTOI(vp)->i_number;
1736         for (;;) {
1737                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1738                         return;
1739                 cgwait = 0;
1740                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1741                         /* Journal entries not yet written.  */
1742                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1743                                 jwait(&LIST_FIRST(
1744                                     &freeblks->fb_jblkdephd)->jb_list,
1745                                     MNT_WAIT);
1746                                 break;
1747                         }
1748                         /* Another thread is executing this item. */
1749                         if (freeblks->fb_state & INPROGRESS) {
1750                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1751                                 break;
1752                         }
1753                         /* Freeblks is waiting on a inode write. */
1754                         if ((freeblks->fb_state & COMPLETE) == 0) {
1755                                 FREE_LOCK(ump);
1756                                 ffs_update(vp, 1);
1757                                 ACQUIRE_LOCK(ump);
1758                                 break;
1759                         }
1760                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1761                             (ALLCOMPLETE | ONWORKLIST)) {
1762                                 remove_from_worklist(&freeblks->fb_list);
1763                                 freeblks->fb_state |= INPROGRESS;
1764                                 FREE_LOCK(ump);
1765                                 if (vn_start_secondary_write(NULL, &mp,
1766                                     V_NOWAIT))
1767                                         panic("process_truncates: "
1768                                             "suspended filesystem");
1769                                 handle_workitem_freeblocks(freeblks, 0);
1770                                 vn_finished_secondary_write(mp);
1771                                 ACQUIRE_LOCK(ump);
1772                                 break;
1773                         }
1774                         if (freeblks->fb_cgwait)
1775                                 cgwait++;
1776                 }
1777                 if (cgwait) {
1778                         FREE_LOCK(ump);
1779                         sync_cgs(mp, MNT_WAIT);
1780                         ffs_sync_snap(mp, MNT_WAIT);
1781                         ACQUIRE_LOCK(ump);
1782                         continue;
1783                 }
1784                 if (freeblks == NULL)
1785                         break;
1786         }
1787         return;
1788 }
1789
1790 /*
1791  * Process one item on the worklist.
1792  */
1793 static int
1794 process_worklist_item(mp, target, flags)
1795         struct mount *mp;
1796         int target;
1797         int flags;
1798 {
1799         struct worklist sentinel;
1800         struct worklist *wk;
1801         struct ufsmount *ump;
1802         int matchcnt;
1803         int error;
1804
1805         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1806         /*
1807          * If we are being called because of a process doing a
1808          * copy-on-write, then it is not safe to write as we may
1809          * recurse into the copy-on-write routine.
1810          */
1811         if (curthread->td_pflags & TDP_COWINPROGRESS)
1812                 return (-1);
1813         PHOLD(curproc); /* Don't let the stack go away. */
1814         ump = VFSTOUFS(mp);
1815         LOCK_OWNED(ump);
1816         matchcnt = 0;
1817         sentinel.wk_mp = NULL;
1818         sentinel.wk_type = D_SENTINEL;
1819         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1820         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1821             wk = LIST_NEXT(&sentinel, wk_list)) {
1822                 if (wk->wk_type == D_SENTINEL) {
1823                         LIST_REMOVE(&sentinel, wk_list);
1824                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1825                         continue;
1826                 }
1827                 if (wk->wk_state & INPROGRESS)
1828                         panic("process_worklist_item: %p already in progress.",
1829                             wk);
1830                 wk->wk_state |= INPROGRESS;
1831                 remove_from_worklist(wk);
1832                 FREE_LOCK(ump);
1833                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1834                         panic("process_worklist_item: suspended filesystem");
1835                 switch (wk->wk_type) {
1836                 case D_DIRREM:
1837                         /* removal of a directory entry */
1838                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1839                         break;
1840
1841                 case D_FREEBLKS:
1842                         /* releasing blocks and/or fragments from a file */
1843                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1844                             flags);
1845                         break;
1846
1847                 case D_FREEFRAG:
1848                         /* releasing a fragment when replaced as a file grows */
1849                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1850                         error = 0;
1851                         break;
1852
1853                 case D_FREEFILE:
1854                         /* releasing an inode when its link count drops to 0 */
1855                         handle_workitem_freefile(WK_FREEFILE(wk));
1856                         error = 0;
1857                         break;
1858
1859                 default:
1860                         panic("%s_process_worklist: Unknown type %s",
1861                             "softdep", TYPENAME(wk->wk_type));
1862                         /* NOTREACHED */
1863                 }
1864                 vn_finished_secondary_write(mp);
1865                 ACQUIRE_LOCK(ump);
1866                 if (error == 0) {
1867                         if (++matchcnt == target)
1868                                 break;
1869                         continue;
1870                 }
1871                 /*
1872                  * We have to retry the worklist item later.  Wake up any
1873                  * waiters who may be able to complete it immediately and
1874                  * add the item back to the head so we don't try to execute
1875                  * it again.
1876                  */
1877                 wk->wk_state &= ~INPROGRESS;
1878                 wake_worklist(wk);
1879                 add_to_worklist(wk, WK_HEAD);
1880         }
1881         /* Sentinal could've become the tail from remove_from_worklist. */
1882         if (ump->softdep_worklist_tail == &sentinel)
1883                 ump->softdep_worklist_tail =
1884                     (struct worklist *)sentinel.wk_list.le_prev;
1885         LIST_REMOVE(&sentinel, wk_list);
1886         PRELE(curproc);
1887         return (matchcnt);
1888 }
1889
1890 /*
1891  * Move dependencies from one buffer to another.
1892  */
1893 int
1894 softdep_move_dependencies(oldbp, newbp)
1895         struct buf *oldbp;
1896         struct buf *newbp;
1897 {
1898         struct worklist *wk, *wktail;
1899         struct ufsmount *ump;
1900         int dirty;
1901
1902         if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1903                 return (0);
1904         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1905             ("softdep_move_dependencies called on non-softdep filesystem"));
1906         dirty = 0;
1907         wktail = NULL;
1908         ump = VFSTOUFS(wk->wk_mp);
1909         ACQUIRE_LOCK(ump);
1910         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1911                 LIST_REMOVE(wk, wk_list);
1912                 if (wk->wk_type == D_BMSAFEMAP &&
1913                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1914                         dirty = 1;
1915                 if (wktail == NULL)
1916                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1917                 else
1918                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1919                 wktail = wk;
1920         }
1921         FREE_LOCK(ump);
1922
1923         return (dirty);
1924 }
1925
1926 /*
1927  * Purge the work list of all items associated with a particular mount point.
1928  */
1929 int
1930 softdep_flushworklist(oldmnt, countp, td)
1931         struct mount *oldmnt;
1932         int *countp;
1933         struct thread *td;
1934 {
1935         struct vnode *devvp;
1936         struct ufsmount *ump;
1937         int count, error;
1938
1939         /*
1940          * Alternately flush the block device associated with the mount
1941          * point and process any dependencies that the flushing
1942          * creates. We continue until no more worklist dependencies
1943          * are found.
1944          */
1945         *countp = 0;
1946         error = 0;
1947         ump = VFSTOUFS(oldmnt);
1948         devvp = ump->um_devvp;
1949         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1950                 *countp += count;
1951                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1952                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1953                 VOP_UNLOCK(devvp);
1954                 if (error != 0)
1955                         break;
1956         }
1957         return (error);
1958 }
1959
1960 #define SU_WAITIDLE_RETRIES     20
1961 static int
1962 softdep_waitidle(struct mount *mp, int flags __unused)
1963 {
1964         struct ufsmount *ump;
1965         struct vnode *devvp;
1966         struct thread *td;
1967         int error, i;
1968
1969         ump = VFSTOUFS(mp);
1970         devvp = ump->um_devvp;
1971         td = curthread;
1972         error = 0;
1973         ACQUIRE_LOCK(ump);
1974         for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1975                 ump->softdep_req = 1;
1976                 KASSERT((flags & FORCECLOSE) == 0 ||
1977                     ump->softdep_on_worklist == 0,
1978                     ("softdep_waitidle: work added after flush"));
1979                 msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1980                     "softdeps", 10 * hz);
1981                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1982                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1983                 VOP_UNLOCK(devvp);
1984                 ACQUIRE_LOCK(ump);
1985                 if (error != 0)
1986                         break;
1987         }
1988         ump->softdep_req = 0;
1989         if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1990                 error = EBUSY;
1991                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1992                     mp);
1993         }
1994         FREE_LOCK(ump);
1995         return (error);
1996 }
1997
1998 /*
1999  * Flush all vnodes and worklist items associated with a specified mount point.
2000  */
2001 int
2002 softdep_flushfiles(oldmnt, flags, td)
2003         struct mount *oldmnt;
2004         int flags;
2005         struct thread *td;
2006 {
2007 #ifdef QUOTA
2008         struct ufsmount *ump;
2009         int i;
2010 #endif
2011         int error, early, depcount, loopcnt, retry_flush_count, retry;
2012         int morework;
2013
2014         KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2015             ("softdep_flushfiles called on non-softdep filesystem"));
2016         loopcnt = 10;
2017         retry_flush_count = 3;
2018 retry_flush:
2019         error = 0;
2020
2021         /*
2022          * Alternately flush the vnodes associated with the mount
2023          * point and process any dependencies that the flushing
2024          * creates. In theory, this loop can happen at most twice,
2025          * but we give it a few extra just to be sure.
2026          */
2027         for (; loopcnt > 0; loopcnt--) {
2028                 /*
2029                  * Do another flush in case any vnodes were brought in
2030                  * as part of the cleanup operations.
2031                  */
2032                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2033                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2034                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2035                         break;
2036                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2037                     depcount == 0)
2038                         break;
2039         }
2040         /*
2041          * If we are unmounting then it is an error to fail. If we
2042          * are simply trying to downgrade to read-only, then filesystem
2043          * activity can keep us busy forever, so we just fail with EBUSY.
2044          */
2045         if (loopcnt == 0) {
2046                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2047                         panic("softdep_flushfiles: looping");
2048                 error = EBUSY;
2049         }
2050         if (!error)
2051                 error = softdep_waitidle(oldmnt, flags);
2052         if (!error) {
2053                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2054                         retry = 0;
2055                         MNT_ILOCK(oldmnt);
2056                         morework = oldmnt->mnt_nvnodelistsize > 0;
2057 #ifdef QUOTA
2058                         ump = VFSTOUFS(oldmnt);
2059                         UFS_LOCK(ump);
2060                         for (i = 0; i < MAXQUOTAS; i++) {
2061                                 if (ump->um_quotas[i] != NULLVP)
2062                                         morework = 1;
2063                         }
2064                         UFS_UNLOCK(ump);
2065 #endif
2066                         if (morework) {
2067                                 if (--retry_flush_count > 0) {
2068                                         retry = 1;
2069                                         loopcnt = 3;
2070                                 } else
2071                                         error = EBUSY;
2072                         }
2073                         MNT_IUNLOCK(oldmnt);
2074                         if (retry)
2075                                 goto retry_flush;
2076                 }
2077         }
2078         return (error);
2079 }
2080
2081 /*
2082  * Structure hashing.
2083  * 
2084  * There are four types of structures that can be looked up:
2085  *      1) pagedep structures identified by mount point, inode number,
2086  *         and logical block.
2087  *      2) inodedep structures identified by mount point and inode number.
2088  *      3) newblk structures identified by mount point and
2089  *         physical block number.
2090  *      4) bmsafemap structures identified by mount point and
2091  *         cylinder group number.
2092  *
2093  * The "pagedep" and "inodedep" dependency structures are hashed
2094  * separately from the file blocks and inodes to which they correspond.
2095  * This separation helps when the in-memory copy of an inode or
2096  * file block must be replaced. It also obviates the need to access
2097  * an inode or file page when simply updating (or de-allocating)
2098  * dependency structures. Lookup of newblk structures is needed to
2099  * find newly allocated blocks when trying to associate them with
2100  * their allocdirect or allocindir structure.
2101  *
2102  * The lookup routines optionally create and hash a new instance when
2103  * an existing entry is not found. The bmsafemap lookup routine always
2104  * allocates a new structure if an existing one is not found.
2105  */
2106 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2107
2108 /*
2109  * Structures and routines associated with pagedep caching.
2110  */
2111 #define PAGEDEP_HASH(ump, inum, lbn) \
2112         (&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2113
2114 static int
2115 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2116         struct pagedep_hashhead *pagedephd;
2117         ino_t ino;
2118         ufs_lbn_t lbn;
2119         struct pagedep **pagedeppp;
2120 {
2121         struct pagedep *pagedep;
2122
2123         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2124                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2125                         *pagedeppp = pagedep;
2126                         return (1);
2127                 }
2128         }
2129         *pagedeppp = NULL;
2130         return (0);
2131 }
2132 /*
2133  * Look up a pagedep. Return 1 if found, 0 otherwise.
2134  * If not found, allocate if DEPALLOC flag is passed.
2135  * Found or allocated entry is returned in pagedeppp.
2136  */
2137 static int
2138 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2139         struct mount *mp;
2140         struct buf *bp;
2141         ino_t ino;
2142         ufs_lbn_t lbn;
2143         int flags;
2144         struct pagedep **pagedeppp;
2145 {
2146         struct pagedep *pagedep;
2147         struct pagedep_hashhead *pagedephd;
2148         struct worklist *wk;
2149         struct ufsmount *ump;
2150         int ret;
2151         int i;
2152
2153         ump = VFSTOUFS(mp);
2154         LOCK_OWNED(ump);
2155         if (bp) {
2156                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2157                         if (wk->wk_type == D_PAGEDEP) {
2158                                 *pagedeppp = WK_PAGEDEP(wk);
2159                                 return (1);
2160                         }
2161                 }
2162         }
2163         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2164         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2165         if (ret) {
2166                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2167                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2168                 return (1);
2169         }
2170         if ((flags & DEPALLOC) == 0)
2171                 return (0);
2172         FREE_LOCK(ump);
2173         pagedep = malloc(sizeof(struct pagedep),
2174             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2175         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2176         ACQUIRE_LOCK(ump);
2177         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2178         if (*pagedeppp) {
2179                 /*
2180                  * This should never happen since we only create pagedeps
2181                  * with the vnode lock held.  Could be an assert.
2182                  */
2183                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2184                 return (ret);
2185         }
2186         pagedep->pd_ino = ino;
2187         pagedep->pd_lbn = lbn;
2188         LIST_INIT(&pagedep->pd_dirremhd);
2189         LIST_INIT(&pagedep->pd_pendinghd);
2190         for (i = 0; i < DAHASHSZ; i++)
2191                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2192         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2193         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2194         *pagedeppp = pagedep;
2195         return (0);
2196 }
2197
2198 /*
2199  * Structures and routines associated with inodedep caching.
2200  */
2201 #define INODEDEP_HASH(ump, inum) \
2202       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2203
2204 static int
2205 inodedep_find(inodedephd, inum, inodedeppp)
2206         struct inodedep_hashhead *inodedephd;
2207         ino_t inum;
2208         struct inodedep **inodedeppp;
2209 {
2210         struct inodedep *inodedep;
2211
2212         LIST_FOREACH(inodedep, inodedephd, id_hash)
2213                 if (inum == inodedep->id_ino)
2214                         break;
2215         if (inodedep) {
2216                 *inodedeppp = inodedep;
2217                 return (1);
2218         }
2219         *inodedeppp = NULL;
2220
2221         return (0);
2222 }
2223 /*
2224  * Look up an inodedep. Return 1 if found, 0 if not found.
2225  * If not found, allocate if DEPALLOC flag is passed.
2226  * Found or allocated entry is returned in inodedeppp.
2227  */
2228 static int
2229 inodedep_lookup(mp, inum, flags, inodedeppp)
2230         struct mount *mp;
2231         ino_t inum;
2232         int flags;
2233         struct inodedep **inodedeppp;
2234 {
2235         struct inodedep *inodedep;
2236         struct inodedep_hashhead *inodedephd;
2237         struct ufsmount *ump;
2238         struct fs *fs;
2239
2240         ump = VFSTOUFS(mp);
2241         LOCK_OWNED(ump);
2242         fs = ump->um_fs;
2243         inodedephd = INODEDEP_HASH(ump, inum);
2244
2245         if (inodedep_find(inodedephd, inum, inodedeppp))
2246                 return (1);
2247         if ((flags & DEPALLOC) == 0)
2248                 return (0);
2249         /*
2250          * If the system is over its limit and our filesystem is
2251          * responsible for more than our share of that usage and
2252          * we are not in a rush, request some inodedep cleanup.
2253          */
2254         if (softdep_excess_items(ump, D_INODEDEP))
2255                 schedule_cleanup(mp);
2256         else
2257                 FREE_LOCK(ump);
2258         inodedep = malloc(sizeof(struct inodedep),
2259                 M_INODEDEP, M_SOFTDEP_FLAGS);
2260         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2261         ACQUIRE_LOCK(ump);
2262         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2263                 WORKITEM_FREE(inodedep, D_INODEDEP);
2264                 return (1);
2265         }
2266         inodedep->id_fs = fs;
2267         inodedep->id_ino = inum;
2268         inodedep->id_state = ALLCOMPLETE;
2269         inodedep->id_nlinkdelta = 0;
2270         inodedep->id_savedino1 = NULL;
2271         inodedep->id_savedsize = -1;
2272         inodedep->id_savedextsize = -1;
2273         inodedep->id_savednlink = -1;
2274         inodedep->id_bmsafemap = NULL;
2275         inodedep->id_mkdiradd = NULL;
2276         LIST_INIT(&inodedep->id_dirremhd);
2277         LIST_INIT(&inodedep->id_pendinghd);
2278         LIST_INIT(&inodedep->id_inowait);
2279         LIST_INIT(&inodedep->id_bufwait);
2280         TAILQ_INIT(&inodedep->id_inoreflst);
2281         TAILQ_INIT(&inodedep->id_inoupdt);
2282         TAILQ_INIT(&inodedep->id_newinoupdt);
2283         TAILQ_INIT(&inodedep->id_extupdt);
2284         TAILQ_INIT(&inodedep->id_newextupdt);
2285         TAILQ_INIT(&inodedep->id_freeblklst);
2286         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2287         *inodedeppp = inodedep;
2288         return (0);
2289 }
2290
2291 /*
2292  * Structures and routines associated with newblk caching.
2293  */
2294 #define NEWBLK_HASH(ump, inum) \
2295         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2296
2297 static int
2298 newblk_find(newblkhd, newblkno, flags, newblkpp)
2299         struct newblk_hashhead *newblkhd;
2300         ufs2_daddr_t newblkno;
2301         int flags;
2302         struct newblk **newblkpp;
2303 {
2304         struct newblk *newblk;
2305
2306         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2307                 if (newblkno != newblk->nb_newblkno)
2308                         continue;
2309                 /*
2310                  * If we're creating a new dependency don't match those that
2311                  * have already been converted to allocdirects.  This is for
2312                  * a frag extend.
2313                  */
2314                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2315                         continue;
2316                 break;
2317         }
2318         if (newblk) {
2319                 *newblkpp = newblk;
2320                 return (1);
2321         }
2322         *newblkpp = NULL;
2323         return (0);
2324 }
2325
2326 /*
2327  * Look up a newblk. Return 1 if found, 0 if not found.
2328  * If not found, allocate if DEPALLOC flag is passed.
2329  * Found or allocated entry is returned in newblkpp.
2330  */
2331 static int
2332 newblk_lookup(mp, newblkno, flags, newblkpp)
2333         struct mount *mp;
2334         ufs2_daddr_t newblkno;
2335         int flags;
2336         struct newblk **newblkpp;
2337 {
2338         struct newblk *newblk;
2339         struct newblk_hashhead *newblkhd;
2340         struct ufsmount *ump;
2341
2342         ump = VFSTOUFS(mp);
2343         LOCK_OWNED(ump);
2344         newblkhd = NEWBLK_HASH(ump, newblkno);
2345         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2346                 return (1);
2347         if ((flags & DEPALLOC) == 0)
2348                 return (0);
2349         if (softdep_excess_items(ump, D_NEWBLK) ||
2350             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2351             softdep_excess_items(ump, D_ALLOCINDIR))
2352                 schedule_cleanup(mp);
2353         else
2354                 FREE_LOCK(ump);
2355         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2356             M_SOFTDEP_FLAGS | M_ZERO);
2357         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2358         ACQUIRE_LOCK(ump);
2359         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2360                 WORKITEM_FREE(newblk, D_NEWBLK);
2361                 return (1);
2362         }
2363         newblk->nb_freefrag = NULL;
2364         LIST_INIT(&newblk->nb_indirdeps);
2365         LIST_INIT(&newblk->nb_newdirblk);
2366         LIST_INIT(&newblk->nb_jwork);
2367         newblk->nb_state = ATTACHED;
2368         newblk->nb_newblkno = newblkno;
2369         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2370         *newblkpp = newblk;
2371         return (0);
2372 }
2373
2374 /*
2375  * Structures and routines associated with freed indirect block caching.
2376  */
2377 #define INDIR_HASH(ump, blkno) \
2378         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2379
2380 /*
2381  * Lookup an indirect block in the indir hash table.  The freework is
2382  * removed and potentially freed.  The caller must do a blocking journal
2383  * write before writing to the blkno.
2384  */
2385 static int
2386 indirblk_lookup(mp, blkno)
2387         struct mount *mp;
2388         ufs2_daddr_t blkno;
2389 {
2390         struct freework *freework;
2391         struct indir_hashhead *wkhd;
2392         struct ufsmount *ump;
2393
2394         ump = VFSTOUFS(mp);
2395         wkhd = INDIR_HASH(ump, blkno);
2396         TAILQ_FOREACH(freework, wkhd, fw_next) {
2397                 if (freework->fw_blkno != blkno)
2398                         continue;
2399                 indirblk_remove(freework);
2400                 return (1);
2401         }
2402         return (0);
2403 }
2404
2405 /*
2406  * Insert an indirect block represented by freework into the indirblk
2407  * hash table so that it may prevent the block from being re-used prior
2408  * to the journal being written.
2409  */
2410 static void
2411 indirblk_insert(freework)
2412         struct freework *freework;
2413 {
2414         struct jblocks *jblocks;
2415         struct jseg *jseg;
2416         struct ufsmount *ump;
2417
2418         ump = VFSTOUFS(freework->fw_list.wk_mp);
2419         jblocks = ump->softdep_jblocks;
2420         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2421         if (jseg == NULL)
2422                 return;
2423         
2424         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2425         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2426             fw_next);
2427         freework->fw_state &= ~DEPCOMPLETE;
2428 }
2429
2430 static void
2431 indirblk_remove(freework)
2432         struct freework *freework;
2433 {
2434         struct ufsmount *ump;
2435
2436         ump = VFSTOUFS(freework->fw_list.wk_mp);
2437         LIST_REMOVE(freework, fw_segs);
2438         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2439         freework->fw_state |= DEPCOMPLETE;
2440         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2441                 WORKITEM_FREE(freework, D_FREEWORK);
2442 }
2443
2444 /*
2445  * Executed during filesystem system initialization before
2446  * mounting any filesystems.
2447  */
2448 void 
2449 softdep_initialize()
2450 {
2451
2452         TAILQ_INIT(&softdepmounts);
2453 #ifdef __LP64__
2454         max_softdeps = desiredvnodes * 4;
2455 #else
2456         max_softdeps = desiredvnodes * 2;
2457 #endif
2458
2459         /* initialise bioops hack */
2460         bioops.io_start = softdep_disk_io_initiation;
2461         bioops.io_complete = softdep_disk_write_complete;
2462         bioops.io_deallocate = softdep_deallocate_dependencies;
2463         bioops.io_countdeps = softdep_count_dependencies;
2464         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2465
2466         /* Initialize the callout with an mtx. */
2467         callout_init_mtx(&softdep_callout, &lk, 0);
2468 }
2469
2470 /*
2471  * Executed after all filesystems have been unmounted during
2472  * filesystem module unload.
2473  */
2474 void
2475 softdep_uninitialize()
2476 {
2477
2478         /* clear bioops hack */
2479         bioops.io_start = NULL;
2480         bioops.io_complete = NULL;
2481         bioops.io_deallocate = NULL;
2482         bioops.io_countdeps = NULL;
2483         softdep_ast_cleanup = NULL;
2484
2485         callout_drain(&softdep_callout);
2486 }
2487
2488 /*
2489  * Called at mount time to notify the dependency code that a
2490  * filesystem wishes to use it.
2491  */
2492 int
2493 softdep_mount(devvp, mp, fs, cred)
2494         struct vnode *devvp;
2495         struct mount *mp;
2496         struct fs *fs;
2497         struct ucred *cred;
2498 {
2499         struct csum_total cstotal;
2500         struct mount_softdeps *sdp;
2501         struct ufsmount *ump;
2502         struct cg *cgp;
2503         struct buf *bp;
2504         u_int cyl, i;
2505         int error;
2506
2507         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2508             M_WAITOK | M_ZERO);
2509         MNT_ILOCK(mp);
2510         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2511         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2512                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2513                         MNTK_SOFTDEP | MNTK_NOASYNC;
2514         }
2515         ump = VFSTOUFS(mp);
2516         ump->um_softdep = sdp;
2517         MNT_IUNLOCK(mp);
2518         rw_init(LOCK_PTR(ump), "per-fs softdep");
2519         sdp->sd_ump = ump;
2520         LIST_INIT(&ump->softdep_workitem_pending);
2521         LIST_INIT(&ump->softdep_journal_pending);
2522         TAILQ_INIT(&ump->softdep_unlinked);
2523         LIST_INIT(&ump->softdep_dirtycg);
2524         ump->softdep_worklist_tail = NULL;
2525         ump->softdep_on_worklist = 0;
2526         ump->softdep_deps = 0;
2527         LIST_INIT(&ump->softdep_mkdirlisthd);
2528         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2529             &ump->pagedep_hash_size);
2530         ump->pagedep_nextclean = 0;
2531         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2532             &ump->inodedep_hash_size);
2533         ump->inodedep_nextclean = 0;
2534         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2535             &ump->newblk_hash_size);
2536         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2537             &ump->bmsafemap_hash_size);
2538         i = 1 << (ffs(desiredvnodes / 10) - 1);
2539         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2540             M_FREEWORK, M_WAITOK);
2541         ump->indir_hash_size = i - 1;
2542         for (i = 0; i <= ump->indir_hash_size; i++)
2543                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2544 #ifdef INVARIANTS
2545         for (i = 0; i <= D_LAST; i++)
2546                 LIST_INIT(&ump->softdep_alldeps[i]);
2547 #endif
2548         ACQUIRE_GBLLOCK(&lk);
2549         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2550         FREE_GBLLOCK(&lk);
2551         if ((fs->fs_flags & FS_SUJ) &&
2552             (error = journal_mount(mp, fs, cred)) != 0) {
2553                 printf("Failed to start journal: %d\n", error);
2554                 softdep_unmount(mp);
2555                 return (error);
2556         }
2557         /*
2558          * Start our flushing thread in the bufdaemon process.
2559          */
2560         ACQUIRE_LOCK(ump);
2561         ump->softdep_flags |= FLUSH_STARTING;
2562         FREE_LOCK(ump);
2563         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2564             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2565             mp->mnt_stat.f_mntonname);
2566         ACQUIRE_LOCK(ump);
2567         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2568                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2569                     hz / 2);
2570         }
2571         FREE_LOCK(ump);
2572         /*
2573          * When doing soft updates, the counters in the
2574          * superblock may have gotten out of sync. Recomputation
2575          * can take a long time and can be deferred for background
2576          * fsck.  However, the old behavior of scanning the cylinder
2577          * groups and recalculating them at mount time is available
2578          * by setting vfs.ffs.compute_summary_at_mount to one.
2579          */
2580         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2581                 return (0);
2582         bzero(&cstotal, sizeof cstotal);
2583         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2584                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2585                     fs->fs_cgsize, cred, &bp)) != 0) {
2586                         brelse(bp);
2587                         softdep_unmount(mp);
2588                         return (error);
2589                 }
2590                 cgp = (struct cg *)bp->b_data;
2591                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2592                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2593                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2594                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2595                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2596                 brelse(bp);
2597         }
2598 #ifdef INVARIANTS
2599         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2600                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2601 #endif
2602         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2603         return (0);
2604 }
2605
2606 void
2607 softdep_unmount(mp)
2608         struct mount *mp;
2609 {
2610         struct ufsmount *ump;
2611 #ifdef INVARIANTS
2612         int i;
2613 #endif
2614
2615         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2616             ("softdep_unmount called on non-softdep filesystem"));
2617         ump = VFSTOUFS(mp);
2618         MNT_ILOCK(mp);
2619         mp->mnt_flag &= ~MNT_SOFTDEP;
2620         if (MOUNTEDSUJ(mp) == 0) {
2621                 MNT_IUNLOCK(mp);
2622         } else {
2623                 mp->mnt_flag &= ~MNT_SUJ;
2624                 MNT_IUNLOCK(mp);
2625                 journal_unmount(ump);
2626         }
2627         /*
2628          * Shut down our flushing thread. Check for NULL is if
2629          * softdep_mount errors out before the thread has been created.
2630          */
2631         if (ump->softdep_flushtd != NULL) {
2632                 ACQUIRE_LOCK(ump);
2633                 ump->softdep_flags |= FLUSH_EXIT;
2634                 wakeup(&ump->softdep_flushtd);
2635                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2636                     "sdwait", 0);
2637                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2638                     ("Thread shutdown failed"));
2639         }
2640         /*
2641          * Free up our resources.
2642          */
2643         ACQUIRE_GBLLOCK(&lk);
2644         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2645         FREE_GBLLOCK(&lk);
2646         rw_destroy(LOCK_PTR(ump));
2647         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2648         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2649         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2650         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2651             ump->bmsafemap_hash_size);
2652         free(ump->indir_hashtbl, M_FREEWORK);
2653 #ifdef INVARIANTS
2654         for (i = 0; i <= D_LAST; i++) {
2655                 KASSERT(ump->softdep_curdeps[i] == 0,
2656                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2657                     TYPENAME(i), ump->softdep_curdeps[i]));
2658                 KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2659                     ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2660                     TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2661         }
2662 #endif
2663         free(ump->um_softdep, M_MOUNTDATA);
2664 }
2665
2666 static struct jblocks *
2667 jblocks_create(void)
2668 {
2669         struct jblocks *jblocks;
2670
2671         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2672         TAILQ_INIT(&jblocks->jb_segs);
2673         jblocks->jb_avail = 10;
2674         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2675             M_JBLOCKS, M_WAITOK | M_ZERO);
2676
2677         return (jblocks);
2678 }
2679
2680 static ufs2_daddr_t
2681 jblocks_alloc(jblocks, bytes, actual)
2682         struct jblocks *jblocks;
2683         int bytes;
2684         int *actual;
2685 {
2686         ufs2_daddr_t daddr;
2687         struct jextent *jext;
2688         int freecnt;
2689         int blocks;
2690
2691         blocks = bytes / DEV_BSIZE;
2692         jext = &jblocks->jb_extent[jblocks->jb_head];
2693         freecnt = jext->je_blocks - jblocks->jb_off;
2694         if (freecnt == 0) {
2695                 jblocks->jb_off = 0;
2696                 if (++jblocks->jb_head > jblocks->jb_used)
2697                         jblocks->jb_head = 0;
2698                 jext = &jblocks->jb_extent[jblocks->jb_head];
2699                 freecnt = jext->je_blocks;
2700         }
2701         if (freecnt > blocks)
2702                 freecnt = blocks;
2703         *actual = freecnt * DEV_BSIZE;
2704         daddr = jext->je_daddr + jblocks->jb_off;
2705         jblocks->jb_off += freecnt;
2706         jblocks->jb_free -= freecnt;
2707
2708         return (daddr);
2709 }
2710
2711 static void
2712 jblocks_free(jblocks, mp, bytes)
2713         struct jblocks *jblocks;
2714         struct mount *mp;
2715         int bytes;
2716 {
2717
2718         LOCK_OWNED(VFSTOUFS(mp));
2719         jblocks->jb_free += bytes / DEV_BSIZE;
2720         if (jblocks->jb_suspended)
2721                 worklist_speedup(mp);
2722         wakeup(jblocks);
2723 }
2724
2725 static void
2726 jblocks_destroy(jblocks)
2727         struct jblocks *jblocks;
2728 {
2729
2730         if (jblocks->jb_extent)
2731                 free(jblocks->jb_extent, M_JBLOCKS);
2732         free(jblocks, M_JBLOCKS);
2733 }
2734
2735 static void
2736 jblocks_add(jblocks, daddr, blocks)
2737         struct jblocks *jblocks;
2738         ufs2_daddr_t daddr;
2739         int blocks;
2740 {
2741         struct jextent *jext;
2742
2743         jblocks->jb_blocks += blocks;
2744         jblocks->jb_free += blocks;
2745         jext = &jblocks->jb_extent[jblocks->jb_used];
2746         /* Adding the first block. */
2747         if (jext->je_daddr == 0) {
2748                 jext->je_daddr = daddr;
2749                 jext->je_blocks = blocks;
2750                 return;
2751         }
2752         /* Extending the last extent. */
2753         if (jext->je_daddr + jext->je_blocks == daddr) {
2754                 jext->je_blocks += blocks;
2755                 return;
2756         }
2757         /* Adding a new extent. */
2758         if (++jblocks->jb_used == jblocks->jb_avail) {
2759                 jblocks->jb_avail *= 2;
2760                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2761                     M_JBLOCKS, M_WAITOK | M_ZERO);
2762                 memcpy(jext, jblocks->jb_extent,
2763                     sizeof(struct jextent) * jblocks->jb_used);
2764                 free(jblocks->jb_extent, M_JBLOCKS);
2765                 jblocks->jb_extent = jext;
2766         }
2767         jext = &jblocks->jb_extent[jblocks->jb_used];
2768         jext->je_daddr = daddr;
2769         jext->je_blocks = blocks;
2770         return;
2771 }
2772
2773 int
2774 softdep_journal_lookup(mp, vpp)
2775         struct mount *mp;
2776         struct vnode **vpp;
2777 {
2778         struct componentname cnp;
2779         struct vnode *dvp;
2780         ino_t sujournal;
2781         int error;
2782
2783         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2784         if (error)
2785                 return (error);
2786         bzero(&cnp, sizeof(cnp));
2787         cnp.cn_nameiop = LOOKUP;
2788         cnp.cn_flags = ISLASTCN;
2789         cnp.cn_thread = curthread;
2790         cnp.cn_cred = curthread->td_ucred;
2791         cnp.cn_pnbuf = SUJ_FILE;
2792         cnp.cn_nameptr = SUJ_FILE;
2793         cnp.cn_namelen = strlen(SUJ_FILE);
2794         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2795         vput(dvp);
2796         if (error != 0)
2797                 return (error);
2798         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2799         return (error);
2800 }
2801
2802 /*
2803  * Open and verify the journal file.
2804  */
2805 static int
2806 journal_mount(mp, fs, cred)
2807         struct mount *mp;
2808         struct fs *fs;
2809         struct ucred *cred;
2810 {
2811         struct jblocks *jblocks;
2812         struct ufsmount *ump;
2813         struct vnode *vp;
2814         struct inode *ip;
2815         ufs2_daddr_t blkno;
2816         int bcount;
2817         int error;
2818         int i;
2819
2820         ump = VFSTOUFS(mp);
2821         ump->softdep_journal_tail = NULL;
2822         ump->softdep_on_journal = 0;
2823         ump->softdep_accdeps = 0;
2824         ump->softdep_req = 0;
2825         ump->softdep_jblocks = NULL;
2826         error = softdep_journal_lookup(mp, &vp);
2827         if (error != 0) {
2828                 printf("Failed to find journal.  Use tunefs to create one\n");
2829                 return (error);
2830         }
2831         ip = VTOI(vp);
2832         if (ip->i_size < SUJ_MIN) {
2833                 error = ENOSPC;
2834                 goto out;
2835         }
2836         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2837         jblocks = jblocks_create();
2838         for (i = 0; i < bcount; i++) {
2839                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2840                 if (error)
2841                         break;
2842                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2843         }
2844         if (error) {
2845                 jblocks_destroy(jblocks);
2846                 goto out;
2847         }
2848         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2849         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2850         ump->softdep_jblocks = jblocks;
2851 out:
2852         if (error == 0) {
2853                 MNT_ILOCK(mp);
2854                 mp->mnt_flag |= MNT_SUJ;
2855                 mp->mnt_flag &= ~MNT_SOFTDEP;
2856                 MNT_IUNLOCK(mp);
2857                 /*
2858                  * Only validate the journal contents if the
2859                  * filesystem is clean, otherwise we write the logs
2860                  * but they'll never be used.  If the filesystem was
2861                  * still dirty when we mounted it the journal is
2862                  * invalid and a new journal can only be valid if it
2863                  * starts from a clean mount.
2864                  */
2865                 if (fs->fs_clean) {
2866                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2867                         ip->i_flags |= IN_MODIFIED;
2868                         ffs_update(vp, 1);
2869                 }
2870         }
2871         vput(vp);
2872         return (error);
2873 }
2874
2875 static void
2876 journal_unmount(ump)
2877         struct ufsmount *ump;
2878 {
2879
2880         if (ump->softdep_jblocks)
2881                 jblocks_destroy(ump->softdep_jblocks);
2882         ump->softdep_jblocks = NULL;
2883 }
2884
2885 /*
2886  * Called when a journal record is ready to be written.  Space is allocated
2887  * and the journal entry is created when the journal is flushed to stable
2888  * store.
2889  */
2890 static void
2891 add_to_journal(wk)
2892         struct worklist *wk;
2893 {
2894         struct ufsmount *ump;
2895
2896         ump = VFSTOUFS(wk->wk_mp);
2897         LOCK_OWNED(ump);
2898         if (wk->wk_state & ONWORKLIST)
2899                 panic("add_to_journal: %s(0x%X) already on list",
2900                     TYPENAME(wk->wk_type), wk->wk_state);
2901         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2902         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2903                 ump->softdep_jblocks->jb_age = ticks;
2904                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2905         } else
2906                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2907         ump->softdep_journal_tail = wk;
2908         ump->softdep_on_journal += 1;
2909 }
2910
2911 /*
2912  * Remove an arbitrary item for the journal worklist maintain the tail
2913  * pointer.  This happens when a new operation obviates the need to
2914  * journal an old operation.
2915  */
2916 static void
2917 remove_from_journal(wk)
2918         struct worklist *wk;
2919 {
2920         struct ufsmount *ump;
2921
2922         ump = VFSTOUFS(wk->wk_mp);
2923         LOCK_OWNED(ump);
2924 #ifdef INVARIANTS
2925         {
2926                 struct worklist *wkn;
2927
2928                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2929                         if (wkn == wk)
2930                                 break;
2931                 if (wkn == NULL)
2932                         panic("remove_from_journal: %p is not in journal", wk);
2933         }
2934 #endif
2935         /*
2936          * We emulate a TAILQ to save space in most structures which do not
2937          * require TAILQ semantics.  Here we must update the tail position
2938          * when removing the tail which is not the final entry. This works
2939          * only if the worklist linkage are at the beginning of the structure.
2940          */
2941         if (ump->softdep_journal_tail == wk)
2942                 ump->softdep_journal_tail =
2943                     (struct worklist *)wk->wk_list.le_prev;
2944         WORKLIST_REMOVE(wk);
2945         ump->softdep_on_journal -= 1;
2946 }
2947
2948 /*
2949  * Check for journal space as well as dependency limits so the prelink
2950  * code can throttle both journaled and non-journaled filesystems.
2951  * Threshold is 0 for low and 1 for min.
2952  */
2953 static int
2954 journal_space(ump, thresh)
2955         struct ufsmount *ump;
2956         int thresh;
2957 {
2958         struct jblocks *jblocks;
2959         int limit, avail;
2960
2961         jblocks = ump->softdep_jblocks;
2962         if (jblocks == NULL)
2963                 return (1);
2964         /*
2965          * We use a tighter restriction here to prevent request_cleanup()
2966          * running in threads from running into locks we currently hold.
2967          * We have to be over the limit and our filesystem has to be
2968          * responsible for more than our share of that usage.
2969          */
2970         limit = (max_softdeps / 10) * 9;
2971         if (dep_current[D_INODEDEP] > limit &&
2972             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2973                 return (0);
2974         if (thresh)
2975                 thresh = jblocks->jb_min;
2976         else
2977                 thresh = jblocks->jb_low;
2978         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2979         avail = jblocks->jb_free - avail;
2980
2981         return (avail > thresh);
2982 }
2983
2984 static void
2985 journal_suspend(ump)
2986         struct ufsmount *ump;
2987 {
2988         struct jblocks *jblocks;
2989         struct mount *mp;
2990         bool set;
2991
2992         mp = UFSTOVFS(ump);
2993         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2994                 return;
2995
2996         jblocks = ump->softdep_jblocks;
2997         vfs_op_enter(mp);
2998         set = false;
2999         MNT_ILOCK(mp);
3000         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3001                 stat_journal_min++;
3002                 mp->mnt_kern_flag |= MNTK_SUSPEND;
3003                 mp->mnt_susp_owner = ump->softdep_flushtd;
3004                 set = true;
3005         }
3006         jblocks->jb_suspended = 1;
3007         MNT_IUNLOCK(mp);
3008         if (!set)
3009                 vfs_op_exit(mp);
3010 }
3011
3012 static int
3013 journal_unsuspend(struct ufsmount *ump)
3014 {
3015         struct jblocks *jblocks;
3016         struct mount *mp;
3017
3018         mp = UFSTOVFS(ump);
3019         jblocks = ump->softdep_jblocks;
3020
3021         if (jblocks != NULL && jblocks->jb_suspended &&
3022             journal_space(ump, jblocks->jb_min)) {
3023                 jblocks->jb_suspended = 0;
3024                 FREE_LOCK(ump);
3025                 mp->mnt_susp_owner = curthread;
3026                 vfs_write_resume(mp, 0);
3027                 ACQUIRE_LOCK(ump);
3028                 return (1);
3029         }
3030         return (0);
3031 }
3032
3033 /*
3034  * Called before any allocation function to be certain that there is
3035  * sufficient space in the journal prior to creating any new records.
3036  * Since in the case of block allocation we may have multiple locked
3037  * buffers at the time of the actual allocation we can not block
3038  * when the journal records are created.  Doing so would create a deadlock
3039  * if any of these buffers needed to be flushed to reclaim space.  Instead
3040  * we require a sufficiently large amount of available space such that
3041  * each thread in the system could have passed this allocation check and
3042  * still have sufficient free space.  With 20% of a minimum journal size
3043  * of 1MB we have 6553 records available.
3044  */
3045 int
3046 softdep_prealloc(vp, waitok)
3047         struct vnode *vp;
3048         int waitok;
3049 {
3050         struct ufsmount *ump;
3051
3052         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3053             ("softdep_prealloc called on non-softdep filesystem"));
3054         /*
3055          * Nothing to do if we are not running journaled soft updates.
3056          * If we currently hold the snapshot lock, we must avoid
3057          * handling other resources that could cause deadlock.  Do not
3058          * touch quotas vnode since it is typically recursed with
3059          * other vnode locks held.
3060          */
3061         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3062             (vp->v_vflag & VV_SYSTEM) != 0)
3063                 return (0);
3064         ump = VFSTOUFS(vp->v_mount);
3065         ACQUIRE_LOCK(ump);
3066         if (journal_space(ump, 0)) {
3067                 FREE_LOCK(ump);
3068                 return (0);
3069         }
3070         stat_journal_low++;
3071         FREE_LOCK(ump);
3072         if (waitok == MNT_NOWAIT)
3073                 return (ENOSPC);
3074         /*
3075          * Attempt to sync this vnode once to flush any journal
3076          * work attached to it.
3077          */
3078         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3079                 ffs_syncvnode(vp, waitok, 0);
3080         ACQUIRE_LOCK(ump);
3081         process_removes(vp);
3082         process_truncates(vp);
3083         if (journal_space(ump, 0) == 0) {
3084                 softdep_speedup(ump);
3085                 if (journal_space(ump, 1) == 0)
3086                         journal_suspend(ump);
3087         }
3088         FREE_LOCK(ump);
3089
3090         return (0);
3091 }
3092
3093 /*
3094  * Before adjusting a link count on a vnode verify that we have sufficient
3095  * journal space.  If not, process operations that depend on the currently
3096  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3097  * and softdep flush threads can not acquire these locks to reclaim space.
3098  */
3099 static void
3100 softdep_prelink(dvp, vp)
3101         struct vnode *dvp;
3102         struct vnode *vp;
3103 {
3104         struct ufsmount *ump;
3105
3106         ump = VFSTOUFS(dvp->v_mount);
3107         LOCK_OWNED(ump);
3108         /*
3109          * Nothing to do if we have sufficient journal space.
3110          * If we currently hold the snapshot lock, we must avoid
3111          * handling other resources that could cause deadlock.
3112          */
3113         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3114                 return;
3115         stat_journal_low++;
3116         FREE_LOCK(ump);
3117         if (vp)
3118                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3119         ffs_syncvnode(dvp, MNT_WAIT, 0);
3120         ACQUIRE_LOCK(ump);
3121         /* Process vp before dvp as it may create .. removes. */
3122         if (vp) {
3123                 process_removes(vp);
3124                 process_truncates(vp);
3125         }
3126         process_removes(dvp);
3127         process_truncates(dvp);
3128         softdep_speedup(ump);
3129         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3130         if (journal_space(ump, 0) == 0) {
3131                 softdep_speedup(ump);
3132                 if (journal_space(ump, 1) == 0)
3133                         journal_suspend(ump);
3134         }
3135 }
3136
3137 static void
3138 jseg_write(ump, jseg, data)
3139         struct ufsmount *ump;
3140         struct jseg *jseg;
3141         uint8_t *data;
3142 {
3143         struct jsegrec *rec;
3144
3145         rec = (struct jsegrec *)data;
3146         rec->jsr_seq = jseg->js_seq;
3147         rec->jsr_oldest = jseg->js_oldseq;
3148         rec->jsr_cnt = jseg->js_cnt;
3149         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3150         rec->jsr_crc = 0;
3151         rec->jsr_time = ump->um_fs->fs_mtime;
3152 }
3153
3154 static inline void
3155 inoref_write(inoref, jseg, rec)
3156         struct inoref *inoref;
3157         struct jseg *jseg;
3158         struct jrefrec *rec;
3159 {
3160
3161         inoref->if_jsegdep->jd_seg = jseg;
3162         rec->jr_ino = inoref->if_ino;
3163         rec->jr_parent = inoref->if_parent;
3164         rec->jr_nlink = inoref->if_nlink;
3165         rec->jr_mode = inoref->if_mode;
3166         rec->jr_diroff = inoref->if_diroff;
3167 }
3168
3169 static void
3170 jaddref_write(jaddref, jseg, data)
3171         struct jaddref *jaddref;
3172         struct jseg *jseg;
3173         uint8_t *data;
3174 {
3175         struct jrefrec *rec;
3176
3177         rec = (struct jrefrec *)data;
3178         rec->jr_op = JOP_ADDREF;
3179         inoref_write(&jaddref->ja_ref, jseg, rec);
3180 }
3181
3182 static void
3183 jremref_write(jremref, jseg, data)
3184         struct jremref *jremref;
3185         struct jseg *jseg;
3186         uint8_t *data;
3187 {
3188         struct jrefrec *rec;
3189
3190         rec = (struct jrefrec *)data;
3191         rec->jr_op = JOP_REMREF;
3192         inoref_write(&jremref->jr_ref, jseg, rec);
3193 }
3194
3195 static void
3196 jmvref_write(jmvref, jseg, data)
3197         struct jmvref *jmvref;
3198         struct jseg *jseg;
3199         uint8_t *data;
3200 {
3201         struct jmvrec *rec;
3202
3203         rec = (struct jmvrec *)data;
3204         rec->jm_op = JOP_MVREF;
3205         rec->jm_ino = jmvref->jm_ino;
3206         rec->jm_parent = jmvref->jm_parent;
3207         rec->jm_oldoff = jmvref->jm_oldoff;
3208         rec->jm_newoff = jmvref->jm_newoff;
3209 }
3210
3211 static void
3212 jnewblk_write(jnewblk, jseg, data)
3213         struct jnewblk *jnewblk;
3214         struct jseg *jseg;
3215         uint8_t *data;
3216 {
3217         struct jblkrec *rec;
3218
3219         jnewblk->jn_jsegdep->jd_seg = jseg;
3220         rec = (struct jblkrec *)data;
3221         rec->jb_op = JOP_NEWBLK;
3222         rec->jb_ino = jnewblk->jn_ino;
3223         rec->jb_blkno = jnewblk->jn_blkno;
3224         rec->jb_lbn = jnewblk->jn_lbn;
3225         rec->jb_frags = jnewblk->jn_frags;
3226         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3227 }
3228
3229 static void
3230 jfreeblk_write(jfreeblk, jseg, data)
3231         struct jfreeblk *jfreeblk;
3232         struct jseg *jseg;
3233         uint8_t *data;
3234 {
3235         struct jblkrec *rec;
3236
3237         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3238         rec = (struct jblkrec *)data;
3239         rec->jb_op = JOP_FREEBLK;
3240         rec->jb_ino = jfreeblk->jf_ino;
3241         rec->jb_blkno = jfreeblk->jf_blkno;
3242         rec->jb_lbn = jfreeblk->jf_lbn;
3243         rec->jb_frags = jfreeblk->jf_frags;
3244         rec->jb_oldfrags = 0;
3245 }
3246
3247 static void
3248 jfreefrag_write(jfreefrag, jseg, data)
3249         struct jfreefrag *jfreefrag;
3250         struct jseg *jseg;
3251         uint8_t *data;
3252 {
3253         struct jblkrec *rec;
3254
3255         jfreefrag->fr_jsegdep->jd_seg = jseg;
3256         rec = (struct jblkrec *)data;
3257         rec->jb_op = JOP_FREEBLK;
3258         rec->jb_ino = jfreefrag->fr_ino;
3259         rec->jb_blkno = jfreefrag->fr_blkno;
3260         rec->jb_lbn = jfreefrag->fr_lbn;
3261         rec->jb_frags = jfreefrag->fr_frags;
3262         rec->jb_oldfrags = 0;
3263 }
3264
3265 static void
3266 jtrunc_write(jtrunc, jseg, data)
3267         struct jtrunc *jtrunc;
3268         struct jseg *jseg;
3269         uint8_t *data;
3270 {
3271         struct jtrncrec *rec;
3272
3273         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3274         rec = (struct jtrncrec *)data;
3275         rec->jt_op = JOP_TRUNC;
3276         rec->jt_ino = jtrunc->jt_ino;
3277         rec->jt_size = jtrunc->jt_size;
3278         rec->jt_extsize = jtrunc->jt_extsize;
3279 }
3280
3281 static void
3282 jfsync_write(jfsync, jseg, data)
3283         struct jfsync *jfsync;
3284         struct jseg *jseg;
3285         uint8_t *data;
3286 {
3287         struct jtrncrec *rec;
3288
3289         rec = (struct jtrncrec *)data;
3290         rec->jt_op = JOP_SYNC;
3291         rec->jt_ino = jfsync->jfs_ino;
3292         rec->jt_size = jfsync->jfs_size;
3293         rec->jt_extsize = jfsync->jfs_extsize;
3294 }
3295
3296 static void
3297 softdep_flushjournal(mp)
3298         struct mount *mp;
3299 {
3300         struct jblocks *jblocks;
3301         struct ufsmount *ump;
3302
3303         if (MOUNTEDSUJ(mp) == 0)
3304                 return;
3305         ump = VFSTOUFS(mp);
3306         jblocks = ump->softdep_jblocks;
3307         ACQUIRE_LOCK(ump);
3308         while (ump->softdep_on_journal) {
3309                 jblocks->jb_needseg = 1;
3310                 softdep_process_journal(mp, NULL, MNT_WAIT);
3311         }
3312         FREE_LOCK(ump);
3313 }
3314
3315 static void softdep_synchronize_completed(struct bio *);
3316 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3317
3318 static void
3319 softdep_synchronize_completed(bp)
3320         struct bio *bp;
3321 {
3322         struct jseg *oldest;
3323         struct jseg *jseg;
3324         struct ufsmount *ump;
3325
3326         /*
3327          * caller1 marks the last segment written before we issued the
3328          * synchronize cache.
3329          */
3330         jseg = bp->bio_caller1;
3331         if (jseg == NULL) {
3332                 g_destroy_bio(bp);
3333                 return;
3334         }
3335         ump = VFSTOUFS(jseg->js_list.wk_mp);
3336         ACQUIRE_LOCK(ump);
3337         oldest = NULL;
3338         /*
3339          * Mark all the journal entries waiting on the synchronize cache
3340          * as completed so they may continue on.
3341          */
3342         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3343                 jseg->js_state |= COMPLETE;
3344                 oldest = jseg;
3345                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3346         }
3347         /*
3348          * Restart deferred journal entry processing from the oldest
3349          * completed jseg.
3350          */
3351         if (oldest)
3352                 complete_jsegs(oldest);
3353
3354         FREE_LOCK(ump);
3355         g_destroy_bio(bp);
3356 }
3357
3358 /*
3359  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3360  * barriers.  The journal must be written prior to any blocks that depend
3361  * on it and the journal can not be released until the blocks have be
3362  * written.  This code handles both barriers simultaneously.
3363  */
3364 static void
3365 softdep_synchronize(bp, ump, caller1)
3366         struct bio *bp;
3367         struct ufsmount *ump;
3368         void *caller1;
3369 {
3370
3371         bp->bio_cmd = BIO_FLUSH;
3372         bp->bio_flags |= BIO_ORDERED;
3373         bp->bio_data = NULL;
3374         bp->bio_offset = ump->um_cp->provider->mediasize;
3375         bp->bio_length = 0;
3376         bp->bio_done = softdep_synchronize_completed;
3377         bp->bio_caller1 = caller1;
3378         g_io_request(bp, ump->um_cp);
3379 }
3380
3381 /*
3382  * Flush some journal records to disk.
3383  */
3384 static void
3385 softdep_process_journal(mp, needwk, flags)
3386         struct mount *mp;
3387         struct worklist *needwk;
3388         int flags;
3389 {
3390         struct jblocks *jblocks;
3391         struct ufsmount *ump;
3392         struct worklist *wk;
3393         struct jseg *jseg;
3394         struct buf *bp;
3395         struct bio *bio;
3396         uint8_t *data;
3397         struct fs *fs;
3398         int shouldflush;
3399         int segwritten;
3400         int jrecmin;    /* Minimum records per block. */
3401         int jrecmax;    /* Maximum records per block. */
3402         int size;
3403         int cnt;
3404         int off;
3405         int devbsize;
3406
3407         if (MOUNTEDSUJ(mp) == 0)
3408                 return;
3409         shouldflush = softdep_flushcache;
3410         bio = NULL;
3411         jseg = NULL;
3412         ump = VFSTOUFS(mp);
3413         LOCK_OWNED(ump);
3414         fs = ump->um_fs;
3415         jblocks = ump->softdep_jblocks;
3416         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3417         /*
3418          * We write anywhere between a disk block and fs block.  The upper
3419          * bound is picked to prevent buffer cache fragmentation and limit
3420          * processing time per I/O.
3421          */
3422         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3423         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3424         segwritten = 0;
3425         for (;;) {
3426                 cnt = ump->softdep_on_journal;
3427                 /*
3428                  * Criteria for writing a segment:
3429                  * 1) We have a full block.
3430                  * 2) We're called from jwait() and haven't found the
3431                  *    journal item yet.
3432                  * 3) Always write if needseg is set.
3433                  * 4) If we are called from process_worklist and have
3434                  *    not yet written anything we write a partial block
3435                  *    to enforce a 1 second maximum latency on journal
3436                  *    entries.
3437                  */
3438                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3439                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3440                         break;
3441                 cnt++;
3442                 /*
3443                  * Verify some free journal space.  softdep_prealloc() should
3444                  * guarantee that we don't run out so this is indicative of
3445                  * a problem with the flow control.  Try to recover
3446                  * gracefully in any event.
3447                  */
3448                 while (jblocks->jb_free == 0) {
3449                         if (flags != MNT_WAIT)
3450                                 break;
3451                         printf("softdep: Out of journal space!\n");
3452                         softdep_speedup(ump);
3453                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3454                 }
3455                 FREE_LOCK(ump);
3456                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3457                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3458                 LIST_INIT(&jseg->js_entries);
3459                 LIST_INIT(&jseg->js_indirs);
3460                 jseg->js_state = ATTACHED;
3461                 if (shouldflush == 0)
3462                         jseg->js_state |= COMPLETE;
3463                 else if (bio == NULL)
3464                         bio = g_alloc_bio();
3465                 jseg->js_jblocks = jblocks;
3466                 bp = geteblk(fs->fs_bsize, 0);
3467                 ACQUIRE_LOCK(ump);
3468                 /*
3469                  * If there was a race while we were allocating the block
3470                  * and jseg the entry we care about was likely written.
3471                  * We bail out in both the WAIT and NOWAIT case and assume
3472                  * the caller will loop if the entry it cares about is
3473                  * not written.
3474                  */
3475                 cnt = ump->softdep_on_journal;
3476                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3477                         bp->b_flags |= B_INVAL | B_NOCACHE;
3478                         WORKITEM_FREE(jseg, D_JSEG);
3479                         FREE_LOCK(ump);
3480                         brelse(bp);
3481                         ACQUIRE_LOCK(ump);
3482                         break;
3483                 }
3484                 /*
3485                  * Calculate the disk block size required for the available
3486                  * records rounded to the min size.
3487                  */
3488                 if (cnt == 0)
3489                         size = devbsize;
3490                 else if (cnt < jrecmax)
3491                         size = howmany(cnt, jrecmin) * devbsize;
3492                 else
3493                         size = fs->fs_bsize;
3494                 /*
3495                  * Allocate a disk block for this journal data and account
3496                  * for truncation of the requested size if enough contiguous
3497                  * space was not available.
3498                  */
3499                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3500                 bp->b_lblkno = bp->b_blkno;
3501                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3502                 bp->b_bcount = size;
3503                 bp->b_flags &= ~B_INVAL;
3504                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3505                 /*
3506                  * Initialize our jseg with cnt records.  Assign the next
3507                  * sequence number to it and link it in-order.
3508                  */
3509                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3510                 jseg->js_buf = bp;
3511                 jseg->js_cnt = cnt;
3512                 jseg->js_refs = cnt + 1;        /* Self ref. */
3513                 jseg->js_size = size;
3514                 jseg->js_seq = jblocks->jb_nextseq++;
3515                 if (jblocks->jb_oldestseg == NULL)
3516                         jblocks->jb_oldestseg = jseg;
3517                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3518                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3519                 if (jblocks->jb_writeseg == NULL)
3520                         jblocks->jb_writeseg = jseg;
3521                 /*
3522                  * Start filling in records from the pending list.
3523                  */
3524                 data = bp->b_data;
3525                 off = 0;
3526
3527                 /*
3528                  * Always put a header on the first block.
3529                  * XXX As with below, there might not be a chance to get
3530                  * into the loop.  Ensure that something valid is written.
3531                  */
3532                 jseg_write(ump, jseg, data);
3533                 off += JREC_SIZE;
3534                 data = bp->b_data + off;
3535
3536                 /*
3537                  * XXX Something is wrong here.  There's no work to do,
3538                  * but we need to perform and I/O and allow it to complete
3539                  * anyways.
3540                  */
3541                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3542                         stat_emptyjblocks++;
3543
3544                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3545                     != NULL) {
3546                         if (cnt == 0)
3547                                 break;
3548                         /* Place a segment header on every device block. */
3549                         if ((off % devbsize) == 0) {
3550                                 jseg_write(ump, jseg, data);
3551                                 off += JREC_SIZE;
3552                                 data = bp->b_data + off;
3553                         }
3554                         if (wk == needwk)
3555                                 needwk = NULL;
3556                         remove_from_journal(wk);
3557                         wk->wk_state |= INPROGRESS;
3558                         WORKLIST_INSERT(&jseg->js_entries, wk);
3559                         switch (wk->wk_type) {
3560                         case D_JADDREF:
3561                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3562                                 break;
3563                         case D_JREMREF:
3564                                 jremref_write(WK_JREMREF(wk), jseg, data);
3565                                 break;
3566                         case D_JMVREF:
3567                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3568                                 break;
3569                         case D_JNEWBLK:
3570                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3571                                 break;
3572                         case D_JFREEBLK:
3573                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3574                                 break;
3575                         case D_JFREEFRAG:
3576                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3577                                 break;
3578                         case D_JTRUNC:
3579                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3580                                 break;
3581                         case D_JFSYNC:
3582                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3583                                 break;
3584                         default:
3585                                 panic("process_journal: Unknown type %s",
3586                                     TYPENAME(wk->wk_type));
3587                                 /* NOTREACHED */
3588                         }
3589                         off += JREC_SIZE;
3590                         data = bp->b_data + off;
3591                         cnt--;
3592                 }
3593
3594                 /* Clear any remaining space so we don't leak kernel data */
3595                 if (size > off)
3596                         bzero(data, size - off);
3597
3598                 /*
3599                  * Write this one buffer and continue.
3600                  */
3601                 segwritten = 1;
3602                 jblocks->jb_needseg = 0;
3603                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3604                 FREE_LOCK(ump);
3605                 pbgetvp(ump->um_devvp, bp);
3606                 /*
3607                  * We only do the blocking wait once we find the journal
3608                  * entry we're looking for.
3609                  */
3610                 if (needwk == NULL && flags == MNT_WAIT)
3611                         bwrite(bp);
3612                 else
3613                         bawrite(bp);
3614                 ACQUIRE_LOCK(ump);
3615         }
3616         /*
3617          * If we wrote a segment issue a synchronize cache so the journal
3618          * is reflected on disk before the data is written.  Since reclaiming
3619          * journal space also requires writing a journal record this
3620          * process also enforces a barrier before reclamation.
3621          */
3622         if (segwritten && shouldflush) {
3623                 softdep_synchronize(bio, ump, 
3624                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3625         } else if (bio)
3626                 g_destroy_bio(bio);
3627         /*
3628          * If we've suspended the filesystem because we ran out of journal
3629          * space either try to sync it here to make some progress or
3630          * unsuspend it if we already have.
3631          */
3632         if (flags == 0 && jblocks->jb_suspended) {
3633                 if (journal_unsuspend(ump))
3634                         return;
3635                 FREE_LOCK(ump);
3636                 VFS_SYNC(mp, MNT_NOWAIT);
3637                 ffs_sbupdate(ump, MNT_WAIT, 0);
3638                 ACQUIRE_LOCK(ump);
3639         }
3640 }
3641
3642 /*
3643  * Complete a jseg, allowing all dependencies awaiting journal writes
3644  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3645  * structures so that the journal segment can be freed to reclaim space.
3646  */
3647 static void
3648 complete_jseg(jseg)
3649         struct jseg *jseg;
3650 {
3651         struct worklist *wk;
3652         struct jmvref *jmvref;
3653 #ifdef INVARIANTS
3654         int i = 0;
3655 #endif
3656
3657         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3658                 WORKLIST_REMOVE(wk);
3659                 wk->wk_state &= ~INPROGRESS;
3660                 wk->wk_state |= COMPLETE;
3661                 KASSERT(i++ < jseg->js_cnt,
3662                     ("handle_written_jseg: overflow %d >= %d",
3663                     i - 1, jseg->js_cnt));
3664                 switch (wk->wk_type) {
3665                 case D_JADDREF:
3666                         handle_written_jaddref(WK_JADDREF(wk));
3667                         break;
3668                 case D_JREMREF:
3669                         handle_written_jremref(WK_JREMREF(wk));
3670                         break;
3671                 case D_JMVREF:
3672                         rele_jseg(jseg);        /* No jsegdep. */
3673                         jmvref = WK_JMVREF(wk);
3674                         LIST_REMOVE(jmvref, jm_deps);
3675                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3676                                 free_pagedep(jmvref->jm_pagedep);
3677                         WORKITEM_FREE(jmvref, D_JMVREF);
3678                         break;
3679                 case D_JNEWBLK:
3680                         handle_written_jnewblk(WK_JNEWBLK(wk));
3681                         break;
3682                 case D_JFREEBLK:
3683                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3684                         break;
3685                 case D_JTRUNC:
3686                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3687                         break;
3688                 case D_JFSYNC:
3689                         rele_jseg(jseg);        /* No jsegdep. */
3690                         WORKITEM_FREE(wk, D_JFSYNC);
3691                         break;
3692                 case D_JFREEFRAG:
3693                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3694                         break;
3695                 default:
3696                         panic("handle_written_jseg: Unknown type %s",
3697                             TYPENAME(wk->wk_type));
3698                         /* NOTREACHED */
3699                 }
3700         }
3701         /* Release the self reference so the structure may be freed. */
3702         rele_jseg(jseg);
3703 }
3704
3705 /*
3706  * Determine which jsegs are ready for completion processing.  Waits for
3707  * synchronize cache to complete as well as forcing in-order completion
3708  * of journal entries.
3709  */
3710 static void
3711 complete_jsegs(jseg)
3712         struct jseg *jseg;
3713 {
3714         struct jblocks *jblocks;
3715         struct jseg *jsegn;
3716
3717         jblocks = jseg->js_jblocks;
3718         /*
3719          * Don't allow out of order completions.  If this isn't the first
3720          * block wait for it to write before we're done.
3721          */
3722         if (jseg != jblocks->jb_writeseg)
3723                 return;
3724         /* Iterate through available jsegs processing their entries. */
3725         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3726                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3727                 jsegn = TAILQ_NEXT(jseg, js_next);
3728                 complete_jseg(jseg);
3729                 jseg = jsegn;
3730         }
3731         jblocks->jb_writeseg = jseg;
3732         /*
3733          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3734          */
3735         free_jsegs(jblocks);
3736 }
3737
3738 /*
3739  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3740  * the final completions.
3741  */
3742 static void
3743 handle_written_jseg(jseg, bp)
3744         struct jseg *jseg;
3745         struct buf *bp;
3746 {
3747
3748         if (jseg->js_refs == 0)
3749                 panic("handle_written_jseg: No self-reference on %p", jseg);
3750         jseg->js_state |= DEPCOMPLETE;
3751         /*
3752          * We'll never need this buffer again, set flags so it will be
3753          * discarded.
3754          */
3755         bp->b_flags |= B_INVAL | B_NOCACHE;
3756         pbrelvp(bp);
3757         complete_jsegs(jseg);
3758 }
3759
3760 static inline struct jsegdep *
3761 inoref_jseg(inoref)
3762         struct inoref *inoref;
3763 {
3764         struct jsegdep *jsegdep;
3765
3766         jsegdep = inoref->if_jsegdep;
3767         inoref->if_jsegdep = NULL;
3768
3769         return (jsegdep);
3770 }
3771
3772 /*
3773  * Called once a jremref has made it to stable store.  The jremref is marked
3774  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3775  * for the jremref to complete will be awoken by free_jremref.
3776  */
3777 static void
3778 handle_written_jremref(jremref)
3779         struct jremref *jremref;
3780 {
3781         struct inodedep *inodedep;
3782         struct jsegdep *jsegdep;
3783         struct dirrem *dirrem;
3784
3785         /* Grab the jsegdep. */
3786         jsegdep = inoref_jseg(&jremref->jr_ref);
3787         /*
3788          * Remove us from the inoref list.
3789          */
3790         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3791             0, &inodedep) == 0)
3792                 panic("handle_written_jremref: Lost inodedep");
3793         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3794         /*
3795          * Complete the dirrem.
3796          */
3797         dirrem = jremref->jr_dirrem;
3798         jremref->jr_dirrem = NULL;
3799         LIST_REMOVE(jremref, jr_deps);
3800         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3801         jwork_insert(&dirrem->dm_jwork, jsegdep);
3802         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3803             (dirrem->dm_state & COMPLETE) != 0)
3804                 add_to_worklist(&dirrem->dm_list, 0);
3805         free_jremref(jremref);
3806 }
3807
3808 /*
3809  * Called once a jaddref has made it to stable store.  The dependency is
3810  * marked complete and any dependent structures are added to the inode
3811  * bufwait list to be completed as soon as it is written.  If a bitmap write
3812  * depends on this entry we move the inode into the inodedephd of the
3813  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3814  */
3815 static void
3816 handle_written_jaddref(jaddref)
3817         struct jaddref *jaddref;
3818 {
3819         struct jsegdep *jsegdep;
3820         struct inodedep *inodedep;
3821         struct diradd *diradd;
3822         struct mkdir *mkdir;
3823
3824         /* Grab the jsegdep. */
3825         jsegdep = inoref_jseg(&jaddref->ja_ref);
3826         mkdir = NULL;
3827         diradd = NULL;
3828         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3829             0, &inodedep) == 0)
3830                 panic("handle_written_jaddref: Lost inodedep.");
3831         if (jaddref->ja_diradd == NULL)
3832                 panic("handle_written_jaddref: No dependency");
3833         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3834                 diradd = jaddref->ja_diradd;
3835                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3836         } else if (jaddref->ja_state & MKDIR_PARENT) {
3837                 mkdir = jaddref->ja_mkdir;
3838                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3839         } else if (jaddref->ja_state & MKDIR_BODY)
3840                 mkdir = jaddref->ja_mkdir;
3841         else
3842                 panic("handle_written_jaddref: Unknown dependency %p",
3843                     jaddref->ja_diradd);
3844         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3845         /*
3846          * Remove us from the inode list.
3847          */
3848         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3849         /*
3850          * The mkdir may be waiting on the jaddref to clear before freeing.
3851          */
3852         if (mkdir) {
3853                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3854                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3855                     TYPENAME(mkdir->md_list.wk_type)));
3856                 mkdir->md_jaddref = NULL;
3857                 diradd = mkdir->md_diradd;
3858                 mkdir->md_state |= DEPCOMPLETE;
3859                 complete_mkdir(mkdir);
3860         }
3861         jwork_insert(&diradd->da_jwork, jsegdep);
3862         if (jaddref->ja_state & NEWBLOCK) {
3863                 inodedep->id_state |= ONDEPLIST;
3864                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3865                     inodedep, id_deps);
3866         }
3867         free_jaddref(jaddref);
3868 }
3869
3870 /*
3871  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3872  * is placed in the bmsafemap to await notification of a written bitmap.  If
3873  * the operation was canceled we add the segdep to the appropriate
3874  * dependency to free the journal space once the canceling operation
3875  * completes.
3876  */
3877 static void
3878 handle_written_jnewblk(jnewblk)
3879         struct jnewblk *jnewblk;
3880 {
3881         struct bmsafemap *bmsafemap;
3882         struct freefrag *freefrag;
3883         struct freework *freework;
3884         struct jsegdep *jsegdep;
3885         struct newblk *newblk;
3886
3887         /* Grab the jsegdep. */
3888         jsegdep = jnewblk->jn_jsegdep;
3889         jnewblk->jn_jsegdep = NULL;
3890         if (jnewblk->jn_dep == NULL) 
3891                 panic("handle_written_jnewblk: No dependency for the segdep.");
3892         switch (jnewblk->jn_dep->wk_type) {
3893         case D_NEWBLK:
3894         case D_ALLOCDIRECT:
3895         case D_ALLOCINDIR:
3896                 /*
3897                  * Add the written block to the bmsafemap so it can
3898                  * be notified when the bitmap is on disk.
3899                  */
3900                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3901                 newblk->nb_jnewblk = NULL;
3902                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3903                         bmsafemap = newblk->nb_bmsafemap;
3904                         newblk->nb_state |= ONDEPLIST;
3905                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3906                             nb_deps);
3907                 }
3908                 jwork_insert(&newblk->nb_jwork, jsegdep);
3909                 break;
3910         case D_FREEFRAG:
3911                 /*
3912                  * A newblock being removed by a freefrag when replaced by
3913                  * frag extension.
3914                  */
3915                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3916                 freefrag->ff_jdep = NULL;
3917                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3918                 break;
3919         case D_FREEWORK:
3920                 /*
3921                  * A direct block was removed by truncate.
3922                  */
3923                 freework = WK_FREEWORK(jnewblk->jn_dep);
3924                 freework->fw_jnewblk = NULL;
3925                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3926                 break;
3927         default:
3928                 panic("handle_written_jnewblk: Unknown type %d.",
3929                     jnewblk->jn_dep->wk_type);
3930         }
3931         jnewblk->jn_dep = NULL;
3932         free_jnewblk(jnewblk);
3933 }
3934
3935 /*
3936  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3937  * an in-flight allocation that has not yet been committed.  Divorce us
3938  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3939  * to the worklist.
3940  */
3941 static void
3942 cancel_jfreefrag(jfreefrag)
3943         struct jfreefrag *jfreefrag;
3944 {
3945         struct freefrag *freefrag;
3946
3947         if (jfreefrag->fr_jsegdep) {
3948                 free_jsegdep(jfreefrag->fr_jsegdep);
3949                 jfreefrag->fr_jsegdep = NULL;
3950         }
3951         freefrag = jfreefrag->fr_freefrag;
3952         jfreefrag->fr_freefrag = NULL;
3953         free_jfreefrag(jfreefrag);
3954         freefrag->ff_state |= DEPCOMPLETE;
3955         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3956 }
3957
3958 /*
3959  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3960  */
3961 static void
3962 free_jfreefrag(jfreefrag)
3963         struct jfreefrag *jfreefrag;
3964 {
3965
3966         if (jfreefrag->fr_state & INPROGRESS)
3967                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3968         else if (jfreefrag->fr_state & ONWORKLIST)
3969                 remove_from_journal(&jfreefrag->fr_list);
3970         if (jfreefrag->fr_freefrag != NULL)
3971                 panic("free_jfreefrag:  Still attached to a freefrag.");
3972         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3973 }
3974
3975 /*
3976  * Called when the journal write for a jfreefrag completes.  The parent
3977  * freefrag is added to the worklist if this completes its dependencies.
3978  */
3979 static void
3980 handle_written_jfreefrag(jfreefrag)
3981         struct jfreefrag *jfreefrag;
3982 {
3983         struct jsegdep *jsegdep;
3984         struct freefrag *freefrag;
3985
3986         /* Grab the jsegdep. */
3987         jsegdep = jfreefrag->fr_jsegdep;
3988         jfreefrag->fr_jsegdep = NULL;
3989         freefrag = jfreefrag->fr_freefrag;
3990         if (freefrag == NULL)
3991                 panic("handle_written_jfreefrag: No freefrag.");
3992         freefrag->ff_state |= DEPCOMPLETE;
3993         freefrag->ff_jdep = NULL;
3994         jwork_insert(&freefrag->ff_jwork, jsegdep);
3995         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3996                 add_to_worklist(&freefrag->ff_list, 0);
3997         jfreefrag->fr_freefrag = NULL;
3998         free_jfreefrag(jfreefrag);
3999 }
4000
4001 /*
4002  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4003  * is removed from the freeblks list of pending journal writes and the
4004  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4005  * have been reclaimed.
4006  */
4007 static void
4008 handle_written_jblkdep(jblkdep)
4009         struct jblkdep *jblkdep;
4010 {
4011         struct freeblks *freeblks;
4012         struct jsegdep *jsegdep;
4013
4014         /* Grab the jsegdep. */
4015         jsegdep = jblkdep->jb_jsegdep;
4016         jblkdep->jb_jsegdep = NULL;
4017         freeblks = jblkdep->jb_freeblks;
4018         LIST_REMOVE(jblkdep, jb_deps);
4019         jwork_insert(&freeblks->fb_jwork, jsegdep);
4020         /*
4021          * If the freeblks is all journaled, we can add it to the worklist.
4022          */
4023         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4024             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4025                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4026
4027         free_jblkdep(jblkdep);
4028 }
4029
4030 static struct jsegdep *
4031 newjsegdep(struct worklist *wk)
4032 {
4033         struct jsegdep *jsegdep;
4034
4035         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4036         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4037         jsegdep->jd_seg = NULL;
4038
4039         return (jsegdep);
4040 }
4041
4042 static struct jmvref *
4043 newjmvref(dp, ino, oldoff, newoff)
4044         struct inode *dp;
4045         ino_t ino;
4046         off_t oldoff;
4047         off_t newoff;
4048 {
4049         struct jmvref *jmvref;
4050
4051         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4052         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4053         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4054         jmvref->jm_parent = dp->i_number;
4055         jmvref->jm_ino = ino;
4056         jmvref->jm_oldoff = oldoff;
4057         jmvref->jm_newoff = newoff;
4058
4059         return (jmvref);
4060 }
4061
4062 /*
4063  * Allocate a new jremref that tracks the removal of ip from dp with the
4064  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4065  * DEPCOMPLETE as we have all the information required for the journal write
4066  * and the directory has already been removed from the buffer.  The caller
4067  * is responsible for linking the jremref into the pagedep and adding it
4068  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4069  * a DOTDOT addition so handle_workitem_remove() can properly assign
4070  * the jsegdep when we're done.
4071  */
4072 static struct jremref *
4073 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4074     off_t diroff, nlink_t nlink)
4075 {
4076         struct jremref *jremref;
4077
4078         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4079         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4080         jremref->jr_state = ATTACHED;
4081         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4082            nlink, ip->i_mode);
4083         jremref->jr_dirrem = dirrem;
4084
4085         return (jremref);
4086 }
4087
4088 static inline void
4089 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4090     nlink_t nlink, uint16_t mode)
4091 {
4092
4093         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4094         inoref->if_diroff = diroff;
4095         inoref->if_ino = ino;
4096         inoref->if_parent = parent;
4097         inoref->if_nlink = nlink;
4098         inoref->if_mode = mode;
4099 }
4100
4101 /*
4102  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4103  * directory offset may not be known until later.  The caller is responsible
4104  * adding the entry to the journal when this information is available.  nlink
4105  * should be the link count prior to the addition and mode is only required
4106  * to have the correct FMT.
4107  */
4108 static struct jaddref *
4109 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4110     uint16_t mode)
4111 {
4112         struct jaddref *jaddref;
4113
4114         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4115         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4116         jaddref->ja_state = ATTACHED;
4117         jaddref->ja_mkdir = NULL;
4118         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4119
4120         return (jaddref);
4121 }
4122
4123 /*
4124  * Create a new free dependency for a freework.  The caller is responsible
4125  * for adjusting the reference count when it has the lock held.  The freedep
4126  * will track an outstanding bitmap write that will ultimately clear the
4127  * freework to continue.
4128  */
4129 static struct freedep *
4130 newfreedep(struct freework *freework)
4131 {
4132         struct freedep *freedep;
4133
4134         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4135         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4136         freedep->fd_freework = freework;
4137
4138         return (freedep);
4139 }
4140
4141 /*
4142  * Free a freedep structure once the buffer it is linked to is written.  If
4143  * this is the last reference to the freework schedule it for completion.
4144  */
4145 static void
4146 free_freedep(freedep)
4147         struct freedep *freedep;
4148 {
4149         struct freework *freework;
4150
4151         freework = freedep->fd_freework;
4152         freework->fw_freeblks->fb_cgwait--;
4153         if (--freework->fw_ref == 0)
4154                 freework_enqueue(freework);
4155         WORKITEM_FREE(freedep, D_FREEDEP);
4156 }
4157
4158 /*
4159  * Allocate a new freework structure that may be a level in an indirect
4160  * when parent is not NULL or a top level block when it is.  The top level
4161  * freework structures are allocated without the per-filesystem lock held
4162  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4163  */
4164 static struct freework *
4165 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4166         struct ufsmount *ump;
4167         struct freeblks *freeblks;
4168         struct freework *parent;
4169         ufs_lbn_t lbn;
4170         ufs2_daddr_t nb;
4171         int frags;
4172         int off;
4173         int journal;
4174 {
4175         struct freework *freework;
4176
4177         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4178         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4179         freework->fw_state = ATTACHED;
4180         freework->fw_jnewblk = NULL;
4181         freework->fw_freeblks = freeblks;
4182         freework->fw_parent = parent;
4183         freework->fw_lbn = lbn;
4184         freework->fw_blkno = nb;
4185         freework->fw_frags = frags;
4186         freework->fw_indir = NULL;
4187         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4188             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4189         freework->fw_start = freework->fw_off = off;
4190         if (journal)
4191                 newjfreeblk(freeblks, lbn, nb, frags);
4192         if (parent == NULL) {
4193                 ACQUIRE_LOCK(ump);
4194                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4195                 freeblks->fb_ref++;
4196                 FREE_LOCK(ump);
4197         }
4198
4199         return (freework);
4200 }
4201
4202 /*
4203  * Eliminate a jfreeblk for a block that does not need journaling.
4204  */
4205 static void
4206 cancel_jfreeblk(freeblks, blkno)
4207         struct freeblks *freeblks;
4208         ufs2_daddr_t blkno;
4209 {
4210         struct jfreeblk *jfreeblk;
4211         struct jblkdep *jblkdep;
4212
4213         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4214                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4215                         continue;
4216                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4217                 if (jfreeblk->jf_blkno == blkno)
4218                         break;
4219         }
4220         if (jblkdep == NULL)
4221                 return;
4222         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4223         free_jsegdep(jblkdep->jb_jsegdep);
4224         LIST_REMOVE(jblkdep, jb_deps);
4225         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4226 }
4227
4228 /*
4229  * Allocate a new jfreeblk to journal top level block pointer when truncating
4230  * a file.  The caller must add this to the worklist when the per-filesystem
4231  * lock is held.
4232  */
4233 static struct jfreeblk *
4234 newjfreeblk(freeblks, lbn, blkno, frags)
4235         struct freeblks *freeblks;
4236         ufs_lbn_t lbn;
4237         ufs2_daddr_t blkno;
4238         int frags;
4239 {
4240         struct jfreeblk *jfreeblk;
4241
4242         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4243         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4244             freeblks->fb_list.wk_mp);
4245         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4246         jfreeblk->jf_dep.jb_freeblks = freeblks;
4247         jfreeblk->jf_ino = freeblks->fb_inum;
4248         jfreeblk->jf_lbn = lbn;
4249         jfreeblk->jf_blkno = blkno;
4250         jfreeblk->jf_frags = frags;
4251         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4252
4253         return (jfreeblk);
4254 }
4255
4256 /*
4257  * The journal is only prepared to handle full-size block numbers, so we
4258  * have to adjust the record to reflect the change to a full-size block.
4259  * For example, suppose we have a block made up of fragments 8-15 and
4260  * want to free its last two fragments. We are given a request that says:
4261  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4262  * where frags are the number of fragments to free and oldfrags are the
4263  * number of fragments to keep. To block align it, we have to change it to
4264  * have a valid full-size blkno, so it becomes:
4265  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4266  */
4267 static void
4268 adjust_newfreework(freeblks, frag_offset)
4269         struct freeblks *freeblks;
4270         int frag_offset;
4271 {
4272         struct jfreeblk *jfreeblk;
4273
4274         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4275             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4276             ("adjust_newfreework: Missing freeblks dependency"));
4277
4278         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4279         jfreeblk->jf_blkno -= frag_offset;
4280         jfreeblk->jf_frags += frag_offset;
4281 }
4282
4283 /*
4284  * Allocate a new jtrunc to track a partial truncation.
4285  */
4286 static struct jtrunc *
4287 newjtrunc(freeblks, size, extsize)
4288         struct freeblks *freeblks;
4289         off_t size;
4290         int extsize;
4291 {
4292         struct jtrunc *jtrunc;
4293
4294         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4295         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4296             freeblks->fb_list.wk_mp);
4297         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4298         jtrunc->jt_dep.jb_freeblks = freeblks;
4299         jtrunc->jt_ino = freeblks->fb_inum;
4300         jtrunc->jt_size = size;
4301         jtrunc->jt_extsize = extsize;
4302         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4303
4304         return (jtrunc);
4305 }
4306
4307 /*
4308  * If we're canceling a new bitmap we have to search for another ref
4309  * to move into the bmsafemap dep.  This might be better expressed
4310  * with another structure.
4311  */
4312 static void
4313 move_newblock_dep(jaddref, inodedep)
4314         struct jaddref *jaddref;
4315         struct inodedep *inodedep;
4316 {
4317         struct inoref *inoref;
4318         struct jaddref *jaddrefn;
4319
4320         jaddrefn = NULL;
4321         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4322             inoref = TAILQ_NEXT(inoref, if_deps)) {
4323                 if ((jaddref->ja_state & NEWBLOCK) &&
4324                     inoref->if_list.wk_type == D_JADDREF) {
4325                         jaddrefn = (struct jaddref *)inoref;
4326                         break;
4327                 }
4328         }
4329         if (jaddrefn == NULL)
4330                 return;
4331         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4332         jaddrefn->ja_state |= jaddref->ja_state &
4333             (ATTACHED | UNDONE | NEWBLOCK);
4334         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4335         jaddref->ja_state |= ATTACHED;
4336         LIST_REMOVE(jaddref, ja_bmdeps);
4337         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4338             ja_bmdeps);
4339 }
4340
4341 /*
4342  * Cancel a jaddref either before it has been written or while it is being
4343  * written.  This happens when a link is removed before the add reaches
4344  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4345  * and inode to prevent the link count or bitmap from reaching the disk
4346  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4347  * required.
4348  *
4349  * Returns 1 if the canceled addref requires journaling of the remove and
4350  * 0 otherwise.
4351  */
4352 static int
4353 cancel_jaddref(jaddref, inodedep, wkhd)
4354         struct jaddref *jaddref;
4355         struct inodedep *inodedep;
4356         struct workhead *wkhd;
4357 {
4358         struct inoref *inoref;
4359         struct jsegdep *jsegdep;
4360         int needsj;
4361
4362         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4363             ("cancel_jaddref: Canceling complete jaddref"));
4364         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4365                 needsj = 1;
4366         else
4367                 needsj = 0;
4368         if (inodedep == NULL)
4369                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4370                     0, &inodedep) == 0)
4371                         panic("cancel_jaddref: Lost inodedep");
4372         /*
4373          * We must adjust the nlink of any reference operation that follows
4374          * us so that it is consistent with the in-memory reference.  This
4375          * ensures that inode nlink rollbacks always have the correct link.
4376          */
4377         if (needsj == 0) {
4378                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4379                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4380                         if (inoref->if_state & GOINGAWAY)
4381                                 break;
4382                         inoref->if_nlink--;
4383                 }
4384         }
4385         jsegdep = inoref_jseg(&jaddref->ja_ref);
4386         if (jaddref->ja_state & NEWBLOCK)
4387                 move_newblock_dep(jaddref, inodedep);
4388         wake_worklist(&jaddref->ja_list);
4389         jaddref->ja_mkdir = NULL;
4390         if (jaddref->ja_state & INPROGRESS) {
4391                 jaddref->ja_state &= ~INPROGRESS;
4392                 WORKLIST_REMOVE(&jaddref->ja_list);
4393                 jwork_insert(wkhd, jsegdep);
4394         } else {
4395                 free_jsegdep(jsegdep);
4396                 if (jaddref->ja_state & DEPCOMPLETE)
4397                         remove_from_journal(&jaddref->ja_list);
4398         }
4399         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4400         /*
4401          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4402          * can arrange for them to be freed with the bitmap.  Otherwise we
4403          * no longer need this addref attached to the inoreflst and it
4404          * will incorrectly adjust nlink if we leave it.
4405          */
4406         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4407                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4408                     if_deps);
4409                 jaddref->ja_state |= COMPLETE;
4410                 free_jaddref(jaddref);
4411                 return (needsj);
4412         }
4413         /*
4414          * Leave the head of the list for jsegdeps for fast merging.
4415          */
4416         if (LIST_FIRST(wkhd) != NULL) {
4417                 jaddref->ja_state |= ONWORKLIST;
4418                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4419         } else
4420                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4421
4422         return (needsj);
4423 }
4424
4425 /* 
4426  * Attempt to free a jaddref structure when some work completes.  This
4427  * should only succeed once the entry is written and all dependencies have
4428  * been notified.
4429  */
4430 static void
4431 free_jaddref(jaddref)
4432         struct jaddref *jaddref;
4433 {
4434
4435         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4436                 return;
4437         if (jaddref->ja_ref.if_jsegdep)
4438                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4439                     jaddref, jaddref->ja_state);
4440         if (jaddref->ja_state & NEWBLOCK)
4441                 LIST_REMOVE(jaddref, ja_bmdeps);
4442         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4443                 panic("free_jaddref: Bad state %p(0x%X)",
4444                     jaddref, jaddref->ja_state);
4445         if (jaddref->ja_mkdir != NULL)
4446                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4447         WORKITEM_FREE(jaddref, D_JADDREF);
4448 }
4449
4450 /*
4451  * Free a jremref structure once it has been written or discarded.
4452  */
4453 static void
4454 free_jremref(jremref)
4455         struct jremref *jremref;
4456 {
4457
4458         if (jremref->jr_ref.if_jsegdep)
4459                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4460         if (jremref->jr_state & INPROGRESS)
4461                 panic("free_jremref: IO still pending");
4462         WORKITEM_FREE(jremref, D_JREMREF);
4463 }
4464
4465 /*
4466  * Free a jnewblk structure.
4467  */
4468 static void
4469 free_jnewblk(jnewblk)
4470         struct jnewblk *jnewblk;
4471 {
4472
4473         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4474                 return;
4475         LIST_REMOVE(jnewblk, jn_deps);
4476         if (jnewblk->jn_dep != NULL)
4477                 panic("free_jnewblk: Dependency still attached.");
4478         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4479 }
4480
4481 /*
4482  * Cancel a jnewblk which has been been made redundant by frag extension.
4483  */
4484 static void
4485 cancel_jnewblk(jnewblk, wkhd)
4486         struct jnewblk *jnewblk;
4487         struct workhead *wkhd;
4488 {
4489         struct jsegdep *jsegdep;
4490
4491         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4492         jsegdep = jnewblk->jn_jsegdep;
4493         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4494                 panic("cancel_jnewblk: Invalid state");
4495         jnewblk->jn_jsegdep  = NULL;
4496         jnewblk->jn_dep = NULL;
4497         jnewblk->jn_state |= GOINGAWAY;
4498         if (jnewblk->jn_state & INPROGRESS) {
4499                 jnewblk->jn_state &= ~INPROGRESS;
4500                 WORKLIST_REMOVE(&jnewblk->jn_list);
4501                 jwork_insert(wkhd, jsegdep);
4502         } else {
4503                 free_jsegdep(jsegdep);
4504                 remove_from_journal(&jnewblk->jn_list);
4505         }
4506         wake_worklist(&jnewblk->jn_list);
4507         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4508 }
4509
4510 static void
4511 free_jblkdep(jblkdep)
4512         struct jblkdep *jblkdep;
4513 {
4514
4515         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4516                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4517         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4518                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4519         else
4520                 panic("free_jblkdep: Unexpected type %s",
4521                     TYPENAME(jblkdep->jb_list.wk_type));
4522 }
4523
4524 /*
4525  * Free a single jseg once it is no longer referenced in memory or on
4526  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4527  * to disappear.
4528  */
4529 static void
4530 free_jseg(jseg, jblocks)
4531         struct jseg *jseg;
4532         struct jblocks *jblocks;
4533 {
4534         struct freework *freework;
4535
4536         /*
4537          * Free freework structures that were lingering to indicate freed
4538          * indirect blocks that forced journal write ordering on reallocate.
4539          */
4540         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4541                 indirblk_remove(freework);
4542         if (jblocks->jb_oldestseg == jseg)
4543                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4544         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4545         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4546         KASSERT(LIST_EMPTY(&jseg->js_entries),
4547             ("free_jseg: Freed jseg has valid entries."));
4548         WORKITEM_FREE(jseg, D_JSEG);
4549 }
4550
4551 /*
4552  * Free all jsegs that meet the criteria for being reclaimed and update
4553  * oldestseg.
4554  */
4555 static void
4556 free_jsegs(jblocks)
4557         struct jblocks *jblocks;
4558 {
4559         struct jseg *jseg;
4560
4561         /*
4562          * Free only those jsegs which have none allocated before them to
4563          * preserve the journal space ordering.
4564          */
4565         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4566                 /*
4567                  * Only reclaim space when nothing depends on this journal
4568                  * set and another set has written that it is no longer
4569                  * valid.
4570                  */
4571                 if (jseg->js_refs != 0) {
4572                         jblocks->jb_oldestseg = jseg;
4573                         return;
4574                 }
4575                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4576                         break;
4577                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4578                         break;
4579                 /*
4580                  * We can free jsegs that didn't write entries when
4581                  * oldestwrseq == js_seq.
4582                  */
4583                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4584                     jseg->js_cnt != 0)
4585                         break;
4586                 free_jseg(jseg, jblocks);
4587         }
4588         /*
4589          * If we exited the loop above we still must discover the
4590          * oldest valid segment.
4591          */
4592         if (jseg)
4593                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4594                      jseg = TAILQ_NEXT(jseg, js_next))
4595                         if (jseg->js_refs != 0)
4596                                 break;
4597         jblocks->jb_oldestseg = jseg;
4598         /*
4599          * The journal has no valid records but some jsegs may still be
4600          * waiting on oldestwrseq to advance.  We force a small record
4601          * out to permit these lingering records to be reclaimed.
4602          */
4603         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4604                 jblocks->jb_needseg = 1;
4605 }
4606
4607 /*
4608  * Release one reference to a jseg and free it if the count reaches 0.  This
4609  * should eventually reclaim journal space as well.
4610  */
4611 static void
4612 rele_jseg(jseg)
4613         struct jseg *jseg;
4614 {
4615
4616         KASSERT(jseg->js_refs > 0,
4617             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4618         if (--jseg->js_refs != 0)
4619                 return;
4620         free_jsegs(jseg->js_jblocks);
4621 }
4622
4623 /*
4624  * Release a jsegdep and decrement the jseg count.
4625  */
4626 static void
4627 free_jsegdep(jsegdep)
4628         struct jsegdep *jsegdep;
4629 {
4630
4631         if (jsegdep->jd_seg)
4632                 rele_jseg(jsegdep->jd_seg);
4633         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4634 }
4635
4636 /*
4637  * Wait for a journal item to make it to disk.  Initiate journal processing
4638  * if required.
4639  */
4640 static int
4641 jwait(wk, waitfor)
4642         struct worklist *wk;
4643         int waitfor;
4644 {
4645
4646         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4647         /*
4648          * Blocking journal waits cause slow synchronous behavior.  Record
4649          * stats on the frequency of these blocking operations.
4650          */
4651         if (waitfor == MNT_WAIT) {
4652                 stat_journal_wait++;
4653                 switch (wk->wk_type) {
4654                 case D_JREMREF:
4655                 case D_JMVREF:
4656                         stat_jwait_filepage++;
4657                         break;
4658                 case D_JTRUNC:
4659                 case D_JFREEBLK:
4660                         stat_jwait_freeblks++;
4661                         break;
4662                 case D_JNEWBLK:
4663                         stat_jwait_newblk++;
4664                         break;
4665                 case D_JADDREF:
4666                         stat_jwait_inode++;
4667                         break;
4668                 default:
4669                         break;
4670                 }
4671         }
4672         /*
4673          * If IO has not started we process the journal.  We can't mark the
4674          * worklist item as IOWAITING because we drop the lock while
4675          * processing the journal and the worklist entry may be freed after
4676          * this point.  The caller may call back in and re-issue the request.
4677          */
4678         if ((wk->wk_state & INPROGRESS) == 0) {
4679                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4680                 if (waitfor != MNT_WAIT)
4681                         return (EBUSY);
4682                 return (0);
4683         }
4684         if (waitfor != MNT_WAIT)
4685                 return (EBUSY);
4686         wait_worklist(wk, "jwait");
4687         return (0);
4688 }
4689
4690 /*
4691  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4692  * appropriate.  This is a convenience function to reduce duplicate code
4693  * for the setup and revert functions below.
4694  */
4695 static struct inodedep *
4696 inodedep_lookup_ip(ip)
4697         struct inode *ip;
4698 {
4699         struct inodedep *inodedep;
4700
4701         KASSERT(ip->i_nlink >= ip->i_effnlink,
4702             ("inodedep_lookup_ip: bad delta"));
4703         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4704             &inodedep);
4705         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4706         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4707
4708         return (inodedep);
4709 }
4710
4711 /*
4712  * Called prior to creating a new inode and linking it to a directory.  The
4713  * jaddref structure must already be allocated by softdep_setup_inomapdep
4714  * and it is discovered here so we can initialize the mode and update
4715  * nlinkdelta.
4716  */
4717 void
4718 softdep_setup_create(dp, ip)
4719         struct inode *dp;
4720         struct inode *ip;
4721 {
4722         struct inodedep *inodedep;
4723         struct jaddref *jaddref;
4724         struct vnode *dvp;
4725
4726         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4727             ("softdep_setup_create called on non-softdep filesystem"));
4728         KASSERT(ip->i_nlink == 1,
4729             ("softdep_setup_create: Invalid link count."));
4730         dvp = ITOV(dp);
4731         ACQUIRE_LOCK(ITOUMP(dp));
4732         inodedep = inodedep_lookup_ip(ip);
4733         if (DOINGSUJ(dvp)) {
4734                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4735                     inoreflst);
4736                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4737                     ("softdep_setup_create: No addref structure present."));
4738         }
4739         softdep_prelink(dvp, NULL);
4740         FREE_LOCK(ITOUMP(dp));
4741 }
4742
4743 /*
4744  * Create a jaddref structure to track the addition of a DOTDOT link when
4745  * we are reparenting an inode as part of a rename.  This jaddref will be
4746  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4747  * non-journaling softdep.
4748  */
4749 void
4750 softdep_setup_dotdot_link(dp, ip)
4751         struct inode *dp;
4752         struct inode *ip;
4753 {
4754         struct inodedep *inodedep;
4755         struct jaddref *jaddref;
4756         struct vnode *dvp;
4757
4758         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4759             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4760         dvp = ITOV(dp);
4761         jaddref = NULL;
4762         /*
4763          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4764          * is used as a normal link would be.
4765          */
4766         if (DOINGSUJ(dvp))
4767                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4768                     dp->i_effnlink - 1, dp->i_mode);
4769         ACQUIRE_LOCK(ITOUMP(dp));
4770         inodedep = inodedep_lookup_ip(dp);
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  * Create a jaddref structure to track a new link to an inode.  The directory
4780  * offset is not known until softdep_setup_directory_add or
4781  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4782  * softdep.
4783  */
4784 void
4785 softdep_setup_link(dp, ip)
4786         struct inode *dp;
4787         struct inode *ip;
4788 {
4789         struct inodedep *inodedep;
4790         struct jaddref *jaddref;
4791         struct vnode *dvp;
4792
4793         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4794             ("softdep_setup_link called on non-softdep filesystem"));
4795         dvp = ITOV(dp);
4796         jaddref = NULL;
4797         if (DOINGSUJ(dvp))
4798                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4799                     ip->i_mode);
4800         ACQUIRE_LOCK(ITOUMP(dp));
4801         inodedep = inodedep_lookup_ip(ip);
4802         if (jaddref)
4803                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4804                     if_deps);
4805         softdep_prelink(dvp, ITOV(ip));
4806         FREE_LOCK(ITOUMP(dp));
4807 }
4808
4809 /*
4810  * Called to create the jaddref structures to track . and .. references as
4811  * well as lookup and further initialize the incomplete jaddref created
4812  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4813  * nlinkdelta for non-journaling softdep.
4814  */
4815 void
4816 softdep_setup_mkdir(dp, ip)
4817         struct inode *dp;
4818         struct inode *ip;
4819 {
4820         struct inodedep *inodedep;
4821         struct jaddref *dotdotaddref;
4822         struct jaddref *dotaddref;
4823         struct jaddref *jaddref;
4824         struct vnode *dvp;
4825
4826         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4827             ("softdep_setup_mkdir called on non-softdep filesystem"));
4828         dvp = ITOV(dp);
4829         dotaddref = dotdotaddref = NULL;
4830         if (DOINGSUJ(dvp)) {
4831                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4832                     ip->i_mode);
4833                 dotaddref->ja_state |= MKDIR_BODY;
4834                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4835                     dp->i_effnlink - 1, dp->i_mode);
4836                 dotdotaddref->ja_state |= MKDIR_PARENT;
4837         }
4838         ACQUIRE_LOCK(ITOUMP(dp));
4839         inodedep = inodedep_lookup_ip(ip);
4840         if (DOINGSUJ(dvp)) {
4841                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4842                     inoreflst);
4843                 KASSERT(jaddref != NULL,
4844                     ("softdep_setup_mkdir: No addref structure present."));
4845                 KASSERT(jaddref->ja_parent == dp->i_number, 
4846                     ("softdep_setup_mkdir: bad parent %ju",
4847                     (uintmax_t)jaddref->ja_parent));
4848                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4849                     if_deps);
4850         }
4851         inodedep = inodedep_lookup_ip(dp);
4852         if (DOINGSUJ(dvp))
4853                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4854                     &dotdotaddref->ja_ref, if_deps);
4855         softdep_prelink(ITOV(dp), NULL);
4856         FREE_LOCK(ITOUMP(dp));
4857 }
4858
4859 /*
4860  * Called to track nlinkdelta of the inode and parent directories prior to
4861  * unlinking a directory.
4862  */
4863 void
4864 softdep_setup_rmdir(dp, ip)
4865         struct inode *dp;
4866         struct inode *ip;
4867 {
4868         struct vnode *dvp;
4869
4870         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4871             ("softdep_setup_rmdir called on non-softdep filesystem"));
4872         dvp = ITOV(dp);
4873         ACQUIRE_LOCK(ITOUMP(dp));
4874         (void) inodedep_lookup_ip(ip);
4875         (void) inodedep_lookup_ip(dp);
4876         softdep_prelink(dvp, ITOV(ip));
4877         FREE_LOCK(ITOUMP(dp));
4878 }
4879
4880 /*
4881  * Called to track nlinkdelta of the inode and parent directories prior to
4882  * unlink.
4883  */
4884 void
4885 softdep_setup_unlink(dp, ip)
4886         struct inode *dp;
4887         struct inode *ip;
4888 {
4889         struct vnode *dvp;
4890
4891         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4892             ("softdep_setup_unlink called on non-softdep filesystem"));
4893         dvp = ITOV(dp);
4894         ACQUIRE_LOCK(ITOUMP(dp));
4895         (void) inodedep_lookup_ip(ip);
4896         (void) inodedep_lookup_ip(dp);
4897         softdep_prelink(dvp, ITOV(ip));
4898         FREE_LOCK(ITOUMP(dp));
4899 }
4900
4901 /*
4902  * Called to release the journal structures created by a failed non-directory
4903  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4904  */
4905 void
4906 softdep_revert_create(dp, ip)
4907         struct inode *dp;
4908         struct inode *ip;
4909 {
4910         struct inodedep *inodedep;
4911         struct jaddref *jaddref;
4912         struct vnode *dvp;
4913
4914         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4915             ("softdep_revert_create called on non-softdep filesystem"));
4916         dvp = ITOV(dp);
4917         ACQUIRE_LOCK(ITOUMP(dp));
4918         inodedep = inodedep_lookup_ip(ip);
4919         if (DOINGSUJ(dvp)) {
4920                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4921                     inoreflst);
4922                 KASSERT(jaddref->ja_parent == dp->i_number,
4923                     ("softdep_revert_create: addref parent mismatch"));
4924                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4925         }
4926         FREE_LOCK(ITOUMP(dp));
4927 }
4928
4929 /*
4930  * Called to release the journal structures created by a failed link
4931  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4932  */
4933 void
4934 softdep_revert_link(dp, ip)
4935         struct inode *dp;
4936         struct inode *ip;
4937 {
4938         struct inodedep *inodedep;
4939         struct jaddref *jaddref;
4940         struct vnode *dvp;
4941
4942         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4943             ("softdep_revert_link called on non-softdep filesystem"));
4944         dvp = ITOV(dp);
4945         ACQUIRE_LOCK(ITOUMP(dp));
4946         inodedep = inodedep_lookup_ip(ip);
4947         if (DOINGSUJ(dvp)) {
4948                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4949                     inoreflst);
4950                 KASSERT(jaddref->ja_parent == dp->i_number,
4951                     ("softdep_revert_link: addref parent mismatch"));
4952                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4953         }
4954         FREE_LOCK(ITOUMP(dp));
4955 }
4956
4957 /*
4958  * Called to release the journal structures created by a failed mkdir
4959  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4960  */
4961 void
4962 softdep_revert_mkdir(dp, ip)
4963         struct inode *dp;
4964         struct inode *ip;
4965 {
4966         struct inodedep *inodedep;
4967         struct jaddref *jaddref;
4968         struct jaddref *dotaddref;
4969         struct vnode *dvp;
4970
4971         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4972             ("softdep_revert_mkdir called on non-softdep filesystem"));
4973         dvp = ITOV(dp);
4974
4975         ACQUIRE_LOCK(ITOUMP(dp));
4976         inodedep = inodedep_lookup_ip(dp);
4977         if (DOINGSUJ(dvp)) {
4978                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4979                     inoreflst);
4980                 KASSERT(jaddref->ja_parent == ip->i_number,
4981                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4982                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4983         }
4984         inodedep = inodedep_lookup_ip(ip);
4985         if (DOINGSUJ(dvp)) {
4986                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4987                     inoreflst);
4988                 KASSERT(jaddref->ja_parent == dp->i_number,
4989                     ("softdep_revert_mkdir: addref parent mismatch"));
4990                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4991                     inoreflst, if_deps);
4992                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4993                 KASSERT(dotaddref->ja_parent == ip->i_number,
4994                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4995                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4996         }
4997         FREE_LOCK(ITOUMP(dp));
4998 }
4999
5000 /* 
5001  * Called to correct nlinkdelta after a failed rmdir.
5002  */
5003 void
5004 softdep_revert_rmdir(dp, ip)
5005         struct inode *dp;
5006         struct inode *ip;
5007 {
5008
5009         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5010             ("softdep_revert_rmdir called on non-softdep filesystem"));
5011         ACQUIRE_LOCK(ITOUMP(dp));
5012         (void) inodedep_lookup_ip(ip);
5013         (void) inodedep_lookup_ip(dp);
5014         FREE_LOCK(ITOUMP(dp));
5015 }
5016
5017 /*
5018  * Protecting the freemaps (or bitmaps).
5019  * 
5020  * To eliminate the need to execute fsck before mounting a filesystem
5021  * after a power failure, one must (conservatively) guarantee that the
5022  * on-disk copy of the bitmaps never indicate that a live inode or block is
5023  * free.  So, when a block or inode is allocated, the bitmap should be
5024  * updated (on disk) before any new pointers.  When a block or inode is
5025  * freed, the bitmap should not be updated until all pointers have been
5026  * reset.  The latter dependency is handled by the delayed de-allocation
5027  * approach described below for block and inode de-allocation.  The former
5028  * dependency is handled by calling the following procedure when a block or
5029  * inode is allocated. When an inode is allocated an "inodedep" is created
5030  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5031  * Each "inodedep" is also inserted into the hash indexing structure so
5032  * that any additional link additions can be made dependent on the inode
5033  * allocation.
5034  * 
5035  * The ufs filesystem maintains a number of free block counts (e.g., per
5036  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5037  * in addition to the bitmaps.  These counts are used to improve efficiency
5038  * during allocation and therefore must be consistent with the bitmaps.
5039  * There is no convenient way to guarantee post-crash consistency of these
5040  * counts with simple update ordering, for two main reasons: (1) The counts
5041  * and bitmaps for a single cylinder group block are not in the same disk
5042  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5043  * be written and the other not.  (2) Some of the counts are located in the
5044  * superblock rather than the cylinder group block. So, we focus our soft
5045  * updates implementation on protecting the bitmaps. When mounting a
5046  * filesystem, we recompute the auxiliary counts from the bitmaps.
5047  */
5048
5049 /*
5050  * Called just after updating the cylinder group block to allocate an inode.
5051  */
5052 void
5053 softdep_setup_inomapdep(bp, ip, newinum, mode)
5054         struct buf *bp;         /* buffer for cylgroup block with inode map */
5055         struct inode *ip;       /* inode related to allocation */
5056         ino_t newinum;          /* new inode number being allocated */
5057         int mode;
5058 {
5059         struct inodedep *inodedep;
5060         struct bmsafemap *bmsafemap;
5061         struct jaddref *jaddref;
5062         struct mount *mp;
5063         struct fs *fs;
5064
5065         mp = ITOVFS(ip);
5066         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5067             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5068         fs = VFSTOUFS(mp)->um_fs;
5069         jaddref = NULL;
5070
5071         /*
5072          * Allocate the journal reference add structure so that the bitmap
5073          * can be dependent on it.
5074          */
5075         if (MOUNTEDSUJ(mp)) {
5076                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5077                 jaddref->ja_state |= NEWBLOCK;
5078         }
5079
5080         /*
5081          * Create a dependency for the newly allocated inode.
5082          * Panic if it already exists as something is seriously wrong.
5083          * Otherwise add it to the dependency list for the buffer holding
5084          * the cylinder group map from which it was allocated.
5085          *
5086          * We have to preallocate a bmsafemap entry in case it is needed
5087          * in bmsafemap_lookup since once we allocate the inodedep, we
5088          * have to finish initializing it before we can FREE_LOCK().
5089          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5090          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5091          * creating the inodedep as it can be freed during the time
5092          * that we FREE_LOCK() while allocating the inodedep. We must
5093          * call workitem_alloc() before entering the locked section as
5094          * it also acquires the lock and we must avoid trying doing so
5095          * recursively.
5096          */
5097         bmsafemap = malloc(sizeof(struct bmsafemap),
5098             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5099         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5100         ACQUIRE_LOCK(ITOUMP(ip));
5101         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5102                 panic("softdep_setup_inomapdep: dependency %p for new"
5103                     "inode already exists", inodedep);
5104         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5105         if (jaddref) {
5106                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5107                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5108                     if_deps);
5109         } else {
5110                 inodedep->id_state |= ONDEPLIST;
5111                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5112         }
5113         inodedep->id_bmsafemap = bmsafemap;
5114         inodedep->id_state &= ~DEPCOMPLETE;
5115         FREE_LOCK(ITOUMP(ip));
5116 }
5117
5118 /*
5119  * Called just after updating the cylinder group block to
5120  * allocate block or fragment.
5121  */
5122 void
5123 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5124         struct buf *bp;         /* buffer for cylgroup block with block map */
5125         struct mount *mp;       /* filesystem doing allocation */
5126         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5127         int frags;              /* Number of fragments. */
5128         int oldfrags;           /* Previous number of fragments for extend. */
5129 {
5130         struct newblk *newblk;
5131         struct bmsafemap *bmsafemap;
5132         struct jnewblk *jnewblk;
5133         struct ufsmount *ump;
5134         struct fs *fs;
5135
5136         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5137             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5138         ump = VFSTOUFS(mp);
5139         fs = ump->um_fs;
5140         jnewblk = NULL;
5141         /*
5142          * Create a dependency for the newly allocated block.
5143          * Add it to the dependency list for the buffer holding
5144          * the cylinder group map from which it was allocated.
5145          */
5146         if (MOUNTEDSUJ(mp)) {
5147                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5148                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5149                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5150                 jnewblk->jn_state = ATTACHED;
5151                 jnewblk->jn_blkno = newblkno;
5152                 jnewblk->jn_frags = frags;
5153                 jnewblk->jn_oldfrags = oldfrags;
5154 #ifdef INVARIANTS
5155                 {
5156                         struct cg *cgp;
5157                         uint8_t *blksfree;
5158                         long bno;
5159                         int i;
5160         
5161                         cgp = (struct cg *)bp->b_data;
5162                         blksfree = cg_blksfree(cgp);
5163                         bno = dtogd(fs, jnewblk->jn_blkno);
5164                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5165                             i++) {
5166                                 if (isset(blksfree, bno + i))
5167                                         panic("softdep_setup_blkmapdep: "
5168                                             "free fragment %d from %d-%d "
5169                                             "state 0x%X dep %p", i,
5170                                             jnewblk->jn_oldfrags,
5171                                             jnewblk->jn_frags,
5172                                             jnewblk->jn_state,
5173                                             jnewblk->jn_dep);
5174                         }
5175                 }
5176 #endif
5177         }
5178
5179         CTR3(KTR_SUJ,
5180             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5181             newblkno, frags, oldfrags);
5182         ACQUIRE_LOCK(ump);
5183         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5184                 panic("softdep_setup_blkmapdep: found block");
5185         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5186             dtog(fs, newblkno), NULL);
5187         if (jnewblk) {
5188                 jnewblk->jn_dep = (struct worklist *)newblk;
5189                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5190         } else {
5191                 newblk->nb_state |= ONDEPLIST;
5192                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5193         }
5194         newblk->nb_bmsafemap = bmsafemap;
5195         newblk->nb_jnewblk = jnewblk;
5196         FREE_LOCK(ump);
5197 }
5198
5199 #define BMSAFEMAP_HASH(ump, cg) \
5200       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5201
5202 static int
5203 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5204         struct bmsafemap_hashhead *bmsafemaphd;
5205         int cg;
5206         struct bmsafemap **bmsafemapp;
5207 {
5208         struct bmsafemap *bmsafemap;
5209
5210         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5211                 if (bmsafemap->sm_cg == cg)
5212                         break;
5213         if (bmsafemap) {
5214                 *bmsafemapp = bmsafemap;
5215                 return (1);
5216         }
5217         *bmsafemapp = NULL;
5218
5219         return (0);
5220 }
5221
5222 /*
5223  * Find the bmsafemap associated with a cylinder group buffer.
5224  * If none exists, create one. The buffer must be locked when
5225  * this routine is called and this routine must be called with
5226  * the softdep lock held. To avoid giving up the lock while
5227  * allocating a new bmsafemap, a preallocated bmsafemap may be
5228  * provided. If it is provided but not needed, it is freed.
5229  */
5230 static struct bmsafemap *
5231 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5232         struct mount *mp;
5233         struct buf *bp;
5234         int cg;
5235         struct bmsafemap *newbmsafemap;
5236 {
5237         struct bmsafemap_hashhead *bmsafemaphd;
5238         struct bmsafemap *bmsafemap, *collision;
5239         struct worklist *wk;
5240         struct ufsmount *ump;
5241
5242         ump = VFSTOUFS(mp);
5243         LOCK_OWNED(ump);
5244         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5245         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5246                 if (wk->wk_type == D_BMSAFEMAP) {
5247                         if (newbmsafemap)
5248                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5249                         return (WK_BMSAFEMAP(wk));
5250                 }
5251         }
5252         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5253         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5254                 if (newbmsafemap)
5255                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5256                 return (bmsafemap);
5257         }
5258         if (newbmsafemap) {
5259                 bmsafemap = newbmsafemap;
5260         } else {
5261                 FREE_LOCK(ump);
5262                 bmsafemap = malloc(sizeof(struct bmsafemap),
5263                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5264                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5265                 ACQUIRE_LOCK(ump);
5266         }
5267         bmsafemap->sm_buf = bp;
5268         LIST_INIT(&bmsafemap->sm_inodedephd);
5269         LIST_INIT(&bmsafemap->sm_inodedepwr);
5270         LIST_INIT(&bmsafemap->sm_newblkhd);
5271         LIST_INIT(&bmsafemap->sm_newblkwr);
5272         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5273         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5274         LIST_INIT(&bmsafemap->sm_freehd);
5275         LIST_INIT(&bmsafemap->sm_freewr);
5276         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5277                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5278                 return (collision);
5279         }
5280         bmsafemap->sm_cg = cg;
5281         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5282         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5283         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5284         return (bmsafemap);
5285 }
5286
5287 /*
5288  * Direct block allocation dependencies.
5289  * 
5290  * When a new block is allocated, the corresponding disk locations must be
5291  * initialized (with zeros or new data) before the on-disk inode points to
5292  * them.  Also, the freemap from which the block was allocated must be
5293  * updated (on disk) before the inode's pointer. These two dependencies are
5294  * independent of each other and are needed for all file blocks and indirect
5295  * blocks that are pointed to directly by the inode.  Just before the
5296  * "in-core" version of the inode is updated with a newly allocated block
5297  * number, a procedure (below) is called to setup allocation dependency
5298  * structures.  These structures are removed when the corresponding
5299  * dependencies are satisfied or when the block allocation becomes obsolete
5300  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5301  * fragment that gets upgraded).  All of these cases are handled in
5302  * procedures described later.
5303  * 
5304  * When a file extension causes a fragment to be upgraded, either to a larger
5305  * fragment or to a full block, the on-disk location may change (if the
5306  * previous fragment could not simply be extended). In this case, the old
5307  * fragment must be de-allocated, but not until after the inode's pointer has
5308  * been updated. In most cases, this is handled by later procedures, which
5309  * will construct a "freefrag" structure to be added to the workitem queue
5310  * when the inode update is complete (or obsolete).  The main exception to
5311  * this is when an allocation occurs while a pending allocation dependency
5312  * (for the same block pointer) remains.  This case is handled in the main
5313  * allocation dependency setup procedure by immediately freeing the
5314  * unreferenced fragments.
5315  */ 
5316 void 
5317 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5318         struct inode *ip;       /* inode to which block is being added */
5319         ufs_lbn_t off;          /* block pointer within inode */
5320         ufs2_daddr_t newblkno;  /* disk block number being added */
5321         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5322         long newsize;           /* size of new block */
5323         long oldsize;           /* size of new block */
5324         struct buf *bp;         /* bp for allocated block */
5325 {
5326         struct allocdirect *adp, *oldadp;
5327         struct allocdirectlst *adphead;
5328         struct freefrag *freefrag;
5329         struct inodedep *inodedep;
5330         struct pagedep *pagedep;
5331         struct jnewblk *jnewblk;
5332         struct newblk *newblk;
5333         struct mount *mp;
5334         ufs_lbn_t lbn;
5335
5336         lbn = bp->b_lblkno;
5337         mp = ITOVFS(ip);
5338         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5339             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5340         if (oldblkno && oldblkno != newblkno)
5341                 /*
5342                  * The usual case is that a smaller fragment that
5343                  * was just allocated has been replaced with a bigger
5344                  * fragment or a full-size block. If it is marked as
5345                  * B_DELWRI, the current contents have not been written
5346                  * to disk. It is possible that the block was written
5347                  * earlier, but very uncommon. If the block has never
5348                  * been written, there is no need to send a BIO_DELETE
5349                  * for it when it is freed. The gain from avoiding the
5350                  * TRIMs for the common case of unwritten blocks far
5351                  * exceeds the cost of the write amplification for the
5352                  * uncommon case of failing to send a TRIM for a block
5353                  * that had been written.
5354                  */
5355                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5356                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5357         else
5358                 freefrag = NULL;
5359
5360         CTR6(KTR_SUJ,
5361             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5362             "off %jd newsize %ld oldsize %d",
5363             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5364         ACQUIRE_LOCK(ITOUMP(ip));
5365         if (off >= UFS_NDADDR) {
5366                 if (lbn > 0)
5367                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5368                             lbn, off);
5369                 /* allocating an indirect block */
5370                 if (oldblkno != 0)
5371                         panic("softdep_setup_allocdirect: non-zero indir");
5372         } else {
5373                 if (off != lbn)
5374                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5375                             lbn, off);
5376                 /*
5377                  * Allocating a direct block.
5378                  *
5379                  * If we are allocating a directory block, then we must
5380                  * allocate an associated pagedep to track additions and
5381                  * deletions.
5382                  */
5383                 if ((ip->i_mode & IFMT) == IFDIR)
5384                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5385                             &pagedep);
5386         }
5387         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5388                 panic("softdep_setup_allocdirect: lost block");
5389         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5390             ("softdep_setup_allocdirect: newblk already initialized"));
5391         /*
5392          * Convert the newblk to an allocdirect.
5393          */
5394         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5395         adp = (struct allocdirect *)newblk;
5396         newblk->nb_freefrag = freefrag;
5397         adp->ad_offset = off;
5398         adp->ad_oldblkno = oldblkno;
5399         adp->ad_newsize = newsize;
5400         adp->ad_oldsize = oldsize;
5401
5402         /*
5403          * Finish initializing the journal.
5404          */
5405         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5406                 jnewblk->jn_ino = ip->i_number;
5407                 jnewblk->jn_lbn = lbn;
5408                 add_to_journal(&jnewblk->jn_list);
5409         }
5410         if (freefrag && freefrag->ff_jdep != NULL &&
5411             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5412                 add_to_journal(freefrag->ff_jdep);
5413         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5414         adp->ad_inodedep = inodedep;
5415
5416         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5417         /*
5418          * The list of allocdirects must be kept in sorted and ascending
5419          * order so that the rollback routines can quickly determine the
5420          * first uncommitted block (the size of the file stored on disk
5421          * ends at the end of the lowest committed fragment, or if there
5422          * are no fragments, at the end of the highest committed block).
5423          * Since files generally grow, the typical case is that the new
5424          * block is to be added at the end of the list. We speed this
5425          * special case by checking against the last allocdirect in the
5426          * list before laboriously traversing the list looking for the
5427          * insertion point.
5428          */
5429         adphead = &inodedep->id_newinoupdt;
5430         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5431         if (oldadp == NULL || oldadp->ad_offset <= off) {
5432                 /* insert at end of list */
5433                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5434                 if (oldadp != NULL && oldadp->ad_offset == off)
5435                         allocdirect_merge(adphead, adp, oldadp);
5436                 FREE_LOCK(ITOUMP(ip));
5437                 return;
5438         }
5439         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5440                 if (oldadp->ad_offset >= off)
5441                         break;
5442         }
5443         if (oldadp == NULL)
5444                 panic("softdep_setup_allocdirect: lost entry");
5445         /* insert in middle of list */
5446         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5447         if (oldadp->ad_offset == off)
5448                 allocdirect_merge(adphead, adp, oldadp);
5449
5450         FREE_LOCK(ITOUMP(ip));
5451 }
5452
5453 /*
5454  * Merge a newer and older journal record to be stored either in a
5455  * newblock or freefrag.  This handles aggregating journal records for
5456  * fragment allocation into a second record as well as replacing a
5457  * journal free with an aborted journal allocation.  A segment for the
5458  * oldest record will be placed on wkhd if it has been written.  If not
5459  * the segment for the newer record will suffice.
5460  */
5461 static struct worklist *
5462 jnewblk_merge(new, old, wkhd)
5463         struct worklist *new;
5464         struct worklist *old;
5465         struct workhead *wkhd;
5466 {
5467         struct jnewblk *njnewblk;
5468         struct jnewblk *jnewblk;
5469
5470         /* Handle NULLs to simplify callers. */
5471         if (new == NULL)
5472                 return (old);
5473         if (old == NULL)
5474                 return (new);
5475         /* Replace a jfreefrag with a jnewblk. */
5476         if (new->wk_type == D_JFREEFRAG) {
5477                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5478                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5479                             old, new);
5480                 cancel_jfreefrag(WK_JFREEFRAG(new));
5481                 return (old);
5482         }
5483         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5484                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5485                     old->wk_type, new->wk_type);
5486         /*
5487          * Handle merging of two jnewblk records that describe
5488          * different sets of fragments in the same block.
5489          */
5490         jnewblk = WK_JNEWBLK(old);
5491         njnewblk = WK_JNEWBLK(new);
5492         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5493                 panic("jnewblk_merge: Merging disparate blocks.");
5494         /*
5495          * The record may be rolled back in the cg.
5496          */
5497         if (jnewblk->jn_state & UNDONE) {
5498                 jnewblk->jn_state &= ~UNDONE;
5499                 njnewblk->jn_state |= UNDONE;
5500                 njnewblk->jn_state &= ~ATTACHED;
5501         }
5502         /*
5503          * We modify the newer addref and free the older so that if neither
5504          * has been written the most up-to-date copy will be on disk.  If
5505          * both have been written but rolled back we only temporarily need
5506          * one of them to fix the bits when the cg write completes.
5507          */
5508         jnewblk->jn_state |= ATTACHED | COMPLETE;
5509         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5510         cancel_jnewblk(jnewblk, wkhd);
5511         WORKLIST_REMOVE(&jnewblk->jn_list);
5512         free_jnewblk(jnewblk);
5513         return (new);
5514 }
5515
5516 /*
5517  * Replace an old allocdirect dependency with a newer one.
5518  */
5519 static void
5520 allocdirect_merge(adphead, newadp, oldadp)
5521         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5522         struct allocdirect *newadp;     /* allocdirect being added */
5523         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5524 {
5525         struct worklist *wk;
5526         struct freefrag *freefrag;
5527
5528         freefrag = NULL;
5529         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5530         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5531             newadp->ad_oldsize != oldadp->ad_newsize ||
5532             newadp->ad_offset >= UFS_NDADDR)
5533                 panic("%s %jd != new %jd || old size %ld != new %ld",
5534                     "allocdirect_merge: old blkno",
5535                     (intmax_t)newadp->ad_oldblkno,
5536                     (intmax_t)oldadp->ad_newblkno,
5537                     newadp->ad_oldsize, oldadp->ad_newsize);
5538         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5539         newadp->ad_oldsize = oldadp->ad_oldsize;
5540         /*
5541          * If the old dependency had a fragment to free or had never
5542          * previously had a block allocated, then the new dependency
5543          * can immediately post its freefrag and adopt the old freefrag.
5544          * This action is done by swapping the freefrag dependencies.
5545          * The new dependency gains the old one's freefrag, and the
5546          * old one gets the new one and then immediately puts it on
5547          * the worklist when it is freed by free_newblk. It is
5548          * not possible to do this swap when the old dependency had a
5549          * non-zero size but no previous fragment to free. This condition
5550          * arises when the new block is an extension of the old block.
5551          * Here, the first part of the fragment allocated to the new
5552          * dependency is part of the block currently claimed on disk by
5553          * the old dependency, so cannot legitimately be freed until the
5554          * conditions for the new dependency are fulfilled.
5555          */
5556         freefrag = newadp->ad_freefrag;
5557         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5558                 newadp->ad_freefrag = oldadp->ad_freefrag;
5559                 oldadp->ad_freefrag = freefrag;
5560         }
5561         /*
5562          * If we are tracking a new directory-block allocation,
5563          * move it from the old allocdirect to the new allocdirect.
5564          */
5565         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5566                 WORKLIST_REMOVE(wk);
5567                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5568                         panic("allocdirect_merge: extra newdirblk");
5569                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5570         }
5571         TAILQ_REMOVE(adphead, oldadp, ad_next);
5572         /*
5573          * We need to move any journal dependencies over to the freefrag
5574          * that releases this block if it exists.  Otherwise we are
5575          * extending an existing block and we'll wait until that is
5576          * complete to release the journal space and extend the
5577          * new journal to cover this old space as well.
5578          */
5579         if (freefrag == NULL) {
5580                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5581                         panic("allocdirect_merge: %jd != %jd",
5582                             oldadp->ad_newblkno, newadp->ad_newblkno);
5583                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5584                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5585                     &oldadp->ad_block.nb_jnewblk->jn_list,
5586                     &newadp->ad_block.nb_jwork);
5587                 oldadp->ad_block.nb_jnewblk = NULL;
5588                 cancel_newblk(&oldadp->ad_block, NULL,
5589                     &newadp->ad_block.nb_jwork);
5590         } else {
5591                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5592                     &freefrag->ff_list, &freefrag->ff_jwork);
5593                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5594                     &freefrag->ff_jwork);
5595         }
5596         free_newblk(&oldadp->ad_block);
5597 }
5598
5599 /*
5600  * Allocate a jfreefrag structure to journal a single block free.
5601  */
5602 static struct jfreefrag *
5603 newjfreefrag(freefrag, ip, blkno, size, lbn)
5604         struct freefrag *freefrag;
5605         struct inode *ip;
5606         ufs2_daddr_t blkno;
5607         long size;
5608         ufs_lbn_t lbn;
5609 {
5610         struct jfreefrag *jfreefrag;
5611         struct fs *fs;
5612
5613         fs = ITOFS(ip);
5614         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5615             M_SOFTDEP_FLAGS);
5616         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5617         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5618         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5619         jfreefrag->fr_ino = ip->i_number;
5620         jfreefrag->fr_lbn = lbn;
5621         jfreefrag->fr_blkno = blkno;
5622         jfreefrag->fr_frags = numfrags(fs, size);
5623         jfreefrag->fr_freefrag = freefrag;
5624
5625         return (jfreefrag);
5626 }
5627
5628 /*
5629  * Allocate a new freefrag structure.
5630  */
5631 static struct freefrag *
5632 newfreefrag(ip, blkno, size, lbn, key)
5633         struct inode *ip;
5634         ufs2_daddr_t blkno;
5635         long size;
5636         ufs_lbn_t lbn;
5637         u_long key;
5638 {
5639         struct freefrag *freefrag;
5640         struct ufsmount *ump;
5641         struct fs *fs;
5642
5643         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5644             ip->i_number, blkno, size, lbn);
5645         ump = ITOUMP(ip);
5646         fs = ump->um_fs;
5647         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5648                 panic("newfreefrag: frag size");
5649         freefrag = malloc(sizeof(struct freefrag),
5650             M_FREEFRAG, M_SOFTDEP_FLAGS);
5651         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5652         freefrag->ff_state = ATTACHED;
5653         LIST_INIT(&freefrag->ff_jwork);
5654         freefrag->ff_inum = ip->i_number;
5655         freefrag->ff_vtype = ITOV(ip)->v_type;
5656         freefrag->ff_blkno = blkno;
5657         freefrag->ff_fragsize = size;
5658         freefrag->ff_key = key;
5659
5660         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5661                 freefrag->ff_jdep = (struct worklist *)
5662                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5663         } else {
5664                 freefrag->ff_state |= DEPCOMPLETE;
5665                 freefrag->ff_jdep = NULL;
5666         }
5667
5668         return (freefrag);
5669 }
5670
5671 /*
5672  * This workitem de-allocates fragments that were replaced during
5673  * file block allocation.
5674  */
5675 static void 
5676 handle_workitem_freefrag(freefrag)
5677         struct freefrag *freefrag;
5678 {
5679         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5680         struct workhead wkhd;
5681
5682         CTR3(KTR_SUJ,
5683             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5684             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5685         /*
5686          * It would be illegal to add new completion items to the
5687          * freefrag after it was schedule to be done so it must be
5688          * safe to modify the list head here.
5689          */
5690         LIST_INIT(&wkhd);
5691         ACQUIRE_LOCK(ump);
5692         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5693         /*
5694          * If the journal has not been written we must cancel it here.
5695          */
5696         if (freefrag->ff_jdep) {
5697                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5698                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5699                             freefrag->ff_jdep->wk_type);
5700                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5701         }
5702         FREE_LOCK(ump);
5703         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5704            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5705            &wkhd, freefrag->ff_key);
5706         ACQUIRE_LOCK(ump);
5707         WORKITEM_FREE(freefrag, D_FREEFRAG);
5708         FREE_LOCK(ump);
5709 }
5710
5711 /*
5712  * Set up a dependency structure for an external attributes data block.
5713  * This routine follows much of the structure of softdep_setup_allocdirect.
5714  * See the description of softdep_setup_allocdirect above for details.
5715  */
5716 void 
5717 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5718         struct inode *ip;
5719         ufs_lbn_t off;
5720         ufs2_daddr_t newblkno;
5721         ufs2_daddr_t oldblkno;
5722         long newsize;
5723         long oldsize;
5724         struct buf *bp;
5725 {
5726         struct allocdirect *adp, *oldadp;
5727         struct allocdirectlst *adphead;
5728         struct freefrag *freefrag;
5729         struct inodedep *inodedep;
5730         struct jnewblk *jnewblk;
5731         struct newblk *newblk;
5732         struct mount *mp;
5733         struct ufsmount *ump;
5734         ufs_lbn_t lbn;
5735
5736         mp = ITOVFS(ip);
5737         ump = VFSTOUFS(mp);
5738         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5739             ("softdep_setup_allocext called on non-softdep filesystem"));
5740         KASSERT(off < UFS_NXADDR,
5741             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5742
5743         lbn = bp->b_lblkno;
5744         if (oldblkno && oldblkno != newblkno)
5745                 /*
5746                  * The usual case is that a smaller fragment that
5747                  * was just allocated has been replaced with a bigger
5748                  * fragment or a full-size block. If it is marked as
5749                  * B_DELWRI, the current contents have not been written
5750                  * to disk. It is possible that the block was written
5751                  * earlier, but very uncommon. If the block has never
5752                  * been written, there is no need to send a BIO_DELETE
5753                  * for it when it is freed. The gain from avoiding the
5754                  * TRIMs for the common case of unwritten blocks far
5755                  * exceeds the cost of the write amplification for the
5756                  * uncommon case of failing to send a TRIM for a block
5757                  * that had been written.
5758                  */
5759                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5760                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5761         else
5762                 freefrag = NULL;
5763
5764         ACQUIRE_LOCK(ump);
5765         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5766                 panic("softdep_setup_allocext: lost block");
5767         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5768             ("softdep_setup_allocext: newblk already initialized"));
5769         /*
5770          * Convert the newblk to an allocdirect.
5771          */
5772         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5773         adp = (struct allocdirect *)newblk;
5774         newblk->nb_freefrag = freefrag;
5775         adp->ad_offset = off;
5776         adp->ad_oldblkno = oldblkno;
5777         adp->ad_newsize = newsize;
5778         adp->ad_oldsize = oldsize;
5779         adp->ad_state |=  EXTDATA;
5780
5781         /*
5782          * Finish initializing the journal.
5783          */
5784         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5785                 jnewblk->jn_ino = ip->i_number;
5786                 jnewblk->jn_lbn = lbn;
5787                 add_to_journal(&jnewblk->jn_list);
5788         }
5789         if (freefrag && freefrag->ff_jdep != NULL &&
5790             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5791                 add_to_journal(freefrag->ff_jdep);
5792         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5793         adp->ad_inodedep = inodedep;
5794
5795         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5796         /*
5797          * The list of allocdirects must be kept in sorted and ascending
5798          * order so that the rollback routines can quickly determine the
5799          * first uncommitted block (the size of the file stored on disk
5800          * ends at the end of the lowest committed fragment, or if there
5801          * are no fragments, at the end of the highest committed block).
5802          * Since files generally grow, the typical case is that the new
5803          * block is to be added at the end of the list. We speed this
5804          * special case by checking against the last allocdirect in the
5805          * list before laboriously traversing the list looking for the
5806          * insertion point.
5807          */
5808         adphead = &inodedep->id_newextupdt;
5809         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5810         if (oldadp == NULL || oldadp->ad_offset <= off) {
5811                 /* insert at end of list */
5812                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5813                 if (oldadp != NULL && oldadp->ad_offset == off)
5814                         allocdirect_merge(adphead, adp, oldadp);
5815                 FREE_LOCK(ump);
5816                 return;
5817         }
5818         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5819                 if (oldadp->ad_offset >= off)
5820                         break;
5821         }
5822         if (oldadp == NULL)
5823                 panic("softdep_setup_allocext: lost entry");
5824         /* insert in middle of list */
5825         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5826         if (oldadp->ad_offset == off)
5827                 allocdirect_merge(adphead, adp, oldadp);
5828         FREE_LOCK(ump);
5829 }
5830
5831 /*
5832  * Indirect block allocation dependencies.
5833  * 
5834  * The same dependencies that exist for a direct block also exist when
5835  * a new block is allocated and pointed to by an entry in a block of
5836  * indirect pointers. The undo/redo states described above are also
5837  * used here. Because an indirect block contains many pointers that
5838  * may have dependencies, a second copy of the entire in-memory indirect
5839  * block is kept. The buffer cache copy is always completely up-to-date.
5840  * The second copy, which is used only as a source for disk writes,
5841  * contains only the safe pointers (i.e., those that have no remaining
5842  * update dependencies). The second copy is freed when all pointers
5843  * are safe. The cache is not allowed to replace indirect blocks with
5844  * pending update dependencies. If a buffer containing an indirect
5845  * block with dependencies is written, these routines will mark it
5846  * dirty again. It can only be successfully written once all the
5847  * dependencies are removed. The ffs_fsync routine in conjunction with
5848  * softdep_sync_metadata work together to get all the dependencies
5849  * removed so that a file can be successfully written to disk. Three
5850  * procedures are used when setting up indirect block pointer
5851  * dependencies. The division is necessary because of the organization
5852  * of the "balloc" routine and because of the distinction between file
5853  * pages and file metadata blocks.
5854  */
5855
5856 /*
5857  * Allocate a new allocindir structure.
5858  */
5859 static struct allocindir *
5860 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5861         struct inode *ip;       /* inode for file being extended */
5862         int ptrno;              /* offset of pointer in indirect block */
5863         ufs2_daddr_t newblkno;  /* disk block number being added */
5864         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5865         ufs_lbn_t lbn;
5866 {
5867         struct newblk *newblk;
5868         struct allocindir *aip;
5869         struct freefrag *freefrag;
5870         struct jnewblk *jnewblk;
5871
5872         if (oldblkno)
5873                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5874                     SINGLETON_KEY);
5875         else
5876                 freefrag = NULL;
5877         ACQUIRE_LOCK(ITOUMP(ip));
5878         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5879                 panic("new_allocindir: lost block");
5880         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5881             ("newallocindir: newblk already initialized"));
5882         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5883         newblk->nb_freefrag = freefrag;
5884         aip = (struct allocindir *)newblk;
5885         aip->ai_offset = ptrno;
5886         aip->ai_oldblkno = oldblkno;
5887         aip->ai_lbn = lbn;
5888         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5889                 jnewblk->jn_ino = ip->i_number;
5890                 jnewblk->jn_lbn = lbn;
5891                 add_to_journal(&jnewblk->jn_list);
5892         }
5893         if (freefrag && freefrag->ff_jdep != NULL &&
5894             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5895                 add_to_journal(freefrag->ff_jdep);
5896         return (aip);
5897 }
5898
5899 /*
5900  * Called just before setting an indirect block pointer
5901  * to a newly allocated file page.
5902  */
5903 void
5904 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5905         struct inode *ip;       /* inode for file being extended */
5906         ufs_lbn_t lbn;          /* allocated block number within file */
5907         struct buf *bp;         /* buffer with indirect blk referencing page */
5908         int ptrno;              /* offset of pointer in indirect block */
5909         ufs2_daddr_t newblkno;  /* disk block number being added */
5910         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5911         struct buf *nbp;        /* buffer holding allocated page */
5912 {
5913         struct inodedep *inodedep;
5914         struct freefrag *freefrag;
5915         struct allocindir *aip;
5916         struct pagedep *pagedep;
5917         struct mount *mp;
5918         struct ufsmount *ump;
5919
5920         mp = ITOVFS(ip);
5921         ump = VFSTOUFS(mp);
5922         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5923             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5924         KASSERT(lbn == nbp->b_lblkno,
5925             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5926             lbn, bp->b_lblkno));
5927         CTR4(KTR_SUJ,
5928             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5929             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5930         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5931         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5932         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5933         /*
5934          * If we are allocating a directory page, then we must
5935          * allocate an associated pagedep to track additions and
5936          * deletions.
5937          */
5938         if ((ip->i_mode & IFMT) == IFDIR)
5939                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5940         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5941         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5942         FREE_LOCK(ump);
5943         if (freefrag)
5944                 handle_workitem_freefrag(freefrag);
5945 }
5946
5947 /*
5948  * Called just before setting an indirect block pointer to a
5949  * newly allocated indirect block.
5950  */
5951 void
5952 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5953         struct buf *nbp;        /* newly allocated indirect block */
5954         struct inode *ip;       /* inode for file being extended */
5955         struct buf *bp;         /* indirect block referencing allocated block */
5956         int ptrno;              /* offset of pointer in indirect block */
5957         ufs2_daddr_t newblkno;  /* disk block number being added */
5958 {
5959         struct inodedep *inodedep;
5960         struct allocindir *aip;
5961         struct ufsmount *ump;
5962         ufs_lbn_t lbn;
5963
5964         ump = ITOUMP(ip);
5965         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5966             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5967         CTR3(KTR_SUJ,
5968             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5969             ip->i_number, newblkno, ptrno);
5970         lbn = nbp->b_lblkno;
5971         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5972         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5973         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5974         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5975         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5976                 panic("softdep_setup_allocindir_meta: Block already existed");
5977         FREE_LOCK(ump);
5978 }
5979
5980 static void
5981 indirdep_complete(indirdep)
5982         struct indirdep *indirdep;
5983 {
5984         struct allocindir *aip;
5985
5986         LIST_REMOVE(indirdep, ir_next);
5987         indirdep->ir_state |= DEPCOMPLETE;
5988
5989         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5990                 LIST_REMOVE(aip, ai_next);
5991                 free_newblk(&aip->ai_block);
5992         }
5993         /*
5994          * If this indirdep is not attached to a buf it was simply waiting
5995          * on completion to clear completehd.  free_indirdep() asserts
5996          * that nothing is dangling.
5997          */
5998         if ((indirdep->ir_state & ONWORKLIST) == 0)
5999                 free_indirdep(indirdep);
6000 }
6001
6002 static struct indirdep *
6003 indirdep_lookup(mp, ip, bp)
6004         struct mount *mp;
6005         struct inode *ip;
6006         struct buf *bp;
6007 {
6008         struct indirdep *indirdep, *newindirdep;
6009         struct newblk *newblk;
6010         struct ufsmount *ump;
6011         struct worklist *wk;
6012         struct fs *fs;
6013         ufs2_daddr_t blkno;
6014
6015         ump = VFSTOUFS(mp);
6016         LOCK_OWNED(ump);
6017         indirdep = NULL;
6018         newindirdep = NULL;
6019         fs = ump->um_fs;
6020         for (;;) {
6021                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6022                         if (wk->wk_type != D_INDIRDEP)
6023                                 continue;
6024                         indirdep = WK_INDIRDEP(wk);
6025                         break;
6026                 }
6027                 /* Found on the buffer worklist, no new structure to free. */
6028                 if (indirdep != NULL && newindirdep == NULL)
6029                         return (indirdep);
6030                 if (indirdep != NULL && newindirdep != NULL)
6031                         panic("indirdep_lookup: simultaneous create");
6032                 /* None found on the buffer and a new structure is ready. */
6033                 if (indirdep == NULL && newindirdep != NULL)
6034                         break;
6035                 /* None found and no new structure available. */
6036                 FREE_LOCK(ump);
6037                 newindirdep = malloc(sizeof(struct indirdep),
6038                     M_INDIRDEP, M_SOFTDEP_FLAGS);
6039                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6040                 newindirdep->ir_state = ATTACHED;
6041                 if (I_IS_UFS1(ip))
6042                         newindirdep->ir_state |= UFS1FMT;
6043                 TAILQ_INIT(&newindirdep->ir_trunc);
6044                 newindirdep->ir_saveddata = NULL;
6045                 LIST_INIT(&newindirdep->ir_deplisthd);
6046                 LIST_INIT(&newindirdep->ir_donehd);
6047                 LIST_INIT(&newindirdep->ir_writehd);
6048                 LIST_INIT(&newindirdep->ir_completehd);
6049                 if (bp->b_blkno == bp->b_lblkno) {
6050                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6051                             NULL, NULL);
6052                         bp->b_blkno = blkno;
6053                 }
6054                 newindirdep->ir_freeblks = NULL;
6055                 newindirdep->ir_savebp =
6056                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6057                 newindirdep->ir_bp = bp;
6058                 BUF_KERNPROC(newindirdep->ir_savebp);
6059                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6060                 ACQUIRE_LOCK(ump);
6061         }
6062         indirdep = newindirdep;
6063         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6064         /*
6065          * If the block is not yet allocated we don't set DEPCOMPLETE so
6066          * that we don't free dependencies until the pointers are valid.
6067          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6068          * than using the hash.
6069          */
6070         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6071                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6072         else
6073                 indirdep->ir_state |= DEPCOMPLETE;
6074         return (indirdep);
6075 }
6076
6077 /*
6078  * Called to finish the allocation of the "aip" allocated
6079  * by one of the two routines above.
6080  */
6081 static struct freefrag *
6082 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6083         struct buf *bp;         /* in-memory copy of the indirect block */
6084         struct inode *ip;       /* inode for file being extended */
6085         struct inodedep *inodedep; /* Inodedep for ip */
6086         struct allocindir *aip; /* allocindir allocated by the above routines */
6087         ufs_lbn_t lbn;          /* Logical block number for this block. */
6088 {
6089         struct fs *fs;
6090         struct indirdep *indirdep;
6091         struct allocindir *oldaip;
6092         struct freefrag *freefrag;
6093         struct mount *mp;
6094         struct ufsmount *ump;
6095
6096         mp = ITOVFS(ip);
6097         ump = VFSTOUFS(mp);
6098         LOCK_OWNED(ump);
6099         fs = ump->um_fs;
6100         if (bp->b_lblkno >= 0)
6101                 panic("setup_allocindir_phase2: not indir blk");
6102         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6103             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6104         indirdep = indirdep_lookup(mp, ip, bp);
6105         KASSERT(indirdep->ir_savebp != NULL,
6106             ("setup_allocindir_phase2 NULL ir_savebp"));
6107         aip->ai_indirdep = indirdep;
6108         /*
6109          * Check for an unwritten dependency for this indirect offset.  If
6110          * there is, merge the old dependency into the new one.  This happens
6111          * as a result of reallocblk only.
6112          */
6113         freefrag = NULL;
6114         if (aip->ai_oldblkno != 0) {
6115                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6116                         if (oldaip->ai_offset == aip->ai_offset) {
6117                                 freefrag = allocindir_merge(aip, oldaip);
6118                                 goto done;
6119                         }
6120                 }
6121                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6122                         if (oldaip->ai_offset == aip->ai_offset) {
6123                                 freefrag = allocindir_merge(aip, oldaip);
6124                                 goto done;
6125                         }
6126                 }
6127         }
6128 done:
6129         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6130         return (freefrag);
6131 }
6132
6133 /*
6134  * Merge two allocindirs which refer to the same block.  Move newblock
6135  * dependencies and setup the freefrags appropriately.
6136  */
6137 static struct freefrag *
6138 allocindir_merge(aip, oldaip)
6139         struct allocindir *aip;
6140         struct allocindir *oldaip;
6141 {
6142         struct freefrag *freefrag;
6143         struct worklist *wk;
6144
6145         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6146                 panic("allocindir_merge: blkno");
6147         aip->ai_oldblkno = oldaip->ai_oldblkno;
6148         freefrag = aip->ai_freefrag;
6149         aip->ai_freefrag = oldaip->ai_freefrag;
6150         oldaip->ai_freefrag = NULL;
6151         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6152         /*
6153          * If we are tracking a new directory-block allocation,
6154          * move it from the old allocindir to the new allocindir.
6155          */
6156         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6157                 WORKLIST_REMOVE(wk);
6158                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6159                         panic("allocindir_merge: extra newdirblk");
6160                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6161         }
6162         /*
6163          * We can skip journaling for this freefrag and just complete
6164          * any pending journal work for the allocindir that is being
6165          * removed after the freefrag completes.
6166          */
6167         if (freefrag->ff_jdep)
6168                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6169         LIST_REMOVE(oldaip, ai_next);
6170         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6171             &freefrag->ff_list, &freefrag->ff_jwork);
6172         free_newblk(&oldaip->ai_block);
6173
6174         return (freefrag);
6175 }
6176
6177 static inline void
6178 setup_freedirect(freeblks, ip, i, needj)
6179         struct freeblks *freeblks;
6180         struct inode *ip;
6181         int i;
6182         int needj;
6183 {
6184         struct ufsmount *ump;
6185         ufs2_daddr_t blkno;
6186         int frags;
6187
6188         blkno = DIP(ip, i_db[i]);
6189         if (blkno == 0)
6190                 return;
6191         DIP_SET(ip, i_db[i], 0);
6192         ump = ITOUMP(ip);
6193         frags = sblksize(ump->um_fs, ip->i_size, i);
6194         frags = numfrags(ump->um_fs, frags);
6195         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6196 }
6197
6198 static inline void
6199 setup_freeext(freeblks, ip, i, needj)
6200         struct freeblks *freeblks;
6201         struct inode *ip;
6202         int i;
6203         int needj;
6204 {
6205         struct ufsmount *ump;
6206         ufs2_daddr_t blkno;
6207         int frags;
6208
6209         blkno = ip->i_din2->di_extb[i];
6210         if (blkno == 0)
6211                 return;
6212         ip->i_din2->di_extb[i] = 0;
6213         ump = ITOUMP(ip);
6214         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6215         frags = numfrags(ump->um_fs, frags);
6216         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6217 }
6218
6219 static inline void
6220 setup_freeindir(freeblks, ip, i, lbn, needj)
6221         struct freeblks *freeblks;
6222         struct inode *ip;
6223         int i;
6224         ufs_lbn_t lbn;
6225         int needj;
6226 {
6227         struct ufsmount *ump;
6228         ufs2_daddr_t blkno;
6229
6230         blkno = DIP(ip, i_ib[i]);
6231         if (blkno == 0)
6232                 return;
6233         DIP_SET(ip, i_ib[i], 0);
6234         ump = ITOUMP(ip);
6235         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6236             0, needj);
6237 }
6238
6239 static inline struct freeblks *
6240 newfreeblks(mp, ip)
6241         struct mount *mp;
6242         struct inode *ip;
6243 {
6244         struct freeblks *freeblks;
6245
6246         freeblks = malloc(sizeof(struct freeblks),
6247                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6248         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6249         LIST_INIT(&freeblks->fb_jblkdephd);
6250         LIST_INIT(&freeblks->fb_jwork);
6251         freeblks->fb_ref = 0;
6252         freeblks->fb_cgwait = 0;
6253         freeblks->fb_state = ATTACHED;
6254         freeblks->fb_uid = ip->i_uid;
6255         freeblks->fb_inum = ip->i_number;
6256         freeblks->fb_vtype = ITOV(ip)->v_type;
6257         freeblks->fb_modrev = DIP(ip, i_modrev);
6258         freeblks->fb_devvp = ITODEVVP(ip);
6259         freeblks->fb_chkcnt = 0;
6260         freeblks->fb_len = 0;
6261
6262         return (freeblks);
6263 }
6264
6265 static void
6266 trunc_indirdep(indirdep, freeblks, bp, off)
6267         struct indirdep *indirdep;
6268         struct freeblks *freeblks;
6269         struct buf *bp;
6270         int off;
6271 {
6272         struct allocindir *aip, *aipn;
6273
6274         /*
6275          * The first set of allocindirs won't be in savedbp.
6276          */
6277         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6278                 if (aip->ai_offset > off)
6279                         cancel_allocindir(aip, bp, freeblks, 1);
6280         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6281                 if (aip->ai_offset > off)
6282                         cancel_allocindir(aip, bp, freeblks, 1);
6283         /*
6284          * These will exist in savedbp.
6285          */
6286         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6287                 if (aip->ai_offset > off)
6288                         cancel_allocindir(aip, NULL, freeblks, 0);
6289         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6290                 if (aip->ai_offset > off)
6291                         cancel_allocindir(aip, NULL, freeblks, 0);
6292 }
6293
6294 /*
6295  * Follow the chain of indirects down to lastlbn creating a freework
6296  * structure for each.  This will be used to start indir_trunc() at
6297  * the right offset and create the journal records for the parrtial
6298  * truncation.  A second step will handle the truncated dependencies.
6299  */
6300 static int
6301 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6302         struct freeblks *freeblks;
6303         struct inode *ip;
6304         ufs_lbn_t lbn;
6305         ufs_lbn_t lastlbn;
6306         ufs2_daddr_t blkno;
6307 {
6308         struct indirdep *indirdep;
6309         struct indirdep *indirn;
6310         struct freework *freework;
6311         struct newblk *newblk;
6312         struct mount *mp;
6313         struct ufsmount *ump;
6314         struct buf *bp;
6315         uint8_t *start;
6316         uint8_t *end;
6317         ufs_lbn_t lbnadd;
6318         int level;
6319         int error;
6320         int off;
6321
6322
6323         freework = NULL;
6324         if (blkno == 0)
6325                 return (0);
6326         mp = freeblks->fb_list.wk_mp;
6327         ump = VFSTOUFS(mp);
6328         /*
6329          * Here, calls to VOP_BMAP() will fail.  However, we already have
6330          * the on-disk address, so we just pass it to bread() instead of
6331          * having bread() attempt to calculate it using VOP_BMAP().
6332          */
6333         error = breadn_flags(ITOV(ip), lbn, blkptrtodb(ump, blkno),
6334             (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6335         if (error)
6336                 return (error);
6337         level = lbn_level(lbn);
6338         lbnadd = lbn_offset(ump->um_fs, level);
6339         /*
6340          * Compute the offset of the last block we want to keep.  Store
6341          * in the freework the first block we want to completely free.
6342          */
6343         off = (lastlbn - -(lbn + level)) / lbnadd;
6344         if (off + 1 == NINDIR(ump->um_fs))
6345                 goto nowork;
6346         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6347         /*
6348          * Link the freework into the indirdep.  This will prevent any new
6349          * allocations from proceeding until we are finished with the
6350          * truncate and the block is written.
6351          */
6352         ACQUIRE_LOCK(ump);
6353         indirdep = indirdep_lookup(mp, ip, bp);
6354         if (indirdep->ir_freeblks)
6355                 panic("setup_trunc_indir: indirdep already truncated.");
6356         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6357         freework->fw_indir = indirdep;
6358         /*
6359          * Cancel any allocindirs that will not make it to disk.
6360          * We have to do this for all copies of the indirdep that
6361          * live on this newblk.
6362          */
6363         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6364                 if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6365                     &newblk) == 0)
6366                         panic("setup_trunc_indir: lost block");
6367                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6368                         trunc_indirdep(indirn, freeblks, bp, off);
6369         } else
6370                 trunc_indirdep(indirdep, freeblks, bp, off);
6371         FREE_LOCK(ump);
6372         /*
6373          * Creation is protected by the buf lock. The saveddata is only
6374          * needed if a full truncation follows a partial truncation but it
6375          * is difficult to allocate in that case so we fetch it anyway.
6376          */
6377         if (indirdep->ir_saveddata == NULL)
6378                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6379                     M_SOFTDEP_FLAGS);
6380 nowork:
6381         /* Fetch the blkno of the child and the zero start offset. */
6382         if (I_IS_UFS1(ip)) {
6383                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6384                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6385         } else {
6386                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6387                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6388         }
6389         if (freework) {
6390                 /* Zero the truncated pointers. */
6391                 end = bp->b_data + bp->b_bcount;
6392                 bzero(start, end - start);
6393                 bdwrite(bp);
6394         } else
6395                 bqrelse(bp);
6396         if (level == 0)
6397                 return (0);
6398         lbn++; /* adjust level */
6399         lbn -= (off * lbnadd);
6400         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6401 }
6402
6403 /*
6404  * Complete the partial truncation of an indirect block setup by
6405  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6406  * copy and writes them to disk before the freeblks is allowed to complete.
6407  */
6408 static void
6409 complete_trunc_indir(freework)
6410         struct freework *freework;
6411 {
6412         struct freework *fwn;
6413         struct indirdep *indirdep;
6414         struct ufsmount *ump;
6415         struct buf *bp;
6416         uintptr_t start;
6417         int count;
6418
6419         ump = VFSTOUFS(freework->fw_list.wk_mp);
6420         LOCK_OWNED(ump);
6421         indirdep = freework->fw_indir;
6422         for (;;) {
6423                 bp = indirdep->ir_bp;
6424                 /* See if the block was discarded. */
6425                 if (bp == NULL)
6426                         break;
6427                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6428                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6429                         break;
6430                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6431                     LOCK_PTR(ump)) == 0)
6432                         BUF_UNLOCK(bp);
6433                 ACQUIRE_LOCK(ump);
6434         }
6435         freework->fw_state |= DEPCOMPLETE;
6436         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6437         /*
6438          * Zero the pointers in the saved copy.
6439          */
6440         if (indirdep->ir_state & UFS1FMT)
6441                 start = sizeof(ufs1_daddr_t);
6442         else
6443                 start = sizeof(ufs2_daddr_t);
6444         start *= freework->fw_start;
6445         count = indirdep->ir_savebp->b_bcount - start;
6446         start += (uintptr_t)indirdep->ir_savebp->b_data;
6447         bzero((char *)start, count);
6448         /*
6449          * We need to start the next truncation in the list if it has not
6450          * been started yet.
6451          */
6452         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6453         if (fwn != NULL) {
6454                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6455                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6456                 if ((fwn->fw_state & ONWORKLIST) == 0)
6457                         freework_enqueue(fwn);
6458         }
6459         /*
6460          * If bp is NULL the block was fully truncated, restore
6461          * the saved block list otherwise free it if it is no
6462          * longer needed.
6463          */
6464         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6465                 if (bp == NULL)
6466                         bcopy(indirdep->ir_saveddata,
6467                             indirdep->ir_savebp->b_data,
6468                             indirdep->ir_savebp->b_bcount);
6469                 free(indirdep->ir_saveddata, M_INDIRDEP);
6470                 indirdep->ir_saveddata = NULL;
6471         }
6472         /*
6473          * When bp is NULL there is a full truncation pending.  We
6474          * must wait for this full truncation to be journaled before
6475          * we can release this freework because the disk pointers will
6476          * never be written as zero.
6477          */
6478         if (bp == NULL)  {
6479                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6480                         handle_written_freework(freework);
6481                 else
6482                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6483                            &freework->fw_list);
6484         } else {
6485                 /* Complete when the real copy is written. */
6486                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6487                 BUF_UNLOCK(bp);
6488         }
6489 }
6490
6491 /*
6492  * Calculate the number of blocks we are going to release where datablocks
6493  * is the current total and length is the new file size.
6494  */
6495 static ufs2_daddr_t
6496 blkcount(fs, datablocks, length)
6497         struct fs *fs;
6498         ufs2_daddr_t datablocks;
6499         off_t length;
6500 {
6501         off_t totblks, numblks;
6502
6503         totblks = 0;
6504         numblks = howmany(length, fs->fs_bsize);
6505         if (numblks <= UFS_NDADDR) {
6506                 totblks = howmany(length, fs->fs_fsize);
6507                 goto out;
6508         }
6509         totblks = blkstofrags(fs, numblks);
6510         numblks -= UFS_NDADDR;
6511         /*
6512          * Count all single, then double, then triple indirects required.
6513          * Subtracting one indirects worth of blocks for each pass
6514          * acknowledges one of each pointed to by the inode.
6515          */
6516         for (;;) {
6517                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6518                 numblks -= NINDIR(fs);
6519                 if (numblks <= 0)
6520                         break;
6521                 numblks = howmany(numblks, NINDIR(fs));
6522         }
6523 out:
6524         totblks = fsbtodb(fs, totblks);
6525         /*
6526          * Handle sparse files.  We can't reclaim more blocks than the inode
6527          * references.  We will correct it later in handle_complete_freeblks()
6528          * when we know the real count.
6529          */
6530         if (totblks > datablocks)
6531                 return (0);
6532         return (datablocks - totblks);
6533 }
6534
6535 /*
6536  * Handle freeblocks for journaled softupdate filesystems.
6537  *
6538  * Contrary to normal softupdates, we must preserve the block pointers in
6539  * indirects until their subordinates are free.  This is to avoid journaling
6540  * every block that is freed which may consume more space than the journal
6541  * itself.  The recovery program will see the free block journals at the
6542  * base of the truncated area and traverse them to reclaim space.  The
6543  * pointers in the inode may be cleared immediately after the journal
6544  * records are written because each direct and indirect pointer in the
6545  * inode is recorded in a journal.  This permits full truncation to proceed
6546  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6547  *
6548  * The algorithm is as follows:
6549  * 1) Traverse the in-memory state and create journal entries to release
6550  *    the relevant blocks and full indirect trees.
6551  * 2) Traverse the indirect block chain adding partial truncation freework
6552  *    records to indirects in the path to lastlbn.  The freework will
6553  *    prevent new allocation dependencies from being satisfied in this
6554  *    indirect until the truncation completes.
6555  * 3) Read and lock the inode block, performing an update with the new size
6556  *    and pointers.  This prevents truncated data from becoming valid on
6557  *    disk through step 4.
6558  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6559  *    eliminate journal work for those records that do not require it.
6560  * 5) Schedule the journal records to be written followed by the inode block.
6561  * 6) Allocate any necessary frags for the end of file.
6562  * 7) Zero any partially truncated blocks.
6563  *
6564  * From this truncation proceeds asynchronously using the freework and
6565  * indir_trunc machinery.  The file will not be extended again into a
6566  * partially truncated indirect block until all work is completed but
6567  * the normal dependency mechanism ensures that it is rolled back/forward
6568  * as appropriate.  Further truncation may occur without delay and is
6569  * serialized in indir_trunc().
6570  */
6571 void
6572 softdep_journal_freeblocks(ip, cred, length, flags)
6573         struct inode *ip;       /* The inode whose length is to be reduced */
6574         struct ucred *cred;
6575         off_t length;           /* The new length for the file */
6576         int flags;              /* IO_EXT and/or IO_NORMAL */
6577 {
6578         struct freeblks *freeblks, *fbn;
6579         struct worklist *wk, *wkn;
6580         struct inodedep *inodedep;
6581         struct jblkdep *jblkdep;
6582         struct allocdirect *adp, *adpn;
6583         struct ufsmount *ump;
6584         struct fs *fs;
6585         struct buf *bp;
6586         struct vnode *vp;
6587         struct mount *mp;
6588         ufs2_daddr_t extblocks, datablocks;
6589         ufs_lbn_t tmpval, lbn, lastlbn;
6590         int frags, lastoff, iboff, allocblock, needj, error, i;
6591
6592         ump = ITOUMP(ip);
6593         mp = UFSTOVFS(ump);
6594         fs = ump->um_fs;
6595         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6596             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6597         vp = ITOV(ip);
6598         needj = 1;
6599         iboff = -1;
6600         allocblock = 0;
6601         extblocks = 0;
6602         datablocks = 0;
6603         frags = 0;
6604         freeblks = newfreeblks(mp, ip);
6605         ACQUIRE_LOCK(ump);
6606         /*
6607          * If we're truncating a removed file that will never be written
6608          * we don't need to journal the block frees.  The canceled journals
6609          * for the allocations will suffice.
6610          */
6611         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6612         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6613             length == 0)
6614                 needj = 0;
6615         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6616             ip->i_number, length, needj);
6617         FREE_LOCK(ump);
6618         /*
6619          * Calculate the lbn that we are truncating to.  This results in -1
6620          * if we're truncating the 0 bytes.  So it is the last lbn we want
6621          * to keep, not the first lbn we want to truncate.
6622          */
6623         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6624         lastoff = blkoff(fs, length);
6625         /*
6626          * Compute frags we are keeping in lastlbn.  0 means all.
6627          */
6628         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6629                 frags = fragroundup(fs, lastoff);
6630                 /* adp offset of last valid allocdirect. */
6631                 iboff = lastlbn;
6632         } else if (lastlbn > 0)
6633                 iboff = UFS_NDADDR;
6634         if (fs->fs_magic == FS_UFS2_MAGIC)
6635                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6636         /*
6637          * Handle normal data blocks and indirects.  This section saves
6638          * values used after the inode update to complete frag and indirect
6639          * truncation.
6640          */
6641         if ((flags & IO_NORMAL) != 0) {
6642                 /*
6643                  * Handle truncation of whole direct and indirect blocks.
6644                  */
6645                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6646                         setup_freedirect(freeblks, ip, i, needj);
6647                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6648                     i < UFS_NIADDR;
6649                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6650                         /* Release a whole indirect tree. */
6651                         if (lbn > lastlbn) {
6652                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6653                                     needj);
6654                                 continue;
6655                         }
6656                         iboff = i + UFS_NDADDR;
6657                         /*
6658                          * Traverse partially truncated indirect tree.
6659                          */
6660                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6661                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6662                                     lastlbn, DIP(ip, i_ib[i]));
6663                 }
6664                 /*
6665                  * Handle partial truncation to a frag boundary.
6666                  */
6667                 if (frags) {
6668                         ufs2_daddr_t blkno;
6669                         long oldfrags;
6670
6671                         oldfrags = blksize(fs, ip, lastlbn);
6672                         blkno = DIP(ip, i_db[lastlbn]);
6673                         if (blkno && oldfrags != frags) {
6674                                 oldfrags -= frags;
6675                                 oldfrags = numfrags(fs, oldfrags);
6676                                 blkno += numfrags(fs, frags);
6677                                 newfreework(ump, freeblks, NULL, lastlbn,
6678                                     blkno, oldfrags, 0, needj);
6679                                 if (needj)
6680                                         adjust_newfreework(freeblks,
6681                                             numfrags(fs, frags));
6682                         } else if (blkno == 0)
6683                                 allocblock = 1;
6684                 }
6685                 /*
6686                  * Add a journal record for partial truncate if we are
6687                  * handling indirect blocks.  Non-indirects need no extra
6688                  * journaling.
6689                  */
6690                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6691                         UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6692                         newjtrunc(freeblks, length, 0);
6693                 }
6694                 ip->i_size = length;
6695                 DIP_SET(ip, i_size, ip->i_size);
6696                 datablocks = DIP(ip, i_blocks) - extblocks;
6697                 if (length != 0)
6698                         datablocks = blkcount(fs, datablocks, length);
6699                 freeblks->fb_len = length;
6700         }
6701         if ((flags & IO_EXT) != 0) {
6702                 for (i = 0; i < UFS_NXADDR; i++)
6703                         setup_freeext(freeblks, ip, i, needj);
6704                 ip->i_din2->di_extsize = 0;
6705                 datablocks += extblocks;
6706         }
6707 #ifdef QUOTA
6708         /* Reference the quotas in case the block count is wrong in the end. */
6709         quotaref(vp, freeblks->fb_quota);
6710         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6711 #endif
6712         freeblks->fb_chkcnt = -datablocks;
6713         UFS_LOCK(ump);
6714         fs->fs_pendingblocks += datablocks;
6715         UFS_UNLOCK(ump);
6716         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6717         /*
6718          * Handle truncation of incomplete alloc direct dependencies.  We
6719          * hold the inode block locked to prevent incomplete dependencies
6720          * from reaching the disk while we are eliminating those that
6721          * have been truncated.  This is a partially inlined ffs_update().
6722          */
6723         ufs_itimes(vp);
6724         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6725         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6726             (int)fs->fs_bsize, cred, &bp);
6727         if (error) {
6728                 softdep_error("softdep_journal_freeblocks", error);
6729                 return;
6730         }
6731         if (bp->b_bufsize == fs->fs_bsize)
6732                 bp->b_flags |= B_CLUSTEROK;
6733         softdep_update_inodeblock(ip, bp, 0);
6734         if (ump->um_fstype == UFS1) {
6735                 *((struct ufs1_dinode *)bp->b_data +
6736                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6737         } else {
6738                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6739                 *((struct ufs2_dinode *)bp->b_data +
6740                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6741         }
6742         ACQUIRE_LOCK(ump);
6743         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6744         if ((inodedep->id_state & IOSTARTED) != 0)
6745                 panic("softdep_setup_freeblocks: inode busy");
6746         /*
6747          * Add the freeblks structure to the list of operations that
6748          * must await the zero'ed inode being written to disk. If we
6749          * still have a bitmap dependency (needj), then the inode
6750          * has never been written to disk, so we can process the
6751          * freeblks below once we have deleted the dependencies.
6752          */
6753         if (needj)
6754                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6755         else
6756                 freeblks->fb_state |= COMPLETE;
6757         if ((flags & IO_NORMAL) != 0) {
6758                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6759                         if (adp->ad_offset > iboff)
6760                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6761                                     freeblks);
6762                         /*
6763                          * Truncate the allocdirect.  We could eliminate
6764                          * or modify journal records as well.
6765                          */
6766                         else if (adp->ad_offset == iboff && frags)
6767                                 adp->ad_newsize = frags;
6768                 }
6769         }
6770         if ((flags & IO_EXT) != 0)
6771                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6772                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6773                             freeblks);
6774         /*
6775          * Scan the bufwait list for newblock dependencies that will never
6776          * make it to disk.
6777          */
6778         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6779                 if (wk->wk_type != D_ALLOCDIRECT)
6780                         continue;
6781                 adp = WK_ALLOCDIRECT(wk);
6782                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6783                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6784                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6785                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6786                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6787                 }
6788         }
6789         /*
6790          * Add journal work.
6791          */
6792         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6793                 add_to_journal(&jblkdep->jb_list);
6794         FREE_LOCK(ump);
6795         bdwrite(bp);
6796         /*
6797          * Truncate dependency structures beyond length.
6798          */
6799         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6800         /*
6801          * This is only set when we need to allocate a fragment because
6802          * none existed at the end of a frag-sized file.  It handles only
6803          * allocating a new, zero filled block.
6804          */
6805         if (allocblock) {
6806                 ip->i_size = length - lastoff;
6807                 DIP_SET(ip, i_size, ip->i_size);
6808                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6809                 if (error != 0) {
6810                         softdep_error("softdep_journal_freeblks", error);
6811                         return;
6812                 }
6813                 ip->i_size = length;
6814                 DIP_SET(ip, i_size, length);
6815                 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
6816                 allocbuf(bp, frags);
6817                 ffs_update(vp, 0);
6818                 bawrite(bp);
6819         } else if (lastoff != 0 && vp->v_type != VDIR) {
6820                 int size;
6821
6822                 /*
6823                  * Zero the end of a truncated frag or block.
6824                  */
6825                 size = sblksize(fs, length, lastlbn);
6826                 error = bread(vp, lastlbn, size, cred, &bp);
6827                 if (error) {
6828                         softdep_error("softdep_journal_freeblks", error);
6829                         return;
6830                 }
6831                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6832                 bawrite(bp);
6833
6834         }
6835         ACQUIRE_LOCK(ump);
6836         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6837         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6838         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6839         /*
6840          * We zero earlier truncations so they don't erroneously
6841          * update i_blocks.
6842          */
6843         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6844                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6845                         fbn->fb_len = 0;
6846         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6847             LIST_EMPTY(&freeblks->fb_jblkdephd))
6848                 freeblks->fb_state |= INPROGRESS;
6849         else
6850                 freeblks = NULL;
6851         FREE_LOCK(ump);
6852         if (freeblks)
6853                 handle_workitem_freeblocks(freeblks, 0);
6854         trunc_pages(ip, length, extblocks, flags);
6855
6856 }
6857
6858 /*
6859  * Flush a JOP_SYNC to the journal.
6860  */
6861 void
6862 softdep_journal_fsync(ip)
6863         struct inode *ip;
6864 {
6865         struct jfsync *jfsync;
6866         struct ufsmount *ump;
6867
6868         ump = ITOUMP(ip);
6869         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6870             ("softdep_journal_fsync called on non-softdep filesystem"));
6871         if ((ip->i_flag & IN_TRUNCATED) == 0)
6872                 return;
6873         ip->i_flag &= ~IN_TRUNCATED;
6874         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6875         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6876         jfsync->jfs_size = ip->i_size;
6877         jfsync->jfs_ino = ip->i_number;
6878         ACQUIRE_LOCK(ump);
6879         add_to_journal(&jfsync->jfs_list);
6880         jwait(&jfsync->jfs_list, MNT_WAIT);
6881         FREE_LOCK(ump);
6882 }
6883
6884 /*
6885  * Block de-allocation dependencies.
6886  * 
6887  * When blocks are de-allocated, the on-disk pointers must be nullified before
6888  * the blocks are made available for use by other files.  (The true
6889  * requirement is that old pointers must be nullified before new on-disk
6890  * pointers are set.  We chose this slightly more stringent requirement to
6891  * reduce complexity.) Our implementation handles this dependency by updating
6892  * the inode (or indirect block) appropriately but delaying the actual block
6893  * de-allocation (i.e., freemap and free space count manipulation) until
6894  * after the updated versions reach stable storage.  After the disk is
6895  * updated, the blocks can be safely de-allocated whenever it is convenient.
6896  * This implementation handles only the common case of reducing a file's
6897  * length to zero. Other cases are handled by the conventional synchronous
6898  * write approach.
6899  *
6900  * The ffs implementation with which we worked double-checks
6901  * the state of the block pointers and file size as it reduces
6902  * a file's length.  Some of this code is replicated here in our
6903  * soft updates implementation.  The freeblks->fb_chkcnt field is
6904  * used to transfer a part of this information to the procedure
6905  * that eventually de-allocates the blocks.
6906  *
6907  * This routine should be called from the routine that shortens
6908  * a file's length, before the inode's size or block pointers
6909  * are modified. It will save the block pointer information for
6910  * later release and zero the inode so that the calling routine
6911  * can release it.
6912  */
6913 void
6914 softdep_setup_freeblocks(ip, length, flags)
6915         struct inode *ip;       /* The inode whose length is to be reduced */
6916         off_t length;           /* The new length for the file */
6917         int flags;              /* IO_EXT and/or IO_NORMAL */
6918 {
6919         struct ufs1_dinode *dp1;
6920         struct ufs2_dinode *dp2;
6921         struct freeblks *freeblks;
6922         struct inodedep *inodedep;
6923         struct allocdirect *adp;
6924         struct ufsmount *ump;
6925         struct buf *bp;
6926         struct fs *fs;
6927         ufs2_daddr_t extblocks, datablocks;
6928         struct mount *mp;
6929         int i, delay, error;
6930         ufs_lbn_t tmpval;
6931         ufs_lbn_t lbn;
6932
6933         ump = ITOUMP(ip);
6934         mp = UFSTOVFS(ump);
6935         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6936             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6937         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6938             ip->i_number, length);
6939         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6940         fs = ump->um_fs;
6941         if ((error = bread(ump->um_devvp,
6942             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6943             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6944                 brelse(bp);
6945                 softdep_error("softdep_setup_freeblocks", error);
6946                 return;
6947         }
6948         freeblks = newfreeblks(mp, ip);
6949         extblocks = 0;
6950         datablocks = 0;
6951         if (fs->fs_magic == FS_UFS2_MAGIC)
6952                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6953         if ((flags & IO_NORMAL) != 0) {
6954                 for (i = 0; i < UFS_NDADDR; i++)
6955                         setup_freedirect(freeblks, ip, i, 0);
6956                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6957                     i < UFS_NIADDR;
6958                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6959                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6960                 ip->i_size = 0;
6961                 DIP_SET(ip, i_size, 0);
6962                 datablocks = DIP(ip, i_blocks) - extblocks;
6963         }
6964         if ((flags & IO_EXT) != 0) {
6965                 for (i = 0; i < UFS_NXADDR; i++)
6966                         setup_freeext(freeblks, ip, i, 0);
6967                 ip->i_din2->di_extsize = 0;
6968                 datablocks += extblocks;
6969         }
6970 #ifdef QUOTA
6971         /* Reference the quotas in case the block count is wrong in the end. */
6972         quotaref(ITOV(ip), freeblks->fb_quota);
6973         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6974 #endif
6975         freeblks->fb_chkcnt = -datablocks;
6976         UFS_LOCK(ump);
6977         fs->fs_pendingblocks += datablocks;
6978         UFS_UNLOCK(ump);
6979         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6980         /*
6981          * Push the zero'ed inode to its disk buffer so that we are free
6982          * to delete its dependencies below. Once the dependencies are gone
6983          * the buffer can be safely released.
6984          */
6985         if (ump->um_fstype == UFS1) {
6986                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6987                     ino_to_fsbo(fs, ip->i_number));
6988                 ip->i_din1->di_freelink = dp1->di_freelink;
6989                 *dp1 = *ip->i_din1;
6990         } else {
6991                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6992                     ino_to_fsbo(fs, ip->i_number));
6993                 ip->i_din2->di_freelink = dp2->di_freelink;
6994                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6995                 *dp2 = *ip->i_din2;
6996         }
6997         /*
6998          * Find and eliminate any inode dependencies.
6999          */
7000         ACQUIRE_LOCK(ump);
7001         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7002         if ((inodedep->id_state & IOSTARTED) != 0)
7003                 panic("softdep_setup_freeblocks: inode busy");
7004         /*
7005          * Add the freeblks structure to the list of operations that
7006          * must await the zero'ed inode being written to disk. If we
7007          * still have a bitmap dependency (delay == 0), then the inode
7008          * has never been written to disk, so we can process the
7009          * freeblks below once we have deleted the dependencies.
7010          */
7011         delay = (inodedep->id_state & DEPCOMPLETE);
7012         if (delay)
7013                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7014         else
7015                 freeblks->fb_state |= COMPLETE;
7016         /*
7017          * Because the file length has been truncated to zero, any
7018          * pending block allocation dependency structures associated
7019          * with this inode are obsolete and can simply be de-allocated.
7020          * We must first merge the two dependency lists to get rid of
7021          * any duplicate freefrag structures, then purge the merged list.
7022          * If we still have a bitmap dependency, then the inode has never
7023          * been written to disk, so we can free any fragments without delay.
7024          */
7025         if (flags & IO_NORMAL) {
7026                 merge_inode_lists(&inodedep->id_newinoupdt,
7027                     &inodedep->id_inoupdt);
7028                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7029                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
7030                             freeblks);
7031         }
7032         if (flags & IO_EXT) {
7033                 merge_inode_lists(&inodedep->id_newextupdt,
7034                     &inodedep->id_extupdt);
7035                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7036                         cancel_allocdirect(&inodedep->id_extupdt, adp,
7037                             freeblks);
7038         }
7039         FREE_LOCK(ump);
7040         bdwrite(bp);
7041         trunc_dependencies(ip, freeblks, -1, 0, flags);
7042         ACQUIRE_LOCK(ump);
7043         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7044                 (void) free_inodedep(inodedep);
7045         freeblks->fb_state |= DEPCOMPLETE;
7046         /*
7047          * If the inode with zeroed block pointers is now on disk
7048          * we can start freeing blocks.
7049          */  
7050         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7051                 freeblks->fb_state |= INPROGRESS;
7052         else
7053                 freeblks = NULL;
7054         FREE_LOCK(ump);
7055         if (freeblks)
7056                 handle_workitem_freeblocks(freeblks, 0);
7057         trunc_pages(ip, length, extblocks, flags);
7058 }
7059
7060 /*
7061  * Eliminate pages from the page cache that back parts of this inode and
7062  * adjust the vnode pager's idea of our size.  This prevents stale data
7063  * from hanging around in the page cache.
7064  */
7065 static void
7066 trunc_pages(ip, length, extblocks, flags)
7067         struct inode *ip;
7068         off_t length;
7069         ufs2_daddr_t extblocks;
7070         int flags;
7071 {
7072         struct vnode *vp;
7073         struct fs *fs;
7074         ufs_lbn_t lbn;
7075         off_t end, extend;
7076
7077         vp = ITOV(ip);
7078         fs = ITOFS(ip);
7079         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7080         if ((flags & IO_EXT) != 0)
7081                 vn_pages_remove(vp, extend, 0);
7082         if ((flags & IO_NORMAL) == 0)
7083                 return;
7084         BO_LOCK(&vp->v_bufobj);
7085         drain_output(vp);
7086         BO_UNLOCK(&vp->v_bufobj);
7087         /*
7088          * The vnode pager eliminates file pages we eliminate indirects
7089          * below.
7090          */
7091         vnode_pager_setsize(vp, length);
7092         /*
7093          * Calculate the end based on the last indirect we want to keep.  If
7094          * the block extends into indirects we can just use the negative of
7095          * its lbn.  Doubles and triples exist at lower numbers so we must
7096          * be careful not to remove those, if they exist.  double and triple
7097          * indirect lbns do not overlap with others so it is not important
7098          * to verify how many levels are required.
7099          */
7100         lbn = lblkno(fs, length);
7101         if (lbn >= UFS_NDADDR) {
7102                 /* Calculate the virtual lbn of the triple indirect. */
7103                 lbn = -lbn - (UFS_NIADDR - 1);
7104                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7105         } else
7106                 end = extend;
7107         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7108 }
7109
7110 /*
7111  * See if the buf bp is in the range eliminated by truncation.
7112  */
7113 static int
7114 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7115         struct buf *bp;
7116         int *blkoffp;
7117         ufs_lbn_t lastlbn;
7118         int lastoff;
7119         int flags;
7120 {
7121         ufs_lbn_t lbn;
7122
7123         *blkoffp = 0;
7124         /* Only match ext/normal blocks as appropriate. */
7125         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7126             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7127                 return (0);
7128         /* ALTDATA is always a full truncation. */
7129         if ((bp->b_xflags & BX_ALTDATA) != 0)
7130                 return (1);
7131         /* -1 is full truncation. */
7132         if (lastlbn == -1)
7133                 return (1);
7134         /*
7135          * If this is a partial truncate we only want those
7136          * blocks and indirect blocks that cover the range
7137          * we're after.
7138          */
7139         lbn = bp->b_lblkno;
7140         if (lbn < 0)
7141                 lbn = -(lbn + lbn_level(lbn));
7142         if (lbn < lastlbn)
7143                 return (0);
7144         /* Here we only truncate lblkno if it's partial. */
7145         if (lbn == lastlbn) {
7146                 if (lastoff == 0)
7147                         return (0);
7148                 *blkoffp = lastoff;
7149         }
7150         return (1);
7151 }
7152
7153 /*
7154  * Eliminate any dependencies that exist in memory beyond lblkno:off
7155  */
7156 static void
7157 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7158         struct inode *ip;
7159         struct freeblks *freeblks;
7160         ufs_lbn_t lastlbn;
7161         int lastoff;
7162         int flags;
7163 {
7164         struct bufobj *bo;
7165         struct vnode *vp;
7166         struct buf *bp;
7167         int blkoff;
7168
7169         /*
7170          * We must wait for any I/O in progress to finish so that
7171          * all potential buffers on the dirty list will be visible.
7172          * Once they are all there, walk the list and get rid of
7173          * any dependencies.
7174          */
7175         vp = ITOV(ip);
7176         bo = &vp->v_bufobj;
7177         BO_LOCK(bo);
7178         drain_output(vp);
7179         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7180                 bp->b_vflags &= ~BV_SCANNED;
7181 restart:
7182         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7183                 if (bp->b_vflags & BV_SCANNED)
7184                         continue;
7185                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7186                         bp->b_vflags |= BV_SCANNED;
7187                         continue;
7188                 }
7189                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7190                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7191                         goto restart;
7192                 BO_UNLOCK(bo);
7193                 if (deallocate_dependencies(bp, freeblks, blkoff))
7194                         bqrelse(bp);
7195                 else
7196                         brelse(bp);
7197                 BO_LOCK(bo);
7198                 goto restart;
7199         }
7200         /*
7201          * Now do the work of vtruncbuf while also matching indirect blocks.
7202          */
7203         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7204                 bp->b_vflags &= ~BV_SCANNED;
7205 cleanrestart:
7206         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7207                 if (bp->b_vflags & BV_SCANNED)
7208                         continue;
7209                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7210                         bp->b_vflags |= BV_SCANNED;
7211                         continue;
7212                 }
7213                 if (BUF_LOCK(bp,
7214                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7215                     BO_LOCKPTR(bo)) == ENOLCK) {
7216                         BO_LOCK(bo);
7217                         goto cleanrestart;
7218                 }
7219                 bp->b_vflags |= BV_SCANNED;
7220                 bremfree(bp);
7221                 if (blkoff != 0) {
7222                         allocbuf(bp, blkoff);
7223                         bqrelse(bp);
7224                 } else {
7225                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7226                         brelse(bp);
7227                 }
7228                 BO_LOCK(bo);
7229                 goto cleanrestart;
7230         }
7231         drain_output(vp);
7232         BO_UNLOCK(bo);
7233 }
7234
7235 static int
7236 cancel_pagedep(pagedep, freeblks, blkoff)
7237         struct pagedep *pagedep;
7238         struct freeblks *freeblks;
7239         int blkoff;
7240 {
7241         struct jremref *jremref;
7242         struct jmvref *jmvref;
7243         struct dirrem *dirrem, *tmp;
7244         int i;
7245
7246         /*
7247          * Copy any directory remove dependencies to the list
7248          * to be processed after the freeblks proceeds.  If
7249          * directory entry never made it to disk they
7250          * can be dumped directly onto the work list.
7251          */
7252         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7253                 /* Skip this directory removal if it is intended to remain. */
7254                 if (dirrem->dm_offset < blkoff)
7255                         continue;
7256                 /*
7257                  * If there are any dirrems we wait for the journal write
7258                  * to complete and then restart the buf scan as the lock
7259                  * has been dropped.
7260                  */
7261                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7262                         jwait(&jremref->jr_list, MNT_WAIT);
7263                         return (ERESTART);
7264                 }
7265                 LIST_REMOVE(dirrem, dm_next);
7266                 dirrem->dm_dirinum = pagedep->pd_ino;
7267                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7268         }
7269         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7270                 jwait(&jmvref->jm_list, MNT_WAIT);
7271                 return (ERESTART);
7272         }
7273         /*
7274          * When we're partially truncating a pagedep we just want to flush
7275          * journal entries and return.  There can not be any adds in the
7276          * truncated portion of the directory and newblk must remain if
7277          * part of the block remains.
7278          */
7279         if (blkoff != 0) {
7280                 struct diradd *dap;
7281
7282                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7283                         if (dap->da_offset > blkoff)
7284                                 panic("cancel_pagedep: diradd %p off %d > %d",
7285                                     dap, dap->da_offset, blkoff);
7286                 for (i = 0; i < DAHASHSZ; i++)
7287                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7288                                 if (dap->da_offset > blkoff)
7289                                         panic("cancel_pagedep: diradd %p off %d > %d",
7290                                             dap, dap->da_offset, blkoff);
7291                 return (0);
7292         }
7293         /*
7294          * There should be no directory add dependencies present
7295          * as the directory could not be truncated until all
7296          * children were removed.
7297          */
7298         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7299             ("deallocate_dependencies: pendinghd != NULL"));
7300         for (i = 0; i < DAHASHSZ; i++)
7301                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7302                     ("deallocate_dependencies: diraddhd != NULL"));
7303         if ((pagedep->pd_state & NEWBLOCK) != 0)
7304                 free_newdirblk(pagedep->pd_newdirblk);
7305         if (free_pagedep(pagedep) == 0)
7306                 panic("Failed to free pagedep %p", pagedep);
7307         return (0);
7308 }
7309
7310 /*
7311  * Reclaim any dependency structures from a buffer that is about to
7312  * be reallocated to a new vnode. The buffer must be locked, thus,
7313  * no I/O completion operations can occur while we are manipulating
7314  * its associated dependencies. The mutex is held so that other I/O's
7315  * associated with related dependencies do not occur.
7316  */
7317 static int
7318 deallocate_dependencies(bp, freeblks, off)
7319         struct buf *bp;
7320         struct freeblks *freeblks;
7321         int off;
7322 {
7323         struct indirdep *indirdep;
7324         struct pagedep *pagedep;
7325         struct worklist *wk, *wkn;
7326         struct ufsmount *ump;
7327
7328         ump = softdep_bp_to_mp(bp);
7329         if (ump == NULL)
7330                 goto done;
7331         ACQUIRE_LOCK(ump);
7332         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7333                 switch (wk->wk_type) {
7334                 case D_INDIRDEP:
7335                         indirdep = WK_INDIRDEP(wk);
7336                         if (bp->b_lblkno >= 0 ||
7337                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7338                                 panic("deallocate_dependencies: not indir");
7339                         cancel_indirdep(indirdep, bp, freeblks);
7340                         continue;
7341
7342                 case D_PAGEDEP:
7343                         pagedep = WK_PAGEDEP(wk);
7344                         if (cancel_pagedep(pagedep, freeblks, off)) {
7345                                 FREE_LOCK(ump);
7346                                 return (ERESTART);
7347                         }
7348                         continue;
7349
7350                 case D_ALLOCINDIR:
7351                         /*
7352                          * Simply remove the allocindir, we'll find it via
7353                          * the indirdep where we can clear pointers if
7354                          * needed.
7355                          */
7356                         WORKLIST_REMOVE(wk);
7357                         continue;
7358
7359                 case D_FREEWORK:
7360                         /*
7361                          * A truncation is waiting for the zero'd pointers
7362                          * to be written.  It can be freed when the freeblks
7363                          * is journaled.
7364                          */
7365                         WORKLIST_REMOVE(wk);
7366                         wk->wk_state |= ONDEPLIST;
7367                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7368                         break;
7369
7370                 case D_ALLOCDIRECT:
7371                         if (off != 0)
7372                                 continue;
7373                         /* FALLTHROUGH */
7374                 default:
7375                         panic("deallocate_dependencies: Unexpected type %s",
7376                             TYPENAME(wk->wk_type));
7377                         /* NOTREACHED */
7378                 }
7379         }
7380         FREE_LOCK(ump);
7381 done:
7382         /*
7383          * Don't throw away this buf, we were partially truncating and
7384          * some deps may always remain.
7385          */
7386         if (off) {
7387                 allocbuf(bp, off);
7388                 bp->b_vflags |= BV_SCANNED;
7389                 return (EBUSY);
7390         }
7391         bp->b_flags |= B_INVAL | B_NOCACHE;
7392
7393         return (0);
7394 }
7395
7396 /*
7397  * An allocdirect is being canceled due to a truncate.  We must make sure
7398  * the journal entry is released in concert with the blkfree that releases
7399  * the storage.  Completed journal entries must not be released until the
7400  * space is no longer pointed to by the inode or in the bitmap.
7401  */
7402 static void
7403 cancel_allocdirect(adphead, adp, freeblks)
7404         struct allocdirectlst *adphead;
7405         struct allocdirect *adp;
7406         struct freeblks *freeblks;
7407 {
7408         struct freework *freework;
7409         struct newblk *newblk;
7410         struct worklist *wk;
7411
7412         TAILQ_REMOVE(adphead, adp, ad_next);
7413         newblk = (struct newblk *)adp;
7414         freework = NULL;
7415         /*
7416          * Find the correct freework structure.
7417          */
7418         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7419                 if (wk->wk_type != D_FREEWORK)
7420                         continue;
7421                 freework = WK_FREEWORK(wk);
7422                 if (freework->fw_blkno == newblk->nb_newblkno)
7423                         break;
7424         }
7425         if (freework == NULL)
7426                 panic("cancel_allocdirect: Freework not found");
7427         /*
7428          * If a newblk exists at all we still have the journal entry that
7429          * initiated the allocation so we do not need to journal the free.
7430          */
7431         cancel_jfreeblk(freeblks, freework->fw_blkno);
7432         /*
7433          * If the journal hasn't been written the jnewblk must be passed
7434          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7435          * this by linking the journal dependency into the freework to be
7436          * freed when freework_freeblock() is called.  If the journal has
7437          * been written we can simply reclaim the journal space when the
7438          * freeblks work is complete.
7439          */
7440         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7441             &freeblks->fb_jwork);
7442         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7443 }
7444
7445
7446 /*
7447  * Cancel a new block allocation.  May be an indirect or direct block.  We
7448  * remove it from various lists and return any journal record that needs to
7449  * be resolved by the caller.
7450  *
7451  * A special consideration is made for indirects which were never pointed
7452  * at on disk and will never be found once this block is released.
7453  */
7454 static struct jnewblk *
7455 cancel_newblk(newblk, wk, wkhd)
7456         struct newblk *newblk;
7457         struct worklist *wk;
7458         struct workhead *wkhd;
7459 {
7460         struct jnewblk *jnewblk;
7461
7462         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7463             
7464         newblk->nb_state |= GOINGAWAY;
7465         /*
7466          * Previously we traversed the completedhd on each indirdep
7467          * attached to this newblk to cancel them and gather journal
7468          * work.  Since we need only the oldest journal segment and
7469          * the lowest point on the tree will always have the oldest
7470          * journal segment we are free to release the segments
7471          * of any subordinates and may leave the indirdep list to
7472          * indirdep_complete() when this newblk is freed.
7473          */
7474         if (newblk->nb_state & ONDEPLIST) {
7475                 newblk->nb_state &= ~ONDEPLIST;
7476                 LIST_REMOVE(newblk, nb_deps);
7477         }
7478         if (newblk->nb_state & ONWORKLIST)
7479                 WORKLIST_REMOVE(&newblk->nb_list);
7480         /*
7481          * If the journal entry hasn't been written we save a pointer to
7482          * the dependency that frees it until it is written or the
7483          * superseding operation completes.
7484          */
7485         jnewblk = newblk->nb_jnewblk;
7486         if (jnewblk != NULL && wk != NULL) {
7487                 newblk->nb_jnewblk = NULL;
7488                 jnewblk->jn_dep = wk;
7489         }
7490         if (!LIST_EMPTY(&newblk->nb_jwork))
7491                 jwork_move(wkhd, &newblk->nb_jwork);
7492         /*
7493          * When truncating we must free the newdirblk early to remove
7494          * the pagedep from the hash before returning.
7495          */
7496         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7497                 free_newdirblk(WK_NEWDIRBLK(wk));
7498         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7499                 panic("cancel_newblk: extra newdirblk");
7500
7501         return (jnewblk);
7502 }
7503
7504 /*
7505  * Schedule the freefrag associated with a newblk to be released once
7506  * the pointers are written and the previous block is no longer needed.
7507  */
7508 static void
7509 newblk_freefrag(newblk)
7510         struct newblk *newblk;
7511 {
7512         struct freefrag *freefrag;
7513
7514         if (newblk->nb_freefrag == NULL)
7515                 return;
7516         freefrag = newblk->nb_freefrag;
7517         newblk->nb_freefrag = NULL;
7518         freefrag->ff_state |= COMPLETE;
7519         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7520                 add_to_worklist(&freefrag->ff_list, 0);
7521 }
7522
7523 /*
7524  * Free a newblk. Generate a new freefrag work request if appropriate.
7525  * This must be called after the inode pointer and any direct block pointers
7526  * are valid or fully removed via truncate or frag extension.
7527  */
7528 static void
7529 free_newblk(newblk)
7530         struct newblk *newblk;
7531 {
7532         struct indirdep *indirdep;
7533         struct worklist *wk;
7534
7535         KASSERT(newblk->nb_jnewblk == NULL,
7536             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7537         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7538             ("free_newblk: unclaimed newblk"));
7539         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7540         newblk_freefrag(newblk);
7541         if (newblk->nb_state & ONDEPLIST)
7542                 LIST_REMOVE(newblk, nb_deps);
7543         if (newblk->nb_state & ONWORKLIST)
7544                 WORKLIST_REMOVE(&newblk->nb_list);
7545         LIST_REMOVE(newblk, nb_hash);
7546         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7547                 free_newdirblk(WK_NEWDIRBLK(wk));
7548         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7549                 panic("free_newblk: extra newdirblk");
7550         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7551                 indirdep_complete(indirdep);
7552         handle_jwork(&newblk->nb_jwork);
7553         WORKITEM_FREE(newblk, D_NEWBLK);
7554 }
7555
7556 /*
7557  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7558  */
7559 static void
7560 free_newdirblk(newdirblk)
7561         struct newdirblk *newdirblk;
7562 {
7563         struct pagedep *pagedep;
7564         struct diradd *dap;
7565         struct worklist *wk;
7566
7567         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7568         WORKLIST_REMOVE(&newdirblk->db_list);
7569         /*
7570          * If the pagedep is still linked onto the directory buffer
7571          * dependency chain, then some of the entries on the
7572          * pd_pendinghd list may not be committed to disk yet. In
7573          * this case, we will simply clear the NEWBLOCK flag and
7574          * let the pd_pendinghd list be processed when the pagedep
7575          * is next written. If the pagedep is no longer on the buffer
7576          * dependency chain, then all the entries on the pd_pending
7577          * list are committed to disk and we can free them here.
7578          */
7579         pagedep = newdirblk->db_pagedep;
7580         pagedep->pd_state &= ~NEWBLOCK;
7581         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7582                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7583                         free_diradd(dap, NULL);
7584                 /*
7585                  * If no dependencies remain, the pagedep will be freed.
7586                  */
7587                 free_pagedep(pagedep);
7588         }
7589         /* Should only ever be one item in the list. */
7590         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7591                 WORKLIST_REMOVE(wk);
7592                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7593         }
7594         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7595 }
7596
7597 /*
7598  * Prepare an inode to be freed. The actual free operation is not
7599  * done until the zero'ed inode has been written to disk.
7600  */
7601 void
7602 softdep_freefile(pvp, ino, mode)
7603         struct vnode *pvp;
7604         ino_t ino;
7605         int mode;
7606 {
7607         struct inode *ip = VTOI(pvp);
7608         struct inodedep *inodedep;
7609         struct freefile *freefile;
7610         struct freeblks *freeblks;
7611         struct ufsmount *ump;
7612
7613         ump = ITOUMP(ip);
7614         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7615             ("softdep_freefile called on non-softdep filesystem"));
7616         /*
7617          * This sets up the inode de-allocation dependency.
7618          */
7619         freefile = malloc(sizeof(struct freefile),
7620                 M_FREEFILE, M_SOFTDEP_FLAGS);
7621         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7622         freefile->fx_mode = mode;
7623         freefile->fx_oldinum = ino;
7624         freefile->fx_devvp = ump->um_devvp;
7625         LIST_INIT(&freefile->fx_jwork);
7626         UFS_LOCK(ump);
7627         ump->um_fs->fs_pendinginodes += 1;
7628         UFS_UNLOCK(ump);
7629
7630         /*
7631          * If the inodedep does not exist, then the zero'ed inode has
7632          * been written to disk. If the allocated inode has never been
7633          * written to disk, then the on-disk inode is zero'ed. In either
7634          * case we can free the file immediately.  If the journal was
7635          * canceled before being written the inode will never make it to
7636          * disk and we must send the canceled journal entrys to
7637          * ffs_freefile() to be cleared in conjunction with the bitmap.
7638          * Any blocks waiting on the inode to write can be safely freed
7639          * here as it will never been written.
7640          */
7641         ACQUIRE_LOCK(ump);
7642         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7643         if (inodedep) {
7644                 /*
7645                  * Clear out freeblks that no longer need to reference
7646                  * this inode.
7647                  */
7648                 while ((freeblks =
7649                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7650                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7651                             fb_next);
7652                         freeblks->fb_state &= ~ONDEPLIST;
7653                 }
7654                 /*
7655                  * Remove this inode from the unlinked list.
7656                  */
7657                 if (inodedep->id_state & UNLINKED) {
7658                         /*
7659                          * Save the journal work to be freed with the bitmap
7660                          * before we clear UNLINKED.  Otherwise it can be lost
7661                          * if the inode block is written.
7662                          */
7663                         handle_bufwait(inodedep, &freefile->fx_jwork);
7664                         clear_unlinked_inodedep(inodedep);
7665                         /*
7666                          * Re-acquire inodedep as we've dropped the
7667                          * per-filesystem lock in clear_unlinked_inodedep().
7668                          */
7669                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7670                 }
7671         }
7672         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7673                 FREE_LOCK(ump);
7674                 handle_workitem_freefile(freefile);
7675                 return;
7676         }
7677         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7678                 inodedep->id_state |= GOINGAWAY;
7679         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7680         FREE_LOCK(ump);
7681         if (ip->i_number == ino)
7682                 UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7683 }
7684
7685 /*
7686  * Check to see if an inode has never been written to disk. If
7687  * so free the inodedep and return success, otherwise return failure.
7688  *
7689  * If we still have a bitmap dependency, then the inode has never
7690  * been written to disk. Drop the dependency as it is no longer
7691  * necessary since the inode is being deallocated. We set the
7692  * ALLCOMPLETE flags since the bitmap now properly shows that the
7693  * inode is not allocated. Even if the inode is actively being
7694  * written, it has been rolled back to its zero'ed state, so we
7695  * are ensured that a zero inode is what is on the disk. For short
7696  * lived files, this change will usually result in removing all the
7697  * dependencies from the inode so that it can be freed immediately.
7698  */
7699 static int
7700 check_inode_unwritten(inodedep)
7701         struct inodedep *inodedep;
7702 {
7703
7704         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7705
7706         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7707             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7708             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7709             !LIST_EMPTY(&inodedep->id_bufwait) ||
7710             !LIST_EMPTY(&inodedep->id_inowait) ||
7711             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7712             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7713             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7714             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7715             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7716             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7717             inodedep->id_mkdiradd != NULL || 
7718             inodedep->id_nlinkdelta != 0)
7719                 return (0);
7720         /*
7721          * Another process might be in initiate_write_inodeblock_ufs[12]
7722          * trying to allocate memory without holding "Softdep Lock".
7723          */
7724         if ((inodedep->id_state & IOSTARTED) != 0 &&
7725             inodedep->id_savedino1 == NULL)
7726                 return (0);
7727
7728         if (inodedep->id_state & ONDEPLIST)
7729                 LIST_REMOVE(inodedep, id_deps);
7730         inodedep->id_state &= ~ONDEPLIST;
7731         inodedep->id_state |= ALLCOMPLETE;
7732         inodedep->id_bmsafemap = NULL;
7733         if (inodedep->id_state & ONWORKLIST)
7734                 WORKLIST_REMOVE(&inodedep->id_list);
7735         if (inodedep->id_savedino1 != NULL) {
7736                 free(inodedep->id_savedino1, M_SAVEDINO);
7737                 inodedep->id_savedino1 = NULL;
7738         }
7739         if (free_inodedep(inodedep) == 0)
7740                 panic("check_inode_unwritten: busy inode");
7741         return (1);
7742 }
7743
7744 static int
7745 check_inodedep_free(inodedep)
7746         struct inodedep *inodedep;
7747 {
7748
7749         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7750         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7751             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7752             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7753             !LIST_EMPTY(&inodedep->id_bufwait) ||
7754             !LIST_EMPTY(&inodedep->id_inowait) ||
7755             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7756             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7757             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7758             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7759             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7760             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7761             inodedep->id_mkdiradd != NULL ||
7762             inodedep->id_nlinkdelta != 0 ||
7763             inodedep->id_savedino1 != NULL)
7764                 return (0);
7765         return (1);
7766 }
7767
7768 /*
7769  * Try to free an inodedep structure. Return 1 if it could be freed.
7770  */
7771 static int
7772 free_inodedep(inodedep)
7773         struct inodedep *inodedep;
7774 {
7775
7776         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7777         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7778             !check_inodedep_free(inodedep))
7779                 return (0);
7780         if (inodedep->id_state & ONDEPLIST)
7781                 LIST_REMOVE(inodedep, id_deps);
7782         LIST_REMOVE(inodedep, id_hash);
7783         WORKITEM_FREE(inodedep, D_INODEDEP);
7784         return (1);
7785 }
7786
7787 /*
7788  * Free the block referenced by a freework structure.  The parent freeblks
7789  * structure is released and completed when the final cg bitmap reaches
7790  * the disk.  This routine may be freeing a jnewblk which never made it to
7791  * disk in which case we do not have to wait as the operation is undone
7792  * in memory immediately.
7793  */
7794 static void
7795 freework_freeblock(freework, key)
7796         struct freework *freework;
7797         u_long key;
7798 {
7799         struct freeblks *freeblks;
7800         struct jnewblk *jnewblk;
7801         struct ufsmount *ump;
7802         struct workhead wkhd;
7803         struct fs *fs;
7804         int bsize;
7805         int needj;
7806
7807         ump = VFSTOUFS(freework->fw_list.wk_mp);
7808         LOCK_OWNED(ump);
7809         /*
7810          * Handle partial truncate separately.
7811          */
7812         if (freework->fw_indir) {
7813                 complete_trunc_indir(freework);
7814                 return;
7815         }
7816         freeblks = freework->fw_freeblks;
7817         fs = ump->um_fs;
7818         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7819         bsize = lfragtosize(fs, freework->fw_frags);
7820         LIST_INIT(&wkhd);
7821         /*
7822          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7823          * on the indirblk hashtable and prevents premature freeing.
7824          */
7825         freework->fw_state |= DEPCOMPLETE;
7826         /*
7827          * SUJ needs to wait for the segment referencing freed indirect
7828          * blocks to expire so that we know the checker will not confuse
7829          * a re-allocated indirect block with its old contents.
7830          */
7831         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7832                 indirblk_insert(freework);
7833         /*
7834          * If we are canceling an existing jnewblk pass it to the free
7835          * routine, otherwise pass the freeblk which will ultimately
7836          * release the freeblks.  If we're not journaling, we can just
7837          * free the freeblks immediately.
7838          */
7839         jnewblk = freework->fw_jnewblk;
7840         if (jnewblk != NULL) {
7841                 cancel_jnewblk(jnewblk, &wkhd);
7842                 needj = 0;
7843         } else if (needj) {
7844                 freework->fw_state |= DELAYEDFREE;
7845                 freeblks->fb_cgwait++;
7846                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7847         }
7848         FREE_LOCK(ump);
7849         freeblks_free(ump, freeblks, btodb(bsize));
7850         CTR4(KTR_SUJ,
7851             "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7852             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7853         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7854             freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7855         ACQUIRE_LOCK(ump);
7856         /*
7857          * The jnewblk will be discarded and the bits in the map never
7858          * made it to disk.  We can immediately free the freeblk.
7859          */
7860         if (needj == 0)
7861                 handle_written_freework(freework);
7862 }
7863
7864 /*
7865  * We enqueue freework items that need processing back on the freeblks and
7866  * add the freeblks to the worklist.  This makes it easier to find all work
7867  * required to flush a truncation in process_truncates().
7868  */
7869 static void
7870 freework_enqueue(freework)
7871         struct freework *freework;
7872 {
7873         struct freeblks *freeblks;
7874
7875         freeblks = freework->fw_freeblks;
7876         if ((freework->fw_state & INPROGRESS) == 0)
7877                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7878         if ((freeblks->fb_state &
7879             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7880             LIST_EMPTY(&freeblks->fb_jblkdephd))
7881                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7882 }
7883
7884 /*
7885  * Start, continue, or finish the process of freeing an indirect block tree.
7886  * The free operation may be paused at any point with fw_off containing the
7887  * offset to restart from.  This enables us to implement some flow control
7888  * for large truncates which may fan out and generate a huge number of
7889  * dependencies.
7890  */
7891 static void
7892 handle_workitem_indirblk(freework)
7893         struct freework *freework;
7894 {
7895         struct freeblks *freeblks;
7896         struct ufsmount *ump;
7897         struct fs *fs;
7898
7899         freeblks = freework->fw_freeblks;
7900         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7901         fs = ump->um_fs;
7902         if (freework->fw_state & DEPCOMPLETE) {
7903                 handle_written_freework(freework);
7904                 return;
7905         }
7906         if (freework->fw_off == NINDIR(fs)) {
7907                 freework_freeblock(freework, SINGLETON_KEY);
7908                 return;
7909         }
7910         freework->fw_state |= INPROGRESS;
7911         FREE_LOCK(ump);
7912         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7913             freework->fw_lbn);
7914         ACQUIRE_LOCK(ump);
7915 }
7916
7917 /*
7918  * Called when a freework structure attached to a cg buf is written.  The
7919  * ref on either the parent or the freeblks structure is released and
7920  * the freeblks is added back to the worklist if there is more work to do.
7921  */
7922 static void
7923 handle_written_freework(freework)
7924         struct freework *freework;
7925 {
7926         struct freeblks *freeblks;
7927         struct freework *parent;
7928
7929         freeblks = freework->fw_freeblks;
7930         parent = freework->fw_parent;
7931         if (freework->fw_state & DELAYEDFREE)
7932                 freeblks->fb_cgwait--;
7933         freework->fw_state |= COMPLETE;
7934         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7935                 WORKITEM_FREE(freework, D_FREEWORK);
7936         if (parent) {
7937                 if (--parent->fw_ref == 0)
7938                         freework_enqueue(parent);
7939                 return;
7940         }
7941         if (--freeblks->fb_ref != 0)
7942                 return;
7943         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7944             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7945                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7946 }
7947
7948 /*
7949  * This workitem routine performs the block de-allocation.
7950  * The workitem is added to the pending list after the updated
7951  * inode block has been written to disk.  As mentioned above,
7952  * checks regarding the number of blocks de-allocated (compared
7953  * to the number of blocks allocated for the file) are also
7954  * performed in this function.
7955  */
7956 static int
7957 handle_workitem_freeblocks(freeblks, flags)
7958         struct freeblks *freeblks;
7959         int flags;
7960 {
7961         struct freework *freework;
7962         struct newblk *newblk;
7963         struct allocindir *aip;
7964         struct ufsmount *ump;
7965         struct worklist *wk;
7966         u_long key;
7967
7968         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7969             ("handle_workitem_freeblocks: Journal entries not written."));
7970         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7971         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7972         ACQUIRE_LOCK(ump);
7973         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7974                 WORKLIST_REMOVE(wk);
7975                 switch (wk->wk_type) {
7976                 case D_DIRREM:
7977                         wk->wk_state |= COMPLETE;
7978                         add_to_worklist(wk, 0);
7979                         continue;
7980
7981                 case D_ALLOCDIRECT:
7982                         free_newblk(WK_NEWBLK(wk));
7983                         continue;
7984
7985                 case D_ALLOCINDIR:
7986                         aip = WK_ALLOCINDIR(wk);
7987                         freework = NULL;
7988                         if (aip->ai_state & DELAYEDFREE) {
7989                                 FREE_LOCK(ump);
7990                                 freework = newfreework(ump, freeblks, NULL,
7991                                     aip->ai_lbn, aip->ai_newblkno,
7992                                     ump->um_fs->fs_frag, 0, 0);
7993                                 ACQUIRE_LOCK(ump);
7994                         }
7995                         newblk = WK_NEWBLK(wk);
7996                         if (newblk->nb_jnewblk) {
7997                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7998                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7999                                 newblk->nb_jnewblk = NULL;
8000                         }
8001                         free_newblk(newblk);
8002                         continue;
8003
8004                 case D_FREEWORK:
8005                         freework = WK_FREEWORK(wk);
8006                         if (freework->fw_lbn <= -UFS_NDADDR)
8007                                 handle_workitem_indirblk(freework);
8008                         else
8009                                 freework_freeblock(freework, key);
8010                         continue;
8011                 default:
8012                         panic("handle_workitem_freeblocks: Unknown type %s",
8013                             TYPENAME(wk->wk_type));
8014                 }
8015         }
8016         if (freeblks->fb_ref != 0) {
8017                 freeblks->fb_state &= ~INPROGRESS;
8018                 wake_worklist(&freeblks->fb_list);
8019                 freeblks = NULL;
8020         }
8021         FREE_LOCK(ump);
8022         ffs_blkrelease_finish(ump, key);
8023         if (freeblks)
8024                 return handle_complete_freeblocks(freeblks, flags);
8025         return (0);
8026 }
8027
8028 /*
8029  * Handle completion of block free via truncate.  This allows fs_pending
8030  * to track the actual free block count more closely than if we only updated
8031  * it at the end.  We must be careful to handle cases where the block count
8032  * on free was incorrect.
8033  */
8034 static void
8035 freeblks_free(ump, freeblks, blocks)
8036         struct ufsmount *ump;
8037         struct freeblks *freeblks;
8038         int blocks;
8039 {
8040         struct fs *fs;
8041         ufs2_daddr_t remain;
8042
8043         UFS_LOCK(ump);
8044         remain = -freeblks->fb_chkcnt;
8045         freeblks->fb_chkcnt += blocks;
8046         if (remain > 0) {
8047                 if (remain < blocks)
8048                         blocks = remain;
8049                 fs = ump->um_fs;
8050                 fs->fs_pendingblocks -= blocks;
8051         }
8052         UFS_UNLOCK(ump);
8053 }
8054
8055 /*
8056  * Once all of the freework workitems are complete we can retire the
8057  * freeblocks dependency and any journal work awaiting completion.  This
8058  * can not be called until all other dependencies are stable on disk.
8059  */
8060 static int
8061 handle_complete_freeblocks(freeblks, flags)
8062         struct freeblks *freeblks;
8063         int flags;
8064 {
8065         struct inodedep *inodedep;
8066         struct inode *ip;
8067         struct vnode *vp;
8068         struct fs *fs;
8069         struct ufsmount *ump;
8070         ufs2_daddr_t spare;
8071
8072         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8073         fs = ump->um_fs;
8074         flags = LK_EXCLUSIVE | flags;
8075         spare = freeblks->fb_chkcnt;
8076
8077         /*
8078          * If we did not release the expected number of blocks we may have
8079          * to adjust the inode block count here.  Only do so if it wasn't
8080          * a truncation to zero and the modrev still matches.
8081          */
8082         if (spare && freeblks->fb_len != 0) {
8083                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8084                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8085                         return (EBUSY);
8086                 ip = VTOI(vp);
8087                 if (ip->i_mode == 0) {
8088                         vgone(vp);
8089                 } else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8090                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8091                         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8092                         /*
8093                          * We must wait so this happens before the
8094                          * journal is reclaimed.
8095                          */
8096                         ffs_update(vp, 1);
8097                 }
8098                 vput(vp);
8099         }
8100         if (spare < 0) {
8101                 UFS_LOCK(ump);
8102                 fs->fs_pendingblocks += spare;
8103                 UFS_UNLOCK(ump);
8104         }
8105 #ifdef QUOTA
8106         /* Handle spare. */
8107         if (spare)
8108                 quotaadj(freeblks->fb_quota, ump, -spare);
8109         quotarele(freeblks->fb_quota);
8110 #endif
8111         ACQUIRE_LOCK(ump);
8112         if (freeblks->fb_state & ONDEPLIST) {
8113                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8114                     0, &inodedep);
8115                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8116                 freeblks->fb_state &= ~ONDEPLIST;
8117                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8118                         free_inodedep(inodedep);
8119         }
8120         /*
8121          * All of the freeblock deps must be complete prior to this call
8122          * so it's now safe to complete earlier outstanding journal entries.
8123          */
8124         handle_jwork(&freeblks->fb_jwork);
8125         WORKITEM_FREE(freeblks, D_FREEBLKS);
8126         FREE_LOCK(ump);
8127         return (0);
8128 }
8129
8130 /*
8131  * Release blocks associated with the freeblks and stored in the indirect
8132  * block dbn. If level is greater than SINGLE, the block is an indirect block
8133  * and recursive calls to indirtrunc must be used to cleanse other indirect
8134  * blocks.
8135  *
8136  * This handles partial and complete truncation of blocks.  Partial is noted
8137  * with goingaway == 0.  In this case the freework is completed after the
8138  * zero'd indirects are written to disk.  For full truncation the freework
8139  * is completed after the block is freed.
8140  */
8141 static void
8142 indir_trunc(freework, dbn, lbn)
8143         struct freework *freework;
8144         ufs2_daddr_t dbn;
8145         ufs_lbn_t lbn;
8146 {
8147         struct freework *nfreework;
8148         struct workhead wkhd;
8149         struct freeblks *freeblks;
8150         struct buf *bp;
8151         struct fs *fs;
8152         struct indirdep *indirdep;
8153         struct mount *mp;
8154         struct ufsmount *ump;
8155         ufs1_daddr_t *bap1;
8156         ufs2_daddr_t nb, nnb, *bap2;
8157         ufs_lbn_t lbnadd, nlbn;
8158         u_long key;
8159         int nblocks, ufs1fmt, freedblocks;
8160         int goingaway, freedeps, needj, level, cnt, i;
8161
8162         freeblks = freework->fw_freeblks;
8163         mp = freeblks->fb_list.wk_mp;
8164         ump = VFSTOUFS(mp);
8165         fs = ump->um_fs;
8166         /*
8167          * Get buffer of block pointers to be freed.  There are three cases:
8168          * 
8169          * 1) Partial truncate caches the indirdep pointer in the freework
8170          *    which provides us a back copy to the save bp which holds the
8171          *    pointers we want to clear.  When this completes the zero
8172          *    pointers are written to the real copy.
8173          * 2) The indirect is being completely truncated, cancel_indirdep()
8174          *    eliminated the real copy and placed the indirdep on the saved
8175          *    copy.  The indirdep and buf are discarded when this completes.
8176          * 3) The indirect was not in memory, we read a copy off of the disk
8177          *    using the devvp and drop and invalidate the buffer when we're
8178          *    done.
8179          */
8180         goingaway = 1;
8181         indirdep = NULL;
8182         if (freework->fw_indir != NULL) {
8183                 goingaway = 0;
8184                 indirdep = freework->fw_indir;
8185                 bp = indirdep->ir_savebp;
8186                 if (bp == NULL || bp->b_blkno != dbn)
8187                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8188                             bp, (intmax_t)dbn);
8189         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8190                 /*
8191                  * The lock prevents the buf dep list from changing and
8192                  * indirects on devvp should only ever have one dependency.
8193                  */
8194                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8195                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8196                         panic("indir_trunc: Bad indirdep %p from buf %p",
8197                             indirdep, bp);
8198         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8199             NOCRED, &bp) != 0) {
8200                 brelse(bp);
8201                 return;
8202         }
8203         ACQUIRE_LOCK(ump);
8204         /* Protects against a race with complete_trunc_indir(). */
8205         freework->fw_state &= ~INPROGRESS;
8206         /*
8207          * If we have an indirdep we need to enforce the truncation order
8208          * and discard it when it is complete.
8209          */
8210         if (indirdep) {
8211                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8212                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8213                         /*
8214                          * Add the complete truncate to the list on the
8215                          * indirdep to enforce in-order processing.
8216                          */
8217                         if (freework->fw_indir == NULL)
8218                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8219                                     freework, fw_next);
8220                         FREE_LOCK(ump);
8221                         return;
8222                 }
8223                 /*
8224                  * If we're goingaway, free the indirdep.  Otherwise it will
8225                  * linger until the write completes.
8226                  */
8227                 if (goingaway)
8228                         free_indirdep(indirdep);
8229         }
8230         FREE_LOCK(ump);
8231         /* Initialize pointers depending on block size. */
8232         if (ump->um_fstype == UFS1) {
8233                 bap1 = (ufs1_daddr_t *)bp->b_data;
8234                 nb = bap1[freework->fw_off];
8235                 ufs1fmt = 1;
8236                 bap2 = NULL;
8237         } else {
8238                 bap2 = (ufs2_daddr_t *)bp->b_data;
8239                 nb = bap2[freework->fw_off];
8240                 ufs1fmt = 0;
8241                 bap1 = NULL;
8242         }
8243         level = lbn_level(lbn);
8244         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8245         lbnadd = lbn_offset(fs, level);
8246         nblocks = btodb(fs->fs_bsize);
8247         nfreework = freework;
8248         freedeps = 0;
8249         cnt = 0;
8250         /*
8251          * Reclaim blocks.  Traverses into nested indirect levels and
8252          * arranges for the current level to be freed when subordinates
8253          * are free when journaling.
8254          */
8255         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8256         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8257                 if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8258                     fs->fs_bsize) != 0)
8259                         nb = 0;
8260                 if (i != NINDIR(fs) - 1) {
8261                         if (ufs1fmt)
8262                                 nnb = bap1[i+1];
8263                         else
8264                                 nnb = bap2[i+1];
8265                 } else
8266                         nnb = 0;
8267                 if (nb == 0)
8268                         continue;
8269                 cnt++;
8270                 if (level != 0) {
8271                         nlbn = (lbn + 1) - (i * lbnadd);
8272                         if (needj != 0) {
8273                                 nfreework = newfreework(ump, freeblks, freework,
8274                                     nlbn, nb, fs->fs_frag, 0, 0);
8275                                 freedeps++;
8276                         }
8277                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8278                 } else {
8279                         struct freedep *freedep;
8280
8281                         /*
8282                          * Attempt to aggregate freedep dependencies for
8283                          * all blocks being released to the same CG.
8284                          */
8285                         LIST_INIT(&wkhd);
8286                         if (needj != 0 &&
8287                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8288                                 freedep = newfreedep(freework);
8289                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8290                                     &freedep->fd_list);
8291                                 freedeps++;
8292                         }
8293                         CTR3(KTR_SUJ,
8294                             "indir_trunc: ino %jd blkno %jd size %d",
8295                             freeblks->fb_inum, nb, fs->fs_bsize);
8296                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8297                             fs->fs_bsize, freeblks->fb_inum,
8298                             freeblks->fb_vtype, &wkhd, key);
8299                 }
8300         }
8301         ffs_blkrelease_finish(ump, key);
8302         if (goingaway) {
8303                 bp->b_flags |= B_INVAL | B_NOCACHE;
8304                 brelse(bp);
8305         }
8306         freedblocks = 0;
8307         if (level == 0)
8308                 freedblocks = (nblocks * cnt);
8309         if (needj == 0)
8310                 freedblocks += nblocks;
8311         freeblks_free(ump, freeblks, freedblocks);
8312         /*
8313          * If we are journaling set up the ref counts and offset so this
8314          * indirect can be completed when its children are free.
8315          */
8316         if (needj) {
8317                 ACQUIRE_LOCK(ump);
8318                 freework->fw_off = i;
8319                 freework->fw_ref += freedeps;
8320                 freework->fw_ref -= NINDIR(fs) + 1;
8321                 if (level == 0)
8322                         freeblks->fb_cgwait += freedeps;
8323                 if (freework->fw_ref == 0)
8324                         freework_freeblock(freework, SINGLETON_KEY);
8325                 FREE_LOCK(ump);
8326                 return;
8327         }
8328         /*
8329          * If we're not journaling we can free the indirect now.
8330          */
8331         dbn = dbtofsb(fs, dbn);
8332         CTR3(KTR_SUJ,
8333             "indir_trunc 2: ino %jd blkno %jd size %d",
8334             freeblks->fb_inum, dbn, fs->fs_bsize);
8335         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8336             freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8337         /* Non SUJ softdep does single-threaded truncations. */
8338         if (freework->fw_blkno == dbn) {
8339                 freework->fw_state |= ALLCOMPLETE;
8340                 ACQUIRE_LOCK(ump);
8341                 handle_written_freework(freework);
8342                 FREE_LOCK(ump);
8343         }
8344         return;
8345 }
8346
8347 /*
8348  * Cancel an allocindir when it is removed via truncation.  When bp is not
8349  * NULL the indirect never appeared on disk and is scheduled to be freed
8350  * independently of the indir so we can more easily track journal work.
8351  */
8352 static void
8353 cancel_allocindir(aip, bp, freeblks, trunc)
8354         struct allocindir *aip;
8355         struct buf *bp;
8356         struct freeblks *freeblks;
8357         int trunc;
8358 {
8359         struct indirdep *indirdep;
8360         struct freefrag *freefrag;
8361         struct newblk *newblk;
8362
8363         newblk = (struct newblk *)aip;
8364         LIST_REMOVE(aip, ai_next);
8365         /*
8366          * We must eliminate the pointer in bp if it must be freed on its
8367          * own due to partial truncate or pending journal work.
8368          */
8369         if (bp && (trunc || newblk->nb_jnewblk)) {
8370                 /*
8371                  * Clear the pointer and mark the aip to be freed
8372                  * directly if it never existed on disk.
8373                  */
8374                 aip->ai_state |= DELAYEDFREE;
8375                 indirdep = aip->ai_indirdep;
8376                 if (indirdep->ir_state & UFS1FMT)
8377                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8378                 else
8379                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8380         }
8381         /*
8382          * When truncating the previous pointer will be freed via
8383          * savedbp.  Eliminate the freefrag which would dup free.
8384          */
8385         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8386                 newblk->nb_freefrag = NULL;
8387                 if (freefrag->ff_jdep)
8388                         cancel_jfreefrag(
8389                             WK_JFREEFRAG(freefrag->ff_jdep));
8390                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8391                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8392         }
8393         /*
8394          * If the journal hasn't been written the jnewblk must be passed
8395          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8396          * this by leaving the journal dependency on the newblk to be freed
8397          * when a freework is created in handle_workitem_freeblocks().
8398          */
8399         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8400         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8401 }
8402
8403 /*
8404  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8405  * in to a newdirblk so any subsequent additions are tracked properly.  The
8406  * caller is responsible for adding the mkdir1 dependency to the journal
8407  * and updating id_mkdiradd.  This function returns with the per-filesystem
8408  * lock held.
8409  */
8410 static struct mkdir *
8411 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8412         struct diradd *dap;
8413         ino_t newinum;
8414         ino_t dinum;
8415         struct buf *newdirbp;
8416         struct mkdir **mkdirp;
8417 {
8418         struct newblk *newblk;
8419         struct pagedep *pagedep;
8420         struct inodedep *inodedep;
8421         struct newdirblk *newdirblk;
8422         struct mkdir *mkdir1, *mkdir2;
8423         struct worklist *wk;
8424         struct jaddref *jaddref;
8425         struct ufsmount *ump;
8426         struct mount *mp;
8427
8428         mp = dap->da_list.wk_mp;
8429         ump = VFSTOUFS(mp);
8430         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8431             M_SOFTDEP_FLAGS);
8432         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8433         LIST_INIT(&newdirblk->db_mkdir);
8434         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8435         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8436         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8437         mkdir1->md_diradd = dap;
8438         mkdir1->md_jaddref = NULL;
8439         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8440         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8441         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8442         mkdir2->md_diradd = dap;
8443         mkdir2->md_jaddref = NULL;
8444         if (MOUNTEDSUJ(mp) == 0) {
8445                 mkdir1->md_state |= DEPCOMPLETE;
8446                 mkdir2->md_state |= DEPCOMPLETE;
8447         }
8448         /*
8449          * Dependency on "." and ".." being written to disk.
8450          */
8451         mkdir1->md_buf = newdirbp;
8452         ACQUIRE_LOCK(VFSTOUFS(mp));
8453         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8454         /*
8455          * We must link the pagedep, allocdirect, and newdirblk for
8456          * the initial file page so the pointer to the new directory
8457          * is not written until the directory contents are live and
8458          * any subsequent additions are not marked live until the
8459          * block is reachable via the inode.
8460          */
8461         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8462                 panic("setup_newdir: lost pagedep");
8463         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8464                 if (wk->wk_type == D_ALLOCDIRECT)
8465                         break;
8466         if (wk == NULL)
8467                 panic("setup_newdir: lost allocdirect");
8468         if (pagedep->pd_state & NEWBLOCK)
8469                 panic("setup_newdir: NEWBLOCK already set");
8470         newblk = WK_NEWBLK(wk);
8471         pagedep->pd_state |= NEWBLOCK;
8472         pagedep->pd_newdirblk = newdirblk;
8473         newdirblk->db_pagedep = pagedep;
8474         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8475         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8476         /*
8477          * Look up the inodedep for the parent directory so that we
8478          * can link mkdir2 into the pending dotdot jaddref or
8479          * the inode write if there is none.  If the inode is
8480          * ALLCOMPLETE and no jaddref is present all dependencies have
8481          * been satisfied and mkdir2 can be freed.
8482          */
8483         inodedep_lookup(mp, dinum, 0, &inodedep);
8484         if (MOUNTEDSUJ(mp)) {
8485                 if (inodedep == NULL)
8486                         panic("setup_newdir: Lost parent.");
8487                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8488                     inoreflst);
8489                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8490                     (jaddref->ja_state & MKDIR_PARENT),
8491                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8492                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8493                 mkdir2->md_jaddref = jaddref;
8494                 jaddref->ja_mkdir = mkdir2;
8495         } else if (inodedep == NULL ||
8496             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8497                 dap->da_state &= ~MKDIR_PARENT;
8498                 WORKITEM_FREE(mkdir2, D_MKDIR);
8499                 mkdir2 = NULL;
8500         } else {
8501                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8502                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8503         }
8504         *mkdirp = mkdir2;
8505
8506         return (mkdir1);
8507 }
8508
8509 /*
8510  * Directory entry addition dependencies.
8511  * 
8512  * When adding a new directory entry, the inode (with its incremented link
8513  * count) must be written to disk before the directory entry's pointer to it.
8514  * Also, if the inode is newly allocated, the corresponding freemap must be
8515  * updated (on disk) before the directory entry's pointer. These requirements
8516  * are met via undo/redo on the directory entry's pointer, which consists
8517  * simply of the inode number.
8518  * 
8519  * As directory entries are added and deleted, the free space within a
8520  * directory block can become fragmented.  The ufs filesystem will compact
8521  * a fragmented directory block to make space for a new entry. When this
8522  * occurs, the offsets of previously added entries change. Any "diradd"
8523  * dependency structures corresponding to these entries must be updated with
8524  * the new offsets.
8525  */
8526
8527 /*
8528  * This routine is called after the in-memory inode's link
8529  * count has been incremented, but before the directory entry's
8530  * pointer to the inode has been set.
8531  */
8532 int
8533 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8534         struct buf *bp;         /* buffer containing directory block */
8535         struct inode *dp;       /* inode for directory */
8536         off_t diroffset;        /* offset of new entry in directory */
8537         ino_t newinum;          /* inode referenced by new directory entry */
8538         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8539         int isnewblk;           /* entry is in a newly allocated block */
8540 {
8541         int offset;             /* offset of new entry within directory block */
8542         ufs_lbn_t lbn;          /* block in directory containing new entry */
8543         struct fs *fs;
8544         struct diradd *dap;
8545         struct newblk *newblk;
8546         struct pagedep *pagedep;
8547         struct inodedep *inodedep;
8548         struct newdirblk *newdirblk;
8549         struct mkdir *mkdir1, *mkdir2;
8550         struct jaddref *jaddref;
8551         struct ufsmount *ump;
8552         struct mount *mp;
8553         int isindir;
8554
8555         mp = ITOVFS(dp);
8556         ump = VFSTOUFS(mp);
8557         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8558             ("softdep_setup_directory_add called on non-softdep filesystem"));
8559         /*
8560          * Whiteouts have no dependencies.
8561          */
8562         if (newinum == UFS_WINO) {
8563                 if (newdirbp != NULL)
8564                         bdwrite(newdirbp);
8565                 return (0);
8566         }
8567         jaddref = NULL;
8568         mkdir1 = mkdir2 = NULL;
8569         fs = ump->um_fs;
8570         lbn = lblkno(fs, diroffset);
8571         offset = blkoff(fs, diroffset);
8572         dap = malloc(sizeof(struct diradd), M_DIRADD,
8573                 M_SOFTDEP_FLAGS|M_ZERO);
8574         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8575         dap->da_offset = offset;
8576         dap->da_newinum = newinum;
8577         dap->da_state = ATTACHED;
8578         LIST_INIT(&dap->da_jwork);
8579         isindir = bp->b_lblkno >= UFS_NDADDR;
8580         newdirblk = NULL;
8581         if (isnewblk &&
8582             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8583                 newdirblk = malloc(sizeof(struct newdirblk),
8584                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8585                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8586                 LIST_INIT(&newdirblk->db_mkdir);
8587         }
8588         /*
8589          * If we're creating a new directory setup the dependencies and set
8590          * the dap state to wait for them.  Otherwise it's COMPLETE and
8591          * we can move on.
8592          */
8593         if (newdirbp == NULL) {
8594                 dap->da_state |= DEPCOMPLETE;
8595                 ACQUIRE_LOCK(ump);
8596         } else {
8597                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8598                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8599                     &mkdir2);
8600         }
8601         /*
8602          * Link into parent directory pagedep to await its being written.
8603          */
8604         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8605 #ifdef INVARIANTS
8606         if (diradd_lookup(pagedep, offset) != NULL)
8607                 panic("softdep_setup_directory_add: %p already at off %d\n",
8608                     diradd_lookup(pagedep, offset), offset);
8609 #endif
8610         dap->da_pagedep = pagedep;
8611         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8612             da_pdlist);
8613         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8614         /*
8615          * If we're journaling, link the diradd into the jaddref so it
8616          * may be completed after the journal entry is written.  Otherwise,
8617          * link the diradd into its inodedep.  If the inode is not yet
8618          * written place it on the bufwait list, otherwise do the post-inode
8619          * write processing to put it on the id_pendinghd list.
8620          */
8621         if (MOUNTEDSUJ(mp)) {
8622                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8623                     inoreflst);
8624                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8625                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8626                 jaddref->ja_diroff = diroffset;
8627                 jaddref->ja_diradd = dap;
8628                 add_to_journal(&jaddref->ja_list);
8629         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8630                 diradd_inode_written(dap, inodedep);
8631         else
8632                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8633         /*
8634          * Add the journal entries for . and .. links now that the primary
8635          * link is written.
8636          */
8637         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8638                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8639                     inoreflst, if_deps);
8640                 KASSERT(jaddref != NULL &&
8641                     jaddref->ja_ino == jaddref->ja_parent &&
8642                     (jaddref->ja_state & MKDIR_BODY),
8643                     ("softdep_setup_directory_add: bad dot jaddref %p",
8644                     jaddref));
8645                 mkdir1->md_jaddref = jaddref;
8646                 jaddref->ja_mkdir = mkdir1;
8647                 /*
8648                  * It is important that the dotdot journal entry
8649                  * is added prior to the dot entry since dot writes
8650                  * both the dot and dotdot links.  These both must
8651                  * be added after the primary link for the journal
8652                  * to remain consistent.
8653                  */
8654                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8655                 add_to_journal(&jaddref->ja_list);
8656         }
8657         /*
8658          * If we are adding a new directory remember this diradd so that if
8659          * we rename it we can keep the dot and dotdot dependencies.  If
8660          * we are adding a new name for an inode that has a mkdiradd we
8661          * must be in rename and we have to move the dot and dotdot
8662          * dependencies to this new name.  The old name is being orphaned
8663          * soon.
8664          */
8665         if (mkdir1 != NULL) {
8666                 if (inodedep->id_mkdiradd != NULL)
8667                         panic("softdep_setup_directory_add: Existing mkdir");
8668                 inodedep->id_mkdiradd = dap;
8669         } else if (inodedep->id_mkdiradd)
8670                 merge_diradd(inodedep, dap);
8671         if (newdirblk != NULL) {
8672                 /*
8673                  * There is nothing to do if we are already tracking
8674                  * this block.
8675                  */
8676                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8677                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8678                         FREE_LOCK(ump);
8679                         return (0);
8680                 }
8681                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8682                     == 0)
8683                         panic("softdep_setup_directory_add: lost entry");
8684                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8685                 pagedep->pd_state |= NEWBLOCK;
8686                 pagedep->pd_newdirblk = newdirblk;
8687                 newdirblk->db_pagedep = pagedep;
8688                 FREE_LOCK(ump);
8689                 /*
8690                  * If we extended into an indirect signal direnter to sync.
8691                  */
8692                 if (isindir)
8693                         return (1);
8694                 return (0);
8695         }
8696         FREE_LOCK(ump);
8697         return (0);
8698 }
8699
8700 /*
8701  * This procedure is called to change the offset of a directory
8702  * entry when compacting a directory block which must be owned
8703  * exclusively by the caller. Note that the actual entry movement
8704  * must be done in this procedure to ensure that no I/O completions
8705  * occur while the move is in progress.
8706  */
8707 void 
8708 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8709         struct buf *bp;         /* Buffer holding directory block. */
8710         struct inode *dp;       /* inode for directory */
8711         caddr_t base;           /* address of dp->i_offset */
8712         caddr_t oldloc;         /* address of old directory location */
8713         caddr_t newloc;         /* address of new directory location */
8714         int entrysize;          /* size of directory entry */
8715 {
8716         int offset, oldoffset, newoffset;
8717         struct pagedep *pagedep;
8718         struct jmvref *jmvref;
8719         struct diradd *dap;
8720         struct direct *de;
8721         struct mount *mp;
8722         struct ufsmount *ump;
8723         ufs_lbn_t lbn;
8724         int flags;
8725
8726         mp = ITOVFS(dp);
8727         ump = VFSTOUFS(mp);
8728         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8729             ("softdep_change_directoryentry_offset called on "
8730              "non-softdep filesystem"));
8731         de = (struct direct *)oldloc;
8732         jmvref = NULL;
8733         flags = 0;
8734         /*
8735          * Moves are always journaled as it would be too complex to
8736          * determine if any affected adds or removes are present in the
8737          * journal.
8738          */
8739         if (MOUNTEDSUJ(mp)) {
8740                 flags = DEPALLOC;
8741                 jmvref = newjmvref(dp, de->d_ino,
8742                     dp->i_offset + (oldloc - base),
8743                     dp->i_offset + (newloc - base));
8744         }
8745         lbn = lblkno(ump->um_fs, dp->i_offset);
8746         offset = blkoff(ump->um_fs, dp->i_offset);
8747         oldoffset = offset + (oldloc - base);
8748         newoffset = offset + (newloc - base);
8749         ACQUIRE_LOCK(ump);
8750         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8751                 goto done;
8752         dap = diradd_lookup(pagedep, oldoffset);
8753         if (dap) {
8754                 dap->da_offset = newoffset;
8755                 newoffset = DIRADDHASH(newoffset);
8756                 oldoffset = DIRADDHASH(oldoffset);
8757                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8758                     newoffset != oldoffset) {
8759                         LIST_REMOVE(dap, da_pdlist);
8760                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8761                             dap, da_pdlist);
8762                 }
8763         }
8764 done:
8765         if (jmvref) {
8766                 jmvref->jm_pagedep = pagedep;
8767                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8768                 add_to_journal(&jmvref->jm_list);
8769         }
8770         bcopy(oldloc, newloc, entrysize);
8771         FREE_LOCK(ump);
8772 }
8773
8774 /*
8775  * Move the mkdir dependencies and journal work from one diradd to another
8776  * when renaming a directory.  The new name must depend on the mkdir deps
8777  * completing as the old name did.  Directories can only have one valid link
8778  * at a time so one must be canonical.
8779  */
8780 static void
8781 merge_diradd(inodedep, newdap)
8782         struct inodedep *inodedep;
8783         struct diradd *newdap;
8784 {
8785         struct diradd *olddap;
8786         struct mkdir *mkdir, *nextmd;
8787         struct ufsmount *ump;
8788         short state;
8789
8790         olddap = inodedep->id_mkdiradd;
8791         inodedep->id_mkdiradd = newdap;
8792         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8793                 newdap->da_state &= ~DEPCOMPLETE;
8794                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8795                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8796                      mkdir = nextmd) {
8797                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8798                         if (mkdir->md_diradd != olddap)
8799                                 continue;
8800                         mkdir->md_diradd = newdap;
8801                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8802                         newdap->da_state |= state;
8803                         olddap->da_state &= ~state;
8804                         if ((olddap->da_state &
8805                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8806                                 break;
8807                 }
8808                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8809                         panic("merge_diradd: unfound ref");
8810         }
8811         /*
8812          * Any mkdir related journal items are not safe to be freed until
8813          * the new name is stable.
8814          */
8815         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8816         olddap->da_state |= DEPCOMPLETE;
8817         complete_diradd(olddap);
8818 }
8819
8820 /*
8821  * Move the diradd to the pending list when all diradd dependencies are
8822  * complete.
8823  */
8824 static void
8825 complete_diradd(dap)
8826         struct diradd *dap;
8827 {
8828         struct pagedep *pagedep;
8829
8830         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8831                 if (dap->da_state & DIRCHG)
8832                         pagedep = dap->da_previous->dm_pagedep;
8833                 else
8834                         pagedep = dap->da_pagedep;
8835                 LIST_REMOVE(dap, da_pdlist);
8836                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8837         }
8838 }
8839
8840 /*
8841  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8842  * add entries and conditonally journal the remove.
8843  */
8844 static void
8845 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8846         struct diradd *dap;
8847         struct dirrem *dirrem;
8848         struct jremref *jremref;
8849         struct jremref *dotremref;
8850         struct jremref *dotdotremref;
8851 {
8852         struct inodedep *inodedep;
8853         struct jaddref *jaddref;
8854         struct inoref *inoref;
8855         struct ufsmount *ump;
8856         struct mkdir *mkdir;
8857
8858         /*
8859          * If no remove references were allocated we're on a non-journaled
8860          * filesystem and can skip the cancel step.
8861          */
8862         if (jremref == NULL) {
8863                 free_diradd(dap, NULL);
8864                 return;
8865         }
8866         /*
8867          * Cancel the primary name an free it if it does not require
8868          * journaling.
8869          */
8870         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8871             0, &inodedep) != 0) {
8872                 /* Abort the addref that reference this diradd.  */
8873                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8874                         if (inoref->if_list.wk_type != D_JADDREF)
8875                                 continue;
8876                         jaddref = (struct jaddref *)inoref;
8877                         if (jaddref->ja_diradd != dap)
8878                                 continue;
8879                         if (cancel_jaddref(jaddref, inodedep,
8880                             &dirrem->dm_jwork) == 0) {
8881                                 free_jremref(jremref);
8882                                 jremref = NULL;
8883                         }
8884                         break;
8885                 }
8886         }
8887         /*
8888          * Cancel subordinate names and free them if they do not require
8889          * journaling.
8890          */
8891         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8892                 ump = VFSTOUFS(dap->da_list.wk_mp);
8893                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8894                         if (mkdir->md_diradd != dap)
8895                                 continue;
8896                         if ((jaddref = mkdir->md_jaddref) == NULL)
8897                                 continue;
8898                         mkdir->md_jaddref = NULL;
8899                         if (mkdir->md_state & MKDIR_PARENT) {
8900                                 if (cancel_jaddref(jaddref, NULL,
8901                                     &dirrem->dm_jwork) == 0) {
8902                                         free_jremref(dotdotremref);
8903                                         dotdotremref = NULL;
8904                                 }
8905                         } else {
8906                                 if (cancel_jaddref(jaddref, inodedep,
8907                                     &dirrem->dm_jwork) == 0) {
8908                                         free_jremref(dotremref);
8909                                         dotremref = NULL;
8910                                 }
8911                         }
8912                 }
8913         }
8914
8915         if (jremref)
8916                 journal_jremref(dirrem, jremref, inodedep);
8917         if (dotremref)
8918                 journal_jremref(dirrem, dotremref, inodedep);
8919         if (dotdotremref)
8920                 journal_jremref(dirrem, dotdotremref, NULL);
8921         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8922         free_diradd(dap, &dirrem->dm_jwork);
8923 }
8924
8925 /*
8926  * Free a diradd dependency structure.
8927  */
8928 static void
8929 free_diradd(dap, wkhd)
8930         struct diradd *dap;
8931         struct workhead *wkhd;
8932 {
8933         struct dirrem *dirrem;
8934         struct pagedep *pagedep;
8935         struct inodedep *inodedep;
8936         struct mkdir *mkdir, *nextmd;
8937         struct ufsmount *ump;
8938
8939         ump = VFSTOUFS(dap->da_list.wk_mp);
8940         LOCK_OWNED(ump);
8941         LIST_REMOVE(dap, da_pdlist);
8942         if (dap->da_state & ONWORKLIST)
8943                 WORKLIST_REMOVE(&dap->da_list);
8944         if ((dap->da_state & DIRCHG) == 0) {
8945                 pagedep = dap->da_pagedep;
8946         } else {
8947                 dirrem = dap->da_previous;
8948                 pagedep = dirrem->dm_pagedep;
8949                 dirrem->dm_dirinum = pagedep->pd_ino;
8950                 dirrem->dm_state |= COMPLETE;
8951                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8952                         add_to_worklist(&dirrem->dm_list, 0);
8953         }
8954         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8955             0, &inodedep) != 0)
8956                 if (inodedep->id_mkdiradd == dap)
8957                         inodedep->id_mkdiradd = NULL;
8958         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8959                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8960                      mkdir = nextmd) {
8961                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8962                         if (mkdir->md_diradd != dap)
8963                                 continue;
8964                         dap->da_state &=
8965                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8966                         LIST_REMOVE(mkdir, md_mkdirs);
8967                         if (mkdir->md_state & ONWORKLIST)
8968                                 WORKLIST_REMOVE(&mkdir->md_list);
8969                         if (mkdir->md_jaddref != NULL)
8970                                 panic("free_diradd: Unexpected jaddref");
8971                         WORKITEM_FREE(mkdir, D_MKDIR);
8972                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8973                                 break;
8974                 }
8975                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8976                         panic("free_diradd: unfound ref");
8977         }
8978         if (inodedep)
8979                 free_inodedep(inodedep);
8980         /*
8981          * Free any journal segments waiting for the directory write.
8982          */
8983         handle_jwork(&dap->da_jwork);
8984         WORKITEM_FREE(dap, D_DIRADD);
8985 }
8986
8987 /*
8988  * Directory entry removal dependencies.
8989  * 
8990  * When removing a directory entry, the entry's inode pointer must be
8991  * zero'ed on disk before the corresponding inode's link count is decremented
8992  * (possibly freeing the inode for re-use). This dependency is handled by
8993  * updating the directory entry but delaying the inode count reduction until
8994  * after the directory block has been written to disk. After this point, the
8995  * inode count can be decremented whenever it is convenient.
8996  */
8997
8998 /*
8999  * This routine should be called immediately after removing
9000  * a directory entry.  The inode's link count should not be
9001  * decremented by the calling procedure -- the soft updates
9002  * code will do this task when it is safe.
9003  */
9004 void 
9005 softdep_setup_remove(bp, dp, ip, isrmdir)
9006         struct buf *bp;         /* buffer containing directory block */
9007         struct inode *dp;       /* inode for the directory being modified */
9008         struct inode *ip;       /* inode for directory entry being removed */
9009         int isrmdir;            /* indicates if doing RMDIR */
9010 {
9011         struct dirrem *dirrem, *prevdirrem;
9012         struct inodedep *inodedep;
9013         struct ufsmount *ump;
9014         int direct;
9015
9016         ump = ITOUMP(ip);
9017         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9018             ("softdep_setup_remove called on non-softdep filesystem"));
9019         /*
9020          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9021          * newdirrem() to setup the full directory remove which requires
9022          * isrmdir > 1.
9023          */
9024         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9025         /*
9026          * Add the dirrem to the inodedep's pending remove list for quick
9027          * discovery later.
9028          */
9029         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9030                 panic("softdep_setup_remove: Lost inodedep.");
9031         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9032         dirrem->dm_state |= ONDEPLIST;
9033         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9034
9035         /*
9036          * If the COMPLETE flag is clear, then there were no active
9037          * entries and we want to roll back to a zeroed entry until
9038          * the new inode is committed to disk. If the COMPLETE flag is
9039          * set then we have deleted an entry that never made it to
9040          * disk. If the entry we deleted resulted from a name change,
9041          * then the old name still resides on disk. We cannot delete
9042          * its inode (returned to us in prevdirrem) until the zeroed
9043          * directory entry gets to disk. The new inode has never been
9044          * referenced on the disk, so can be deleted immediately.
9045          */
9046         if ((dirrem->dm_state & COMPLETE) == 0) {
9047                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9048                     dm_next);
9049                 FREE_LOCK(ump);
9050         } else {
9051                 if (prevdirrem != NULL)
9052                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9053                             prevdirrem, dm_next);
9054                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9055                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9056                 FREE_LOCK(ump);
9057                 if (direct)
9058                         handle_workitem_remove(dirrem, 0);
9059         }
9060 }
9061
9062 /*
9063  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9064  * pd_pendinghd list of a pagedep.
9065  */
9066 static struct diradd *
9067 diradd_lookup(pagedep, offset)
9068         struct pagedep *pagedep;
9069         int offset;
9070 {
9071         struct diradd *dap;
9072
9073         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9074                 if (dap->da_offset == offset)
9075                         return (dap);
9076         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9077                 if (dap->da_offset == offset)
9078                         return (dap);
9079         return (NULL);
9080 }
9081
9082 /*
9083  * Search for a .. diradd dependency in a directory that is being removed.
9084  * If the directory was renamed to a new parent we have a diradd rather
9085  * than a mkdir for the .. entry.  We need to cancel it now before
9086  * it is found in truncate().
9087  */
9088 static struct jremref *
9089 cancel_diradd_dotdot(ip, dirrem, jremref)
9090         struct inode *ip;
9091         struct dirrem *dirrem;
9092         struct jremref *jremref;
9093 {
9094         struct pagedep *pagedep;
9095         struct diradd *dap;
9096         struct worklist *wk;
9097
9098         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9099                 return (jremref);
9100         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9101         if (dap == NULL)
9102                 return (jremref);
9103         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9104         /*
9105          * Mark any journal work as belonging to the parent so it is freed
9106          * with the .. reference.
9107          */
9108         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9109                 wk->wk_state |= MKDIR_PARENT;
9110         return (NULL);
9111 }
9112
9113 /*
9114  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9115  * replace it with a dirrem/diradd pair as a result of re-parenting a
9116  * directory.  This ensures that we don't simultaneously have a mkdir and
9117  * a diradd for the same .. entry.
9118  */
9119 static struct jremref *
9120 cancel_mkdir_dotdot(ip, dirrem, jremref)
9121         struct inode *ip;
9122         struct dirrem *dirrem;
9123         struct jremref *jremref;
9124 {
9125         struct inodedep *inodedep;
9126         struct jaddref *jaddref;
9127         struct ufsmount *ump;
9128         struct mkdir *mkdir;
9129         struct diradd *dap;
9130         struct mount *mp;
9131
9132         mp = ITOVFS(ip);
9133         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9134                 return (jremref);
9135         dap = inodedep->id_mkdiradd;
9136         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9137                 return (jremref);
9138         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9139         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9140             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9141                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9142                         break;
9143         if (mkdir == NULL)
9144                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9145         if ((jaddref = mkdir->md_jaddref) != NULL) {
9146                 mkdir->md_jaddref = NULL;
9147                 jaddref->ja_state &= ~MKDIR_PARENT;
9148                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9149                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9150                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9151                         journal_jremref(dirrem, jremref, inodedep);
9152                         jremref = NULL;
9153                 }
9154         }
9155         if (mkdir->md_state & ONWORKLIST)
9156                 WORKLIST_REMOVE(&mkdir->md_list);
9157         mkdir->md_state |= ALLCOMPLETE;
9158         complete_mkdir(mkdir);
9159         return (jremref);
9160 }
9161
9162 static void
9163 journal_jremref(dirrem, jremref, inodedep)
9164         struct dirrem *dirrem;
9165         struct jremref *jremref;
9166         struct inodedep *inodedep;
9167 {
9168
9169         if (inodedep == NULL)
9170                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9171                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9172                         panic("journal_jremref: Lost inodedep");
9173         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9174         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9175         add_to_journal(&jremref->jr_list);
9176 }
9177
9178 static void
9179 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9180         struct dirrem *dirrem;
9181         struct jremref *jremref;
9182         struct jremref *dotremref;
9183         struct jremref *dotdotremref;
9184 {
9185         struct inodedep *inodedep;
9186
9187
9188         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9189             &inodedep) == 0)
9190                 panic("dirrem_journal: Lost inodedep");
9191         journal_jremref(dirrem, jremref, inodedep);
9192         if (dotremref)
9193                 journal_jremref(dirrem, dotremref, inodedep);
9194         if (dotdotremref)
9195                 journal_jremref(dirrem, dotdotremref, NULL);
9196 }
9197
9198 /*
9199  * Allocate a new dirrem if appropriate and return it along with
9200  * its associated pagedep. Called without a lock, returns with lock.
9201  */
9202 static struct dirrem *
9203 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9204         struct buf *bp;         /* buffer containing directory block */
9205         struct inode *dp;       /* inode for the directory being modified */
9206         struct inode *ip;       /* inode for directory entry being removed */
9207         int isrmdir;            /* indicates if doing RMDIR */
9208         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9209 {
9210         int offset;
9211         ufs_lbn_t lbn;
9212         struct diradd *dap;
9213         struct dirrem *dirrem;
9214         struct pagedep *pagedep;
9215         struct jremref *jremref;
9216         struct jremref *dotremref;
9217         struct jremref *dotdotremref;
9218         struct vnode *dvp;
9219         struct ufsmount *ump;
9220
9221         /*
9222          * Whiteouts have no deletion dependencies.
9223          */
9224         if (ip == NULL)
9225                 panic("newdirrem: whiteout");
9226         dvp = ITOV(dp);
9227         ump = ITOUMP(dp);
9228
9229         /*
9230          * If the system is over its limit and our filesystem is
9231          * responsible for more than our share of that usage and
9232          * we are not a snapshot, request some inodedep cleanup.
9233          * Limiting the number of dirrem structures will also limit
9234          * the number of freefile and freeblks structures.
9235          */
9236         ACQUIRE_LOCK(ump);
9237         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9238                 schedule_cleanup(UFSTOVFS(ump));
9239         else
9240                 FREE_LOCK(ump);
9241         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9242             M_ZERO);
9243         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9244         LIST_INIT(&dirrem->dm_jremrefhd);
9245         LIST_INIT(&dirrem->dm_jwork);
9246         dirrem->dm_state = isrmdir ? RMDIR : 0;
9247         dirrem->dm_oldinum = ip->i_number;
9248         *prevdirremp = NULL;
9249         /*
9250          * Allocate remove reference structures to track journal write
9251          * dependencies.  We will always have one for the link and
9252          * when doing directories we will always have one more for dot.
9253          * When renaming a directory we skip the dotdot link change so
9254          * this is not needed.
9255          */
9256         jremref = dotremref = dotdotremref = NULL;
9257         if (DOINGSUJ(dvp)) {
9258                 if (isrmdir) {
9259                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9260                             ip->i_effnlink + 2);
9261                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9262                             ip->i_effnlink + 1);
9263                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9264                             dp->i_effnlink + 1);
9265                         dotdotremref->jr_state |= MKDIR_PARENT;
9266                 } else
9267                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9268                             ip->i_effnlink + 1);
9269         }
9270         ACQUIRE_LOCK(ump);
9271         lbn = lblkno(ump->um_fs, dp->i_offset);
9272         offset = blkoff(ump->um_fs, dp->i_offset);
9273         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9274             &pagedep);
9275         dirrem->dm_pagedep = pagedep;
9276         dirrem->dm_offset = offset;
9277         /*
9278          * If we're renaming a .. link to a new directory, cancel any
9279          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9280          * the jremref is preserved for any potential diradd in this
9281          * location.  This can not coincide with a rmdir.
9282          */
9283         if (dp->i_offset == DOTDOT_OFFSET) {
9284                 if (isrmdir)
9285                         panic("newdirrem: .. directory change during remove?");
9286                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9287         }
9288         /*
9289          * If we're removing a directory search for the .. dependency now and
9290          * cancel it.  Any pending journal work will be added to the dirrem
9291          * to be completed when the workitem remove completes.
9292          */
9293         if (isrmdir)
9294                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9295         /*
9296          * Check for a diradd dependency for the same directory entry.
9297          * If present, then both dependencies become obsolete and can
9298          * be de-allocated.
9299          */
9300         dap = diradd_lookup(pagedep, offset);
9301         if (dap == NULL) {
9302                 /*
9303                  * Link the jremref structures into the dirrem so they are
9304                  * written prior to the pagedep.
9305                  */
9306                 if (jremref)
9307                         dirrem_journal(dirrem, jremref, dotremref,
9308                             dotdotremref);
9309                 return (dirrem);
9310         }
9311         /*
9312          * Must be ATTACHED at this point.
9313          */
9314         if ((dap->da_state & ATTACHED) == 0)
9315                 panic("newdirrem: not ATTACHED");
9316         if (dap->da_newinum != ip->i_number)
9317                 panic("newdirrem: inum %ju should be %ju",
9318                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9319         /*
9320          * If we are deleting a changed name that never made it to disk,
9321          * then return the dirrem describing the previous inode (which
9322          * represents the inode currently referenced from this entry on disk).
9323          */
9324         if ((dap->da_state & DIRCHG) != 0) {
9325                 *prevdirremp = dap->da_previous;
9326                 dap->da_state &= ~DIRCHG;
9327                 dap->da_pagedep = pagedep;
9328         }
9329         /*
9330          * We are deleting an entry that never made it to disk.
9331          * Mark it COMPLETE so we can delete its inode immediately.
9332          */
9333         dirrem->dm_state |= COMPLETE;
9334         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9335 #ifdef INVARIANTS
9336         if (isrmdir == 0) {
9337                 struct worklist *wk;
9338
9339                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9340                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9341                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9342         }
9343 #endif
9344
9345         return (dirrem);
9346 }
9347
9348 /*
9349  * Directory entry change dependencies.
9350  * 
9351  * Changing an existing directory entry requires that an add operation
9352  * be completed first followed by a deletion. The semantics for the addition
9353  * are identical to the description of adding a new entry above except
9354  * that the rollback is to the old inode number rather than zero. Once
9355  * the addition dependency is completed, the removal is done as described
9356  * in the removal routine above.
9357  */
9358
9359 /*
9360  * This routine should be called immediately after changing
9361  * a directory entry.  The inode's link count should not be
9362  * decremented by the calling procedure -- the soft updates
9363  * code will perform this task when it is safe.
9364  */
9365 void 
9366 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9367         struct buf *bp;         /* buffer containing directory block */
9368         struct inode *dp;       /* inode for the directory being modified */
9369         struct inode *ip;       /* inode for directory entry being removed */
9370         ino_t newinum;          /* new inode number for changed entry */
9371         int isrmdir;            /* indicates if doing RMDIR */
9372 {
9373         int offset;
9374         struct diradd *dap = NULL;
9375         struct dirrem *dirrem, *prevdirrem;
9376         struct pagedep *pagedep;
9377         struct inodedep *inodedep;
9378         struct jaddref *jaddref;
9379         struct mount *mp;
9380         struct ufsmount *ump;
9381
9382         mp = ITOVFS(dp);
9383         ump = VFSTOUFS(mp);
9384         offset = blkoff(ump->um_fs, dp->i_offset);
9385         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9386            ("softdep_setup_directory_change called on non-softdep filesystem"));
9387
9388         /*
9389          * Whiteouts do not need diradd dependencies.
9390          */
9391         if (newinum != UFS_WINO) {
9392                 dap = malloc(sizeof(struct diradd),
9393                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9394                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9395                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9396                 dap->da_offset = offset;
9397                 dap->da_newinum = newinum;
9398                 LIST_INIT(&dap->da_jwork);
9399         }
9400
9401         /*
9402          * Allocate a new dirrem and ACQUIRE_LOCK.
9403          */
9404         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9405         pagedep = dirrem->dm_pagedep;
9406         /*
9407          * The possible values for isrmdir:
9408          *      0 - non-directory file rename
9409          *      1 - directory rename within same directory
9410          *   inum - directory rename to new directory of given inode number
9411          * When renaming to a new directory, we are both deleting and
9412          * creating a new directory entry, so the link count on the new
9413          * directory should not change. Thus we do not need the followup
9414          * dirrem which is usually done in handle_workitem_remove. We set
9415          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9416          * followup dirrem.
9417          */
9418         if (isrmdir > 1)
9419                 dirrem->dm_state |= DIRCHG;
9420
9421         /*
9422          * Whiteouts have no additional dependencies,
9423          * so just put the dirrem on the correct list.
9424          */
9425         if (newinum == UFS_WINO) {
9426                 if ((dirrem->dm_state & COMPLETE) == 0) {
9427                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9428                             dm_next);
9429                 } else {
9430                         dirrem->dm_dirinum = pagedep->pd_ino;
9431                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9432                                 add_to_worklist(&dirrem->dm_list, 0);
9433                 }
9434                 FREE_LOCK(ump);
9435                 return;
9436         }
9437         /*
9438          * Add the dirrem to the inodedep's pending remove list for quick
9439          * discovery later.  A valid nlinkdelta ensures that this lookup
9440          * will not fail.
9441          */
9442         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9443                 panic("softdep_setup_directory_change: Lost inodedep.");
9444         dirrem->dm_state |= ONDEPLIST;
9445         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9446
9447         /*
9448          * If the COMPLETE flag is clear, then there were no active
9449          * entries and we want to roll back to the previous inode until
9450          * the new inode is committed to disk. If the COMPLETE flag is
9451          * set, then we have deleted an entry that never made it to disk.
9452          * If the entry we deleted resulted from a name change, then the old
9453          * inode reference still resides on disk. Any rollback that we do
9454          * needs to be to that old inode (returned to us in prevdirrem). If
9455          * the entry we deleted resulted from a create, then there is
9456          * no entry on the disk, so we want to roll back to zero rather
9457          * than the uncommitted inode. In either of the COMPLETE cases we
9458          * want to immediately free the unwritten and unreferenced inode.
9459          */
9460         if ((dirrem->dm_state & COMPLETE) == 0) {
9461                 dap->da_previous = dirrem;
9462         } else {
9463                 if (prevdirrem != NULL) {
9464                         dap->da_previous = prevdirrem;
9465                 } else {
9466                         dap->da_state &= ~DIRCHG;
9467                         dap->da_pagedep = pagedep;
9468                 }
9469                 dirrem->dm_dirinum = pagedep->pd_ino;
9470                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9471                         add_to_worklist(&dirrem->dm_list, 0);
9472         }
9473         /*
9474          * Lookup the jaddref for this journal entry.  We must finish
9475          * initializing it and make the diradd write dependent on it.
9476          * If we're not journaling, put it on the id_bufwait list if the
9477          * inode is not yet written. If it is written, do the post-inode
9478          * write processing to put it on the id_pendinghd list.
9479          */
9480         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9481         if (MOUNTEDSUJ(mp)) {
9482                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9483                     inoreflst);
9484                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9485                     ("softdep_setup_directory_change: bad jaddref %p",
9486                     jaddref));
9487                 jaddref->ja_diroff = dp->i_offset;
9488                 jaddref->ja_diradd = dap;
9489                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9490                     dap, da_pdlist);
9491                 add_to_journal(&jaddref->ja_list);
9492         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9493                 dap->da_state |= COMPLETE;
9494                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9495                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9496         } else {
9497                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9498                     dap, da_pdlist);
9499                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9500         }
9501         /*
9502          * If we're making a new name for a directory that has not been
9503          * committed when need to move the dot and dotdot references to
9504          * this new name.
9505          */
9506         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9507                 merge_diradd(inodedep, dap);
9508         FREE_LOCK(ump);
9509 }
9510
9511 /*
9512  * Called whenever the link count on an inode is changed.
9513  * It creates an inode dependency so that the new reference(s)
9514  * to the inode cannot be committed to disk until the updated
9515  * inode has been written.
9516  */
9517 void
9518 softdep_change_linkcnt(ip)
9519         struct inode *ip;       /* the inode with the increased link count */
9520 {
9521         struct inodedep *inodedep;
9522         struct ufsmount *ump;
9523
9524         ump = ITOUMP(ip);
9525         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9526             ("softdep_change_linkcnt called on non-softdep filesystem"));
9527         ACQUIRE_LOCK(ump);
9528         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9529         if (ip->i_nlink < ip->i_effnlink)
9530                 panic("softdep_change_linkcnt: bad delta");
9531         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9532         FREE_LOCK(ump);
9533 }
9534
9535 /*
9536  * Attach a sbdep dependency to the superblock buf so that we can keep
9537  * track of the head of the linked list of referenced but unlinked inodes.
9538  */
9539 void
9540 softdep_setup_sbupdate(ump, fs, bp)
9541         struct ufsmount *ump;
9542         struct fs *fs;
9543         struct buf *bp;
9544 {
9545         struct sbdep *sbdep;
9546         struct worklist *wk;
9547
9548         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9549             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9550         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9551                 if (wk->wk_type == D_SBDEP)
9552                         break;
9553         if (wk != NULL)
9554                 return;
9555         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9556         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9557         sbdep->sb_fs = fs;
9558         sbdep->sb_ump = ump;
9559         ACQUIRE_LOCK(ump);
9560         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9561         FREE_LOCK(ump);
9562 }
9563
9564 /*
9565  * Return the first unlinked inodedep which is ready to be the head of the
9566  * list.  The inodedep and all those after it must have valid next pointers.
9567  */
9568 static struct inodedep *
9569 first_unlinked_inodedep(ump)
9570         struct ufsmount *ump;
9571 {
9572         struct inodedep *inodedep;
9573         struct inodedep *idp;
9574
9575         LOCK_OWNED(ump);
9576         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9577             inodedep; inodedep = idp) {
9578                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9579                         return (NULL);
9580                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9581                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9582                         break;
9583                 if ((inodedep->id_state & UNLINKPREV) == 0)
9584                         break;
9585         }
9586         return (inodedep);
9587 }
9588
9589 /*
9590  * Set the sujfree unlinked head pointer prior to writing a superblock.
9591  */
9592 static void
9593 initiate_write_sbdep(sbdep)
9594         struct sbdep *sbdep;
9595 {
9596         struct inodedep *inodedep;
9597         struct fs *bpfs;
9598         struct fs *fs;
9599
9600         bpfs = sbdep->sb_fs;
9601         fs = sbdep->sb_ump->um_fs;
9602         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9603         if (inodedep) {
9604                 fs->fs_sujfree = inodedep->id_ino;
9605                 inodedep->id_state |= UNLINKPREV;
9606         } else
9607                 fs->fs_sujfree = 0;
9608         bpfs->fs_sujfree = fs->fs_sujfree;
9609         /*
9610          * Because we have made changes to the superblock, we need to
9611          * recompute its check-hash.
9612          */
9613         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9614 }
9615
9616 /*
9617  * After a superblock is written determine whether it must be written again
9618  * due to a changing unlinked list head.
9619  */
9620 static int
9621 handle_written_sbdep(sbdep, bp)
9622         struct sbdep *sbdep;
9623         struct buf *bp;
9624 {
9625         struct inodedep *inodedep;
9626         struct fs *fs;
9627
9628         LOCK_OWNED(sbdep->sb_ump);
9629         fs = sbdep->sb_fs;
9630         /*
9631          * If the superblock doesn't match the in-memory list start over.
9632          */
9633         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9634         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9635             (inodedep == NULL && fs->fs_sujfree != 0)) {
9636                 bdirty(bp);
9637                 return (1);
9638         }
9639         WORKITEM_FREE(sbdep, D_SBDEP);
9640         if (fs->fs_sujfree == 0)
9641                 return (0);
9642         /*
9643          * Now that we have a record of this inode in stable store allow it
9644          * to be written to free up pending work.  Inodes may see a lot of
9645          * write activity after they are unlinked which we must not hold up.
9646          */
9647         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9648                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9649                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9650                             inodedep, inodedep->id_state);
9651                 if (inodedep->id_state & UNLINKONLIST)
9652                         break;
9653                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9654         }
9655
9656         return (0);
9657 }
9658
9659 /*
9660  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9661  */
9662 static void
9663 unlinked_inodedep(mp, inodedep)
9664         struct mount *mp;
9665         struct inodedep *inodedep;
9666 {
9667         struct ufsmount *ump;
9668
9669         ump = VFSTOUFS(mp);
9670         LOCK_OWNED(ump);
9671         if (MOUNTEDSUJ(mp) == 0)
9672                 return;
9673         ump->um_fs->fs_fmod = 1;
9674         if (inodedep->id_state & UNLINKED)
9675                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9676         inodedep->id_state |= UNLINKED;
9677         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9678 }
9679
9680 /*
9681  * Remove an inodedep from the unlinked inodedep list.  This may require
9682  * disk writes if the inode has made it that far.
9683  */
9684 static void
9685 clear_unlinked_inodedep(inodedep)
9686         struct inodedep *inodedep;
9687 {
9688         struct ufs2_dinode *dip;
9689         struct ufsmount *ump;
9690         struct inodedep *idp;
9691         struct inodedep *idn;
9692         struct fs *fs, *bpfs;
9693         struct buf *bp;
9694         ino_t ino;
9695         ino_t nino;
9696         ino_t pino;
9697         int error;
9698
9699         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9700         fs = ump->um_fs;
9701         ino = inodedep->id_ino;
9702         error = 0;
9703         for (;;) {
9704                 LOCK_OWNED(ump);
9705                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9706                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9707                     inodedep));
9708                 /*
9709                  * If nothing has yet been written simply remove us from
9710                  * the in memory list and return.  This is the most common
9711                  * case where handle_workitem_remove() loses the final
9712                  * reference.
9713                  */
9714                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9715                         break;
9716                 /*
9717                  * If we have a NEXT pointer and no PREV pointer we can simply
9718                  * clear NEXT's PREV and remove ourselves from the list.  Be
9719                  * careful not to clear PREV if the superblock points at
9720                  * next as well.
9721                  */
9722                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9723                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9724                         if (idn && fs->fs_sujfree != idn->id_ino)
9725                                 idn->id_state &= ~UNLINKPREV;
9726                         break;
9727                 }
9728                 /*
9729                  * Here we have an inodedep which is actually linked into
9730                  * the list.  We must remove it by forcing a write to the
9731                  * link before us, whether it be the superblock or an inode.
9732                  * Unfortunately the list may change while we're waiting
9733                  * on the buf lock for either resource so we must loop until
9734                  * we lock the right one.  If both the superblock and an
9735                  * inode point to this inode we must clear the inode first
9736                  * followed by the superblock.
9737                  */
9738                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9739                 pino = 0;
9740                 if (idp && (idp->id_state & UNLINKNEXT))
9741                         pino = idp->id_ino;
9742                 FREE_LOCK(ump);
9743                 if (pino == 0) {
9744                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9745                             (int)fs->fs_sbsize, 0, 0, 0);
9746                 } else {
9747                         error = bread(ump->um_devvp,
9748                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9749                             (int)fs->fs_bsize, NOCRED, &bp);
9750                         if (error)
9751                                 brelse(bp);
9752                 }
9753                 ACQUIRE_LOCK(ump);
9754                 if (error)
9755                         break;
9756                 /* If the list has changed restart the loop. */
9757                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9758                 nino = 0;
9759                 if (idp && (idp->id_state & UNLINKNEXT))
9760                         nino = idp->id_ino;
9761                 if (nino != pino ||
9762                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9763                         FREE_LOCK(ump);
9764                         brelse(bp);
9765                         ACQUIRE_LOCK(ump);
9766                         continue;
9767                 }
9768                 nino = 0;
9769                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9770                 if (idn)
9771                         nino = idn->id_ino;
9772                 /*
9773                  * Remove us from the in memory list.  After this we cannot
9774                  * access the inodedep.
9775                  */
9776                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9777                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9778                     inodedep));
9779                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9780                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9781                 FREE_LOCK(ump);
9782                 /*
9783                  * The predecessor's next pointer is manually updated here
9784                  * so that the NEXT flag is never cleared for an element
9785                  * that is in the list.
9786                  */
9787                 if (pino == 0) {
9788                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9789                         bpfs = (struct fs *)bp->b_data;
9790                         ffs_oldfscompat_write(bpfs, ump);
9791                         softdep_setup_sbupdate(ump, bpfs, bp);
9792                         /*
9793                          * Because we may have made changes to the superblock,
9794                          * we need to recompute its check-hash.
9795                          */
9796                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9797                 } else if (fs->fs_magic == FS_UFS1_MAGIC) {
9798                         ((struct ufs1_dinode *)bp->b_data +
9799                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9800                 } else {
9801                         dip = (struct ufs2_dinode *)bp->b_data +
9802                             ino_to_fsbo(fs, pino);
9803                         dip->di_freelink = nino;
9804                         ffs_update_dinode_ckhash(fs, dip);
9805                 }
9806                 /*
9807                  * If the bwrite fails we have no recourse to recover.  The
9808                  * filesystem is corrupted already.
9809                  */
9810                 bwrite(bp);
9811                 ACQUIRE_LOCK(ump);
9812                 /*
9813                  * If the superblock pointer still needs to be cleared force
9814                  * a write here.
9815                  */
9816                 if (fs->fs_sujfree == ino) {
9817                         FREE_LOCK(ump);
9818                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9819                             (int)fs->fs_sbsize, 0, 0, 0);
9820                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9821                         bpfs = (struct fs *)bp->b_data;
9822                         ffs_oldfscompat_write(bpfs, ump);
9823                         softdep_setup_sbupdate(ump, bpfs, bp);
9824                         /*
9825                          * Because we may have made changes to the superblock,
9826                          * we need to recompute its check-hash.
9827                          */
9828                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9829                         bwrite(bp);
9830                         ACQUIRE_LOCK(ump);
9831                 }
9832
9833                 if (fs->fs_sujfree != ino)
9834                         return;
9835                 panic("clear_unlinked_inodedep: Failed to clear free head");
9836         }
9837         if (inodedep->id_ino == fs->fs_sujfree)
9838                 panic("clear_unlinked_inodedep: Freeing head of free list");
9839         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9840         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9841         return;
9842 }
9843
9844 /*
9845  * This workitem decrements the inode's link count.
9846  * If the link count reaches zero, the file is removed.
9847  */
9848 static int
9849 handle_workitem_remove(dirrem, flags)
9850         struct dirrem *dirrem;
9851         int flags;
9852 {
9853         struct inodedep *inodedep;
9854         struct workhead dotdotwk;
9855         struct worklist *wk;
9856         struct ufsmount *ump;
9857         struct mount *mp;
9858         struct vnode *vp;
9859         struct inode *ip;
9860         ino_t oldinum;
9861
9862         if (dirrem->dm_state & ONWORKLIST)
9863                 panic("handle_workitem_remove: dirrem %p still on worklist",
9864                     dirrem);
9865         oldinum = dirrem->dm_oldinum;
9866         mp = dirrem->dm_list.wk_mp;
9867         ump = VFSTOUFS(mp);
9868         flags |= LK_EXCLUSIVE;
9869         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9870                 return (EBUSY);
9871         ip = VTOI(vp);
9872         MPASS(ip->i_mode != 0);
9873         ACQUIRE_LOCK(ump);
9874         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9875                 panic("handle_workitem_remove: lost inodedep");
9876         if (dirrem->dm_state & ONDEPLIST)
9877                 LIST_REMOVE(dirrem, dm_inonext);
9878         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9879             ("handle_workitem_remove:  Journal entries not written."));
9880
9881         /*
9882          * Move all dependencies waiting on the remove to complete
9883          * from the dirrem to the inode inowait list to be completed
9884          * after the inode has been updated and written to disk.
9885          *
9886          * Any marked MKDIR_PARENT are saved to be completed when the 
9887          * dotdot ref is removed unless DIRCHG is specified.  For
9888          * directory change operations there will be no further
9889          * directory writes and the jsegdeps need to be moved along
9890          * with the rest to be completed when the inode is free or
9891          * stable in the inode free list.
9892          */
9893         LIST_INIT(&dotdotwk);
9894         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9895                 WORKLIST_REMOVE(wk);
9896                 if ((dirrem->dm_state & DIRCHG) == 0 &&
9897                     wk->wk_state & MKDIR_PARENT) {
9898                         wk->wk_state &= ~MKDIR_PARENT;
9899                         WORKLIST_INSERT(&dotdotwk, wk);
9900                         continue;
9901                 }
9902                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9903         }
9904         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9905         /*
9906          * Normal file deletion.
9907          */
9908         if ((dirrem->dm_state & RMDIR) == 0) {
9909                 ip->i_nlink--;
9910                 KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
9911                     "%ju negative i_nlink %d", (intmax_t)ip->i_number,
9912                     ip->i_nlink));
9913                 DIP_SET(ip, i_nlink, ip->i_nlink);
9914                 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9915                 if (ip->i_nlink < ip->i_effnlink)
9916                         panic("handle_workitem_remove: bad file delta");
9917                 if (ip->i_nlink == 0) 
9918                         unlinked_inodedep(mp, inodedep);
9919                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9920                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9921                     ("handle_workitem_remove: worklist not empty. %s",
9922                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9923                 WORKITEM_FREE(dirrem, D_DIRREM);
9924                 FREE_LOCK(ump);
9925                 goto out;
9926         }
9927         /*
9928          * Directory deletion. Decrement reference count for both the
9929          * just deleted parent directory entry and the reference for ".".
9930          * Arrange to have the reference count on the parent decremented
9931          * to account for the loss of "..".
9932          */
9933         ip->i_nlink -= 2;
9934         KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
9935             "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
9936         DIP_SET(ip, i_nlink, ip->i_nlink);
9937         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9938         if (ip->i_nlink < ip->i_effnlink)
9939                 panic("handle_workitem_remove: bad dir delta");
9940         if (ip->i_nlink == 0)
9941                 unlinked_inodedep(mp, inodedep);
9942         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9943         /*
9944          * Rename a directory to a new parent. Since, we are both deleting
9945          * and creating a new directory entry, the link count on the new
9946          * directory should not change. Thus we skip the followup dirrem.
9947          */
9948         if (dirrem->dm_state & DIRCHG) {
9949                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9950                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9951                 WORKITEM_FREE(dirrem, D_DIRREM);
9952                 FREE_LOCK(ump);
9953                 goto out;
9954         }
9955         dirrem->dm_state = ONDEPLIST;
9956         dirrem->dm_oldinum = dirrem->dm_dirinum;
9957         /*
9958          * Place the dirrem on the parent's diremhd list.
9959          */
9960         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9961                 panic("handle_workitem_remove: lost dir inodedep");
9962         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9963         /*
9964          * If the allocated inode has never been written to disk, then
9965          * the on-disk inode is zero'ed and we can remove the file
9966          * immediately.  When journaling if the inode has been marked
9967          * unlinked and not DEPCOMPLETE we know it can never be written.
9968          */
9969         inodedep_lookup(mp, oldinum, 0, &inodedep);
9970         if (inodedep == NULL ||
9971             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9972             check_inode_unwritten(inodedep)) {
9973                 FREE_LOCK(ump);
9974                 vput(vp);
9975                 return handle_workitem_remove(dirrem, flags);
9976         }
9977         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9978         FREE_LOCK(ump);
9979         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9980 out:
9981         ffs_update(vp, 0);
9982         vput(vp);
9983         return (0);
9984 }
9985
9986 /*
9987  * Inode de-allocation dependencies.
9988  * 
9989  * When an inode's link count is reduced to zero, it can be de-allocated. We
9990  * found it convenient to postpone de-allocation until after the inode is
9991  * written to disk with its new link count (zero).  At this point, all of the
9992  * on-disk inode's block pointers are nullified and, with careful dependency
9993  * list ordering, all dependencies related to the inode will be satisfied and
9994  * the corresponding dependency structures de-allocated.  So, if/when the
9995  * inode is reused, there will be no mixing of old dependencies with new
9996  * ones.  This artificial dependency is set up by the block de-allocation
9997  * procedure above (softdep_setup_freeblocks) and completed by the
9998  * following procedure.
9999  */
10000 static void 
10001 handle_workitem_freefile(freefile)
10002         struct freefile *freefile;
10003 {
10004         struct workhead wkhd;
10005         struct fs *fs;
10006         struct ufsmount *ump;
10007         int error;
10008 #ifdef INVARIANTS
10009         struct inodedep *idp;
10010 #endif
10011
10012         ump = VFSTOUFS(freefile->fx_list.wk_mp);
10013         fs = ump->um_fs;
10014 #ifdef INVARIANTS
10015         ACQUIRE_LOCK(ump);
10016         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10017         FREE_LOCK(ump);
10018         if (error)
10019                 panic("handle_workitem_freefile: inodedep %p survived", idp);
10020 #endif
10021         UFS_LOCK(ump);
10022         fs->fs_pendinginodes -= 1;
10023         UFS_UNLOCK(ump);
10024         LIST_INIT(&wkhd);
10025         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10026         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10027             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10028                 softdep_error("handle_workitem_freefile", error);
10029         ACQUIRE_LOCK(ump);
10030         WORKITEM_FREE(freefile, D_FREEFILE);
10031         FREE_LOCK(ump);
10032 }
10033
10034
10035 /*
10036  * Helper function which unlinks marker element from work list and returns
10037  * the next element on the list.
10038  */
10039 static __inline struct worklist *
10040 markernext(struct worklist *marker)
10041 {
10042         struct worklist *next;
10043         
10044         next = LIST_NEXT(marker, wk_list);
10045         LIST_REMOVE(marker, wk_list);
10046         return next;
10047 }
10048
10049 /*
10050  * Disk writes.
10051  * 
10052  * The dependency structures constructed above are most actively used when file
10053  * system blocks are written to disk.  No constraints are placed on when a
10054  * block can be written, but unsatisfied update dependencies are made safe by
10055  * modifying (or replacing) the source memory for the duration of the disk
10056  * write.  When the disk write completes, the memory block is again brought
10057  * up-to-date.
10058  *
10059  * In-core inode structure reclamation.
10060  * 
10061  * Because there are a finite number of "in-core" inode structures, they are
10062  * reused regularly.  By transferring all inode-related dependencies to the
10063  * in-memory inode block and indexing them separately (via "inodedep"s), we
10064  * can allow "in-core" inode structures to be reused at any time and avoid
10065  * any increase in contention.
10066  *
10067  * Called just before entering the device driver to initiate a new disk I/O.
10068  * The buffer must be locked, thus, no I/O completion operations can occur
10069  * while we are manipulating its associated dependencies.
10070  */
10071 static void 
10072 softdep_disk_io_initiation(bp)
10073         struct buf *bp;         /* structure describing disk write to occur */
10074 {
10075         struct worklist *wk;
10076         struct worklist marker;
10077         struct inodedep *inodedep;
10078         struct freeblks *freeblks;
10079         struct jblkdep *jblkdep;
10080         struct newblk *newblk;
10081         struct ufsmount *ump;
10082
10083         /*
10084          * We only care about write operations. There should never
10085          * be dependencies for reads.
10086          */
10087         if (bp->b_iocmd != BIO_WRITE)
10088                 panic("softdep_disk_io_initiation: not write");
10089
10090         if (bp->b_vflags & BV_BKGRDINPROG)
10091                 panic("softdep_disk_io_initiation: Writing buffer with "
10092                     "background write in progress: %p", bp);
10093
10094         ump = softdep_bp_to_mp(bp);
10095         if (ump == NULL)
10096                 return;
10097
10098         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
10099         PHOLD(curproc);                 /* Don't swap out kernel stack */
10100         ACQUIRE_LOCK(ump);
10101         /*
10102          * Do any necessary pre-I/O processing.
10103          */
10104         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10105              wk = markernext(&marker)) {
10106                 LIST_INSERT_AFTER(wk, &marker, wk_list);
10107                 switch (wk->wk_type) {
10108
10109                 case D_PAGEDEP:
10110                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10111                         continue;
10112
10113                 case D_INODEDEP:
10114                         inodedep = WK_INODEDEP(wk);
10115                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10116                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10117                         else
10118                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10119                         continue;
10120
10121                 case D_INDIRDEP:
10122                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10123                         continue;
10124
10125                 case D_BMSAFEMAP:
10126                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10127                         continue;
10128
10129                 case D_JSEG:
10130                         WK_JSEG(wk)->js_buf = NULL;
10131                         continue;
10132
10133                 case D_FREEBLKS:
10134                         freeblks = WK_FREEBLKS(wk);
10135                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10136                         /*
10137                          * We have to wait for the freeblks to be journaled
10138                          * before we can write an inodeblock with updated
10139                          * pointers.  Be careful to arrange the marker so
10140                          * we revisit the freeblks if it's not removed by
10141                          * the first jwait().
10142                          */
10143                         if (jblkdep != NULL) {
10144                                 LIST_REMOVE(&marker, wk_list);
10145                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10146                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10147                         }
10148                         continue;
10149                 case D_ALLOCDIRECT:
10150                 case D_ALLOCINDIR:
10151                         /*
10152                          * We have to wait for the jnewblk to be journaled
10153                          * before we can write to a block if the contents
10154                          * may be confused with an earlier file's indirect
10155                          * at recovery time.  Handle the marker as described
10156                          * above.
10157                          */
10158                         newblk = WK_NEWBLK(wk);
10159                         if (newblk->nb_jnewblk != NULL &&
10160                             indirblk_lookup(newblk->nb_list.wk_mp,
10161                             newblk->nb_newblkno)) {
10162                                 LIST_REMOVE(&marker, wk_list);
10163                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10164                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10165                         }
10166                         continue;
10167
10168                 case D_SBDEP:
10169                         initiate_write_sbdep(WK_SBDEP(wk));
10170                         continue;
10171
10172                 case D_MKDIR:
10173                 case D_FREEWORK:
10174                 case D_FREEDEP:
10175                 case D_JSEGDEP:
10176                         continue;
10177
10178                 default:
10179                         panic("handle_disk_io_initiation: Unexpected type %s",
10180                             TYPENAME(wk->wk_type));
10181                         /* NOTREACHED */
10182                 }
10183         }
10184         FREE_LOCK(ump);
10185         PRELE(curproc);                 /* Allow swapout of kernel stack */
10186 }
10187
10188 /*
10189  * Called from within the procedure above to deal with unsatisfied
10190  * allocation dependencies in a directory. The buffer must be locked,
10191  * thus, no I/O completion operations can occur while we are
10192  * manipulating its associated dependencies.
10193  */
10194 static void
10195 initiate_write_filepage(pagedep, bp)
10196         struct pagedep *pagedep;
10197         struct buf *bp;
10198 {
10199         struct jremref *jremref;
10200         struct jmvref *jmvref;
10201         struct dirrem *dirrem;
10202         struct diradd *dap;
10203         struct direct *ep;
10204         int i;
10205
10206         if (pagedep->pd_state & IOSTARTED) {
10207                 /*
10208                  * This can only happen if there is a driver that does not
10209                  * understand chaining. Here biodone will reissue the call
10210                  * to strategy for the incomplete buffers.
10211                  */
10212                 printf("initiate_write_filepage: already started\n");
10213                 return;
10214         }
10215         pagedep->pd_state |= IOSTARTED;
10216         /*
10217          * Wait for all journal remove dependencies to hit the disk.
10218          * We can not allow any potentially conflicting directory adds
10219          * to be visible before removes and rollback is too difficult.
10220          * The per-filesystem lock may be dropped and re-acquired, however 
10221          * we hold the buf locked so the dependency can not go away.
10222          */
10223         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10224                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10225                         jwait(&jremref->jr_list, MNT_WAIT);
10226         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10227                 jwait(&jmvref->jm_list, MNT_WAIT);
10228         for (i = 0; i < DAHASHSZ; i++) {
10229                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10230                         ep = (struct direct *)
10231                             ((char *)bp->b_data + dap->da_offset);
10232                         if (ep->d_ino != dap->da_newinum)
10233                                 panic("%s: dir inum %ju != new %ju",
10234                                     "initiate_write_filepage",
10235                                     (uintmax_t)ep->d_ino,
10236                                     (uintmax_t)dap->da_newinum);
10237                         if (dap->da_state & DIRCHG)
10238                                 ep->d_ino = dap->da_previous->dm_oldinum;
10239                         else
10240                                 ep->d_ino = 0;
10241                         dap->da_state &= ~ATTACHED;
10242                         dap->da_state |= UNDONE;
10243                 }
10244         }
10245 }
10246
10247 /*
10248  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10249  * Note that any bug fixes made to this routine must be done in the
10250  * version found below.
10251  *
10252  * Called from within the procedure above to deal with unsatisfied
10253  * allocation dependencies in an inodeblock. The buffer must be
10254  * locked, thus, no I/O completion operations can occur while we
10255  * are manipulating its associated dependencies.
10256  */
10257 static void 
10258 initiate_write_inodeblock_ufs1(inodedep, bp)
10259         struct inodedep *inodedep;
10260         struct buf *bp;                 /* The inode block */
10261 {
10262         struct allocdirect *adp, *lastadp;
10263         struct ufs1_dinode *dp;
10264         struct ufs1_dinode *sip;
10265         struct inoref *inoref;
10266         struct ufsmount *ump;
10267         struct fs *fs;
10268         ufs_lbn_t i;
10269 #ifdef INVARIANTS
10270         ufs_lbn_t prevlbn = 0;
10271 #endif
10272         int deplist;
10273
10274         if (inodedep->id_state & IOSTARTED)
10275                 panic("initiate_write_inodeblock_ufs1: already started");
10276         inodedep->id_state |= IOSTARTED;
10277         fs = inodedep->id_fs;
10278         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10279         LOCK_OWNED(ump);
10280         dp = (struct ufs1_dinode *)bp->b_data +
10281             ino_to_fsbo(fs, inodedep->id_ino);
10282
10283         /*
10284          * If we're on the unlinked list but have not yet written our
10285          * next pointer initialize it here.
10286          */
10287         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10288                 struct inodedep *inon;
10289
10290                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10291                 dp->di_freelink = inon ? inon->id_ino : 0;
10292         }
10293         /*
10294          * If the bitmap is not yet written, then the allocated
10295          * inode cannot be written to disk.
10296          */
10297         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10298                 if (inodedep->id_savedino1 != NULL)
10299                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10300                 FREE_LOCK(ump);
10301                 sip = malloc(sizeof(struct ufs1_dinode),
10302                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10303                 ACQUIRE_LOCK(ump);
10304                 inodedep->id_savedino1 = sip;
10305                 *inodedep->id_savedino1 = *dp;
10306                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10307                 dp->di_gen = inodedep->id_savedino1->di_gen;
10308                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10309                 return;
10310         }
10311         /*
10312          * If no dependencies, then there is nothing to roll back.
10313          */
10314         inodedep->id_savedsize = dp->di_size;
10315         inodedep->id_savedextsize = 0;
10316         inodedep->id_savednlink = dp->di_nlink;
10317         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10318             TAILQ_EMPTY(&inodedep->id_inoreflst))
10319                 return;
10320         /*
10321          * Revert the link count to that of the first unwritten journal entry.
10322          */
10323         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10324         if (inoref)
10325                 dp->di_nlink = inoref->if_nlink;
10326         /*
10327          * Set the dependencies to busy.
10328          */
10329         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10330              adp = TAILQ_NEXT(adp, ad_next)) {
10331 #ifdef INVARIANTS
10332                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10333                         panic("softdep_write_inodeblock: lbn order");
10334                 prevlbn = adp->ad_offset;
10335                 if (adp->ad_offset < UFS_NDADDR &&
10336                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10337                         panic("initiate_write_inodeblock_ufs1: "
10338                             "direct pointer #%jd mismatch %d != %jd",
10339                             (intmax_t)adp->ad_offset,
10340                             dp->di_db[adp->ad_offset],
10341                             (intmax_t)adp->ad_newblkno);
10342                 if (adp->ad_offset >= UFS_NDADDR &&
10343                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10344                         panic("initiate_write_inodeblock_ufs1: "
10345                             "indirect pointer #%jd mismatch %d != %jd",
10346                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10347                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10348                             (intmax_t)adp->ad_newblkno);
10349                 deplist |= 1 << adp->ad_offset;
10350                 if ((adp->ad_state & ATTACHED) == 0)
10351                         panic("initiate_write_inodeblock_ufs1: "
10352                             "Unknown state 0x%x", adp->ad_state);
10353 #endif /* INVARIANTS */
10354                 adp->ad_state &= ~ATTACHED;
10355                 adp->ad_state |= UNDONE;
10356         }
10357         /*
10358          * The on-disk inode cannot claim to be any larger than the last
10359          * fragment that has been written. Otherwise, the on-disk inode
10360          * might have fragments that were not the last block in the file
10361          * which would corrupt the filesystem.
10362          */
10363         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10364              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10365                 if (adp->ad_offset >= UFS_NDADDR)
10366                         break;
10367                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10368                 /* keep going until hitting a rollback to a frag */
10369                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10370                         continue;
10371                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10372                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10373 #ifdef INVARIANTS
10374                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10375                                 panic("initiate_write_inodeblock_ufs1: "
10376                                     "lost dep1");
10377 #endif /* INVARIANTS */
10378                         dp->di_db[i] = 0;
10379                 }
10380                 for (i = 0; i < UFS_NIADDR; i++) {
10381 #ifdef INVARIANTS
10382                         if (dp->di_ib[i] != 0 &&
10383                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10384                                 panic("initiate_write_inodeblock_ufs1: "
10385                                     "lost dep2");
10386 #endif /* INVARIANTS */
10387                         dp->di_ib[i] = 0;
10388                 }
10389                 return;
10390         }
10391         /*
10392          * If we have zero'ed out the last allocated block of the file,
10393          * roll back the size to the last currently allocated block.
10394          * We know that this last allocated block is a full-sized as
10395          * we already checked for fragments in the loop above.
10396          */
10397         if (lastadp != NULL &&
10398             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10399                 for (i = lastadp->ad_offset; i >= 0; i--)
10400                         if (dp->di_db[i] != 0)
10401                                 break;
10402                 dp->di_size = (i + 1) * fs->fs_bsize;
10403         }
10404         /*
10405          * The only dependencies are for indirect blocks.
10406          *
10407          * The file size for indirect block additions is not guaranteed.
10408          * Such a guarantee would be non-trivial to achieve. The conventional
10409          * synchronous write implementation also does not make this guarantee.
10410          * Fsck should catch and fix discrepancies. Arguably, the file size
10411          * can be over-estimated without destroying integrity when the file
10412          * moves into the indirect blocks (i.e., is large). If we want to
10413          * postpone fsck, we are stuck with this argument.
10414          */
10415         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10416                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10417 }
10418                 
10419 /*
10420  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10421  * Note that any bug fixes made to this routine must be done in the
10422  * version found above.
10423  *
10424  * Called from within the procedure above to deal with unsatisfied
10425  * allocation dependencies in an inodeblock. The buffer must be
10426  * locked, thus, no I/O completion operations can occur while we
10427  * are manipulating its associated dependencies.
10428  */
10429 static void 
10430 initiate_write_inodeblock_ufs2(inodedep, bp)
10431         struct inodedep *inodedep;
10432         struct buf *bp;                 /* The inode block */
10433 {
10434         struct allocdirect *adp, *lastadp;
10435         struct ufs2_dinode *dp;
10436         struct ufs2_dinode *sip;
10437         struct inoref *inoref;
10438         struct ufsmount *ump;
10439         struct fs *fs;
10440         ufs_lbn_t i;
10441 #ifdef INVARIANTS
10442         ufs_lbn_t prevlbn = 0;
10443 #endif
10444         int deplist;
10445
10446         if (inodedep->id_state & IOSTARTED)
10447                 panic("initiate_write_inodeblock_ufs2: already started");
10448         inodedep->id_state |= IOSTARTED;
10449         fs = inodedep->id_fs;
10450         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10451         LOCK_OWNED(ump);
10452         dp = (struct ufs2_dinode *)bp->b_data +
10453             ino_to_fsbo(fs, inodedep->id_ino);
10454
10455         /*
10456          * If we're on the unlinked list but have not yet written our
10457          * next pointer initialize it here.
10458          */
10459         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10460                 struct inodedep *inon;
10461
10462                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10463                 dp->di_freelink = inon ? inon->id_ino : 0;
10464                 ffs_update_dinode_ckhash(fs, dp);
10465         }
10466         /*
10467          * If the bitmap is not yet written, then the allocated
10468          * inode cannot be written to disk.
10469          */
10470         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10471                 if (inodedep->id_savedino2 != NULL)
10472                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10473                 FREE_LOCK(ump);
10474                 sip = malloc(sizeof(struct ufs2_dinode),
10475                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10476                 ACQUIRE_LOCK(ump);
10477                 inodedep->id_savedino2 = sip;
10478                 *inodedep->id_savedino2 = *dp;
10479                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10480                 dp->di_gen = inodedep->id_savedino2->di_gen;
10481                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10482                 return;
10483         }
10484         /*
10485          * If no dependencies, then there is nothing to roll back.
10486          */
10487         inodedep->id_savedsize = dp->di_size;
10488         inodedep->id_savedextsize = dp->di_extsize;
10489         inodedep->id_savednlink = dp->di_nlink;
10490         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10491             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10492             TAILQ_EMPTY(&inodedep->id_inoreflst))
10493                 return;
10494         /*
10495          * Revert the link count to that of the first unwritten journal entry.
10496          */
10497         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10498         if (inoref)
10499                 dp->di_nlink = inoref->if_nlink;
10500
10501         /*
10502          * Set the ext data dependencies to busy.
10503          */
10504         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10505              adp = TAILQ_NEXT(adp, ad_next)) {
10506 #ifdef INVARIANTS
10507                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10508                         panic("initiate_write_inodeblock_ufs2: lbn order");
10509                 prevlbn = adp->ad_offset;
10510                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10511                         panic("initiate_write_inodeblock_ufs2: "
10512                             "ext pointer #%jd mismatch %jd != %jd",
10513                             (intmax_t)adp->ad_offset,
10514                             (intmax_t)dp->di_extb[adp->ad_offset],
10515                             (intmax_t)adp->ad_newblkno);
10516                 deplist |= 1 << adp->ad_offset;
10517                 if ((adp->ad_state & ATTACHED) == 0)
10518                         panic("initiate_write_inodeblock_ufs2: Unknown "
10519                             "state 0x%x", adp->ad_state);
10520 #endif /* INVARIANTS */
10521                 adp->ad_state &= ~ATTACHED;
10522                 adp->ad_state |= UNDONE;
10523         }
10524         /*
10525          * The on-disk inode cannot claim to be any larger than the last
10526          * fragment that has been written. Otherwise, the on-disk inode
10527          * might have fragments that were not the last block in the ext
10528          * data which would corrupt the filesystem.
10529          */
10530         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10531              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10532                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10533                 /* keep going until hitting a rollback to a frag */
10534                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10535                         continue;
10536                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10537                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10538 #ifdef INVARIANTS
10539                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10540                                 panic("initiate_write_inodeblock_ufs2: "
10541                                     "lost dep1");
10542 #endif /* INVARIANTS */
10543                         dp->di_extb[i] = 0;
10544                 }
10545                 lastadp = NULL;
10546                 break;
10547         }
10548         /*
10549          * If we have zero'ed out the last allocated block of the ext
10550          * data, roll back the size to the last currently allocated block.
10551          * We know that this last allocated block is a full-sized as
10552          * we already checked for fragments in the loop above.
10553          */
10554         if (lastadp != NULL &&
10555             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10556                 for (i = lastadp->ad_offset; i >= 0; i--)
10557                         if (dp->di_extb[i] != 0)
10558                                 break;
10559                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10560         }
10561         /*
10562          * Set the file data dependencies to busy.
10563          */
10564         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10565              adp = TAILQ_NEXT(adp, ad_next)) {
10566 #ifdef INVARIANTS
10567                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10568                         panic("softdep_write_inodeblock: lbn order");
10569                 if ((adp->ad_state & ATTACHED) == 0)
10570                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10571                 prevlbn = adp->ad_offset;
10572                 if (adp->ad_offset < UFS_NDADDR &&
10573                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10574                         panic("initiate_write_inodeblock_ufs2: "
10575                             "direct pointer #%jd mismatch %jd != %jd",
10576                             (intmax_t)adp->ad_offset,
10577                             (intmax_t)dp->di_db[adp->ad_offset],
10578                             (intmax_t)adp->ad_newblkno);
10579                 if (adp->ad_offset >= UFS_NDADDR &&
10580                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10581                         panic("initiate_write_inodeblock_ufs2: "
10582                             "indirect pointer #%jd mismatch %jd != %jd",
10583                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10584                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10585                             (intmax_t)adp->ad_newblkno);
10586                 deplist |= 1 << adp->ad_offset;
10587                 if ((adp->ad_state & ATTACHED) == 0)
10588                         panic("initiate_write_inodeblock_ufs2: Unknown "
10589                              "state 0x%x", adp->ad_state);
10590 #endif /* INVARIANTS */
10591                 adp->ad_state &= ~ATTACHED;
10592                 adp->ad_state |= UNDONE;
10593         }
10594         /*
10595          * The on-disk inode cannot claim to be any larger than the last
10596          * fragment that has been written. Otherwise, the on-disk inode
10597          * might have fragments that were not the last block in the file
10598          * which would corrupt the filesystem.
10599          */
10600         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10601              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10602                 if (adp->ad_offset >= UFS_NDADDR)
10603                         break;
10604                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10605                 /* keep going until hitting a rollback to a frag */
10606                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10607                         continue;
10608                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10609                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10610 #ifdef INVARIANTS
10611                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10612                                 panic("initiate_write_inodeblock_ufs2: "
10613                                     "lost dep2");
10614 #endif /* INVARIANTS */
10615                         dp->di_db[i] = 0;
10616                 }
10617                 for (i = 0; i < UFS_NIADDR; i++) {
10618 #ifdef INVARIANTS
10619                         if (dp->di_ib[i] != 0 &&
10620                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10621                                 panic("initiate_write_inodeblock_ufs2: "
10622                                     "lost dep3");
10623 #endif /* INVARIANTS */
10624                         dp->di_ib[i] = 0;
10625                 }
10626                 ffs_update_dinode_ckhash(fs, dp);
10627                 return;
10628         }
10629         /*
10630          * If we have zero'ed out the last allocated block of the file,
10631          * roll back the size to the last currently allocated block.
10632          * We know that this last allocated block is a full-sized as
10633          * we already checked for fragments in the loop above.
10634          */
10635         if (lastadp != NULL &&
10636             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10637                 for (i = lastadp->ad_offset; i >= 0; i--)
10638                         if (dp->di_db[i] != 0)
10639                                 break;
10640                 dp->di_size = (i + 1) * fs->fs_bsize;
10641         }
10642         /*
10643          * The only dependencies are for indirect blocks.
10644          *
10645          * The file size for indirect block additions is not guaranteed.
10646          * Such a guarantee would be non-trivial to achieve. The conventional
10647          * synchronous write implementation also does not make this guarantee.
10648          * Fsck should catch and fix discrepancies. Arguably, the file size
10649          * can be over-estimated without destroying integrity when the file
10650          * moves into the indirect blocks (i.e., is large). If we want to
10651          * postpone fsck, we are stuck with this argument.
10652          */
10653         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10654                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10655         ffs_update_dinode_ckhash(fs, dp);
10656 }
10657
10658 /*
10659  * Cancel an indirdep as a result of truncation.  Release all of the
10660  * children allocindirs and place their journal work on the appropriate
10661  * list.
10662  */
10663 static void
10664 cancel_indirdep(indirdep, bp, freeblks)
10665         struct indirdep *indirdep;
10666         struct buf *bp;
10667         struct freeblks *freeblks;
10668 {
10669         struct allocindir *aip;
10670
10671         /*
10672          * None of the indirect pointers will ever be visible,
10673          * so they can simply be tossed. GOINGAWAY ensures
10674          * that allocated pointers will be saved in the buffer
10675          * cache until they are freed. Note that they will
10676          * only be able to be found by their physical address
10677          * since the inode mapping the logical address will
10678          * be gone. The save buffer used for the safe copy
10679          * was allocated in setup_allocindir_phase2 using
10680          * the physical address so it could be used for this
10681          * purpose. Hence we swap the safe copy with the real
10682          * copy, allowing the safe copy to be freed and holding
10683          * on to the real copy for later use in indir_trunc.
10684          */
10685         if (indirdep->ir_state & GOINGAWAY)
10686                 panic("cancel_indirdep: already gone");
10687         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10688                 indirdep->ir_state |= DEPCOMPLETE;
10689                 LIST_REMOVE(indirdep, ir_next);
10690         }
10691         indirdep->ir_state |= GOINGAWAY;
10692         /*
10693          * Pass in bp for blocks still have journal writes
10694          * pending so we can cancel them on their own.
10695          */
10696         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10697                 cancel_allocindir(aip, bp, freeblks, 0);
10698         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10699                 cancel_allocindir(aip, NULL, freeblks, 0);
10700         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10701                 cancel_allocindir(aip, NULL, freeblks, 0);
10702         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10703                 cancel_allocindir(aip, NULL, freeblks, 0);
10704         /*
10705          * If there are pending partial truncations we need to keep the
10706          * old block copy around until they complete.  This is because
10707          * the current b_data is not a perfect superset of the available
10708          * blocks.
10709          */
10710         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10711                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10712         else
10713                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10714         WORKLIST_REMOVE(&indirdep->ir_list);
10715         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10716         indirdep->ir_bp = NULL;
10717         indirdep->ir_freeblks = freeblks;
10718 }
10719
10720 /*
10721  * Free an indirdep once it no longer has new pointers to track.
10722  */
10723 static void
10724 free_indirdep(indirdep)
10725         struct indirdep *indirdep;
10726 {
10727
10728         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10729             ("free_indirdep: Indir trunc list not empty."));
10730         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10731             ("free_indirdep: Complete head not empty."));
10732         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10733             ("free_indirdep: write head not empty."));
10734         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10735             ("free_indirdep: done head not empty."));
10736         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10737             ("free_indirdep: deplist head not empty."));
10738         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10739             ("free_indirdep: %p still on newblk list.", indirdep));
10740         KASSERT(indirdep->ir_saveddata == NULL,
10741             ("free_indirdep: %p still has saved data.", indirdep));
10742         if (indirdep->ir_state & ONWORKLIST)
10743                 WORKLIST_REMOVE(&indirdep->ir_list);
10744         WORKITEM_FREE(indirdep, D_INDIRDEP);
10745 }
10746
10747 /*
10748  * Called before a write to an indirdep.  This routine is responsible for
10749  * rolling back pointers to a safe state which includes only those
10750  * allocindirs which have been completed.
10751  */
10752 static void
10753 initiate_write_indirdep(indirdep, bp)
10754         struct indirdep *indirdep;
10755         struct buf *bp;
10756 {
10757         struct ufsmount *ump;
10758
10759         indirdep->ir_state |= IOSTARTED;
10760         if (indirdep->ir_state & GOINGAWAY)
10761                 panic("disk_io_initiation: indirdep gone");
10762         /*
10763          * If there are no remaining dependencies, this will be writing
10764          * the real pointers.
10765          */
10766         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10767             TAILQ_EMPTY(&indirdep->ir_trunc))
10768                 return;
10769         /*
10770          * Replace up-to-date version with safe version.
10771          */
10772         if (indirdep->ir_saveddata == NULL) {
10773                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10774                 LOCK_OWNED(ump);
10775                 FREE_LOCK(ump);
10776                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10777                     M_SOFTDEP_FLAGS);
10778                 ACQUIRE_LOCK(ump);
10779         }
10780         indirdep->ir_state &= ~ATTACHED;
10781         indirdep->ir_state |= UNDONE;
10782         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10783         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10784             bp->b_bcount);
10785 }
10786
10787 /*
10788  * Called when an inode has been cleared in a cg bitmap.  This finally
10789  * eliminates any canceled jaddrefs
10790  */
10791 void
10792 softdep_setup_inofree(mp, bp, ino, wkhd)
10793         struct mount *mp;
10794         struct buf *bp;
10795         ino_t ino;
10796         struct workhead *wkhd;
10797 {
10798         struct worklist *wk, *wkn;
10799         struct inodedep *inodedep;
10800         struct ufsmount *ump;
10801         uint8_t *inosused;
10802         struct cg *cgp;
10803         struct fs *fs;
10804
10805         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10806             ("softdep_setup_inofree called on non-softdep filesystem"));
10807         ump = VFSTOUFS(mp);
10808         ACQUIRE_LOCK(ump);
10809         fs = ump->um_fs;
10810         cgp = (struct cg *)bp->b_data;
10811         inosused = cg_inosused(cgp);
10812         if (isset(inosused, ino % fs->fs_ipg))
10813                 panic("softdep_setup_inofree: inode %ju not freed.",
10814                     (uintmax_t)ino);
10815         if (inodedep_lookup(mp, ino, 0, &inodedep))
10816                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10817                     (uintmax_t)ino, inodedep);
10818         if (wkhd) {
10819                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10820                         if (wk->wk_type != D_JADDREF)
10821                                 continue;
10822                         WORKLIST_REMOVE(wk);
10823                         /*
10824                          * We can free immediately even if the jaddref
10825                          * isn't attached in a background write as now
10826                          * the bitmaps are reconciled.
10827                          */
10828                         wk->wk_state |= COMPLETE | ATTACHED;
10829                         free_jaddref(WK_JADDREF(wk));
10830                 }
10831                 jwork_move(&bp->b_dep, wkhd);
10832         }
10833         FREE_LOCK(ump);
10834 }
10835
10836 /*
10837  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10838  * map.  Any dependencies waiting for the write to clear are added to the
10839  * buf's list and any jnewblks that are being canceled are discarded
10840  * immediately.
10841  */
10842 void
10843 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10844         struct mount *mp;
10845         struct buf *bp;
10846         ufs2_daddr_t blkno;
10847         int frags;
10848         struct workhead *wkhd;
10849 {
10850         struct bmsafemap *bmsafemap;
10851         struct jnewblk *jnewblk;
10852         struct ufsmount *ump;
10853         struct worklist *wk;
10854         struct fs *fs;
10855 #ifdef INVARIANTS
10856         uint8_t *blksfree;
10857         struct cg *cgp;
10858         ufs2_daddr_t jstart;
10859         ufs2_daddr_t jend;
10860         ufs2_daddr_t end;
10861         long bno;
10862         int i;
10863 #endif
10864
10865         CTR3(KTR_SUJ,
10866             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10867             blkno, frags, wkhd);
10868
10869         ump = VFSTOUFS(mp);
10870         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10871             ("softdep_setup_blkfree called on non-softdep filesystem"));
10872         ACQUIRE_LOCK(ump);
10873         /* Lookup the bmsafemap so we track when it is dirty. */
10874         fs = ump->um_fs;
10875         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10876         /*
10877          * Detach any jnewblks which have been canceled.  They must linger
10878          * until the bitmap is cleared again by ffs_blkfree() to prevent
10879          * an unjournaled allocation from hitting the disk.
10880          */
10881         if (wkhd) {
10882                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10883                         CTR2(KTR_SUJ,
10884                             "softdep_setup_blkfree: blkno %jd wk type %d",
10885                             blkno, wk->wk_type);
10886                         WORKLIST_REMOVE(wk);
10887                         if (wk->wk_type != D_JNEWBLK) {
10888                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10889                                 continue;
10890                         }
10891                         jnewblk = WK_JNEWBLK(wk);
10892                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10893                             ("softdep_setup_blkfree: jnewblk not canceled."));
10894 #ifdef INVARIANTS
10895                         /*
10896                          * Assert that this block is free in the bitmap
10897                          * before we discard the jnewblk.
10898                          */
10899                         cgp = (struct cg *)bp->b_data;
10900                         blksfree = cg_blksfree(cgp);
10901                         bno = dtogd(fs, jnewblk->jn_blkno);
10902                         for (i = jnewblk->jn_oldfrags;
10903                             i < jnewblk->jn_frags; i++) {
10904                                 if (isset(blksfree, bno + i))
10905                                         continue;
10906                                 panic("softdep_setup_blkfree: not free");
10907                         }
10908 #endif
10909                         /*
10910                          * Even if it's not attached we can free immediately
10911                          * as the new bitmap is correct.
10912                          */
10913                         wk->wk_state |= COMPLETE | ATTACHED;
10914                         free_jnewblk(jnewblk);
10915                 }
10916         }
10917
10918 #ifdef INVARIANTS
10919         /*
10920          * Assert that we are not freeing a block which has an outstanding
10921          * allocation dependency.
10922          */
10923         fs = VFSTOUFS(mp)->um_fs;
10924         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10925         end = blkno + frags;
10926         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10927                 /*
10928                  * Don't match against blocks that will be freed when the
10929                  * background write is done.
10930                  */
10931                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10932                     (COMPLETE | DEPCOMPLETE))
10933                         continue;
10934                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10935                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10936                 if ((blkno >= jstart && blkno < jend) ||
10937                     (end > jstart && end <= jend)) {
10938                         printf("state 0x%X %jd - %d %d dep %p\n",
10939                             jnewblk->jn_state, jnewblk->jn_blkno,
10940                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10941                             jnewblk->jn_dep);
10942                         panic("softdep_setup_blkfree: "
10943                             "%jd-%jd(%d) overlaps with %jd-%jd",
10944                             blkno, end, frags, jstart, jend);
10945                 }
10946         }
10947 #endif
10948         FREE_LOCK(ump);
10949 }
10950
10951 /*
10952  * Revert a block allocation when the journal record that describes it
10953  * is not yet written.
10954  */
10955 static int
10956 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10957         struct jnewblk *jnewblk;
10958         struct fs *fs;
10959         struct cg *cgp;
10960         uint8_t *blksfree;
10961 {
10962         ufs1_daddr_t fragno;
10963         long cgbno, bbase;
10964         int frags, blk;
10965         int i;
10966
10967         frags = 0;
10968         cgbno = dtogd(fs, jnewblk->jn_blkno);
10969         /*
10970          * We have to test which frags need to be rolled back.  We may
10971          * be operating on a stale copy when doing background writes.
10972          */
10973         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10974                 if (isclr(blksfree, cgbno + i))
10975                         frags++;
10976         if (frags == 0)
10977                 return (0);
10978         /*
10979          * This is mostly ffs_blkfree() sans some validation and
10980          * superblock updates.
10981          */
10982         if (frags == fs->fs_frag) {
10983                 fragno = fragstoblks(fs, cgbno);
10984                 ffs_setblock(fs, blksfree, fragno);
10985                 ffs_clusteracct(fs, cgp, fragno, 1);
10986                 cgp->cg_cs.cs_nbfree++;
10987         } else {
10988                 cgbno += jnewblk->jn_oldfrags;
10989                 bbase = cgbno - fragnum(fs, cgbno);
10990                 /* Decrement the old frags.  */
10991                 blk = blkmap(fs, blksfree, bbase);
10992                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10993                 /* Deallocate the fragment */
10994                 for (i = 0; i < frags; i++)
10995                         setbit(blksfree, cgbno + i);
10996                 cgp->cg_cs.cs_nffree += frags;
10997                 /* Add back in counts associated with the new frags */
10998                 blk = blkmap(fs, blksfree, bbase);
10999                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11000                 /* If a complete block has been reassembled, account for it. */
11001                 fragno = fragstoblks(fs, bbase);
11002                 if (ffs_isblock(fs, blksfree, fragno)) {
11003                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
11004                         ffs_clusteracct(fs, cgp, fragno, 1);
11005                         cgp->cg_cs.cs_nbfree++;
11006                 }
11007         }
11008         stat_jnewblk++;
11009         jnewblk->jn_state &= ~ATTACHED;
11010         jnewblk->jn_state |= UNDONE;
11011
11012         return (frags);
11013 }
11014
11015 static void
11016 initiate_write_bmsafemap(bmsafemap, bp)
11017         struct bmsafemap *bmsafemap;
11018         struct buf *bp;                 /* The cg block. */
11019 {
11020         struct jaddref *jaddref;
11021         struct jnewblk *jnewblk;
11022         uint8_t *inosused;
11023         uint8_t *blksfree;
11024         struct cg *cgp;
11025         struct fs *fs;
11026         ino_t ino;
11027
11028         /*
11029          * If this is a background write, we did this at the time that
11030          * the copy was made, so do not need to do it again.
11031          */
11032         if (bmsafemap->sm_state & IOSTARTED)
11033                 return;
11034         bmsafemap->sm_state |= IOSTARTED;
11035         /*
11036          * Clear any inode allocations which are pending journal writes.
11037          */
11038         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11039                 cgp = (struct cg *)bp->b_data;
11040                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11041                 inosused = cg_inosused(cgp);
11042                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11043                         ino = jaddref->ja_ino % fs->fs_ipg;
11044                         if (isset(inosused, ino)) {
11045                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11046                                         cgp->cg_cs.cs_ndir--;
11047                                 cgp->cg_cs.cs_nifree++;
11048                                 clrbit(inosused, ino);
11049                                 jaddref->ja_state &= ~ATTACHED;
11050                                 jaddref->ja_state |= UNDONE;
11051                                 stat_jaddref++;
11052                         } else
11053                                 panic("initiate_write_bmsafemap: inode %ju "
11054                                     "marked free", (uintmax_t)jaddref->ja_ino);
11055                 }
11056         }
11057         /*
11058          * Clear any block allocations which are pending journal writes.
11059          */
11060         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11061                 cgp = (struct cg *)bp->b_data;
11062                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11063                 blksfree = cg_blksfree(cgp);
11064                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11065                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11066                                 continue;
11067                         panic("initiate_write_bmsafemap: block %jd "
11068                             "marked free", jnewblk->jn_blkno);
11069                 }
11070         }
11071         /*
11072          * Move allocation lists to the written lists so they can be
11073          * cleared once the block write is complete.
11074          */
11075         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11076             inodedep, id_deps);
11077         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11078             newblk, nb_deps);
11079         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11080             wk_list);
11081 }
11082
11083 /*
11084  * This routine is called during the completion interrupt
11085  * service routine for a disk write (from the procedure called
11086  * by the device driver to inform the filesystem caches of
11087  * a request completion).  It should be called early in this
11088  * procedure, before the block is made available to other
11089  * processes or other routines are called.
11090  *
11091  */
11092 static void 
11093 softdep_disk_write_complete(bp)
11094         struct buf *bp;         /* describes the completed disk write */
11095 {
11096         struct worklist *wk;
11097         struct worklist *owk;
11098         struct ufsmount *ump;
11099         struct workhead reattach;
11100         struct freeblks *freeblks;
11101         struct buf *sbp;
11102
11103         ump = softdep_bp_to_mp(bp);
11104         KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11105             ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11106              "with outstanding dependencies for buffer %p", bp));
11107         if (ump == NULL)
11108                 return;
11109         /*
11110          * If an error occurred while doing the write, then the data
11111          * has not hit the disk and the dependencies cannot be processed.
11112          * But we do have to go through and roll forward any dependencies
11113          * that were rolled back before the disk write.
11114          */
11115         sbp = NULL;
11116         ACQUIRE_LOCK(ump);
11117         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11118                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11119                         switch (wk->wk_type) {
11120
11121                         case D_PAGEDEP:
11122                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11123                                 continue;
11124
11125                         case D_INODEDEP:
11126                                 handle_written_inodeblock(WK_INODEDEP(wk),
11127                                     bp, 0);
11128                                 continue;
11129
11130                         case D_BMSAFEMAP:
11131                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11132                                     bp, 0);
11133                                 continue;
11134
11135                         case D_INDIRDEP:
11136                                 handle_written_indirdep(WK_INDIRDEP(wk),
11137                                     bp, &sbp, 0);
11138                                 continue;
11139                         default:
11140                                 /* nothing to roll forward */
11141                                 continue;
11142                         }
11143                 }
11144                 FREE_LOCK(ump);
11145                 if (sbp)
11146                         brelse(sbp);
11147                 return;
11148         }
11149         LIST_INIT(&reattach);
11150
11151         /*
11152          * Ump SU lock must not be released anywhere in this code segment.
11153          */
11154         owk = NULL;
11155         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11156                 WORKLIST_REMOVE(wk);
11157                 atomic_add_long(&dep_write[wk->wk_type], 1);
11158                 if (wk == owk)
11159                         panic("duplicate worklist: %p\n", wk);
11160                 owk = wk;
11161                 switch (wk->wk_type) {
11162
11163                 case D_PAGEDEP:
11164                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11165                             WRITESUCCEEDED))
11166                                 WORKLIST_INSERT(&reattach, wk);
11167                         continue;
11168
11169                 case D_INODEDEP:
11170                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11171                             WRITESUCCEEDED))
11172                                 WORKLIST_INSERT(&reattach, wk);
11173                         continue;
11174
11175                 case D_BMSAFEMAP:
11176                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11177                             WRITESUCCEEDED))
11178                                 WORKLIST_INSERT(&reattach, wk);
11179                         continue;
11180
11181                 case D_MKDIR:
11182                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11183                         continue;
11184
11185                 case D_ALLOCDIRECT:
11186                         wk->wk_state |= COMPLETE;
11187                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11188                         continue;
11189
11190                 case D_ALLOCINDIR:
11191                         wk->wk_state |= COMPLETE;
11192                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11193                         continue;
11194
11195                 case D_INDIRDEP:
11196                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11197                             WRITESUCCEEDED))
11198                                 WORKLIST_INSERT(&reattach, wk);
11199                         continue;
11200
11201                 case D_FREEBLKS:
11202                         wk->wk_state |= COMPLETE;
11203                         freeblks = WK_FREEBLKS(wk);
11204                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11205                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11206                                 add_to_worklist(wk, WK_NODELAY);
11207                         continue;
11208
11209                 case D_FREEWORK:
11210                         handle_written_freework(WK_FREEWORK(wk));
11211                         break;
11212
11213                 case D_JSEGDEP:
11214                         free_jsegdep(WK_JSEGDEP(wk));
11215                         continue;
11216
11217                 case D_JSEG:
11218                         handle_written_jseg(WK_JSEG(wk), bp);
11219                         continue;
11220
11221                 case D_SBDEP:
11222                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11223                                 WORKLIST_INSERT(&reattach, wk);
11224                         continue;
11225
11226                 case D_FREEDEP:
11227                         free_freedep(WK_FREEDEP(wk));
11228                         continue;
11229
11230                 default:
11231                         panic("handle_disk_write_complete: Unknown type %s",
11232                             TYPENAME(wk->wk_type));
11233                         /* NOTREACHED */
11234                 }
11235         }
11236         /*
11237          * Reattach any requests that must be redone.
11238          */
11239         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11240                 WORKLIST_REMOVE(wk);
11241                 WORKLIST_INSERT(&bp->b_dep, wk);
11242         }
11243         FREE_LOCK(ump);
11244         if (sbp)
11245                 brelse(sbp);
11246 }
11247
11248 /*
11249  * Called from within softdep_disk_write_complete above.
11250  */
11251 static void 
11252 handle_allocdirect_partdone(adp, wkhd)
11253         struct allocdirect *adp;        /* the completed allocdirect */
11254         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11255 {
11256         struct allocdirectlst *listhead;
11257         struct allocdirect *listadp;
11258         struct inodedep *inodedep;
11259         long bsize;
11260
11261         LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11262         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11263                 return;
11264         /*
11265          * The on-disk inode cannot claim to be any larger than the last
11266          * fragment that has been written. Otherwise, the on-disk inode
11267          * might have fragments that were not the last block in the file
11268          * which would corrupt the filesystem. Thus, we cannot free any
11269          * allocdirects after one whose ad_oldblkno claims a fragment as
11270          * these blocks must be rolled back to zero before writing the inode.
11271          * We check the currently active set of allocdirects in id_inoupdt
11272          * or id_extupdt as appropriate.
11273          */
11274         inodedep = adp->ad_inodedep;
11275         bsize = inodedep->id_fs->fs_bsize;
11276         if (adp->ad_state & EXTDATA)
11277                 listhead = &inodedep->id_extupdt;
11278         else
11279                 listhead = &inodedep->id_inoupdt;
11280         TAILQ_FOREACH(listadp, listhead, ad_next) {
11281                 /* found our block */
11282                 if (listadp == adp)
11283                         break;
11284                 /* continue if ad_oldlbn is not a fragment */
11285                 if (listadp->ad_oldsize == 0 ||
11286                     listadp->ad_oldsize == bsize)
11287                         continue;
11288                 /* hit a fragment */
11289                 return;
11290         }
11291         /*
11292          * If we have reached the end of the current list without
11293          * finding the just finished dependency, then it must be
11294          * on the future dependency list. Future dependencies cannot
11295          * be freed until they are moved to the current list.
11296          */
11297         if (listadp == NULL) {
11298 #ifdef INVARIANTS
11299                 if (adp->ad_state & EXTDATA)
11300                         listhead = &inodedep->id_newextupdt;
11301                 else
11302                         listhead = &inodedep->id_newinoupdt;
11303                 TAILQ_FOREACH(listadp, listhead, ad_next)
11304                         /* found our block */
11305                         if (listadp == adp)
11306                                 break;
11307                 if (listadp == NULL)
11308                         panic("handle_allocdirect_partdone: lost dep");
11309 #endif /* INVARIANTS */
11310                 return;
11311         }
11312         /*
11313          * If we have found the just finished dependency, then queue
11314          * it along with anything that follows it that is complete.
11315          * Since the pointer has not yet been written in the inode
11316          * as the dependency prevents it, place the allocdirect on the
11317          * bufwait list where it will be freed once the pointer is
11318          * valid.
11319          */
11320         if (wkhd == NULL)
11321                 wkhd = &inodedep->id_bufwait;
11322         for (; adp; adp = listadp) {
11323                 listadp = TAILQ_NEXT(adp, ad_next);
11324                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11325                         return;
11326                 TAILQ_REMOVE(listhead, adp, ad_next);
11327                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11328         }
11329 }
11330
11331 /*
11332  * Called from within softdep_disk_write_complete above.  This routine
11333  * completes successfully written allocindirs.
11334  */
11335 static void
11336 handle_allocindir_partdone(aip)
11337         struct allocindir *aip;         /* the completed allocindir */
11338 {
11339         struct indirdep *indirdep;
11340
11341         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11342                 return;
11343         indirdep = aip->ai_indirdep;
11344         LIST_REMOVE(aip, ai_next);
11345         /*
11346          * Don't set a pointer while the buffer is undergoing IO or while
11347          * we have active truncations.
11348          */
11349         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11350                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11351                 return;
11352         }
11353         if (indirdep->ir_state & UFS1FMT)
11354                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11355                     aip->ai_newblkno;
11356         else
11357                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11358                     aip->ai_newblkno;
11359         /*
11360          * Await the pointer write before freeing the allocindir.
11361          */
11362         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11363 }
11364
11365 /*
11366  * Release segments held on a jwork list.
11367  */
11368 static void
11369 handle_jwork(wkhd)
11370         struct workhead *wkhd;
11371 {
11372         struct worklist *wk;
11373
11374         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11375                 WORKLIST_REMOVE(wk);
11376                 switch (wk->wk_type) {
11377                 case D_JSEGDEP:
11378                         free_jsegdep(WK_JSEGDEP(wk));
11379                         continue;
11380                 case D_FREEDEP:
11381                         free_freedep(WK_FREEDEP(wk));
11382                         continue;
11383                 case D_FREEFRAG:
11384                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11385                         WORKITEM_FREE(wk, D_FREEFRAG);
11386                         continue;
11387                 case D_FREEWORK:
11388                         handle_written_freework(WK_FREEWORK(wk));
11389                         continue;
11390                 default:
11391                         panic("handle_jwork: Unknown type %s\n",
11392                             TYPENAME(wk->wk_type));
11393                 }
11394         }
11395 }
11396
11397 /*
11398  * Handle the bufwait list on an inode when it is safe to release items
11399  * held there.  This normally happens after an inode block is written but
11400  * may be delayed and handled later if there are pending journal items that
11401  * are not yet safe to be released.
11402  */
11403 static struct freefile *
11404 handle_bufwait(inodedep, refhd)
11405         struct inodedep *inodedep;
11406         struct workhead *refhd;
11407 {
11408         struct jaddref *jaddref;
11409         struct freefile *freefile;
11410         struct worklist *wk;
11411
11412         freefile = NULL;
11413         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11414                 WORKLIST_REMOVE(wk);
11415                 switch (wk->wk_type) {
11416                 case D_FREEFILE:
11417                         /*
11418                          * We defer adding freefile to the worklist
11419                          * until all other additions have been made to
11420                          * ensure that it will be done after all the
11421                          * old blocks have been freed.
11422                          */
11423                         if (freefile != NULL)
11424                                 panic("handle_bufwait: freefile");
11425                         freefile = WK_FREEFILE(wk);
11426                         continue;
11427
11428                 case D_MKDIR:
11429                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11430                         continue;
11431
11432                 case D_DIRADD:
11433                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11434                         continue;
11435
11436                 case D_FREEFRAG:
11437                         wk->wk_state |= COMPLETE;
11438                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11439                                 add_to_worklist(wk, 0);
11440                         continue;
11441
11442                 case D_DIRREM:
11443                         wk->wk_state |= COMPLETE;
11444                         add_to_worklist(wk, 0);
11445                         continue;
11446
11447                 case D_ALLOCDIRECT:
11448                 case D_ALLOCINDIR:
11449                         free_newblk(WK_NEWBLK(wk));
11450                         continue;
11451
11452                 case D_JNEWBLK:
11453                         wk->wk_state |= COMPLETE;
11454                         free_jnewblk(WK_JNEWBLK(wk));
11455                         continue;
11456
11457                 /*
11458                  * Save freed journal segments and add references on
11459                  * the supplied list which will delay their release
11460                  * until the cg bitmap is cleared on disk.
11461                  */
11462                 case D_JSEGDEP:
11463                         if (refhd == NULL)
11464                                 free_jsegdep(WK_JSEGDEP(wk));
11465                         else
11466                                 WORKLIST_INSERT(refhd, wk);
11467                         continue;
11468
11469                 case D_JADDREF:
11470                         jaddref = WK_JADDREF(wk);
11471                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11472                             if_deps);
11473                         /*
11474                          * Transfer any jaddrefs to the list to be freed with
11475                          * the bitmap if we're handling a removed file.
11476                          */
11477                         if (refhd == NULL) {
11478                                 wk->wk_state |= COMPLETE;
11479                                 free_jaddref(jaddref);
11480                         } else
11481                                 WORKLIST_INSERT(refhd, wk);
11482                         continue;
11483
11484                 default:
11485                         panic("handle_bufwait: Unknown type %p(%s)",
11486                             wk, TYPENAME(wk->wk_type));
11487                         /* NOTREACHED */
11488                 }
11489         }
11490         return (freefile);
11491 }
11492 /*
11493  * Called from within softdep_disk_write_complete above to restore
11494  * in-memory inode block contents to their most up-to-date state. Note
11495  * that this routine is always called from interrupt level with further
11496  * interrupts from this device blocked.
11497  *
11498  * If the write did not succeed, we will do all the roll-forward
11499  * operations, but we will not take the actions that will allow its
11500  * dependencies to be processed.
11501  */
11502 static int 
11503 handle_written_inodeblock(inodedep, bp, flags)
11504         struct inodedep *inodedep;
11505         struct buf *bp;         /* buffer containing the inode block */
11506         int flags;
11507 {
11508         struct freefile *freefile;
11509         struct allocdirect *adp, *nextadp;
11510         struct ufs1_dinode *dp1 = NULL;
11511         struct ufs2_dinode *dp2 = NULL;
11512         struct workhead wkhd;
11513         int hadchanges, fstype;
11514         ino_t freelink;
11515
11516         LIST_INIT(&wkhd);
11517         hadchanges = 0;
11518         freefile = NULL;
11519         if ((inodedep->id_state & IOSTARTED) == 0)
11520                 panic("handle_written_inodeblock: not started");
11521         inodedep->id_state &= ~IOSTARTED;
11522         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11523                 fstype = UFS1;
11524                 dp1 = (struct ufs1_dinode *)bp->b_data +
11525                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11526                 freelink = dp1->di_freelink;
11527         } else {
11528                 fstype = UFS2;
11529                 dp2 = (struct ufs2_dinode *)bp->b_data +
11530                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11531                 freelink = dp2->di_freelink;
11532         }
11533         /*
11534          * Leave this inodeblock dirty until it's in the list.
11535          */
11536         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11537             (flags & WRITESUCCEEDED)) {
11538                 struct inodedep *inon;
11539
11540                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11541                 if ((inon == NULL && freelink == 0) ||
11542                     (inon && inon->id_ino == freelink)) {
11543                         if (inon)
11544                                 inon->id_state |= UNLINKPREV;
11545                         inodedep->id_state |= UNLINKNEXT;
11546                 }
11547                 hadchanges = 1;
11548         }
11549         /*
11550          * If we had to rollback the inode allocation because of
11551          * bitmaps being incomplete, then simply restore it.
11552          * Keep the block dirty so that it will not be reclaimed until
11553          * all associated dependencies have been cleared and the
11554          * corresponding updates written to disk.
11555          */
11556         if (inodedep->id_savedino1 != NULL) {
11557                 hadchanges = 1;
11558                 if (fstype == UFS1)
11559                         *dp1 = *inodedep->id_savedino1;
11560                 else
11561                         *dp2 = *inodedep->id_savedino2;
11562                 free(inodedep->id_savedino1, M_SAVEDINO);
11563                 inodedep->id_savedino1 = NULL;
11564                 if ((bp->b_flags & B_DELWRI) == 0)
11565                         stat_inode_bitmap++;
11566                 bdirty(bp);
11567                 /*
11568                  * If the inode is clear here and GOINGAWAY it will never
11569                  * be written.  Process the bufwait and clear any pending
11570                  * work which may include the freefile.
11571                  */
11572                 if (inodedep->id_state & GOINGAWAY)
11573                         goto bufwait;
11574                 return (1);
11575         }
11576         if (flags & WRITESUCCEEDED)
11577                 inodedep->id_state |= COMPLETE;
11578         /*
11579          * Roll forward anything that had to be rolled back before 
11580          * the inode could be updated.
11581          */
11582         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11583                 nextadp = TAILQ_NEXT(adp, ad_next);
11584                 if (adp->ad_state & ATTACHED)
11585                         panic("handle_written_inodeblock: new entry");
11586                 if (fstype == UFS1) {
11587                         if (adp->ad_offset < UFS_NDADDR) {
11588                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11589                                         panic("%s %s #%jd mismatch %d != %jd",
11590                                             "handle_written_inodeblock:",
11591                                             "direct pointer",
11592                                             (intmax_t)adp->ad_offset,
11593                                             dp1->di_db[adp->ad_offset],
11594                                             (intmax_t)adp->ad_oldblkno);
11595                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11596                         } else {
11597                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11598                                     0)
11599                                         panic("%s: %s #%jd allocated as %d",
11600                                             "handle_written_inodeblock",
11601                                             "indirect pointer",
11602                                             (intmax_t)adp->ad_offset -
11603                                             UFS_NDADDR,
11604                                             dp1->di_ib[adp->ad_offset -
11605                                             UFS_NDADDR]);
11606                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11607                                     adp->ad_newblkno;
11608                         }
11609                 } else {
11610                         if (adp->ad_offset < UFS_NDADDR) {
11611                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11612                                         panic("%s: %s #%jd %s %jd != %jd",
11613                                             "handle_written_inodeblock",
11614                                             "direct pointer",
11615                                             (intmax_t)adp->ad_offset, "mismatch",
11616                                             (intmax_t)dp2->di_db[adp->ad_offset],
11617                                             (intmax_t)adp->ad_oldblkno);
11618                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11619                         } else {
11620                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11621                                     0)
11622                                         panic("%s: %s #%jd allocated as %jd",
11623                                             "handle_written_inodeblock",
11624                                             "indirect pointer",
11625                                             (intmax_t)adp->ad_offset -
11626                                             UFS_NDADDR,
11627                                             (intmax_t)
11628                                             dp2->di_ib[adp->ad_offset -
11629                                             UFS_NDADDR]);
11630                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11631                                     adp->ad_newblkno;
11632                         }
11633                 }
11634                 adp->ad_state &= ~UNDONE;
11635                 adp->ad_state |= ATTACHED;
11636                 hadchanges = 1;
11637         }
11638         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11639                 nextadp = TAILQ_NEXT(adp, ad_next);
11640                 if (adp->ad_state & ATTACHED)
11641                         panic("handle_written_inodeblock: new entry");
11642                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11643                         panic("%s: direct pointers #%jd %s %jd != %jd",
11644                             "handle_written_inodeblock",
11645                             (intmax_t)adp->ad_offset, "mismatch",
11646                             (intmax_t)dp2->di_extb[adp->ad_offset],
11647                             (intmax_t)adp->ad_oldblkno);
11648                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11649                 adp->ad_state &= ~UNDONE;
11650                 adp->ad_state |= ATTACHED;
11651                 hadchanges = 1;
11652         }
11653         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11654                 stat_direct_blk_ptrs++;
11655         /*
11656          * Reset the file size to its most up-to-date value.
11657          */
11658         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11659                 panic("handle_written_inodeblock: bad size");
11660         if (inodedep->id_savednlink > UFS_LINK_MAX)
11661                 panic("handle_written_inodeblock: Invalid link count "
11662                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11663                     inodedep);
11664         if (fstype == UFS1) {
11665                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11666                         dp1->di_nlink = inodedep->id_savednlink;
11667                         hadchanges = 1;
11668                 }
11669                 if (dp1->di_size != inodedep->id_savedsize) {
11670                         dp1->di_size = inodedep->id_savedsize;
11671                         hadchanges = 1;
11672                 }
11673         } else {
11674                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11675                         dp2->di_nlink = inodedep->id_savednlink;
11676                         hadchanges = 1;
11677                 }
11678                 if (dp2->di_size != inodedep->id_savedsize) {
11679                         dp2->di_size = inodedep->id_savedsize;
11680                         hadchanges = 1;
11681                 }
11682                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11683                         dp2->di_extsize = inodedep->id_savedextsize;
11684                         hadchanges = 1;
11685                 }
11686         }
11687         inodedep->id_savedsize = -1;
11688         inodedep->id_savedextsize = -1;
11689         inodedep->id_savednlink = -1;
11690         /*
11691          * If there were any rollbacks in the inode block, then it must be
11692          * marked dirty so that its will eventually get written back in
11693          * its correct form.
11694          */
11695         if (hadchanges) {
11696                 if (fstype == UFS2)
11697                         ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11698                 bdirty(bp);
11699         }
11700 bufwait:
11701         /*
11702          * If the write did not succeed, we have done all the roll-forward
11703          * operations, but we cannot take the actions that will allow its
11704          * dependencies to be processed.
11705          */
11706         if ((flags & WRITESUCCEEDED) == 0)
11707                 return (hadchanges);
11708         /*
11709          * Process any allocdirects that completed during the update.
11710          */
11711         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11712                 handle_allocdirect_partdone(adp, &wkhd);
11713         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11714                 handle_allocdirect_partdone(adp, &wkhd);
11715         /*
11716          * Process deallocations that were held pending until the
11717          * inode had been written to disk. Freeing of the inode
11718          * is delayed until after all blocks have been freed to
11719          * avoid creation of new <vfsid, inum, lbn> triples
11720          * before the old ones have been deleted.  Completely
11721          * unlinked inodes are not processed until the unlinked
11722          * inode list is written or the last reference is removed.
11723          */
11724         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11725                 freefile = handle_bufwait(inodedep, NULL);
11726                 if (freefile && !LIST_EMPTY(&wkhd)) {
11727                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11728                         freefile = NULL;
11729                 }
11730         }
11731         /*
11732          * Move rolled forward dependency completions to the bufwait list
11733          * now that those that were already written have been processed.
11734          */
11735         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11736                 panic("handle_written_inodeblock: bufwait but no changes");
11737         jwork_move(&inodedep->id_bufwait, &wkhd);
11738
11739         if (freefile != NULL) {
11740                 /*
11741                  * If the inode is goingaway it was never written.  Fake up
11742                  * the state here so free_inodedep() can succeed.
11743                  */
11744                 if (inodedep->id_state & GOINGAWAY)
11745                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11746                 if (free_inodedep(inodedep) == 0)
11747                         panic("handle_written_inodeblock: live inodedep %p",
11748                             inodedep);
11749                 add_to_worklist(&freefile->fx_list, 0);
11750                 return (0);
11751         }
11752
11753         /*
11754          * If no outstanding dependencies, free it.
11755          */
11756         if (free_inodedep(inodedep) ||
11757             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11758              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11759              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11760              LIST_FIRST(&inodedep->id_bufwait) == 0))
11761                 return (0);
11762         return (hadchanges);
11763 }
11764
11765 /*
11766  * Perform needed roll-forwards and kick off any dependencies that
11767  * can now be processed.
11768  *
11769  * If the write did not succeed, we will do all the roll-forward
11770  * operations, but we will not take the actions that will allow its
11771  * dependencies to be processed.
11772  */
11773 static int
11774 handle_written_indirdep(indirdep, bp, bpp, flags)
11775         struct indirdep *indirdep;
11776         struct buf *bp;
11777         struct buf **bpp;
11778         int flags;
11779 {
11780         struct allocindir *aip;
11781         struct buf *sbp;
11782         int chgs;
11783
11784         if (indirdep->ir_state & GOINGAWAY)
11785                 panic("handle_written_indirdep: indirdep gone");
11786         if ((indirdep->ir_state & IOSTARTED) == 0)
11787                 panic("handle_written_indirdep: IO not started");
11788         chgs = 0;
11789         /*
11790          * If there were rollbacks revert them here.
11791          */
11792         if (indirdep->ir_saveddata) {
11793                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11794                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11795                         free(indirdep->ir_saveddata, M_INDIRDEP);
11796                         indirdep->ir_saveddata = NULL;
11797                 }
11798                 chgs = 1;
11799         }
11800         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11801         indirdep->ir_state |= ATTACHED;
11802         /*
11803          * If the write did not succeed, we have done all the roll-forward
11804          * operations, but we cannot take the actions that will allow its
11805          * dependencies to be processed.
11806          */
11807         if ((flags & WRITESUCCEEDED) == 0) {
11808                 stat_indir_blk_ptrs++;
11809                 bdirty(bp);
11810                 return (1);
11811         }
11812         /*
11813          * Move allocindirs with written pointers to the completehd if
11814          * the indirdep's pointer is not yet written.  Otherwise
11815          * free them here.
11816          */
11817         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11818                 LIST_REMOVE(aip, ai_next);
11819                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11820                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11821                             ai_next);
11822                         newblk_freefrag(&aip->ai_block);
11823                         continue;
11824                 }
11825                 free_newblk(&aip->ai_block);
11826         }
11827         /*
11828          * Move allocindirs that have finished dependency processing from
11829          * the done list to the write list after updating the pointers.
11830          */
11831         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11832                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11833                         handle_allocindir_partdone(aip);
11834                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11835                                 panic("disk_write_complete: not gone");
11836                         chgs = 1;
11837                 }
11838         }
11839         /*
11840          * Preserve the indirdep if there were any changes or if it is not
11841          * yet valid on disk.
11842          */
11843         if (chgs) {
11844                 stat_indir_blk_ptrs++;
11845                 bdirty(bp);
11846                 return (1);
11847         }
11848         /*
11849          * If there were no changes we can discard the savedbp and detach
11850          * ourselves from the buf.  We are only carrying completed pointers
11851          * in this case.
11852          */
11853         sbp = indirdep->ir_savebp;
11854         sbp->b_flags |= B_INVAL | B_NOCACHE;
11855         indirdep->ir_savebp = NULL;
11856         indirdep->ir_bp = NULL;
11857         if (*bpp != NULL)
11858                 panic("handle_written_indirdep: bp already exists.");
11859         *bpp = sbp;
11860         /*
11861          * The indirdep may not be freed until its parent points at it.
11862          */
11863         if (indirdep->ir_state & DEPCOMPLETE)
11864                 free_indirdep(indirdep);
11865
11866         return (0);
11867 }
11868
11869 /*
11870  * Process a diradd entry after its dependent inode has been written.
11871  */
11872 static void
11873 diradd_inode_written(dap, inodedep)
11874         struct diradd *dap;
11875         struct inodedep *inodedep;
11876 {
11877
11878         LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11879         dap->da_state |= COMPLETE;
11880         complete_diradd(dap);
11881         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11882 }
11883
11884 /*
11885  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11886  * be called with the per-filesystem lock and the buf lock on the cg held.
11887  */
11888 static int
11889 bmsafemap_backgroundwrite(bmsafemap, bp)
11890         struct bmsafemap *bmsafemap;
11891         struct buf *bp;
11892 {
11893         int dirty;
11894
11895         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11896         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11897             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11898         /*
11899          * If we're initiating a background write we need to process the
11900          * rollbacks as they exist now, not as they exist when IO starts.
11901          * No other consumers will look at the contents of the shadowed
11902          * buf so this is safe to do here.
11903          */
11904         if (bp->b_xflags & BX_BKGRDMARKER)
11905                 initiate_write_bmsafemap(bmsafemap, bp);
11906
11907         return (dirty);
11908 }
11909
11910 /*
11911  * Re-apply an allocation when a cg write is complete.
11912  */
11913 static int
11914 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11915         struct jnewblk *jnewblk;
11916         struct fs *fs;
11917         struct cg *cgp;
11918         uint8_t *blksfree;
11919 {
11920         ufs1_daddr_t fragno;
11921         ufs2_daddr_t blkno;
11922         long cgbno, bbase;
11923         int frags, blk;
11924         int i;
11925
11926         frags = 0;
11927         cgbno = dtogd(fs, jnewblk->jn_blkno);
11928         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11929                 if (isclr(blksfree, cgbno + i))
11930                         panic("jnewblk_rollforward: re-allocated fragment");
11931                 frags++;
11932         }
11933         if (frags == fs->fs_frag) {
11934                 blkno = fragstoblks(fs, cgbno);
11935                 ffs_clrblock(fs, blksfree, (long)blkno);
11936                 ffs_clusteracct(fs, cgp, blkno, -1);
11937                 cgp->cg_cs.cs_nbfree--;
11938         } else {
11939                 bbase = cgbno - fragnum(fs, cgbno);
11940                 cgbno += jnewblk->jn_oldfrags;
11941                 /* If a complete block had been reassembled, account for it. */
11942                 fragno = fragstoblks(fs, bbase);
11943                 if (ffs_isblock(fs, blksfree, fragno)) {
11944                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11945                         ffs_clusteracct(fs, cgp, fragno, -1);
11946                         cgp->cg_cs.cs_nbfree--;
11947                 }
11948                 /* Decrement the old frags.  */
11949                 blk = blkmap(fs, blksfree, bbase);
11950                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11951                 /* Allocate the fragment */
11952                 for (i = 0; i < frags; i++)
11953                         clrbit(blksfree, cgbno + i);
11954                 cgp->cg_cs.cs_nffree -= frags;
11955                 /* Add back in counts associated with the new frags */
11956                 blk = blkmap(fs, blksfree, bbase);
11957                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11958         }
11959         return (frags);
11960 }
11961
11962 /*
11963  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11964  * changes if it's not a background write.  Set all written dependencies 
11965  * to DEPCOMPLETE and free the structure if possible.
11966  *
11967  * If the write did not succeed, we will do all the roll-forward
11968  * operations, but we will not take the actions that will allow its
11969  * dependencies to be processed.
11970  */
11971 static int
11972 handle_written_bmsafemap(bmsafemap, bp, flags)
11973         struct bmsafemap *bmsafemap;
11974         struct buf *bp;
11975         int flags;
11976 {
11977         struct newblk *newblk;
11978         struct inodedep *inodedep;
11979         struct jaddref *jaddref, *jatmp;
11980         struct jnewblk *jnewblk, *jntmp;
11981         struct ufsmount *ump;
11982         uint8_t *inosused;
11983         uint8_t *blksfree;
11984         struct cg *cgp;
11985         struct fs *fs;
11986         ino_t ino;
11987         int foreground;
11988         int chgs;
11989
11990         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11991                 panic("handle_written_bmsafemap: Not started\n");
11992         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11993         chgs = 0;
11994         bmsafemap->sm_state &= ~IOSTARTED;
11995         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11996         /*
11997          * If write was successful, release journal work that was waiting
11998          * on the write. Otherwise move the work back.
11999          */
12000         if (flags & WRITESUCCEEDED)
12001                 handle_jwork(&bmsafemap->sm_freewr);
12002         else
12003                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12004                     worklist, wk_list);
12005
12006         /*
12007          * Restore unwritten inode allocation pending jaddref writes.
12008          */
12009         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12010                 cgp = (struct cg *)bp->b_data;
12011                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12012                 inosused = cg_inosused(cgp);
12013                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12014                     ja_bmdeps, jatmp) {
12015                         if ((jaddref->ja_state & UNDONE) == 0)
12016                                 continue;
12017                         ino = jaddref->ja_ino % fs->fs_ipg;
12018                         if (isset(inosused, ino))
12019                                 panic("handle_written_bmsafemap: "
12020                                     "re-allocated inode");
12021                         /* Do the roll-forward only if it's a real copy. */
12022                         if (foreground) {
12023                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
12024                                         cgp->cg_cs.cs_ndir++;
12025                                 cgp->cg_cs.cs_nifree--;
12026                                 setbit(inosused, ino);
12027                                 chgs = 1;
12028                         }
12029                         jaddref->ja_state &= ~UNDONE;
12030                         jaddref->ja_state |= ATTACHED;
12031                         free_jaddref(jaddref);
12032                 }
12033         }
12034         /*
12035          * Restore any block allocations which are pending journal writes.
12036          */
12037         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12038                 cgp = (struct cg *)bp->b_data;
12039                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12040                 blksfree = cg_blksfree(cgp);
12041                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12042                     jntmp) {
12043                         if ((jnewblk->jn_state & UNDONE) == 0)
12044                                 continue;
12045                         /* Do the roll-forward only if it's a real copy. */
12046                         if (foreground &&
12047                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12048                                 chgs = 1;
12049                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12050                         jnewblk->jn_state |= ATTACHED;
12051                         free_jnewblk(jnewblk);
12052                 }
12053         }
12054         /*
12055          * If the write did not succeed, we have done all the roll-forward
12056          * operations, but we cannot take the actions that will allow its
12057          * dependencies to be processed.
12058          */
12059         if ((flags & WRITESUCCEEDED) == 0) {
12060                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12061                     newblk, nb_deps);
12062                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12063                     worklist, wk_list);
12064                 if (foreground)
12065                         bdirty(bp);
12066                 return (1);
12067         }
12068         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12069                 newblk->nb_state |= DEPCOMPLETE;
12070                 newblk->nb_state &= ~ONDEPLIST;
12071                 newblk->nb_bmsafemap = NULL;
12072                 LIST_REMOVE(newblk, nb_deps);
12073                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12074                         handle_allocdirect_partdone(
12075                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12076                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12077                         handle_allocindir_partdone(
12078                             WK_ALLOCINDIR(&newblk->nb_list));
12079                 else if (newblk->nb_list.wk_type != D_NEWBLK)
12080                         panic("handle_written_bmsafemap: Unexpected type: %s",
12081                             TYPENAME(newblk->nb_list.wk_type));
12082         }
12083         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12084                 inodedep->id_state |= DEPCOMPLETE;
12085                 inodedep->id_state &= ~ONDEPLIST;
12086                 LIST_REMOVE(inodedep, id_deps);
12087                 inodedep->id_bmsafemap = NULL;
12088         }
12089         LIST_REMOVE(bmsafemap, sm_next);
12090         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12091             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12092             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12093             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12094             LIST_EMPTY(&bmsafemap->sm_freehd)) {
12095                 LIST_REMOVE(bmsafemap, sm_hash);
12096                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12097                 return (0);
12098         }
12099         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12100         if (foreground)
12101                 bdirty(bp);
12102         return (1);
12103 }
12104
12105 /*
12106  * Try to free a mkdir dependency.
12107  */
12108 static void
12109 complete_mkdir(mkdir)
12110         struct mkdir *mkdir;
12111 {
12112         struct diradd *dap;
12113
12114         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12115                 return;
12116         LIST_REMOVE(mkdir, md_mkdirs);
12117         dap = mkdir->md_diradd;
12118         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12119         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12120                 dap->da_state |= DEPCOMPLETE;
12121                 complete_diradd(dap);
12122         }
12123         WORKITEM_FREE(mkdir, D_MKDIR);
12124 }
12125
12126 /*
12127  * Handle the completion of a mkdir dependency.
12128  */
12129 static void
12130 handle_written_mkdir(mkdir, type)
12131         struct mkdir *mkdir;
12132         int type;
12133 {
12134
12135         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12136                 panic("handle_written_mkdir: bad type");
12137         mkdir->md_state |= COMPLETE;
12138         complete_mkdir(mkdir);
12139 }
12140
12141 static int
12142 free_pagedep(pagedep)
12143         struct pagedep *pagedep;
12144 {
12145         int i;
12146
12147         if (pagedep->pd_state & NEWBLOCK)
12148                 return (0);
12149         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12150                 return (0);
12151         for (i = 0; i < DAHASHSZ; i++)
12152                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12153                         return (0);
12154         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12155                 return (0);
12156         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12157                 return (0);
12158         if (pagedep->pd_state & ONWORKLIST)
12159                 WORKLIST_REMOVE(&pagedep->pd_list);
12160         LIST_REMOVE(pagedep, pd_hash);
12161         WORKITEM_FREE(pagedep, D_PAGEDEP);
12162
12163         return (1);
12164 }
12165
12166 /*
12167  * Called from within softdep_disk_write_complete above.
12168  * A write operation was just completed. Removed inodes can
12169  * now be freed and associated block pointers may be committed.
12170  * Note that this routine is always called from interrupt level
12171  * with further interrupts from this device blocked.
12172  *
12173  * If the write did not succeed, we will do all the roll-forward
12174  * operations, but we will not take the actions that will allow its
12175  * dependencies to be processed.
12176  */
12177 static int 
12178 handle_written_filepage(pagedep, bp, flags)
12179         struct pagedep *pagedep;
12180         struct buf *bp;         /* buffer containing the written page */
12181         int flags;
12182 {
12183         struct dirrem *dirrem;
12184         struct diradd *dap, *nextdap;
12185         struct direct *ep;
12186         int i, chgs;
12187
12188         if ((pagedep->pd_state & IOSTARTED) == 0)
12189                 panic("handle_written_filepage: not started");
12190         pagedep->pd_state &= ~IOSTARTED;
12191         if ((flags & WRITESUCCEEDED) == 0)
12192                 goto rollforward;
12193         /*
12194          * Process any directory removals that have been committed.
12195          */
12196         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12197                 LIST_REMOVE(dirrem, dm_next);
12198                 dirrem->dm_state |= COMPLETE;
12199                 dirrem->dm_dirinum = pagedep->pd_ino;
12200                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12201                     ("handle_written_filepage: Journal entries not written."));
12202                 add_to_worklist(&dirrem->dm_list, 0);
12203         }
12204         /*
12205          * Free any directory additions that have been committed.
12206          * If it is a newly allocated block, we have to wait until
12207          * the on-disk directory inode claims the new block.
12208          */
12209         if ((pagedep->pd_state & NEWBLOCK) == 0)
12210                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12211                         free_diradd(dap, NULL);
12212 rollforward:
12213         /*
12214          * Uncommitted directory entries must be restored.
12215          */
12216         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12217                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12218                      dap = nextdap) {
12219                         nextdap = LIST_NEXT(dap, da_pdlist);
12220                         if (dap->da_state & ATTACHED)
12221                                 panic("handle_written_filepage: attached");
12222                         ep = (struct direct *)
12223                             ((char *)bp->b_data + dap->da_offset);
12224                         ep->d_ino = dap->da_newinum;
12225                         dap->da_state &= ~UNDONE;
12226                         dap->da_state |= ATTACHED;
12227                         chgs = 1;
12228                         /*
12229                          * If the inode referenced by the directory has
12230                          * been written out, then the dependency can be
12231                          * moved to the pending list.
12232                          */
12233                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12234                                 LIST_REMOVE(dap, da_pdlist);
12235                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12236                                     da_pdlist);
12237                         }
12238                 }
12239         }
12240         /*
12241          * If there were any rollbacks in the directory, then it must be
12242          * marked dirty so that its will eventually get written back in
12243          * its correct form.
12244          */
12245         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12246                 if ((bp->b_flags & B_DELWRI) == 0)
12247                         stat_dir_entry++;
12248                 bdirty(bp);
12249                 return (1);
12250         }
12251         /*
12252          * If we are not waiting for a new directory block to be
12253          * claimed by its inode, then the pagedep will be freed.
12254          * Otherwise it will remain to track any new entries on
12255          * the page in case they are fsync'ed.
12256          */
12257         free_pagedep(pagedep);
12258         return (0);
12259 }
12260
12261 /*
12262  * Writing back in-core inode structures.
12263  * 
12264  * The filesystem only accesses an inode's contents when it occupies an
12265  * "in-core" inode structure.  These "in-core" structures are separate from
12266  * the page frames used to cache inode blocks.  Only the latter are
12267  * transferred to/from the disk.  So, when the updated contents of the
12268  * "in-core" inode structure are copied to the corresponding in-memory inode
12269  * block, the dependencies are also transferred.  The following procedure is
12270  * called when copying a dirty "in-core" inode to a cached inode block.
12271  */
12272
12273 /*
12274  * Called when an inode is loaded from disk. If the effective link count
12275  * differed from the actual link count when it was last flushed, then we
12276  * need to ensure that the correct effective link count is put back.
12277  */
12278 void 
12279 softdep_load_inodeblock(ip)
12280         struct inode *ip;       /* the "in_core" copy of the inode */
12281 {
12282         struct inodedep *inodedep;
12283         struct ufsmount *ump;
12284
12285         ump = ITOUMP(ip);
12286         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12287             ("softdep_load_inodeblock called on non-softdep filesystem"));
12288         /*
12289          * Check for alternate nlink count.
12290          */
12291         ip->i_effnlink = ip->i_nlink;
12292         ACQUIRE_LOCK(ump);
12293         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12294                 FREE_LOCK(ump);
12295                 return;
12296         }
12297         ip->i_effnlink -= inodedep->id_nlinkdelta;
12298         KASSERT(ip->i_effnlink >= 0,
12299             ("softdep_load_inodeblock: negative i_effnlink"));
12300         FREE_LOCK(ump);
12301 }
12302
12303 /*
12304  * This routine is called just before the "in-core" inode
12305  * information is to be copied to the in-memory inode block.
12306  * Recall that an inode block contains several inodes. If
12307  * the force flag is set, then the dependencies will be
12308  * cleared so that the update can always be made. Note that
12309  * the buffer is locked when this routine is called, so we
12310  * will never be in the middle of writing the inode block 
12311  * to disk.
12312  */
12313 void 
12314 softdep_update_inodeblock(ip, bp, waitfor)
12315         struct inode *ip;       /* the "in_core" copy of the inode */
12316         struct buf *bp;         /* the buffer containing the inode block */
12317         int waitfor;            /* nonzero => update must be allowed */
12318 {
12319         struct inodedep *inodedep;
12320         struct inoref *inoref;
12321         struct ufsmount *ump;
12322         struct worklist *wk;
12323         struct mount *mp;
12324         struct buf *ibp;
12325         struct fs *fs;
12326         int error;
12327
12328         ump = ITOUMP(ip);
12329         mp = UFSTOVFS(ump);
12330         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12331             ("softdep_update_inodeblock called on non-softdep filesystem"));
12332         fs = ump->um_fs;
12333         /*
12334          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12335          * does not have access to the in-core ip so must write directly into
12336          * the inode block buffer when setting freelink.
12337          */
12338         if (fs->fs_magic == FS_UFS1_MAGIC)
12339                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12340                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12341         else
12342                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12343                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12344         /*
12345          * If the effective link count is not equal to the actual link
12346          * count, then we must track the difference in an inodedep while
12347          * the inode is (potentially) tossed out of the cache. Otherwise,
12348          * if there is no existing inodedep, then there are no dependencies
12349          * to track.
12350          */
12351         ACQUIRE_LOCK(ump);
12352 again:
12353         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12354                 FREE_LOCK(ump);
12355                 if (ip->i_effnlink != ip->i_nlink)
12356                         panic("softdep_update_inodeblock: bad link count");
12357                 return;
12358         }
12359         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12360                 panic("softdep_update_inodeblock: bad delta");
12361         /*
12362          * If we're flushing all dependencies we must also move any waiting
12363          * for journal writes onto the bufwait list prior to I/O.
12364          */
12365         if (waitfor) {
12366                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12367                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12368                             == DEPCOMPLETE) {
12369                                 jwait(&inoref->if_list, MNT_WAIT);
12370                                 goto again;
12371                         }
12372                 }
12373         }
12374         /*
12375          * Changes have been initiated. Anything depending on these
12376          * changes cannot occur until this inode has been written.
12377          */
12378         inodedep->id_state &= ~COMPLETE;
12379         if ((inodedep->id_state & ONWORKLIST) == 0)
12380                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12381         /*
12382          * Any new dependencies associated with the incore inode must 
12383          * now be moved to the list associated with the buffer holding
12384          * the in-memory copy of the inode. Once merged process any
12385          * allocdirects that are completed by the merger.
12386          */
12387         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12388         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12389                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12390                     NULL);
12391         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12392         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12393                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12394                     NULL);
12395         /*
12396          * Now that the inode has been pushed into the buffer, the
12397          * operations dependent on the inode being written to disk
12398          * can be moved to the id_bufwait so that they will be
12399          * processed when the buffer I/O completes.
12400          */
12401         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12402                 WORKLIST_REMOVE(wk);
12403                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12404         }
12405         /*
12406          * Newly allocated inodes cannot be written until the bitmap
12407          * that allocates them have been written (indicated by
12408          * DEPCOMPLETE being set in id_state). If we are doing a
12409          * forced sync (e.g., an fsync on a file), we force the bitmap
12410          * to be written so that the update can be done.
12411          */
12412         if (waitfor == 0) {
12413                 FREE_LOCK(ump);
12414                 return;
12415         }
12416 retry:
12417         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12418                 FREE_LOCK(ump);
12419                 return;
12420         }
12421         ibp = inodedep->id_bmsafemap->sm_buf;
12422         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12423         if (ibp == NULL) {
12424                 /*
12425                  * If ibp came back as NULL, the dependency could have been
12426                  * freed while we slept.  Look it up again, and check to see
12427                  * that it has completed.
12428                  */
12429                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12430                         goto retry;
12431                 FREE_LOCK(ump);
12432                 return;
12433         }
12434         FREE_LOCK(ump);
12435         if ((error = bwrite(ibp)) != 0)
12436                 softdep_error("softdep_update_inodeblock: bwrite", error);
12437 }
12438
12439 /*
12440  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12441  * old inode dependency list (such as id_inoupdt).
12442  */
12443 static void
12444 merge_inode_lists(newlisthead, oldlisthead)
12445         struct allocdirectlst *newlisthead;
12446         struct allocdirectlst *oldlisthead;
12447 {
12448         struct allocdirect *listadp, *newadp;
12449
12450         newadp = TAILQ_FIRST(newlisthead);
12451         if (newadp != NULL)
12452                 LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12453         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12454                 if (listadp->ad_offset < newadp->ad_offset) {
12455                         listadp = TAILQ_NEXT(listadp, ad_next);
12456                         continue;
12457                 }
12458                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12459                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12460                 if (listadp->ad_offset == newadp->ad_offset) {
12461                         allocdirect_merge(oldlisthead, newadp,
12462                             listadp);
12463                         listadp = newadp;
12464                 }
12465                 newadp = TAILQ_FIRST(newlisthead);
12466         }
12467         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12468                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12469                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12470         }
12471 }
12472
12473 /*
12474  * If we are doing an fsync, then we must ensure that any directory
12475  * entries for the inode have been written after the inode gets to disk.
12476  */
12477 int
12478 softdep_fsync(vp)
12479         struct vnode *vp;       /* the "in_core" copy of the inode */
12480 {
12481         struct inodedep *inodedep;
12482         struct pagedep *pagedep;
12483         struct inoref *inoref;
12484         struct ufsmount *ump;
12485         struct worklist *wk;
12486         struct diradd *dap;
12487         struct mount *mp;
12488         struct vnode *pvp;
12489         struct inode *ip;
12490         struct buf *bp;
12491         struct fs *fs;
12492         struct thread *td = curthread;
12493         int error, flushparent, pagedep_new_block;
12494         ino_t parentino;
12495         ufs_lbn_t lbn;
12496
12497         ip = VTOI(vp);
12498         mp = vp->v_mount;
12499         ump = VFSTOUFS(mp);
12500         fs = ump->um_fs;
12501         if (MOUNTEDSOFTDEP(mp) == 0)
12502                 return (0);
12503         ACQUIRE_LOCK(ump);
12504 restart:
12505         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12506                 FREE_LOCK(ump);
12507                 return (0);
12508         }
12509         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12510                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12511                     == DEPCOMPLETE) {
12512                         jwait(&inoref->if_list, MNT_WAIT);
12513                         goto restart;
12514                 }
12515         }
12516         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12517             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12518             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12519             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12520             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12521                 panic("softdep_fsync: pending ops %p", inodedep);
12522         for (error = 0, flushparent = 0; ; ) {
12523                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12524                         break;
12525                 if (wk->wk_type != D_DIRADD)
12526                         panic("softdep_fsync: Unexpected type %s",
12527                             TYPENAME(wk->wk_type));
12528                 dap = WK_DIRADD(wk);
12529                 /*
12530                  * Flush our parent if this directory entry has a MKDIR_PARENT
12531                  * dependency or is contained in a newly allocated block.
12532                  */
12533                 if (dap->da_state & DIRCHG)
12534                         pagedep = dap->da_previous->dm_pagedep;
12535                 else
12536                         pagedep = dap->da_pagedep;
12537                 parentino = pagedep->pd_ino;
12538                 lbn = pagedep->pd_lbn;
12539                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12540                         panic("softdep_fsync: dirty");
12541                 if ((dap->da_state & MKDIR_PARENT) ||
12542                     (pagedep->pd_state & NEWBLOCK))
12543                         flushparent = 1;
12544                 else
12545                         flushparent = 0;
12546                 /*
12547                  * If we are being fsync'ed as part of vgone'ing this vnode,
12548                  * then we will not be able to release and recover the
12549                  * vnode below, so we just have to give up on writing its
12550                  * directory entry out. It will eventually be written, just
12551                  * not now, but then the user was not asking to have it
12552                  * written, so we are not breaking any promises.
12553                  */
12554                 if (VN_IS_DOOMED(vp))
12555                         break;
12556                 /*
12557                  * We prevent deadlock by always fetching inodes from the
12558                  * root, moving down the directory tree. Thus, when fetching
12559                  * our parent directory, we first try to get the lock. If
12560                  * that fails, we must unlock ourselves before requesting
12561                  * the lock on our parent. See the comment in ufs_lookup
12562                  * for details on possible races.
12563                  */
12564                 FREE_LOCK(ump);
12565                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12566                     FFSV_FORCEINSMQ)) {
12567                         /*
12568                          * Unmount cannot proceed after unlock because
12569                          * caller must have called vn_start_write().
12570                          */
12571                         VOP_UNLOCK(vp);
12572                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12573                             &pvp, FFSV_FORCEINSMQ);
12574                         MPASS(VTOI(pvp)->i_mode != 0);
12575                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12576                         if (VN_IS_DOOMED(vp)) {
12577                                 if (error == 0)
12578                                         vput(pvp);
12579                                 error = ENOENT;
12580                         }
12581                         if (error != 0)
12582                                 return (error);
12583                 }
12584                 /*
12585                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12586                  * that are contained in direct blocks will be resolved by 
12587                  * doing a ffs_update. Pagedeps contained in indirect blocks
12588                  * may require a complete sync'ing of the directory. So, we
12589                  * try the cheap and fast ffs_update first, and if that fails,
12590                  * then we do the slower ffs_syncvnode of the directory.
12591                  */
12592                 if (flushparent) {
12593                         int locked;
12594
12595                         if ((error = ffs_update(pvp, 1)) != 0) {
12596                                 vput(pvp);
12597                                 return (error);
12598                         }
12599                         ACQUIRE_LOCK(ump);
12600                         locked = 1;
12601                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12602                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12603                                         if (wk->wk_type != D_DIRADD)
12604                                                 panic("softdep_fsync: Unexpected type %s",
12605                                                       TYPENAME(wk->wk_type));
12606                                         dap = WK_DIRADD(wk);
12607                                         if (dap->da_state & DIRCHG)
12608                                                 pagedep = dap->da_previous->dm_pagedep;
12609                                         else
12610                                                 pagedep = dap->da_pagedep;
12611                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12612                                         FREE_LOCK(ump);
12613                                         locked = 0;
12614                                         if (pagedep_new_block && (error =
12615                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12616                                                 vput(pvp);
12617                                                 return (error);
12618                                         }
12619                                 }
12620                         }
12621                         if (locked)
12622                                 FREE_LOCK(ump);
12623                 }
12624                 /*
12625                  * Flush directory page containing the inode's name.
12626                  */
12627                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12628                     &bp);
12629                 if (error == 0)
12630                         error = bwrite(bp);
12631                 else
12632                         brelse(bp);
12633                 vput(pvp);
12634                 if (error != 0)
12635                         return (error);
12636                 ACQUIRE_LOCK(ump);
12637                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12638                         break;
12639         }
12640         FREE_LOCK(ump);
12641         return (0);
12642 }
12643
12644 /*
12645  * Flush all the dirty bitmaps associated with the block device
12646  * before flushing the rest of the dirty blocks so as to reduce
12647  * the number of dependencies that will have to be rolled back.
12648  *
12649  * XXX Unused?
12650  */
12651 void
12652 softdep_fsync_mountdev(vp)
12653         struct vnode *vp;
12654 {
12655         struct buf *bp, *nbp;
12656         struct worklist *wk;
12657         struct bufobj *bo;
12658
12659         if (!vn_isdisk(vp, NULL))
12660                 panic("softdep_fsync_mountdev: vnode not a disk");
12661         bo = &vp->v_bufobj;
12662 restart:
12663         BO_LOCK(bo);
12664         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12665                 /* 
12666                  * If it is already scheduled, skip to the next buffer.
12667                  */
12668                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12669                         continue;
12670
12671                 if ((bp->b_flags & B_DELWRI) == 0)
12672                         panic("softdep_fsync_mountdev: not dirty");
12673                 /*
12674                  * We are only interested in bitmaps with outstanding
12675                  * dependencies.
12676                  */
12677                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12678                     wk->wk_type != D_BMSAFEMAP ||
12679                     (bp->b_vflags & BV_BKGRDINPROG)) {
12680                         BUF_UNLOCK(bp);
12681                         continue;
12682                 }
12683                 BO_UNLOCK(bo);
12684                 bremfree(bp);
12685                 (void) bawrite(bp);
12686                 goto restart;
12687         }
12688         drain_output(vp);
12689         BO_UNLOCK(bo);
12690 }
12691
12692 /*
12693  * Sync all cylinder groups that were dirty at the time this function is
12694  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12695  * is used to flush freedep activity that may be holding up writes to a
12696  * indirect block.
12697  */
12698 static int
12699 sync_cgs(mp, waitfor)
12700         struct mount *mp;
12701         int waitfor;
12702 {
12703         struct bmsafemap *bmsafemap;
12704         struct bmsafemap *sentinel;
12705         struct ufsmount *ump;
12706         struct buf *bp;
12707         int error;
12708
12709         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12710         sentinel->sm_cg = -1;
12711         ump = VFSTOUFS(mp);
12712         error = 0;
12713         ACQUIRE_LOCK(ump);
12714         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12715         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12716             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12717                 /* Skip sentinels and cgs with no work to release. */
12718                 if (bmsafemap->sm_cg == -1 ||
12719                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12720                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12721                         LIST_REMOVE(sentinel, sm_next);
12722                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12723                         continue;
12724                 }
12725                 /*
12726                  * If we don't get the lock and we're waiting try again, if
12727                  * not move on to the next buf and try to sync it.
12728                  */
12729                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12730                 if (bp == NULL && waitfor == MNT_WAIT)
12731                         continue;
12732                 LIST_REMOVE(sentinel, sm_next);
12733                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12734                 if (bp == NULL)
12735                         continue;
12736                 FREE_LOCK(ump);
12737                 if (waitfor == MNT_NOWAIT)
12738                         bawrite(bp);
12739                 else
12740                         error = bwrite(bp);
12741                 ACQUIRE_LOCK(ump);
12742                 if (error)
12743                         break;
12744         }
12745         LIST_REMOVE(sentinel, sm_next);
12746         FREE_LOCK(ump);
12747         free(sentinel, M_BMSAFEMAP);
12748         return (error);
12749 }
12750
12751 /*
12752  * This routine is called when we are trying to synchronously flush a
12753  * file. This routine must eliminate any filesystem metadata dependencies
12754  * so that the syncing routine can succeed.
12755  */
12756 int
12757 softdep_sync_metadata(struct vnode *vp)
12758 {
12759         struct inode *ip;
12760         int error;
12761
12762         ip = VTOI(vp);
12763         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12764             ("softdep_sync_metadata called on non-softdep filesystem"));
12765         /*
12766          * Ensure that any direct block dependencies have been cleared,
12767          * truncations are started, and inode references are journaled.
12768          */
12769         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12770         /*
12771          * Write all journal records to prevent rollbacks on devvp.
12772          */
12773         if (vp->v_type == VCHR)
12774                 softdep_flushjournal(vp->v_mount);
12775         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12776         /*
12777          * Ensure that all truncates are written so we won't find deps on
12778          * indirect blocks.
12779          */
12780         process_truncates(vp);
12781         FREE_LOCK(VFSTOUFS(vp->v_mount));
12782
12783         return (error);
12784 }
12785
12786 /*
12787  * This routine is called when we are attempting to sync a buf with
12788  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12789  * other IO it can but returns EBUSY if the buffer is not yet able to
12790  * be written.  Dependencies which will not cause rollbacks will always
12791  * return 0.
12792  */
12793 int
12794 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12795 {
12796         struct indirdep *indirdep;
12797         struct pagedep *pagedep;
12798         struct allocindir *aip;
12799         struct newblk *newblk;
12800         struct ufsmount *ump;
12801         struct buf *nbp;
12802         struct worklist *wk;
12803         int i, error;
12804
12805         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12806             ("softdep_sync_buf called on non-softdep filesystem"));
12807         /*
12808          * For VCHR we just don't want to force flush any dependencies that
12809          * will cause rollbacks.
12810          */
12811         if (vp->v_type == VCHR) {
12812                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12813                         return (EBUSY);
12814                 return (0);
12815         }
12816         ump = VFSTOUFS(vp->v_mount);
12817         ACQUIRE_LOCK(ump);
12818         /*
12819          * As we hold the buffer locked, none of its dependencies
12820          * will disappear.
12821          */
12822         error = 0;
12823 top:
12824         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12825                 switch (wk->wk_type) {
12826
12827                 case D_ALLOCDIRECT:
12828                 case D_ALLOCINDIR:
12829                         newblk = WK_NEWBLK(wk);
12830                         if (newblk->nb_jnewblk != NULL) {
12831                                 if (waitfor == MNT_NOWAIT) {
12832                                         error = EBUSY;
12833                                         goto out_unlock;
12834                                 }
12835                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12836                                 goto top;
12837                         }
12838                         if (newblk->nb_state & DEPCOMPLETE ||
12839                             waitfor == MNT_NOWAIT)
12840                                 continue;
12841                         nbp = newblk->nb_bmsafemap->sm_buf;
12842                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12843                         if (nbp == NULL)
12844                                 goto top;
12845                         FREE_LOCK(ump);
12846                         if ((error = bwrite(nbp)) != 0)
12847                                 goto out;
12848                         ACQUIRE_LOCK(ump);
12849                         continue;
12850
12851                 case D_INDIRDEP:
12852                         indirdep = WK_INDIRDEP(wk);
12853                         if (waitfor == MNT_NOWAIT) {
12854                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12855                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12856                                         error = EBUSY;
12857                                         goto out_unlock;
12858                                 }
12859                         }
12860                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12861                                 panic("softdep_sync_buf: truncation pending.");
12862                 restart:
12863                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12864                                 newblk = (struct newblk *)aip;
12865                                 if (newblk->nb_jnewblk != NULL) {
12866                                         jwait(&newblk->nb_jnewblk->jn_list,
12867                                             waitfor);
12868                                         goto restart;
12869                                 }
12870                                 if (newblk->nb_state & DEPCOMPLETE)
12871                                         continue;
12872                                 nbp = newblk->nb_bmsafemap->sm_buf;
12873                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12874                                 if (nbp == NULL)
12875                                         goto restart;
12876                                 FREE_LOCK(ump);
12877                                 if ((error = bwrite(nbp)) != 0)
12878                                         goto out;
12879                                 ACQUIRE_LOCK(ump);
12880                                 goto restart;
12881                         }
12882                         continue;
12883
12884                 case D_PAGEDEP:
12885                         /*
12886                          * Only flush directory entries in synchronous passes.
12887                          */
12888                         if (waitfor != MNT_WAIT) {
12889                                 error = EBUSY;
12890                                 goto out_unlock;
12891                         }
12892                         /*
12893                          * While syncing snapshots, we must allow recursive
12894                          * lookups.
12895                          */
12896                         BUF_AREC(bp);
12897                         /*
12898                          * We are trying to sync a directory that may
12899                          * have dependencies on both its own metadata
12900                          * and/or dependencies on the inodes of any
12901                          * recently allocated files. We walk its diradd
12902                          * lists pushing out the associated inode.
12903                          */
12904                         pagedep = WK_PAGEDEP(wk);
12905                         for (i = 0; i < DAHASHSZ; i++) {
12906                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12907                                         continue;
12908                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12909                                     &pagedep->pd_diraddhd[i]))) {
12910                                         BUF_NOREC(bp);
12911                                         goto out_unlock;
12912                                 }
12913                         }
12914                         BUF_NOREC(bp);
12915                         continue;
12916
12917                 case D_FREEWORK:
12918                 case D_FREEDEP:
12919                 case D_JSEGDEP:
12920                 case D_JNEWBLK:
12921                         continue;
12922
12923                 default:
12924                         panic("softdep_sync_buf: Unknown type %s",
12925                             TYPENAME(wk->wk_type));
12926                         /* NOTREACHED */
12927                 }
12928         }
12929 out_unlock:
12930         FREE_LOCK(ump);
12931 out:
12932         return (error);
12933 }
12934
12935 /*
12936  * Flush the dependencies associated with an inodedep.
12937  */
12938 static int
12939 flush_inodedep_deps(vp, mp, ino)
12940         struct vnode *vp;
12941         struct mount *mp;
12942         ino_t ino;
12943 {
12944         struct inodedep *inodedep;
12945         struct inoref *inoref;
12946         struct ufsmount *ump;
12947         int error, waitfor;
12948
12949         /*
12950          * This work is done in two passes. The first pass grabs most
12951          * of the buffers and begins asynchronously writing them. The
12952          * only way to wait for these asynchronous writes is to sleep
12953          * on the filesystem vnode which may stay busy for a long time
12954          * if the filesystem is active. So, instead, we make a second
12955          * pass over the dependencies blocking on each write. In the
12956          * usual case we will be blocking against a write that we
12957          * initiated, so when it is done the dependency will have been
12958          * resolved. Thus the second pass is expected to end quickly.
12959          * We give a brief window at the top of the loop to allow
12960          * any pending I/O to complete.
12961          */
12962         ump = VFSTOUFS(mp);
12963         LOCK_OWNED(ump);
12964         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12965                 if (error)
12966                         return (error);
12967                 FREE_LOCK(ump);
12968                 ACQUIRE_LOCK(ump);
12969 restart:
12970                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12971                         return (0);
12972                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12973                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12974                             == DEPCOMPLETE) {
12975                                 jwait(&inoref->if_list, MNT_WAIT);
12976                                 goto restart;
12977                         }
12978                 }
12979                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12980                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12981                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12982                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12983                         continue;
12984                 /*
12985                  * If pass2, we are done, otherwise do pass 2.
12986                  */
12987                 if (waitfor == MNT_WAIT)
12988                         break;
12989                 waitfor = MNT_WAIT;
12990         }
12991         /*
12992          * Try freeing inodedep in case all dependencies have been removed.
12993          */
12994         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12995                 (void) free_inodedep(inodedep);
12996         return (0);
12997 }
12998
12999 /*
13000  * Flush an inode dependency list.
13001  */
13002 static int
13003 flush_deplist(listhead, waitfor, errorp)
13004         struct allocdirectlst *listhead;
13005         int waitfor;
13006         int *errorp;
13007 {
13008         struct allocdirect *adp;
13009         struct newblk *newblk;
13010         struct ufsmount *ump;
13011         struct buf *bp;
13012
13013         if ((adp = TAILQ_FIRST(listhead)) == NULL)
13014                 return (0);
13015         ump = VFSTOUFS(adp->ad_list.wk_mp);
13016         LOCK_OWNED(ump);
13017         TAILQ_FOREACH(adp, listhead, ad_next) {
13018                 newblk = (struct newblk *)adp;
13019                 if (newblk->nb_jnewblk != NULL) {
13020                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13021                         return (1);
13022                 }
13023                 if (newblk->nb_state & DEPCOMPLETE)
13024                         continue;
13025                 bp = newblk->nb_bmsafemap->sm_buf;
13026                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13027                 if (bp == NULL) {
13028                         if (waitfor == MNT_NOWAIT)
13029                                 continue;
13030                         return (1);
13031                 }
13032                 FREE_LOCK(ump);
13033                 if (waitfor == MNT_NOWAIT)
13034                         bawrite(bp);
13035                 else 
13036                         *errorp = bwrite(bp);
13037                 ACQUIRE_LOCK(ump);
13038                 return (1);
13039         }
13040         return (0);
13041 }
13042
13043 /*
13044  * Flush dependencies associated with an allocdirect block.
13045  */
13046 static int
13047 flush_newblk_dep(vp, mp, lbn)
13048         struct vnode *vp;
13049         struct mount *mp;
13050         ufs_lbn_t lbn;
13051 {
13052         struct newblk *newblk;
13053         struct ufsmount *ump;
13054         struct bufobj *bo;
13055         struct inode *ip;
13056         struct buf *bp;
13057         ufs2_daddr_t blkno;
13058         int error;
13059
13060         error = 0;
13061         bo = &vp->v_bufobj;
13062         ip = VTOI(vp);
13063         blkno = DIP(ip, i_db[lbn]);
13064         if (blkno == 0)
13065                 panic("flush_newblk_dep: Missing block");
13066         ump = VFSTOUFS(mp);
13067         ACQUIRE_LOCK(ump);
13068         /*
13069          * Loop until all dependencies related to this block are satisfied.
13070          * We must be careful to restart after each sleep in case a write
13071          * completes some part of this process for us.
13072          */
13073         for (;;) {
13074                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13075                         FREE_LOCK(ump);
13076                         break;
13077                 }
13078                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13079                         panic("flush_newblk_dep: Bad newblk %p", newblk);
13080                 /*
13081                  * Flush the journal.
13082                  */
13083                 if (newblk->nb_jnewblk != NULL) {
13084                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13085                         continue;
13086                 }
13087                 /*
13088                  * Write the bitmap dependency.
13089                  */
13090                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13091                         bp = newblk->nb_bmsafemap->sm_buf;
13092                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13093                         if (bp == NULL)
13094                                 continue;
13095                         FREE_LOCK(ump);
13096                         error = bwrite(bp);
13097                         if (error)
13098                                 break;
13099                         ACQUIRE_LOCK(ump);
13100                         continue;
13101                 }
13102                 /*
13103                  * Write the buffer.
13104                  */
13105                 FREE_LOCK(ump);
13106                 BO_LOCK(bo);
13107                 bp = gbincore(bo, lbn);
13108                 if (bp != NULL) {
13109                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13110                             LK_INTERLOCK, BO_LOCKPTR(bo));
13111                         if (error == ENOLCK) {
13112                                 ACQUIRE_LOCK(ump);
13113                                 error = 0;
13114                                 continue; /* Slept, retry */
13115                         }
13116                         if (error != 0)
13117                                 break;  /* Failed */
13118                         if (bp->b_flags & B_DELWRI) {
13119                                 bremfree(bp);
13120                                 error = bwrite(bp);
13121                                 if (error)
13122                                         break;
13123                         } else
13124                                 BUF_UNLOCK(bp);
13125                 } else
13126                         BO_UNLOCK(bo);
13127                 /*
13128                  * We have to wait for the direct pointers to
13129                  * point at the newdirblk before the dependency
13130                  * will go away.
13131                  */
13132                 error = ffs_update(vp, 1);
13133                 if (error)
13134                         break;
13135                 ACQUIRE_LOCK(ump);
13136         }
13137         return (error);
13138 }
13139
13140 /*
13141  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13142  */
13143 static int
13144 flush_pagedep_deps(pvp, mp, diraddhdp)
13145         struct vnode *pvp;
13146         struct mount *mp;
13147         struct diraddhd *diraddhdp;
13148 {
13149         struct inodedep *inodedep;
13150         struct inoref *inoref;
13151         struct ufsmount *ump;
13152         struct diradd *dap;
13153         struct vnode *vp;
13154         int error = 0;
13155         struct buf *bp;
13156         ino_t inum;
13157         struct diraddhd unfinished;
13158
13159         LIST_INIT(&unfinished);
13160         ump = VFSTOUFS(mp);
13161         LOCK_OWNED(ump);
13162 restart:
13163         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13164                 /*
13165                  * Flush ourselves if this directory entry
13166                  * has a MKDIR_PARENT dependency.
13167                  */
13168                 if (dap->da_state & MKDIR_PARENT) {
13169                         FREE_LOCK(ump);
13170                         if ((error = ffs_update(pvp, 1)) != 0)
13171                                 break;
13172                         ACQUIRE_LOCK(ump);
13173                         /*
13174                          * If that cleared dependencies, go on to next.
13175                          */
13176                         if (dap != LIST_FIRST(diraddhdp))
13177                                 continue;
13178                         /*
13179                          * All MKDIR_PARENT dependencies and all the
13180                          * NEWBLOCK pagedeps that are contained in direct
13181                          * blocks were resolved by doing above ffs_update.
13182                          * Pagedeps contained in indirect blocks may
13183                          * require a complete sync'ing of the directory.
13184                          * We are in the midst of doing a complete sync,
13185                          * so if they are not resolved in this pass we
13186                          * defer them for now as they will be sync'ed by
13187                          * our caller shortly.
13188                          */
13189                         LIST_REMOVE(dap, da_pdlist);
13190                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13191                         continue;
13192                 }
13193                 /*
13194                  * A newly allocated directory must have its "." and
13195                  * ".." entries written out before its name can be
13196                  * committed in its parent. 
13197                  */
13198                 inum = dap->da_newinum;
13199                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13200                         panic("flush_pagedep_deps: lost inode1");
13201                 /*
13202                  * Wait for any pending journal adds to complete so we don't
13203                  * cause rollbacks while syncing.
13204                  */
13205                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13206                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13207                             == DEPCOMPLETE) {
13208                                 jwait(&inoref->if_list, MNT_WAIT);
13209                                 goto restart;
13210                         }
13211                 }
13212                 if (dap->da_state & MKDIR_BODY) {
13213                         FREE_LOCK(ump);
13214                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13215                             FFSV_FORCEINSMQ)))
13216                                 break;
13217                         MPASS(VTOI(vp)->i_mode != 0);
13218                         error = flush_newblk_dep(vp, mp, 0);
13219                         /*
13220                          * If we still have the dependency we might need to
13221                          * update the vnode to sync the new link count to
13222                          * disk.
13223                          */
13224                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13225                                 error = ffs_update(vp, 1);
13226                         vput(vp);
13227                         if (error != 0)
13228                                 break;
13229                         ACQUIRE_LOCK(ump);
13230                         /*
13231                          * If that cleared dependencies, go on to next.
13232                          */
13233                         if (dap != LIST_FIRST(diraddhdp))
13234                                 continue;
13235                         if (dap->da_state & MKDIR_BODY) {
13236                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13237                                     &inodedep);
13238                                 panic("flush_pagedep_deps: MKDIR_BODY "
13239                                     "inodedep %p dap %p vp %p",
13240                                     inodedep, dap, vp);
13241                         }
13242                 }
13243                 /*
13244                  * Flush the inode on which the directory entry depends.
13245                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13246                  * the only remaining dependency is that the updated inode
13247                  * count must get pushed to disk. The inode has already
13248                  * been pushed into its inode buffer (via VOP_UPDATE) at
13249                  * the time of the reference count change. So we need only
13250                  * locate that buffer, ensure that there will be no rollback
13251                  * caused by a bitmap dependency, then write the inode buffer.
13252                  */
13253 retry:
13254                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13255                         panic("flush_pagedep_deps: lost inode");
13256                 /*
13257                  * If the inode still has bitmap dependencies,
13258                  * push them to disk.
13259                  */
13260                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13261                         bp = inodedep->id_bmsafemap->sm_buf;
13262                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13263                         if (bp == NULL)
13264                                 goto retry;
13265                         FREE_LOCK(ump);
13266                         if ((error = bwrite(bp)) != 0)
13267                                 break;
13268                         ACQUIRE_LOCK(ump);
13269                         if (dap != LIST_FIRST(diraddhdp))
13270                                 continue;
13271                 }
13272                 /*
13273                  * If the inode is still sitting in a buffer waiting
13274                  * to be written or waiting for the link count to be
13275                  * adjusted update it here to flush it to disk.
13276                  */
13277                 if (dap == LIST_FIRST(diraddhdp)) {
13278                         FREE_LOCK(ump);
13279                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13280                             FFSV_FORCEINSMQ)))
13281                                 break;
13282                         MPASS(VTOI(vp)->i_mode != 0);
13283                         error = ffs_update(vp, 1);
13284                         vput(vp);
13285                         if (error)
13286                                 break;
13287                         ACQUIRE_LOCK(ump);
13288                 }
13289                 /*
13290                  * If we have failed to get rid of all the dependencies
13291                  * then something is seriously wrong.
13292                  */
13293                 if (dap == LIST_FIRST(diraddhdp)) {
13294                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13295                         panic("flush_pagedep_deps: failed to flush " 
13296                             "inodedep %p ino %ju dap %p",
13297                             inodedep, (uintmax_t)inum, dap);
13298                 }
13299         }
13300         if (error)
13301                 ACQUIRE_LOCK(ump);
13302         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13303                 LIST_REMOVE(dap, da_pdlist);
13304                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13305         }
13306         return (error);
13307 }
13308
13309 /*
13310  * A large burst of file addition or deletion activity can drive the
13311  * memory load excessively high. First attempt to slow things down
13312  * using the techniques below. If that fails, this routine requests
13313  * the offending operations to fall back to running synchronously
13314  * until the memory load returns to a reasonable level.
13315  */
13316 int
13317 softdep_slowdown(vp)
13318         struct vnode *vp;
13319 {
13320         struct ufsmount *ump;
13321         int jlow;
13322         int max_softdeps_hard;
13323
13324         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13325             ("softdep_slowdown called on non-softdep filesystem"));
13326         ump = VFSTOUFS(vp->v_mount);
13327         ACQUIRE_LOCK(ump);
13328         jlow = 0;
13329         /*
13330          * Check for journal space if needed.
13331          */
13332         if (DOINGSUJ(vp)) {
13333                 if (journal_space(ump, 0) == 0)
13334                         jlow = 1;
13335         }
13336         /*
13337          * If the system is under its limits and our filesystem is
13338          * not responsible for more than our share of the usage and
13339          * we are not low on journal space, then no need to slow down.
13340          */
13341         max_softdeps_hard = max_softdeps * 11 / 10;
13342         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13343             dep_current[D_INODEDEP] < max_softdeps_hard &&
13344             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13345             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13346             ump->softdep_curdeps[D_DIRREM] <
13347             (max_softdeps_hard / 2) / stat_flush_threads &&
13348             ump->softdep_curdeps[D_INODEDEP] <
13349             max_softdeps_hard / stat_flush_threads &&
13350             ump->softdep_curdeps[D_INDIRDEP] <
13351             (max_softdeps_hard / 1000) / stat_flush_threads &&
13352             ump->softdep_curdeps[D_FREEBLKS] <
13353             max_softdeps_hard / stat_flush_threads) {
13354                 FREE_LOCK(ump);
13355                 return (0);
13356         }
13357         /*
13358          * If the journal is low or our filesystem is over its limit
13359          * then speedup the cleanup.
13360          */
13361         if (ump->softdep_curdeps[D_INDIRDEP] <
13362             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13363                 softdep_speedup(ump);
13364         stat_sync_limit_hit += 1;
13365         FREE_LOCK(ump);
13366         /*
13367          * We only slow down the rate at which new dependencies are
13368          * generated if we are not using journaling. With journaling,
13369          * the cleanup should always be sufficient to keep things
13370          * under control.
13371          */
13372         if (DOINGSUJ(vp))
13373                 return (0);
13374         return (1);
13375 }
13376
13377 /*
13378  * Called by the allocation routines when they are about to fail
13379  * in the hope that we can free up the requested resource (inodes
13380  * or disk space).
13381  * 
13382  * First check to see if the work list has anything on it. If it has,
13383  * clean up entries until we successfully free the requested resource.
13384  * Because this process holds inodes locked, we cannot handle any remove
13385  * requests that might block on a locked inode as that could lead to
13386  * deadlock. If the worklist yields none of the requested resource,
13387  * start syncing out vnodes to free up the needed space.
13388  */
13389 int
13390 softdep_request_cleanup(fs, vp, cred, resource)
13391         struct fs *fs;
13392         struct vnode *vp;
13393         struct ucred *cred;
13394         int resource;
13395 {
13396         struct ufsmount *ump;
13397         struct mount *mp;
13398         long starttime;
13399         ufs2_daddr_t needed;
13400         int error, failed_vnode;
13401
13402         /*
13403          * If we are being called because of a process doing a
13404          * copy-on-write, then it is not safe to process any
13405          * worklist items as we will recurse into the copyonwrite
13406          * routine.  This will result in an incoherent snapshot.
13407          * If the vnode that we hold is a snapshot, we must avoid
13408          * handling other resources that could cause deadlock.
13409          */
13410         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13411                 return (0);
13412
13413         if (resource == FLUSH_BLOCKS_WAIT)
13414                 stat_cleanup_blkrequests += 1;
13415         else
13416                 stat_cleanup_inorequests += 1;
13417
13418         mp = vp->v_mount;
13419         ump = VFSTOUFS(mp);
13420         mtx_assert(UFS_MTX(ump), MA_OWNED);
13421         UFS_UNLOCK(ump);
13422         error = ffs_update(vp, 1);
13423         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13424                 UFS_LOCK(ump);
13425                 return (0);
13426         }
13427         /*
13428          * If we are in need of resources, start by cleaning up
13429          * any block removals associated with our inode.
13430          */
13431         ACQUIRE_LOCK(ump);
13432         process_removes(vp);
13433         process_truncates(vp);
13434         FREE_LOCK(ump);
13435         /*
13436          * Now clean up at least as many resources as we will need.
13437          *
13438          * When requested to clean up inodes, the number that are needed
13439          * is set by the number of simultaneous writers (mnt_writeopcount)
13440          * plus a bit of slop (2) in case some more writers show up while
13441          * we are cleaning.
13442          *
13443          * When requested to free up space, the amount of space that
13444          * we need is enough blocks to allocate a full-sized segment
13445          * (fs_contigsumsize). The number of such segments that will
13446          * be needed is set by the number of simultaneous writers
13447          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13448          * writers show up while we are cleaning.
13449          *
13450          * Additionally, if we are unpriviledged and allocating space,
13451          * we need to ensure that we clean up enough blocks to get the
13452          * needed number of blocks over the threshold of the minimum
13453          * number of blocks required to be kept free by the filesystem
13454          * (fs_minfree).
13455          */
13456         if (resource == FLUSH_INODES_WAIT) {
13457                 needed = vfs_mount_fetch_counter(vp->v_mount,
13458                     MNT_COUNT_WRITEOPCOUNT) + 2;
13459         } else if (resource == FLUSH_BLOCKS_WAIT) {
13460                 needed = (vfs_mount_fetch_counter(vp->v_mount,
13461                     MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13462                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13463                         needed += fragstoblks(fs,
13464                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13465                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13466         } else {
13467                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13468                     resource);
13469                 UFS_LOCK(ump);
13470                 return (0);
13471         }
13472         starttime = time_second;
13473 retry:
13474         if (resource == FLUSH_BLOCKS_WAIT &&
13475             fs->fs_cstotal.cs_nbfree <= needed)
13476                 softdep_send_speedup(ump, needed * fs->fs_bsize,
13477                     BIO_SPEEDUP_TRIM);
13478         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13479             fs->fs_cstotal.cs_nbfree <= needed) ||
13480             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13481             fs->fs_cstotal.cs_nifree <= needed)) {
13482                 ACQUIRE_LOCK(ump);
13483                 if (ump->softdep_on_worklist > 0 &&
13484                     process_worklist_item(UFSTOVFS(ump),
13485                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13486                         stat_worklist_push += 1;
13487                 FREE_LOCK(ump);
13488         }
13489         /*
13490          * If we still need resources and there are no more worklist
13491          * entries to process to obtain them, we have to start flushing
13492          * the dirty vnodes to force the release of additional requests
13493          * to the worklist that we can then process to reap addition
13494          * resources. We walk the vnodes associated with the mount point
13495          * until we get the needed worklist requests that we can reap.
13496          *
13497          * If there are several threads all needing to clean the same
13498          * mount point, only one is allowed to walk the mount list.
13499          * When several threads all try to walk the same mount list,
13500          * they end up competing with each other and often end up in
13501          * livelock. This approach ensures that forward progress is
13502          * made at the cost of occational ENOSPC errors being returned
13503          * that might otherwise have been avoided.
13504          */
13505         error = 1;
13506         if ((resource == FLUSH_BLOCKS_WAIT && 
13507              fs->fs_cstotal.cs_nbfree <= needed) ||
13508             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13509              fs->fs_cstotal.cs_nifree <= needed)) {
13510                 ACQUIRE_LOCK(ump);
13511                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13512                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13513                         FREE_LOCK(ump);
13514                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13515                         ACQUIRE_LOCK(ump);
13516                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13517                         FREE_LOCK(ump);
13518                         if (ump->softdep_on_worklist > 0) {
13519                                 stat_cleanup_retries += 1;
13520                                 if (!failed_vnode)
13521                                         goto retry;
13522                         }
13523                 } else {
13524                         FREE_LOCK(ump);
13525                         error = 0;
13526                 }
13527                 stat_cleanup_failures += 1;
13528         }
13529         if (time_second - starttime > stat_cleanup_high_delay)
13530                 stat_cleanup_high_delay = time_second - starttime;
13531         UFS_LOCK(ump);
13532         return (error);
13533 }
13534
13535 /*
13536  * Scan the vnodes for the specified mount point flushing out any
13537  * vnodes that can be locked without waiting. Finally, try to flush
13538  * the device associated with the mount point if it can be locked
13539  * without waiting.
13540  *
13541  * We return 0 if we were able to lock every vnode in our scan.
13542  * If we had to skip one or more vnodes, we return 1.
13543  */
13544 static int
13545 softdep_request_cleanup_flush(mp, ump)
13546         struct mount *mp;
13547         struct ufsmount *ump;
13548 {
13549         struct thread *td;
13550         struct vnode *lvp, *mvp;
13551         int failed_vnode;
13552
13553         failed_vnode = 0;
13554         td = curthread;
13555         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13556                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13557                         VI_UNLOCK(lvp);
13558                         continue;
13559                 }
13560                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13561                     td) != 0) {
13562                         failed_vnode = 1;
13563                         continue;
13564                 }
13565                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13566                         vput(lvp);
13567                         continue;
13568                 }
13569                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13570                 vput(lvp);
13571         }
13572         lvp = ump->um_devvp;
13573         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13574                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13575                 VOP_UNLOCK(lvp);
13576         }
13577         return (failed_vnode);
13578 }
13579
13580 static bool
13581 softdep_excess_items(struct ufsmount *ump, int item)
13582 {
13583
13584         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13585         return (dep_current[item] > max_softdeps &&
13586             ump->softdep_curdeps[item] > max_softdeps /
13587             stat_flush_threads);
13588 }
13589
13590 static void
13591 schedule_cleanup(struct mount *mp)
13592 {
13593         struct ufsmount *ump;
13594         struct thread *td;
13595
13596         ump = VFSTOUFS(mp);
13597         LOCK_OWNED(ump);
13598         FREE_LOCK(ump);
13599         td = curthread;
13600         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13601             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13602                 /*
13603                  * No ast is delivered to kernel threads, so nobody
13604                  * would deref the mp.  Some kernel threads
13605                  * explicitely check for AST, e.g. NFS daemon does
13606                  * this in the serving loop.
13607                  */
13608                 return;
13609         }
13610         if (td->td_su != NULL)
13611                 vfs_rel(td->td_su);
13612         vfs_ref(mp);
13613         td->td_su = mp;
13614         thread_lock(td);
13615         td->td_flags |= TDF_ASTPENDING;
13616         thread_unlock(td);
13617 }
13618
13619 static void
13620 softdep_ast_cleanup_proc(struct thread *td)
13621 {
13622         struct mount *mp;
13623         struct ufsmount *ump;
13624         int error;
13625         bool req;
13626
13627         while ((mp = td->td_su) != NULL) {
13628                 td->td_su = NULL;
13629                 error = vfs_busy(mp, MBF_NOWAIT);
13630                 vfs_rel(mp);
13631                 if (error != 0)
13632                         return;
13633                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13634                         ump = VFSTOUFS(mp);
13635                         for (;;) {
13636                                 req = false;
13637                                 ACQUIRE_LOCK(ump);
13638                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13639                                         req = true;
13640                                         request_cleanup(mp, FLUSH_INODES);
13641                                 }
13642                                 if (softdep_excess_items(ump, D_DIRREM)) {
13643                                         req = true;
13644                                         request_cleanup(mp, FLUSH_BLOCKS);
13645                                 }
13646                                 FREE_LOCK(ump);
13647                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13648                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13649                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13650                                         error = vn_start_write(NULL, &mp,
13651                                             V_WAIT);
13652                                         if (error == 0) {
13653                                                 req = true;
13654                                                 VFS_SYNC(mp, MNT_WAIT);
13655                                                 vn_finished_write(mp);
13656                                         }
13657                                 }
13658                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13659                                         break;
13660                         }
13661                 }
13662                 vfs_unbusy(mp);
13663         }
13664         if ((mp = td->td_su) != NULL) {
13665                 td->td_su = NULL;
13666                 vfs_rel(mp);
13667         }
13668 }
13669
13670 /*
13671  * If memory utilization has gotten too high, deliberately slow things
13672  * down and speed up the I/O processing.
13673  */
13674 static int
13675 request_cleanup(mp, resource)
13676         struct mount *mp;
13677         int resource;
13678 {
13679         struct thread *td = curthread;
13680         struct ufsmount *ump;
13681
13682         ump = VFSTOUFS(mp);
13683         LOCK_OWNED(ump);
13684         /*
13685          * We never hold up the filesystem syncer or buf daemon.
13686          */
13687         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13688                 return (0);
13689         /*
13690          * First check to see if the work list has gotten backlogged.
13691          * If it has, co-opt this process to help clean up two entries.
13692          * Because this process may hold inodes locked, we cannot
13693          * handle any remove requests that might block on a locked
13694          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13695          * to avoid recursively processing the worklist.
13696          */
13697         if (ump->softdep_on_worklist > max_softdeps / 10) {
13698                 td->td_pflags |= TDP_SOFTDEP;
13699                 process_worklist_item(mp, 2, LK_NOWAIT);
13700                 td->td_pflags &= ~TDP_SOFTDEP;
13701                 stat_worklist_push += 2;
13702                 return(1);
13703         }
13704         /*
13705          * Next, we attempt to speed up the syncer process. If that
13706          * is successful, then we allow the process to continue.
13707          */
13708         if (softdep_speedup(ump) &&
13709             resource != FLUSH_BLOCKS_WAIT &&
13710             resource != FLUSH_INODES_WAIT)
13711                 return(0);
13712         /*
13713          * If we are resource constrained on inode dependencies, try
13714          * flushing some dirty inodes. Otherwise, we are constrained
13715          * by file deletions, so try accelerating flushes of directories
13716          * with removal dependencies. We would like to do the cleanup
13717          * here, but we probably hold an inode locked at this point and 
13718          * that might deadlock against one that we try to clean. So,
13719          * the best that we can do is request the syncer daemon to do
13720          * the cleanup for us.
13721          */
13722         switch (resource) {
13723
13724         case FLUSH_INODES:
13725         case FLUSH_INODES_WAIT:
13726                 ACQUIRE_GBLLOCK(&lk);
13727                 stat_ino_limit_push += 1;
13728                 req_clear_inodedeps += 1;
13729                 FREE_GBLLOCK(&lk);
13730                 stat_countp = &stat_ino_limit_hit;
13731                 break;
13732
13733         case FLUSH_BLOCKS:
13734         case FLUSH_BLOCKS_WAIT:
13735                 ACQUIRE_GBLLOCK(&lk);
13736                 stat_blk_limit_push += 1;
13737                 req_clear_remove += 1;
13738                 FREE_GBLLOCK(&lk);
13739                 stat_countp = &stat_blk_limit_hit;
13740                 break;
13741
13742         default:
13743                 panic("request_cleanup: unknown type");
13744         }
13745         /*
13746          * Hopefully the syncer daemon will catch up and awaken us.
13747          * We wait at most tickdelay before proceeding in any case.
13748          */
13749         ACQUIRE_GBLLOCK(&lk);
13750         FREE_LOCK(ump);
13751         proc_waiting += 1;
13752         if (callout_pending(&softdep_callout) == FALSE)
13753                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13754                     pause_timer, 0);
13755
13756         if ((td->td_pflags & TDP_KTHREAD) == 0)
13757                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13758         proc_waiting -= 1;
13759         FREE_GBLLOCK(&lk);
13760         ACQUIRE_LOCK(ump);
13761         return (1);
13762 }
13763
13764 /*
13765  * Awaken processes pausing in request_cleanup and clear proc_waiting
13766  * to indicate that there is no longer a timer running. Pause_timer
13767  * will be called with the global softdep mutex (&lk) locked.
13768  */
13769 static void
13770 pause_timer(arg)
13771         void *arg;
13772 {
13773
13774         GBLLOCK_OWNED(&lk);
13775         /*
13776          * The callout_ API has acquired mtx and will hold it around this
13777          * function call.
13778          */
13779         *stat_countp += proc_waiting;
13780         wakeup(&proc_waiting);
13781 }
13782
13783 /*
13784  * If requested, try removing inode or removal dependencies.
13785  */
13786 static void
13787 check_clear_deps(mp)
13788         struct mount *mp;
13789 {
13790         struct ufsmount *ump;
13791         bool suj_susp;
13792
13793         /*
13794          * Tell the lower layers that any TRIM or WRITE transactions that have
13795          * been delayed for performance reasons should proceed to help alleviate
13796          * the shortage faster. The race between checking req_* and the softdep
13797          * mutex (lk) is fine since this is an advisory operation that at most
13798          * causes deferred work to be done sooner.
13799          */
13800         ump = VFSTOUFS(mp);
13801         suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
13802         if (req_clear_remove || req_clear_inodedeps || suj_susp) {
13803                 FREE_LOCK(ump);
13804                 softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
13805                 ACQUIRE_LOCK(ump);
13806         }
13807
13808         /*
13809          * If we are suspended, it may be because of our using
13810          * too many inodedeps, so help clear them out.
13811          */
13812         if (suj_susp)
13813                 clear_inodedeps(mp);
13814
13815         /*
13816          * General requests for cleanup of backed up dependencies
13817          */
13818         ACQUIRE_GBLLOCK(&lk);
13819         if (req_clear_inodedeps) {
13820                 req_clear_inodedeps -= 1;
13821                 FREE_GBLLOCK(&lk);
13822                 clear_inodedeps(mp);
13823                 ACQUIRE_GBLLOCK(&lk);
13824                 wakeup(&proc_waiting);
13825         }
13826         if (req_clear_remove) {
13827                 req_clear_remove -= 1;
13828                 FREE_GBLLOCK(&lk);
13829                 clear_remove(mp);
13830                 ACQUIRE_GBLLOCK(&lk);
13831                 wakeup(&proc_waiting);
13832         }
13833         FREE_GBLLOCK(&lk);
13834 }
13835
13836 /*
13837  * Flush out a directory with at least one removal dependency in an effort to
13838  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13839  */
13840 static void
13841 clear_remove(mp)
13842         struct mount *mp;
13843 {
13844         struct pagedep_hashhead *pagedephd;
13845         struct pagedep *pagedep;
13846         struct ufsmount *ump;
13847         struct vnode *vp;
13848         struct bufobj *bo;
13849         int error, cnt;
13850         ino_t ino;
13851
13852         ump = VFSTOUFS(mp);
13853         LOCK_OWNED(ump);
13854
13855         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13856                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13857                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13858                         ump->pagedep_nextclean = 0;
13859                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13860                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13861                                 continue;
13862                         ino = pagedep->pd_ino;
13863                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13864                                 continue;
13865                         FREE_LOCK(ump);
13866
13867                         /*
13868                          * Let unmount clear deps
13869                          */
13870                         error = vfs_busy(mp, MBF_NOWAIT);
13871                         if (error != 0)
13872                                 goto finish_write;
13873                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13874                              FFSV_FORCEINSMQ);
13875                         vfs_unbusy(mp);
13876                         if (error != 0) {
13877                                 softdep_error("clear_remove: vget", error);
13878                                 goto finish_write;
13879                         }
13880                         MPASS(VTOI(vp)->i_mode != 0);
13881                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13882                                 softdep_error("clear_remove: fsync", error);
13883                         bo = &vp->v_bufobj;
13884                         BO_LOCK(bo);
13885                         drain_output(vp);
13886                         BO_UNLOCK(bo);
13887                         vput(vp);
13888                 finish_write:
13889                         vn_finished_write(mp);
13890                         ACQUIRE_LOCK(ump);
13891                         return;
13892                 }
13893         }
13894 }
13895
13896 /*
13897  * Clear out a block of dirty inodes in an effort to reduce
13898  * the number of inodedep dependency structures.
13899  */
13900 static void
13901 clear_inodedeps(mp)
13902         struct mount *mp;
13903 {
13904         struct inodedep_hashhead *inodedephd;
13905         struct inodedep *inodedep;
13906         struct ufsmount *ump;
13907         struct vnode *vp;
13908         struct fs *fs;
13909         int error, cnt;
13910         ino_t firstino, lastino, ino;
13911
13912         ump = VFSTOUFS(mp);
13913         fs = ump->um_fs;
13914         LOCK_OWNED(ump);
13915         /*
13916          * Pick a random inode dependency to be cleared.
13917          * We will then gather up all the inodes in its block 
13918          * that have dependencies and flush them out.
13919          */
13920         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13921                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13922                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13923                         ump->inodedep_nextclean = 0;
13924                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13925                         break;
13926         }
13927         if (inodedep == NULL)
13928                 return;
13929         /*
13930          * Find the last inode in the block with dependencies.
13931          */
13932         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13933         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13934                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13935                         break;
13936         /*
13937          * Asynchronously push all but the last inode with dependencies.
13938          * Synchronously push the last inode with dependencies to ensure
13939          * that the inode block gets written to free up the inodedeps.
13940          */
13941         for (ino = firstino; ino <= lastino; ino++) {
13942                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13943                         continue;
13944                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13945                         continue;
13946                 FREE_LOCK(ump);
13947                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13948                 if (error != 0) {
13949                         vn_finished_write(mp);
13950                         ACQUIRE_LOCK(ump);
13951                         return;
13952                 }
13953                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13954                     FFSV_FORCEINSMQ)) != 0) {
13955                         softdep_error("clear_inodedeps: vget", error);
13956                         vfs_unbusy(mp);
13957                         vn_finished_write(mp);
13958                         ACQUIRE_LOCK(ump);
13959                         return;
13960                 }
13961                 vfs_unbusy(mp);
13962                 if (VTOI(vp)->i_mode == 0) {
13963                         vgone(vp);
13964                 } else if (ino == lastino) {
13965                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13966                                 softdep_error("clear_inodedeps: fsync1", error);
13967                 } else {
13968                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13969                                 softdep_error("clear_inodedeps: fsync2", error);
13970                         BO_LOCK(&vp->v_bufobj);
13971                         drain_output(vp);
13972                         BO_UNLOCK(&vp->v_bufobj);
13973                 }
13974                 vput(vp);
13975                 vn_finished_write(mp);
13976                 ACQUIRE_LOCK(ump);
13977         }
13978 }
13979
13980 void
13981 softdep_buf_append(bp, wkhd)
13982         struct buf *bp;
13983         struct workhead *wkhd;
13984 {
13985         struct worklist *wk;
13986         struct ufsmount *ump;
13987
13988         if ((wk = LIST_FIRST(wkhd)) == NULL)
13989                 return;
13990         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13991             ("softdep_buf_append called on non-softdep filesystem"));
13992         ump = VFSTOUFS(wk->wk_mp);
13993         ACQUIRE_LOCK(ump);
13994         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13995                 WORKLIST_REMOVE(wk);
13996                 WORKLIST_INSERT(&bp->b_dep, wk);
13997         }
13998         FREE_LOCK(ump);
13999
14000 }
14001
14002 void
14003 softdep_inode_append(ip, cred, wkhd)
14004         struct inode *ip;
14005         struct ucred *cred;
14006         struct workhead *wkhd;
14007 {
14008         struct buf *bp;
14009         struct fs *fs;
14010         struct ufsmount *ump;
14011         int error;
14012
14013         ump = ITOUMP(ip);
14014         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14015             ("softdep_inode_append called on non-softdep filesystem"));
14016         fs = ump->um_fs;
14017         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14018             (int)fs->fs_bsize, cred, &bp);
14019         if (error) {
14020                 bqrelse(bp);
14021                 softdep_freework(wkhd);
14022                 return;
14023         }
14024         softdep_buf_append(bp, wkhd);
14025         bqrelse(bp);
14026 }
14027
14028 void
14029 softdep_freework(wkhd)
14030         struct workhead *wkhd;
14031 {
14032         struct worklist *wk;
14033         struct ufsmount *ump;
14034
14035         if ((wk = LIST_FIRST(wkhd)) == NULL)
14036                 return;
14037         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14038             ("softdep_freework called on non-softdep filesystem"));
14039         ump = VFSTOUFS(wk->wk_mp);
14040         ACQUIRE_LOCK(ump);
14041         handle_jwork(wkhd);
14042         FREE_LOCK(ump);
14043 }
14044
14045 static struct ufsmount *
14046 softdep_bp_to_mp(bp)
14047         struct buf *bp;
14048 {
14049         struct mount *mp;
14050         struct vnode *vp;
14051
14052         if (LIST_EMPTY(&bp->b_dep))
14053                 return (NULL);
14054         vp = bp->b_vp;
14055         KASSERT(vp != NULL,
14056             ("%s, buffer with dependencies lacks vnode", __func__));
14057
14058         /*
14059          * The ump mount point is stable after we get a correct
14060          * pointer, since bp is locked and this prevents unmount from
14061          * proceeding.  But to get to it, we cannot dereference bp->b_dep
14062          * head wk_mp, because we do not yet own SU ump lock and
14063          * workitem might be freed while dereferenced.
14064          */
14065 retry:
14066         switch (vp->v_type) {
14067         case VCHR:
14068                 VI_LOCK(vp);
14069                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14070                 VI_UNLOCK(vp);
14071                 if (mp == NULL)
14072                         goto retry;
14073                 break;
14074         case VREG:
14075         case VDIR:
14076         case VLNK:
14077         case VFIFO:
14078         case VSOCK:
14079                 mp = vp->v_mount;
14080                 break;
14081         case VBLK:
14082                 vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14083                 /* FALLTHROUGH */
14084         case VNON:
14085         case VBAD:
14086         case VMARKER:
14087                 mp = NULL;
14088                 break;
14089         default:
14090                 vn_printf(vp, "unknown vnode type");
14091                 mp = NULL;
14092                 break;
14093         }
14094         return (VFSTOUFS(mp));
14095 }
14096
14097 /*
14098  * Function to determine if the buffer has outstanding dependencies
14099  * that will cause a roll-back if the buffer is written. If wantcount
14100  * is set, return number of dependencies, otherwise just yes or no.
14101  */
14102 static int
14103 softdep_count_dependencies(bp, wantcount)
14104         struct buf *bp;
14105         int wantcount;
14106 {
14107         struct worklist *wk;
14108         struct ufsmount *ump;
14109         struct bmsafemap *bmsafemap;
14110         struct freework *freework;
14111         struct inodedep *inodedep;
14112         struct indirdep *indirdep;
14113         struct freeblks *freeblks;
14114         struct allocindir *aip;
14115         struct pagedep *pagedep;
14116         struct dirrem *dirrem;
14117         struct newblk *newblk;
14118         struct mkdir *mkdir;
14119         struct diradd *dap;
14120         int i, retval;
14121
14122         ump = softdep_bp_to_mp(bp);
14123         if (ump == NULL)
14124                 return (0);
14125         retval = 0;
14126         ACQUIRE_LOCK(ump);
14127         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14128                 switch (wk->wk_type) {
14129
14130                 case D_INODEDEP:
14131                         inodedep = WK_INODEDEP(wk);
14132                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14133                                 /* bitmap allocation dependency */
14134                                 retval += 1;
14135                                 if (!wantcount)
14136                                         goto out;
14137                         }
14138                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14139                                 /* direct block pointer dependency */
14140                                 retval += 1;
14141                                 if (!wantcount)
14142                                         goto out;
14143                         }
14144                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14145                                 /* direct block pointer dependency */
14146                                 retval += 1;
14147                                 if (!wantcount)
14148                                         goto out;
14149                         }
14150                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14151                                 /* Add reference dependency. */
14152                                 retval += 1;
14153                                 if (!wantcount)
14154                                         goto out;
14155                         }
14156                         continue;
14157
14158                 case D_INDIRDEP:
14159                         indirdep = WK_INDIRDEP(wk);
14160
14161                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14162                                 /* indirect truncation dependency */
14163                                 retval += 1;
14164                                 if (!wantcount)
14165                                         goto out;
14166                         }
14167
14168                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14169                                 /* indirect block pointer dependency */
14170                                 retval += 1;
14171                                 if (!wantcount)
14172                                         goto out;
14173                         }
14174                         continue;
14175
14176                 case D_PAGEDEP:
14177                         pagedep = WK_PAGEDEP(wk);
14178                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14179                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14180                                         /* Journal remove ref dependency. */
14181                                         retval += 1;
14182                                         if (!wantcount)
14183                                                 goto out;
14184                                 }
14185                         }
14186                         for (i = 0; i < DAHASHSZ; i++) {
14187
14188                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14189                                         /* directory entry dependency */
14190                                         retval += 1;
14191                                         if (!wantcount)
14192                                                 goto out;
14193                                 }
14194                         }
14195                         continue;
14196
14197                 case D_BMSAFEMAP:
14198                         bmsafemap = WK_BMSAFEMAP(wk);
14199                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14200                                 /* Add reference dependency. */
14201                                 retval += 1;
14202                                 if (!wantcount)
14203                                         goto out;
14204                         }
14205                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14206                                 /* Allocate block dependency. */
14207                                 retval += 1;
14208                                 if (!wantcount)
14209                                         goto out;
14210                         }
14211                         continue;
14212
14213                 case D_FREEBLKS:
14214                         freeblks = WK_FREEBLKS(wk);
14215                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14216                                 /* Freeblk journal dependency. */
14217                                 retval += 1;
14218                                 if (!wantcount)
14219                                         goto out;
14220                         }
14221                         continue;
14222
14223                 case D_ALLOCDIRECT:
14224                 case D_ALLOCINDIR:
14225                         newblk = WK_NEWBLK(wk);
14226                         if (newblk->nb_jnewblk) {
14227                                 /* Journal allocate dependency. */
14228                                 retval += 1;
14229                                 if (!wantcount)
14230                                         goto out;
14231                         }
14232                         continue;
14233
14234                 case D_MKDIR:
14235                         mkdir = WK_MKDIR(wk);
14236                         if (mkdir->md_jaddref) {
14237                                 /* Journal reference dependency. */
14238                                 retval += 1;
14239                                 if (!wantcount)
14240                                         goto out;
14241                         }
14242                         continue;
14243
14244                 case D_FREEWORK:
14245                 case D_FREEDEP:
14246                 case D_JSEGDEP:
14247                 case D_JSEG:
14248                 case D_SBDEP:
14249                         /* never a dependency on these blocks */
14250                         continue;
14251
14252                 default:
14253                         panic("softdep_count_dependencies: Unexpected type %s",
14254                             TYPENAME(wk->wk_type));
14255                         /* NOTREACHED */
14256                 }
14257         }
14258 out:
14259         FREE_LOCK(ump);
14260         return (retval);
14261 }
14262
14263 /*
14264  * Acquire exclusive access to a buffer.
14265  * Must be called with a locked mtx parameter.
14266  * Return acquired buffer or NULL on failure.
14267  */
14268 static struct buf *
14269 getdirtybuf(bp, lock, waitfor)
14270         struct buf *bp;
14271         struct rwlock *lock;
14272         int waitfor;
14273 {
14274         int error;
14275
14276         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14277                 if (waitfor != MNT_WAIT)
14278                         return (NULL);
14279                 error = BUF_LOCK(bp,
14280                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14281                 /*
14282                  * Even if we successfully acquire bp here, we have dropped
14283                  * lock, which may violates our guarantee.
14284                  */
14285                 if (error == 0)
14286                         BUF_UNLOCK(bp);
14287                 else if (error != ENOLCK)
14288                         panic("getdirtybuf: inconsistent lock: %d", error);
14289                 rw_wlock(lock);
14290                 return (NULL);
14291         }
14292         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14293                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14294                         rw_wunlock(lock);
14295                         BO_LOCK(bp->b_bufobj);
14296                         BUF_UNLOCK(bp);
14297                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14298                                 bp->b_vflags |= BV_BKGRDWAIT;
14299                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14300                                        PRIBIO | PDROP, "getbuf", 0);
14301                         } else
14302                                 BO_UNLOCK(bp->b_bufobj);
14303                         rw_wlock(lock);
14304                         return (NULL);
14305                 }
14306                 BUF_UNLOCK(bp);
14307                 if (waitfor != MNT_WAIT)
14308                         return (NULL);
14309 #ifdef DEBUG_VFS_LOCKS
14310                 if (bp->b_vp->v_type != VCHR)
14311                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14312 #endif
14313                 bp->b_vflags |= BV_BKGRDWAIT;
14314                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14315                 return (NULL);
14316         }
14317         if ((bp->b_flags & B_DELWRI) == 0) {
14318                 BUF_UNLOCK(bp);
14319                 return (NULL);
14320         }
14321         bremfree(bp);
14322         return (bp);
14323 }
14324
14325
14326 /*
14327  * Check if it is safe to suspend the file system now.  On entry,
14328  * the vnode interlock for devvp should be held.  Return 0 with
14329  * the mount interlock held if the file system can be suspended now,
14330  * otherwise return EAGAIN with the mount interlock held.
14331  */
14332 int
14333 softdep_check_suspend(struct mount *mp,
14334                       struct vnode *devvp,
14335                       int softdep_depcnt,
14336                       int softdep_accdepcnt,
14337                       int secondary_writes,
14338                       int secondary_accwrites)
14339 {
14340         struct bufobj *bo;
14341         struct ufsmount *ump;
14342         struct inodedep *inodedep;
14343         int error, unlinked;
14344
14345         bo = &devvp->v_bufobj;
14346         ASSERT_BO_WLOCKED(bo);
14347
14348         /*
14349          * If we are not running with soft updates, then we need only
14350          * deal with secondary writes as we try to suspend.
14351          */
14352         if (MOUNTEDSOFTDEP(mp) == 0) {
14353                 MNT_ILOCK(mp);
14354                 while (mp->mnt_secondary_writes != 0) {
14355                         BO_UNLOCK(bo);
14356                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14357                             (PUSER - 1) | PDROP, "secwr", 0);
14358                         BO_LOCK(bo);
14359                         MNT_ILOCK(mp);
14360                 }
14361
14362                 /*
14363                  * Reasons for needing more work before suspend:
14364                  * - Dirty buffers on devvp.
14365                  * - Secondary writes occurred after start of vnode sync loop
14366                  */
14367                 error = 0;
14368                 if (bo->bo_numoutput > 0 ||
14369                     bo->bo_dirty.bv_cnt > 0 ||
14370                     secondary_writes != 0 ||
14371                     mp->mnt_secondary_writes != 0 ||
14372                     secondary_accwrites != mp->mnt_secondary_accwrites)
14373                         error = EAGAIN;
14374                 BO_UNLOCK(bo);
14375                 return (error);
14376         }
14377
14378         /*
14379          * If we are running with soft updates, then we need to coordinate
14380          * with them as we try to suspend.
14381          */
14382         ump = VFSTOUFS(mp);
14383         for (;;) {
14384                 if (!TRY_ACQUIRE_LOCK(ump)) {
14385                         BO_UNLOCK(bo);
14386                         ACQUIRE_LOCK(ump);
14387                         FREE_LOCK(ump);
14388                         BO_LOCK(bo);
14389                         continue;
14390                 }
14391                 MNT_ILOCK(mp);
14392                 if (mp->mnt_secondary_writes != 0) {
14393                         FREE_LOCK(ump);
14394                         BO_UNLOCK(bo);
14395                         msleep(&mp->mnt_secondary_writes,
14396                                MNT_MTX(mp),
14397                                (PUSER - 1) | PDROP, "secwr", 0);
14398                         BO_LOCK(bo);
14399                         continue;
14400                 }
14401                 break;
14402         }
14403
14404         unlinked = 0;
14405         if (MOUNTEDSUJ(mp)) {
14406                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14407                     inodedep != NULL;
14408                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14409                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14410                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14411                             UNLINKONLIST) ||
14412                             !check_inodedep_free(inodedep))
14413                                 continue;
14414                         unlinked++;
14415                 }
14416         }
14417
14418         /*
14419          * Reasons for needing more work before suspend:
14420          * - Dirty buffers on devvp.
14421          * - Softdep activity occurred after start of vnode sync loop
14422          * - Secondary writes occurred after start of vnode sync loop
14423          */
14424         error = 0;
14425         if (bo->bo_numoutput > 0 ||
14426             bo->bo_dirty.bv_cnt > 0 ||
14427             softdep_depcnt != unlinked ||
14428             ump->softdep_deps != unlinked ||
14429             softdep_accdepcnt != ump->softdep_accdeps ||
14430             secondary_writes != 0 ||
14431             mp->mnt_secondary_writes != 0 ||
14432             secondary_accwrites != mp->mnt_secondary_accwrites)
14433                 error = EAGAIN;
14434         FREE_LOCK(ump);
14435         BO_UNLOCK(bo);
14436         return (error);
14437 }
14438
14439
14440 /*
14441  * Get the number of dependency structures for the file system, both
14442  * the current number and the total number allocated.  These will
14443  * later be used to detect that softdep processing has occurred.
14444  */
14445 void
14446 softdep_get_depcounts(struct mount *mp,
14447                       int *softdep_depsp,
14448                       int *softdep_accdepsp)
14449 {
14450         struct ufsmount *ump;
14451
14452         if (MOUNTEDSOFTDEP(mp) == 0) {
14453                 *softdep_depsp = 0;
14454                 *softdep_accdepsp = 0;
14455                 return;
14456         }
14457         ump = VFSTOUFS(mp);
14458         ACQUIRE_LOCK(ump);
14459         *softdep_depsp = ump->softdep_deps;
14460         *softdep_accdepsp = ump->softdep_accdeps;
14461         FREE_LOCK(ump);
14462 }
14463
14464 /*
14465  * Wait for pending output on a vnode to complete.
14466  */
14467 static void
14468 drain_output(vp)
14469         struct vnode *vp;
14470 {
14471
14472         ASSERT_VOP_LOCKED(vp, "drain_output");
14473         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14474 }
14475
14476 /*
14477  * Called whenever a buffer that is being invalidated or reallocated
14478  * contains dependencies. This should only happen if an I/O error has
14479  * occurred. The routine is called with the buffer locked.
14480  */ 
14481 static void
14482 softdep_deallocate_dependencies(bp)
14483         struct buf *bp;
14484 {
14485
14486         if ((bp->b_ioflags & BIO_ERROR) == 0)
14487                 panic("softdep_deallocate_dependencies: dangling deps");
14488         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14489                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14490         else
14491                 printf("softdep_deallocate_dependencies: "
14492                     "got error %d while accessing filesystem\n", bp->b_error);
14493         if (bp->b_error != ENXIO)
14494                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14495 }
14496
14497 /*
14498  * Function to handle asynchronous write errors in the filesystem.
14499  */
14500 static void
14501 softdep_error(func, error)
14502         char *func;
14503         int error;
14504 {
14505
14506         /* XXX should do something better! */
14507         printf("%s: got error %d while accessing filesystem\n", func, error);
14508 }
14509
14510 #ifdef DDB
14511
14512 /* exported to ffs_vfsops.c */
14513 extern void db_print_ffs(struct ufsmount *ump);
14514 void
14515 db_print_ffs(struct ufsmount *ump)
14516 {
14517         db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14518             ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14519         db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14520             ump->um_fs, ump->softdep_on_worklist,
14521             ump->softdep_deps, ump->softdep_req);
14522 }
14523
14524 static void
14525 worklist_print(struct worklist *wk, int verbose)
14526 {
14527
14528         if (!verbose) {
14529                 db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14530                     (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14531                 return;
14532         }
14533         db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14534             TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14535             LIST_NEXT(wk, wk_list));
14536         db_print_ffs(VFSTOUFS(wk->wk_mp));
14537 }
14538
14539 static void
14540 inodedep_print(struct inodedep *inodedep, int verbose)
14541 {
14542
14543         worklist_print(&inodedep->id_list, 0);
14544         db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14545             inodedep->id_fs,
14546             (intmax_t)inodedep->id_ino,
14547             (intmax_t)fsbtodb(inodedep->id_fs,
14548                 ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14549             (intmax_t)inodedep->id_nlinkdelta,
14550             (intmax_t)inodedep->id_savednlink);
14551
14552         if (verbose == 0)
14553                 return;
14554
14555         db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14556             inodedep->id_bmsafemap,
14557             inodedep->id_mkdiradd,
14558             TAILQ_FIRST(&inodedep->id_inoreflst));
14559         db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14560             LIST_FIRST(&inodedep->id_dirremhd),
14561             LIST_FIRST(&inodedep->id_pendinghd),
14562             LIST_FIRST(&inodedep->id_bufwait));
14563         db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14564             LIST_FIRST(&inodedep->id_inowait),
14565             TAILQ_FIRST(&inodedep->id_inoupdt),
14566             TAILQ_FIRST(&inodedep->id_newinoupdt));
14567         db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14568             TAILQ_FIRST(&inodedep->id_extupdt),
14569             TAILQ_FIRST(&inodedep->id_newextupdt),
14570             TAILQ_FIRST(&inodedep->id_freeblklst));
14571         db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14572             inodedep->id_savedino1,
14573             (intmax_t)inodedep->id_savedsize,
14574             (intmax_t)inodedep->id_savedextsize);
14575 }
14576
14577 static void
14578 newblk_print(struct newblk *nbp)
14579 {
14580
14581         worklist_print(&nbp->nb_list, 0);
14582         db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14583         db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14584             &nbp->nb_jnewblk,
14585             &nbp->nb_bmsafemap,
14586             &nbp->nb_freefrag);
14587         db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14588             LIST_FIRST(&nbp->nb_indirdeps),
14589             LIST_FIRST(&nbp->nb_newdirblk),
14590             LIST_FIRST(&nbp->nb_jwork));
14591 }
14592
14593 static void
14594 allocdirect_print(struct allocdirect *adp)
14595 {
14596
14597         newblk_print(&adp->ad_block);
14598         db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14599             adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14600         db_printf("    offset %d, inodedep %p\n",
14601             adp->ad_offset, adp->ad_inodedep);
14602 }
14603
14604 static void
14605 allocindir_print(struct allocindir *aip)
14606 {
14607
14608         newblk_print(&aip->ai_block);
14609         db_printf("    oldblkno %jd, lbn %jd\n",
14610             (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14611         db_printf("    offset %d, indirdep %p\n",
14612             aip->ai_offset, aip->ai_indirdep);
14613 }
14614
14615 static void
14616 mkdir_print(struct mkdir *mkdir)
14617 {
14618
14619         worklist_print(&mkdir->md_list, 0);
14620         db_printf("    diradd %p, jaddref %p, buf %p\n",
14621                 mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14622 }
14623
14624 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14625 {
14626
14627         if (have_addr == 0) {
14628                 db_printf("inodedep address required\n");
14629                 return;
14630         }
14631         inodedep_print((struct inodedep*)addr, 1);
14632 }
14633
14634 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14635 {
14636         struct inodedep_hashhead *inodedephd;
14637         struct inodedep *inodedep;
14638         struct ufsmount *ump;
14639         int cnt;
14640
14641         if (have_addr == 0) {
14642                 db_printf("ufsmount address required\n");
14643                 return;
14644         }
14645         ump = (struct ufsmount *)addr;
14646         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14647                 inodedephd = &ump->inodedep_hashtbl[cnt];
14648                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14649                         inodedep_print(inodedep, 0);
14650                 }
14651         }
14652 }
14653
14654 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14655 {
14656
14657         if (have_addr == 0) {
14658                 db_printf("worklist address required\n");
14659                 return;
14660         }
14661         worklist_print((struct worklist *)addr, 1);
14662 }
14663
14664 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14665 {
14666         struct worklist *wk;
14667         struct workhead *wkhd;
14668
14669         if (have_addr == 0) {
14670                 db_printf("worklist address required "
14671                     "(for example value in bp->b_dep)\n");
14672                 return;
14673         }
14674         /*
14675          * We often do not have the address of the worklist head but
14676          * instead a pointer to its first entry (e.g., we have the
14677          * contents of bp->b_dep rather than &bp->b_dep). But the back
14678          * pointer of bp->b_dep will point at the head of the list, so
14679          * we cheat and use that instead. If we are in the middle of
14680          * a list we will still get the same result, so nothing
14681          * unexpected will result.
14682          */
14683         wk = (struct worklist *)addr;
14684         if (wk == NULL)
14685                 return;
14686         wkhd = (struct workhead *)wk->wk_list.le_prev;
14687         LIST_FOREACH(wk, wkhd, wk_list) {
14688                 switch(wk->wk_type) {
14689                 case D_INODEDEP:
14690                         inodedep_print(WK_INODEDEP(wk), 0);
14691                         continue;
14692                 case D_ALLOCDIRECT:
14693                         allocdirect_print(WK_ALLOCDIRECT(wk));
14694                         continue;
14695                 case D_ALLOCINDIR:
14696                         allocindir_print(WK_ALLOCINDIR(wk));
14697                         continue;
14698                 case D_MKDIR:
14699                         mkdir_print(WK_MKDIR(wk));
14700                         continue;
14701                 default:
14702                         worklist_print(wk, 0);
14703                         continue;
14704                 }
14705         }
14706 }
14707
14708 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14709 {
14710         if (have_addr == 0) {
14711                 db_printf("mkdir address required\n");
14712                 return;
14713         }
14714         mkdir_print((struct mkdir *)addr);
14715 }
14716
14717 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14718 {
14719         struct mkdirlist *mkdirlisthd;
14720         struct mkdir *mkdir;
14721
14722         if (have_addr == 0) {
14723                 db_printf("mkdir listhead address required\n");
14724                 return;
14725         }
14726         mkdirlisthd = (struct mkdirlist *)addr;
14727         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14728                 mkdir_print(mkdir);
14729                 if (mkdir->md_diradd != NULL) {
14730                         db_printf("    ");
14731                         worklist_print(&mkdir->md_diradd->da_list, 0);
14732                 }
14733                 if (mkdir->md_jaddref != NULL) {
14734                         db_printf("    ");
14735                         worklist_print(&mkdir->md_jaddref->ja_list, 0);
14736                 }
14737         }
14738 }
14739
14740 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14741 {
14742         if (have_addr == 0) {
14743                 db_printf("allocdirect address required\n");
14744                 return;
14745         }
14746         allocdirect_print((struct allocdirect *)addr);
14747 }
14748
14749 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14750 {
14751         if (have_addr == 0) {
14752                 db_printf("allocindir address required\n");
14753                 return;
14754         }
14755         allocindir_print((struct allocindir *)addr);
14756 }
14757
14758 #endif /* DDB */
14759
14760 #endif /* SOFTUPDATES */