]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
Don't defer wakeup()s for completed journal workitems.
[FreeBSD/FreeBSD.git] / sys / ufs / ffs / ffs_softdep.c
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *      Marshall Kirk McKusick          http://www.mckusick.com/softdep/
14  *      1614 Oxford Street              mckusick@mckusick.com
15  *      Berkeley, CA 94709-1608         +1-510-843-9542
16  *      USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *      from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
40  */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/racct.h>
73 #include <sys/rwlock.h>
74 #include <sys/stat.h>
75 #include <sys/sysctl.h>
76 #include <sys/syslog.h>
77 #include <sys/vnode.h>
78 #include <sys/conf.h>
79
80 #include <ufs/ufs/dir.h>
81 #include <ufs/ufs/extattr.h>
82 #include <ufs/ufs/quota.h>
83 #include <ufs/ufs/inode.h>
84 #include <ufs/ufs/ufsmount.h>
85 #include <ufs/ffs/fs.h>
86 #include <ufs/ffs/softdep.h>
87 #include <ufs/ffs/ffs_extern.h>
88 #include <ufs/ufs/ufs_extern.h>
89
90 #include <vm/vm.h>
91 #include <vm/vm_extern.h>
92 #include <vm/vm_object.h>
93
94 #include <geom/geom.h>
95
96 #include <ddb/ddb.h>
97
98 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
99
100 #ifndef SOFTUPDATES
101
102 int
103 softdep_flushfiles(oldmnt, flags, td)
104         struct mount *oldmnt;
105         int flags;
106         struct thread *td;
107 {
108
109         panic("softdep_flushfiles called");
110 }
111
112 int
113 softdep_mount(devvp, mp, fs, cred)
114         struct vnode *devvp;
115         struct mount *mp;
116         struct fs *fs;
117         struct ucred *cred;
118 {
119
120         return (0);
121 }
122
123 void
124 softdep_initialize()
125 {
126
127         return;
128 }
129
130 void
131 softdep_uninitialize()
132 {
133
134         return;
135 }
136
137 void
138 softdep_unmount(mp)
139         struct mount *mp;
140 {
141
142         panic("softdep_unmount called");
143 }
144
145 void
146 softdep_setup_sbupdate(ump, fs, bp)
147         struct ufsmount *ump;
148         struct fs *fs;
149         struct buf *bp;
150 {
151
152         panic("softdep_setup_sbupdate called");
153 }
154
155 void
156 softdep_setup_inomapdep(bp, ip, newinum, mode)
157         struct buf *bp;
158         struct inode *ip;
159         ino_t newinum;
160         int mode;
161 {
162
163         panic("softdep_setup_inomapdep called");
164 }
165
166 void
167 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
168         struct buf *bp;
169         struct mount *mp;
170         ufs2_daddr_t newblkno;
171         int frags;
172         int oldfrags;
173 {
174
175         panic("softdep_setup_blkmapdep called");
176 }
177
178 void
179 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
180         struct inode *ip;
181         ufs_lbn_t lbn;
182         ufs2_daddr_t newblkno;
183         ufs2_daddr_t oldblkno;
184         long newsize;
185         long oldsize;
186         struct buf *bp;
187 {
188         
189         panic("softdep_setup_allocdirect called");
190 }
191
192 void
193 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
194         struct inode *ip;
195         ufs_lbn_t lbn;
196         ufs2_daddr_t newblkno;
197         ufs2_daddr_t oldblkno;
198         long newsize;
199         long oldsize;
200         struct buf *bp;
201 {
202         
203         panic("softdep_setup_allocext called");
204 }
205
206 void
207 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
208         struct inode *ip;
209         ufs_lbn_t lbn;
210         struct buf *bp;
211         int ptrno;
212         ufs2_daddr_t newblkno;
213         ufs2_daddr_t oldblkno;
214         struct buf *nbp;
215 {
216
217         panic("softdep_setup_allocindir_page called");
218 }
219
220 void
221 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
222         struct buf *nbp;
223         struct inode *ip;
224         struct buf *bp;
225         int ptrno;
226         ufs2_daddr_t newblkno;
227 {
228
229         panic("softdep_setup_allocindir_meta called");
230 }
231
232 void
233 softdep_journal_freeblocks(ip, cred, length, flags)
234         struct inode *ip;
235         struct ucred *cred;
236         off_t length;
237         int flags;
238 {
239         
240         panic("softdep_journal_freeblocks called");
241 }
242
243 void
244 softdep_journal_fsync(ip)
245         struct inode *ip;
246 {
247
248         panic("softdep_journal_fsync called");
249 }
250
251 void
252 softdep_setup_freeblocks(ip, length, flags)
253         struct inode *ip;
254         off_t length;
255         int flags;
256 {
257         
258         panic("softdep_setup_freeblocks called");
259 }
260
261 void
262 softdep_freefile(pvp, ino, mode)
263                 struct vnode *pvp;
264                 ino_t ino;
265                 int mode;
266 {
267
268         panic("softdep_freefile called");
269 }
270
271 int
272 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
273         struct buf *bp;
274         struct inode *dp;
275         off_t diroffset;
276         ino_t newinum;
277         struct buf *newdirbp;
278         int isnewblk;
279 {
280
281         panic("softdep_setup_directory_add called");
282 }
283
284 void
285 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
286         struct buf *bp;
287         struct inode *dp;
288         caddr_t base;
289         caddr_t oldloc;
290         caddr_t newloc;
291         int entrysize;
292 {
293
294         panic("softdep_change_directoryentry_offset called");
295 }
296
297 void
298 softdep_setup_remove(bp, dp, ip, isrmdir)
299         struct buf *bp;
300         struct inode *dp;
301         struct inode *ip;
302         int isrmdir;
303 {
304         
305         panic("softdep_setup_remove called");
306 }
307
308 void
309 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
310         struct buf *bp;
311         struct inode *dp;
312         struct inode *ip;
313         ino_t newinum;
314         int isrmdir;
315 {
316
317         panic("softdep_setup_directory_change called");
318 }
319
320 void
321 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
322         struct mount *mp;
323         struct buf *bp;
324         ufs2_daddr_t blkno;
325         int frags;
326         struct workhead *wkhd;
327 {
328
329         panic("%s called", __FUNCTION__);
330 }
331
332 void
333 softdep_setup_inofree(mp, bp, ino, wkhd)
334         struct mount *mp;
335         struct buf *bp;
336         ino_t ino;
337         struct workhead *wkhd;
338 {
339
340         panic("%s called", __FUNCTION__);
341 }
342
343 void
344 softdep_setup_unlink(dp, ip)
345         struct inode *dp;
346         struct inode *ip;
347 {
348
349         panic("%s called", __FUNCTION__);
350 }
351
352 void
353 softdep_setup_link(dp, ip)
354         struct inode *dp;
355         struct inode *ip;
356 {
357
358         panic("%s called", __FUNCTION__);
359 }
360
361 void
362 softdep_revert_link(dp, ip)
363         struct inode *dp;
364         struct inode *ip;
365 {
366
367         panic("%s called", __FUNCTION__);
368 }
369
370 void
371 softdep_setup_rmdir(dp, ip)
372         struct inode *dp;
373         struct inode *ip;
374 {
375
376         panic("%s called", __FUNCTION__);
377 }
378
379 void
380 softdep_revert_rmdir(dp, ip)
381         struct inode *dp;
382         struct inode *ip;
383 {
384
385         panic("%s called", __FUNCTION__);
386 }
387
388 void
389 softdep_setup_create(dp, ip)
390         struct inode *dp;
391         struct inode *ip;
392 {
393
394         panic("%s called", __FUNCTION__);
395 }
396
397 void
398 softdep_revert_create(dp, ip)
399         struct inode *dp;
400         struct inode *ip;
401 {
402
403         panic("%s called", __FUNCTION__);
404 }
405
406 void
407 softdep_setup_mkdir(dp, ip)
408         struct inode *dp;
409         struct inode *ip;
410 {
411
412         panic("%s called", __FUNCTION__);
413 }
414
415 void
416 softdep_revert_mkdir(dp, ip)
417         struct inode *dp;
418         struct inode *ip;
419 {
420
421         panic("%s called", __FUNCTION__);
422 }
423
424 void
425 softdep_setup_dotdot_link(dp, ip)
426         struct inode *dp;
427         struct inode *ip;
428 {
429
430         panic("%s called", __FUNCTION__);
431 }
432
433 int
434 softdep_prealloc(vp, waitok)
435         struct vnode *vp;
436         int waitok;
437 {
438
439         panic("%s called", __FUNCTION__);
440 }
441
442 int
443 softdep_journal_lookup(mp, vpp)
444         struct mount *mp;
445         struct vnode **vpp;
446 {
447
448         return (ENOENT);
449 }
450
451 void
452 softdep_change_linkcnt(ip)
453         struct inode *ip;
454 {
455
456         panic("softdep_change_linkcnt called");
457 }
458
459 void 
460 softdep_load_inodeblock(ip)
461         struct inode *ip;
462 {
463
464         panic("softdep_load_inodeblock called");
465 }
466
467 void
468 softdep_update_inodeblock(ip, bp, waitfor)
469         struct inode *ip;
470         struct buf *bp;
471         int waitfor;
472 {
473
474         panic("softdep_update_inodeblock called");
475 }
476
477 int
478 softdep_fsync(vp)
479         struct vnode *vp;       /* the "in_core" copy of the inode */
480 {
481
482         return (0);
483 }
484
485 void
486 softdep_fsync_mountdev(vp)
487         struct vnode *vp;
488 {
489
490         return;
491 }
492
493 int
494 softdep_flushworklist(oldmnt, countp, td)
495         struct mount *oldmnt;
496         int *countp;
497         struct thread *td;
498 {
499
500         *countp = 0;
501         return (0);
502 }
503
504 int
505 softdep_sync_metadata(struct vnode *vp)
506 {
507
508         panic("softdep_sync_metadata called");
509 }
510
511 int
512 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
513 {
514
515         panic("softdep_sync_buf called");
516 }
517
518 int
519 softdep_slowdown(vp)
520         struct vnode *vp;
521 {
522
523         panic("softdep_slowdown called");
524 }
525
526 int
527 softdep_request_cleanup(fs, vp, cred, resource)
528         struct fs *fs;
529         struct vnode *vp;
530         struct ucred *cred;
531         int resource;
532 {
533
534         return (0);
535 }
536
537 int
538 softdep_check_suspend(struct mount *mp,
539                       struct vnode *devvp,
540                       int softdep_depcnt,
541                       int softdep_accdepcnt,
542                       int secondary_writes,
543                       int secondary_accwrites)
544 {
545         struct bufobj *bo;
546         int error;
547         
548         (void) softdep_depcnt,
549         (void) softdep_accdepcnt;
550
551         bo = &devvp->v_bufobj;
552         ASSERT_BO_WLOCKED(bo);
553
554         MNT_ILOCK(mp);
555         while (mp->mnt_secondary_writes != 0) {
556                 BO_UNLOCK(bo);
557                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
558                     (PUSER - 1) | PDROP, "secwr", 0);
559                 BO_LOCK(bo);
560                 MNT_ILOCK(mp);
561         }
562
563         /*
564          * Reasons for needing more work before suspend:
565          * - Dirty buffers on devvp.
566          * - Secondary writes occurred after start of vnode sync loop
567          */
568         error = 0;
569         if (bo->bo_numoutput > 0 ||
570             bo->bo_dirty.bv_cnt > 0 ||
571             secondary_writes != 0 ||
572             mp->mnt_secondary_writes != 0 ||
573             secondary_accwrites != mp->mnt_secondary_accwrites)
574                 error = EAGAIN;
575         BO_UNLOCK(bo);
576         return (error);
577 }
578
579 void
580 softdep_get_depcounts(struct mount *mp,
581                       int *softdepactivep,
582                       int *softdepactiveaccp)
583 {
584         (void) mp;
585         *softdepactivep = 0;
586         *softdepactiveaccp = 0;
587 }
588
589 void
590 softdep_buf_append(bp, wkhd)
591         struct buf *bp;
592         struct workhead *wkhd;
593 {
594
595         panic("softdep_buf_appendwork called");
596 }
597
598 void
599 softdep_inode_append(ip, cred, wkhd)
600         struct inode *ip;
601         struct ucred *cred;
602         struct workhead *wkhd;
603 {
604
605         panic("softdep_inode_appendwork called");
606 }
607
608 void
609 softdep_freework(wkhd)
610         struct workhead *wkhd;
611 {
612
613         panic("softdep_freework called");
614 }
615
616 #else
617
618 FEATURE(softupdates, "FFS soft-updates support");
619
620 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
621     "soft updates stats");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
623     "total dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
625     "high use dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
627     "current dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
629     "current dependencies written");
630
631 unsigned long dep_current[D_LAST + 1];
632 unsigned long dep_highuse[D_LAST + 1];
633 unsigned long dep_total[D_LAST + 1];
634 unsigned long dep_write[D_LAST + 1];
635
636 #define SOFTDEP_TYPE(type, str, long)                                   \
637     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
638     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
639         &dep_total[D_ ## type], 0, "");                                 \
640     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
641         &dep_current[D_ ## type], 0, "");                               \
642     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
643         &dep_highuse[D_ ## type], 0, "");                               \
644     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
645         &dep_write[D_ ## type], 0, "");
646
647 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
648 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
649 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
650     "Block or frag allocated from cyl group map");
651 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
652 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
653 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
654 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
655 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
656 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
657 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
658 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
659 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
660 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
661 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
662 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
663 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
664 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
665 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
666 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
667 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
668 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
669 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
670 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
671 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
672 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
673 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
674 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
675
676 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
677
678 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
679 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
680 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
681
682 #define M_SOFTDEP_FLAGS (M_WAITOK)
683
684 /* 
685  * translate from workitem type to memory type
686  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
687  */
688 static struct malloc_type *memtype[] = {
689         M_PAGEDEP,
690         M_INODEDEP,
691         M_BMSAFEMAP,
692         M_NEWBLK,
693         M_ALLOCDIRECT,
694         M_INDIRDEP,
695         M_ALLOCINDIR,
696         M_FREEFRAG,
697         M_FREEBLKS,
698         M_FREEFILE,
699         M_DIRADD,
700         M_MKDIR,
701         M_DIRREM,
702         M_NEWDIRBLK,
703         M_FREEWORK,
704         M_FREEDEP,
705         M_JADDREF,
706         M_JREMREF,
707         M_JMVREF,
708         M_JNEWBLK,
709         M_JFREEBLK,
710         M_JFREEFRAG,
711         M_JSEG,
712         M_JSEGDEP,
713         M_SBDEP,
714         M_JTRUNC,
715         M_JFSYNC,
716         M_SENTINEL
717 };
718
719 #define DtoM(type) (memtype[type])
720
721 /*
722  * Names of malloc types.
723  */
724 #define TYPENAME(type)  \
725         ((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
726 /*
727  * End system adaptation definitions.
728  */
729
730 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
731 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
732
733 /*
734  * Internal function prototypes.
735  */
736 static  void check_clear_deps(struct mount *);
737 static  void softdep_error(char *, int);
738 static  int softdep_process_worklist(struct mount *, int);
739 static  int softdep_waitidle(struct mount *, int);
740 static  void drain_output(struct vnode *);
741 static  struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
742 static  int check_inodedep_free(struct inodedep *);
743 static  void clear_remove(struct mount *);
744 static  void clear_inodedeps(struct mount *);
745 static  void unlinked_inodedep(struct mount *, struct inodedep *);
746 static  void clear_unlinked_inodedep(struct inodedep *);
747 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
748 static  int flush_pagedep_deps(struct vnode *, struct mount *,
749             struct diraddhd *);
750 static  int free_pagedep(struct pagedep *);
751 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
752 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
753 static  int flush_deplist(struct allocdirectlst *, int, int *);
754 static  int sync_cgs(struct mount *, int);
755 static  int handle_written_filepage(struct pagedep *, struct buf *, int);
756 static  int handle_written_sbdep(struct sbdep *, struct buf *);
757 static  void initiate_write_sbdep(struct sbdep *);
758 static  void diradd_inode_written(struct diradd *, struct inodedep *);
759 static  int handle_written_indirdep(struct indirdep *, struct buf *,
760             struct buf**, int);
761 static  int handle_written_inodeblock(struct inodedep *, struct buf *, int);
762 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
763             uint8_t *);
764 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
765 static  void handle_written_jaddref(struct jaddref *);
766 static  void handle_written_jremref(struct jremref *);
767 static  void handle_written_jseg(struct jseg *, struct buf *);
768 static  void handle_written_jnewblk(struct jnewblk *);
769 static  void handle_written_jblkdep(struct jblkdep *);
770 static  void handle_written_jfreefrag(struct jfreefrag *);
771 static  void complete_jseg(struct jseg *);
772 static  void complete_jsegs(struct jseg *);
773 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
774 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
775 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
776 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
777 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
778 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
779 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
780 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
781 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
782 static  inline void inoref_write(struct inoref *, struct jseg *,
783             struct jrefrec *);
784 static  void handle_allocdirect_partdone(struct allocdirect *,
785             struct workhead *);
786 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
787             struct workhead *);
788 static  void indirdep_complete(struct indirdep *);
789 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
790 static  void indirblk_insert(struct freework *);
791 static  void indirblk_remove(struct freework *);
792 static  void handle_allocindir_partdone(struct allocindir *);
793 static  void initiate_write_filepage(struct pagedep *, struct buf *);
794 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
795 static  void handle_written_mkdir(struct mkdir *, int);
796 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
797             uint8_t *);
798 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
799 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
800 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
801 static  void handle_workitem_freefile(struct freefile *);
802 static  int handle_workitem_remove(struct dirrem *, int);
803 static  struct dirrem *newdirrem(struct buf *, struct inode *,
804             struct inode *, int, struct dirrem **);
805 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
806             struct buf *);
807 static  void cancel_indirdep(struct indirdep *, struct buf *,
808             struct freeblks *);
809 static  void free_indirdep(struct indirdep *);
810 static  void free_diradd(struct diradd *, struct workhead *);
811 static  void merge_diradd(struct inodedep *, struct diradd *);
812 static  void complete_diradd(struct diradd *);
813 static  struct diradd *diradd_lookup(struct pagedep *, int);
814 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
815             struct jremref *);
816 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
817             struct jremref *);
818 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
819             struct jremref *, struct jremref *);
820 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
821             struct jremref *);
822 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
823             struct freeblks *, int);
824 static  int setup_trunc_indir(struct freeblks *, struct inode *,
825             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
826 static  void complete_trunc_indir(struct freework *);
827 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
828             int);
829 static  void complete_mkdir(struct mkdir *);
830 static  void free_newdirblk(struct newdirblk *);
831 static  void free_jremref(struct jremref *);
832 static  void free_jaddref(struct jaddref *);
833 static  void free_jsegdep(struct jsegdep *);
834 static  void free_jsegs(struct jblocks *);
835 static  void rele_jseg(struct jseg *);
836 static  void free_jseg(struct jseg *, struct jblocks *);
837 static  void free_jnewblk(struct jnewblk *);
838 static  void free_jblkdep(struct jblkdep *);
839 static  void free_jfreefrag(struct jfreefrag *);
840 static  void free_freedep(struct freedep *);
841 static  void journal_jremref(struct dirrem *, struct jremref *,
842             struct inodedep *);
843 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
844 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
845             struct workhead *);
846 static  void cancel_jfreefrag(struct jfreefrag *);
847 static  inline void setup_freedirect(struct freeblks *, struct inode *,
848             int, int);
849 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
850 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
851             ufs_lbn_t, int);
852 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
853 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
854 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
855 static  ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
856 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
857 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
858             int, int);
859 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
860 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
861 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
862 static  void newblk_freefrag(struct newblk*);
863 static  void free_newblk(struct newblk *);
864 static  void cancel_allocdirect(struct allocdirectlst *,
865             struct allocdirect *, struct freeblks *);
866 static  int check_inode_unwritten(struct inodedep *);
867 static  int free_inodedep(struct inodedep *);
868 static  void freework_freeblock(struct freework *);
869 static  void freework_enqueue(struct freework *);
870 static  int handle_workitem_freeblocks(struct freeblks *, int);
871 static  int handle_complete_freeblocks(struct freeblks *, int);
872 static  void handle_workitem_indirblk(struct freework *);
873 static  void handle_written_freework(struct freework *);
874 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
875 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
876             struct workhead *);
877 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
878             struct inodedep *, struct allocindir *, ufs_lbn_t);
879 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
880             ufs2_daddr_t, ufs_lbn_t);
881 static  void handle_workitem_freefrag(struct freefrag *);
882 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
883             ufs_lbn_t);
884 static  void allocdirect_merge(struct allocdirectlst *,
885             struct allocdirect *, struct allocdirect *);
886 static  struct freefrag *allocindir_merge(struct allocindir *,
887             struct allocindir *);
888 static  int bmsafemap_find(struct bmsafemap_hashhead *, int,
889             struct bmsafemap **);
890 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
891             int cg, struct bmsafemap *);
892 static  int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
893             struct newblk **);
894 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
895 static  int inodedep_find(struct inodedep_hashhead *, ino_t,
896             struct inodedep **);
897 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
898 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
899             int, struct pagedep **);
900 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
901             struct pagedep **);
902 static  void pause_timer(void *);
903 static  int request_cleanup(struct mount *, int);
904 static  int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
905 static  void schedule_cleanup(struct mount *);
906 static void softdep_ast_cleanup_proc(struct thread *);
907 static  int process_worklist_item(struct mount *, int, int);
908 static  void process_removes(struct vnode *);
909 static  void process_truncates(struct vnode *);
910 static  void jwork_move(struct workhead *, struct workhead *);
911 static  void jwork_insert(struct workhead *, struct jsegdep *);
912 static  void add_to_worklist(struct worklist *, int);
913 static  void wake_worklist(struct worklist *);
914 static  void wait_worklist(struct worklist *, char *);
915 static  void remove_from_worklist(struct worklist *);
916 static  void softdep_flush(void *);
917 static  void softdep_flushjournal(struct mount *);
918 static  int softdep_speedup(struct ufsmount *);
919 static  void worklist_speedup(struct mount *);
920 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
921 static  void journal_unmount(struct ufsmount *);
922 static  int journal_space(struct ufsmount *, int);
923 static  void journal_suspend(struct ufsmount *);
924 static  int journal_unsuspend(struct ufsmount *ump);
925 static  void softdep_prelink(struct vnode *, struct vnode *);
926 static  void add_to_journal(struct worklist *);
927 static  void remove_from_journal(struct worklist *);
928 static  bool softdep_excess_items(struct ufsmount *, int);
929 static  void softdep_process_journal(struct mount *, struct worklist *, int);
930 static  struct jremref *newjremref(struct dirrem *, struct inode *,
931             struct inode *ip, off_t, nlink_t);
932 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
933             uint16_t);
934 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
935             uint16_t);
936 static  inline struct jsegdep *inoref_jseg(struct inoref *);
937 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
938 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
939             ufs2_daddr_t, int);
940 static  void adjust_newfreework(struct freeblks *, int);
941 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
942 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
943 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
944 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
945             ufs2_daddr_t, long, ufs_lbn_t);
946 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
947             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
948 static  int jwait(struct worklist *, int);
949 static  struct inodedep *inodedep_lookup_ip(struct inode *);
950 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
951 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
952 static  void handle_jwork(struct workhead *);
953 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
954             struct mkdir **);
955 static  struct jblocks *jblocks_create(void);
956 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
957 static  void jblocks_free(struct jblocks *, struct mount *, int);
958 static  void jblocks_destroy(struct jblocks *);
959 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
960
961 /*
962  * Exported softdep operations.
963  */
964 static  void softdep_disk_io_initiation(struct buf *);
965 static  void softdep_disk_write_complete(struct buf *);
966 static  void softdep_deallocate_dependencies(struct buf *);
967 static  int softdep_count_dependencies(struct buf *bp, int);
968
969 /*
970  * Global lock over all of soft updates.
971  */
972 static struct mtx lk;
973 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
974
975 #define ACQUIRE_GBLLOCK(lk)     mtx_lock(lk)
976 #define FREE_GBLLOCK(lk)        mtx_unlock(lk)
977 #define GBLLOCK_OWNED(lk)       mtx_assert((lk), MA_OWNED)
978
979 /*
980  * Per-filesystem soft-updates locking.
981  */
982 #define LOCK_PTR(ump)           (&(ump)->um_softdep->sd_fslock)
983 #define TRY_ACQUIRE_LOCK(ump)   rw_try_wlock(&(ump)->um_softdep->sd_fslock)
984 #define ACQUIRE_LOCK(ump)       rw_wlock(&(ump)->um_softdep->sd_fslock)
985 #define FREE_LOCK(ump)          rw_wunlock(&(ump)->um_softdep->sd_fslock)
986 #define LOCK_OWNED(ump)         rw_assert(&(ump)->um_softdep->sd_fslock, \
987                                     RA_WLOCKED)
988
989 #define BUF_AREC(bp)            lockallowrecurse(&(bp)->b_lock)
990 #define BUF_NOREC(bp)           lockdisablerecurse(&(bp)->b_lock)
991
992 /*
993  * Worklist queue management.
994  * These routines require that the lock be held.
995  */
996 #ifndef /* NOT */ DEBUG
997 #define WORKLIST_INSERT(head, item) do {        \
998         (item)->wk_state |= ONWORKLIST;         \
999         LIST_INSERT_HEAD(head, item, wk_list);  \
1000 } while (0)
1001 #define WORKLIST_REMOVE(item) do {              \
1002         (item)->wk_state &= ~ONWORKLIST;        \
1003         LIST_REMOVE(item, wk_list);             \
1004 } while (0)
1005 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1006 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1007
1008 #else /* DEBUG */
1009 static  void worklist_insert(struct workhead *, struct worklist *, int);
1010 static  void worklist_remove(struct worklist *, int);
1011
1012 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1013 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1014 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1015 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1016
1017 static void
1018 worklist_insert(head, item, locked)
1019         struct workhead *head;
1020         struct worklist *item;
1021         int locked;
1022 {
1023
1024         if (locked)
1025                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1026         if (item->wk_state & ONWORKLIST)
1027                 panic("worklist_insert: %p %s(0x%X) already on list",
1028                     item, TYPENAME(item->wk_type), item->wk_state);
1029         item->wk_state |= ONWORKLIST;
1030         LIST_INSERT_HEAD(head, item, wk_list);
1031 }
1032
1033 static void
1034 worklist_remove(item, locked)
1035         struct worklist *item;
1036         int locked;
1037 {
1038
1039         if (locked)
1040                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1041         if ((item->wk_state & ONWORKLIST) == 0)
1042                 panic("worklist_remove: %p %s(0x%X) not on list",
1043                     item, TYPENAME(item->wk_type), item->wk_state);
1044         item->wk_state &= ~ONWORKLIST;
1045         LIST_REMOVE(item, wk_list);
1046 }
1047 #endif /* DEBUG */
1048
1049 /*
1050  * Merge two jsegdeps keeping only the oldest one as newer references
1051  * can't be discarded until after older references.
1052  */
1053 static inline struct jsegdep *
1054 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1055 {
1056         struct jsegdep *swp;
1057
1058         if (two == NULL)
1059                 return (one);
1060
1061         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1062                 swp = one;
1063                 one = two;
1064                 two = swp;
1065         }
1066         WORKLIST_REMOVE(&two->jd_list);
1067         free_jsegdep(two);
1068
1069         return (one);
1070 }
1071
1072 /*
1073  * If two freedeps are compatible free one to reduce list size.
1074  */
1075 static inline struct freedep *
1076 freedep_merge(struct freedep *one, struct freedep *two)
1077 {
1078         if (two == NULL)
1079                 return (one);
1080
1081         if (one->fd_freework == two->fd_freework) {
1082                 WORKLIST_REMOVE(&two->fd_list);
1083                 free_freedep(two);
1084         }
1085         return (one);
1086 }
1087
1088 /*
1089  * Move journal work from one list to another.  Duplicate freedeps and
1090  * jsegdeps are coalesced to keep the lists as small as possible.
1091  */
1092 static void
1093 jwork_move(dst, src)
1094         struct workhead *dst;
1095         struct workhead *src;
1096 {
1097         struct freedep *freedep;
1098         struct jsegdep *jsegdep;
1099         struct worklist *wkn;
1100         struct worklist *wk;
1101
1102         KASSERT(dst != src,
1103             ("jwork_move: dst == src"));
1104         freedep = NULL;
1105         jsegdep = NULL;
1106         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1107                 if (wk->wk_type == D_JSEGDEP)
1108                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1109                 else if (wk->wk_type == D_FREEDEP)
1110                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1111         }
1112
1113         while ((wk = LIST_FIRST(src)) != NULL) {
1114                 WORKLIST_REMOVE(wk);
1115                 WORKLIST_INSERT(dst, wk);
1116                 if (wk->wk_type == D_JSEGDEP) {
1117                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1118                         continue;
1119                 }
1120                 if (wk->wk_type == D_FREEDEP)
1121                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1122         }
1123 }
1124
1125 static void
1126 jwork_insert(dst, jsegdep)
1127         struct workhead *dst;
1128         struct jsegdep *jsegdep;
1129 {
1130         struct jsegdep *jsegdepn;
1131         struct worklist *wk;
1132
1133         LIST_FOREACH(wk, dst, wk_list)
1134                 if (wk->wk_type == D_JSEGDEP)
1135                         break;
1136         if (wk == NULL) {
1137                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1138                 return;
1139         }
1140         jsegdepn = WK_JSEGDEP(wk);
1141         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1142                 WORKLIST_REMOVE(wk);
1143                 free_jsegdep(jsegdepn);
1144                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1145         } else
1146                 free_jsegdep(jsegdep);
1147 }
1148
1149 /*
1150  * Routines for tracking and managing workitems.
1151  */
1152 static  void workitem_free(struct worklist *, int);
1153 static  void workitem_alloc(struct worklist *, int, struct mount *);
1154 static  void workitem_reassign(struct worklist *, int);
1155
1156 #define WORKITEM_FREE(item, type) \
1157         workitem_free((struct worklist *)(item), (type))
1158 #define WORKITEM_REASSIGN(item, type) \
1159         workitem_reassign((struct worklist *)(item), (type))
1160
1161 static void
1162 workitem_free(item, type)
1163         struct worklist *item;
1164         int type;
1165 {
1166         struct ufsmount *ump;
1167
1168 #ifdef DEBUG
1169         if (item->wk_state & ONWORKLIST)
1170                 panic("workitem_free: %s(0x%X) still on list",
1171                     TYPENAME(item->wk_type), item->wk_state);
1172         if (item->wk_type != type && type != D_NEWBLK)
1173                 panic("workitem_free: type mismatch %s != %s",
1174                     TYPENAME(item->wk_type), TYPENAME(type));
1175 #endif
1176         if (item->wk_state & IOWAITING)
1177                 wakeup(item);
1178         ump = VFSTOUFS(item->wk_mp);
1179         LOCK_OWNED(ump);
1180         KASSERT(ump->softdep_deps > 0,
1181             ("workitem_free: %s: softdep_deps going negative",
1182             ump->um_fs->fs_fsmnt));
1183         if (--ump->softdep_deps == 0 && ump->softdep_req)
1184                 wakeup(&ump->softdep_deps);
1185         KASSERT(dep_current[item->wk_type] > 0,
1186             ("workitem_free: %s: dep_current[%s] going negative",
1187             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1188         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1189             ("workitem_free: %s: softdep_curdeps[%s] going negative",
1190             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1191         atomic_subtract_long(&dep_current[item->wk_type], 1);
1192         ump->softdep_curdeps[item->wk_type] -= 1;
1193         free(item, DtoM(type));
1194 }
1195
1196 static void
1197 workitem_alloc(item, type, mp)
1198         struct worklist *item;
1199         int type;
1200         struct mount *mp;
1201 {
1202         struct ufsmount *ump;
1203
1204         item->wk_type = type;
1205         item->wk_mp = mp;
1206         item->wk_state = 0;
1207
1208         ump = VFSTOUFS(mp);
1209         ACQUIRE_GBLLOCK(&lk);
1210         dep_current[type]++;
1211         if (dep_current[type] > dep_highuse[type])
1212                 dep_highuse[type] = dep_current[type];
1213         dep_total[type]++;
1214         FREE_GBLLOCK(&lk);
1215         ACQUIRE_LOCK(ump);
1216         ump->softdep_curdeps[type] += 1;
1217         ump->softdep_deps++;
1218         ump->softdep_accdeps++;
1219         FREE_LOCK(ump);
1220 }
1221
1222 static void
1223 workitem_reassign(item, newtype)
1224         struct worklist *item;
1225         int newtype;
1226 {
1227         struct ufsmount *ump;
1228
1229         ump = VFSTOUFS(item->wk_mp);
1230         LOCK_OWNED(ump);
1231         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1232             ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1233             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1234         ump->softdep_curdeps[item->wk_type] -= 1;
1235         ump->softdep_curdeps[newtype] += 1;
1236         KASSERT(dep_current[item->wk_type] > 0,
1237             ("workitem_reassign: %s: dep_current[%s] going negative",
1238             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1239         ACQUIRE_GBLLOCK(&lk);
1240         dep_current[newtype]++;
1241         dep_current[item->wk_type]--;
1242         if (dep_current[newtype] > dep_highuse[newtype])
1243                 dep_highuse[newtype] = dep_current[newtype];
1244         dep_total[newtype]++;
1245         FREE_GBLLOCK(&lk);
1246         item->wk_type = newtype;
1247 }
1248
1249 /*
1250  * Workitem queue management
1251  */
1252 static int max_softdeps;        /* maximum number of structs before slowdown */
1253 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1254 static int proc_waiting;        /* tracks whether we have a timeout posted */
1255 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1256 static struct callout softdep_callout;
1257 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1258 static int req_clear_remove;    /* syncer process flush some freeblks */
1259 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1260
1261 /*
1262  * runtime statistics
1263  */
1264 static int stat_flush_threads;  /* number of softdep flushing threads */
1265 static int stat_worklist_push;  /* number of worklist cleanups */
1266 static int stat_blk_limit_push; /* number of times block limit neared */
1267 static int stat_ino_limit_push; /* number of times inode limit neared */
1268 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1269 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1270 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1271 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1272 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1273 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1274 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1275 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1276 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1277 static int stat_journal_min;    /* Times hit journal min threshold */
1278 static int stat_journal_low;    /* Times hit journal low threshold */
1279 static int stat_journal_wait;   /* Times blocked in jwait(). */
1280 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1281 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1282 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1283 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1284 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1285 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1286 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1287 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1288 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1289 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1290
1291 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1292     &max_softdeps, 0, "");
1293 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1294     &tickdelay, 0, "");
1295 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1296     &stat_flush_threads, 0, "");
1297 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1298     &stat_worklist_push, 0,"");
1299 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1300     &stat_blk_limit_push, 0,"");
1301 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1302     &stat_ino_limit_push, 0,"");
1303 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1304     &stat_blk_limit_hit, 0, "");
1305 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1306     &stat_ino_limit_hit, 0, "");
1307 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1308     &stat_sync_limit_hit, 0, "");
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1310     &stat_indir_blk_ptrs, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1312     &stat_inode_bitmap, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1314     &stat_direct_blk_ptrs, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1316     &stat_dir_entry, 0, "");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1318     &stat_jaddref, 0, "");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1320     &stat_jnewblk, 0, "");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1322     &stat_journal_low, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1324     &stat_journal_min, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1326     &stat_journal_wait, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1328     &stat_jwait_filepage, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1330     &stat_jwait_freeblks, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1332     &stat_jwait_inode, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1334     &stat_jwait_newblk, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1336     &stat_cleanup_blkrequests, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1338     &stat_cleanup_inorequests, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1340     &stat_cleanup_high_delay, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1342     &stat_cleanup_retries, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1344     &stat_cleanup_failures, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1346     &softdep_flushcache, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1348     &stat_emptyjblocks, 0, "");
1349
1350 SYSCTL_DECL(_vfs_ffs);
1351
1352 /* Whether to recompute the summary at mount time */
1353 static int compute_summary_at_mount = 0;
1354 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1355            &compute_summary_at_mount, 0, "Recompute summary at mount");
1356 static int print_threads = 0;
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1358     &print_threads, 0, "Notify flusher thread start/stop");
1359
1360 /* List of all filesystems mounted with soft updates */
1361 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1362
1363 /*
1364  * This function cleans the worklist for a filesystem.
1365  * Each filesystem running with soft dependencies gets its own
1366  * thread to run in this function. The thread is started up in
1367  * softdep_mount and shutdown in softdep_unmount. They show up
1368  * as part of the kernel "bufdaemon" process whose process
1369  * entry is available in bufdaemonproc.
1370  */
1371 static int searchfailed;
1372 extern struct proc *bufdaemonproc;
1373 static void
1374 softdep_flush(addr)
1375         void *addr;
1376 {
1377         struct mount *mp;
1378         struct thread *td;
1379         struct ufsmount *ump;
1380
1381         td = curthread;
1382         td->td_pflags |= TDP_NORUNNINGBUF;
1383         mp = (struct mount *)addr;
1384         ump = VFSTOUFS(mp);
1385         atomic_add_int(&stat_flush_threads, 1);
1386         ACQUIRE_LOCK(ump);
1387         ump->softdep_flags &= ~FLUSH_STARTING;
1388         wakeup(&ump->softdep_flushtd);
1389         FREE_LOCK(ump);
1390         if (print_threads) {
1391                 if (stat_flush_threads == 1)
1392                         printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1393                             bufdaemonproc->p_pid);
1394                 printf("Start thread %s\n", td->td_name);
1395         }
1396         for (;;) {      
1397                 while (softdep_process_worklist(mp, 0) > 0 ||
1398                     (MOUNTEDSUJ(mp) &&
1399                     VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1400                         kthread_suspend_check();
1401                 ACQUIRE_LOCK(ump);
1402                 if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1403                         msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1404                             "sdflush", hz / 2);
1405                 ump->softdep_flags &= ~FLUSH_CLEANUP;
1406                 /*
1407                  * Check to see if we are done and need to exit.
1408                  */
1409                 if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1410                         FREE_LOCK(ump);
1411                         continue;
1412                 }
1413                 ump->softdep_flags &= ~FLUSH_EXIT;
1414                 FREE_LOCK(ump);
1415                 wakeup(&ump->softdep_flags);
1416                 if (print_threads)
1417                         printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1418                 atomic_subtract_int(&stat_flush_threads, 1);
1419                 kthread_exit();
1420                 panic("kthread_exit failed\n");
1421         }
1422 }
1423
1424 static void
1425 worklist_speedup(mp)
1426         struct mount *mp;
1427 {
1428         struct ufsmount *ump;
1429
1430         ump = VFSTOUFS(mp);
1431         LOCK_OWNED(ump);
1432         if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1433                 ump->softdep_flags |= FLUSH_CLEANUP;
1434         wakeup(&ump->softdep_flushtd);
1435 }
1436
1437 static int
1438 softdep_speedup(ump)
1439         struct ufsmount *ump;
1440 {
1441         struct ufsmount *altump;
1442         struct mount_softdeps *sdp;
1443
1444         LOCK_OWNED(ump);
1445         worklist_speedup(ump->um_mountp);
1446         bd_speedup();
1447         /*
1448          * If we have global shortages, then we need other
1449          * filesystems to help with the cleanup. Here we wakeup a
1450          * flusher thread for a filesystem that is over its fair
1451          * share of resources.
1452          */
1453         if (req_clear_inodedeps || req_clear_remove) {
1454                 ACQUIRE_GBLLOCK(&lk);
1455                 TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1456                         if ((altump = sdp->sd_ump) == ump)
1457                                 continue;
1458                         if (((req_clear_inodedeps &&
1459                             altump->softdep_curdeps[D_INODEDEP] >
1460                             max_softdeps / stat_flush_threads) ||
1461                             (req_clear_remove &&
1462                             altump->softdep_curdeps[D_DIRREM] >
1463                             (max_softdeps / 2) / stat_flush_threads)) &&
1464                             TRY_ACQUIRE_LOCK(altump))
1465                                 break;
1466                 }
1467                 if (sdp == NULL) {
1468                         searchfailed++;
1469                         FREE_GBLLOCK(&lk);
1470                 } else {
1471                         /*
1472                          * Move to the end of the list so we pick a
1473                          * different one on out next try.
1474                          */
1475                         TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1476                         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1477                         FREE_GBLLOCK(&lk);
1478                         if ((altump->softdep_flags &
1479                             (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1480                                 altump->softdep_flags |= FLUSH_CLEANUP;
1481                         altump->um_softdep->sd_cleanups++;
1482                         wakeup(&altump->softdep_flushtd);
1483                         FREE_LOCK(altump);
1484                 }
1485         }
1486         return (speedup_syncer());
1487 }
1488
1489 /*
1490  * Add an item to the end of the work queue.
1491  * This routine requires that the lock be held.
1492  * This is the only routine that adds items to the list.
1493  * The following routine is the only one that removes items
1494  * and does so in order from first to last.
1495  */
1496
1497 #define WK_HEAD         0x0001  /* Add to HEAD. */
1498 #define WK_NODELAY      0x0002  /* Process immediately. */
1499
1500 static void
1501 add_to_worklist(wk, flags)
1502         struct worklist *wk;
1503         int flags;
1504 {
1505         struct ufsmount *ump;
1506
1507         ump = VFSTOUFS(wk->wk_mp);
1508         LOCK_OWNED(ump);
1509         if (wk->wk_state & ONWORKLIST)
1510                 panic("add_to_worklist: %s(0x%X) already on list",
1511                     TYPENAME(wk->wk_type), wk->wk_state);
1512         wk->wk_state |= ONWORKLIST;
1513         if (ump->softdep_on_worklist == 0) {
1514                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1515                 ump->softdep_worklist_tail = wk;
1516         } else if (flags & WK_HEAD) {
1517                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1518         } else {
1519                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1520                 ump->softdep_worklist_tail = wk;
1521         }
1522         ump->softdep_on_worklist += 1;
1523         if (flags & WK_NODELAY)
1524                 worklist_speedup(wk->wk_mp);
1525 }
1526
1527 /*
1528  * Remove the item to be processed. If we are removing the last
1529  * item on the list, we need to recalculate the tail pointer.
1530  */
1531 static void
1532 remove_from_worklist(wk)
1533         struct worklist *wk;
1534 {
1535         struct ufsmount *ump;
1536
1537         ump = VFSTOUFS(wk->wk_mp);
1538         WORKLIST_REMOVE(wk);
1539         if (ump->softdep_worklist_tail == wk)
1540                 ump->softdep_worklist_tail =
1541                     (struct worklist *)wk->wk_list.le_prev;
1542         ump->softdep_on_worklist -= 1;
1543 }
1544
1545 static void
1546 wake_worklist(wk)
1547         struct worklist *wk;
1548 {
1549         if (wk->wk_state & IOWAITING) {
1550                 wk->wk_state &= ~IOWAITING;
1551                 wakeup(wk);
1552         }
1553 }
1554
1555 static void
1556 wait_worklist(wk, wmesg)
1557         struct worklist *wk;
1558         char *wmesg;
1559 {
1560         struct ufsmount *ump;
1561
1562         ump = VFSTOUFS(wk->wk_mp);
1563         wk->wk_state |= IOWAITING;
1564         msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1565 }
1566
1567 /*
1568  * Process that runs once per second to handle items in the background queue.
1569  *
1570  * Note that we ensure that everything is done in the order in which they
1571  * appear in the queue. The code below depends on this property to ensure
1572  * that blocks of a file are freed before the inode itself is freed. This
1573  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1574  * until all the old ones have been purged from the dependency lists.
1575  */
1576 static int 
1577 softdep_process_worklist(mp, full)
1578         struct mount *mp;
1579         int full;
1580 {
1581         int cnt, matchcnt;
1582         struct ufsmount *ump;
1583         long starttime;
1584
1585         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1586         if (MOUNTEDSOFTDEP(mp) == 0)
1587                 return (0);
1588         matchcnt = 0;
1589         ump = VFSTOUFS(mp);
1590         ACQUIRE_LOCK(ump);
1591         starttime = time_second;
1592         softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1593         check_clear_deps(mp);
1594         while (ump->softdep_on_worklist > 0) {
1595                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1596                         break;
1597                 else
1598                         matchcnt += cnt;
1599                 check_clear_deps(mp);
1600                 /*
1601                  * We do not generally want to stop for buffer space, but if
1602                  * we are really being a buffer hog, we will stop and wait.
1603                  */
1604                 if (should_yield()) {
1605                         FREE_LOCK(ump);
1606                         kern_yield(PRI_USER);
1607                         bwillwrite();
1608                         ACQUIRE_LOCK(ump);
1609                 }
1610                 /*
1611                  * Never allow processing to run for more than one
1612                  * second. This gives the syncer thread the opportunity
1613                  * to pause if appropriate.
1614                  */
1615                 if (!full && starttime != time_second)
1616                         break;
1617         }
1618         if (full == 0)
1619                 journal_unsuspend(ump);
1620         FREE_LOCK(ump);
1621         return (matchcnt);
1622 }
1623
1624 /*
1625  * Process all removes associated with a vnode if we are running out of
1626  * journal space.  Any other process which attempts to flush these will
1627  * be unable as we have the vnodes locked.
1628  */
1629 static void
1630 process_removes(vp)
1631         struct vnode *vp;
1632 {
1633         struct inodedep *inodedep;
1634         struct dirrem *dirrem;
1635         struct ufsmount *ump;
1636         struct mount *mp;
1637         ino_t inum;
1638
1639         mp = vp->v_mount;
1640         ump = VFSTOUFS(mp);
1641         LOCK_OWNED(ump);
1642         inum = VTOI(vp)->i_number;
1643         for (;;) {
1644 top:
1645                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1646                         return;
1647                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1648                         /*
1649                          * If another thread is trying to lock this vnode
1650                          * it will fail but we must wait for it to do so
1651                          * before we can proceed.
1652                          */
1653                         if (dirrem->dm_state & INPROGRESS) {
1654                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1655                                 goto top;
1656                         }
1657                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1658                             (COMPLETE | ONWORKLIST))
1659                                 break;
1660                 }
1661                 if (dirrem == NULL)
1662                         return;
1663                 remove_from_worklist(&dirrem->dm_list);
1664                 FREE_LOCK(ump);
1665                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1666                         panic("process_removes: suspended filesystem");
1667                 handle_workitem_remove(dirrem, 0);
1668                 vn_finished_secondary_write(mp);
1669                 ACQUIRE_LOCK(ump);
1670         }
1671 }
1672
1673 /*
1674  * Process all truncations associated with a vnode if we are running out
1675  * of journal space.  This is called when the vnode lock is already held
1676  * and no other process can clear the truncation.  This function returns
1677  * a value greater than zero if it did any work.
1678  */
1679 static void
1680 process_truncates(vp)
1681         struct vnode *vp;
1682 {
1683         struct inodedep *inodedep;
1684         struct freeblks *freeblks;
1685         struct ufsmount *ump;
1686         struct mount *mp;
1687         ino_t inum;
1688         int cgwait;
1689
1690         mp = vp->v_mount;
1691         ump = VFSTOUFS(mp);
1692         LOCK_OWNED(ump);
1693         inum = VTOI(vp)->i_number;
1694         for (;;) {
1695                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1696                         return;
1697                 cgwait = 0;
1698                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1699                         /* Journal entries not yet written.  */
1700                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1701                                 jwait(&LIST_FIRST(
1702                                     &freeblks->fb_jblkdephd)->jb_list,
1703                                     MNT_WAIT);
1704                                 break;
1705                         }
1706                         /* Another thread is executing this item. */
1707                         if (freeblks->fb_state & INPROGRESS) {
1708                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1709                                 break;
1710                         }
1711                         /* Freeblks is waiting on a inode write. */
1712                         if ((freeblks->fb_state & COMPLETE) == 0) {
1713                                 FREE_LOCK(ump);
1714                                 ffs_update(vp, 1);
1715                                 ACQUIRE_LOCK(ump);
1716                                 break;
1717                         }
1718                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1719                             (ALLCOMPLETE | ONWORKLIST)) {
1720                                 remove_from_worklist(&freeblks->fb_list);
1721                                 freeblks->fb_state |= INPROGRESS;
1722                                 FREE_LOCK(ump);
1723                                 if (vn_start_secondary_write(NULL, &mp,
1724                                     V_NOWAIT))
1725                                         panic("process_truncates: "
1726                                             "suspended filesystem");
1727                                 handle_workitem_freeblocks(freeblks, 0);
1728                                 vn_finished_secondary_write(mp);
1729                                 ACQUIRE_LOCK(ump);
1730                                 break;
1731                         }
1732                         if (freeblks->fb_cgwait)
1733                                 cgwait++;
1734                 }
1735                 if (cgwait) {
1736                         FREE_LOCK(ump);
1737                         sync_cgs(mp, MNT_WAIT);
1738                         ffs_sync_snap(mp, MNT_WAIT);
1739                         ACQUIRE_LOCK(ump);
1740                         continue;
1741                 }
1742                 if (freeblks == NULL)
1743                         break;
1744         }
1745         return;
1746 }
1747
1748 /*
1749  * Process one item on the worklist.
1750  */
1751 static int
1752 process_worklist_item(mp, target, flags)
1753         struct mount *mp;
1754         int target;
1755         int flags;
1756 {
1757         struct worklist sentinel;
1758         struct worklist *wk;
1759         struct ufsmount *ump;
1760         int matchcnt;
1761         int error;
1762
1763         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1764         /*
1765          * If we are being called because of a process doing a
1766          * copy-on-write, then it is not safe to write as we may
1767          * recurse into the copy-on-write routine.
1768          */
1769         if (curthread->td_pflags & TDP_COWINPROGRESS)
1770                 return (-1);
1771         PHOLD(curproc); /* Don't let the stack go away. */
1772         ump = VFSTOUFS(mp);
1773         LOCK_OWNED(ump);
1774         matchcnt = 0;
1775         sentinel.wk_mp = NULL;
1776         sentinel.wk_type = D_SENTINEL;
1777         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1778         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1779             wk = LIST_NEXT(&sentinel, wk_list)) {
1780                 if (wk->wk_type == D_SENTINEL) {
1781                         LIST_REMOVE(&sentinel, wk_list);
1782                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1783                         continue;
1784                 }
1785                 if (wk->wk_state & INPROGRESS)
1786                         panic("process_worklist_item: %p already in progress.",
1787                             wk);
1788                 wk->wk_state |= INPROGRESS;
1789                 remove_from_worklist(wk);
1790                 FREE_LOCK(ump);
1791                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1792                         panic("process_worklist_item: suspended filesystem");
1793                 switch (wk->wk_type) {
1794                 case D_DIRREM:
1795                         /* removal of a directory entry */
1796                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1797                         break;
1798
1799                 case D_FREEBLKS:
1800                         /* releasing blocks and/or fragments from a file */
1801                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1802                             flags);
1803                         break;
1804
1805                 case D_FREEFRAG:
1806                         /* releasing a fragment when replaced as a file grows */
1807                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1808                         error = 0;
1809                         break;
1810
1811                 case D_FREEFILE:
1812                         /* releasing an inode when its link count drops to 0 */
1813                         handle_workitem_freefile(WK_FREEFILE(wk));
1814                         error = 0;
1815                         break;
1816
1817                 default:
1818                         panic("%s_process_worklist: Unknown type %s",
1819                             "softdep", TYPENAME(wk->wk_type));
1820                         /* NOTREACHED */
1821                 }
1822                 vn_finished_secondary_write(mp);
1823                 ACQUIRE_LOCK(ump);
1824                 if (error == 0) {
1825                         if (++matchcnt == target)
1826                                 break;
1827                         continue;
1828                 }
1829                 /*
1830                  * We have to retry the worklist item later.  Wake up any
1831                  * waiters who may be able to complete it immediately and
1832                  * add the item back to the head so we don't try to execute
1833                  * it again.
1834                  */
1835                 wk->wk_state &= ~INPROGRESS;
1836                 wake_worklist(wk);
1837                 add_to_worklist(wk, WK_HEAD);
1838         }
1839         LIST_REMOVE(&sentinel, wk_list);
1840         /* Sentinal could've become the tail from remove_from_worklist. */
1841         if (ump->softdep_worklist_tail == &sentinel)
1842                 ump->softdep_worklist_tail =
1843                     (struct worklist *)sentinel.wk_list.le_prev;
1844         PRELE(curproc);
1845         return (matchcnt);
1846 }
1847
1848 /*
1849  * Move dependencies from one buffer to another.
1850  */
1851 int
1852 softdep_move_dependencies(oldbp, newbp)
1853         struct buf *oldbp;
1854         struct buf *newbp;
1855 {
1856         struct worklist *wk, *wktail;
1857         struct ufsmount *ump;
1858         int dirty;
1859
1860         if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1861                 return (0);
1862         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1863             ("softdep_move_dependencies called on non-softdep filesystem"));
1864         dirty = 0;
1865         wktail = NULL;
1866         ump = VFSTOUFS(wk->wk_mp);
1867         ACQUIRE_LOCK(ump);
1868         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1869                 LIST_REMOVE(wk, wk_list);
1870                 if (wk->wk_type == D_BMSAFEMAP &&
1871                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1872                         dirty = 1;
1873                 if (wktail == NULL)
1874                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1875                 else
1876                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1877                 wktail = wk;
1878         }
1879         FREE_LOCK(ump);
1880
1881         return (dirty);
1882 }
1883
1884 /*
1885  * Purge the work list of all items associated with a particular mount point.
1886  */
1887 int
1888 softdep_flushworklist(oldmnt, countp, td)
1889         struct mount *oldmnt;
1890         int *countp;
1891         struct thread *td;
1892 {
1893         struct vnode *devvp;
1894         struct ufsmount *ump;
1895         int count, error;
1896
1897         /*
1898          * Alternately flush the block device associated with the mount
1899          * point and process any dependencies that the flushing
1900          * creates. We continue until no more worklist dependencies
1901          * are found.
1902          */
1903         *countp = 0;
1904         error = 0;
1905         ump = VFSTOUFS(oldmnt);
1906         devvp = ump->um_devvp;
1907         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1908                 *countp += count;
1909                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1910                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1911                 VOP_UNLOCK(devvp, 0);
1912                 if (error != 0)
1913                         break;
1914         }
1915         return (error);
1916 }
1917
1918 #define SU_WAITIDLE_RETRIES     20
1919 static int
1920 softdep_waitidle(struct mount *mp, int flags __unused)
1921 {
1922         struct ufsmount *ump;
1923         struct vnode *devvp;
1924         struct thread *td;
1925         int error, i;
1926
1927         ump = VFSTOUFS(mp);
1928         devvp = ump->um_devvp;
1929         td = curthread;
1930         error = 0;
1931         ACQUIRE_LOCK(ump);
1932         for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1933                 ump->softdep_req = 1;
1934                 KASSERT((flags & FORCECLOSE) == 0 ||
1935                     ump->softdep_on_worklist == 0,
1936                     ("softdep_waitidle: work added after flush"));
1937                 msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1938                     "softdeps", 10 * hz);
1939                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1940                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1941                 VOP_UNLOCK(devvp, 0);
1942                 ACQUIRE_LOCK(ump);
1943                 if (error != 0)
1944                         break;
1945         }
1946         ump->softdep_req = 0;
1947         if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1948                 error = EBUSY;
1949                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1950                     mp);
1951         }
1952         FREE_LOCK(ump);
1953         return (error);
1954 }
1955
1956 /*
1957  * Flush all vnodes and worklist items associated with a specified mount point.
1958  */
1959 int
1960 softdep_flushfiles(oldmnt, flags, td)
1961         struct mount *oldmnt;
1962         int flags;
1963         struct thread *td;
1964 {
1965 #ifdef QUOTA
1966         struct ufsmount *ump;
1967         int i;
1968 #endif
1969         int error, early, depcount, loopcnt, retry_flush_count, retry;
1970         int morework;
1971
1972         KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1973             ("softdep_flushfiles called on non-softdep filesystem"));
1974         loopcnt = 10;
1975         retry_flush_count = 3;
1976 retry_flush:
1977         error = 0;
1978
1979         /*
1980          * Alternately flush the vnodes associated with the mount
1981          * point and process any dependencies that the flushing
1982          * creates. In theory, this loop can happen at most twice,
1983          * but we give it a few extra just to be sure.
1984          */
1985         for (; loopcnt > 0; loopcnt--) {
1986                 /*
1987                  * Do another flush in case any vnodes were brought in
1988                  * as part of the cleanup operations.
1989                  */
1990                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1991                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1992                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1993                         break;
1994                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1995                     depcount == 0)
1996                         break;
1997         }
1998         /*
1999          * If we are unmounting then it is an error to fail. If we
2000          * are simply trying to downgrade to read-only, then filesystem
2001          * activity can keep us busy forever, so we just fail with EBUSY.
2002          */
2003         if (loopcnt == 0) {
2004                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2005                         panic("softdep_flushfiles: looping");
2006                 error = EBUSY;
2007         }
2008         if (!error)
2009                 error = softdep_waitidle(oldmnt, flags);
2010         if (!error) {
2011                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2012                         retry = 0;
2013                         MNT_ILOCK(oldmnt);
2014                         KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2015                             ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2016                         morework = oldmnt->mnt_nvnodelistsize > 0;
2017 #ifdef QUOTA
2018                         ump = VFSTOUFS(oldmnt);
2019                         UFS_LOCK(ump);
2020                         for (i = 0; i < MAXQUOTAS; i++) {
2021                                 if (ump->um_quotas[i] != NULLVP)
2022                                         morework = 1;
2023                         }
2024                         UFS_UNLOCK(ump);
2025 #endif
2026                         if (morework) {
2027                                 if (--retry_flush_count > 0) {
2028                                         retry = 1;
2029                                         loopcnt = 3;
2030                                 } else
2031                                         error = EBUSY;
2032                         }
2033                         MNT_IUNLOCK(oldmnt);
2034                         if (retry)
2035                                 goto retry_flush;
2036                 }
2037         }
2038         return (error);
2039 }
2040
2041 /*
2042  * Structure hashing.
2043  * 
2044  * There are four types of structures that can be looked up:
2045  *      1) pagedep structures identified by mount point, inode number,
2046  *         and logical block.
2047  *      2) inodedep structures identified by mount point and inode number.
2048  *      3) newblk structures identified by mount point and
2049  *         physical block number.
2050  *      4) bmsafemap structures identified by mount point and
2051  *         cylinder group number.
2052  *
2053  * The "pagedep" and "inodedep" dependency structures are hashed
2054  * separately from the file blocks and inodes to which they correspond.
2055  * This separation helps when the in-memory copy of an inode or
2056  * file block must be replaced. It also obviates the need to access
2057  * an inode or file page when simply updating (or de-allocating)
2058  * dependency structures. Lookup of newblk structures is needed to
2059  * find newly allocated blocks when trying to associate them with
2060  * their allocdirect or allocindir structure.
2061  *
2062  * The lookup routines optionally create and hash a new instance when
2063  * an existing entry is not found. The bmsafemap lookup routine always
2064  * allocates a new structure if an existing one is not found.
2065  */
2066 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2067
2068 /*
2069  * Structures and routines associated with pagedep caching.
2070  */
2071 #define PAGEDEP_HASH(ump, inum, lbn) \
2072         (&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2073
2074 static int
2075 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2076         struct pagedep_hashhead *pagedephd;
2077         ino_t ino;
2078         ufs_lbn_t lbn;
2079         struct pagedep **pagedeppp;
2080 {
2081         struct pagedep *pagedep;
2082
2083         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2084                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2085                         *pagedeppp = pagedep;
2086                         return (1);
2087                 }
2088         }
2089         *pagedeppp = NULL;
2090         return (0);
2091 }
2092 /*
2093  * Look up a pagedep. Return 1 if found, 0 otherwise.
2094  * If not found, allocate if DEPALLOC flag is passed.
2095  * Found or allocated entry is returned in pagedeppp.
2096  * This routine must be called with splbio interrupts blocked.
2097  */
2098 static int
2099 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2100         struct mount *mp;
2101         struct buf *bp;
2102         ino_t ino;
2103         ufs_lbn_t lbn;
2104         int flags;
2105         struct pagedep **pagedeppp;
2106 {
2107         struct pagedep *pagedep;
2108         struct pagedep_hashhead *pagedephd;
2109         struct worklist *wk;
2110         struct ufsmount *ump;
2111         int ret;
2112         int i;
2113
2114         ump = VFSTOUFS(mp);
2115         LOCK_OWNED(ump);
2116         if (bp) {
2117                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2118                         if (wk->wk_type == D_PAGEDEP) {
2119                                 *pagedeppp = WK_PAGEDEP(wk);
2120                                 return (1);
2121                         }
2122                 }
2123         }
2124         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2125         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2126         if (ret) {
2127                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2128                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2129                 return (1);
2130         }
2131         if ((flags & DEPALLOC) == 0)
2132                 return (0);
2133         FREE_LOCK(ump);
2134         pagedep = malloc(sizeof(struct pagedep),
2135             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2136         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2137         ACQUIRE_LOCK(ump);
2138         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2139         if (*pagedeppp) {
2140                 /*
2141                  * This should never happen since we only create pagedeps
2142                  * with the vnode lock held.  Could be an assert.
2143                  */
2144                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2145                 return (ret);
2146         }
2147         pagedep->pd_ino = ino;
2148         pagedep->pd_lbn = lbn;
2149         LIST_INIT(&pagedep->pd_dirremhd);
2150         LIST_INIT(&pagedep->pd_pendinghd);
2151         for (i = 0; i < DAHASHSZ; i++)
2152                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2153         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2154         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2155         *pagedeppp = pagedep;
2156         return (0);
2157 }
2158
2159 /*
2160  * Structures and routines associated with inodedep caching.
2161  */
2162 #define INODEDEP_HASH(ump, inum) \
2163       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2164
2165 static int
2166 inodedep_find(inodedephd, inum, inodedeppp)
2167         struct inodedep_hashhead *inodedephd;
2168         ino_t inum;
2169         struct inodedep **inodedeppp;
2170 {
2171         struct inodedep *inodedep;
2172
2173         LIST_FOREACH(inodedep, inodedephd, id_hash)
2174                 if (inum == inodedep->id_ino)
2175                         break;
2176         if (inodedep) {
2177                 *inodedeppp = inodedep;
2178                 return (1);
2179         }
2180         *inodedeppp = NULL;
2181
2182         return (0);
2183 }
2184 /*
2185  * Look up an inodedep. Return 1 if found, 0 if not found.
2186  * If not found, allocate if DEPALLOC flag is passed.
2187  * Found or allocated entry is returned in inodedeppp.
2188  * This routine must be called with splbio interrupts blocked.
2189  */
2190 static int
2191 inodedep_lookup(mp, inum, flags, inodedeppp)
2192         struct mount *mp;
2193         ino_t inum;
2194         int flags;
2195         struct inodedep **inodedeppp;
2196 {
2197         struct inodedep *inodedep;
2198         struct inodedep_hashhead *inodedephd;
2199         struct ufsmount *ump;
2200         struct fs *fs;
2201
2202         ump = VFSTOUFS(mp);
2203         LOCK_OWNED(ump);
2204         fs = ump->um_fs;
2205         inodedephd = INODEDEP_HASH(ump, inum);
2206
2207         if (inodedep_find(inodedephd, inum, inodedeppp))
2208                 return (1);
2209         if ((flags & DEPALLOC) == 0)
2210                 return (0);
2211         /*
2212          * If the system is over its limit and our filesystem is
2213          * responsible for more than our share of that usage and
2214          * we are not in a rush, request some inodedep cleanup.
2215          */
2216         if (softdep_excess_items(ump, D_INODEDEP))
2217                 schedule_cleanup(mp);
2218         else
2219                 FREE_LOCK(ump);
2220         inodedep = malloc(sizeof(struct inodedep),
2221                 M_INODEDEP, M_SOFTDEP_FLAGS);
2222         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2223         ACQUIRE_LOCK(ump);
2224         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2225                 WORKITEM_FREE(inodedep, D_INODEDEP);
2226                 return (1);
2227         }
2228         inodedep->id_fs = fs;
2229         inodedep->id_ino = inum;
2230         inodedep->id_state = ALLCOMPLETE;
2231         inodedep->id_nlinkdelta = 0;
2232         inodedep->id_savedino1 = NULL;
2233         inodedep->id_savedsize = -1;
2234         inodedep->id_savedextsize = -1;
2235         inodedep->id_savednlink = -1;
2236         inodedep->id_bmsafemap = NULL;
2237         inodedep->id_mkdiradd = NULL;
2238         LIST_INIT(&inodedep->id_dirremhd);
2239         LIST_INIT(&inodedep->id_pendinghd);
2240         LIST_INIT(&inodedep->id_inowait);
2241         LIST_INIT(&inodedep->id_bufwait);
2242         TAILQ_INIT(&inodedep->id_inoreflst);
2243         TAILQ_INIT(&inodedep->id_inoupdt);
2244         TAILQ_INIT(&inodedep->id_newinoupdt);
2245         TAILQ_INIT(&inodedep->id_extupdt);
2246         TAILQ_INIT(&inodedep->id_newextupdt);
2247         TAILQ_INIT(&inodedep->id_freeblklst);
2248         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2249         *inodedeppp = inodedep;
2250         return (0);
2251 }
2252
2253 /*
2254  * Structures and routines associated with newblk caching.
2255  */
2256 #define NEWBLK_HASH(ump, inum) \
2257         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2258
2259 static int
2260 newblk_find(newblkhd, newblkno, flags, newblkpp)
2261         struct newblk_hashhead *newblkhd;
2262         ufs2_daddr_t newblkno;
2263         int flags;
2264         struct newblk **newblkpp;
2265 {
2266         struct newblk *newblk;
2267
2268         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2269                 if (newblkno != newblk->nb_newblkno)
2270                         continue;
2271                 /*
2272                  * If we're creating a new dependency don't match those that
2273                  * have already been converted to allocdirects.  This is for
2274                  * a frag extend.
2275                  */
2276                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2277                         continue;
2278                 break;
2279         }
2280         if (newblk) {
2281                 *newblkpp = newblk;
2282                 return (1);
2283         }
2284         *newblkpp = NULL;
2285         return (0);
2286 }
2287
2288 /*
2289  * Look up a newblk. Return 1 if found, 0 if not found.
2290  * If not found, allocate if DEPALLOC flag is passed.
2291  * Found or allocated entry is returned in newblkpp.
2292  */
2293 static int
2294 newblk_lookup(mp, newblkno, flags, newblkpp)
2295         struct mount *mp;
2296         ufs2_daddr_t newblkno;
2297         int flags;
2298         struct newblk **newblkpp;
2299 {
2300         struct newblk *newblk;
2301         struct newblk_hashhead *newblkhd;
2302         struct ufsmount *ump;
2303
2304         ump = VFSTOUFS(mp);
2305         LOCK_OWNED(ump);
2306         newblkhd = NEWBLK_HASH(ump, newblkno);
2307         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2308                 return (1);
2309         if ((flags & DEPALLOC) == 0)
2310                 return (0);
2311         if (softdep_excess_items(ump, D_NEWBLK) ||
2312             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2313             softdep_excess_items(ump, D_ALLOCINDIR))
2314                 schedule_cleanup(mp);
2315         else
2316                 FREE_LOCK(ump);
2317         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2318             M_SOFTDEP_FLAGS | M_ZERO);
2319         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2320         ACQUIRE_LOCK(ump);
2321         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2322                 WORKITEM_FREE(newblk, D_NEWBLK);
2323                 return (1);
2324         }
2325         newblk->nb_freefrag = NULL;
2326         LIST_INIT(&newblk->nb_indirdeps);
2327         LIST_INIT(&newblk->nb_newdirblk);
2328         LIST_INIT(&newblk->nb_jwork);
2329         newblk->nb_state = ATTACHED;
2330         newblk->nb_newblkno = newblkno;
2331         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2332         *newblkpp = newblk;
2333         return (0);
2334 }
2335
2336 /*
2337  * Structures and routines associated with freed indirect block caching.
2338  */
2339 #define INDIR_HASH(ump, blkno) \
2340         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2341
2342 /*
2343  * Lookup an indirect block in the indir hash table.  The freework is
2344  * removed and potentially freed.  The caller must do a blocking journal
2345  * write before writing to the blkno.
2346  */
2347 static int
2348 indirblk_lookup(mp, blkno)
2349         struct mount *mp;
2350         ufs2_daddr_t blkno;
2351 {
2352         struct freework *freework;
2353         struct indir_hashhead *wkhd;
2354         struct ufsmount *ump;
2355
2356         ump = VFSTOUFS(mp);
2357         wkhd = INDIR_HASH(ump, blkno);
2358         TAILQ_FOREACH(freework, wkhd, fw_next) {
2359                 if (freework->fw_blkno != blkno)
2360                         continue;
2361                 indirblk_remove(freework);
2362                 return (1);
2363         }
2364         return (0);
2365 }
2366
2367 /*
2368  * Insert an indirect block represented by freework into the indirblk
2369  * hash table so that it may prevent the block from being re-used prior
2370  * to the journal being written.
2371  */
2372 static void
2373 indirblk_insert(freework)
2374         struct freework *freework;
2375 {
2376         struct jblocks *jblocks;
2377         struct jseg *jseg;
2378         struct ufsmount *ump;
2379
2380         ump = VFSTOUFS(freework->fw_list.wk_mp);
2381         jblocks = ump->softdep_jblocks;
2382         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2383         if (jseg == NULL)
2384                 return;
2385         
2386         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2387         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2388             fw_next);
2389         freework->fw_state &= ~DEPCOMPLETE;
2390 }
2391
2392 static void
2393 indirblk_remove(freework)
2394         struct freework *freework;
2395 {
2396         struct ufsmount *ump;
2397
2398         ump = VFSTOUFS(freework->fw_list.wk_mp);
2399         LIST_REMOVE(freework, fw_segs);
2400         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2401         freework->fw_state |= DEPCOMPLETE;
2402         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2403                 WORKITEM_FREE(freework, D_FREEWORK);
2404 }
2405
2406 /*
2407  * Executed during filesystem system initialization before
2408  * mounting any filesystems.
2409  */
2410 void 
2411 softdep_initialize()
2412 {
2413
2414         TAILQ_INIT(&softdepmounts);
2415 #ifdef __LP64__
2416         max_softdeps = desiredvnodes * 4;
2417 #else
2418         max_softdeps = desiredvnodes * 2;
2419 #endif
2420
2421         /* initialise bioops hack */
2422         bioops.io_start = softdep_disk_io_initiation;
2423         bioops.io_complete = softdep_disk_write_complete;
2424         bioops.io_deallocate = softdep_deallocate_dependencies;
2425         bioops.io_countdeps = softdep_count_dependencies;
2426         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2427
2428         /* Initialize the callout with an mtx. */
2429         callout_init_mtx(&softdep_callout, &lk, 0);
2430 }
2431
2432 /*
2433  * Executed after all filesystems have been unmounted during
2434  * filesystem module unload.
2435  */
2436 void
2437 softdep_uninitialize()
2438 {
2439
2440         /* clear bioops hack */
2441         bioops.io_start = NULL;
2442         bioops.io_complete = NULL;
2443         bioops.io_deallocate = NULL;
2444         bioops.io_countdeps = NULL;
2445         softdep_ast_cleanup = NULL;
2446
2447         callout_drain(&softdep_callout);
2448 }
2449
2450 /*
2451  * Called at mount time to notify the dependency code that a
2452  * filesystem wishes to use it.
2453  */
2454 int
2455 softdep_mount(devvp, mp, fs, cred)
2456         struct vnode *devvp;
2457         struct mount *mp;
2458         struct fs *fs;
2459         struct ucred *cred;
2460 {
2461         struct csum_total cstotal;
2462         struct mount_softdeps *sdp;
2463         struct ufsmount *ump;
2464         struct cg *cgp;
2465         struct buf *bp;
2466         int i, error, cyl;
2467
2468         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2469             M_WAITOK | M_ZERO);
2470         MNT_ILOCK(mp);
2471         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2472         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2473                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2474                         MNTK_SOFTDEP | MNTK_NOASYNC;
2475         }
2476         ump = VFSTOUFS(mp);
2477         ump->um_softdep = sdp;
2478         MNT_IUNLOCK(mp);
2479         rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2480         sdp->sd_ump = ump;
2481         LIST_INIT(&ump->softdep_workitem_pending);
2482         LIST_INIT(&ump->softdep_journal_pending);
2483         TAILQ_INIT(&ump->softdep_unlinked);
2484         LIST_INIT(&ump->softdep_dirtycg);
2485         ump->softdep_worklist_tail = NULL;
2486         ump->softdep_on_worklist = 0;
2487         ump->softdep_deps = 0;
2488         LIST_INIT(&ump->softdep_mkdirlisthd);
2489         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2490             &ump->pagedep_hash_size);
2491         ump->pagedep_nextclean = 0;
2492         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2493             &ump->inodedep_hash_size);
2494         ump->inodedep_nextclean = 0;
2495         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2496             &ump->newblk_hash_size);
2497         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2498             &ump->bmsafemap_hash_size);
2499         i = 1 << (ffs(desiredvnodes / 10) - 1);
2500         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2501             M_FREEWORK, M_WAITOK);
2502         ump->indir_hash_size = i - 1;
2503         for (i = 0; i <= ump->indir_hash_size; i++)
2504                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2505         ACQUIRE_GBLLOCK(&lk);
2506         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2507         FREE_GBLLOCK(&lk);
2508         if ((fs->fs_flags & FS_SUJ) &&
2509             (error = journal_mount(mp, fs, cred)) != 0) {
2510                 printf("Failed to start journal: %d\n", error);
2511                 softdep_unmount(mp);
2512                 return (error);
2513         }
2514         /*
2515          * Start our flushing thread in the bufdaemon process.
2516          */
2517         ACQUIRE_LOCK(ump);
2518         ump->softdep_flags |= FLUSH_STARTING;
2519         FREE_LOCK(ump);
2520         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2521             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2522             mp->mnt_stat.f_mntonname);
2523         ACQUIRE_LOCK(ump);
2524         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2525                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2526                     hz / 2);
2527         }
2528         FREE_LOCK(ump);
2529         /*
2530          * When doing soft updates, the counters in the
2531          * superblock may have gotten out of sync. Recomputation
2532          * can take a long time and can be deferred for background
2533          * fsck.  However, the old behavior of scanning the cylinder
2534          * groups and recalculating them at mount time is available
2535          * by setting vfs.ffs.compute_summary_at_mount to one.
2536          */
2537         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2538                 return (0);
2539         bzero(&cstotal, sizeof cstotal);
2540         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2541                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2542                     fs->fs_cgsize, cred, &bp)) != 0) {
2543                         brelse(bp);
2544                         softdep_unmount(mp);
2545                         return (error);
2546                 }
2547                 cgp = (struct cg *)bp->b_data;
2548                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2549                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2550                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2551                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2552                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2553                 brelse(bp);
2554         }
2555 #ifdef DEBUG
2556         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2557                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2558 #endif
2559         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2560         return (0);
2561 }
2562
2563 void
2564 softdep_unmount(mp)
2565         struct mount *mp;
2566 {
2567         struct ufsmount *ump;
2568 #ifdef INVARIANTS
2569         int i;
2570 #endif
2571
2572         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2573             ("softdep_unmount called on non-softdep filesystem"));
2574         ump = VFSTOUFS(mp);
2575         MNT_ILOCK(mp);
2576         mp->mnt_flag &= ~MNT_SOFTDEP;
2577         if (MOUNTEDSUJ(mp) == 0) {
2578                 MNT_IUNLOCK(mp);
2579         } else {
2580                 mp->mnt_flag &= ~MNT_SUJ;
2581                 MNT_IUNLOCK(mp);
2582                 journal_unmount(ump);
2583         }
2584         /*
2585          * Shut down our flushing thread. Check for NULL is if
2586          * softdep_mount errors out before the thread has been created.
2587          */
2588         if (ump->softdep_flushtd != NULL) {
2589                 ACQUIRE_LOCK(ump);
2590                 ump->softdep_flags |= FLUSH_EXIT;
2591                 wakeup(&ump->softdep_flushtd);
2592                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2593                     "sdwait", 0);
2594                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2595                     ("Thread shutdown failed"));
2596         }
2597         /*
2598          * Free up our resources.
2599          */
2600         ACQUIRE_GBLLOCK(&lk);
2601         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2602         FREE_GBLLOCK(&lk);
2603         rw_destroy(LOCK_PTR(ump));
2604         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2605         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2606         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2607         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2608             ump->bmsafemap_hash_size);
2609         free(ump->indir_hashtbl, M_FREEWORK);
2610 #ifdef INVARIANTS
2611         for (i = 0; i <= D_LAST; i++)
2612                 KASSERT(ump->softdep_curdeps[i] == 0,
2613                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2614                     TYPENAME(i), ump->softdep_curdeps[i]));
2615 #endif
2616         free(ump->um_softdep, M_MOUNTDATA);
2617 }
2618
2619 static struct jblocks *
2620 jblocks_create(void)
2621 {
2622         struct jblocks *jblocks;
2623
2624         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2625         TAILQ_INIT(&jblocks->jb_segs);
2626         jblocks->jb_avail = 10;
2627         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2628             M_JBLOCKS, M_WAITOK | M_ZERO);
2629
2630         return (jblocks);
2631 }
2632
2633 static ufs2_daddr_t
2634 jblocks_alloc(jblocks, bytes, actual)
2635         struct jblocks *jblocks;
2636         int bytes;
2637         int *actual;
2638 {
2639         ufs2_daddr_t daddr;
2640         struct jextent *jext;
2641         int freecnt;
2642         int blocks;
2643
2644         blocks = bytes / DEV_BSIZE;
2645         jext = &jblocks->jb_extent[jblocks->jb_head];
2646         freecnt = jext->je_blocks - jblocks->jb_off;
2647         if (freecnt == 0) {
2648                 jblocks->jb_off = 0;
2649                 if (++jblocks->jb_head > jblocks->jb_used)
2650                         jblocks->jb_head = 0;
2651                 jext = &jblocks->jb_extent[jblocks->jb_head];
2652                 freecnt = jext->je_blocks;
2653         }
2654         if (freecnt > blocks)
2655                 freecnt = blocks;
2656         *actual = freecnt * DEV_BSIZE;
2657         daddr = jext->je_daddr + jblocks->jb_off;
2658         jblocks->jb_off += freecnt;
2659         jblocks->jb_free -= freecnt;
2660
2661         return (daddr);
2662 }
2663
2664 static void
2665 jblocks_free(jblocks, mp, bytes)
2666         struct jblocks *jblocks;
2667         struct mount *mp;
2668         int bytes;
2669 {
2670
2671         LOCK_OWNED(VFSTOUFS(mp));
2672         jblocks->jb_free += bytes / DEV_BSIZE;
2673         if (jblocks->jb_suspended)
2674                 worklist_speedup(mp);
2675         wakeup(jblocks);
2676 }
2677
2678 static void
2679 jblocks_destroy(jblocks)
2680         struct jblocks *jblocks;
2681 {
2682
2683         if (jblocks->jb_extent)
2684                 free(jblocks->jb_extent, M_JBLOCKS);
2685         free(jblocks, M_JBLOCKS);
2686 }
2687
2688 static void
2689 jblocks_add(jblocks, daddr, blocks)
2690         struct jblocks *jblocks;
2691         ufs2_daddr_t daddr;
2692         int blocks;
2693 {
2694         struct jextent *jext;
2695
2696         jblocks->jb_blocks += blocks;
2697         jblocks->jb_free += blocks;
2698         jext = &jblocks->jb_extent[jblocks->jb_used];
2699         /* Adding the first block. */
2700         if (jext->je_daddr == 0) {
2701                 jext->je_daddr = daddr;
2702                 jext->je_blocks = blocks;
2703                 return;
2704         }
2705         /* Extending the last extent. */
2706         if (jext->je_daddr + jext->je_blocks == daddr) {
2707                 jext->je_blocks += blocks;
2708                 return;
2709         }
2710         /* Adding a new extent. */
2711         if (++jblocks->jb_used == jblocks->jb_avail) {
2712                 jblocks->jb_avail *= 2;
2713                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2714                     M_JBLOCKS, M_WAITOK | M_ZERO);
2715                 memcpy(jext, jblocks->jb_extent,
2716                     sizeof(struct jextent) * jblocks->jb_used);
2717                 free(jblocks->jb_extent, M_JBLOCKS);
2718                 jblocks->jb_extent = jext;
2719         }
2720         jext = &jblocks->jb_extent[jblocks->jb_used];
2721         jext->je_daddr = daddr;
2722         jext->je_blocks = blocks;
2723         return;
2724 }
2725
2726 int
2727 softdep_journal_lookup(mp, vpp)
2728         struct mount *mp;
2729         struct vnode **vpp;
2730 {
2731         struct componentname cnp;
2732         struct vnode *dvp;
2733         ino_t sujournal;
2734         int error;
2735
2736         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2737         if (error)
2738                 return (error);
2739         bzero(&cnp, sizeof(cnp));
2740         cnp.cn_nameiop = LOOKUP;
2741         cnp.cn_flags = ISLASTCN;
2742         cnp.cn_thread = curthread;
2743         cnp.cn_cred = curthread->td_ucred;
2744         cnp.cn_pnbuf = SUJ_FILE;
2745         cnp.cn_nameptr = SUJ_FILE;
2746         cnp.cn_namelen = strlen(SUJ_FILE);
2747         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2748         vput(dvp);
2749         if (error != 0)
2750                 return (error);
2751         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2752         return (error);
2753 }
2754
2755 /*
2756  * Open and verify the journal file.
2757  */
2758 static int
2759 journal_mount(mp, fs, cred)
2760         struct mount *mp;
2761         struct fs *fs;
2762         struct ucred *cred;
2763 {
2764         struct jblocks *jblocks;
2765         struct ufsmount *ump;
2766         struct vnode *vp;
2767         struct inode *ip;
2768         ufs2_daddr_t blkno;
2769         int bcount;
2770         int error;
2771         int i;
2772
2773         ump = VFSTOUFS(mp);
2774         ump->softdep_journal_tail = NULL;
2775         ump->softdep_on_journal = 0;
2776         ump->softdep_accdeps = 0;
2777         ump->softdep_req = 0;
2778         ump->softdep_jblocks = NULL;
2779         error = softdep_journal_lookup(mp, &vp);
2780         if (error != 0) {
2781                 printf("Failed to find journal.  Use tunefs to create one\n");
2782                 return (error);
2783         }
2784         ip = VTOI(vp);
2785         if (ip->i_size < SUJ_MIN) {
2786                 error = ENOSPC;
2787                 goto out;
2788         }
2789         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2790         jblocks = jblocks_create();
2791         for (i = 0; i < bcount; i++) {
2792                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2793                 if (error)
2794                         break;
2795                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2796         }
2797         if (error) {
2798                 jblocks_destroy(jblocks);
2799                 goto out;
2800         }
2801         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2802         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2803         ump->softdep_jblocks = jblocks;
2804 out:
2805         if (error == 0) {
2806                 MNT_ILOCK(mp);
2807                 mp->mnt_flag |= MNT_SUJ;
2808                 mp->mnt_flag &= ~MNT_SOFTDEP;
2809                 MNT_IUNLOCK(mp);
2810                 /*
2811                  * Only validate the journal contents if the
2812                  * filesystem is clean, otherwise we write the logs
2813                  * but they'll never be used.  If the filesystem was
2814                  * still dirty when we mounted it the journal is
2815                  * invalid and a new journal can only be valid if it
2816                  * starts from a clean mount.
2817                  */
2818                 if (fs->fs_clean) {
2819                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2820                         ip->i_flags |= IN_MODIFIED;
2821                         ffs_update(vp, 1);
2822                 }
2823         }
2824         vput(vp);
2825         return (error);
2826 }
2827
2828 static void
2829 journal_unmount(ump)
2830         struct ufsmount *ump;
2831 {
2832
2833         if (ump->softdep_jblocks)
2834                 jblocks_destroy(ump->softdep_jblocks);
2835         ump->softdep_jblocks = NULL;
2836 }
2837
2838 /*
2839  * Called when a journal record is ready to be written.  Space is allocated
2840  * and the journal entry is created when the journal is flushed to stable
2841  * store.
2842  */
2843 static void
2844 add_to_journal(wk)
2845         struct worklist *wk;
2846 {
2847         struct ufsmount *ump;
2848
2849         ump = VFSTOUFS(wk->wk_mp);
2850         LOCK_OWNED(ump);
2851         if (wk->wk_state & ONWORKLIST)
2852                 panic("add_to_journal: %s(0x%X) already on list",
2853                     TYPENAME(wk->wk_type), wk->wk_state);
2854         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2855         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2856                 ump->softdep_jblocks->jb_age = ticks;
2857                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2858         } else
2859                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2860         ump->softdep_journal_tail = wk;
2861         ump->softdep_on_journal += 1;
2862 }
2863
2864 /*
2865  * Remove an arbitrary item for the journal worklist maintain the tail
2866  * pointer.  This happens when a new operation obviates the need to
2867  * journal an old operation.
2868  */
2869 static void
2870 remove_from_journal(wk)
2871         struct worklist *wk;
2872 {
2873         struct ufsmount *ump;
2874
2875         ump = VFSTOUFS(wk->wk_mp);
2876         LOCK_OWNED(ump);
2877 #ifdef SUJ_DEBUG
2878         {
2879                 struct worklist *wkn;
2880
2881                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2882                         if (wkn == wk)
2883                                 break;
2884                 if (wkn == NULL)
2885                         panic("remove_from_journal: %p is not in journal", wk);
2886         }
2887 #endif
2888         /*
2889          * We emulate a TAILQ to save space in most structures which do not
2890          * require TAILQ semantics.  Here we must update the tail position
2891          * when removing the tail which is not the final entry. This works
2892          * only if the worklist linkage are at the beginning of the structure.
2893          */
2894         if (ump->softdep_journal_tail == wk)
2895                 ump->softdep_journal_tail =
2896                     (struct worklist *)wk->wk_list.le_prev;
2897
2898         WORKLIST_REMOVE(wk);
2899         ump->softdep_on_journal -= 1;
2900 }
2901
2902 /*
2903  * Check for journal space as well as dependency limits so the prelink
2904  * code can throttle both journaled and non-journaled filesystems.
2905  * Threshold is 0 for low and 1 for min.
2906  */
2907 static int
2908 journal_space(ump, thresh)
2909         struct ufsmount *ump;
2910         int thresh;
2911 {
2912         struct jblocks *jblocks;
2913         int limit, avail;
2914
2915         jblocks = ump->softdep_jblocks;
2916         if (jblocks == NULL)
2917                 return (1);
2918         /*
2919          * We use a tighter restriction here to prevent request_cleanup()
2920          * running in threads from running into locks we currently hold.
2921          * We have to be over the limit and our filesystem has to be
2922          * responsible for more than our share of that usage.
2923          */
2924         limit = (max_softdeps / 10) * 9;
2925         if (dep_current[D_INODEDEP] > limit &&
2926             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2927                 return (0);
2928         if (thresh)
2929                 thresh = jblocks->jb_min;
2930         else
2931                 thresh = jblocks->jb_low;
2932         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2933         avail = jblocks->jb_free - avail;
2934
2935         return (avail > thresh);
2936 }
2937
2938 static void
2939 journal_suspend(ump)
2940         struct ufsmount *ump;
2941 {
2942         struct jblocks *jblocks;
2943         struct mount *mp;
2944
2945         mp = UFSTOVFS(ump);
2946         jblocks = ump->softdep_jblocks;
2947         MNT_ILOCK(mp);
2948         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2949                 stat_journal_min++;
2950                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2951                 mp->mnt_susp_owner = ump->softdep_flushtd;
2952         }
2953         jblocks->jb_suspended = 1;
2954         MNT_IUNLOCK(mp);
2955 }
2956
2957 static int
2958 journal_unsuspend(struct ufsmount *ump)
2959 {
2960         struct jblocks *jblocks;
2961         struct mount *mp;
2962
2963         mp = UFSTOVFS(ump);
2964         jblocks = ump->softdep_jblocks;
2965
2966         if (jblocks != NULL && jblocks->jb_suspended &&
2967             journal_space(ump, jblocks->jb_min)) {
2968                 jblocks->jb_suspended = 0;
2969                 FREE_LOCK(ump);
2970                 mp->mnt_susp_owner = curthread;
2971                 vfs_write_resume(mp, 0);
2972                 ACQUIRE_LOCK(ump);
2973                 return (1);
2974         }
2975         return (0);
2976 }
2977
2978 /*
2979  * Called before any allocation function to be certain that there is
2980  * sufficient space in the journal prior to creating any new records.
2981  * Since in the case of block allocation we may have multiple locked
2982  * buffers at the time of the actual allocation we can not block
2983  * when the journal records are created.  Doing so would create a deadlock
2984  * if any of these buffers needed to be flushed to reclaim space.  Instead
2985  * we require a sufficiently large amount of available space such that
2986  * each thread in the system could have passed this allocation check and
2987  * still have sufficient free space.  With 20% of a minimum journal size
2988  * of 1MB we have 6553 records available.
2989  */
2990 int
2991 softdep_prealloc(vp, waitok)
2992         struct vnode *vp;
2993         int waitok;
2994 {
2995         struct ufsmount *ump;
2996
2997         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2998             ("softdep_prealloc called on non-softdep filesystem"));
2999         /*
3000          * Nothing to do if we are not running journaled soft updates.
3001          * If we currently hold the snapshot lock, we must avoid
3002          * handling other resources that could cause deadlock.  Do not
3003          * touch quotas vnode since it is typically recursed with
3004          * other vnode locks held.
3005          */
3006         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3007             (vp->v_vflag & VV_SYSTEM) != 0)
3008                 return (0);
3009         ump = VFSTOUFS(vp->v_mount);
3010         ACQUIRE_LOCK(ump);
3011         if (journal_space(ump, 0)) {
3012                 FREE_LOCK(ump);
3013                 return (0);
3014         }
3015         stat_journal_low++;
3016         FREE_LOCK(ump);
3017         if (waitok == MNT_NOWAIT)
3018                 return (ENOSPC);
3019         /*
3020          * Attempt to sync this vnode once to flush any journal
3021          * work attached to it.
3022          */
3023         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3024                 ffs_syncvnode(vp, waitok, 0);
3025         ACQUIRE_LOCK(ump);
3026         process_removes(vp);
3027         process_truncates(vp);
3028         if (journal_space(ump, 0) == 0) {
3029                 softdep_speedup(ump);
3030                 if (journal_space(ump, 1) == 0)
3031                         journal_suspend(ump);
3032         }
3033         FREE_LOCK(ump);
3034
3035         return (0);
3036 }
3037
3038 /*
3039  * Before adjusting a link count on a vnode verify that we have sufficient
3040  * journal space.  If not, process operations that depend on the currently
3041  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3042  * and softdep flush threads can not acquire these locks to reclaim space.
3043  */
3044 static void
3045 softdep_prelink(dvp, vp)
3046         struct vnode *dvp;
3047         struct vnode *vp;
3048 {
3049         struct ufsmount *ump;
3050
3051         ump = VFSTOUFS(dvp->v_mount);
3052         LOCK_OWNED(ump);
3053         /*
3054          * Nothing to do if we have sufficient journal space.
3055          * If we currently hold the snapshot lock, we must avoid
3056          * handling other resources that could cause deadlock.
3057          */
3058         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3059                 return;
3060         stat_journal_low++;
3061         FREE_LOCK(ump);
3062         if (vp)
3063                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3064         ffs_syncvnode(dvp, MNT_WAIT, 0);
3065         ACQUIRE_LOCK(ump);
3066         /* Process vp before dvp as it may create .. removes. */
3067         if (vp) {
3068                 process_removes(vp);
3069                 process_truncates(vp);
3070         }
3071         process_removes(dvp);
3072         process_truncates(dvp);
3073         softdep_speedup(ump);
3074         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3075         if (journal_space(ump, 0) == 0) {
3076                 softdep_speedup(ump);
3077                 if (journal_space(ump, 1) == 0)
3078                         journal_suspend(ump);
3079         }
3080 }
3081
3082 static void
3083 jseg_write(ump, jseg, data)
3084         struct ufsmount *ump;
3085         struct jseg *jseg;
3086         uint8_t *data;
3087 {
3088         struct jsegrec *rec;
3089
3090         rec = (struct jsegrec *)data;
3091         rec->jsr_seq = jseg->js_seq;
3092         rec->jsr_oldest = jseg->js_oldseq;
3093         rec->jsr_cnt = jseg->js_cnt;
3094         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3095         rec->jsr_crc = 0;
3096         rec->jsr_time = ump->um_fs->fs_mtime;
3097 }
3098
3099 static inline void
3100 inoref_write(inoref, jseg, rec)
3101         struct inoref *inoref;
3102         struct jseg *jseg;
3103         struct jrefrec *rec;
3104 {
3105
3106         inoref->if_jsegdep->jd_seg = jseg;
3107         rec->jr_ino = inoref->if_ino;
3108         rec->jr_parent = inoref->if_parent;
3109         rec->jr_nlink = inoref->if_nlink;
3110         rec->jr_mode = inoref->if_mode;
3111         rec->jr_diroff = inoref->if_diroff;
3112 }
3113
3114 static void
3115 jaddref_write(jaddref, jseg, data)
3116         struct jaddref *jaddref;
3117         struct jseg *jseg;
3118         uint8_t *data;
3119 {
3120         struct jrefrec *rec;
3121
3122         rec = (struct jrefrec *)data;
3123         rec->jr_op = JOP_ADDREF;
3124         inoref_write(&jaddref->ja_ref, jseg, rec);
3125 }
3126
3127 static void
3128 jremref_write(jremref, jseg, data)
3129         struct jremref *jremref;
3130         struct jseg *jseg;
3131         uint8_t *data;
3132 {
3133         struct jrefrec *rec;
3134
3135         rec = (struct jrefrec *)data;
3136         rec->jr_op = JOP_REMREF;
3137         inoref_write(&jremref->jr_ref, jseg, rec);
3138 }
3139
3140 static void
3141 jmvref_write(jmvref, jseg, data)
3142         struct jmvref *jmvref;
3143         struct jseg *jseg;
3144         uint8_t *data;
3145 {
3146         struct jmvrec *rec;
3147
3148         rec = (struct jmvrec *)data;
3149         rec->jm_op = JOP_MVREF;
3150         rec->jm_ino = jmvref->jm_ino;
3151         rec->jm_parent = jmvref->jm_parent;
3152         rec->jm_oldoff = jmvref->jm_oldoff;
3153         rec->jm_newoff = jmvref->jm_newoff;
3154 }
3155
3156 static void
3157 jnewblk_write(jnewblk, jseg, data)
3158         struct jnewblk *jnewblk;
3159         struct jseg *jseg;
3160         uint8_t *data;
3161 {
3162         struct jblkrec *rec;
3163
3164         jnewblk->jn_jsegdep->jd_seg = jseg;
3165         rec = (struct jblkrec *)data;
3166         rec->jb_op = JOP_NEWBLK;
3167         rec->jb_ino = jnewblk->jn_ino;
3168         rec->jb_blkno = jnewblk->jn_blkno;
3169         rec->jb_lbn = jnewblk->jn_lbn;
3170         rec->jb_frags = jnewblk->jn_frags;
3171         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3172 }
3173
3174 static void
3175 jfreeblk_write(jfreeblk, jseg, data)
3176         struct jfreeblk *jfreeblk;
3177         struct jseg *jseg;
3178         uint8_t *data;
3179 {
3180         struct jblkrec *rec;
3181
3182         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3183         rec = (struct jblkrec *)data;
3184         rec->jb_op = JOP_FREEBLK;
3185         rec->jb_ino = jfreeblk->jf_ino;
3186         rec->jb_blkno = jfreeblk->jf_blkno;
3187         rec->jb_lbn = jfreeblk->jf_lbn;
3188         rec->jb_frags = jfreeblk->jf_frags;
3189         rec->jb_oldfrags = 0;
3190 }
3191
3192 static void
3193 jfreefrag_write(jfreefrag, jseg, data)
3194         struct jfreefrag *jfreefrag;
3195         struct jseg *jseg;
3196         uint8_t *data;
3197 {
3198         struct jblkrec *rec;
3199
3200         jfreefrag->fr_jsegdep->jd_seg = jseg;
3201         rec = (struct jblkrec *)data;
3202         rec->jb_op = JOP_FREEBLK;
3203         rec->jb_ino = jfreefrag->fr_ino;
3204         rec->jb_blkno = jfreefrag->fr_blkno;
3205         rec->jb_lbn = jfreefrag->fr_lbn;
3206         rec->jb_frags = jfreefrag->fr_frags;
3207         rec->jb_oldfrags = 0;
3208 }
3209
3210 static void
3211 jtrunc_write(jtrunc, jseg, data)
3212         struct jtrunc *jtrunc;
3213         struct jseg *jseg;
3214         uint8_t *data;
3215 {
3216         struct jtrncrec *rec;
3217
3218         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3219         rec = (struct jtrncrec *)data;
3220         rec->jt_op = JOP_TRUNC;
3221         rec->jt_ino = jtrunc->jt_ino;
3222         rec->jt_size = jtrunc->jt_size;
3223         rec->jt_extsize = jtrunc->jt_extsize;
3224 }
3225
3226 static void
3227 jfsync_write(jfsync, jseg, data)
3228         struct jfsync *jfsync;
3229         struct jseg *jseg;
3230         uint8_t *data;
3231 {
3232         struct jtrncrec *rec;
3233
3234         rec = (struct jtrncrec *)data;
3235         rec->jt_op = JOP_SYNC;
3236         rec->jt_ino = jfsync->jfs_ino;
3237         rec->jt_size = jfsync->jfs_size;
3238         rec->jt_extsize = jfsync->jfs_extsize;
3239 }
3240
3241 static void
3242 softdep_flushjournal(mp)
3243         struct mount *mp;
3244 {
3245         struct jblocks *jblocks;
3246         struct ufsmount *ump;
3247
3248         if (MOUNTEDSUJ(mp) == 0)
3249                 return;
3250         ump = VFSTOUFS(mp);
3251         jblocks = ump->softdep_jblocks;
3252         ACQUIRE_LOCK(ump);
3253         while (ump->softdep_on_journal) {
3254                 jblocks->jb_needseg = 1;
3255                 softdep_process_journal(mp, NULL, MNT_WAIT);
3256         }
3257         FREE_LOCK(ump);
3258 }
3259
3260 static void softdep_synchronize_completed(struct bio *);
3261 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3262
3263 static void
3264 softdep_synchronize_completed(bp)
3265         struct bio *bp;
3266 {
3267         struct jseg *oldest;
3268         struct jseg *jseg;
3269         struct ufsmount *ump;
3270
3271         /*
3272          * caller1 marks the last segment written before we issued the
3273          * synchronize cache.
3274          */
3275         jseg = bp->bio_caller1;
3276         if (jseg == NULL) {
3277                 g_destroy_bio(bp);
3278                 return;
3279         }
3280         ump = VFSTOUFS(jseg->js_list.wk_mp);
3281         ACQUIRE_LOCK(ump);
3282         oldest = NULL;
3283         /*
3284          * Mark all the journal entries waiting on the synchronize cache
3285          * as completed so they may continue on.
3286          */
3287         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3288                 jseg->js_state |= COMPLETE;
3289                 oldest = jseg;
3290                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3291         }
3292         /*
3293          * Restart deferred journal entry processing from the oldest
3294          * completed jseg.
3295          */
3296         if (oldest)
3297                 complete_jsegs(oldest);
3298
3299         FREE_LOCK(ump);
3300         g_destroy_bio(bp);
3301 }
3302
3303 /*
3304  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3305  * barriers.  The journal must be written prior to any blocks that depend
3306  * on it and the journal can not be released until the blocks have be
3307  * written.  This code handles both barriers simultaneously.
3308  */
3309 static void
3310 softdep_synchronize(bp, ump, caller1)
3311         struct bio *bp;
3312         struct ufsmount *ump;
3313         void *caller1;
3314 {
3315
3316         bp->bio_cmd = BIO_FLUSH;
3317         bp->bio_flags |= BIO_ORDERED;
3318         bp->bio_data = NULL;
3319         bp->bio_offset = ump->um_cp->provider->mediasize;
3320         bp->bio_length = 0;
3321         bp->bio_done = softdep_synchronize_completed;
3322         bp->bio_caller1 = caller1;
3323         g_io_request(bp,
3324             (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3325 }
3326
3327 /*
3328  * Flush some journal records to disk.
3329  */
3330 static void
3331 softdep_process_journal(mp, needwk, flags)
3332         struct mount *mp;
3333         struct worklist *needwk;
3334         int flags;
3335 {
3336         struct jblocks *jblocks;
3337         struct ufsmount *ump;
3338         struct worklist *wk;
3339         struct jseg *jseg;
3340         struct buf *bp;
3341         struct bio *bio;
3342         uint8_t *data;
3343         struct fs *fs;
3344         int shouldflush;
3345         int segwritten;
3346         int jrecmin;    /* Minimum records per block. */
3347         int jrecmax;    /* Maximum records per block. */
3348         int size;
3349         int cnt;
3350         int off;
3351         int devbsize;
3352
3353         if (MOUNTEDSUJ(mp) == 0)
3354                 return;
3355         shouldflush = softdep_flushcache;
3356         bio = NULL;
3357         jseg = NULL;
3358         ump = VFSTOUFS(mp);
3359         LOCK_OWNED(ump);
3360         fs = ump->um_fs;
3361         jblocks = ump->softdep_jblocks;
3362         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3363         /*
3364          * We write anywhere between a disk block and fs block.  The upper
3365          * bound is picked to prevent buffer cache fragmentation and limit
3366          * processing time per I/O.
3367          */
3368         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3369         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3370         segwritten = 0;
3371         for (;;) {
3372                 cnt = ump->softdep_on_journal;
3373                 /*
3374                  * Criteria for writing a segment:
3375                  * 1) We have a full block.
3376                  * 2) We're called from jwait() and haven't found the
3377                  *    journal item yet.
3378                  * 3) Always write if needseg is set.
3379                  * 4) If we are called from process_worklist and have
3380                  *    not yet written anything we write a partial block
3381                  *    to enforce a 1 second maximum latency on journal
3382                  *    entries.
3383                  */
3384                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3385                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3386                         break;
3387                 cnt++;
3388                 /*
3389                  * Verify some free journal space.  softdep_prealloc() should
3390                  * guarantee that we don't run out so this is indicative of
3391                  * a problem with the flow control.  Try to recover
3392                  * gracefully in any event.
3393                  */
3394                 while (jblocks->jb_free == 0) {
3395                         if (flags != MNT_WAIT)
3396                                 break;
3397                         printf("softdep: Out of journal space!\n");
3398                         softdep_speedup(ump);
3399                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3400                 }
3401                 FREE_LOCK(ump);
3402                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3403                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3404                 LIST_INIT(&jseg->js_entries);
3405                 LIST_INIT(&jseg->js_indirs);
3406                 jseg->js_state = ATTACHED;
3407                 if (shouldflush == 0)
3408                         jseg->js_state |= COMPLETE;
3409                 else if (bio == NULL)
3410                         bio = g_alloc_bio();
3411                 jseg->js_jblocks = jblocks;
3412                 bp = geteblk(fs->fs_bsize, 0);
3413                 ACQUIRE_LOCK(ump);
3414                 /*
3415                  * If there was a race while we were allocating the block
3416                  * and jseg the entry we care about was likely written.
3417                  * We bail out in both the WAIT and NOWAIT case and assume
3418                  * the caller will loop if the entry it cares about is
3419                  * not written.
3420                  */
3421                 cnt = ump->softdep_on_journal;
3422                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3423                         bp->b_flags |= B_INVAL | B_NOCACHE;
3424                         WORKITEM_FREE(jseg, D_JSEG);
3425                         FREE_LOCK(ump);
3426                         brelse(bp);
3427                         ACQUIRE_LOCK(ump);
3428                         break;
3429                 }
3430                 /*
3431                  * Calculate the disk block size required for the available
3432                  * records rounded to the min size.
3433                  */
3434                 if (cnt == 0)
3435                         size = devbsize;
3436                 else if (cnt < jrecmax)
3437                         size = howmany(cnt, jrecmin) * devbsize;
3438                 else
3439                         size = fs->fs_bsize;
3440                 /*
3441                  * Allocate a disk block for this journal data and account
3442                  * for truncation of the requested size if enough contiguous
3443                  * space was not available.
3444                  */
3445                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3446                 bp->b_lblkno = bp->b_blkno;
3447                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3448                 bp->b_bcount = size;
3449                 bp->b_flags &= ~B_INVAL;
3450                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3451                 /*
3452                  * Initialize our jseg with cnt records.  Assign the next
3453                  * sequence number to it and link it in-order.
3454                  */
3455                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3456                 jseg->js_buf = bp;
3457                 jseg->js_cnt = cnt;
3458                 jseg->js_refs = cnt + 1;        /* Self ref. */
3459                 jseg->js_size = size;
3460                 jseg->js_seq = jblocks->jb_nextseq++;
3461                 if (jblocks->jb_oldestseg == NULL)
3462                         jblocks->jb_oldestseg = jseg;
3463                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3464                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3465                 if (jblocks->jb_writeseg == NULL)
3466                         jblocks->jb_writeseg = jseg;
3467                 /*
3468                  * Start filling in records from the pending list.
3469                  */
3470                 data = bp->b_data;
3471                 off = 0;
3472
3473                 /*
3474                  * Always put a header on the first block.
3475                  * XXX As with below, there might not be a chance to get
3476                  * into the loop.  Ensure that something valid is written.
3477                  */
3478                 jseg_write(ump, jseg, data);
3479                 off += JREC_SIZE;
3480                 data = bp->b_data + off;
3481
3482                 /*
3483                  * XXX Something is wrong here.  There's no work to do,
3484                  * but we need to perform and I/O and allow it to complete
3485                  * anyways.
3486                  */
3487                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3488                         stat_emptyjblocks++;
3489
3490                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3491                     != NULL) {
3492                         if (cnt == 0)
3493                                 break;
3494                         /* Place a segment header on every device block. */
3495                         if ((off % devbsize) == 0) {
3496                                 jseg_write(ump, jseg, data);
3497                                 off += JREC_SIZE;
3498                                 data = bp->b_data + off;
3499                         }
3500                         if (wk == needwk)
3501                                 needwk = NULL;
3502                         remove_from_journal(wk);
3503                         wk->wk_state |= INPROGRESS;
3504                         WORKLIST_INSERT(&jseg->js_entries, wk);
3505                         switch (wk->wk_type) {
3506                         case D_JADDREF:
3507                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3508                                 break;
3509                         case D_JREMREF:
3510                                 jremref_write(WK_JREMREF(wk), jseg, data);
3511                                 break;
3512                         case D_JMVREF:
3513                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3514                                 break;
3515                         case D_JNEWBLK:
3516                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3517                                 break;
3518                         case D_JFREEBLK:
3519                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3520                                 break;
3521                         case D_JFREEFRAG:
3522                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3523                                 break;
3524                         case D_JTRUNC:
3525                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3526                                 break;
3527                         case D_JFSYNC:
3528                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3529                                 break;
3530                         default:
3531                                 panic("process_journal: Unknown type %s",
3532                                     TYPENAME(wk->wk_type));
3533                                 /* NOTREACHED */
3534                         }
3535                         off += JREC_SIZE;
3536                         data = bp->b_data + off;
3537                         cnt--;
3538                 }
3539
3540                 /* Clear any remaining space so we don't leak kernel data */
3541                 if (size > off)
3542                         bzero(data, size - off);
3543
3544                 /*
3545                  * Write this one buffer and continue.
3546                  */
3547                 segwritten = 1;
3548                 jblocks->jb_needseg = 0;
3549                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3550                 FREE_LOCK(ump);
3551                 pbgetvp(ump->um_devvp, bp);
3552                 /*
3553                  * We only do the blocking wait once we find the journal
3554                  * entry we're looking for.
3555                  */
3556                 if (needwk == NULL && flags == MNT_WAIT)
3557                         bwrite(bp);
3558                 else
3559                         bawrite(bp);
3560                 ACQUIRE_LOCK(ump);
3561         }
3562         /*
3563          * If we wrote a segment issue a synchronize cache so the journal
3564          * is reflected on disk before the data is written.  Since reclaiming
3565          * journal space also requires writing a journal record this
3566          * process also enforces a barrier before reclamation.
3567          */
3568         if (segwritten && shouldflush) {
3569                 softdep_synchronize(bio, ump, 
3570                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3571         } else if (bio)
3572                 g_destroy_bio(bio);
3573         /*
3574          * If we've suspended the filesystem because we ran out of journal
3575          * space either try to sync it here to make some progress or
3576          * unsuspend it if we already have.
3577          */
3578         if (flags == 0 && jblocks->jb_suspended) {
3579                 if (journal_unsuspend(ump))
3580                         return;
3581                 FREE_LOCK(ump);
3582                 VFS_SYNC(mp, MNT_NOWAIT);
3583                 ffs_sbupdate(ump, MNT_WAIT, 0);
3584                 ACQUIRE_LOCK(ump);
3585         }
3586 }
3587
3588 /*
3589  * Complete a jseg, allowing all dependencies awaiting journal writes
3590  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3591  * structures so that the journal segment can be freed to reclaim space.
3592  */
3593 static void
3594 complete_jseg(jseg)
3595         struct jseg *jseg;
3596 {
3597         struct worklist *wk;
3598         struct jmvref *jmvref;
3599 #ifdef INVARIANTS
3600         int i = 0;
3601 #endif
3602
3603         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3604                 WORKLIST_REMOVE(wk);
3605                 wk->wk_state &= ~INPROGRESS;
3606                 wk->wk_state |= COMPLETE;
3607                 KASSERT(i++ < jseg->js_cnt,
3608                     ("handle_written_jseg: overflow %d >= %d",
3609                     i - 1, jseg->js_cnt));
3610                 switch (wk->wk_type) {
3611                 case D_JADDREF:
3612                         handle_written_jaddref(WK_JADDREF(wk));
3613                         break;
3614                 case D_JREMREF:
3615                         handle_written_jremref(WK_JREMREF(wk));
3616                         break;
3617                 case D_JMVREF:
3618                         rele_jseg(jseg);        /* No jsegdep. */
3619                         jmvref = WK_JMVREF(wk);
3620                         LIST_REMOVE(jmvref, jm_deps);
3621                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3622                                 free_pagedep(jmvref->jm_pagedep);
3623                         WORKITEM_FREE(jmvref, D_JMVREF);
3624                         break;
3625                 case D_JNEWBLK:
3626                         handle_written_jnewblk(WK_JNEWBLK(wk));
3627                         break;
3628                 case D_JFREEBLK:
3629                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3630                         break;
3631                 case D_JTRUNC:
3632                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3633                         break;
3634                 case D_JFSYNC:
3635                         rele_jseg(jseg);        /* No jsegdep. */
3636                         WORKITEM_FREE(wk, D_JFSYNC);
3637                         break;
3638                 case D_JFREEFRAG:
3639                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3640                         break;
3641                 default:
3642                         panic("handle_written_jseg: Unknown type %s",
3643                             TYPENAME(wk->wk_type));
3644                         /* NOTREACHED */
3645                 }
3646         }
3647         /* Release the self reference so the structure may be freed. */
3648         rele_jseg(jseg);
3649 }
3650
3651 /*
3652  * Determine which jsegs are ready for completion processing.  Waits for
3653  * synchronize cache to complete as well as forcing in-order completion
3654  * of journal entries.
3655  */
3656 static void
3657 complete_jsegs(jseg)
3658         struct jseg *jseg;
3659 {
3660         struct jblocks *jblocks;
3661         struct jseg *jsegn;
3662
3663         jblocks = jseg->js_jblocks;
3664         /*
3665          * Don't allow out of order completions.  If this isn't the first
3666          * block wait for it to write before we're done.
3667          */
3668         if (jseg != jblocks->jb_writeseg)
3669                 return;
3670         /* Iterate through available jsegs processing their entries. */
3671         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3672                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3673                 jsegn = TAILQ_NEXT(jseg, js_next);
3674                 complete_jseg(jseg);
3675                 jseg = jsegn;
3676         }
3677         jblocks->jb_writeseg = jseg;
3678         /*
3679          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3680          */
3681         free_jsegs(jblocks);
3682 }
3683
3684 /*
3685  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3686  * the final completions.
3687  */
3688 static void
3689 handle_written_jseg(jseg, bp)
3690         struct jseg *jseg;
3691         struct buf *bp;
3692 {
3693
3694         if (jseg->js_refs == 0)
3695                 panic("handle_written_jseg: No self-reference on %p", jseg);
3696         jseg->js_state |= DEPCOMPLETE;
3697         /*
3698          * We'll never need this buffer again, set flags so it will be
3699          * discarded.
3700          */
3701         bp->b_flags |= B_INVAL | B_NOCACHE;
3702         pbrelvp(bp);
3703         complete_jsegs(jseg);
3704 }
3705
3706 static inline struct jsegdep *
3707 inoref_jseg(inoref)
3708         struct inoref *inoref;
3709 {
3710         struct jsegdep *jsegdep;
3711
3712         jsegdep = inoref->if_jsegdep;
3713         inoref->if_jsegdep = NULL;
3714
3715         return (jsegdep);
3716 }
3717
3718 /*
3719  * Called once a jremref has made it to stable store.  The jremref is marked
3720  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3721  * for the jremref to complete will be awoken by free_jremref.
3722  */
3723 static void
3724 handle_written_jremref(jremref)
3725         struct jremref *jremref;
3726 {
3727         struct inodedep *inodedep;
3728         struct jsegdep *jsegdep;
3729         struct dirrem *dirrem;
3730
3731         /* Grab the jsegdep. */
3732         jsegdep = inoref_jseg(&jremref->jr_ref);
3733         /*
3734          * Remove us from the inoref list.
3735          */
3736         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3737             0, &inodedep) == 0)
3738                 panic("handle_written_jremref: Lost inodedep");
3739         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3740         /*
3741          * Complete the dirrem.
3742          */
3743         dirrem = jremref->jr_dirrem;
3744         jremref->jr_dirrem = NULL;
3745         LIST_REMOVE(jremref, jr_deps);
3746         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3747         jwork_insert(&dirrem->dm_jwork, jsegdep);
3748         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3749             (dirrem->dm_state & COMPLETE) != 0)
3750                 add_to_worklist(&dirrem->dm_list, 0);
3751         free_jremref(jremref);
3752 }
3753
3754 /*
3755  * Called once a jaddref has made it to stable store.  The dependency is
3756  * marked complete and any dependent structures are added to the inode
3757  * bufwait list to be completed as soon as it is written.  If a bitmap write
3758  * depends on this entry we move the inode into the inodedephd of the
3759  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3760  */
3761 static void
3762 handle_written_jaddref(jaddref)
3763         struct jaddref *jaddref;
3764 {
3765         struct jsegdep *jsegdep;
3766         struct inodedep *inodedep;
3767         struct diradd *diradd;
3768         struct mkdir *mkdir;
3769
3770         /* Grab the jsegdep. */
3771         jsegdep = inoref_jseg(&jaddref->ja_ref);
3772         mkdir = NULL;
3773         diradd = NULL;
3774         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3775             0, &inodedep) == 0)
3776                 panic("handle_written_jaddref: Lost inodedep.");
3777         if (jaddref->ja_diradd == NULL)
3778                 panic("handle_written_jaddref: No dependency");
3779         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3780                 diradd = jaddref->ja_diradd;
3781                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3782         } else if (jaddref->ja_state & MKDIR_PARENT) {
3783                 mkdir = jaddref->ja_mkdir;
3784                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3785         } else if (jaddref->ja_state & MKDIR_BODY)
3786                 mkdir = jaddref->ja_mkdir;
3787         else
3788                 panic("handle_written_jaddref: Unknown dependency %p",
3789                     jaddref->ja_diradd);
3790         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3791         /*
3792          * Remove us from the inode list.
3793          */
3794         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3795         /*
3796          * The mkdir may be waiting on the jaddref to clear before freeing.
3797          */
3798         if (mkdir) {
3799                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3800                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3801                     TYPENAME(mkdir->md_list.wk_type)));
3802                 mkdir->md_jaddref = NULL;
3803                 diradd = mkdir->md_diradd;
3804                 mkdir->md_state |= DEPCOMPLETE;
3805                 complete_mkdir(mkdir);
3806         }
3807         jwork_insert(&diradd->da_jwork, jsegdep);
3808         if (jaddref->ja_state & NEWBLOCK) {
3809                 inodedep->id_state |= ONDEPLIST;
3810                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3811                     inodedep, id_deps);
3812         }
3813         free_jaddref(jaddref);
3814 }
3815
3816 /*
3817  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3818  * is placed in the bmsafemap to await notification of a written bitmap.  If
3819  * the operation was canceled we add the segdep to the appropriate
3820  * dependency to free the journal space once the canceling operation
3821  * completes.
3822  */
3823 static void
3824 handle_written_jnewblk(jnewblk)
3825         struct jnewblk *jnewblk;
3826 {
3827         struct bmsafemap *bmsafemap;
3828         struct freefrag *freefrag;
3829         struct freework *freework;
3830         struct jsegdep *jsegdep;
3831         struct newblk *newblk;
3832
3833         /* Grab the jsegdep. */
3834         jsegdep = jnewblk->jn_jsegdep;
3835         jnewblk->jn_jsegdep = NULL;
3836         if (jnewblk->jn_dep == NULL) 
3837                 panic("handle_written_jnewblk: No dependency for the segdep.");
3838         switch (jnewblk->jn_dep->wk_type) {
3839         case D_NEWBLK:
3840         case D_ALLOCDIRECT:
3841         case D_ALLOCINDIR:
3842                 /*
3843                  * Add the written block to the bmsafemap so it can
3844                  * be notified when the bitmap is on disk.
3845                  */
3846                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3847                 newblk->nb_jnewblk = NULL;
3848                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3849                         bmsafemap = newblk->nb_bmsafemap;
3850                         newblk->nb_state |= ONDEPLIST;
3851                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3852                             nb_deps);
3853                 }
3854                 jwork_insert(&newblk->nb_jwork, jsegdep);
3855                 break;
3856         case D_FREEFRAG:
3857                 /*
3858                  * A newblock being removed by a freefrag when replaced by
3859                  * frag extension.
3860                  */
3861                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3862                 freefrag->ff_jdep = NULL;
3863                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3864                 break;
3865         case D_FREEWORK:
3866                 /*
3867                  * A direct block was removed by truncate.
3868                  */
3869                 freework = WK_FREEWORK(jnewblk->jn_dep);
3870                 freework->fw_jnewblk = NULL;
3871                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3872                 break;
3873         default:
3874                 panic("handle_written_jnewblk: Unknown type %d.",
3875                     jnewblk->jn_dep->wk_type);
3876         }
3877         jnewblk->jn_dep = NULL;
3878         free_jnewblk(jnewblk);
3879 }
3880
3881 /*
3882  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3883  * an in-flight allocation that has not yet been committed.  Divorce us
3884  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3885  * to the worklist.
3886  */
3887 static void
3888 cancel_jfreefrag(jfreefrag)
3889         struct jfreefrag *jfreefrag;
3890 {
3891         struct freefrag *freefrag;
3892
3893         if (jfreefrag->fr_jsegdep) {
3894                 free_jsegdep(jfreefrag->fr_jsegdep);
3895                 jfreefrag->fr_jsegdep = NULL;
3896         }
3897         freefrag = jfreefrag->fr_freefrag;
3898         jfreefrag->fr_freefrag = NULL;
3899         free_jfreefrag(jfreefrag);
3900         freefrag->ff_state |= DEPCOMPLETE;
3901         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3902 }
3903
3904 /*
3905  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3906  */
3907 static void
3908 free_jfreefrag(jfreefrag)
3909         struct jfreefrag *jfreefrag;
3910 {
3911
3912         if (jfreefrag->fr_state & INPROGRESS)
3913                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3914         else if (jfreefrag->fr_state & ONWORKLIST)
3915                 remove_from_journal(&jfreefrag->fr_list);
3916         if (jfreefrag->fr_freefrag != NULL)
3917                 panic("free_jfreefrag:  Still attached to a freefrag.");
3918         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3919 }
3920
3921 /*
3922  * Called when the journal write for a jfreefrag completes.  The parent
3923  * freefrag is added to the worklist if this completes its dependencies.
3924  */
3925 static void
3926 handle_written_jfreefrag(jfreefrag)
3927         struct jfreefrag *jfreefrag;
3928 {
3929         struct jsegdep *jsegdep;
3930         struct freefrag *freefrag;
3931
3932         /* Grab the jsegdep. */
3933         jsegdep = jfreefrag->fr_jsegdep;
3934         jfreefrag->fr_jsegdep = NULL;
3935         freefrag = jfreefrag->fr_freefrag;
3936         if (freefrag == NULL)
3937                 panic("handle_written_jfreefrag: No freefrag.");
3938         freefrag->ff_state |= DEPCOMPLETE;
3939         freefrag->ff_jdep = NULL;
3940         jwork_insert(&freefrag->ff_jwork, jsegdep);
3941         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3942                 add_to_worklist(&freefrag->ff_list, 0);
3943         jfreefrag->fr_freefrag = NULL;
3944         free_jfreefrag(jfreefrag);
3945 }
3946
3947 /*
3948  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3949  * is removed from the freeblks list of pending journal writes and the
3950  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3951  * have been reclaimed.
3952  */
3953 static void
3954 handle_written_jblkdep(jblkdep)
3955         struct jblkdep *jblkdep;
3956 {
3957         struct freeblks *freeblks;
3958         struct jsegdep *jsegdep;
3959
3960         /* Grab the jsegdep. */
3961         jsegdep = jblkdep->jb_jsegdep;
3962         jblkdep->jb_jsegdep = NULL;
3963         freeblks = jblkdep->jb_freeblks;
3964         LIST_REMOVE(jblkdep, jb_deps);
3965         jwork_insert(&freeblks->fb_jwork, jsegdep);
3966         /*
3967          * If the freeblks is all journaled, we can add it to the worklist.
3968          */
3969         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3970             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3971                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3972
3973         free_jblkdep(jblkdep);
3974 }
3975
3976 static struct jsegdep *
3977 newjsegdep(struct worklist *wk)
3978 {
3979         struct jsegdep *jsegdep;
3980
3981         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3982         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3983         jsegdep->jd_seg = NULL;
3984
3985         return (jsegdep);
3986 }
3987
3988 static struct jmvref *
3989 newjmvref(dp, ino, oldoff, newoff)
3990         struct inode *dp;
3991         ino_t ino;
3992         off_t oldoff;
3993         off_t newoff;
3994 {
3995         struct jmvref *jmvref;
3996
3997         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3998         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
3999         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4000         jmvref->jm_parent = dp->i_number;
4001         jmvref->jm_ino = ino;
4002         jmvref->jm_oldoff = oldoff;
4003         jmvref->jm_newoff = newoff;
4004
4005         return (jmvref);
4006 }
4007
4008 /*
4009  * Allocate a new jremref that tracks the removal of ip from dp with the
4010  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4011  * DEPCOMPLETE as we have all the information required for the journal write
4012  * and the directory has already been removed from the buffer.  The caller
4013  * is responsible for linking the jremref into the pagedep and adding it
4014  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4015  * a DOTDOT addition so handle_workitem_remove() can properly assign
4016  * the jsegdep when we're done.
4017  */
4018 static struct jremref *
4019 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4020     off_t diroff, nlink_t nlink)
4021 {
4022         struct jremref *jremref;
4023
4024         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4025         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4026         jremref->jr_state = ATTACHED;
4027         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4028            nlink, ip->i_mode);
4029         jremref->jr_dirrem = dirrem;
4030
4031         return (jremref);
4032 }
4033
4034 static inline void
4035 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4036     nlink_t nlink, uint16_t mode)
4037 {
4038
4039         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4040         inoref->if_diroff = diroff;
4041         inoref->if_ino = ino;
4042         inoref->if_parent = parent;
4043         inoref->if_nlink = nlink;
4044         inoref->if_mode = mode;
4045 }
4046
4047 /*
4048  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4049  * directory offset may not be known until later.  The caller is responsible
4050  * adding the entry to the journal when this information is available.  nlink
4051  * should be the link count prior to the addition and mode is only required
4052  * to have the correct FMT.
4053  */
4054 static struct jaddref *
4055 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4056     uint16_t mode)
4057 {
4058         struct jaddref *jaddref;
4059
4060         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4061         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4062         jaddref->ja_state = ATTACHED;
4063         jaddref->ja_mkdir = NULL;
4064         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4065
4066         return (jaddref);
4067 }
4068
4069 /*
4070  * Create a new free dependency for a freework.  The caller is responsible
4071  * for adjusting the reference count when it has the lock held.  The freedep
4072  * will track an outstanding bitmap write that will ultimately clear the
4073  * freework to continue.
4074  */
4075 static struct freedep *
4076 newfreedep(struct freework *freework)
4077 {
4078         struct freedep *freedep;
4079
4080         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4081         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4082         freedep->fd_freework = freework;
4083
4084         return (freedep);
4085 }
4086
4087 /*
4088  * Free a freedep structure once the buffer it is linked to is written.  If
4089  * this is the last reference to the freework schedule it for completion.
4090  */
4091 static void
4092 free_freedep(freedep)
4093         struct freedep *freedep;
4094 {
4095         struct freework *freework;
4096
4097         freework = freedep->fd_freework;
4098         freework->fw_freeblks->fb_cgwait--;
4099         if (--freework->fw_ref == 0)
4100                 freework_enqueue(freework);
4101         WORKITEM_FREE(freedep, D_FREEDEP);
4102 }
4103
4104 /*
4105  * Allocate a new freework structure that may be a level in an indirect
4106  * when parent is not NULL or a top level block when it is.  The top level
4107  * freework structures are allocated without the per-filesystem lock held
4108  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4109  */
4110 static struct freework *
4111 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4112         struct ufsmount *ump;
4113         struct freeblks *freeblks;
4114         struct freework *parent;
4115         ufs_lbn_t lbn;
4116         ufs2_daddr_t nb;
4117         int frags;
4118         int off;
4119         int journal;
4120 {
4121         struct freework *freework;
4122
4123         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4124         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4125         freework->fw_state = ATTACHED;
4126         freework->fw_jnewblk = NULL;
4127         freework->fw_freeblks = freeblks;
4128         freework->fw_parent = parent;
4129         freework->fw_lbn = lbn;
4130         freework->fw_blkno = nb;
4131         freework->fw_frags = frags;
4132         freework->fw_indir = NULL;
4133         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4134             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4135         freework->fw_start = freework->fw_off = off;
4136         if (journal)
4137                 newjfreeblk(freeblks, lbn, nb, frags);
4138         if (parent == NULL) {
4139                 ACQUIRE_LOCK(ump);
4140                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4141                 freeblks->fb_ref++;
4142                 FREE_LOCK(ump);
4143         }
4144
4145         return (freework);
4146 }
4147
4148 /*
4149  * Eliminate a jfreeblk for a block that does not need journaling.
4150  */
4151 static void
4152 cancel_jfreeblk(freeblks, blkno)
4153         struct freeblks *freeblks;
4154         ufs2_daddr_t blkno;
4155 {
4156         struct jfreeblk *jfreeblk;
4157         struct jblkdep *jblkdep;
4158
4159         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4160                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4161                         continue;
4162                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4163                 if (jfreeblk->jf_blkno == blkno)
4164                         break;
4165         }
4166         if (jblkdep == NULL)
4167                 return;
4168         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4169         free_jsegdep(jblkdep->jb_jsegdep);
4170         LIST_REMOVE(jblkdep, jb_deps);
4171         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4172 }
4173
4174 /*
4175  * Allocate a new jfreeblk to journal top level block pointer when truncating
4176  * a file.  The caller must add this to the worklist when the per-filesystem
4177  * lock is held.
4178  */
4179 static struct jfreeblk *
4180 newjfreeblk(freeblks, lbn, blkno, frags)
4181         struct freeblks *freeblks;
4182         ufs_lbn_t lbn;
4183         ufs2_daddr_t blkno;
4184         int frags;
4185 {
4186         struct jfreeblk *jfreeblk;
4187
4188         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4189         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4190             freeblks->fb_list.wk_mp);
4191         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4192         jfreeblk->jf_dep.jb_freeblks = freeblks;
4193         jfreeblk->jf_ino = freeblks->fb_inum;
4194         jfreeblk->jf_lbn = lbn;
4195         jfreeblk->jf_blkno = blkno;
4196         jfreeblk->jf_frags = frags;
4197         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4198
4199         return (jfreeblk);
4200 }
4201
4202 /*
4203  * The journal is only prepared to handle full-size block numbers, so we
4204  * have to adjust the record to reflect the change to a full-size block.
4205  * For example, suppose we have a block made up of fragments 8-15 and
4206  * want to free its last two fragments. We are given a request that says:
4207  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4208  * where frags are the number of fragments to free and oldfrags are the
4209  * number of fragments to keep. To block align it, we have to change it to
4210  * have a valid full-size blkno, so it becomes:
4211  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4212  */
4213 static void
4214 adjust_newfreework(freeblks, frag_offset)
4215         struct freeblks *freeblks;
4216         int frag_offset;
4217 {
4218         struct jfreeblk *jfreeblk;
4219
4220         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4221             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4222             ("adjust_newfreework: Missing freeblks dependency"));
4223
4224         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4225         jfreeblk->jf_blkno -= frag_offset;
4226         jfreeblk->jf_frags += frag_offset;
4227 }
4228
4229 /*
4230  * Allocate a new jtrunc to track a partial truncation.
4231  */
4232 static struct jtrunc *
4233 newjtrunc(freeblks, size, extsize)
4234         struct freeblks *freeblks;
4235         off_t size;
4236         int extsize;
4237 {
4238         struct jtrunc *jtrunc;
4239
4240         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4241         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4242             freeblks->fb_list.wk_mp);
4243         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4244         jtrunc->jt_dep.jb_freeblks = freeblks;
4245         jtrunc->jt_ino = freeblks->fb_inum;
4246         jtrunc->jt_size = size;
4247         jtrunc->jt_extsize = extsize;
4248         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4249
4250         return (jtrunc);
4251 }
4252
4253 /*
4254  * If we're canceling a new bitmap we have to search for another ref
4255  * to move into the bmsafemap dep.  This might be better expressed
4256  * with another structure.
4257  */
4258 static void
4259 move_newblock_dep(jaddref, inodedep)
4260         struct jaddref *jaddref;
4261         struct inodedep *inodedep;
4262 {
4263         struct inoref *inoref;
4264         struct jaddref *jaddrefn;
4265
4266         jaddrefn = NULL;
4267         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4268             inoref = TAILQ_NEXT(inoref, if_deps)) {
4269                 if ((jaddref->ja_state & NEWBLOCK) &&
4270                     inoref->if_list.wk_type == D_JADDREF) {
4271                         jaddrefn = (struct jaddref *)inoref;
4272                         break;
4273                 }
4274         }
4275         if (jaddrefn == NULL)
4276                 return;
4277         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4278         jaddrefn->ja_state |= jaddref->ja_state &
4279             (ATTACHED | UNDONE | NEWBLOCK);
4280         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4281         jaddref->ja_state |= ATTACHED;
4282         LIST_REMOVE(jaddref, ja_bmdeps);
4283         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4284             ja_bmdeps);
4285 }
4286
4287 /*
4288  * Cancel a jaddref either before it has been written or while it is being
4289  * written.  This happens when a link is removed before the add reaches
4290  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4291  * and inode to prevent the link count or bitmap from reaching the disk
4292  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4293  * required.
4294  *
4295  * Returns 1 if the canceled addref requires journaling of the remove and
4296  * 0 otherwise.
4297  */
4298 static int
4299 cancel_jaddref(jaddref, inodedep, wkhd)
4300         struct jaddref *jaddref;
4301         struct inodedep *inodedep;
4302         struct workhead *wkhd;
4303 {
4304         struct inoref *inoref;
4305         struct jsegdep *jsegdep;
4306         int needsj;
4307
4308         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4309             ("cancel_jaddref: Canceling complete jaddref"));
4310         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4311                 needsj = 1;
4312         else
4313                 needsj = 0;
4314         if (inodedep == NULL)
4315                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4316                     0, &inodedep) == 0)
4317                         panic("cancel_jaddref: Lost inodedep");
4318         /*
4319          * We must adjust the nlink of any reference operation that follows
4320          * us so that it is consistent with the in-memory reference.  This
4321          * ensures that inode nlink rollbacks always have the correct link.
4322          */
4323         if (needsj == 0) {
4324                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4325                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4326                         if (inoref->if_state & GOINGAWAY)
4327                                 break;
4328                         inoref->if_nlink--;
4329                 }
4330         }
4331         jsegdep = inoref_jseg(&jaddref->ja_ref);
4332         if (jaddref->ja_state & NEWBLOCK)
4333                 move_newblock_dep(jaddref, inodedep);
4334         wake_worklist(&jaddref->ja_list);
4335         jaddref->ja_mkdir = NULL;
4336         if (jaddref->ja_state & INPROGRESS) {
4337                 jaddref->ja_state &= ~INPROGRESS;
4338                 WORKLIST_REMOVE(&jaddref->ja_list);
4339                 jwork_insert(wkhd, jsegdep);
4340         } else {
4341                 free_jsegdep(jsegdep);
4342                 if (jaddref->ja_state & DEPCOMPLETE)
4343                         remove_from_journal(&jaddref->ja_list);
4344         }
4345         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4346         /*
4347          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4348          * can arrange for them to be freed with the bitmap.  Otherwise we
4349          * no longer need this addref attached to the inoreflst and it
4350          * will incorrectly adjust nlink if we leave it.
4351          */
4352         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4353                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4354                     if_deps);
4355                 jaddref->ja_state |= COMPLETE;
4356                 free_jaddref(jaddref);
4357                 return (needsj);
4358         }
4359         /*
4360          * Leave the head of the list for jsegdeps for fast merging.
4361          */
4362         if (LIST_FIRST(wkhd) != NULL) {
4363                 jaddref->ja_state |= ONWORKLIST;
4364                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4365         } else
4366                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4367
4368         return (needsj);
4369 }
4370
4371 /* 
4372  * Attempt to free a jaddref structure when some work completes.  This
4373  * should only succeed once the entry is written and all dependencies have
4374  * been notified.
4375  */
4376 static void
4377 free_jaddref(jaddref)
4378         struct jaddref *jaddref;
4379 {
4380
4381         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4382                 return;
4383         if (jaddref->ja_ref.if_jsegdep)
4384                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4385                     jaddref, jaddref->ja_state);
4386         if (jaddref->ja_state & NEWBLOCK)
4387                 LIST_REMOVE(jaddref, ja_bmdeps);
4388         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4389                 panic("free_jaddref: Bad state %p(0x%X)",
4390                     jaddref, jaddref->ja_state);
4391         if (jaddref->ja_mkdir != NULL)
4392                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4393         WORKITEM_FREE(jaddref, D_JADDREF);
4394 }
4395
4396 /*
4397  * Free a jremref structure once it has been written or discarded.
4398  */
4399 static void
4400 free_jremref(jremref)
4401         struct jremref *jremref;
4402 {
4403
4404         if (jremref->jr_ref.if_jsegdep)
4405                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4406         if (jremref->jr_state & INPROGRESS)
4407                 panic("free_jremref: IO still pending");
4408         WORKITEM_FREE(jremref, D_JREMREF);
4409 }
4410
4411 /*
4412  * Free a jnewblk structure.
4413  */
4414 static void
4415 free_jnewblk(jnewblk)
4416         struct jnewblk *jnewblk;
4417 {
4418
4419         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4420                 return;
4421         LIST_REMOVE(jnewblk, jn_deps);
4422         if (jnewblk->jn_dep != NULL)
4423                 panic("free_jnewblk: Dependency still attached.");
4424         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4425 }
4426
4427 /*
4428  * Cancel a jnewblk which has been been made redundant by frag extension.
4429  */
4430 static void
4431 cancel_jnewblk(jnewblk, wkhd)
4432         struct jnewblk *jnewblk;
4433         struct workhead *wkhd;
4434 {
4435         struct jsegdep *jsegdep;
4436
4437         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4438         jsegdep = jnewblk->jn_jsegdep;
4439         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4440                 panic("cancel_jnewblk: Invalid state");
4441         jnewblk->jn_jsegdep  = NULL;
4442         jnewblk->jn_dep = NULL;
4443         jnewblk->jn_state |= GOINGAWAY;
4444         if (jnewblk->jn_state & INPROGRESS) {
4445                 jnewblk->jn_state &= ~INPROGRESS;
4446                 WORKLIST_REMOVE(&jnewblk->jn_list);
4447                 jwork_insert(wkhd, jsegdep);
4448         } else {
4449                 free_jsegdep(jsegdep);
4450                 remove_from_journal(&jnewblk->jn_list);
4451         }
4452         wake_worklist(&jnewblk->jn_list);
4453         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4454 }
4455
4456 static void
4457 free_jblkdep(jblkdep)
4458         struct jblkdep *jblkdep;
4459 {
4460
4461         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4462                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4463         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4464                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4465         else
4466                 panic("free_jblkdep: Unexpected type %s",
4467                     TYPENAME(jblkdep->jb_list.wk_type));
4468 }
4469
4470 /*
4471  * Free a single jseg once it is no longer referenced in memory or on
4472  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4473  * to disappear.
4474  */
4475 static void
4476 free_jseg(jseg, jblocks)
4477         struct jseg *jseg;
4478         struct jblocks *jblocks;
4479 {
4480         struct freework *freework;
4481
4482         /*
4483          * Free freework structures that were lingering to indicate freed
4484          * indirect blocks that forced journal write ordering on reallocate.
4485          */
4486         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4487                 indirblk_remove(freework);
4488         if (jblocks->jb_oldestseg == jseg)
4489                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4490         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4491         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4492         KASSERT(LIST_EMPTY(&jseg->js_entries),
4493             ("free_jseg: Freed jseg has valid entries."));
4494         WORKITEM_FREE(jseg, D_JSEG);
4495 }
4496
4497 /*
4498  * Free all jsegs that meet the criteria for being reclaimed and update
4499  * oldestseg.
4500  */
4501 static void
4502 free_jsegs(jblocks)
4503         struct jblocks *jblocks;
4504 {
4505         struct jseg *jseg;
4506
4507         /*
4508          * Free only those jsegs which have none allocated before them to
4509          * preserve the journal space ordering.
4510          */
4511         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4512                 /*
4513                  * Only reclaim space when nothing depends on this journal
4514                  * set and another set has written that it is no longer
4515                  * valid.
4516                  */
4517                 if (jseg->js_refs != 0) {
4518                         jblocks->jb_oldestseg = jseg;
4519                         return;
4520                 }
4521                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4522                         break;
4523                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4524                         break;
4525                 /*
4526                  * We can free jsegs that didn't write entries when
4527                  * oldestwrseq == js_seq.
4528                  */
4529                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4530                     jseg->js_cnt != 0)
4531                         break;
4532                 free_jseg(jseg, jblocks);
4533         }
4534         /*
4535          * If we exited the loop above we still must discover the
4536          * oldest valid segment.
4537          */
4538         if (jseg)
4539                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4540                      jseg = TAILQ_NEXT(jseg, js_next))
4541                         if (jseg->js_refs != 0)
4542                                 break;
4543         jblocks->jb_oldestseg = jseg;
4544         /*
4545          * The journal has no valid records but some jsegs may still be
4546          * waiting on oldestwrseq to advance.  We force a small record
4547          * out to permit these lingering records to be reclaimed.
4548          */
4549         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4550                 jblocks->jb_needseg = 1;
4551 }
4552
4553 /*
4554  * Release one reference to a jseg and free it if the count reaches 0.  This
4555  * should eventually reclaim journal space as well.
4556  */
4557 static void
4558 rele_jseg(jseg)
4559         struct jseg *jseg;
4560 {
4561
4562         KASSERT(jseg->js_refs > 0,
4563             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4564         if (--jseg->js_refs != 0)
4565                 return;
4566         free_jsegs(jseg->js_jblocks);
4567 }
4568
4569 /*
4570  * Release a jsegdep and decrement the jseg count.
4571  */
4572 static void
4573 free_jsegdep(jsegdep)
4574         struct jsegdep *jsegdep;
4575 {
4576
4577         if (jsegdep->jd_seg)
4578                 rele_jseg(jsegdep->jd_seg);
4579         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4580 }
4581
4582 /*
4583  * Wait for a journal item to make it to disk.  Initiate journal processing
4584  * if required.
4585  */
4586 static int
4587 jwait(wk, waitfor)
4588         struct worklist *wk;
4589         int waitfor;
4590 {
4591
4592         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4593         /*
4594          * Blocking journal waits cause slow synchronous behavior.  Record
4595          * stats on the frequency of these blocking operations.
4596          */
4597         if (waitfor == MNT_WAIT) {
4598                 stat_journal_wait++;
4599                 switch (wk->wk_type) {
4600                 case D_JREMREF:
4601                 case D_JMVREF:
4602                         stat_jwait_filepage++;
4603                         break;
4604                 case D_JTRUNC:
4605                 case D_JFREEBLK:
4606                         stat_jwait_freeblks++;
4607                         break;
4608                 case D_JNEWBLK:
4609                         stat_jwait_newblk++;
4610                         break;
4611                 case D_JADDREF:
4612                         stat_jwait_inode++;
4613                         break;
4614                 default:
4615                         break;
4616                 }
4617         }
4618         /*
4619          * If IO has not started we process the journal.  We can't mark the
4620          * worklist item as IOWAITING because we drop the lock while
4621          * processing the journal and the worklist entry may be freed after
4622          * this point.  The caller may call back in and re-issue the request.
4623          */
4624         if ((wk->wk_state & INPROGRESS) == 0) {
4625                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4626                 if (waitfor != MNT_WAIT)
4627                         return (EBUSY);
4628                 return (0);
4629         }
4630         if (waitfor != MNT_WAIT)
4631                 return (EBUSY);
4632         wait_worklist(wk, "jwait");
4633         return (0);
4634 }
4635
4636 /*
4637  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4638  * appropriate.  This is a convenience function to reduce duplicate code
4639  * for the setup and revert functions below.
4640  */
4641 static struct inodedep *
4642 inodedep_lookup_ip(ip)
4643         struct inode *ip;
4644 {
4645         struct inodedep *inodedep;
4646
4647         KASSERT(ip->i_nlink >= ip->i_effnlink,
4648             ("inodedep_lookup_ip: bad delta"));
4649         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4650             &inodedep);
4651         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4652         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4653
4654         return (inodedep);
4655 }
4656
4657 /*
4658  * Called prior to creating a new inode and linking it to a directory.  The
4659  * jaddref structure must already be allocated by softdep_setup_inomapdep
4660  * and it is discovered here so we can initialize the mode and update
4661  * nlinkdelta.
4662  */
4663 void
4664 softdep_setup_create(dp, ip)
4665         struct inode *dp;
4666         struct inode *ip;
4667 {
4668         struct inodedep *inodedep;
4669         struct jaddref *jaddref;
4670         struct vnode *dvp;
4671
4672         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4673             ("softdep_setup_create called on non-softdep filesystem"));
4674         KASSERT(ip->i_nlink == 1,
4675             ("softdep_setup_create: Invalid link count."));
4676         dvp = ITOV(dp);
4677         ACQUIRE_LOCK(ITOUMP(dp));
4678         inodedep = inodedep_lookup_ip(ip);
4679         if (DOINGSUJ(dvp)) {
4680                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4681                     inoreflst);
4682                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4683                     ("softdep_setup_create: No addref structure present."));
4684         }
4685         softdep_prelink(dvp, NULL);
4686         FREE_LOCK(ITOUMP(dp));
4687 }
4688
4689 /*
4690  * Create a jaddref structure to track the addition of a DOTDOT link when
4691  * we are reparenting an inode as part of a rename.  This jaddref will be
4692  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4693  * non-journaling softdep.
4694  */
4695 void
4696 softdep_setup_dotdot_link(dp, ip)
4697         struct inode *dp;
4698         struct inode *ip;
4699 {
4700         struct inodedep *inodedep;
4701         struct jaddref *jaddref;
4702         struct vnode *dvp;
4703
4704         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4705             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4706         dvp = ITOV(dp);
4707         jaddref = NULL;
4708         /*
4709          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4710          * is used as a normal link would be.
4711          */
4712         if (DOINGSUJ(dvp))
4713                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4714                     dp->i_effnlink - 1, dp->i_mode);
4715         ACQUIRE_LOCK(ITOUMP(dp));
4716         inodedep = inodedep_lookup_ip(dp);
4717         if (jaddref)
4718                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4719                     if_deps);
4720         softdep_prelink(dvp, ITOV(ip));
4721         FREE_LOCK(ITOUMP(dp));
4722 }
4723
4724 /*
4725  * Create a jaddref structure to track a new link to an inode.  The directory
4726  * offset is not known until softdep_setup_directory_add or
4727  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4728  * softdep.
4729  */
4730 void
4731 softdep_setup_link(dp, ip)
4732         struct inode *dp;
4733         struct inode *ip;
4734 {
4735         struct inodedep *inodedep;
4736         struct jaddref *jaddref;
4737         struct vnode *dvp;
4738
4739         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4740             ("softdep_setup_link called on non-softdep filesystem"));
4741         dvp = ITOV(dp);
4742         jaddref = NULL;
4743         if (DOINGSUJ(dvp))
4744                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4745                     ip->i_mode);
4746         ACQUIRE_LOCK(ITOUMP(dp));
4747         inodedep = inodedep_lookup_ip(ip);
4748         if (jaddref)
4749                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4750                     if_deps);
4751         softdep_prelink(dvp, ITOV(ip));
4752         FREE_LOCK(ITOUMP(dp));
4753 }
4754
4755 /*
4756  * Called to create the jaddref structures to track . and .. references as
4757  * well as lookup and further initialize the incomplete jaddref created
4758  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4759  * nlinkdelta for non-journaling softdep.
4760  */
4761 void
4762 softdep_setup_mkdir(dp, ip)
4763         struct inode *dp;
4764         struct inode *ip;
4765 {
4766         struct inodedep *inodedep;
4767         struct jaddref *dotdotaddref;
4768         struct jaddref *dotaddref;
4769         struct jaddref *jaddref;
4770         struct vnode *dvp;
4771
4772         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4773             ("softdep_setup_mkdir called on non-softdep filesystem"));
4774         dvp = ITOV(dp);
4775         dotaddref = dotdotaddref = NULL;
4776         if (DOINGSUJ(dvp)) {
4777                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4778                     ip->i_mode);
4779                 dotaddref->ja_state |= MKDIR_BODY;
4780                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4781                     dp->i_effnlink - 1, dp->i_mode);
4782                 dotdotaddref->ja_state |= MKDIR_PARENT;
4783         }
4784         ACQUIRE_LOCK(ITOUMP(dp));
4785         inodedep = inodedep_lookup_ip(ip);
4786         if (DOINGSUJ(dvp)) {
4787                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4788                     inoreflst);
4789                 KASSERT(jaddref != NULL,
4790                     ("softdep_setup_mkdir: No addref structure present."));
4791                 KASSERT(jaddref->ja_parent == dp->i_number, 
4792                     ("softdep_setup_mkdir: bad parent %ju",
4793                     (uintmax_t)jaddref->ja_parent));
4794                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4795                     if_deps);
4796         }
4797         inodedep = inodedep_lookup_ip(dp);
4798         if (DOINGSUJ(dvp))
4799                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4800                     &dotdotaddref->ja_ref, if_deps);
4801         softdep_prelink(ITOV(dp), NULL);
4802         FREE_LOCK(ITOUMP(dp));
4803 }
4804
4805 /*
4806  * Called to track nlinkdelta of the inode and parent directories prior to
4807  * unlinking a directory.
4808  */
4809 void
4810 softdep_setup_rmdir(dp, ip)
4811         struct inode *dp;
4812         struct inode *ip;
4813 {
4814         struct vnode *dvp;
4815
4816         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4817             ("softdep_setup_rmdir called on non-softdep filesystem"));
4818         dvp = ITOV(dp);
4819         ACQUIRE_LOCK(ITOUMP(dp));
4820         (void) inodedep_lookup_ip(ip);
4821         (void) inodedep_lookup_ip(dp);
4822         softdep_prelink(dvp, ITOV(ip));
4823         FREE_LOCK(ITOUMP(dp));
4824 }
4825
4826 /*
4827  * Called to track nlinkdelta of the inode and parent directories prior to
4828  * unlink.
4829  */
4830 void
4831 softdep_setup_unlink(dp, ip)
4832         struct inode *dp;
4833         struct inode *ip;
4834 {
4835         struct vnode *dvp;
4836
4837         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4838             ("softdep_setup_unlink called on non-softdep filesystem"));
4839         dvp = ITOV(dp);
4840         ACQUIRE_LOCK(ITOUMP(dp));
4841         (void) inodedep_lookup_ip(ip);
4842         (void) inodedep_lookup_ip(dp);
4843         softdep_prelink(dvp, ITOV(ip));
4844         FREE_LOCK(ITOUMP(dp));
4845 }
4846
4847 /*
4848  * Called to release the journal structures created by a failed non-directory
4849  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4850  */
4851 void
4852 softdep_revert_create(dp, ip)
4853         struct inode *dp;
4854         struct inode *ip;
4855 {
4856         struct inodedep *inodedep;
4857         struct jaddref *jaddref;
4858         struct vnode *dvp;
4859
4860         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4861             ("softdep_revert_create called on non-softdep filesystem"));
4862         dvp = ITOV(dp);
4863         ACQUIRE_LOCK(ITOUMP(dp));
4864         inodedep = inodedep_lookup_ip(ip);
4865         if (DOINGSUJ(dvp)) {
4866                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4867                     inoreflst);
4868                 KASSERT(jaddref->ja_parent == dp->i_number,
4869                     ("softdep_revert_create: addref parent mismatch"));
4870                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4871         }
4872         FREE_LOCK(ITOUMP(dp));
4873 }
4874
4875 /*
4876  * Called to release the journal structures created by a failed link
4877  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4878  */
4879 void
4880 softdep_revert_link(dp, ip)
4881         struct inode *dp;
4882         struct inode *ip;
4883 {
4884         struct inodedep *inodedep;
4885         struct jaddref *jaddref;
4886         struct vnode *dvp;
4887
4888         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4889             ("softdep_revert_link called on non-softdep filesystem"));
4890         dvp = ITOV(dp);
4891         ACQUIRE_LOCK(ITOUMP(dp));
4892         inodedep = inodedep_lookup_ip(ip);
4893         if (DOINGSUJ(dvp)) {
4894                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4895                     inoreflst);
4896                 KASSERT(jaddref->ja_parent == dp->i_number,
4897                     ("softdep_revert_link: addref parent mismatch"));
4898                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4899         }
4900         FREE_LOCK(ITOUMP(dp));
4901 }
4902
4903 /*
4904  * Called to release the journal structures created by a failed mkdir
4905  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4906  */
4907 void
4908 softdep_revert_mkdir(dp, ip)
4909         struct inode *dp;
4910         struct inode *ip;
4911 {
4912         struct inodedep *inodedep;
4913         struct jaddref *jaddref;
4914         struct jaddref *dotaddref;
4915         struct vnode *dvp;
4916
4917         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4918             ("softdep_revert_mkdir called on non-softdep filesystem"));
4919         dvp = ITOV(dp);
4920
4921         ACQUIRE_LOCK(ITOUMP(dp));
4922         inodedep = inodedep_lookup_ip(dp);
4923         if (DOINGSUJ(dvp)) {
4924                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4925                     inoreflst);
4926                 KASSERT(jaddref->ja_parent == ip->i_number,
4927                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4928                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4929         }
4930         inodedep = inodedep_lookup_ip(ip);
4931         if (DOINGSUJ(dvp)) {
4932                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4933                     inoreflst);
4934                 KASSERT(jaddref->ja_parent == dp->i_number,
4935                     ("softdep_revert_mkdir: addref parent mismatch"));
4936                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4937                     inoreflst, if_deps);
4938                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4939                 KASSERT(dotaddref->ja_parent == ip->i_number,
4940                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4941                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4942         }
4943         FREE_LOCK(ITOUMP(dp));
4944 }
4945
4946 /* 
4947  * Called to correct nlinkdelta after a failed rmdir.
4948  */
4949 void
4950 softdep_revert_rmdir(dp, ip)
4951         struct inode *dp;
4952         struct inode *ip;
4953 {
4954
4955         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4956             ("softdep_revert_rmdir called on non-softdep filesystem"));
4957         ACQUIRE_LOCK(ITOUMP(dp));
4958         (void) inodedep_lookup_ip(ip);
4959         (void) inodedep_lookup_ip(dp);
4960         FREE_LOCK(ITOUMP(dp));
4961 }
4962
4963 /*
4964  * Protecting the freemaps (or bitmaps).
4965  * 
4966  * To eliminate the need to execute fsck before mounting a filesystem
4967  * after a power failure, one must (conservatively) guarantee that the
4968  * on-disk copy of the bitmaps never indicate that a live inode or block is
4969  * free.  So, when a block or inode is allocated, the bitmap should be
4970  * updated (on disk) before any new pointers.  When a block or inode is
4971  * freed, the bitmap should not be updated until all pointers have been
4972  * reset.  The latter dependency is handled by the delayed de-allocation
4973  * approach described below for block and inode de-allocation.  The former
4974  * dependency is handled by calling the following procedure when a block or
4975  * inode is allocated. When an inode is allocated an "inodedep" is created
4976  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4977  * Each "inodedep" is also inserted into the hash indexing structure so
4978  * that any additional link additions can be made dependent on the inode
4979  * allocation.
4980  * 
4981  * The ufs filesystem maintains a number of free block counts (e.g., per
4982  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4983  * in addition to the bitmaps.  These counts are used to improve efficiency
4984  * during allocation and therefore must be consistent with the bitmaps.
4985  * There is no convenient way to guarantee post-crash consistency of these
4986  * counts with simple update ordering, for two main reasons: (1) The counts
4987  * and bitmaps for a single cylinder group block are not in the same disk
4988  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4989  * be written and the other not.  (2) Some of the counts are located in the
4990  * superblock rather than the cylinder group block. So, we focus our soft
4991  * updates implementation on protecting the bitmaps. When mounting a
4992  * filesystem, we recompute the auxiliary counts from the bitmaps.
4993  */
4994
4995 /*
4996  * Called just after updating the cylinder group block to allocate an inode.
4997  */
4998 void
4999 softdep_setup_inomapdep(bp, ip, newinum, mode)
5000         struct buf *bp;         /* buffer for cylgroup block with inode map */
5001         struct inode *ip;       /* inode related to allocation */
5002         ino_t newinum;          /* new inode number being allocated */
5003         int mode;
5004 {
5005         struct inodedep *inodedep;
5006         struct bmsafemap *bmsafemap;
5007         struct jaddref *jaddref;
5008         struct mount *mp;
5009         struct fs *fs;
5010
5011         mp = ITOVFS(ip);
5012         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5013             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5014         fs = VFSTOUFS(mp)->um_fs;
5015         jaddref = NULL;
5016
5017         /*
5018          * Allocate the journal reference add structure so that the bitmap
5019          * can be dependent on it.
5020          */
5021         if (MOUNTEDSUJ(mp)) {
5022                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5023                 jaddref->ja_state |= NEWBLOCK;
5024         }
5025
5026         /*
5027          * Create a dependency for the newly allocated inode.
5028          * Panic if it already exists as something is seriously wrong.
5029          * Otherwise add it to the dependency list for the buffer holding
5030          * the cylinder group map from which it was allocated.
5031          *
5032          * We have to preallocate a bmsafemap entry in case it is needed
5033          * in bmsafemap_lookup since once we allocate the inodedep, we
5034          * have to finish initializing it before we can FREE_LOCK().
5035          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5036          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5037          * creating the inodedep as it can be freed during the time
5038          * that we FREE_LOCK() while allocating the inodedep. We must
5039          * call workitem_alloc() before entering the locked section as
5040          * it also acquires the lock and we must avoid trying doing so
5041          * recursively.
5042          */
5043         bmsafemap = malloc(sizeof(struct bmsafemap),
5044             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5045         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5046         ACQUIRE_LOCK(ITOUMP(ip));
5047         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5048                 panic("softdep_setup_inomapdep: dependency %p for new"
5049                     "inode already exists", inodedep);
5050         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5051         if (jaddref) {
5052                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5053                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5054                     if_deps);
5055         } else {
5056                 inodedep->id_state |= ONDEPLIST;
5057                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5058         }
5059         inodedep->id_bmsafemap = bmsafemap;
5060         inodedep->id_state &= ~DEPCOMPLETE;
5061         FREE_LOCK(ITOUMP(ip));
5062 }
5063
5064 /*
5065  * Called just after updating the cylinder group block to
5066  * allocate block or fragment.
5067  */
5068 void
5069 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5070         struct buf *bp;         /* buffer for cylgroup block with block map */
5071         struct mount *mp;       /* filesystem doing allocation */
5072         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5073         int frags;              /* Number of fragments. */
5074         int oldfrags;           /* Previous number of fragments for extend. */
5075 {
5076         struct newblk *newblk;
5077         struct bmsafemap *bmsafemap;
5078         struct jnewblk *jnewblk;
5079         struct ufsmount *ump;
5080         struct fs *fs;
5081
5082         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5083             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5084         ump = VFSTOUFS(mp);
5085         fs = ump->um_fs;
5086         jnewblk = NULL;
5087         /*
5088          * Create a dependency for the newly allocated block.
5089          * Add it to the dependency list for the buffer holding
5090          * the cylinder group map from which it was allocated.
5091          */
5092         if (MOUNTEDSUJ(mp)) {
5093                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5094                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5095                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5096                 jnewblk->jn_state = ATTACHED;
5097                 jnewblk->jn_blkno = newblkno;
5098                 jnewblk->jn_frags = frags;
5099                 jnewblk->jn_oldfrags = oldfrags;
5100 #ifdef SUJ_DEBUG
5101                 {
5102                         struct cg *cgp;
5103                         uint8_t *blksfree;
5104                         long bno;
5105                         int i;
5106         
5107                         cgp = (struct cg *)bp->b_data;
5108                         blksfree = cg_blksfree(cgp);
5109                         bno = dtogd(fs, jnewblk->jn_blkno);
5110                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5111                             i++) {
5112                                 if (isset(blksfree, bno + i))
5113                                         panic("softdep_setup_blkmapdep: "
5114                                             "free fragment %d from %d-%d "
5115                                             "state 0x%X dep %p", i,
5116                                             jnewblk->jn_oldfrags,
5117                                             jnewblk->jn_frags,
5118                                             jnewblk->jn_state,
5119                                             jnewblk->jn_dep);
5120                         }
5121                 }
5122 #endif
5123         }
5124
5125         CTR3(KTR_SUJ,
5126             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5127             newblkno, frags, oldfrags);
5128         ACQUIRE_LOCK(ump);
5129         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5130                 panic("softdep_setup_blkmapdep: found block");
5131         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5132             dtog(fs, newblkno), NULL);
5133         if (jnewblk) {
5134                 jnewblk->jn_dep = (struct worklist *)newblk;
5135                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5136         } else {
5137                 newblk->nb_state |= ONDEPLIST;
5138                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5139         }
5140         newblk->nb_bmsafemap = bmsafemap;
5141         newblk->nb_jnewblk = jnewblk;
5142         FREE_LOCK(ump);
5143 }
5144
5145 #define BMSAFEMAP_HASH(ump, cg) \
5146       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5147
5148 static int
5149 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5150         struct bmsafemap_hashhead *bmsafemaphd;
5151         int cg;
5152         struct bmsafemap **bmsafemapp;
5153 {
5154         struct bmsafemap *bmsafemap;
5155
5156         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5157                 if (bmsafemap->sm_cg == cg)
5158                         break;
5159         if (bmsafemap) {
5160                 *bmsafemapp = bmsafemap;
5161                 return (1);
5162         }
5163         *bmsafemapp = NULL;
5164
5165         return (0);
5166 }
5167
5168 /*
5169  * Find the bmsafemap associated with a cylinder group buffer.
5170  * If none exists, create one. The buffer must be locked when
5171  * this routine is called and this routine must be called with
5172  * the softdep lock held. To avoid giving up the lock while
5173  * allocating a new bmsafemap, a preallocated bmsafemap may be
5174  * provided. If it is provided but not needed, it is freed.
5175  */
5176 static struct bmsafemap *
5177 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5178         struct mount *mp;
5179         struct buf *bp;
5180         int cg;
5181         struct bmsafemap *newbmsafemap;
5182 {
5183         struct bmsafemap_hashhead *bmsafemaphd;
5184         struct bmsafemap *bmsafemap, *collision;
5185         struct worklist *wk;
5186         struct ufsmount *ump;
5187
5188         ump = VFSTOUFS(mp);
5189         LOCK_OWNED(ump);
5190         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5191         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5192                 if (wk->wk_type == D_BMSAFEMAP) {
5193                         if (newbmsafemap)
5194                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5195                         return (WK_BMSAFEMAP(wk));
5196                 }
5197         }
5198         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5199         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5200                 if (newbmsafemap)
5201                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5202                 return (bmsafemap);
5203         }
5204         if (newbmsafemap) {
5205                 bmsafemap = newbmsafemap;
5206         } else {
5207                 FREE_LOCK(ump);
5208                 bmsafemap = malloc(sizeof(struct bmsafemap),
5209                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5210                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5211                 ACQUIRE_LOCK(ump);
5212         }
5213         bmsafemap->sm_buf = bp;
5214         LIST_INIT(&bmsafemap->sm_inodedephd);
5215         LIST_INIT(&bmsafemap->sm_inodedepwr);
5216         LIST_INIT(&bmsafemap->sm_newblkhd);
5217         LIST_INIT(&bmsafemap->sm_newblkwr);
5218         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5219         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5220         LIST_INIT(&bmsafemap->sm_freehd);
5221         LIST_INIT(&bmsafemap->sm_freewr);
5222         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5223                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5224                 return (collision);
5225         }
5226         bmsafemap->sm_cg = cg;
5227         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5228         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5229         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5230         return (bmsafemap);
5231 }
5232
5233 /*
5234  * Direct block allocation dependencies.
5235  * 
5236  * When a new block is allocated, the corresponding disk locations must be
5237  * initialized (with zeros or new data) before the on-disk inode points to
5238  * them.  Also, the freemap from which the block was allocated must be
5239  * updated (on disk) before the inode's pointer. These two dependencies are
5240  * independent of each other and are needed for all file blocks and indirect
5241  * blocks that are pointed to directly by the inode.  Just before the
5242  * "in-core" version of the inode is updated with a newly allocated block
5243  * number, a procedure (below) is called to setup allocation dependency
5244  * structures.  These structures are removed when the corresponding
5245  * dependencies are satisfied or when the block allocation becomes obsolete
5246  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5247  * fragment that gets upgraded).  All of these cases are handled in
5248  * procedures described later.
5249  * 
5250  * When a file extension causes a fragment to be upgraded, either to a larger
5251  * fragment or to a full block, the on-disk location may change (if the
5252  * previous fragment could not simply be extended). In this case, the old
5253  * fragment must be de-allocated, but not until after the inode's pointer has
5254  * been updated. In most cases, this is handled by later procedures, which
5255  * will construct a "freefrag" structure to be added to the workitem queue
5256  * when the inode update is complete (or obsolete).  The main exception to
5257  * this is when an allocation occurs while a pending allocation dependency
5258  * (for the same block pointer) remains.  This case is handled in the main
5259  * allocation dependency setup procedure by immediately freeing the
5260  * unreferenced fragments.
5261  */ 
5262 void 
5263 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5264         struct inode *ip;       /* inode to which block is being added */
5265         ufs_lbn_t off;          /* block pointer within inode */
5266         ufs2_daddr_t newblkno;  /* disk block number being added */
5267         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5268         long newsize;           /* size of new block */
5269         long oldsize;           /* size of new block */
5270         struct buf *bp;         /* bp for allocated block */
5271 {
5272         struct allocdirect *adp, *oldadp;
5273         struct allocdirectlst *adphead;
5274         struct freefrag *freefrag;
5275         struct inodedep *inodedep;
5276         struct pagedep *pagedep;
5277         struct jnewblk *jnewblk;
5278         struct newblk *newblk;
5279         struct mount *mp;
5280         ufs_lbn_t lbn;
5281
5282         lbn = bp->b_lblkno;
5283         mp = ITOVFS(ip);
5284         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5285             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5286         if (oldblkno && oldblkno != newblkno)
5287                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5288         else
5289                 freefrag = NULL;
5290
5291         CTR6(KTR_SUJ,
5292             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5293             "off %jd newsize %ld oldsize %d",
5294             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5295         ACQUIRE_LOCK(ITOUMP(ip));
5296         if (off >= UFS_NDADDR) {
5297                 if (lbn > 0)
5298                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5299                             lbn, off);
5300                 /* allocating an indirect block */
5301                 if (oldblkno != 0)
5302                         panic("softdep_setup_allocdirect: non-zero indir");
5303         } else {
5304                 if (off != lbn)
5305                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5306                             lbn, off);
5307                 /*
5308                  * Allocating a direct block.
5309                  *
5310                  * If we are allocating a directory block, then we must
5311                  * allocate an associated pagedep to track additions and
5312                  * deletions.
5313                  */
5314                 if ((ip->i_mode & IFMT) == IFDIR)
5315                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5316                             &pagedep);
5317         }
5318         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5319                 panic("softdep_setup_allocdirect: lost block");
5320         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5321             ("softdep_setup_allocdirect: newblk already initialized"));
5322         /*
5323          * Convert the newblk to an allocdirect.
5324          */
5325         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5326         adp = (struct allocdirect *)newblk;
5327         newblk->nb_freefrag = freefrag;
5328         adp->ad_offset = off;
5329         adp->ad_oldblkno = oldblkno;
5330         adp->ad_newsize = newsize;
5331         adp->ad_oldsize = oldsize;
5332
5333         /*
5334          * Finish initializing the journal.
5335          */
5336         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5337                 jnewblk->jn_ino = ip->i_number;
5338                 jnewblk->jn_lbn = lbn;
5339                 add_to_journal(&jnewblk->jn_list);
5340         }
5341         if (freefrag && freefrag->ff_jdep != NULL &&
5342             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5343                 add_to_journal(freefrag->ff_jdep);
5344         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5345         adp->ad_inodedep = inodedep;
5346
5347         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5348         /*
5349          * The list of allocdirects must be kept in sorted and ascending
5350          * order so that the rollback routines can quickly determine the
5351          * first uncommitted block (the size of the file stored on disk
5352          * ends at the end of the lowest committed fragment, or if there
5353          * are no fragments, at the end of the highest committed block).
5354          * Since files generally grow, the typical case is that the new
5355          * block is to be added at the end of the list. We speed this
5356          * special case by checking against the last allocdirect in the
5357          * list before laboriously traversing the list looking for the
5358          * insertion point.
5359          */
5360         adphead = &inodedep->id_newinoupdt;
5361         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5362         if (oldadp == NULL || oldadp->ad_offset <= off) {
5363                 /* insert at end of list */
5364                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5365                 if (oldadp != NULL && oldadp->ad_offset == off)
5366                         allocdirect_merge(adphead, adp, oldadp);
5367                 FREE_LOCK(ITOUMP(ip));
5368                 return;
5369         }
5370         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5371                 if (oldadp->ad_offset >= off)
5372                         break;
5373         }
5374         if (oldadp == NULL)
5375                 panic("softdep_setup_allocdirect: lost entry");
5376         /* insert in middle of list */
5377         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5378         if (oldadp->ad_offset == off)
5379                 allocdirect_merge(adphead, adp, oldadp);
5380
5381         FREE_LOCK(ITOUMP(ip));
5382 }
5383
5384 /*
5385  * Merge a newer and older journal record to be stored either in a
5386  * newblock or freefrag.  This handles aggregating journal records for
5387  * fragment allocation into a second record as well as replacing a
5388  * journal free with an aborted journal allocation.  A segment for the
5389  * oldest record will be placed on wkhd if it has been written.  If not
5390  * the segment for the newer record will suffice.
5391  */
5392 static struct worklist *
5393 jnewblk_merge(new, old, wkhd)
5394         struct worklist *new;
5395         struct worklist *old;
5396         struct workhead *wkhd;
5397 {
5398         struct jnewblk *njnewblk;
5399         struct jnewblk *jnewblk;
5400
5401         /* Handle NULLs to simplify callers. */
5402         if (new == NULL)
5403                 return (old);
5404         if (old == NULL)
5405                 return (new);
5406         /* Replace a jfreefrag with a jnewblk. */
5407         if (new->wk_type == D_JFREEFRAG) {
5408                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5409                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5410                             old, new);
5411                 cancel_jfreefrag(WK_JFREEFRAG(new));
5412                 return (old);
5413         }
5414         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5415                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5416                     old->wk_type, new->wk_type);
5417         /*
5418          * Handle merging of two jnewblk records that describe
5419          * different sets of fragments in the same block.
5420          */
5421         jnewblk = WK_JNEWBLK(old);
5422         njnewblk = WK_JNEWBLK(new);
5423         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5424                 panic("jnewblk_merge: Merging disparate blocks.");
5425         /*
5426          * The record may be rolled back in the cg.
5427          */
5428         if (jnewblk->jn_state & UNDONE) {
5429                 jnewblk->jn_state &= ~UNDONE;
5430                 njnewblk->jn_state |= UNDONE;
5431                 njnewblk->jn_state &= ~ATTACHED;
5432         }
5433         /*
5434          * We modify the newer addref and free the older so that if neither
5435          * has been written the most up-to-date copy will be on disk.  If
5436          * both have been written but rolled back we only temporarily need
5437          * one of them to fix the bits when the cg write completes.
5438          */
5439         jnewblk->jn_state |= ATTACHED | COMPLETE;
5440         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5441         cancel_jnewblk(jnewblk, wkhd);
5442         WORKLIST_REMOVE(&jnewblk->jn_list);
5443         free_jnewblk(jnewblk);
5444         return (new);
5445 }
5446
5447 /*
5448  * Replace an old allocdirect dependency with a newer one.
5449  * This routine must be called with splbio interrupts blocked.
5450  */
5451 static void
5452 allocdirect_merge(adphead, newadp, oldadp)
5453         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5454         struct allocdirect *newadp;     /* allocdirect being added */
5455         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5456 {
5457         struct worklist *wk;
5458         struct freefrag *freefrag;
5459
5460         freefrag = NULL;
5461         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5462         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5463             newadp->ad_oldsize != oldadp->ad_newsize ||
5464             newadp->ad_offset >= UFS_NDADDR)
5465                 panic("%s %jd != new %jd || old size %ld != new %ld",
5466                     "allocdirect_merge: old blkno",
5467                     (intmax_t)newadp->ad_oldblkno,
5468                     (intmax_t)oldadp->ad_newblkno,
5469                     newadp->ad_oldsize, oldadp->ad_newsize);
5470         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5471         newadp->ad_oldsize = oldadp->ad_oldsize;
5472         /*
5473          * If the old dependency had a fragment to free or had never
5474          * previously had a block allocated, then the new dependency
5475          * can immediately post its freefrag and adopt the old freefrag.
5476          * This action is done by swapping the freefrag dependencies.
5477          * The new dependency gains the old one's freefrag, and the
5478          * old one gets the new one and then immediately puts it on
5479          * the worklist when it is freed by free_newblk. It is
5480          * not possible to do this swap when the old dependency had a
5481          * non-zero size but no previous fragment to free. This condition
5482          * arises when the new block is an extension of the old block.
5483          * Here, the first part of the fragment allocated to the new
5484          * dependency is part of the block currently claimed on disk by
5485          * the old dependency, so cannot legitimately be freed until the
5486          * conditions for the new dependency are fulfilled.
5487          */
5488         freefrag = newadp->ad_freefrag;
5489         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5490                 newadp->ad_freefrag = oldadp->ad_freefrag;
5491                 oldadp->ad_freefrag = freefrag;
5492         }
5493         /*
5494          * If we are tracking a new directory-block allocation,
5495          * move it from the old allocdirect to the new allocdirect.
5496          */
5497         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5498                 WORKLIST_REMOVE(wk);
5499                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5500                         panic("allocdirect_merge: extra newdirblk");
5501                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5502         }
5503         TAILQ_REMOVE(adphead, oldadp, ad_next);
5504         /*
5505          * We need to move any journal dependencies over to the freefrag
5506          * that releases this block if it exists.  Otherwise we are
5507          * extending an existing block and we'll wait until that is
5508          * complete to release the journal space and extend the
5509          * new journal to cover this old space as well.
5510          */
5511         if (freefrag == NULL) {
5512                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5513                         panic("allocdirect_merge: %jd != %jd",
5514                             oldadp->ad_newblkno, newadp->ad_newblkno);
5515                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5516                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5517                     &oldadp->ad_block.nb_jnewblk->jn_list,
5518                     &newadp->ad_block.nb_jwork);
5519                 oldadp->ad_block.nb_jnewblk = NULL;
5520                 cancel_newblk(&oldadp->ad_block, NULL,
5521                     &newadp->ad_block.nb_jwork);
5522         } else {
5523                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5524                     &freefrag->ff_list, &freefrag->ff_jwork);
5525                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5526                     &freefrag->ff_jwork);
5527         }
5528         free_newblk(&oldadp->ad_block);
5529 }
5530
5531 /*
5532  * Allocate a jfreefrag structure to journal a single block free.
5533  */
5534 static struct jfreefrag *
5535 newjfreefrag(freefrag, ip, blkno, size, lbn)
5536         struct freefrag *freefrag;
5537         struct inode *ip;
5538         ufs2_daddr_t blkno;
5539         long size;
5540         ufs_lbn_t lbn;
5541 {
5542         struct jfreefrag *jfreefrag;
5543         struct fs *fs;
5544
5545         fs = ITOFS(ip);
5546         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5547             M_SOFTDEP_FLAGS);
5548         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5549         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5550         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5551         jfreefrag->fr_ino = ip->i_number;
5552         jfreefrag->fr_lbn = lbn;
5553         jfreefrag->fr_blkno = blkno;
5554         jfreefrag->fr_frags = numfrags(fs, size);
5555         jfreefrag->fr_freefrag = freefrag;
5556
5557         return (jfreefrag);
5558 }
5559
5560 /*
5561  * Allocate a new freefrag structure.
5562  */
5563 static struct freefrag *
5564 newfreefrag(ip, blkno, size, lbn)
5565         struct inode *ip;
5566         ufs2_daddr_t blkno;
5567         long size;
5568         ufs_lbn_t lbn;
5569 {
5570         struct freefrag *freefrag;
5571         struct ufsmount *ump;
5572         struct fs *fs;
5573
5574         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5575             ip->i_number, blkno, size, lbn);
5576         ump = ITOUMP(ip);
5577         fs = ump->um_fs;
5578         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5579                 panic("newfreefrag: frag size");
5580         freefrag = malloc(sizeof(struct freefrag),
5581             M_FREEFRAG, M_SOFTDEP_FLAGS);
5582         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5583         freefrag->ff_state = ATTACHED;
5584         LIST_INIT(&freefrag->ff_jwork);
5585         freefrag->ff_inum = ip->i_number;
5586         freefrag->ff_vtype = ITOV(ip)->v_type;
5587         freefrag->ff_blkno = blkno;
5588         freefrag->ff_fragsize = size;
5589
5590         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5591                 freefrag->ff_jdep = (struct worklist *)
5592                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5593         } else {
5594                 freefrag->ff_state |= DEPCOMPLETE;
5595                 freefrag->ff_jdep = NULL;
5596         }
5597
5598         return (freefrag);
5599 }
5600
5601 /*
5602  * This workitem de-allocates fragments that were replaced during
5603  * file block allocation.
5604  */
5605 static void 
5606 handle_workitem_freefrag(freefrag)
5607         struct freefrag *freefrag;
5608 {
5609         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5610         struct workhead wkhd;
5611
5612         CTR3(KTR_SUJ,
5613             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5614             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5615         /*
5616          * It would be illegal to add new completion items to the
5617          * freefrag after it was schedule to be done so it must be
5618          * safe to modify the list head here.
5619          */
5620         LIST_INIT(&wkhd);
5621         ACQUIRE_LOCK(ump);
5622         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5623         /*
5624          * If the journal has not been written we must cancel it here.
5625          */
5626         if (freefrag->ff_jdep) {
5627                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5628                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5629                             freefrag->ff_jdep->wk_type);
5630                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5631         }
5632         FREE_LOCK(ump);
5633         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5634            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5635         ACQUIRE_LOCK(ump);
5636         WORKITEM_FREE(freefrag, D_FREEFRAG);
5637         FREE_LOCK(ump);
5638 }
5639
5640 /*
5641  * Set up a dependency structure for an external attributes data block.
5642  * This routine follows much of the structure of softdep_setup_allocdirect.
5643  * See the description of softdep_setup_allocdirect above for details.
5644  */
5645 void 
5646 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5647         struct inode *ip;
5648         ufs_lbn_t off;
5649         ufs2_daddr_t newblkno;
5650         ufs2_daddr_t oldblkno;
5651         long newsize;
5652         long oldsize;
5653         struct buf *bp;
5654 {
5655         struct allocdirect *adp, *oldadp;
5656         struct allocdirectlst *adphead;
5657         struct freefrag *freefrag;
5658         struct inodedep *inodedep;
5659         struct jnewblk *jnewblk;
5660         struct newblk *newblk;
5661         struct mount *mp;
5662         struct ufsmount *ump;
5663         ufs_lbn_t lbn;
5664
5665         mp = ITOVFS(ip);
5666         ump = VFSTOUFS(mp);
5667         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5668             ("softdep_setup_allocext called on non-softdep filesystem"));
5669         KASSERT(off < UFS_NXADDR,
5670             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5671
5672         lbn = bp->b_lblkno;
5673         if (oldblkno && oldblkno != newblkno)
5674                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5675         else
5676                 freefrag = NULL;
5677
5678         ACQUIRE_LOCK(ump);
5679         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5680                 panic("softdep_setup_allocext: lost block");
5681         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5682             ("softdep_setup_allocext: newblk already initialized"));
5683         /*
5684          * Convert the newblk to an allocdirect.
5685          */
5686         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5687         adp = (struct allocdirect *)newblk;
5688         newblk->nb_freefrag = freefrag;
5689         adp->ad_offset = off;
5690         adp->ad_oldblkno = oldblkno;
5691         adp->ad_newsize = newsize;
5692         adp->ad_oldsize = oldsize;
5693         adp->ad_state |=  EXTDATA;
5694
5695         /*
5696          * Finish initializing the journal.
5697          */
5698         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5699                 jnewblk->jn_ino = ip->i_number;
5700                 jnewblk->jn_lbn = lbn;
5701                 add_to_journal(&jnewblk->jn_list);
5702         }
5703         if (freefrag && freefrag->ff_jdep != NULL &&
5704             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5705                 add_to_journal(freefrag->ff_jdep);
5706         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5707         adp->ad_inodedep = inodedep;
5708
5709         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5710         /*
5711          * The list of allocdirects must be kept in sorted and ascending
5712          * order so that the rollback routines can quickly determine the
5713          * first uncommitted block (the size of the file stored on disk
5714          * ends at the end of the lowest committed fragment, or if there
5715          * are no fragments, at the end of the highest committed block).
5716          * Since files generally grow, the typical case is that the new
5717          * block is to be added at the end of the list. We speed this
5718          * special case by checking against the last allocdirect in the
5719          * list before laboriously traversing the list looking for the
5720          * insertion point.
5721          */
5722         adphead = &inodedep->id_newextupdt;
5723         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5724         if (oldadp == NULL || oldadp->ad_offset <= off) {
5725                 /* insert at end of list */
5726                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5727                 if (oldadp != NULL && oldadp->ad_offset == off)
5728                         allocdirect_merge(adphead, adp, oldadp);
5729                 FREE_LOCK(ump);
5730                 return;
5731         }
5732         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5733                 if (oldadp->ad_offset >= off)
5734                         break;
5735         }
5736         if (oldadp == NULL)
5737                 panic("softdep_setup_allocext: lost entry");
5738         /* insert in middle of list */
5739         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5740         if (oldadp->ad_offset == off)
5741                 allocdirect_merge(adphead, adp, oldadp);
5742         FREE_LOCK(ump);
5743 }
5744
5745 /*
5746  * Indirect block allocation dependencies.
5747  * 
5748  * The same dependencies that exist for a direct block also exist when
5749  * a new block is allocated and pointed to by an entry in a block of
5750  * indirect pointers. The undo/redo states described above are also
5751  * used here. Because an indirect block contains many pointers that
5752  * may have dependencies, a second copy of the entire in-memory indirect
5753  * block is kept. The buffer cache copy is always completely up-to-date.
5754  * The second copy, which is used only as a source for disk writes,
5755  * contains only the safe pointers (i.e., those that have no remaining
5756  * update dependencies). The second copy is freed when all pointers
5757  * are safe. The cache is not allowed to replace indirect blocks with
5758  * pending update dependencies. If a buffer containing an indirect
5759  * block with dependencies is written, these routines will mark it
5760  * dirty again. It can only be successfully written once all the
5761  * dependencies are removed. The ffs_fsync routine in conjunction with
5762  * softdep_sync_metadata work together to get all the dependencies
5763  * removed so that a file can be successfully written to disk. Three
5764  * procedures are used when setting up indirect block pointer
5765  * dependencies. The division is necessary because of the organization
5766  * of the "balloc" routine and because of the distinction between file
5767  * pages and file metadata blocks.
5768  */
5769
5770 /*
5771  * Allocate a new allocindir structure.
5772  */
5773 static struct allocindir *
5774 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5775         struct inode *ip;       /* inode for file being extended */
5776         int ptrno;              /* offset of pointer in indirect block */
5777         ufs2_daddr_t newblkno;  /* disk block number being added */
5778         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5779         ufs_lbn_t lbn;
5780 {
5781         struct newblk *newblk;
5782         struct allocindir *aip;
5783         struct freefrag *freefrag;
5784         struct jnewblk *jnewblk;
5785
5786         if (oldblkno)
5787                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn);
5788         else
5789                 freefrag = NULL;
5790         ACQUIRE_LOCK(ITOUMP(ip));
5791         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5792                 panic("new_allocindir: lost block");
5793         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5794             ("newallocindir: newblk already initialized"));
5795         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5796         newblk->nb_freefrag = freefrag;
5797         aip = (struct allocindir *)newblk;
5798         aip->ai_offset = ptrno;
5799         aip->ai_oldblkno = oldblkno;
5800         aip->ai_lbn = lbn;
5801         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5802                 jnewblk->jn_ino = ip->i_number;
5803                 jnewblk->jn_lbn = lbn;
5804                 add_to_journal(&jnewblk->jn_list);
5805         }
5806         if (freefrag && freefrag->ff_jdep != NULL &&
5807             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5808                 add_to_journal(freefrag->ff_jdep);
5809         return (aip);
5810 }
5811
5812 /*
5813  * Called just before setting an indirect block pointer
5814  * to a newly allocated file page.
5815  */
5816 void
5817 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5818         struct inode *ip;       /* inode for file being extended */
5819         ufs_lbn_t lbn;          /* allocated block number within file */
5820         struct buf *bp;         /* buffer with indirect blk referencing page */
5821         int ptrno;              /* offset of pointer in indirect block */
5822         ufs2_daddr_t newblkno;  /* disk block number being added */
5823         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5824         struct buf *nbp;        /* buffer holding allocated page */
5825 {
5826         struct inodedep *inodedep;
5827         struct freefrag *freefrag;
5828         struct allocindir *aip;
5829         struct pagedep *pagedep;
5830         struct mount *mp;
5831         struct ufsmount *ump;
5832
5833         mp = ITOVFS(ip);
5834         ump = VFSTOUFS(mp);
5835         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5836             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5837         KASSERT(lbn == nbp->b_lblkno,
5838             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5839             lbn, bp->b_lblkno));
5840         CTR4(KTR_SUJ,
5841             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5842             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5843         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5844         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5845         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5846         /*
5847          * If we are allocating a directory page, then we must
5848          * allocate an associated pagedep to track additions and
5849          * deletions.
5850          */
5851         if ((ip->i_mode & IFMT) == IFDIR)
5852                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5853         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5854         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5855         FREE_LOCK(ump);
5856         if (freefrag)
5857                 handle_workitem_freefrag(freefrag);
5858 }
5859
5860 /*
5861  * Called just before setting an indirect block pointer to a
5862  * newly allocated indirect block.
5863  */
5864 void
5865 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5866         struct buf *nbp;        /* newly allocated indirect block */
5867         struct inode *ip;       /* inode for file being extended */
5868         struct buf *bp;         /* indirect block referencing allocated block */
5869         int ptrno;              /* offset of pointer in indirect block */
5870         ufs2_daddr_t newblkno;  /* disk block number being added */
5871 {
5872         struct inodedep *inodedep;
5873         struct allocindir *aip;
5874         struct ufsmount *ump;
5875         ufs_lbn_t lbn;
5876
5877         ump = ITOUMP(ip);
5878         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5879             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5880         CTR3(KTR_SUJ,
5881             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5882             ip->i_number, newblkno, ptrno);
5883         lbn = nbp->b_lblkno;
5884         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5885         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5886         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5887         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5888         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5889                 panic("softdep_setup_allocindir_meta: Block already existed");
5890         FREE_LOCK(ump);
5891 }
5892
5893 static void
5894 indirdep_complete(indirdep)
5895         struct indirdep *indirdep;
5896 {
5897         struct allocindir *aip;
5898
5899         LIST_REMOVE(indirdep, ir_next);
5900         indirdep->ir_state |= DEPCOMPLETE;
5901
5902         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5903                 LIST_REMOVE(aip, ai_next);
5904                 free_newblk(&aip->ai_block);
5905         }
5906         /*
5907          * If this indirdep is not attached to a buf it was simply waiting
5908          * on completion to clear completehd.  free_indirdep() asserts
5909          * that nothing is dangling.
5910          */
5911         if ((indirdep->ir_state & ONWORKLIST) == 0)
5912                 free_indirdep(indirdep);
5913 }
5914
5915 static struct indirdep *
5916 indirdep_lookup(mp, ip, bp)
5917         struct mount *mp;
5918         struct inode *ip;
5919         struct buf *bp;
5920 {
5921         struct indirdep *indirdep, *newindirdep;
5922         struct newblk *newblk;
5923         struct ufsmount *ump;
5924         struct worklist *wk;
5925         struct fs *fs;
5926         ufs2_daddr_t blkno;
5927
5928         ump = VFSTOUFS(mp);
5929         LOCK_OWNED(ump);
5930         indirdep = NULL;
5931         newindirdep = NULL;
5932         fs = ump->um_fs;
5933         for (;;) {
5934                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5935                         if (wk->wk_type != D_INDIRDEP)
5936                                 continue;
5937                         indirdep = WK_INDIRDEP(wk);
5938                         break;
5939                 }
5940                 /* Found on the buffer worklist, no new structure to free. */
5941                 if (indirdep != NULL && newindirdep == NULL)
5942                         return (indirdep);
5943                 if (indirdep != NULL && newindirdep != NULL)
5944                         panic("indirdep_lookup: simultaneous create");
5945                 /* None found on the buffer and a new structure is ready. */
5946                 if (indirdep == NULL && newindirdep != NULL)
5947                         break;
5948                 /* None found and no new structure available. */
5949                 FREE_LOCK(ump);
5950                 newindirdep = malloc(sizeof(struct indirdep),
5951                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5952                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5953                 newindirdep->ir_state = ATTACHED;
5954                 if (I_IS_UFS1(ip))
5955                         newindirdep->ir_state |= UFS1FMT;
5956                 TAILQ_INIT(&newindirdep->ir_trunc);
5957                 newindirdep->ir_saveddata = NULL;
5958                 LIST_INIT(&newindirdep->ir_deplisthd);
5959                 LIST_INIT(&newindirdep->ir_donehd);
5960                 LIST_INIT(&newindirdep->ir_writehd);
5961                 LIST_INIT(&newindirdep->ir_completehd);
5962                 if (bp->b_blkno == bp->b_lblkno) {
5963                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5964                             NULL, NULL);
5965                         bp->b_blkno = blkno;
5966                 }
5967                 newindirdep->ir_freeblks = NULL;
5968                 newindirdep->ir_savebp =
5969                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5970                 newindirdep->ir_bp = bp;
5971                 BUF_KERNPROC(newindirdep->ir_savebp);
5972                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5973                 ACQUIRE_LOCK(ump);
5974         }
5975         indirdep = newindirdep;
5976         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5977         /*
5978          * If the block is not yet allocated we don't set DEPCOMPLETE so
5979          * that we don't free dependencies until the pointers are valid.
5980          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5981          * than using the hash.
5982          */
5983         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5984                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5985         else
5986                 indirdep->ir_state |= DEPCOMPLETE;
5987         return (indirdep);
5988 }
5989
5990 /*
5991  * Called to finish the allocation of the "aip" allocated
5992  * by one of the two routines above.
5993  */
5994 static struct freefrag *
5995 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5996         struct buf *bp;         /* in-memory copy of the indirect block */
5997         struct inode *ip;       /* inode for file being extended */
5998         struct inodedep *inodedep; /* Inodedep for ip */
5999         struct allocindir *aip; /* allocindir allocated by the above routines */
6000         ufs_lbn_t lbn;          /* Logical block number for this block. */
6001 {
6002         struct fs *fs;
6003         struct indirdep *indirdep;
6004         struct allocindir *oldaip;
6005         struct freefrag *freefrag;
6006         struct mount *mp;
6007         struct ufsmount *ump;
6008
6009         mp = ITOVFS(ip);
6010         ump = VFSTOUFS(mp);
6011         LOCK_OWNED(ump);
6012         fs = ump->um_fs;
6013         if (bp->b_lblkno >= 0)
6014                 panic("setup_allocindir_phase2: not indir blk");
6015         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6016             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6017         indirdep = indirdep_lookup(mp, ip, bp);
6018         KASSERT(indirdep->ir_savebp != NULL,
6019             ("setup_allocindir_phase2 NULL ir_savebp"));
6020         aip->ai_indirdep = indirdep;
6021         /*
6022          * Check for an unwritten dependency for this indirect offset.  If
6023          * there is, merge the old dependency into the new one.  This happens
6024          * as a result of reallocblk only.
6025          */
6026         freefrag = NULL;
6027         if (aip->ai_oldblkno != 0) {
6028                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6029                         if (oldaip->ai_offset == aip->ai_offset) {
6030                                 freefrag = allocindir_merge(aip, oldaip);
6031                                 goto done;
6032                         }
6033                 }
6034                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6035                         if (oldaip->ai_offset == aip->ai_offset) {
6036                                 freefrag = allocindir_merge(aip, oldaip);
6037                                 goto done;
6038                         }
6039                 }
6040         }
6041 done:
6042         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6043         return (freefrag);
6044 }
6045
6046 /*
6047  * Merge two allocindirs which refer to the same block.  Move newblock
6048  * dependencies and setup the freefrags appropriately.
6049  */
6050 static struct freefrag *
6051 allocindir_merge(aip, oldaip)
6052         struct allocindir *aip;
6053         struct allocindir *oldaip;
6054 {
6055         struct freefrag *freefrag;
6056         struct worklist *wk;
6057
6058         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6059                 panic("allocindir_merge: blkno");
6060         aip->ai_oldblkno = oldaip->ai_oldblkno;
6061         freefrag = aip->ai_freefrag;
6062         aip->ai_freefrag = oldaip->ai_freefrag;
6063         oldaip->ai_freefrag = NULL;
6064         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6065         /*
6066          * If we are tracking a new directory-block allocation,
6067          * move it from the old allocindir to the new allocindir.
6068          */
6069         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6070                 WORKLIST_REMOVE(wk);
6071                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6072                         panic("allocindir_merge: extra newdirblk");
6073                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6074         }
6075         /*
6076          * We can skip journaling for this freefrag and just complete
6077          * any pending journal work for the allocindir that is being
6078          * removed after the freefrag completes.
6079          */
6080         if (freefrag->ff_jdep)
6081                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6082         LIST_REMOVE(oldaip, ai_next);
6083         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6084             &freefrag->ff_list, &freefrag->ff_jwork);
6085         free_newblk(&oldaip->ai_block);
6086
6087         return (freefrag);
6088 }
6089
6090 static inline void
6091 setup_freedirect(freeblks, ip, i, needj)
6092         struct freeblks *freeblks;
6093         struct inode *ip;
6094         int i;
6095         int needj;
6096 {
6097         struct ufsmount *ump;
6098         ufs2_daddr_t blkno;
6099         int frags;
6100
6101         blkno = DIP(ip, i_db[i]);
6102         if (blkno == 0)
6103                 return;
6104         DIP_SET(ip, i_db[i], 0);
6105         ump = ITOUMP(ip);
6106         frags = sblksize(ump->um_fs, ip->i_size, i);
6107         frags = numfrags(ump->um_fs, frags);
6108         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6109 }
6110
6111 static inline void
6112 setup_freeext(freeblks, ip, i, needj)
6113         struct freeblks *freeblks;
6114         struct inode *ip;
6115         int i;
6116         int needj;
6117 {
6118         struct ufsmount *ump;
6119         ufs2_daddr_t blkno;
6120         int frags;
6121
6122         blkno = ip->i_din2->di_extb[i];
6123         if (blkno == 0)
6124                 return;
6125         ip->i_din2->di_extb[i] = 0;
6126         ump = ITOUMP(ip);
6127         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6128         frags = numfrags(ump->um_fs, frags);
6129         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6130 }
6131
6132 static inline void
6133 setup_freeindir(freeblks, ip, i, lbn, needj)
6134         struct freeblks *freeblks;
6135         struct inode *ip;
6136         int i;
6137         ufs_lbn_t lbn;
6138         int needj;
6139 {
6140         struct ufsmount *ump;
6141         ufs2_daddr_t blkno;
6142
6143         blkno = DIP(ip, i_ib[i]);
6144         if (blkno == 0)
6145                 return;
6146         DIP_SET(ip, i_ib[i], 0);
6147         ump = ITOUMP(ip);
6148         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6149             0, needj);
6150 }
6151
6152 static inline struct freeblks *
6153 newfreeblks(mp, ip)
6154         struct mount *mp;
6155         struct inode *ip;
6156 {
6157         struct freeblks *freeblks;
6158
6159         freeblks = malloc(sizeof(struct freeblks),
6160                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6161         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6162         LIST_INIT(&freeblks->fb_jblkdephd);
6163         LIST_INIT(&freeblks->fb_jwork);
6164         freeblks->fb_ref = 0;
6165         freeblks->fb_cgwait = 0;
6166         freeblks->fb_state = ATTACHED;
6167         freeblks->fb_uid = ip->i_uid;
6168         freeblks->fb_inum = ip->i_number;
6169         freeblks->fb_vtype = ITOV(ip)->v_type;
6170         freeblks->fb_modrev = DIP(ip, i_modrev);
6171         freeblks->fb_devvp = ITODEVVP(ip);
6172         freeblks->fb_chkcnt = 0;
6173         freeblks->fb_len = 0;
6174
6175         return (freeblks);
6176 }
6177
6178 static void
6179 trunc_indirdep(indirdep, freeblks, bp, off)
6180         struct indirdep *indirdep;
6181         struct freeblks *freeblks;
6182         struct buf *bp;
6183         int off;
6184 {
6185         struct allocindir *aip, *aipn;
6186
6187         /*
6188          * The first set of allocindirs won't be in savedbp.
6189          */
6190         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6191                 if (aip->ai_offset > off)
6192                         cancel_allocindir(aip, bp, freeblks, 1);
6193         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6194                 if (aip->ai_offset > off)
6195                         cancel_allocindir(aip, bp, freeblks, 1);
6196         /*
6197          * These will exist in savedbp.
6198          */
6199         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6200                 if (aip->ai_offset > off)
6201                         cancel_allocindir(aip, NULL, freeblks, 0);
6202         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6203                 if (aip->ai_offset > off)
6204                         cancel_allocindir(aip, NULL, freeblks, 0);
6205 }
6206
6207 /*
6208  * Follow the chain of indirects down to lastlbn creating a freework
6209  * structure for each.  This will be used to start indir_trunc() at
6210  * the right offset and create the journal records for the parrtial
6211  * truncation.  A second step will handle the truncated dependencies.
6212  */
6213 static int
6214 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6215         struct freeblks *freeblks;
6216         struct inode *ip;
6217         ufs_lbn_t lbn;
6218         ufs_lbn_t lastlbn;
6219         ufs2_daddr_t blkno;
6220 {
6221         struct indirdep *indirdep;
6222         struct indirdep *indirn;
6223         struct freework *freework;
6224         struct newblk *newblk;
6225         struct mount *mp;
6226         struct ufsmount *ump;
6227         struct buf *bp;
6228         uint8_t *start;
6229         uint8_t *end;
6230         ufs_lbn_t lbnadd;
6231         int level;
6232         int error;
6233         int off;
6234
6235
6236         freework = NULL;
6237         if (blkno == 0)
6238                 return (0);
6239         mp = freeblks->fb_list.wk_mp;
6240         ump = VFSTOUFS(mp);
6241         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6242         if ((bp->b_flags & B_CACHE) == 0) {
6243                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6244                 bp->b_iocmd = BIO_READ;
6245                 bp->b_flags &= ~B_INVAL;
6246                 bp->b_ioflags &= ~BIO_ERROR;
6247                 vfs_busy_pages(bp, 0);
6248                 bp->b_iooffset = dbtob(bp->b_blkno);
6249                 bstrategy(bp);
6250 #ifdef RACCT
6251                 if (racct_enable) {
6252                         PROC_LOCK(curproc);
6253                         racct_add_buf(curproc, bp, 0);
6254                         PROC_UNLOCK(curproc);
6255                 }
6256 #endif /* RACCT */
6257                 curthread->td_ru.ru_inblock++;
6258                 error = bufwait(bp);
6259                 if (error) {
6260                         brelse(bp);
6261                         return (error);
6262                 }
6263         }
6264         level = lbn_level(lbn);
6265         lbnadd = lbn_offset(ump->um_fs, level);
6266         /*
6267          * Compute the offset of the last block we want to keep.  Store
6268          * in the freework the first block we want to completely free.
6269          */
6270         off = (lastlbn - -(lbn + level)) / lbnadd;
6271         if (off + 1 == NINDIR(ump->um_fs))
6272                 goto nowork;
6273         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6274         /*
6275          * Link the freework into the indirdep.  This will prevent any new
6276          * allocations from proceeding until we are finished with the
6277          * truncate and the block is written.
6278          */
6279         ACQUIRE_LOCK(ump);
6280         indirdep = indirdep_lookup(mp, ip, bp);
6281         if (indirdep->ir_freeblks)
6282                 panic("setup_trunc_indir: indirdep already truncated.");
6283         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6284         freework->fw_indir = indirdep;
6285         /*
6286          * Cancel any allocindirs that will not make it to disk.
6287          * We have to do this for all copies of the indirdep that
6288          * live on this newblk.
6289          */
6290         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6291                 newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0, &newblk);
6292                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6293                         trunc_indirdep(indirn, freeblks, bp, off);
6294         } else
6295                 trunc_indirdep(indirdep, freeblks, bp, off);
6296         FREE_LOCK(ump);
6297         /*
6298          * Creation is protected by the buf lock. The saveddata is only
6299          * needed if a full truncation follows a partial truncation but it
6300          * is difficult to allocate in that case so we fetch it anyway.
6301          */
6302         if (indirdep->ir_saveddata == NULL)
6303                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6304                     M_SOFTDEP_FLAGS);
6305 nowork:
6306         /* Fetch the blkno of the child and the zero start offset. */
6307         if (I_IS_UFS1(ip)) {
6308                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6309                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6310         } else {
6311                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6312                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6313         }
6314         if (freework) {
6315                 /* Zero the truncated pointers. */
6316                 end = bp->b_data + bp->b_bcount;
6317                 bzero(start, end - start);
6318                 bdwrite(bp);
6319         } else
6320                 bqrelse(bp);
6321         if (level == 0)
6322                 return (0);
6323         lbn++; /* adjust level */
6324         lbn -= (off * lbnadd);
6325         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6326 }
6327
6328 /*
6329  * Complete the partial truncation of an indirect block setup by
6330  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6331  * copy and writes them to disk before the freeblks is allowed to complete.
6332  */
6333 static void
6334 complete_trunc_indir(freework)
6335         struct freework *freework;
6336 {
6337         struct freework *fwn;
6338         struct indirdep *indirdep;
6339         struct ufsmount *ump;
6340         struct buf *bp;
6341         uintptr_t start;
6342         int count;
6343
6344         ump = VFSTOUFS(freework->fw_list.wk_mp);
6345         LOCK_OWNED(ump);
6346         indirdep = freework->fw_indir;
6347         for (;;) {
6348                 bp = indirdep->ir_bp;
6349                 /* See if the block was discarded. */
6350                 if (bp == NULL)
6351                         break;
6352                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6353                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6354                         break;
6355                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6356                     LOCK_PTR(ump)) == 0)
6357                         BUF_UNLOCK(bp);
6358                 ACQUIRE_LOCK(ump);
6359         }
6360         freework->fw_state |= DEPCOMPLETE;
6361         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6362         /*
6363          * Zero the pointers in the saved copy.
6364          */
6365         if (indirdep->ir_state & UFS1FMT)
6366                 start = sizeof(ufs1_daddr_t);
6367         else
6368                 start = sizeof(ufs2_daddr_t);
6369         start *= freework->fw_start;
6370         count = indirdep->ir_savebp->b_bcount - start;
6371         start += (uintptr_t)indirdep->ir_savebp->b_data;
6372         bzero((char *)start, count);
6373         /*
6374          * We need to start the next truncation in the list if it has not
6375          * been started yet.
6376          */
6377         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6378         if (fwn != NULL) {
6379                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6380                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6381                 if ((fwn->fw_state & ONWORKLIST) == 0)
6382                         freework_enqueue(fwn);
6383         }
6384         /*
6385          * If bp is NULL the block was fully truncated, restore
6386          * the saved block list otherwise free it if it is no
6387          * longer needed.
6388          */
6389         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6390                 if (bp == NULL)
6391                         bcopy(indirdep->ir_saveddata,
6392                             indirdep->ir_savebp->b_data,
6393                             indirdep->ir_savebp->b_bcount);
6394                 free(indirdep->ir_saveddata, M_INDIRDEP);
6395                 indirdep->ir_saveddata = NULL;
6396         }
6397         /*
6398          * When bp is NULL there is a full truncation pending.  We
6399          * must wait for this full truncation to be journaled before
6400          * we can release this freework because the disk pointers will
6401          * never be written as zero.
6402          */
6403         if (bp == NULL)  {
6404                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6405                         handle_written_freework(freework);
6406                 else
6407                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6408                            &freework->fw_list);
6409         } else {
6410                 /* Complete when the real copy is written. */
6411                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6412                 BUF_UNLOCK(bp);
6413         }
6414 }
6415
6416 /*
6417  * Calculate the number of blocks we are going to release where datablocks
6418  * is the current total and length is the new file size.
6419  */
6420 static ufs2_daddr_t
6421 blkcount(fs, datablocks, length)
6422         struct fs *fs;
6423         ufs2_daddr_t datablocks;
6424         off_t length;
6425 {
6426         off_t totblks, numblks;
6427
6428         totblks = 0;
6429         numblks = howmany(length, fs->fs_bsize);
6430         if (numblks <= UFS_NDADDR) {
6431                 totblks = howmany(length, fs->fs_fsize);
6432                 goto out;
6433         }
6434         totblks = blkstofrags(fs, numblks);
6435         numblks -= UFS_NDADDR;
6436         /*
6437          * Count all single, then double, then triple indirects required.
6438          * Subtracting one indirects worth of blocks for each pass
6439          * acknowledges one of each pointed to by the inode.
6440          */
6441         for (;;) {
6442                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6443                 numblks -= NINDIR(fs);
6444                 if (numblks <= 0)
6445                         break;
6446                 numblks = howmany(numblks, NINDIR(fs));
6447         }
6448 out:
6449         totblks = fsbtodb(fs, totblks);
6450         /*
6451          * Handle sparse files.  We can't reclaim more blocks than the inode
6452          * references.  We will correct it later in handle_complete_freeblks()
6453          * when we know the real count.
6454          */
6455         if (totblks > datablocks)
6456                 return (0);
6457         return (datablocks - totblks);
6458 }
6459
6460 /*
6461  * Handle freeblocks for journaled softupdate filesystems.
6462  *
6463  * Contrary to normal softupdates, we must preserve the block pointers in
6464  * indirects until their subordinates are free.  This is to avoid journaling
6465  * every block that is freed which may consume more space than the journal
6466  * itself.  The recovery program will see the free block journals at the
6467  * base of the truncated area and traverse them to reclaim space.  The
6468  * pointers in the inode may be cleared immediately after the journal
6469  * records are written because each direct and indirect pointer in the
6470  * inode is recorded in a journal.  This permits full truncation to proceed
6471  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6472  *
6473  * The algorithm is as follows:
6474  * 1) Traverse the in-memory state and create journal entries to release
6475  *    the relevant blocks and full indirect trees.
6476  * 2) Traverse the indirect block chain adding partial truncation freework
6477  *    records to indirects in the path to lastlbn.  The freework will
6478  *    prevent new allocation dependencies from being satisfied in this
6479  *    indirect until the truncation completes.
6480  * 3) Read and lock the inode block, performing an update with the new size
6481  *    and pointers.  This prevents truncated data from becoming valid on
6482  *    disk through step 4.
6483  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6484  *    eliminate journal work for those records that do not require it.
6485  * 5) Schedule the journal records to be written followed by the inode block.
6486  * 6) Allocate any necessary frags for the end of file.
6487  * 7) Zero any partially truncated blocks.
6488  *
6489  * From this truncation proceeds asynchronously using the freework and
6490  * indir_trunc machinery.  The file will not be extended again into a
6491  * partially truncated indirect block until all work is completed but
6492  * the normal dependency mechanism ensures that it is rolled back/forward
6493  * as appropriate.  Further truncation may occur without delay and is
6494  * serialized in indir_trunc().
6495  */
6496 void
6497 softdep_journal_freeblocks(ip, cred, length, flags)
6498         struct inode *ip;       /* The inode whose length is to be reduced */
6499         struct ucred *cred;
6500         off_t length;           /* The new length for the file */
6501         int flags;              /* IO_EXT and/or IO_NORMAL */
6502 {
6503         struct freeblks *freeblks, *fbn;
6504         struct worklist *wk, *wkn;
6505         struct inodedep *inodedep;
6506         struct jblkdep *jblkdep;
6507         struct allocdirect *adp, *adpn;
6508         struct ufsmount *ump;
6509         struct fs *fs;
6510         struct buf *bp;
6511         struct vnode *vp;
6512         struct mount *mp;
6513         ufs2_daddr_t extblocks, datablocks;
6514         ufs_lbn_t tmpval, lbn, lastlbn;
6515         int frags, lastoff, iboff, allocblock, needj, error, i;
6516
6517         ump = ITOUMP(ip);
6518         mp = UFSTOVFS(ump);
6519         fs = ump->um_fs;
6520         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6521             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6522         vp = ITOV(ip);
6523         needj = 1;
6524         iboff = -1;
6525         allocblock = 0;
6526         extblocks = 0;
6527         datablocks = 0;
6528         frags = 0;
6529         freeblks = newfreeblks(mp, ip);
6530         ACQUIRE_LOCK(ump);
6531         /*
6532          * If we're truncating a removed file that will never be written
6533          * we don't need to journal the block frees.  The canceled journals
6534          * for the allocations will suffice.
6535          */
6536         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6537         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6538             length == 0)
6539                 needj = 0;
6540         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6541             ip->i_number, length, needj);
6542         FREE_LOCK(ump);
6543         /*
6544          * Calculate the lbn that we are truncating to.  This results in -1
6545          * if we're truncating the 0 bytes.  So it is the last lbn we want
6546          * to keep, not the first lbn we want to truncate.
6547          */
6548         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6549         lastoff = blkoff(fs, length);
6550         /*
6551          * Compute frags we are keeping in lastlbn.  0 means all.
6552          */
6553         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6554                 frags = fragroundup(fs, lastoff);
6555                 /* adp offset of last valid allocdirect. */
6556                 iboff = lastlbn;
6557         } else if (lastlbn > 0)
6558                 iboff = UFS_NDADDR;
6559         if (fs->fs_magic == FS_UFS2_MAGIC)
6560                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6561         /*
6562          * Handle normal data blocks and indirects.  This section saves
6563          * values used after the inode update to complete frag and indirect
6564          * truncation.
6565          */
6566         if ((flags & IO_NORMAL) != 0) {
6567                 /*
6568                  * Handle truncation of whole direct and indirect blocks.
6569                  */
6570                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6571                         setup_freedirect(freeblks, ip, i, needj);
6572                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6573                     i < UFS_NIADDR;
6574                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6575                         /* Release a whole indirect tree. */
6576                         if (lbn > lastlbn) {
6577                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6578                                     needj);
6579                                 continue;
6580                         }
6581                         iboff = i + UFS_NDADDR;
6582                         /*
6583                          * Traverse partially truncated indirect tree.
6584                          */
6585                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6586                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6587                                     lastlbn, DIP(ip, i_ib[i]));
6588                 }
6589                 /*
6590                  * Handle partial truncation to a frag boundary.
6591                  */
6592                 if (frags) {
6593                         ufs2_daddr_t blkno;
6594                         long oldfrags;
6595
6596                         oldfrags = blksize(fs, ip, lastlbn);
6597                         blkno = DIP(ip, i_db[lastlbn]);
6598                         if (blkno && oldfrags != frags) {
6599                                 oldfrags -= frags;
6600                                 oldfrags = numfrags(fs, oldfrags);
6601                                 blkno += numfrags(fs, frags);
6602                                 newfreework(ump, freeblks, NULL, lastlbn,
6603                                     blkno, oldfrags, 0, needj);
6604                                 if (needj)
6605                                         adjust_newfreework(freeblks,
6606                                             numfrags(fs, frags));
6607                         } else if (blkno == 0)
6608                                 allocblock = 1;
6609                 }
6610                 /*
6611                  * Add a journal record for partial truncate if we are
6612                  * handling indirect blocks.  Non-indirects need no extra
6613                  * journaling.
6614                  */
6615                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6616                         ip->i_flag |= IN_TRUNCATED;
6617                         newjtrunc(freeblks, length, 0);
6618                 }
6619                 ip->i_size = length;
6620                 DIP_SET(ip, i_size, ip->i_size);
6621                 datablocks = DIP(ip, i_blocks) - extblocks;
6622                 if (length != 0)
6623                         datablocks = blkcount(fs, datablocks, length);
6624                 freeblks->fb_len = length;
6625         }
6626         if ((flags & IO_EXT) != 0) {
6627                 for (i = 0; i < UFS_NXADDR; i++)
6628                         setup_freeext(freeblks, ip, i, needj);
6629                 ip->i_din2->di_extsize = 0;
6630                 datablocks += extblocks;
6631         }
6632 #ifdef QUOTA
6633         /* Reference the quotas in case the block count is wrong in the end. */
6634         quotaref(vp, freeblks->fb_quota);
6635         (void) chkdq(ip, -datablocks, NOCRED, 0);
6636 #endif
6637         freeblks->fb_chkcnt = -datablocks;
6638         UFS_LOCK(ump);
6639         fs->fs_pendingblocks += datablocks;
6640         UFS_UNLOCK(ump);
6641         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6642         /*
6643          * Handle truncation of incomplete alloc direct dependencies.  We
6644          * hold the inode block locked to prevent incomplete dependencies
6645          * from reaching the disk while we are eliminating those that
6646          * have been truncated.  This is a partially inlined ffs_update().
6647          */
6648         ufs_itimes(vp);
6649         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6650         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6651             (int)fs->fs_bsize, cred, &bp);
6652         if (error) {
6653                 brelse(bp);
6654                 softdep_error("softdep_journal_freeblocks", error);
6655                 return;
6656         }
6657         if (bp->b_bufsize == fs->fs_bsize)
6658                 bp->b_flags |= B_CLUSTEROK;
6659         softdep_update_inodeblock(ip, bp, 0);
6660         if (ump->um_fstype == UFS1)
6661                 *((struct ufs1_dinode *)bp->b_data +
6662                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6663         else
6664                 *((struct ufs2_dinode *)bp->b_data +
6665                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6666         ACQUIRE_LOCK(ump);
6667         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6668         if ((inodedep->id_state & IOSTARTED) != 0)
6669                 panic("softdep_setup_freeblocks: inode busy");
6670         /*
6671          * Add the freeblks structure to the list of operations that
6672          * must await the zero'ed inode being written to disk. If we
6673          * still have a bitmap dependency (needj), then the inode
6674          * has never been written to disk, so we can process the
6675          * freeblks below once we have deleted the dependencies.
6676          */
6677         if (needj)
6678                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6679         else
6680                 freeblks->fb_state |= COMPLETE;
6681         if ((flags & IO_NORMAL) != 0) {
6682                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6683                         if (adp->ad_offset > iboff)
6684                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6685                                     freeblks);
6686                         /*
6687                          * Truncate the allocdirect.  We could eliminate
6688                          * or modify journal records as well.
6689                          */
6690                         else if (adp->ad_offset == iboff && frags)
6691                                 adp->ad_newsize = frags;
6692                 }
6693         }
6694         if ((flags & IO_EXT) != 0)
6695                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6696                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6697                             freeblks);
6698         /*
6699          * Scan the bufwait list for newblock dependencies that will never
6700          * make it to disk.
6701          */
6702         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6703                 if (wk->wk_type != D_ALLOCDIRECT)
6704                         continue;
6705                 adp = WK_ALLOCDIRECT(wk);
6706                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6707                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6708                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6709                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6710                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6711                 }
6712         }
6713         /*
6714          * Add journal work.
6715          */
6716         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6717                 add_to_journal(&jblkdep->jb_list);
6718         FREE_LOCK(ump);
6719         bdwrite(bp);
6720         /*
6721          * Truncate dependency structures beyond length.
6722          */
6723         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6724         /*
6725          * This is only set when we need to allocate a fragment because
6726          * none existed at the end of a frag-sized file.  It handles only
6727          * allocating a new, zero filled block.
6728          */
6729         if (allocblock) {
6730                 ip->i_size = length - lastoff;
6731                 DIP_SET(ip, i_size, ip->i_size);
6732                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6733                 if (error != 0) {
6734                         softdep_error("softdep_journal_freeblks", error);
6735                         return;
6736                 }
6737                 ip->i_size = length;
6738                 DIP_SET(ip, i_size, length);
6739                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6740                 allocbuf(bp, frags);
6741                 ffs_update(vp, 0);
6742                 bawrite(bp);
6743         } else if (lastoff != 0 && vp->v_type != VDIR) {
6744                 int size;
6745
6746                 /*
6747                  * Zero the end of a truncated frag or block.
6748                  */
6749                 size = sblksize(fs, length, lastlbn);
6750                 error = bread(vp, lastlbn, size, cred, &bp);
6751                 if (error) {
6752                         softdep_error("softdep_journal_freeblks", error);
6753                         return;
6754                 }
6755                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6756                 bawrite(bp);
6757
6758         }
6759         ACQUIRE_LOCK(ump);
6760         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6761         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6762         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6763         /*
6764          * We zero earlier truncations so they don't erroneously
6765          * update i_blocks.
6766          */
6767         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6768                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6769                         fbn->fb_len = 0;
6770         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6771             LIST_EMPTY(&freeblks->fb_jblkdephd))
6772                 freeblks->fb_state |= INPROGRESS;
6773         else
6774                 freeblks = NULL;
6775         FREE_LOCK(ump);
6776         if (freeblks)
6777                 handle_workitem_freeblocks(freeblks, 0);
6778         trunc_pages(ip, length, extblocks, flags);
6779
6780 }
6781
6782 /*
6783  * Flush a JOP_SYNC to the journal.
6784  */
6785 void
6786 softdep_journal_fsync(ip)
6787         struct inode *ip;
6788 {
6789         struct jfsync *jfsync;
6790         struct ufsmount *ump;
6791
6792         ump = ITOUMP(ip);
6793         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6794             ("softdep_journal_fsync called on non-softdep filesystem"));
6795         if ((ip->i_flag & IN_TRUNCATED) == 0)
6796                 return;
6797         ip->i_flag &= ~IN_TRUNCATED;
6798         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6799         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6800         jfsync->jfs_size = ip->i_size;
6801         jfsync->jfs_ino = ip->i_number;
6802         ACQUIRE_LOCK(ump);
6803         add_to_journal(&jfsync->jfs_list);
6804         jwait(&jfsync->jfs_list, MNT_WAIT);
6805         FREE_LOCK(ump);
6806 }
6807
6808 /*
6809  * Block de-allocation dependencies.
6810  * 
6811  * When blocks are de-allocated, the on-disk pointers must be nullified before
6812  * the blocks are made available for use by other files.  (The true
6813  * requirement is that old pointers must be nullified before new on-disk
6814  * pointers are set.  We chose this slightly more stringent requirement to
6815  * reduce complexity.) Our implementation handles this dependency by updating
6816  * the inode (or indirect block) appropriately but delaying the actual block
6817  * de-allocation (i.e., freemap and free space count manipulation) until
6818  * after the updated versions reach stable storage.  After the disk is
6819  * updated, the blocks can be safely de-allocated whenever it is convenient.
6820  * This implementation handles only the common case of reducing a file's
6821  * length to zero. Other cases are handled by the conventional synchronous
6822  * write approach.
6823  *
6824  * The ffs implementation with which we worked double-checks
6825  * the state of the block pointers and file size as it reduces
6826  * a file's length.  Some of this code is replicated here in our
6827  * soft updates implementation.  The freeblks->fb_chkcnt field is
6828  * used to transfer a part of this information to the procedure
6829  * that eventually de-allocates the blocks.
6830  *
6831  * This routine should be called from the routine that shortens
6832  * a file's length, before the inode's size or block pointers
6833  * are modified. It will save the block pointer information for
6834  * later release and zero the inode so that the calling routine
6835  * can release it.
6836  */
6837 void
6838 softdep_setup_freeblocks(ip, length, flags)
6839         struct inode *ip;       /* The inode whose length is to be reduced */
6840         off_t length;           /* The new length for the file */
6841         int flags;              /* IO_EXT and/or IO_NORMAL */
6842 {
6843         struct ufs1_dinode *dp1;
6844         struct ufs2_dinode *dp2;
6845         struct freeblks *freeblks;
6846         struct inodedep *inodedep;
6847         struct allocdirect *adp;
6848         struct ufsmount *ump;
6849         struct buf *bp;
6850         struct fs *fs;
6851         ufs2_daddr_t extblocks, datablocks;
6852         struct mount *mp;
6853         int i, delay, error;
6854         ufs_lbn_t tmpval;
6855         ufs_lbn_t lbn;
6856
6857         ump = ITOUMP(ip);
6858         mp = UFSTOVFS(ump);
6859         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6860             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6861         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6862             ip->i_number, length);
6863         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6864         fs = ump->um_fs;
6865         if ((error = bread(ump->um_devvp,
6866             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6867             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6868                 brelse(bp);
6869                 softdep_error("softdep_setup_freeblocks", error);
6870                 return;
6871         }
6872         freeblks = newfreeblks(mp, ip);
6873         extblocks = 0;
6874         datablocks = 0;
6875         if (fs->fs_magic == FS_UFS2_MAGIC)
6876                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6877         if ((flags & IO_NORMAL) != 0) {
6878                 for (i = 0; i < UFS_NDADDR; i++)
6879                         setup_freedirect(freeblks, ip, i, 0);
6880                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6881                     i < UFS_NIADDR;
6882                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6883                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6884                 ip->i_size = 0;
6885                 DIP_SET(ip, i_size, 0);
6886                 datablocks = DIP(ip, i_blocks) - extblocks;
6887         }
6888         if ((flags & IO_EXT) != 0) {
6889                 for (i = 0; i < UFS_NXADDR; i++)
6890                         setup_freeext(freeblks, ip, i, 0);
6891                 ip->i_din2->di_extsize = 0;
6892                 datablocks += extblocks;
6893         }
6894 #ifdef QUOTA
6895         /* Reference the quotas in case the block count is wrong in the end. */
6896         quotaref(ITOV(ip), freeblks->fb_quota);
6897         (void) chkdq(ip, -datablocks, NOCRED, 0);
6898 #endif
6899         freeblks->fb_chkcnt = -datablocks;
6900         UFS_LOCK(ump);
6901         fs->fs_pendingblocks += datablocks;
6902         UFS_UNLOCK(ump);
6903         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6904         /*
6905          * Push the zero'ed inode to to its disk buffer so that we are free
6906          * to delete its dependencies below. Once the dependencies are gone
6907          * the buffer can be safely released.
6908          */
6909         if (ump->um_fstype == UFS1) {
6910                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6911                     ino_to_fsbo(fs, ip->i_number));
6912                 ip->i_din1->di_freelink = dp1->di_freelink;
6913                 *dp1 = *ip->i_din1;
6914         } else {
6915                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6916                     ino_to_fsbo(fs, ip->i_number));
6917                 ip->i_din2->di_freelink = dp2->di_freelink;
6918                 *dp2 = *ip->i_din2;
6919         }
6920         /*
6921          * Find and eliminate any inode dependencies.
6922          */
6923         ACQUIRE_LOCK(ump);
6924         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6925         if ((inodedep->id_state & IOSTARTED) != 0)
6926                 panic("softdep_setup_freeblocks: inode busy");
6927         /*
6928          * Add the freeblks structure to the list of operations that
6929          * must await the zero'ed inode being written to disk. If we
6930          * still have a bitmap dependency (delay == 0), then the inode
6931          * has never been written to disk, so we can process the
6932          * freeblks below once we have deleted the dependencies.
6933          */
6934         delay = (inodedep->id_state & DEPCOMPLETE);
6935         if (delay)
6936                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6937         else
6938                 freeblks->fb_state |= COMPLETE;
6939         /*
6940          * Because the file length has been truncated to zero, any
6941          * pending block allocation dependency structures associated
6942          * with this inode are obsolete and can simply be de-allocated.
6943          * We must first merge the two dependency lists to get rid of
6944          * any duplicate freefrag structures, then purge the merged list.
6945          * If we still have a bitmap dependency, then the inode has never
6946          * been written to disk, so we can free any fragments without delay.
6947          */
6948         if (flags & IO_NORMAL) {
6949                 merge_inode_lists(&inodedep->id_newinoupdt,
6950                     &inodedep->id_inoupdt);
6951                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6952                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6953                             freeblks);
6954         }
6955         if (flags & IO_EXT) {
6956                 merge_inode_lists(&inodedep->id_newextupdt,
6957                     &inodedep->id_extupdt);
6958                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6959                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6960                             freeblks);
6961         }
6962         FREE_LOCK(ump);
6963         bdwrite(bp);
6964         trunc_dependencies(ip, freeblks, -1, 0, flags);
6965         ACQUIRE_LOCK(ump);
6966         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6967                 (void) free_inodedep(inodedep);
6968         freeblks->fb_state |= DEPCOMPLETE;
6969         /*
6970          * If the inode with zeroed block pointers is now on disk
6971          * we can start freeing blocks.
6972          */  
6973         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6974                 freeblks->fb_state |= INPROGRESS;
6975         else
6976                 freeblks = NULL;
6977         FREE_LOCK(ump);
6978         if (freeblks)
6979                 handle_workitem_freeblocks(freeblks, 0);
6980         trunc_pages(ip, length, extblocks, flags);
6981 }
6982
6983 /*
6984  * Eliminate pages from the page cache that back parts of this inode and
6985  * adjust the vnode pager's idea of our size.  This prevents stale data
6986  * from hanging around in the page cache.
6987  */
6988 static void
6989 trunc_pages(ip, length, extblocks, flags)
6990         struct inode *ip;
6991         off_t length;
6992         ufs2_daddr_t extblocks;
6993         int flags;
6994 {
6995         struct vnode *vp;
6996         struct fs *fs;
6997         ufs_lbn_t lbn;
6998         off_t end, extend;
6999
7000         vp = ITOV(ip);
7001         fs = ITOFS(ip);
7002         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7003         if ((flags & IO_EXT) != 0)
7004                 vn_pages_remove(vp, extend, 0);
7005         if ((flags & IO_NORMAL) == 0)
7006                 return;
7007         BO_LOCK(&vp->v_bufobj);
7008         drain_output(vp);
7009         BO_UNLOCK(&vp->v_bufobj);
7010         /*
7011          * The vnode pager eliminates file pages we eliminate indirects
7012          * below.
7013          */
7014         vnode_pager_setsize(vp, length);
7015         /*
7016          * Calculate the end based on the last indirect we want to keep.  If
7017          * the block extends into indirects we can just use the negative of
7018          * its lbn.  Doubles and triples exist at lower numbers so we must
7019          * be careful not to remove those, if they exist.  double and triple
7020          * indirect lbns do not overlap with others so it is not important
7021          * to verify how many levels are required.
7022          */
7023         lbn = lblkno(fs, length);
7024         if (lbn >= UFS_NDADDR) {
7025                 /* Calculate the virtual lbn of the triple indirect. */
7026                 lbn = -lbn - (UFS_NIADDR - 1);
7027                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7028         } else
7029                 end = extend;
7030         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7031 }
7032
7033 /*
7034  * See if the buf bp is in the range eliminated by truncation.
7035  */
7036 static int
7037 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7038         struct buf *bp;
7039         int *blkoffp;
7040         ufs_lbn_t lastlbn;
7041         int lastoff;
7042         int flags;
7043 {
7044         ufs_lbn_t lbn;
7045
7046         *blkoffp = 0;
7047         /* Only match ext/normal blocks as appropriate. */
7048         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7049             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7050                 return (0);
7051         /* ALTDATA is always a full truncation. */
7052         if ((bp->b_xflags & BX_ALTDATA) != 0)
7053                 return (1);
7054         /* -1 is full truncation. */
7055         if (lastlbn == -1)
7056                 return (1);
7057         /*
7058          * If this is a partial truncate we only want those
7059          * blocks and indirect blocks that cover the range
7060          * we're after.
7061          */
7062         lbn = bp->b_lblkno;
7063         if (lbn < 0)
7064                 lbn = -(lbn + lbn_level(lbn));
7065         if (lbn < lastlbn)
7066                 return (0);
7067         /* Here we only truncate lblkno if it's partial. */
7068         if (lbn == lastlbn) {
7069                 if (lastoff == 0)
7070                         return (0);
7071                 *blkoffp = lastoff;
7072         }
7073         return (1);
7074 }
7075
7076 /*
7077  * Eliminate any dependencies that exist in memory beyond lblkno:off
7078  */
7079 static void
7080 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7081         struct inode *ip;
7082         struct freeblks *freeblks;
7083         ufs_lbn_t lastlbn;
7084         int lastoff;
7085         int flags;
7086 {
7087         struct bufobj *bo;
7088         struct vnode *vp;
7089         struct buf *bp;
7090         int blkoff;
7091
7092         /*
7093          * We must wait for any I/O in progress to finish so that
7094          * all potential buffers on the dirty list will be visible.
7095          * Once they are all there, walk the list and get rid of
7096          * any dependencies.
7097          */
7098         vp = ITOV(ip);
7099         bo = &vp->v_bufobj;
7100         BO_LOCK(bo);
7101         drain_output(vp);
7102         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7103                 bp->b_vflags &= ~BV_SCANNED;
7104 restart:
7105         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7106                 if (bp->b_vflags & BV_SCANNED)
7107                         continue;
7108                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7109                         bp->b_vflags |= BV_SCANNED;
7110                         continue;
7111                 }
7112                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7113                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7114                         goto restart;
7115                 BO_UNLOCK(bo);
7116                 if (deallocate_dependencies(bp, freeblks, blkoff))
7117                         bqrelse(bp);
7118                 else
7119                         brelse(bp);
7120                 BO_LOCK(bo);
7121                 goto restart;
7122         }
7123         /*
7124          * Now do the work of vtruncbuf while also matching indirect blocks.
7125          */
7126         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7127                 bp->b_vflags &= ~BV_SCANNED;
7128 cleanrestart:
7129         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7130                 if (bp->b_vflags & BV_SCANNED)
7131                         continue;
7132                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7133                         bp->b_vflags |= BV_SCANNED;
7134                         continue;
7135                 }
7136                 if (BUF_LOCK(bp,
7137                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7138                     BO_LOCKPTR(bo)) == ENOLCK) {
7139                         BO_LOCK(bo);
7140                         goto cleanrestart;
7141                 }
7142                 bp->b_vflags |= BV_SCANNED;
7143                 bremfree(bp);
7144                 if (blkoff != 0) {
7145                         allocbuf(bp, blkoff);
7146                         bqrelse(bp);
7147                 } else {
7148                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7149                         brelse(bp);
7150                 }
7151                 BO_LOCK(bo);
7152                 goto cleanrestart;
7153         }
7154         drain_output(vp);
7155         BO_UNLOCK(bo);
7156 }
7157
7158 static int
7159 cancel_pagedep(pagedep, freeblks, blkoff)
7160         struct pagedep *pagedep;
7161         struct freeblks *freeblks;
7162         int blkoff;
7163 {
7164         struct jremref *jremref;
7165         struct jmvref *jmvref;
7166         struct dirrem *dirrem, *tmp;
7167         int i;
7168
7169         /*
7170          * Copy any directory remove dependencies to the list
7171          * to be processed after the freeblks proceeds.  If
7172          * directory entry never made it to disk they
7173          * can be dumped directly onto the work list.
7174          */
7175         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7176                 /* Skip this directory removal if it is intended to remain. */
7177                 if (dirrem->dm_offset < blkoff)
7178                         continue;
7179                 /*
7180                  * If there are any dirrems we wait for the journal write
7181                  * to complete and then restart the buf scan as the lock
7182                  * has been dropped.
7183                  */
7184                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7185                         jwait(&jremref->jr_list, MNT_WAIT);
7186                         return (ERESTART);
7187                 }
7188                 LIST_REMOVE(dirrem, dm_next);
7189                 dirrem->dm_dirinum = pagedep->pd_ino;
7190                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7191         }
7192         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7193                 jwait(&jmvref->jm_list, MNT_WAIT);
7194                 return (ERESTART);
7195         }
7196         /*
7197          * When we're partially truncating a pagedep we just want to flush
7198          * journal entries and return.  There can not be any adds in the
7199          * truncated portion of the directory and newblk must remain if
7200          * part of the block remains.
7201          */
7202         if (blkoff != 0) {
7203                 struct diradd *dap;
7204
7205                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7206                         if (dap->da_offset > blkoff)
7207                                 panic("cancel_pagedep: diradd %p off %d > %d",
7208                                     dap, dap->da_offset, blkoff);
7209                 for (i = 0; i < DAHASHSZ; i++)
7210                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7211                                 if (dap->da_offset > blkoff)
7212                                         panic("cancel_pagedep: diradd %p off %d > %d",
7213                                             dap, dap->da_offset, blkoff);
7214                 return (0);
7215         }
7216         /*
7217          * There should be no directory add dependencies present
7218          * as the directory could not be truncated until all
7219          * children were removed.
7220          */
7221         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7222             ("deallocate_dependencies: pendinghd != NULL"));
7223         for (i = 0; i < DAHASHSZ; i++)
7224                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7225                     ("deallocate_dependencies: diraddhd != NULL"));
7226         if ((pagedep->pd_state & NEWBLOCK) != 0)
7227                 free_newdirblk(pagedep->pd_newdirblk);
7228         if (free_pagedep(pagedep) == 0)
7229                 panic("Failed to free pagedep %p", pagedep);
7230         return (0);
7231 }
7232
7233 /*
7234  * Reclaim any dependency structures from a buffer that is about to
7235  * be reallocated to a new vnode. The buffer must be locked, thus,
7236  * no I/O completion operations can occur while we are manipulating
7237  * its associated dependencies. The mutex is held so that other I/O's
7238  * associated with related dependencies do not occur.
7239  */
7240 static int
7241 deallocate_dependencies(bp, freeblks, off)
7242         struct buf *bp;
7243         struct freeblks *freeblks;
7244         int off;
7245 {
7246         struct indirdep *indirdep;
7247         struct pagedep *pagedep;
7248         struct worklist *wk, *wkn;
7249         struct ufsmount *ump;
7250
7251         if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7252                 goto done;
7253         ump = VFSTOUFS(wk->wk_mp);
7254         ACQUIRE_LOCK(ump);
7255         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7256                 switch (wk->wk_type) {
7257                 case D_INDIRDEP:
7258                         indirdep = WK_INDIRDEP(wk);
7259                         if (bp->b_lblkno >= 0 ||
7260                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7261                                 panic("deallocate_dependencies: not indir");
7262                         cancel_indirdep(indirdep, bp, freeblks);
7263                         continue;
7264
7265                 case D_PAGEDEP:
7266                         pagedep = WK_PAGEDEP(wk);
7267                         if (cancel_pagedep(pagedep, freeblks, off)) {
7268                                 FREE_LOCK(ump);
7269                                 return (ERESTART);
7270                         }
7271                         continue;
7272
7273                 case D_ALLOCINDIR:
7274                         /*
7275                          * Simply remove the allocindir, we'll find it via
7276                          * the indirdep where we can clear pointers if
7277                          * needed.
7278                          */
7279                         WORKLIST_REMOVE(wk);
7280                         continue;
7281
7282                 case D_FREEWORK:
7283                         /*
7284                          * A truncation is waiting for the zero'd pointers
7285                          * to be written.  It can be freed when the freeblks
7286                          * is journaled.
7287                          */
7288                         WORKLIST_REMOVE(wk);
7289                         wk->wk_state |= ONDEPLIST;
7290                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7291                         break;
7292
7293                 case D_ALLOCDIRECT:
7294                         if (off != 0)
7295                                 continue;
7296                         /* FALLTHROUGH */
7297                 default:
7298                         panic("deallocate_dependencies: Unexpected type %s",
7299                             TYPENAME(wk->wk_type));
7300                         /* NOTREACHED */
7301                 }
7302         }
7303         FREE_LOCK(ump);
7304 done:
7305         /*
7306          * Don't throw away this buf, we were partially truncating and
7307          * some deps may always remain.
7308          */
7309         if (off) {
7310                 allocbuf(bp, off);
7311                 bp->b_vflags |= BV_SCANNED;
7312                 return (EBUSY);
7313         }
7314         bp->b_flags |= B_INVAL | B_NOCACHE;
7315
7316         return (0);
7317 }
7318
7319 /*
7320  * An allocdirect is being canceled due to a truncate.  We must make sure
7321  * the journal entry is released in concert with the blkfree that releases
7322  * the storage.  Completed journal entries must not be released until the
7323  * space is no longer pointed to by the inode or in the bitmap.
7324  */
7325 static void
7326 cancel_allocdirect(adphead, adp, freeblks)
7327         struct allocdirectlst *adphead;
7328         struct allocdirect *adp;
7329         struct freeblks *freeblks;
7330 {
7331         struct freework *freework;
7332         struct newblk *newblk;
7333         struct worklist *wk;
7334
7335         TAILQ_REMOVE(adphead, adp, ad_next);
7336         newblk = (struct newblk *)adp;
7337         freework = NULL;
7338         /*
7339          * Find the correct freework structure.
7340          */
7341         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7342                 if (wk->wk_type != D_FREEWORK)
7343                         continue;
7344                 freework = WK_FREEWORK(wk);
7345                 if (freework->fw_blkno == newblk->nb_newblkno)
7346                         break;
7347         }
7348         if (freework == NULL)
7349                 panic("cancel_allocdirect: Freework not found");
7350         /*
7351          * If a newblk exists at all we still have the journal entry that
7352          * initiated the allocation so we do not need to journal the free.
7353          */
7354         cancel_jfreeblk(freeblks, freework->fw_blkno);
7355         /*
7356          * If the journal hasn't been written the jnewblk must be passed
7357          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7358          * this by linking the journal dependency into the freework to be
7359          * freed when freework_freeblock() is called.  If the journal has
7360          * been written we can simply reclaim the journal space when the
7361          * freeblks work is complete.
7362          */
7363         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7364             &freeblks->fb_jwork);
7365         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7366 }
7367
7368
7369 /*
7370  * Cancel a new block allocation.  May be an indirect or direct block.  We
7371  * remove it from various lists and return any journal record that needs to
7372  * be resolved by the caller.
7373  *
7374  * A special consideration is made for indirects which were never pointed
7375  * at on disk and will never be found once this block is released.
7376  */
7377 static struct jnewblk *
7378 cancel_newblk(newblk, wk, wkhd)
7379         struct newblk *newblk;
7380         struct worklist *wk;
7381         struct workhead *wkhd;
7382 {
7383         struct jnewblk *jnewblk;
7384
7385         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7386             
7387         newblk->nb_state |= GOINGAWAY;
7388         /*
7389          * Previously we traversed the completedhd on each indirdep
7390          * attached to this newblk to cancel them and gather journal
7391          * work.  Since we need only the oldest journal segment and
7392          * the lowest point on the tree will always have the oldest
7393          * journal segment we are free to release the segments
7394          * of any subordinates and may leave the indirdep list to
7395          * indirdep_complete() when this newblk is freed.
7396          */
7397         if (newblk->nb_state & ONDEPLIST) {
7398                 newblk->nb_state &= ~ONDEPLIST;
7399                 LIST_REMOVE(newblk, nb_deps);
7400         }
7401         if (newblk->nb_state & ONWORKLIST)
7402                 WORKLIST_REMOVE(&newblk->nb_list);
7403         /*
7404          * If the journal entry hasn't been written we save a pointer to
7405          * the dependency that frees it until it is written or the
7406          * superseding operation completes.
7407          */
7408         jnewblk = newblk->nb_jnewblk;
7409         if (jnewblk != NULL && wk != NULL) {
7410                 newblk->nb_jnewblk = NULL;
7411                 jnewblk->jn_dep = wk;
7412         }
7413         if (!LIST_EMPTY(&newblk->nb_jwork))
7414                 jwork_move(wkhd, &newblk->nb_jwork);
7415         /*
7416          * When truncating we must free the newdirblk early to remove
7417          * the pagedep from the hash before returning.
7418          */
7419         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7420                 free_newdirblk(WK_NEWDIRBLK(wk));
7421         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7422                 panic("cancel_newblk: extra newdirblk");
7423
7424         return (jnewblk);
7425 }
7426
7427 /*
7428  * Schedule the freefrag associated with a newblk to be released once
7429  * the pointers are written and the previous block is no longer needed.
7430  */
7431 static void
7432 newblk_freefrag(newblk)
7433         struct newblk *newblk;
7434 {
7435         struct freefrag *freefrag;
7436
7437         if (newblk->nb_freefrag == NULL)
7438                 return;
7439         freefrag = newblk->nb_freefrag;
7440         newblk->nb_freefrag = NULL;
7441         freefrag->ff_state |= COMPLETE;
7442         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7443                 add_to_worklist(&freefrag->ff_list, 0);
7444 }
7445
7446 /*
7447  * Free a newblk. Generate a new freefrag work request if appropriate.
7448  * This must be called after the inode pointer and any direct block pointers
7449  * are valid or fully removed via truncate or frag extension.
7450  */
7451 static void
7452 free_newblk(newblk)
7453         struct newblk *newblk;
7454 {
7455         struct indirdep *indirdep;
7456         struct worklist *wk;
7457
7458         KASSERT(newblk->nb_jnewblk == NULL,
7459             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7460         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7461             ("free_newblk: unclaimed newblk"));
7462         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7463         newblk_freefrag(newblk);
7464         if (newblk->nb_state & ONDEPLIST)
7465                 LIST_REMOVE(newblk, nb_deps);
7466         if (newblk->nb_state & ONWORKLIST)
7467                 WORKLIST_REMOVE(&newblk->nb_list);
7468         LIST_REMOVE(newblk, nb_hash);
7469         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7470                 free_newdirblk(WK_NEWDIRBLK(wk));
7471         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7472                 panic("free_newblk: extra newdirblk");
7473         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7474                 indirdep_complete(indirdep);
7475         handle_jwork(&newblk->nb_jwork);
7476         WORKITEM_FREE(newblk, D_NEWBLK);
7477 }
7478
7479 /*
7480  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7481  * This routine must be called with splbio interrupts blocked.
7482  */
7483 static void
7484 free_newdirblk(newdirblk)
7485         struct newdirblk *newdirblk;
7486 {
7487         struct pagedep *pagedep;
7488         struct diradd *dap;
7489         struct worklist *wk;
7490
7491         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7492         WORKLIST_REMOVE(&newdirblk->db_list);
7493         /*
7494          * If the pagedep is still linked onto the directory buffer
7495          * dependency chain, then some of the entries on the
7496          * pd_pendinghd list may not be committed to disk yet. In
7497          * this case, we will simply clear the NEWBLOCK flag and
7498          * let the pd_pendinghd list be processed when the pagedep
7499          * is next written. If the pagedep is no longer on the buffer
7500          * dependency chain, then all the entries on the pd_pending
7501          * list are committed to disk and we can free them here.
7502          */
7503         pagedep = newdirblk->db_pagedep;
7504         pagedep->pd_state &= ~NEWBLOCK;
7505         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7506                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7507                         free_diradd(dap, NULL);
7508                 /*
7509                  * If no dependencies remain, the pagedep will be freed.
7510                  */
7511                 free_pagedep(pagedep);
7512         }
7513         /* Should only ever be one item in the list. */
7514         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7515                 WORKLIST_REMOVE(wk);
7516                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7517         }
7518         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7519 }
7520
7521 /*
7522  * Prepare an inode to be freed. The actual free operation is not
7523  * done until the zero'ed inode has been written to disk.
7524  */
7525 void
7526 softdep_freefile(pvp, ino, mode)
7527         struct vnode *pvp;
7528         ino_t ino;
7529         int mode;
7530 {
7531         struct inode *ip = VTOI(pvp);
7532         struct inodedep *inodedep;
7533         struct freefile *freefile;
7534         struct freeblks *freeblks;
7535         struct ufsmount *ump;
7536
7537         ump = ITOUMP(ip);
7538         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7539             ("softdep_freefile called on non-softdep filesystem"));
7540         /*
7541          * This sets up the inode de-allocation dependency.
7542          */
7543         freefile = malloc(sizeof(struct freefile),
7544                 M_FREEFILE, M_SOFTDEP_FLAGS);
7545         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7546         freefile->fx_mode = mode;
7547         freefile->fx_oldinum = ino;
7548         freefile->fx_devvp = ump->um_devvp;
7549         LIST_INIT(&freefile->fx_jwork);
7550         UFS_LOCK(ump);
7551         ump->um_fs->fs_pendinginodes += 1;
7552         UFS_UNLOCK(ump);
7553
7554         /*
7555          * If the inodedep does not exist, then the zero'ed inode has
7556          * been written to disk. If the allocated inode has never been
7557          * written to disk, then the on-disk inode is zero'ed. In either
7558          * case we can free the file immediately.  If the journal was
7559          * canceled before being written the inode will never make it to
7560          * disk and we must send the canceled journal entrys to
7561          * ffs_freefile() to be cleared in conjunction with the bitmap.
7562          * Any blocks waiting on the inode to write can be safely freed
7563          * here as it will never been written.
7564          */
7565         ACQUIRE_LOCK(ump);
7566         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7567         if (inodedep) {
7568                 /*
7569                  * Clear out freeblks that no longer need to reference
7570                  * this inode.
7571                  */
7572                 while ((freeblks =
7573                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7574                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7575                             fb_next);
7576                         freeblks->fb_state &= ~ONDEPLIST;
7577                 }
7578                 /*
7579                  * Remove this inode from the unlinked list.
7580                  */
7581                 if (inodedep->id_state & UNLINKED) {
7582                         /*
7583                          * Save the journal work to be freed with the bitmap
7584                          * before we clear UNLINKED.  Otherwise it can be lost
7585                          * if the inode block is written.
7586                          */
7587                         handle_bufwait(inodedep, &freefile->fx_jwork);
7588                         clear_unlinked_inodedep(inodedep);
7589                         /*
7590                          * Re-acquire inodedep as we've dropped the
7591                          * per-filesystem lock in clear_unlinked_inodedep().
7592                          */
7593                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7594                 }
7595         }
7596         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7597                 FREE_LOCK(ump);
7598                 handle_workitem_freefile(freefile);
7599                 return;
7600         }
7601         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7602                 inodedep->id_state |= GOINGAWAY;
7603         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7604         FREE_LOCK(ump);
7605         if (ip->i_number == ino)
7606                 ip->i_flag |= IN_MODIFIED;
7607 }
7608
7609 /*
7610  * Check to see if an inode has never been written to disk. If
7611  * so free the inodedep and return success, otherwise return failure.
7612  * This routine must be called with splbio interrupts blocked.
7613  *
7614  * If we still have a bitmap dependency, then the inode has never
7615  * been written to disk. Drop the dependency as it is no longer
7616  * necessary since the inode is being deallocated. We set the
7617  * ALLCOMPLETE flags since the bitmap now properly shows that the
7618  * inode is not allocated. Even if the inode is actively being
7619  * written, it has been rolled back to its zero'ed state, so we
7620  * are ensured that a zero inode is what is on the disk. For short
7621  * lived files, this change will usually result in removing all the
7622  * dependencies from the inode so that it can be freed immediately.
7623  */
7624 static int
7625 check_inode_unwritten(inodedep)
7626         struct inodedep *inodedep;
7627 {
7628
7629         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7630
7631         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7632             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7633             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7634             !LIST_EMPTY(&inodedep->id_bufwait) ||
7635             !LIST_EMPTY(&inodedep->id_inowait) ||
7636             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7637             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7638             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7639             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7640             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7641             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7642             inodedep->id_mkdiradd != NULL || 
7643             inodedep->id_nlinkdelta != 0)
7644                 return (0);
7645         /*
7646          * Another process might be in initiate_write_inodeblock_ufs[12]
7647          * trying to allocate memory without holding "Softdep Lock".
7648          */
7649         if ((inodedep->id_state & IOSTARTED) != 0 &&
7650             inodedep->id_savedino1 == NULL)
7651                 return (0);
7652
7653         if (inodedep->id_state & ONDEPLIST)
7654                 LIST_REMOVE(inodedep, id_deps);
7655         inodedep->id_state &= ~ONDEPLIST;
7656         inodedep->id_state |= ALLCOMPLETE;
7657         inodedep->id_bmsafemap = NULL;
7658         if (inodedep->id_state & ONWORKLIST)
7659                 WORKLIST_REMOVE(&inodedep->id_list);
7660         if (inodedep->id_savedino1 != NULL) {
7661                 free(inodedep->id_savedino1, M_SAVEDINO);
7662                 inodedep->id_savedino1 = NULL;
7663         }
7664         if (free_inodedep(inodedep) == 0)
7665                 panic("check_inode_unwritten: busy inode");
7666         return (1);
7667 }
7668
7669 static int
7670 check_inodedep_free(inodedep)
7671         struct inodedep *inodedep;
7672 {
7673
7674         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7675         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7676             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7677             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7678             !LIST_EMPTY(&inodedep->id_bufwait) ||
7679             !LIST_EMPTY(&inodedep->id_inowait) ||
7680             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7681             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7682             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7683             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7684             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7685             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7686             inodedep->id_mkdiradd != NULL ||
7687             inodedep->id_nlinkdelta != 0 ||
7688             inodedep->id_savedino1 != NULL)
7689                 return (0);
7690         return (1);
7691 }
7692
7693 /*
7694  * Try to free an inodedep structure. Return 1 if it could be freed.
7695  */
7696 static int
7697 free_inodedep(inodedep)
7698         struct inodedep *inodedep;
7699 {
7700
7701         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7702         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7703             !check_inodedep_free(inodedep))
7704                 return (0);
7705         if (inodedep->id_state & ONDEPLIST)
7706                 LIST_REMOVE(inodedep, id_deps);
7707         LIST_REMOVE(inodedep, id_hash);
7708         WORKITEM_FREE(inodedep, D_INODEDEP);
7709         return (1);
7710 }
7711
7712 /*
7713  * Free the block referenced by a freework structure.  The parent freeblks
7714  * structure is released and completed when the final cg bitmap reaches
7715  * the disk.  This routine may be freeing a jnewblk which never made it to
7716  * disk in which case we do not have to wait as the operation is undone
7717  * in memory immediately.
7718  */
7719 static void
7720 freework_freeblock(freework)
7721         struct freework *freework;
7722 {
7723         struct freeblks *freeblks;
7724         struct jnewblk *jnewblk;
7725         struct ufsmount *ump;
7726         struct workhead wkhd;
7727         struct fs *fs;
7728         int bsize;
7729         int needj;
7730
7731         ump = VFSTOUFS(freework->fw_list.wk_mp);
7732         LOCK_OWNED(ump);
7733         /*
7734          * Handle partial truncate separately.
7735          */
7736         if (freework->fw_indir) {
7737                 complete_trunc_indir(freework);
7738                 return;
7739         }
7740         freeblks = freework->fw_freeblks;
7741         fs = ump->um_fs;
7742         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7743         bsize = lfragtosize(fs, freework->fw_frags);
7744         LIST_INIT(&wkhd);
7745         /*
7746          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7747          * on the indirblk hashtable and prevents premature freeing.
7748          */
7749         freework->fw_state |= DEPCOMPLETE;
7750         /*
7751          * SUJ needs to wait for the segment referencing freed indirect
7752          * blocks to expire so that we know the checker will not confuse
7753          * a re-allocated indirect block with its old contents.
7754          */
7755         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7756                 indirblk_insert(freework);
7757         /*
7758          * If we are canceling an existing jnewblk pass it to the free
7759          * routine, otherwise pass the freeblk which will ultimately
7760          * release the freeblks.  If we're not journaling, we can just
7761          * free the freeblks immediately.
7762          */
7763         jnewblk = freework->fw_jnewblk;
7764         if (jnewblk != NULL) {
7765                 cancel_jnewblk(jnewblk, &wkhd);
7766                 needj = 0;
7767         } else if (needj) {
7768                 freework->fw_state |= DELAYEDFREE;
7769                 freeblks->fb_cgwait++;
7770                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7771         }
7772         FREE_LOCK(ump);
7773         freeblks_free(ump, freeblks, btodb(bsize));
7774         CTR4(KTR_SUJ,
7775             "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7776             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7777         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7778             freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7779         ACQUIRE_LOCK(ump);
7780         /*
7781          * The jnewblk will be discarded and the bits in the map never
7782          * made it to disk.  We can immediately free the freeblk.
7783          */
7784         if (needj == 0)
7785                 handle_written_freework(freework);
7786 }
7787
7788 /*
7789  * We enqueue freework items that need processing back on the freeblks and
7790  * add the freeblks to the worklist.  This makes it easier to find all work
7791  * required to flush a truncation in process_truncates().
7792  */
7793 static void
7794 freework_enqueue(freework)
7795         struct freework *freework;
7796 {
7797         struct freeblks *freeblks;
7798
7799         freeblks = freework->fw_freeblks;
7800         if ((freework->fw_state & INPROGRESS) == 0)
7801                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7802         if ((freeblks->fb_state &
7803             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7804             LIST_EMPTY(&freeblks->fb_jblkdephd))
7805                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7806 }
7807
7808 /*
7809  * Start, continue, or finish the process of freeing an indirect block tree.
7810  * The free operation may be paused at any point with fw_off containing the
7811  * offset to restart from.  This enables us to implement some flow control
7812  * for large truncates which may fan out and generate a huge number of
7813  * dependencies.
7814  */
7815 static void
7816 handle_workitem_indirblk(freework)
7817         struct freework *freework;
7818 {
7819         struct freeblks *freeblks;
7820         struct ufsmount *ump;
7821         struct fs *fs;
7822
7823         freeblks = freework->fw_freeblks;
7824         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7825         fs = ump->um_fs;
7826         if (freework->fw_state & DEPCOMPLETE) {
7827                 handle_written_freework(freework);
7828                 return;
7829         }
7830         if (freework->fw_off == NINDIR(fs)) {
7831                 freework_freeblock(freework);
7832                 return;
7833         }
7834         freework->fw_state |= INPROGRESS;
7835         FREE_LOCK(ump);
7836         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7837             freework->fw_lbn);
7838         ACQUIRE_LOCK(ump);
7839 }
7840
7841 /*
7842  * Called when a freework structure attached to a cg buf is written.  The
7843  * ref on either the parent or the freeblks structure is released and
7844  * the freeblks is added back to the worklist if there is more work to do.
7845  */
7846 static void
7847 handle_written_freework(freework)
7848         struct freework *freework;
7849 {
7850         struct freeblks *freeblks;
7851         struct freework *parent;
7852
7853         freeblks = freework->fw_freeblks;
7854         parent = freework->fw_parent;
7855         if (freework->fw_state & DELAYEDFREE)
7856                 freeblks->fb_cgwait--;
7857         freework->fw_state |= COMPLETE;
7858         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7859                 WORKITEM_FREE(freework, D_FREEWORK);
7860         if (parent) {
7861                 if (--parent->fw_ref == 0)
7862                         freework_enqueue(parent);
7863                 return;
7864         }
7865         if (--freeblks->fb_ref != 0)
7866                 return;
7867         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7868             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7869                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7870 }
7871
7872 /*
7873  * This workitem routine performs the block de-allocation.
7874  * The workitem is added to the pending list after the updated
7875  * inode block has been written to disk.  As mentioned above,
7876  * checks regarding the number of blocks de-allocated (compared
7877  * to the number of blocks allocated for the file) are also
7878  * performed in this function.
7879  */
7880 static int
7881 handle_workitem_freeblocks(freeblks, flags)
7882         struct freeblks *freeblks;
7883         int flags;
7884 {
7885         struct freework *freework;
7886         struct newblk *newblk;
7887         struct allocindir *aip;
7888         struct ufsmount *ump;
7889         struct worklist *wk;
7890
7891         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7892             ("handle_workitem_freeblocks: Journal entries not written."));
7893         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7894         ACQUIRE_LOCK(ump);
7895         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7896                 WORKLIST_REMOVE(wk);
7897                 switch (wk->wk_type) {
7898                 case D_DIRREM:
7899                         wk->wk_state |= COMPLETE;
7900                         add_to_worklist(wk, 0);
7901                         continue;
7902
7903                 case D_ALLOCDIRECT:
7904                         free_newblk(WK_NEWBLK(wk));
7905                         continue;
7906
7907                 case D_ALLOCINDIR:
7908                         aip = WK_ALLOCINDIR(wk);
7909                         freework = NULL;
7910                         if (aip->ai_state & DELAYEDFREE) {
7911                                 FREE_LOCK(ump);
7912                                 freework = newfreework(ump, freeblks, NULL,
7913                                     aip->ai_lbn, aip->ai_newblkno,
7914                                     ump->um_fs->fs_frag, 0, 0);
7915                                 ACQUIRE_LOCK(ump);
7916                         }
7917                         newblk = WK_NEWBLK(wk);
7918                         if (newblk->nb_jnewblk) {
7919                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7920                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7921                                 newblk->nb_jnewblk = NULL;
7922                         }
7923                         free_newblk(newblk);
7924                         continue;
7925
7926                 case D_FREEWORK:
7927                         freework = WK_FREEWORK(wk);
7928                         if (freework->fw_lbn <= -UFS_NDADDR)
7929                                 handle_workitem_indirblk(freework);
7930                         else
7931                                 freework_freeblock(freework);
7932                         continue;
7933                 default:
7934                         panic("handle_workitem_freeblocks: Unknown type %s",
7935                             TYPENAME(wk->wk_type));
7936                 }
7937         }
7938         if (freeblks->fb_ref != 0) {
7939                 freeblks->fb_state &= ~INPROGRESS;
7940                 wake_worklist(&freeblks->fb_list);
7941                 freeblks = NULL;
7942         }
7943         FREE_LOCK(ump);
7944         if (freeblks)
7945                 return handle_complete_freeblocks(freeblks, flags);
7946         return (0);
7947 }
7948
7949 /*
7950  * Handle completion of block free via truncate.  This allows fs_pending
7951  * to track the actual free block count more closely than if we only updated
7952  * it at the end.  We must be careful to handle cases where the block count
7953  * on free was incorrect.
7954  */
7955 static void
7956 freeblks_free(ump, freeblks, blocks)
7957         struct ufsmount *ump;
7958         struct freeblks *freeblks;
7959         int blocks;
7960 {
7961         struct fs *fs;
7962         ufs2_daddr_t remain;
7963
7964         UFS_LOCK(ump);
7965         remain = -freeblks->fb_chkcnt;
7966         freeblks->fb_chkcnt += blocks;
7967         if (remain > 0) {
7968                 if (remain < blocks)
7969                         blocks = remain;
7970                 fs = ump->um_fs;
7971                 fs->fs_pendingblocks -= blocks;
7972         }
7973         UFS_UNLOCK(ump);
7974 }
7975
7976 /*
7977  * Once all of the freework workitems are complete we can retire the
7978  * freeblocks dependency and any journal work awaiting completion.  This
7979  * can not be called until all other dependencies are stable on disk.
7980  */
7981 static int
7982 handle_complete_freeblocks(freeblks, flags)
7983         struct freeblks *freeblks;
7984         int flags;
7985 {
7986         struct inodedep *inodedep;
7987         struct inode *ip;
7988         struct vnode *vp;
7989         struct fs *fs;
7990         struct ufsmount *ump;
7991         ufs2_daddr_t spare;
7992
7993         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7994         fs = ump->um_fs;
7995         flags = LK_EXCLUSIVE | flags;
7996         spare = freeblks->fb_chkcnt;
7997
7998         /*
7999          * If we did not release the expected number of blocks we may have
8000          * to adjust the inode block count here.  Only do so if it wasn't
8001          * a truncation to zero and the modrev still matches.
8002          */
8003         if (spare && freeblks->fb_len != 0) {
8004                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8005                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8006                         return (EBUSY);
8007                 ip = VTOI(vp);
8008                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8009                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8010                         ip->i_flag |= IN_CHANGE;
8011                         /*
8012                          * We must wait so this happens before the
8013                          * journal is reclaimed.
8014                          */
8015                         ffs_update(vp, 1);
8016                 }
8017                 vput(vp);
8018         }
8019         if (spare < 0) {
8020                 UFS_LOCK(ump);
8021                 fs->fs_pendingblocks += spare;
8022                 UFS_UNLOCK(ump);
8023         }
8024 #ifdef QUOTA
8025         /* Handle spare. */
8026         if (spare)
8027                 quotaadj(freeblks->fb_quota, ump, -spare);
8028         quotarele(freeblks->fb_quota);
8029 #endif
8030         ACQUIRE_LOCK(ump);
8031         if (freeblks->fb_state & ONDEPLIST) {
8032                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8033                     0, &inodedep);
8034                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8035                 freeblks->fb_state &= ~ONDEPLIST;
8036                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8037                         free_inodedep(inodedep);
8038         }
8039         /*
8040          * All of the freeblock deps must be complete prior to this call
8041          * so it's now safe to complete earlier outstanding journal entries.
8042          */
8043         handle_jwork(&freeblks->fb_jwork);
8044         WORKITEM_FREE(freeblks, D_FREEBLKS);
8045         FREE_LOCK(ump);
8046         return (0);
8047 }
8048
8049 /*
8050  * Release blocks associated with the freeblks and stored in the indirect
8051  * block dbn. If level is greater than SINGLE, the block is an indirect block
8052  * and recursive calls to indirtrunc must be used to cleanse other indirect
8053  * blocks.
8054  *
8055  * This handles partial and complete truncation of blocks.  Partial is noted
8056  * with goingaway == 0.  In this case the freework is completed after the
8057  * zero'd indirects are written to disk.  For full truncation the freework
8058  * is completed after the block is freed.
8059  */
8060 static void
8061 indir_trunc(freework, dbn, lbn)
8062         struct freework *freework;
8063         ufs2_daddr_t dbn;
8064         ufs_lbn_t lbn;
8065 {
8066         struct freework *nfreework;
8067         struct workhead wkhd;
8068         struct freeblks *freeblks;
8069         struct buf *bp;
8070         struct fs *fs;
8071         struct indirdep *indirdep;
8072         struct ufsmount *ump;
8073         ufs1_daddr_t *bap1;
8074         ufs2_daddr_t nb, nnb, *bap2;
8075         ufs_lbn_t lbnadd, nlbn;
8076         int i, nblocks, ufs1fmt;
8077         int freedblocks;
8078         int goingaway;
8079         int freedeps;
8080         int needj;
8081         int level;
8082         int cnt;
8083
8084         freeblks = freework->fw_freeblks;
8085         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8086         fs = ump->um_fs;
8087         /*
8088          * Get buffer of block pointers to be freed.  There are three cases:
8089          * 
8090          * 1) Partial truncate caches the indirdep pointer in the freework
8091          *    which provides us a back copy to the save bp which holds the
8092          *    pointers we want to clear.  When this completes the zero
8093          *    pointers are written to the real copy.
8094          * 2) The indirect is being completely truncated, cancel_indirdep()
8095          *    eliminated the real copy and placed the indirdep on the saved
8096          *    copy.  The indirdep and buf are discarded when this completes.
8097          * 3) The indirect was not in memory, we read a copy off of the disk
8098          *    using the devvp and drop and invalidate the buffer when we're
8099          *    done.
8100          */
8101         goingaway = 1;
8102         indirdep = NULL;
8103         if (freework->fw_indir != NULL) {
8104                 goingaway = 0;
8105                 indirdep = freework->fw_indir;
8106                 bp = indirdep->ir_savebp;
8107                 if (bp == NULL || bp->b_blkno != dbn)
8108                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8109                             bp, (intmax_t)dbn);
8110         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8111                 /*
8112                  * The lock prevents the buf dep list from changing and
8113                  * indirects on devvp should only ever have one dependency.
8114                  */
8115                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8116                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8117                         panic("indir_trunc: Bad indirdep %p from buf %p",
8118                             indirdep, bp);
8119         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8120             NOCRED, &bp) != 0) {
8121                 brelse(bp);
8122                 return;
8123         }
8124         ACQUIRE_LOCK(ump);
8125         /* Protects against a race with complete_trunc_indir(). */
8126         freework->fw_state &= ~INPROGRESS;
8127         /*
8128          * If we have an indirdep we need to enforce the truncation order
8129          * and discard it when it is complete.
8130          */
8131         if (indirdep) {
8132                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8133                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8134                         /*
8135                          * Add the complete truncate to the list on the
8136                          * indirdep to enforce in-order processing.
8137                          */
8138                         if (freework->fw_indir == NULL)
8139                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8140                                     freework, fw_next);
8141                         FREE_LOCK(ump);
8142                         return;
8143                 }
8144                 /*
8145                  * If we're goingaway, free the indirdep.  Otherwise it will
8146                  * linger until the write completes.
8147                  */
8148                 if (goingaway)
8149                         free_indirdep(indirdep);
8150         }
8151         FREE_LOCK(ump);
8152         /* Initialize pointers depending on block size. */
8153         if (ump->um_fstype == UFS1) {
8154                 bap1 = (ufs1_daddr_t *)bp->b_data;
8155                 nb = bap1[freework->fw_off];
8156                 ufs1fmt = 1;
8157                 bap2 = NULL;
8158         } else {
8159                 bap2 = (ufs2_daddr_t *)bp->b_data;
8160                 nb = bap2[freework->fw_off];
8161                 ufs1fmt = 0;
8162                 bap1 = NULL;
8163         }
8164         level = lbn_level(lbn);
8165         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8166         lbnadd = lbn_offset(fs, level);
8167         nblocks = btodb(fs->fs_bsize);
8168         nfreework = freework;
8169         freedeps = 0;
8170         cnt = 0;
8171         /*
8172          * Reclaim blocks.  Traverses into nested indirect levels and
8173          * arranges for the current level to be freed when subordinates
8174          * are free when journaling.
8175          */
8176         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8177                 if (i != NINDIR(fs) - 1) {
8178                         if (ufs1fmt)
8179                                 nnb = bap1[i+1];
8180                         else
8181                                 nnb = bap2[i+1];
8182                 } else
8183                         nnb = 0;
8184                 if (nb == 0)
8185                         continue;
8186                 cnt++;
8187                 if (level != 0) {
8188                         nlbn = (lbn + 1) - (i * lbnadd);
8189                         if (needj != 0) {
8190                                 nfreework = newfreework(ump, freeblks, freework,
8191                                     nlbn, nb, fs->fs_frag, 0, 0);
8192                                 freedeps++;
8193                         }
8194                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8195                 } else {
8196                         struct freedep *freedep;
8197
8198                         /*
8199                          * Attempt to aggregate freedep dependencies for
8200                          * all blocks being released to the same CG.
8201                          */
8202                         LIST_INIT(&wkhd);
8203                         if (needj != 0 &&
8204                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8205                                 freedep = newfreedep(freework);
8206                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8207                                     &freedep->fd_list);
8208                                 freedeps++;
8209                         }
8210                         CTR3(KTR_SUJ,
8211                             "indir_trunc: ino %d blkno %jd size %ld",
8212                             freeblks->fb_inum, nb, fs->fs_bsize);
8213                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8214                             fs->fs_bsize, freeblks->fb_inum,
8215                             freeblks->fb_vtype, &wkhd);
8216                 }
8217         }
8218         if (goingaway) {
8219                 bp->b_flags |= B_INVAL | B_NOCACHE;
8220                 brelse(bp);
8221         }
8222         freedblocks = 0;
8223         if (level == 0)
8224                 freedblocks = (nblocks * cnt);
8225         if (needj == 0)
8226                 freedblocks += nblocks;
8227         freeblks_free(ump, freeblks, freedblocks);
8228         /*
8229          * If we are journaling set up the ref counts and offset so this
8230          * indirect can be completed when its children are free.
8231          */
8232         if (needj) {
8233                 ACQUIRE_LOCK(ump);
8234                 freework->fw_off = i;
8235                 freework->fw_ref += freedeps;
8236                 freework->fw_ref -= NINDIR(fs) + 1;
8237                 if (level == 0)
8238                         freeblks->fb_cgwait += freedeps;
8239                 if (freework->fw_ref == 0)
8240                         freework_freeblock(freework);
8241                 FREE_LOCK(ump);
8242                 return;
8243         }
8244         /*
8245          * If we're not journaling we can free the indirect now.
8246          */
8247         dbn = dbtofsb(fs, dbn);
8248         CTR3(KTR_SUJ,
8249             "indir_trunc 2: ino %d blkno %jd size %ld",
8250             freeblks->fb_inum, dbn, fs->fs_bsize);
8251         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8252             freeblks->fb_inum, freeblks->fb_vtype, NULL);
8253         /* Non SUJ softdep does single-threaded truncations. */
8254         if (freework->fw_blkno == dbn) {
8255                 freework->fw_state |= ALLCOMPLETE;
8256                 ACQUIRE_LOCK(ump);
8257                 handle_written_freework(freework);
8258                 FREE_LOCK(ump);
8259         }
8260         return;
8261 }
8262
8263 /*
8264  * Cancel an allocindir when it is removed via truncation.  When bp is not
8265  * NULL the indirect never appeared on disk and is scheduled to be freed
8266  * independently of the indir so we can more easily track journal work.
8267  */
8268 static void
8269 cancel_allocindir(aip, bp, freeblks, trunc)
8270         struct allocindir *aip;
8271         struct buf *bp;
8272         struct freeblks *freeblks;
8273         int trunc;
8274 {
8275         struct indirdep *indirdep;
8276         struct freefrag *freefrag;
8277         struct newblk *newblk;
8278
8279         newblk = (struct newblk *)aip;
8280         LIST_REMOVE(aip, ai_next);
8281         /*
8282          * We must eliminate the pointer in bp if it must be freed on its
8283          * own due to partial truncate or pending journal work.
8284          */
8285         if (bp && (trunc || newblk->nb_jnewblk)) {
8286                 /*
8287                  * Clear the pointer and mark the aip to be freed
8288                  * directly if it never existed on disk.
8289                  */
8290                 aip->ai_state |= DELAYEDFREE;
8291                 indirdep = aip->ai_indirdep;
8292                 if (indirdep->ir_state & UFS1FMT)
8293                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8294                 else
8295                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8296         }
8297         /*
8298          * When truncating the previous pointer will be freed via
8299          * savedbp.  Eliminate the freefrag which would dup free.
8300          */
8301         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8302                 newblk->nb_freefrag = NULL;
8303                 if (freefrag->ff_jdep)
8304                         cancel_jfreefrag(
8305                             WK_JFREEFRAG(freefrag->ff_jdep));
8306                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8307                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8308         }
8309         /*
8310          * If the journal hasn't been written the jnewblk must be passed
8311          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8312          * this by leaving the journal dependency on the newblk to be freed
8313          * when a freework is created in handle_workitem_freeblocks().
8314          */
8315         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8316         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8317 }
8318
8319 /*
8320  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8321  * in to a newdirblk so any subsequent additions are tracked properly.  The
8322  * caller is responsible for adding the mkdir1 dependency to the journal
8323  * and updating id_mkdiradd.  This function returns with the per-filesystem
8324  * lock held.
8325  */
8326 static struct mkdir *
8327 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8328         struct diradd *dap;
8329         ino_t newinum;
8330         ino_t dinum;
8331         struct buf *newdirbp;
8332         struct mkdir **mkdirp;
8333 {
8334         struct newblk *newblk;
8335         struct pagedep *pagedep;
8336         struct inodedep *inodedep;
8337         struct newdirblk *newdirblk;
8338         struct mkdir *mkdir1, *mkdir2;
8339         struct worklist *wk;
8340         struct jaddref *jaddref;
8341         struct ufsmount *ump;
8342         struct mount *mp;
8343
8344         mp = dap->da_list.wk_mp;
8345         ump = VFSTOUFS(mp);
8346         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8347             M_SOFTDEP_FLAGS);
8348         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8349         LIST_INIT(&newdirblk->db_mkdir);
8350         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8351         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8352         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8353         mkdir1->md_diradd = dap;
8354         mkdir1->md_jaddref = NULL;
8355         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8356         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8357         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8358         mkdir2->md_diradd = dap;
8359         mkdir2->md_jaddref = NULL;
8360         if (MOUNTEDSUJ(mp) == 0) {
8361                 mkdir1->md_state |= DEPCOMPLETE;
8362                 mkdir2->md_state |= DEPCOMPLETE;
8363         }
8364         /*
8365          * Dependency on "." and ".." being written to disk.
8366          */
8367         mkdir1->md_buf = newdirbp;
8368         ACQUIRE_LOCK(VFSTOUFS(mp));
8369         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8370         /*
8371          * We must link the pagedep, allocdirect, and newdirblk for
8372          * the initial file page so the pointer to the new directory
8373          * is not written until the directory contents are live and
8374          * any subsequent additions are not marked live until the
8375          * block is reachable via the inode.
8376          */
8377         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8378                 panic("setup_newdir: lost pagedep");
8379         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8380                 if (wk->wk_type == D_ALLOCDIRECT)
8381                         break;
8382         if (wk == NULL)
8383                 panic("setup_newdir: lost allocdirect");
8384         if (pagedep->pd_state & NEWBLOCK)
8385                 panic("setup_newdir: NEWBLOCK already set");
8386         newblk = WK_NEWBLK(wk);
8387         pagedep->pd_state |= NEWBLOCK;
8388         pagedep->pd_newdirblk = newdirblk;
8389         newdirblk->db_pagedep = pagedep;
8390         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8391         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8392         /*
8393          * Look up the inodedep for the parent directory so that we
8394          * can link mkdir2 into the pending dotdot jaddref or
8395          * the inode write if there is none.  If the inode is
8396          * ALLCOMPLETE and no jaddref is present all dependencies have
8397          * been satisfied and mkdir2 can be freed.
8398          */
8399         inodedep_lookup(mp, dinum, 0, &inodedep);
8400         if (MOUNTEDSUJ(mp)) {
8401                 if (inodedep == NULL)
8402                         panic("setup_newdir: Lost parent.");
8403                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8404                     inoreflst);
8405                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8406                     (jaddref->ja_state & MKDIR_PARENT),
8407                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8408                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8409                 mkdir2->md_jaddref = jaddref;
8410                 jaddref->ja_mkdir = mkdir2;
8411         } else if (inodedep == NULL ||
8412             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8413                 dap->da_state &= ~MKDIR_PARENT;
8414                 WORKITEM_FREE(mkdir2, D_MKDIR);
8415                 mkdir2 = NULL;
8416         } else {
8417                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8418                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8419         }
8420         *mkdirp = mkdir2;
8421
8422         return (mkdir1);
8423 }
8424
8425 /*
8426  * Directory entry addition dependencies.
8427  * 
8428  * When adding a new directory entry, the inode (with its incremented link
8429  * count) must be written to disk before the directory entry's pointer to it.
8430  * Also, if the inode is newly allocated, the corresponding freemap must be
8431  * updated (on disk) before the directory entry's pointer. These requirements
8432  * are met via undo/redo on the directory entry's pointer, which consists
8433  * simply of the inode number.
8434  * 
8435  * As directory entries are added and deleted, the free space within a
8436  * directory block can become fragmented.  The ufs filesystem will compact
8437  * a fragmented directory block to make space for a new entry. When this
8438  * occurs, the offsets of previously added entries change. Any "diradd"
8439  * dependency structures corresponding to these entries must be updated with
8440  * the new offsets.
8441  */
8442
8443 /*
8444  * This routine is called after the in-memory inode's link
8445  * count has been incremented, but before the directory entry's
8446  * pointer to the inode has been set.
8447  */
8448 int
8449 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8450         struct buf *bp;         /* buffer containing directory block */
8451         struct inode *dp;       /* inode for directory */
8452         off_t diroffset;        /* offset of new entry in directory */
8453         ino_t newinum;          /* inode referenced by new directory entry */
8454         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8455         int isnewblk;           /* entry is in a newly allocated block */
8456 {
8457         int offset;             /* offset of new entry within directory block */
8458         ufs_lbn_t lbn;          /* block in directory containing new entry */
8459         struct fs *fs;
8460         struct diradd *dap;
8461         struct newblk *newblk;
8462         struct pagedep *pagedep;
8463         struct inodedep *inodedep;
8464         struct newdirblk *newdirblk;
8465         struct mkdir *mkdir1, *mkdir2;
8466         struct jaddref *jaddref;
8467         struct ufsmount *ump;
8468         struct mount *mp;
8469         int isindir;
8470
8471         mp = ITOVFS(dp);
8472         ump = VFSTOUFS(mp);
8473         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8474             ("softdep_setup_directory_add called on non-softdep filesystem"));
8475         /*
8476          * Whiteouts have no dependencies.
8477          */
8478         if (newinum == UFS_WINO) {
8479                 if (newdirbp != NULL)
8480                         bdwrite(newdirbp);
8481                 return (0);
8482         }
8483         jaddref = NULL;
8484         mkdir1 = mkdir2 = NULL;
8485         fs = ump->um_fs;
8486         lbn = lblkno(fs, diroffset);
8487         offset = blkoff(fs, diroffset);
8488         dap = malloc(sizeof(struct diradd), M_DIRADD,
8489                 M_SOFTDEP_FLAGS|M_ZERO);
8490         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8491         dap->da_offset = offset;
8492         dap->da_newinum = newinum;
8493         dap->da_state = ATTACHED;
8494         LIST_INIT(&dap->da_jwork);
8495         isindir = bp->b_lblkno >= UFS_NDADDR;
8496         newdirblk = NULL;
8497         if (isnewblk &&
8498             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8499                 newdirblk = malloc(sizeof(struct newdirblk),
8500                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8501                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8502                 LIST_INIT(&newdirblk->db_mkdir);
8503         }
8504         /*
8505          * If we're creating a new directory setup the dependencies and set
8506          * the dap state to wait for them.  Otherwise it's COMPLETE and
8507          * we can move on.
8508          */
8509         if (newdirbp == NULL) {
8510                 dap->da_state |= DEPCOMPLETE;
8511                 ACQUIRE_LOCK(ump);
8512         } else {
8513                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8514                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8515                     &mkdir2);
8516         }
8517         /*
8518          * Link into parent directory pagedep to await its being written.
8519          */
8520         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8521 #ifdef DEBUG
8522         if (diradd_lookup(pagedep, offset) != NULL)
8523                 panic("softdep_setup_directory_add: %p already at off %d\n",
8524                     diradd_lookup(pagedep, offset), offset);
8525 #endif
8526         dap->da_pagedep = pagedep;
8527         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8528             da_pdlist);
8529         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8530         /*
8531          * If we're journaling, link the diradd into the jaddref so it
8532          * may be completed after the journal entry is written.  Otherwise,
8533          * link the diradd into its inodedep.  If the inode is not yet
8534          * written place it on the bufwait list, otherwise do the post-inode
8535          * write processing to put it on the id_pendinghd list.
8536          */
8537         if (MOUNTEDSUJ(mp)) {
8538                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8539                     inoreflst);
8540                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8541                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8542                 jaddref->ja_diroff = diroffset;
8543                 jaddref->ja_diradd = dap;
8544                 add_to_journal(&jaddref->ja_list);
8545         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8546                 diradd_inode_written(dap, inodedep);
8547         else
8548                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8549         /*
8550          * Add the journal entries for . and .. links now that the primary
8551          * link is written.
8552          */
8553         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8554                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8555                     inoreflst, if_deps);
8556                 KASSERT(jaddref != NULL &&
8557                     jaddref->ja_ino == jaddref->ja_parent &&
8558                     (jaddref->ja_state & MKDIR_BODY),
8559                     ("softdep_setup_directory_add: bad dot jaddref %p",
8560                     jaddref));
8561                 mkdir1->md_jaddref = jaddref;
8562                 jaddref->ja_mkdir = mkdir1;
8563                 /*
8564                  * It is important that the dotdot journal entry
8565                  * is added prior to the dot entry since dot writes
8566                  * both the dot and dotdot links.  These both must
8567                  * be added after the primary link for the journal
8568                  * to remain consistent.
8569                  */
8570                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8571                 add_to_journal(&jaddref->ja_list);
8572         }
8573         /*
8574          * If we are adding a new directory remember this diradd so that if
8575          * we rename it we can keep the dot and dotdot dependencies.  If
8576          * we are adding a new name for an inode that has a mkdiradd we
8577          * must be in rename and we have to move the dot and dotdot
8578          * dependencies to this new name.  The old name is being orphaned
8579          * soon.
8580          */
8581         if (mkdir1 != NULL) {
8582                 if (inodedep->id_mkdiradd != NULL)
8583                         panic("softdep_setup_directory_add: Existing mkdir");
8584                 inodedep->id_mkdiradd = dap;
8585         } else if (inodedep->id_mkdiradd)
8586                 merge_diradd(inodedep, dap);
8587         if (newdirblk != NULL) {
8588                 /*
8589                  * There is nothing to do if we are already tracking
8590                  * this block.
8591                  */
8592                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8593                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8594                         FREE_LOCK(ump);
8595                         return (0);
8596                 }
8597                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8598                     == 0)
8599                         panic("softdep_setup_directory_add: lost entry");
8600                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8601                 pagedep->pd_state |= NEWBLOCK;
8602                 pagedep->pd_newdirblk = newdirblk;
8603                 newdirblk->db_pagedep = pagedep;
8604                 FREE_LOCK(ump);
8605                 /*
8606                  * If we extended into an indirect signal direnter to sync.
8607                  */
8608                 if (isindir)
8609                         return (1);
8610                 return (0);
8611         }
8612         FREE_LOCK(ump);
8613         return (0);
8614 }
8615
8616 /*
8617  * This procedure is called to change the offset of a directory
8618  * entry when compacting a directory block which must be owned
8619  * exclusively by the caller. Note that the actual entry movement
8620  * must be done in this procedure to ensure that no I/O completions
8621  * occur while the move is in progress.
8622  */
8623 void 
8624 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8625         struct buf *bp;         /* Buffer holding directory block. */
8626         struct inode *dp;       /* inode for directory */
8627         caddr_t base;           /* address of dp->i_offset */
8628         caddr_t oldloc;         /* address of old directory location */
8629         caddr_t newloc;         /* address of new directory location */
8630         int entrysize;          /* size of directory entry */
8631 {
8632         int offset, oldoffset, newoffset;
8633         struct pagedep *pagedep;
8634         struct jmvref *jmvref;
8635         struct diradd *dap;
8636         struct direct *de;
8637         struct mount *mp;
8638         struct ufsmount *ump;
8639         ufs_lbn_t lbn;
8640         int flags;
8641
8642         mp = ITOVFS(dp);
8643         ump = VFSTOUFS(mp);
8644         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8645             ("softdep_change_directoryentry_offset called on "
8646              "non-softdep filesystem"));
8647         de = (struct direct *)oldloc;
8648         jmvref = NULL;
8649         flags = 0;
8650         /*
8651          * Moves are always journaled as it would be too complex to
8652          * determine if any affected adds or removes are present in the
8653          * journal.
8654          */
8655         if (MOUNTEDSUJ(mp)) {
8656                 flags = DEPALLOC;
8657                 jmvref = newjmvref(dp, de->d_ino,
8658                     dp->i_offset + (oldloc - base),
8659                     dp->i_offset + (newloc - base));
8660         }
8661         lbn = lblkno(ump->um_fs, dp->i_offset);
8662         offset = blkoff(ump->um_fs, dp->i_offset);
8663         oldoffset = offset + (oldloc - base);
8664         newoffset = offset + (newloc - base);
8665         ACQUIRE_LOCK(ump);
8666         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8667                 goto done;
8668         dap = diradd_lookup(pagedep, oldoffset);
8669         if (dap) {
8670                 dap->da_offset = newoffset;
8671                 newoffset = DIRADDHASH(newoffset);
8672                 oldoffset = DIRADDHASH(oldoffset);
8673                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8674                     newoffset != oldoffset) {
8675                         LIST_REMOVE(dap, da_pdlist);
8676                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8677                             dap, da_pdlist);
8678                 }
8679         }
8680 done:
8681         if (jmvref) {
8682                 jmvref->jm_pagedep = pagedep;
8683                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8684                 add_to_journal(&jmvref->jm_list);
8685         }
8686         bcopy(oldloc, newloc, entrysize);
8687         FREE_LOCK(ump);
8688 }
8689
8690 /*
8691  * Move the mkdir dependencies and journal work from one diradd to another
8692  * when renaming a directory.  The new name must depend on the mkdir deps
8693  * completing as the old name did.  Directories can only have one valid link
8694  * at a time so one must be canonical.
8695  */
8696 static void
8697 merge_diradd(inodedep, newdap)
8698         struct inodedep *inodedep;
8699         struct diradd *newdap;
8700 {
8701         struct diradd *olddap;
8702         struct mkdir *mkdir, *nextmd;
8703         struct ufsmount *ump;
8704         short state;
8705
8706         olddap = inodedep->id_mkdiradd;
8707         inodedep->id_mkdiradd = newdap;
8708         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8709                 newdap->da_state &= ~DEPCOMPLETE;
8710                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8711                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8712                      mkdir = nextmd) {
8713                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8714                         if (mkdir->md_diradd != olddap)
8715                                 continue;
8716                         mkdir->md_diradd = newdap;
8717                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8718                         newdap->da_state |= state;
8719                         olddap->da_state &= ~state;
8720                         if ((olddap->da_state &
8721                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8722                                 break;
8723                 }
8724                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8725                         panic("merge_diradd: unfound ref");
8726         }
8727         /*
8728          * Any mkdir related journal items are not safe to be freed until
8729          * the new name is stable.
8730          */
8731         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8732         olddap->da_state |= DEPCOMPLETE;
8733         complete_diradd(olddap);
8734 }
8735
8736 /*
8737  * Move the diradd to the pending list when all diradd dependencies are
8738  * complete.
8739  */
8740 static void
8741 complete_diradd(dap)
8742         struct diradd *dap;
8743 {
8744         struct pagedep *pagedep;
8745
8746         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8747                 if (dap->da_state & DIRCHG)
8748                         pagedep = dap->da_previous->dm_pagedep;
8749                 else
8750                         pagedep = dap->da_pagedep;
8751                 LIST_REMOVE(dap, da_pdlist);
8752                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8753         }
8754 }
8755
8756 /*
8757  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8758  * add entries and conditonally journal the remove.
8759  */
8760 static void
8761 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8762         struct diradd *dap;
8763         struct dirrem *dirrem;
8764         struct jremref *jremref;
8765         struct jremref *dotremref;
8766         struct jremref *dotdotremref;
8767 {
8768         struct inodedep *inodedep;
8769         struct jaddref *jaddref;
8770         struct inoref *inoref;
8771         struct ufsmount *ump;
8772         struct mkdir *mkdir;
8773
8774         /*
8775          * If no remove references were allocated we're on a non-journaled
8776          * filesystem and can skip the cancel step.
8777          */
8778         if (jremref == NULL) {
8779                 free_diradd(dap, NULL);
8780                 return;
8781         }
8782         /*
8783          * Cancel the primary name an free it if it does not require
8784          * journaling.
8785          */
8786         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8787             0, &inodedep) != 0) {
8788                 /* Abort the addref that reference this diradd.  */
8789                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8790                         if (inoref->if_list.wk_type != D_JADDREF)
8791                                 continue;
8792                         jaddref = (struct jaddref *)inoref;
8793                         if (jaddref->ja_diradd != dap)
8794                                 continue;
8795                         if (cancel_jaddref(jaddref, inodedep,
8796                             &dirrem->dm_jwork) == 0) {
8797                                 free_jremref(jremref);
8798                                 jremref = NULL;
8799                         }
8800                         break;
8801                 }
8802         }
8803         /*
8804          * Cancel subordinate names and free them if they do not require
8805          * journaling.
8806          */
8807         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8808                 ump = VFSTOUFS(dap->da_list.wk_mp);
8809                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8810                         if (mkdir->md_diradd != dap)
8811                                 continue;
8812                         if ((jaddref = mkdir->md_jaddref) == NULL)
8813                                 continue;
8814                         mkdir->md_jaddref = NULL;
8815                         if (mkdir->md_state & MKDIR_PARENT) {
8816                                 if (cancel_jaddref(jaddref, NULL,
8817                                     &dirrem->dm_jwork) == 0) {
8818                                         free_jremref(dotdotremref);
8819                                         dotdotremref = NULL;
8820                                 }
8821                         } else {
8822                                 if (cancel_jaddref(jaddref, inodedep,
8823                                     &dirrem->dm_jwork) == 0) {
8824                                         free_jremref(dotremref);
8825                                         dotremref = NULL;
8826                                 }
8827                         }
8828                 }
8829         }
8830
8831         if (jremref)
8832                 journal_jremref(dirrem, jremref, inodedep);
8833         if (dotremref)
8834                 journal_jremref(dirrem, dotremref, inodedep);
8835         if (dotdotremref)
8836                 journal_jremref(dirrem, dotdotremref, NULL);
8837         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8838         free_diradd(dap, &dirrem->dm_jwork);
8839 }
8840
8841 /*
8842  * Free a diradd dependency structure. This routine must be called
8843  * with splbio interrupts blocked.
8844  */
8845 static void
8846 free_diradd(dap, wkhd)
8847         struct diradd *dap;
8848         struct workhead *wkhd;
8849 {
8850         struct dirrem *dirrem;
8851         struct pagedep *pagedep;
8852         struct inodedep *inodedep;
8853         struct mkdir *mkdir, *nextmd;
8854         struct ufsmount *ump;
8855
8856         ump = VFSTOUFS(dap->da_list.wk_mp);
8857         LOCK_OWNED(ump);
8858         LIST_REMOVE(dap, da_pdlist);
8859         if (dap->da_state & ONWORKLIST)
8860                 WORKLIST_REMOVE(&dap->da_list);
8861         if ((dap->da_state & DIRCHG) == 0) {
8862                 pagedep = dap->da_pagedep;
8863         } else {
8864                 dirrem = dap->da_previous;
8865                 pagedep = dirrem->dm_pagedep;
8866                 dirrem->dm_dirinum = pagedep->pd_ino;
8867                 dirrem->dm_state |= COMPLETE;
8868                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8869                         add_to_worklist(&dirrem->dm_list, 0);
8870         }
8871         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8872             0, &inodedep) != 0)
8873                 if (inodedep->id_mkdiradd == dap)
8874                         inodedep->id_mkdiradd = NULL;
8875         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8876                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8877                      mkdir = nextmd) {
8878                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8879                         if (mkdir->md_diradd != dap)
8880                                 continue;
8881                         dap->da_state &=
8882                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8883                         LIST_REMOVE(mkdir, md_mkdirs);
8884                         if (mkdir->md_state & ONWORKLIST)
8885                                 WORKLIST_REMOVE(&mkdir->md_list);
8886                         if (mkdir->md_jaddref != NULL)
8887                                 panic("free_diradd: Unexpected jaddref");
8888                         WORKITEM_FREE(mkdir, D_MKDIR);
8889                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8890                                 break;
8891                 }
8892                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8893                         panic("free_diradd: unfound ref");
8894         }
8895         if (inodedep)
8896                 free_inodedep(inodedep);
8897         /*
8898          * Free any journal segments waiting for the directory write.
8899          */
8900         handle_jwork(&dap->da_jwork);
8901         WORKITEM_FREE(dap, D_DIRADD);
8902 }
8903
8904 /*
8905  * Directory entry removal dependencies.
8906  * 
8907  * When removing a directory entry, the entry's inode pointer must be
8908  * zero'ed on disk before the corresponding inode's link count is decremented
8909  * (possibly freeing the inode for re-use). This dependency is handled by
8910  * updating the directory entry but delaying the inode count reduction until
8911  * after the directory block has been written to disk. After this point, the
8912  * inode count can be decremented whenever it is convenient.
8913  */
8914
8915 /*
8916  * This routine should be called immediately after removing
8917  * a directory entry.  The inode's link count should not be
8918  * decremented by the calling procedure -- the soft updates
8919  * code will do this task when it is safe.
8920  */
8921 void 
8922 softdep_setup_remove(bp, dp, ip, isrmdir)
8923         struct buf *bp;         /* buffer containing directory block */
8924         struct inode *dp;       /* inode for the directory being modified */
8925         struct inode *ip;       /* inode for directory entry being removed */
8926         int isrmdir;            /* indicates if doing RMDIR */
8927 {
8928         struct dirrem *dirrem, *prevdirrem;
8929         struct inodedep *inodedep;
8930         struct ufsmount *ump;
8931         int direct;
8932
8933         ump = ITOUMP(ip);
8934         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8935             ("softdep_setup_remove called on non-softdep filesystem"));
8936         /*
8937          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8938          * newdirrem() to setup the full directory remove which requires
8939          * isrmdir > 1.
8940          */
8941         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8942         /*
8943          * Add the dirrem to the inodedep's pending remove list for quick
8944          * discovery later.
8945          */
8946         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8947                 panic("softdep_setup_remove: Lost inodedep.");
8948         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8949         dirrem->dm_state |= ONDEPLIST;
8950         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8951
8952         /*
8953          * If the COMPLETE flag is clear, then there were no active
8954          * entries and we want to roll back to a zeroed entry until
8955          * the new inode is committed to disk. If the COMPLETE flag is
8956          * set then we have deleted an entry that never made it to
8957          * disk. If the entry we deleted resulted from a name change,
8958          * then the old name still resides on disk. We cannot delete
8959          * its inode (returned to us in prevdirrem) until the zeroed
8960          * directory entry gets to disk. The new inode has never been
8961          * referenced on the disk, so can be deleted immediately.
8962          */
8963         if ((dirrem->dm_state & COMPLETE) == 0) {
8964                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8965                     dm_next);
8966                 FREE_LOCK(ump);
8967         } else {
8968                 if (prevdirrem != NULL)
8969                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8970                             prevdirrem, dm_next);
8971                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8972                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8973                 FREE_LOCK(ump);
8974                 if (direct)
8975                         handle_workitem_remove(dirrem, 0);
8976         }
8977 }
8978
8979 /*
8980  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8981  * pd_pendinghd list of a pagedep.
8982  */
8983 static struct diradd *
8984 diradd_lookup(pagedep, offset)
8985         struct pagedep *pagedep;
8986         int offset;
8987 {
8988         struct diradd *dap;
8989
8990         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8991                 if (dap->da_offset == offset)
8992                         return (dap);
8993         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8994                 if (dap->da_offset == offset)
8995                         return (dap);
8996         return (NULL);
8997 }
8998
8999 /*
9000  * Search for a .. diradd dependency in a directory that is being removed.
9001  * If the directory was renamed to a new parent we have a diradd rather
9002  * than a mkdir for the .. entry.  We need to cancel it now before
9003  * it is found in truncate().
9004  */
9005 static struct jremref *
9006 cancel_diradd_dotdot(ip, dirrem, jremref)
9007         struct inode *ip;
9008         struct dirrem *dirrem;
9009         struct jremref *jremref;
9010 {
9011         struct pagedep *pagedep;
9012         struct diradd *dap;
9013         struct worklist *wk;
9014
9015         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9016                 return (jremref);
9017         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9018         if (dap == NULL)
9019                 return (jremref);
9020         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9021         /*
9022          * Mark any journal work as belonging to the parent so it is freed
9023          * with the .. reference.
9024          */
9025         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9026                 wk->wk_state |= MKDIR_PARENT;
9027         return (NULL);
9028 }
9029
9030 /*
9031  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9032  * replace it with a dirrem/diradd pair as a result of re-parenting a
9033  * directory.  This ensures that we don't simultaneously have a mkdir and
9034  * a diradd for the same .. entry.
9035  */
9036 static struct jremref *
9037 cancel_mkdir_dotdot(ip, dirrem, jremref)
9038         struct inode *ip;
9039         struct dirrem *dirrem;
9040         struct jremref *jremref;
9041 {
9042         struct inodedep *inodedep;
9043         struct jaddref *jaddref;
9044         struct ufsmount *ump;
9045         struct mkdir *mkdir;
9046         struct diradd *dap;
9047         struct mount *mp;
9048
9049         mp = ITOVFS(ip);
9050         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9051                 return (jremref);
9052         dap = inodedep->id_mkdiradd;
9053         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9054                 return (jremref);
9055         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9056         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9057             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9058                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9059                         break;
9060         if (mkdir == NULL)
9061                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9062         if ((jaddref = mkdir->md_jaddref) != NULL) {
9063                 mkdir->md_jaddref = NULL;
9064                 jaddref->ja_state &= ~MKDIR_PARENT;
9065                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9066                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9067                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9068                         journal_jremref(dirrem, jremref, inodedep);
9069                         jremref = NULL;
9070                 }
9071         }
9072         if (mkdir->md_state & ONWORKLIST)
9073                 WORKLIST_REMOVE(&mkdir->md_list);
9074         mkdir->md_state |= ALLCOMPLETE;
9075         complete_mkdir(mkdir);
9076         return (jremref);
9077 }
9078
9079 static void
9080 journal_jremref(dirrem, jremref, inodedep)
9081         struct dirrem *dirrem;
9082         struct jremref *jremref;
9083         struct inodedep *inodedep;
9084 {
9085
9086         if (inodedep == NULL)
9087                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9088                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9089                         panic("journal_jremref: Lost inodedep");
9090         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9091         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9092         add_to_journal(&jremref->jr_list);
9093 }
9094
9095 static void
9096 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9097         struct dirrem *dirrem;
9098         struct jremref *jremref;
9099         struct jremref *dotremref;
9100         struct jremref *dotdotremref;
9101 {
9102         struct inodedep *inodedep;
9103
9104
9105         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9106             &inodedep) == 0)
9107                 panic("dirrem_journal: Lost inodedep");
9108         journal_jremref(dirrem, jremref, inodedep);
9109         if (dotremref)
9110                 journal_jremref(dirrem, dotremref, inodedep);
9111         if (dotdotremref)
9112                 journal_jremref(dirrem, dotdotremref, NULL);
9113 }
9114
9115 /*
9116  * Allocate a new dirrem if appropriate and return it along with
9117  * its associated pagedep. Called without a lock, returns with lock.
9118  */
9119 static struct dirrem *
9120 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9121         struct buf *bp;         /* buffer containing directory block */
9122         struct inode *dp;       /* inode for the directory being modified */
9123         struct inode *ip;       /* inode for directory entry being removed */
9124         int isrmdir;            /* indicates if doing RMDIR */
9125         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9126 {
9127         int offset;
9128         ufs_lbn_t lbn;
9129         struct diradd *dap;
9130         struct dirrem *dirrem;
9131         struct pagedep *pagedep;
9132         struct jremref *jremref;
9133         struct jremref *dotremref;
9134         struct jremref *dotdotremref;
9135         struct vnode *dvp;
9136         struct ufsmount *ump;
9137
9138         /*
9139          * Whiteouts have no deletion dependencies.
9140          */
9141         if (ip == NULL)
9142                 panic("newdirrem: whiteout");
9143         dvp = ITOV(dp);
9144         ump = ITOUMP(dp);
9145
9146         /*
9147          * If the system is over its limit and our filesystem is
9148          * responsible for more than our share of that usage and
9149          * we are not a snapshot, request some inodedep cleanup.
9150          * Limiting the number of dirrem structures will also limit
9151          * the number of freefile and freeblks structures.
9152          */
9153         ACQUIRE_LOCK(ump);
9154         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9155                 schedule_cleanup(UFSTOVFS(ump));
9156         else
9157                 FREE_LOCK(ump);
9158         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9159             M_ZERO);
9160         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9161         LIST_INIT(&dirrem->dm_jremrefhd);
9162         LIST_INIT(&dirrem->dm_jwork);
9163         dirrem->dm_state = isrmdir ? RMDIR : 0;
9164         dirrem->dm_oldinum = ip->i_number;
9165         *prevdirremp = NULL;
9166         /*
9167          * Allocate remove reference structures to track journal write
9168          * dependencies.  We will always have one for the link and
9169          * when doing directories we will always have one more for dot.
9170          * When renaming a directory we skip the dotdot link change so
9171          * this is not needed.
9172          */
9173         jremref = dotremref = dotdotremref = NULL;
9174         if (DOINGSUJ(dvp)) {
9175                 if (isrmdir) {
9176                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9177                             ip->i_effnlink + 2);
9178                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9179                             ip->i_effnlink + 1);
9180                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9181                             dp->i_effnlink + 1);
9182                         dotdotremref->jr_state |= MKDIR_PARENT;
9183                 } else
9184                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9185                             ip->i_effnlink + 1);
9186         }
9187         ACQUIRE_LOCK(ump);
9188         lbn = lblkno(ump->um_fs, dp->i_offset);
9189         offset = blkoff(ump->um_fs, dp->i_offset);
9190         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9191             &pagedep);
9192         dirrem->dm_pagedep = pagedep;
9193         dirrem->dm_offset = offset;
9194         /*
9195          * If we're renaming a .. link to a new directory, cancel any
9196          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9197          * the jremref is preserved for any potential diradd in this
9198          * location.  This can not coincide with a rmdir.
9199          */
9200         if (dp->i_offset == DOTDOT_OFFSET) {
9201                 if (isrmdir)
9202                         panic("newdirrem: .. directory change during remove?");
9203                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9204         }
9205         /*
9206          * If we're removing a directory search for the .. dependency now and
9207          * cancel it.  Any pending journal work will be added to the dirrem
9208          * to be completed when the workitem remove completes.
9209          */
9210         if (isrmdir)
9211                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9212         /*
9213          * Check for a diradd dependency for the same directory entry.
9214          * If present, then both dependencies become obsolete and can
9215          * be de-allocated.
9216          */
9217         dap = diradd_lookup(pagedep, offset);
9218         if (dap == NULL) {
9219                 /*
9220                  * Link the jremref structures into the dirrem so they are
9221                  * written prior to the pagedep.
9222                  */
9223                 if (jremref)
9224                         dirrem_journal(dirrem, jremref, dotremref,
9225                             dotdotremref);
9226                 return (dirrem);
9227         }
9228         /*
9229          * Must be ATTACHED at this point.
9230          */
9231         if ((dap->da_state & ATTACHED) == 0)
9232                 panic("newdirrem: not ATTACHED");
9233         if (dap->da_newinum != ip->i_number)
9234                 panic("newdirrem: inum %ju should be %ju",
9235                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9236         /*
9237          * If we are deleting a changed name that never made it to disk,
9238          * then return the dirrem describing the previous inode (which
9239          * represents the inode currently referenced from this entry on disk).
9240          */
9241         if ((dap->da_state & DIRCHG) != 0) {
9242                 *prevdirremp = dap->da_previous;
9243                 dap->da_state &= ~DIRCHG;
9244                 dap->da_pagedep = pagedep;
9245         }
9246         /*
9247          * We are deleting an entry that never made it to disk.
9248          * Mark it COMPLETE so we can delete its inode immediately.
9249          */
9250         dirrem->dm_state |= COMPLETE;
9251         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9252 #ifdef SUJ_DEBUG
9253         if (isrmdir == 0) {
9254                 struct worklist *wk;
9255
9256                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9257                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9258                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9259         }
9260 #endif
9261
9262         return (dirrem);
9263 }
9264
9265 /*
9266  * Directory entry change dependencies.
9267  * 
9268  * Changing an existing directory entry requires that an add operation
9269  * be completed first followed by a deletion. The semantics for the addition
9270  * are identical to the description of adding a new entry above except
9271  * that the rollback is to the old inode number rather than zero. Once
9272  * the addition dependency is completed, the removal is done as described
9273  * in the removal routine above.
9274  */
9275
9276 /*
9277  * This routine should be called immediately after changing
9278  * a directory entry.  The inode's link count should not be
9279  * decremented by the calling procedure -- the soft updates
9280  * code will perform this task when it is safe.
9281  */
9282 void 
9283 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9284         struct buf *bp;         /* buffer containing directory block */
9285         struct inode *dp;       /* inode for the directory being modified */
9286         struct inode *ip;       /* inode for directory entry being removed */
9287         ino_t newinum;          /* new inode number for changed entry */
9288         int isrmdir;            /* indicates if doing RMDIR */
9289 {
9290         int offset;
9291         struct diradd *dap = NULL;
9292         struct dirrem *dirrem, *prevdirrem;
9293         struct pagedep *pagedep;
9294         struct inodedep *inodedep;
9295         struct jaddref *jaddref;
9296         struct mount *mp;
9297         struct ufsmount *ump;
9298
9299         mp = ITOVFS(dp);
9300         ump = VFSTOUFS(mp);
9301         offset = blkoff(ump->um_fs, dp->i_offset);
9302         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9303            ("softdep_setup_directory_change called on non-softdep filesystem"));
9304
9305         /*
9306          * Whiteouts do not need diradd dependencies.
9307          */
9308         if (newinum != UFS_WINO) {
9309                 dap = malloc(sizeof(struct diradd),
9310                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9311                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9312                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9313                 dap->da_offset = offset;
9314                 dap->da_newinum = newinum;
9315                 LIST_INIT(&dap->da_jwork);
9316         }
9317
9318         /*
9319          * Allocate a new dirrem and ACQUIRE_LOCK.
9320          */
9321         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9322         pagedep = dirrem->dm_pagedep;
9323         /*
9324          * The possible values for isrmdir:
9325          *      0 - non-directory file rename
9326          *      1 - directory rename within same directory
9327          *   inum - directory rename to new directory of given inode number
9328          * When renaming to a new directory, we are both deleting and
9329          * creating a new directory entry, so the link count on the new
9330          * directory should not change. Thus we do not need the followup
9331          * dirrem which is usually done in handle_workitem_remove. We set
9332          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9333          * followup dirrem.
9334          */
9335         if (isrmdir > 1)
9336                 dirrem->dm_state |= DIRCHG;
9337
9338         /*
9339          * Whiteouts have no additional dependencies,
9340          * so just put the dirrem on the correct list.
9341          */
9342         if (newinum == UFS_WINO) {
9343                 if ((dirrem->dm_state & COMPLETE) == 0) {
9344                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9345                             dm_next);
9346                 } else {
9347                         dirrem->dm_dirinum = pagedep->pd_ino;
9348                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9349                                 add_to_worklist(&dirrem->dm_list, 0);
9350                 }
9351                 FREE_LOCK(ump);
9352                 return;
9353         }
9354         /*
9355          * Add the dirrem to the inodedep's pending remove list for quick
9356          * discovery later.  A valid nlinkdelta ensures that this lookup
9357          * will not fail.
9358          */
9359         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9360                 panic("softdep_setup_directory_change: Lost inodedep.");
9361         dirrem->dm_state |= ONDEPLIST;
9362         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9363
9364         /*
9365          * If the COMPLETE flag is clear, then there were no active
9366          * entries and we want to roll back to the previous inode until
9367          * the new inode is committed to disk. If the COMPLETE flag is
9368          * set, then we have deleted an entry that never made it to disk.
9369          * If the entry we deleted resulted from a name change, then the old
9370          * inode reference still resides on disk. Any rollback that we do
9371          * needs to be to that old inode (returned to us in prevdirrem). If
9372          * the entry we deleted resulted from a create, then there is
9373          * no entry on the disk, so we want to roll back to zero rather
9374          * than the uncommitted inode. In either of the COMPLETE cases we
9375          * want to immediately free the unwritten and unreferenced inode.
9376          */
9377         if ((dirrem->dm_state & COMPLETE) == 0) {
9378                 dap->da_previous = dirrem;
9379         } else {
9380                 if (prevdirrem != NULL) {
9381                         dap->da_previous = prevdirrem;
9382                 } else {
9383                         dap->da_state &= ~DIRCHG;
9384                         dap->da_pagedep = pagedep;
9385                 }
9386                 dirrem->dm_dirinum = pagedep->pd_ino;
9387                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9388                         add_to_worklist(&dirrem->dm_list, 0);
9389         }
9390         /*
9391          * Lookup the jaddref for this journal entry.  We must finish
9392          * initializing it and make the diradd write dependent on it.
9393          * If we're not journaling, put it on the id_bufwait list if the
9394          * inode is not yet written. If it is written, do the post-inode
9395          * write processing to put it on the id_pendinghd list.
9396          */
9397         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9398         if (MOUNTEDSUJ(mp)) {
9399                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9400                     inoreflst);
9401                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9402                     ("softdep_setup_directory_change: bad jaddref %p",
9403                     jaddref));
9404                 jaddref->ja_diroff = dp->i_offset;
9405                 jaddref->ja_diradd = dap;
9406                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9407                     dap, da_pdlist);
9408                 add_to_journal(&jaddref->ja_list);
9409         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9410                 dap->da_state |= COMPLETE;
9411                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9412                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9413         } else {
9414                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9415                     dap, da_pdlist);
9416                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9417         }
9418         /*
9419          * If we're making a new name for a directory that has not been
9420          * committed when need to move the dot and dotdot references to
9421          * this new name.
9422          */
9423         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9424                 merge_diradd(inodedep, dap);
9425         FREE_LOCK(ump);
9426 }
9427
9428 /*
9429  * Called whenever the link count on an inode is changed.
9430  * It creates an inode dependency so that the new reference(s)
9431  * to the inode cannot be committed to disk until the updated
9432  * inode has been written.
9433  */
9434 void
9435 softdep_change_linkcnt(ip)
9436         struct inode *ip;       /* the inode with the increased link count */
9437 {
9438         struct inodedep *inodedep;
9439         struct ufsmount *ump;
9440
9441         ump = ITOUMP(ip);
9442         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9443             ("softdep_change_linkcnt called on non-softdep filesystem"));
9444         ACQUIRE_LOCK(ump);
9445         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9446         if (ip->i_nlink < ip->i_effnlink)
9447                 panic("softdep_change_linkcnt: bad delta");
9448         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9449         FREE_LOCK(ump);
9450 }
9451
9452 /*
9453  * Attach a sbdep dependency to the superblock buf so that we can keep
9454  * track of the head of the linked list of referenced but unlinked inodes.
9455  */
9456 void
9457 softdep_setup_sbupdate(ump, fs, bp)
9458         struct ufsmount *ump;
9459         struct fs *fs;
9460         struct buf *bp;
9461 {
9462         struct sbdep *sbdep;
9463         struct worklist *wk;
9464
9465         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9466             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9467         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9468                 if (wk->wk_type == D_SBDEP)
9469                         break;
9470         if (wk != NULL)
9471                 return;
9472         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9473         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9474         sbdep->sb_fs = fs;
9475         sbdep->sb_ump = ump;
9476         ACQUIRE_LOCK(ump);
9477         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9478         FREE_LOCK(ump);
9479 }
9480
9481 /*
9482  * Return the first unlinked inodedep which is ready to be the head of the
9483  * list.  The inodedep and all those after it must have valid next pointers.
9484  */
9485 static struct inodedep *
9486 first_unlinked_inodedep(ump)
9487         struct ufsmount *ump;
9488 {
9489         struct inodedep *inodedep;
9490         struct inodedep *idp;
9491
9492         LOCK_OWNED(ump);
9493         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9494             inodedep; inodedep = idp) {
9495                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9496                         return (NULL);
9497                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9498                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9499                         break;
9500                 if ((inodedep->id_state & UNLINKPREV) == 0)
9501                         break;
9502         }
9503         return (inodedep);
9504 }
9505
9506 /*
9507  * Set the sujfree unlinked head pointer prior to writing a superblock.
9508  */
9509 static void
9510 initiate_write_sbdep(sbdep)
9511         struct sbdep *sbdep;
9512 {
9513         struct inodedep *inodedep;
9514         struct fs *bpfs;
9515         struct fs *fs;
9516
9517         bpfs = sbdep->sb_fs;
9518         fs = sbdep->sb_ump->um_fs;
9519         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9520         if (inodedep) {
9521                 fs->fs_sujfree = inodedep->id_ino;
9522                 inodedep->id_state |= UNLINKPREV;
9523         } else
9524                 fs->fs_sujfree = 0;
9525         bpfs->fs_sujfree = fs->fs_sujfree;
9526 }
9527
9528 /*
9529  * After a superblock is written determine whether it must be written again
9530  * due to a changing unlinked list head.
9531  */
9532 static int
9533 handle_written_sbdep(sbdep, bp)
9534         struct sbdep *sbdep;
9535         struct buf *bp;
9536 {
9537         struct inodedep *inodedep;
9538         struct fs *fs;
9539
9540         LOCK_OWNED(sbdep->sb_ump);
9541         fs = sbdep->sb_fs;
9542         /*
9543          * If the superblock doesn't match the in-memory list start over.
9544          */
9545         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9546         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9547             (inodedep == NULL && fs->fs_sujfree != 0)) {
9548                 bdirty(bp);
9549                 return (1);
9550         }
9551         WORKITEM_FREE(sbdep, D_SBDEP);
9552         if (fs->fs_sujfree == 0)
9553                 return (0);
9554         /*
9555          * Now that we have a record of this inode in stable store allow it
9556          * to be written to free up pending work.  Inodes may see a lot of
9557          * write activity after they are unlinked which we must not hold up.
9558          */
9559         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9560                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9561                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9562                             inodedep, inodedep->id_state);
9563                 if (inodedep->id_state & UNLINKONLIST)
9564                         break;
9565                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9566         }
9567
9568         return (0);
9569 }
9570
9571 /*
9572  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9573  */
9574 static void
9575 unlinked_inodedep(mp, inodedep)
9576         struct mount *mp;
9577         struct inodedep *inodedep;
9578 {
9579         struct ufsmount *ump;
9580
9581         ump = VFSTOUFS(mp);
9582         LOCK_OWNED(ump);
9583         if (MOUNTEDSUJ(mp) == 0)
9584                 return;
9585         ump->um_fs->fs_fmod = 1;
9586         if (inodedep->id_state & UNLINKED)
9587                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9588         inodedep->id_state |= UNLINKED;
9589         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9590 }
9591
9592 /*
9593  * Remove an inodedep from the unlinked inodedep list.  This may require
9594  * disk writes if the inode has made it that far.
9595  */
9596 static void
9597 clear_unlinked_inodedep(inodedep)
9598         struct inodedep *inodedep;
9599 {
9600         struct ufsmount *ump;
9601         struct inodedep *idp;
9602         struct inodedep *idn;
9603         struct fs *fs;
9604         struct buf *bp;
9605         ino_t ino;
9606         ino_t nino;
9607         ino_t pino;
9608         int error;
9609
9610         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9611         fs = ump->um_fs;
9612         ino = inodedep->id_ino;
9613         error = 0;
9614         for (;;) {
9615                 LOCK_OWNED(ump);
9616                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9617                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9618                     inodedep));
9619                 /*
9620                  * If nothing has yet been written simply remove us from
9621                  * the in memory list and return.  This is the most common
9622                  * case where handle_workitem_remove() loses the final
9623                  * reference.
9624                  */
9625                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9626                         break;
9627                 /*
9628                  * If we have a NEXT pointer and no PREV pointer we can simply
9629                  * clear NEXT's PREV and remove ourselves from the list.  Be
9630                  * careful not to clear PREV if the superblock points at
9631                  * next as well.
9632                  */
9633                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9634                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9635                         if (idn && fs->fs_sujfree != idn->id_ino)
9636                                 idn->id_state &= ~UNLINKPREV;
9637                         break;
9638                 }
9639                 /*
9640                  * Here we have an inodedep which is actually linked into
9641                  * the list.  We must remove it by forcing a write to the
9642                  * link before us, whether it be the superblock or an inode.
9643                  * Unfortunately the list may change while we're waiting
9644                  * on the buf lock for either resource so we must loop until
9645                  * we lock the right one.  If both the superblock and an
9646                  * inode point to this inode we must clear the inode first
9647                  * followed by the superblock.
9648                  */
9649                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9650                 pino = 0;
9651                 if (idp && (idp->id_state & UNLINKNEXT))
9652                         pino = idp->id_ino;
9653                 FREE_LOCK(ump);
9654                 if (pino == 0) {
9655                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9656                             (int)fs->fs_sbsize, 0, 0, 0);
9657                 } else {
9658                         error = bread(ump->um_devvp,
9659                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9660                             (int)fs->fs_bsize, NOCRED, &bp);
9661                         if (error)
9662                                 brelse(bp);
9663                 }
9664                 ACQUIRE_LOCK(ump);
9665                 if (error)
9666                         break;
9667                 /* If the list has changed restart the loop. */
9668                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9669                 nino = 0;
9670                 if (idp && (idp->id_state & UNLINKNEXT))
9671                         nino = idp->id_ino;
9672                 if (nino != pino ||
9673                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9674                         FREE_LOCK(ump);
9675                         brelse(bp);
9676                         ACQUIRE_LOCK(ump);
9677                         continue;
9678                 }
9679                 nino = 0;
9680                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9681                 if (idn)
9682                         nino = idn->id_ino;
9683                 /*
9684                  * Remove us from the in memory list.  After this we cannot
9685                  * access the inodedep.
9686                  */
9687                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9688                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9689                     inodedep));
9690                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9691                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9692                 FREE_LOCK(ump);
9693                 /*
9694                  * The predecessor's next pointer is manually updated here
9695                  * so that the NEXT flag is never cleared for an element
9696                  * that is in the list.
9697                  */
9698                 if (pino == 0) {
9699                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9700                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9701                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9702                             bp);
9703                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9704                         ((struct ufs1_dinode *)bp->b_data +
9705                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9706                 else
9707                         ((struct ufs2_dinode *)bp->b_data +
9708                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9709                 /*
9710                  * If the bwrite fails we have no recourse to recover.  The
9711                  * filesystem is corrupted already.
9712                  */
9713                 bwrite(bp);
9714                 ACQUIRE_LOCK(ump);
9715                 /*
9716                  * If the superblock pointer still needs to be cleared force
9717                  * a write here.
9718                  */
9719                 if (fs->fs_sujfree == ino) {
9720                         FREE_LOCK(ump);
9721                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9722                             (int)fs->fs_sbsize, 0, 0, 0);
9723                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9724                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9725                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9726                             bp);
9727                         bwrite(bp);
9728                         ACQUIRE_LOCK(ump);
9729                 }
9730
9731                 if (fs->fs_sujfree != ino)
9732                         return;
9733                 panic("clear_unlinked_inodedep: Failed to clear free head");
9734         }
9735         if (inodedep->id_ino == fs->fs_sujfree)
9736                 panic("clear_unlinked_inodedep: Freeing head of free list");
9737         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9738         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9739         return;
9740 }
9741
9742 /*
9743  * This workitem decrements the inode's link count.
9744  * If the link count reaches zero, the file is removed.
9745  */
9746 static int
9747 handle_workitem_remove(dirrem, flags)
9748         struct dirrem *dirrem;
9749         int flags;
9750 {
9751         struct inodedep *inodedep;
9752         struct workhead dotdotwk;
9753         struct worklist *wk;
9754         struct ufsmount *ump;
9755         struct mount *mp;
9756         struct vnode *vp;
9757         struct inode *ip;
9758         ino_t oldinum;
9759
9760         if (dirrem->dm_state & ONWORKLIST)
9761                 panic("handle_workitem_remove: dirrem %p still on worklist",
9762                     dirrem);
9763         oldinum = dirrem->dm_oldinum;
9764         mp = dirrem->dm_list.wk_mp;
9765         ump = VFSTOUFS(mp);
9766         flags |= LK_EXCLUSIVE;
9767         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9768                 return (EBUSY);
9769         ip = VTOI(vp);
9770         ACQUIRE_LOCK(ump);
9771         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9772                 panic("handle_workitem_remove: lost inodedep");
9773         if (dirrem->dm_state & ONDEPLIST)
9774                 LIST_REMOVE(dirrem, dm_inonext);
9775         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9776             ("handle_workitem_remove:  Journal entries not written."));
9777
9778         /*
9779          * Move all dependencies waiting on the remove to complete
9780          * from the dirrem to the inode inowait list to be completed
9781          * after the inode has been updated and written to disk.  Any
9782          * marked MKDIR_PARENT are saved to be completed when the .. ref
9783          * is removed.
9784          */
9785         LIST_INIT(&dotdotwk);
9786         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9787                 WORKLIST_REMOVE(wk);
9788                 if (wk->wk_state & MKDIR_PARENT) {
9789                         wk->wk_state &= ~MKDIR_PARENT;
9790                         WORKLIST_INSERT(&dotdotwk, wk);
9791                         continue;
9792                 }
9793                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9794         }
9795         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9796         /*
9797          * Normal file deletion.
9798          */
9799         if ((dirrem->dm_state & RMDIR) == 0) {
9800                 ip->i_nlink--;
9801                 DIP_SET(ip, i_nlink, ip->i_nlink);
9802                 ip->i_flag |= IN_CHANGE;
9803                 if (ip->i_nlink < ip->i_effnlink)
9804                         panic("handle_workitem_remove: bad file delta");
9805                 if (ip->i_nlink == 0) 
9806                         unlinked_inodedep(mp, inodedep);
9807                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9808                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9809                     ("handle_workitem_remove: worklist not empty. %s",
9810                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9811                 WORKITEM_FREE(dirrem, D_DIRREM);
9812                 FREE_LOCK(ump);
9813                 goto out;
9814         }
9815         /*
9816          * Directory deletion. Decrement reference count for both the
9817          * just deleted parent directory entry and the reference for ".".
9818          * Arrange to have the reference count on the parent decremented
9819          * to account for the loss of "..".
9820          */
9821         ip->i_nlink -= 2;
9822         DIP_SET(ip, i_nlink, ip->i_nlink);
9823         ip->i_flag |= IN_CHANGE;
9824         if (ip->i_nlink < ip->i_effnlink)
9825                 panic("handle_workitem_remove: bad dir delta");
9826         if (ip->i_nlink == 0)
9827                 unlinked_inodedep(mp, inodedep);
9828         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9829         /*
9830          * Rename a directory to a new parent. Since, we are both deleting
9831          * and creating a new directory entry, the link count on the new
9832          * directory should not change. Thus we skip the followup dirrem.
9833          */
9834         if (dirrem->dm_state & DIRCHG) {
9835                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9836                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9837                 WORKITEM_FREE(dirrem, D_DIRREM);
9838                 FREE_LOCK(ump);
9839                 goto out;
9840         }
9841         dirrem->dm_state = ONDEPLIST;
9842         dirrem->dm_oldinum = dirrem->dm_dirinum;
9843         /*
9844          * Place the dirrem on the parent's diremhd list.
9845          */
9846         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9847                 panic("handle_workitem_remove: lost dir inodedep");
9848         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9849         /*
9850          * If the allocated inode has never been written to disk, then
9851          * the on-disk inode is zero'ed and we can remove the file
9852          * immediately.  When journaling if the inode has been marked
9853          * unlinked and not DEPCOMPLETE we know it can never be written.
9854          */
9855         inodedep_lookup(mp, oldinum, 0, &inodedep);
9856         if (inodedep == NULL ||
9857             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9858             check_inode_unwritten(inodedep)) {
9859                 FREE_LOCK(ump);
9860                 vput(vp);
9861                 return handle_workitem_remove(dirrem, flags);
9862         }
9863         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9864         FREE_LOCK(ump);
9865         ip->i_flag |= IN_CHANGE;
9866 out:
9867         ffs_update(vp, 0);
9868         vput(vp);
9869         return (0);
9870 }
9871
9872 /*
9873  * Inode de-allocation dependencies.
9874  * 
9875  * When an inode's link count is reduced to zero, it can be de-allocated. We
9876  * found it convenient to postpone de-allocation until after the inode is
9877  * written to disk with its new link count (zero).  At this point, all of the
9878  * on-disk inode's block pointers are nullified and, with careful dependency
9879  * list ordering, all dependencies related to the inode will be satisfied and
9880  * the corresponding dependency structures de-allocated.  So, if/when the
9881  * inode is reused, there will be no mixing of old dependencies with new
9882  * ones.  This artificial dependency is set up by the block de-allocation
9883  * procedure above (softdep_setup_freeblocks) and completed by the
9884  * following procedure.
9885  */
9886 static void 
9887 handle_workitem_freefile(freefile)
9888         struct freefile *freefile;
9889 {
9890         struct workhead wkhd;
9891         struct fs *fs;
9892         struct inodedep *idp;
9893         struct ufsmount *ump;
9894         int error;
9895
9896         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9897         fs = ump->um_fs;
9898 #ifdef DEBUG
9899         ACQUIRE_LOCK(ump);
9900         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9901         FREE_LOCK(ump);
9902         if (error)
9903                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9904 #endif
9905         UFS_LOCK(ump);
9906         fs->fs_pendinginodes -= 1;
9907         UFS_UNLOCK(ump);
9908         LIST_INIT(&wkhd);
9909         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9910         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9911             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9912                 softdep_error("handle_workitem_freefile", error);
9913         ACQUIRE_LOCK(ump);
9914         WORKITEM_FREE(freefile, D_FREEFILE);
9915         FREE_LOCK(ump);
9916 }
9917
9918
9919 /*
9920  * Helper function which unlinks marker element from work list and returns
9921  * the next element on the list.
9922  */
9923 static __inline struct worklist *
9924 markernext(struct worklist *marker)
9925 {
9926         struct worklist *next;
9927         
9928         next = LIST_NEXT(marker, wk_list);
9929         LIST_REMOVE(marker, wk_list);
9930         return next;
9931 }
9932
9933 /*
9934  * Disk writes.
9935  * 
9936  * The dependency structures constructed above are most actively used when file
9937  * system blocks are written to disk.  No constraints are placed on when a
9938  * block can be written, but unsatisfied update dependencies are made safe by
9939  * modifying (or replacing) the source memory for the duration of the disk
9940  * write.  When the disk write completes, the memory block is again brought
9941  * up-to-date.
9942  *
9943  * In-core inode structure reclamation.
9944  * 
9945  * Because there are a finite number of "in-core" inode structures, they are
9946  * reused regularly.  By transferring all inode-related dependencies to the
9947  * in-memory inode block and indexing them separately (via "inodedep"s), we
9948  * can allow "in-core" inode structures to be reused at any time and avoid
9949  * any increase in contention.
9950  *
9951  * Called just before entering the device driver to initiate a new disk I/O.
9952  * The buffer must be locked, thus, no I/O completion operations can occur
9953  * while we are manipulating its associated dependencies.
9954  */
9955 static void 
9956 softdep_disk_io_initiation(bp)
9957         struct buf *bp;         /* structure describing disk write to occur */
9958 {
9959         struct worklist *wk;
9960         struct worklist marker;
9961         struct inodedep *inodedep;
9962         struct freeblks *freeblks;
9963         struct jblkdep *jblkdep;
9964         struct newblk *newblk;
9965         struct ufsmount *ump;
9966
9967         /*
9968          * We only care about write operations. There should never
9969          * be dependencies for reads.
9970          */
9971         if (bp->b_iocmd != BIO_WRITE)
9972                 panic("softdep_disk_io_initiation: not write");
9973
9974         if (bp->b_vflags & BV_BKGRDINPROG)
9975                 panic("softdep_disk_io_initiation: Writing buffer with "
9976                     "background write in progress: %p", bp);
9977
9978         if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9979                 return;
9980         ump = VFSTOUFS(wk->wk_mp);
9981
9982         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
9983         PHOLD(curproc);                 /* Don't swap out kernel stack */
9984         ACQUIRE_LOCK(ump);
9985         /*
9986          * Do any necessary pre-I/O processing.
9987          */
9988         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9989              wk = markernext(&marker)) {
9990                 LIST_INSERT_AFTER(wk, &marker, wk_list);
9991                 switch (wk->wk_type) {
9992
9993                 case D_PAGEDEP:
9994                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
9995                         continue;
9996
9997                 case D_INODEDEP:
9998                         inodedep = WK_INODEDEP(wk);
9999                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10000                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10001                         else
10002                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10003                         continue;
10004
10005                 case D_INDIRDEP:
10006                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10007                         continue;
10008
10009                 case D_BMSAFEMAP:
10010                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10011                         continue;
10012
10013                 case D_JSEG:
10014                         WK_JSEG(wk)->js_buf = NULL;
10015                         continue;
10016
10017                 case D_FREEBLKS:
10018                         freeblks = WK_FREEBLKS(wk);
10019                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10020                         /*
10021                          * We have to wait for the freeblks to be journaled
10022                          * before we can write an inodeblock with updated
10023                          * pointers.  Be careful to arrange the marker so
10024                          * we revisit the freeblks if it's not removed by
10025                          * the first jwait().
10026                          */
10027                         if (jblkdep != NULL) {
10028                                 LIST_REMOVE(&marker, wk_list);
10029                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10030                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10031                         }
10032                         continue;
10033                 case D_ALLOCDIRECT:
10034                 case D_ALLOCINDIR:
10035                         /*
10036                          * We have to wait for the jnewblk to be journaled
10037                          * before we can write to a block if the contents
10038                          * may be confused with an earlier file's indirect
10039                          * at recovery time.  Handle the marker as described
10040                          * above.
10041                          */
10042                         newblk = WK_NEWBLK(wk);
10043                         if (newblk->nb_jnewblk != NULL &&
10044                             indirblk_lookup(newblk->nb_list.wk_mp,
10045                             newblk->nb_newblkno)) {
10046                                 LIST_REMOVE(&marker, wk_list);
10047                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10048                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10049                         }
10050                         continue;
10051
10052                 case D_SBDEP:
10053                         initiate_write_sbdep(WK_SBDEP(wk));
10054                         continue;
10055
10056                 case D_MKDIR:
10057                 case D_FREEWORK:
10058                 case D_FREEDEP:
10059                 case D_JSEGDEP:
10060                         continue;
10061
10062                 default:
10063                         panic("handle_disk_io_initiation: Unexpected type %s",
10064                             TYPENAME(wk->wk_type));
10065                         /* NOTREACHED */
10066                 }
10067         }
10068         FREE_LOCK(ump);
10069         PRELE(curproc);                 /* Allow swapout of kernel stack */
10070 }
10071
10072 /*
10073  * Called from within the procedure above to deal with unsatisfied
10074  * allocation dependencies in a directory. The buffer must be locked,
10075  * thus, no I/O completion operations can occur while we are
10076  * manipulating its associated dependencies.
10077  */
10078 static void
10079 initiate_write_filepage(pagedep, bp)
10080         struct pagedep *pagedep;
10081         struct buf *bp;
10082 {
10083         struct jremref *jremref;
10084         struct jmvref *jmvref;
10085         struct dirrem *dirrem;
10086         struct diradd *dap;
10087         struct direct *ep;
10088         int i;
10089
10090         if (pagedep->pd_state & IOSTARTED) {
10091                 /*
10092                  * This can only happen if there is a driver that does not
10093                  * understand chaining. Here biodone will reissue the call
10094                  * to strategy for the incomplete buffers.
10095                  */
10096                 printf("initiate_write_filepage: already started\n");
10097                 return;
10098         }
10099         pagedep->pd_state |= IOSTARTED;
10100         /*
10101          * Wait for all journal remove dependencies to hit the disk.
10102          * We can not allow any potentially conflicting directory adds
10103          * to be visible before removes and rollback is too difficult.
10104          * The per-filesystem lock may be dropped and re-acquired, however 
10105          * we hold the buf locked so the dependency can not go away.
10106          */
10107         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10108                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10109                         jwait(&jremref->jr_list, MNT_WAIT);
10110         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10111                 jwait(&jmvref->jm_list, MNT_WAIT);
10112         for (i = 0; i < DAHASHSZ; i++) {
10113                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10114                         ep = (struct direct *)
10115                             ((char *)bp->b_data + dap->da_offset);
10116                         if (ep->d_ino != dap->da_newinum)
10117                                 panic("%s: dir inum %ju != new %ju",
10118                                     "initiate_write_filepage",
10119                                     (uintmax_t)ep->d_ino,
10120                                     (uintmax_t)dap->da_newinum);
10121                         if (dap->da_state & DIRCHG)
10122                                 ep->d_ino = dap->da_previous->dm_oldinum;
10123                         else
10124                                 ep->d_ino = 0;
10125                         dap->da_state &= ~ATTACHED;
10126                         dap->da_state |= UNDONE;
10127                 }
10128         }
10129 }
10130
10131 /*
10132  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10133  * Note that any bug fixes made to this routine must be done in the
10134  * version found below.
10135  *
10136  * Called from within the procedure above to deal with unsatisfied
10137  * allocation dependencies in an inodeblock. The buffer must be
10138  * locked, thus, no I/O completion operations can occur while we
10139  * are manipulating its associated dependencies.
10140  */
10141 static void 
10142 initiate_write_inodeblock_ufs1(inodedep, bp)
10143         struct inodedep *inodedep;
10144         struct buf *bp;                 /* The inode block */
10145 {
10146         struct allocdirect *adp, *lastadp;
10147         struct ufs1_dinode *dp;
10148         struct ufs1_dinode *sip;
10149         struct inoref *inoref;
10150         struct ufsmount *ump;
10151         struct fs *fs;
10152         ufs_lbn_t i;
10153 #ifdef INVARIANTS
10154         ufs_lbn_t prevlbn = 0;
10155 #endif
10156         int deplist;
10157
10158         if (inodedep->id_state & IOSTARTED)
10159                 panic("initiate_write_inodeblock_ufs1: already started");
10160         inodedep->id_state |= IOSTARTED;
10161         fs = inodedep->id_fs;
10162         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10163         LOCK_OWNED(ump);
10164         dp = (struct ufs1_dinode *)bp->b_data +
10165             ino_to_fsbo(fs, inodedep->id_ino);
10166
10167         /*
10168          * If we're on the unlinked list but have not yet written our
10169          * next pointer initialize it here.
10170          */
10171         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10172                 struct inodedep *inon;
10173
10174                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10175                 dp->di_freelink = inon ? inon->id_ino : 0;
10176         }
10177         /*
10178          * If the bitmap is not yet written, then the allocated
10179          * inode cannot be written to disk.
10180          */
10181         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10182                 if (inodedep->id_savedino1 != NULL)
10183                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10184                 FREE_LOCK(ump);
10185                 sip = malloc(sizeof(struct ufs1_dinode),
10186                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10187                 ACQUIRE_LOCK(ump);
10188                 inodedep->id_savedino1 = sip;
10189                 *inodedep->id_savedino1 = *dp;
10190                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10191                 dp->di_gen = inodedep->id_savedino1->di_gen;
10192                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10193                 return;
10194         }
10195         /*
10196          * If no dependencies, then there is nothing to roll back.
10197          */
10198         inodedep->id_savedsize = dp->di_size;
10199         inodedep->id_savedextsize = 0;
10200         inodedep->id_savednlink = dp->di_nlink;
10201         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10202             TAILQ_EMPTY(&inodedep->id_inoreflst))
10203                 return;
10204         /*
10205          * Revert the link count to that of the first unwritten journal entry.
10206          */
10207         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10208         if (inoref)
10209                 dp->di_nlink = inoref->if_nlink;
10210         /*
10211          * Set the dependencies to busy.
10212          */
10213         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10214              adp = TAILQ_NEXT(adp, ad_next)) {
10215 #ifdef INVARIANTS
10216                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10217                         panic("softdep_write_inodeblock: lbn order");
10218                 prevlbn = adp->ad_offset;
10219                 if (adp->ad_offset < UFS_NDADDR &&
10220                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10221                         panic("%s: direct pointer #%jd mismatch %d != %jd",
10222                             "softdep_write_inodeblock",
10223                             (intmax_t)adp->ad_offset,
10224                             dp->di_db[adp->ad_offset],
10225                             (intmax_t)adp->ad_newblkno);
10226                 if (adp->ad_offset >= UFS_NDADDR &&
10227                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10228                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
10229                             "softdep_write_inodeblock",
10230                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10231                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10232                             (intmax_t)adp->ad_newblkno);
10233                 deplist |= 1 << adp->ad_offset;
10234                 if ((adp->ad_state & ATTACHED) == 0)
10235                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10236                             adp->ad_state);
10237 #endif /* INVARIANTS */
10238                 adp->ad_state &= ~ATTACHED;
10239                 adp->ad_state |= UNDONE;
10240         }
10241         /*
10242          * The on-disk inode cannot claim to be any larger than the last
10243          * fragment that has been written. Otherwise, the on-disk inode
10244          * might have fragments that were not the last block in the file
10245          * which would corrupt the filesystem.
10246          */
10247         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10248              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10249                 if (adp->ad_offset >= UFS_NDADDR)
10250                         break;
10251                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10252                 /* keep going until hitting a rollback to a frag */
10253                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10254                         continue;
10255                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10256                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10257 #ifdef INVARIANTS
10258                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10259                                 panic("softdep_write_inodeblock: lost dep1");
10260 #endif /* INVARIANTS */
10261                         dp->di_db[i] = 0;
10262                 }
10263                 for (i = 0; i < UFS_NIADDR; i++) {
10264 #ifdef INVARIANTS
10265                         if (dp->di_ib[i] != 0 &&
10266                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10267                                 panic("softdep_write_inodeblock: lost dep2");
10268 #endif /* INVARIANTS */
10269                         dp->di_ib[i] = 0;
10270                 }
10271                 return;
10272         }
10273         /*
10274          * If we have zero'ed out the last allocated block of the file,
10275          * roll back the size to the last currently allocated block.
10276          * We know that this last allocated block is a full-sized as
10277          * we already checked for fragments in the loop above.
10278          */
10279         if (lastadp != NULL &&
10280             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10281                 for (i = lastadp->ad_offset; i >= 0; i--)
10282                         if (dp->di_db[i] != 0)
10283                                 break;
10284                 dp->di_size = (i + 1) * fs->fs_bsize;
10285         }
10286         /*
10287          * The only dependencies are for indirect blocks.
10288          *
10289          * The file size for indirect block additions is not guaranteed.
10290          * Such a guarantee would be non-trivial to achieve. The conventional
10291          * synchronous write implementation also does not make this guarantee.
10292          * Fsck should catch and fix discrepancies. Arguably, the file size
10293          * can be over-estimated without destroying integrity when the file
10294          * moves into the indirect blocks (i.e., is large). If we want to
10295          * postpone fsck, we are stuck with this argument.
10296          */
10297         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10298                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10299 }
10300                 
10301 /*
10302  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10303  * Note that any bug fixes made to this routine must be done in the
10304  * version found above.
10305  *
10306  * Called from within the procedure above to deal with unsatisfied
10307  * allocation dependencies in an inodeblock. The buffer must be
10308  * locked, thus, no I/O completion operations can occur while we
10309  * are manipulating its associated dependencies.
10310  */
10311 static void 
10312 initiate_write_inodeblock_ufs2(inodedep, bp)
10313         struct inodedep *inodedep;
10314         struct buf *bp;                 /* The inode block */
10315 {
10316         struct allocdirect *adp, *lastadp;
10317         struct ufs2_dinode *dp;
10318         struct ufs2_dinode *sip;
10319         struct inoref *inoref;
10320         struct ufsmount *ump;
10321         struct fs *fs;
10322         ufs_lbn_t i;
10323 #ifdef INVARIANTS
10324         ufs_lbn_t prevlbn = 0;
10325 #endif
10326         int deplist;
10327
10328         if (inodedep->id_state & IOSTARTED)
10329                 panic("initiate_write_inodeblock_ufs2: already started");
10330         inodedep->id_state |= IOSTARTED;
10331         fs = inodedep->id_fs;
10332         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10333         LOCK_OWNED(ump);
10334         dp = (struct ufs2_dinode *)bp->b_data +
10335             ino_to_fsbo(fs, inodedep->id_ino);
10336
10337         /*
10338          * If we're on the unlinked list but have not yet written our
10339          * next pointer initialize it here.
10340          */
10341         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10342                 struct inodedep *inon;
10343
10344                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10345                 dp->di_freelink = inon ? inon->id_ino : 0;
10346         }
10347         /*
10348          * If the bitmap is not yet written, then the allocated
10349          * inode cannot be written to disk.
10350          */
10351         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10352                 if (inodedep->id_savedino2 != NULL)
10353                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10354                 FREE_LOCK(ump);
10355                 sip = malloc(sizeof(struct ufs2_dinode),
10356                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10357                 ACQUIRE_LOCK(ump);
10358                 inodedep->id_savedino2 = sip;
10359                 *inodedep->id_savedino2 = *dp;
10360                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10361                 dp->di_gen = inodedep->id_savedino2->di_gen;
10362                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10363                 return;
10364         }
10365         /*
10366          * If no dependencies, then there is nothing to roll back.
10367          */
10368         inodedep->id_savedsize = dp->di_size;
10369         inodedep->id_savedextsize = dp->di_extsize;
10370         inodedep->id_savednlink = dp->di_nlink;
10371         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10372             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10373             TAILQ_EMPTY(&inodedep->id_inoreflst))
10374                 return;
10375         /*
10376          * Revert the link count to that of the first unwritten journal entry.
10377          */
10378         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10379         if (inoref)
10380                 dp->di_nlink = inoref->if_nlink;
10381
10382         /*
10383          * Set the ext data dependencies to busy.
10384          */
10385         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10386              adp = TAILQ_NEXT(adp, ad_next)) {
10387 #ifdef INVARIANTS
10388                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10389                         panic("softdep_write_inodeblock: lbn order");
10390                 prevlbn = adp->ad_offset;
10391                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10392                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10393                             "softdep_write_inodeblock",
10394                             (intmax_t)adp->ad_offset,
10395                             (intmax_t)dp->di_extb[adp->ad_offset],
10396                             (intmax_t)adp->ad_newblkno);
10397                 deplist |= 1 << adp->ad_offset;
10398                 if ((adp->ad_state & ATTACHED) == 0)
10399                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10400                             adp->ad_state);
10401 #endif /* INVARIANTS */
10402                 adp->ad_state &= ~ATTACHED;
10403                 adp->ad_state |= UNDONE;
10404         }
10405         /*
10406          * The on-disk inode cannot claim to be any larger than the last
10407          * fragment that has been written. Otherwise, the on-disk inode
10408          * might have fragments that were not the last block in the ext
10409          * data which would corrupt the filesystem.
10410          */
10411         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10412              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10413                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10414                 /* keep going until hitting a rollback to a frag */
10415                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10416                         continue;
10417                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10418                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10419 #ifdef INVARIANTS
10420                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10421                                 panic("softdep_write_inodeblock: lost dep1");
10422 #endif /* INVARIANTS */
10423                         dp->di_extb[i] = 0;
10424                 }
10425                 lastadp = NULL;
10426                 break;
10427         }
10428         /*
10429          * If we have zero'ed out the last allocated block of the ext
10430          * data, roll back the size to the last currently allocated block.
10431          * We know that this last allocated block is a full-sized as
10432          * we already checked for fragments in the loop above.
10433          */
10434         if (lastadp != NULL &&
10435             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10436                 for (i = lastadp->ad_offset; i >= 0; i--)
10437                         if (dp->di_extb[i] != 0)
10438                                 break;
10439                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10440         }
10441         /*
10442          * Set the file data dependencies to busy.
10443          */
10444         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10445              adp = TAILQ_NEXT(adp, ad_next)) {
10446 #ifdef INVARIANTS
10447                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10448                         panic("softdep_write_inodeblock: lbn order");
10449                 if ((adp->ad_state & ATTACHED) == 0)
10450                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10451                 prevlbn = adp->ad_offset;
10452                 if (adp->ad_offset < UFS_NDADDR &&
10453                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10454                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10455                             "softdep_write_inodeblock",
10456                             (intmax_t)adp->ad_offset,
10457                             (intmax_t)dp->di_db[adp->ad_offset],
10458                             (intmax_t)adp->ad_newblkno);
10459                 if (adp->ad_offset >= UFS_NDADDR &&
10460                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10461                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
10462                             "softdep_write_inodeblock:",
10463                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10464                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10465                             (intmax_t)adp->ad_newblkno);
10466                 deplist |= 1 << adp->ad_offset;
10467                 if ((adp->ad_state & ATTACHED) == 0)
10468                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10469                             adp->ad_state);
10470 #endif /* INVARIANTS */
10471                 adp->ad_state &= ~ATTACHED;
10472                 adp->ad_state |= UNDONE;
10473         }
10474         /*
10475          * The on-disk inode cannot claim to be any larger than the last
10476          * fragment that has been written. Otherwise, the on-disk inode
10477          * might have fragments that were not the last block in the file
10478          * which would corrupt the filesystem.
10479          */
10480         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10481              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10482                 if (adp->ad_offset >= UFS_NDADDR)
10483                         break;
10484                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10485                 /* keep going until hitting a rollback to a frag */
10486                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10487                         continue;
10488                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10489                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10490 #ifdef INVARIANTS
10491                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10492                                 panic("softdep_write_inodeblock: lost dep2");
10493 #endif /* INVARIANTS */
10494                         dp->di_db[i] = 0;
10495                 }
10496                 for (i = 0; i < UFS_NIADDR; i++) {
10497 #ifdef INVARIANTS
10498                         if (dp->di_ib[i] != 0 &&
10499                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10500                                 panic("softdep_write_inodeblock: lost dep3");
10501 #endif /* INVARIANTS */
10502                         dp->di_ib[i] = 0;
10503                 }
10504                 return;
10505         }
10506         /*
10507          * If we have zero'ed out the last allocated block of the file,
10508          * roll back the size to the last currently allocated block.
10509          * We know that this last allocated block is a full-sized as
10510          * we already checked for fragments in the loop above.
10511          */
10512         if (lastadp != NULL &&
10513             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10514                 for (i = lastadp->ad_offset; i >= 0; i--)
10515                         if (dp->di_db[i] != 0)
10516                                 break;
10517                 dp->di_size = (i + 1) * fs->fs_bsize;
10518         }
10519         /*
10520          * The only dependencies are for indirect blocks.
10521          *
10522          * The file size for indirect block additions is not guaranteed.
10523          * Such a guarantee would be non-trivial to achieve. The conventional
10524          * synchronous write implementation also does not make this guarantee.
10525          * Fsck should catch and fix discrepancies. Arguably, the file size
10526          * can be over-estimated without destroying integrity when the file
10527          * moves into the indirect blocks (i.e., is large). If we want to
10528          * postpone fsck, we are stuck with this argument.
10529          */
10530         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10531                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10532 }
10533
10534 /*
10535  * Cancel an indirdep as a result of truncation.  Release all of the
10536  * children allocindirs and place their journal work on the appropriate
10537  * list.
10538  */
10539 static void
10540 cancel_indirdep(indirdep, bp, freeblks)
10541         struct indirdep *indirdep;
10542         struct buf *bp;
10543         struct freeblks *freeblks;
10544 {
10545         struct allocindir *aip;
10546
10547         /*
10548          * None of the indirect pointers will ever be visible,
10549          * so they can simply be tossed. GOINGAWAY ensures
10550          * that allocated pointers will be saved in the buffer
10551          * cache until they are freed. Note that they will
10552          * only be able to be found by their physical address
10553          * since the inode mapping the logical address will
10554          * be gone. The save buffer used for the safe copy
10555          * was allocated in setup_allocindir_phase2 using
10556          * the physical address so it could be used for this
10557          * purpose. Hence we swap the safe copy with the real
10558          * copy, allowing the safe copy to be freed and holding
10559          * on to the real copy for later use in indir_trunc.
10560          */
10561         if (indirdep->ir_state & GOINGAWAY)
10562                 panic("cancel_indirdep: already gone");
10563         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10564                 indirdep->ir_state |= DEPCOMPLETE;
10565                 LIST_REMOVE(indirdep, ir_next);
10566         }
10567         indirdep->ir_state |= GOINGAWAY;
10568         /*
10569          * Pass in bp for blocks still have journal writes
10570          * pending so we can cancel them on their own.
10571          */
10572         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10573                 cancel_allocindir(aip, bp, freeblks, 0);
10574         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10575                 cancel_allocindir(aip, NULL, freeblks, 0);
10576         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10577                 cancel_allocindir(aip, NULL, freeblks, 0);
10578         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10579                 cancel_allocindir(aip, NULL, freeblks, 0);
10580         /*
10581          * If there are pending partial truncations we need to keep the
10582          * old block copy around until they complete.  This is because
10583          * the current b_data is not a perfect superset of the available
10584          * blocks.
10585          */
10586         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10587                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10588         else
10589                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10590         WORKLIST_REMOVE(&indirdep->ir_list);
10591         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10592         indirdep->ir_bp = NULL;
10593         indirdep->ir_freeblks = freeblks;
10594 }
10595
10596 /*
10597  * Free an indirdep once it no longer has new pointers to track.
10598  */
10599 static void
10600 free_indirdep(indirdep)
10601         struct indirdep *indirdep;
10602 {
10603
10604         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10605             ("free_indirdep: Indir trunc list not empty."));
10606         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10607             ("free_indirdep: Complete head not empty."));
10608         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10609             ("free_indirdep: write head not empty."));
10610         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10611             ("free_indirdep: done head not empty."));
10612         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10613             ("free_indirdep: deplist head not empty."));
10614         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10615             ("free_indirdep: %p still on newblk list.", indirdep));
10616         KASSERT(indirdep->ir_saveddata == NULL,
10617             ("free_indirdep: %p still has saved data.", indirdep));
10618         if (indirdep->ir_state & ONWORKLIST)
10619                 WORKLIST_REMOVE(&indirdep->ir_list);
10620         WORKITEM_FREE(indirdep, D_INDIRDEP);
10621 }
10622
10623 /*
10624  * Called before a write to an indirdep.  This routine is responsible for
10625  * rolling back pointers to a safe state which includes only those
10626  * allocindirs which have been completed.
10627  */
10628 static void
10629 initiate_write_indirdep(indirdep, bp)
10630         struct indirdep *indirdep;
10631         struct buf *bp;
10632 {
10633         struct ufsmount *ump;
10634
10635         indirdep->ir_state |= IOSTARTED;
10636         if (indirdep->ir_state & GOINGAWAY)
10637                 panic("disk_io_initiation: indirdep gone");
10638         /*
10639          * If there are no remaining dependencies, this will be writing
10640          * the real pointers.
10641          */
10642         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10643             TAILQ_EMPTY(&indirdep->ir_trunc))
10644                 return;
10645         /*
10646          * Replace up-to-date version with safe version.
10647          */
10648         if (indirdep->ir_saveddata == NULL) {
10649                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10650                 LOCK_OWNED(ump);
10651                 FREE_LOCK(ump);
10652                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10653                     M_SOFTDEP_FLAGS);
10654                 ACQUIRE_LOCK(ump);
10655         }
10656         indirdep->ir_state &= ~ATTACHED;
10657         indirdep->ir_state |= UNDONE;
10658         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10659         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10660             bp->b_bcount);
10661 }
10662
10663 /*
10664  * Called when an inode has been cleared in a cg bitmap.  This finally
10665  * eliminates any canceled jaddrefs
10666  */
10667 void
10668 softdep_setup_inofree(mp, bp, ino, wkhd)
10669         struct mount *mp;
10670         struct buf *bp;
10671         ino_t ino;
10672         struct workhead *wkhd;
10673 {
10674         struct worklist *wk, *wkn;
10675         struct inodedep *inodedep;
10676         struct ufsmount *ump;
10677         uint8_t *inosused;
10678         struct cg *cgp;
10679         struct fs *fs;
10680
10681         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10682             ("softdep_setup_inofree called on non-softdep filesystem"));
10683         ump = VFSTOUFS(mp);
10684         ACQUIRE_LOCK(ump);
10685         fs = ump->um_fs;
10686         cgp = (struct cg *)bp->b_data;
10687         inosused = cg_inosused(cgp);
10688         if (isset(inosused, ino % fs->fs_ipg))
10689                 panic("softdep_setup_inofree: inode %ju not freed.",
10690                     (uintmax_t)ino);
10691         if (inodedep_lookup(mp, ino, 0, &inodedep))
10692                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10693                     (uintmax_t)ino, inodedep);
10694         if (wkhd) {
10695                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10696                         if (wk->wk_type != D_JADDREF)
10697                                 continue;
10698                         WORKLIST_REMOVE(wk);
10699                         /*
10700                          * We can free immediately even if the jaddref
10701                          * isn't attached in a background write as now
10702                          * the bitmaps are reconciled.
10703                          */
10704                         wk->wk_state |= COMPLETE | ATTACHED;
10705                         free_jaddref(WK_JADDREF(wk));
10706                 }
10707                 jwork_move(&bp->b_dep, wkhd);
10708         }
10709         FREE_LOCK(ump);
10710 }
10711
10712
10713 /*
10714  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10715  * map.  Any dependencies waiting for the write to clear are added to the
10716  * buf's list and any jnewblks that are being canceled are discarded
10717  * immediately.
10718  */
10719 void
10720 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10721         struct mount *mp;
10722         struct buf *bp;
10723         ufs2_daddr_t blkno;
10724         int frags;
10725         struct workhead *wkhd;
10726 {
10727         struct bmsafemap *bmsafemap;
10728         struct jnewblk *jnewblk;
10729         struct ufsmount *ump;
10730         struct worklist *wk;
10731         struct fs *fs;
10732 #ifdef SUJ_DEBUG
10733         uint8_t *blksfree;
10734         struct cg *cgp;
10735         ufs2_daddr_t jstart;
10736         ufs2_daddr_t jend;
10737         ufs2_daddr_t end;
10738         long bno;
10739         int i;
10740 #endif
10741
10742         CTR3(KTR_SUJ,
10743             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10744             blkno, frags, wkhd);
10745
10746         ump = VFSTOUFS(mp);
10747         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10748             ("softdep_setup_blkfree called on non-softdep filesystem"));
10749         ACQUIRE_LOCK(ump);
10750         /* Lookup the bmsafemap so we track when it is dirty. */
10751         fs = ump->um_fs;
10752         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10753         /*
10754          * Detach any jnewblks which have been canceled.  They must linger
10755          * until the bitmap is cleared again by ffs_blkfree() to prevent
10756          * an unjournaled allocation from hitting the disk.
10757          */
10758         if (wkhd) {
10759                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10760                         CTR2(KTR_SUJ,
10761                             "softdep_setup_blkfree: blkno %jd wk type %d",
10762                             blkno, wk->wk_type);
10763                         WORKLIST_REMOVE(wk);
10764                         if (wk->wk_type != D_JNEWBLK) {
10765                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10766                                 continue;
10767                         }
10768                         jnewblk = WK_JNEWBLK(wk);
10769                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10770                             ("softdep_setup_blkfree: jnewblk not canceled."));
10771 #ifdef SUJ_DEBUG
10772                         /*
10773                          * Assert that this block is free in the bitmap
10774                          * before we discard the jnewblk.
10775                          */
10776                         cgp = (struct cg *)bp->b_data;
10777                         blksfree = cg_blksfree(cgp);
10778                         bno = dtogd(fs, jnewblk->jn_blkno);
10779                         for (i = jnewblk->jn_oldfrags;
10780                             i < jnewblk->jn_frags; i++) {
10781                                 if (isset(blksfree, bno + i))
10782                                         continue;
10783                                 panic("softdep_setup_blkfree: not free");
10784                         }
10785 #endif
10786                         /*
10787                          * Even if it's not attached we can free immediately
10788                          * as the new bitmap is correct.
10789                          */
10790                         wk->wk_state |= COMPLETE | ATTACHED;
10791                         free_jnewblk(jnewblk);
10792                 }
10793         }
10794
10795 #ifdef SUJ_DEBUG
10796         /*
10797          * Assert that we are not freeing a block which has an outstanding
10798          * allocation dependency.
10799          */
10800         fs = VFSTOUFS(mp)->um_fs;
10801         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10802         end = blkno + frags;
10803         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10804                 /*
10805                  * Don't match against blocks that will be freed when the
10806                  * background write is done.
10807                  */
10808                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10809                     (COMPLETE | DEPCOMPLETE))
10810                         continue;
10811                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10812                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10813                 if ((blkno >= jstart && blkno < jend) ||
10814                     (end > jstart && end <= jend)) {
10815                         printf("state 0x%X %jd - %d %d dep %p\n",
10816                             jnewblk->jn_state, jnewblk->jn_blkno,
10817                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10818                             jnewblk->jn_dep);
10819                         panic("softdep_setup_blkfree: "
10820                             "%jd-%jd(%d) overlaps with %jd-%jd",
10821                             blkno, end, frags, jstart, jend);
10822                 }
10823         }
10824 #endif
10825         FREE_LOCK(ump);
10826 }
10827
10828 /*
10829  * Revert a block allocation when the journal record that describes it
10830  * is not yet written.
10831  */
10832 static int
10833 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10834         struct jnewblk *jnewblk;
10835         struct fs *fs;
10836         struct cg *cgp;
10837         uint8_t *blksfree;
10838 {
10839         ufs1_daddr_t fragno;
10840         long cgbno, bbase;
10841         int frags, blk;
10842         int i;
10843
10844         frags = 0;
10845         cgbno = dtogd(fs, jnewblk->jn_blkno);
10846         /*
10847          * We have to test which frags need to be rolled back.  We may
10848          * be operating on a stale copy when doing background writes.
10849          */
10850         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10851                 if (isclr(blksfree, cgbno + i))
10852                         frags++;
10853         if (frags == 0)
10854                 return (0);
10855         /*
10856          * This is mostly ffs_blkfree() sans some validation and
10857          * superblock updates.
10858          */
10859         if (frags == fs->fs_frag) {
10860                 fragno = fragstoblks(fs, cgbno);
10861                 ffs_setblock(fs, blksfree, fragno);
10862                 ffs_clusteracct(fs, cgp, fragno, 1);
10863                 cgp->cg_cs.cs_nbfree++;
10864         } else {
10865                 cgbno += jnewblk->jn_oldfrags;
10866                 bbase = cgbno - fragnum(fs, cgbno);
10867                 /* Decrement the old frags.  */
10868                 blk = blkmap(fs, blksfree, bbase);
10869                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10870                 /* Deallocate the fragment */
10871                 for (i = 0; i < frags; i++)
10872                         setbit(blksfree, cgbno + i);
10873                 cgp->cg_cs.cs_nffree += frags;
10874                 /* Add back in counts associated with the new frags */
10875                 blk = blkmap(fs, blksfree, bbase);
10876                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10877                 /* If a complete block has been reassembled, account for it. */
10878                 fragno = fragstoblks(fs, bbase);
10879                 if (ffs_isblock(fs, blksfree, fragno)) {
10880                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10881                         ffs_clusteracct(fs, cgp, fragno, 1);
10882                         cgp->cg_cs.cs_nbfree++;
10883                 }
10884         }
10885         stat_jnewblk++;
10886         jnewblk->jn_state &= ~ATTACHED;
10887         jnewblk->jn_state |= UNDONE;
10888
10889         return (frags);
10890 }
10891
10892 static void
10893 initiate_write_bmsafemap(bmsafemap, bp)
10894         struct bmsafemap *bmsafemap;
10895         struct buf *bp;                 /* The cg block. */
10896 {
10897         struct jaddref *jaddref;
10898         struct jnewblk *jnewblk;
10899         uint8_t *inosused;
10900         uint8_t *blksfree;
10901         struct cg *cgp;
10902         struct fs *fs;
10903         ino_t ino;
10904
10905         /*
10906          * If this is a background write, we did this at the time that
10907          * the copy was made, so do not need to do it again.
10908          */
10909         if (bmsafemap->sm_state & IOSTARTED)
10910                 return;
10911         bmsafemap->sm_state |= IOSTARTED;
10912         /*
10913          * Clear any inode allocations which are pending journal writes.
10914          */
10915         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10916                 cgp = (struct cg *)bp->b_data;
10917                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10918                 inosused = cg_inosused(cgp);
10919                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10920                         ino = jaddref->ja_ino % fs->fs_ipg;
10921                         if (isset(inosused, ino)) {
10922                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10923                                         cgp->cg_cs.cs_ndir--;
10924                                 cgp->cg_cs.cs_nifree++;
10925                                 clrbit(inosused, ino);
10926                                 jaddref->ja_state &= ~ATTACHED;
10927                                 jaddref->ja_state |= UNDONE;
10928                                 stat_jaddref++;
10929                         } else
10930                                 panic("initiate_write_bmsafemap: inode %ju "
10931                                     "marked free", (uintmax_t)jaddref->ja_ino);
10932                 }
10933         }
10934         /*
10935          * Clear any block allocations which are pending journal writes.
10936          */
10937         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10938                 cgp = (struct cg *)bp->b_data;
10939                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10940                 blksfree = cg_blksfree(cgp);
10941                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10942                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10943                                 continue;
10944                         panic("initiate_write_bmsafemap: block %jd "
10945                             "marked free", jnewblk->jn_blkno);
10946                 }
10947         }
10948         /*
10949          * Move allocation lists to the written lists so they can be
10950          * cleared once the block write is complete.
10951          */
10952         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10953             inodedep, id_deps);
10954         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10955             newblk, nb_deps);
10956         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10957             wk_list);
10958 }
10959
10960 /*
10961  * This routine is called during the completion interrupt
10962  * service routine for a disk write (from the procedure called
10963  * by the device driver to inform the filesystem caches of
10964  * a request completion).  It should be called early in this
10965  * procedure, before the block is made available to other
10966  * processes or other routines are called.
10967  *
10968  */
10969 static void 
10970 softdep_disk_write_complete(bp)
10971         struct buf *bp;         /* describes the completed disk write */
10972 {
10973         struct worklist *wk;
10974         struct worklist *owk;
10975         struct ufsmount *ump;
10976         struct workhead reattach;
10977         struct freeblks *freeblks;
10978         struct buf *sbp;
10979
10980         /*
10981          * If an error occurred while doing the write, then the data
10982          * has not hit the disk and the dependencies cannot be processed.
10983          * But we do have to go through and roll forward any dependencies
10984          * that were rolled back before the disk write.
10985          */
10986         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
10987                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
10988                         switch (wk->wk_type) {
10989
10990                         case D_PAGEDEP:
10991                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
10992                                 continue;
10993
10994                         case D_INODEDEP:
10995                                 handle_written_inodeblock(WK_INODEDEP(wk),
10996                                     bp, 0);
10997                                 continue;
10998
10999                         case D_BMSAFEMAP:
11000                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11001                                     bp, 0);
11002                                 continue;
11003
11004                         case D_INDIRDEP:
11005                                 handle_written_indirdep(WK_INDIRDEP(wk),
11006                                     bp, &sbp, 0);
11007                                 continue;
11008                         default:
11009                                 /* nothing to roll forward */
11010                                 continue;
11011                         }
11012                 }
11013                 return;
11014         }
11015         if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
11016                 return;
11017         ump = VFSTOUFS(wk->wk_mp);
11018         LIST_INIT(&reattach);
11019         /*
11020          * This lock must not be released anywhere in this code segment.
11021          */
11022         sbp = NULL;
11023         owk = NULL;
11024         ACQUIRE_LOCK(ump);
11025         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11026                 WORKLIST_REMOVE(wk);
11027                 atomic_add_long(&dep_write[wk->wk_type], 1);
11028                 if (wk == owk)
11029                         panic("duplicate worklist: %p\n", wk);
11030                 owk = wk;
11031                 switch (wk->wk_type) {
11032
11033                 case D_PAGEDEP:
11034                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11035                             WRITESUCCEEDED))
11036                                 WORKLIST_INSERT(&reattach, wk);
11037                         continue;
11038
11039                 case D_INODEDEP:
11040                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11041                             WRITESUCCEEDED))
11042                                 WORKLIST_INSERT(&reattach, wk);
11043                         continue;
11044
11045                 case D_BMSAFEMAP:
11046                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11047                             WRITESUCCEEDED))
11048                                 WORKLIST_INSERT(&reattach, wk);
11049                         continue;
11050
11051                 case D_MKDIR:
11052                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11053                         continue;
11054
11055                 case D_ALLOCDIRECT:
11056                         wk->wk_state |= COMPLETE;
11057                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11058                         continue;
11059
11060                 case D_ALLOCINDIR:
11061                         wk->wk_state |= COMPLETE;
11062                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11063                         continue;
11064
11065                 case D_INDIRDEP:
11066                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11067                             WRITESUCCEEDED))
11068                                 WORKLIST_INSERT(&reattach, wk);
11069                         continue;
11070
11071                 case D_FREEBLKS:
11072                         wk->wk_state |= COMPLETE;
11073                         freeblks = WK_FREEBLKS(wk);
11074                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11075                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11076                                 add_to_worklist(wk, WK_NODELAY);
11077                         continue;
11078
11079                 case D_FREEWORK:
11080                         handle_written_freework(WK_FREEWORK(wk));
11081                         break;
11082
11083                 case D_JSEGDEP:
11084                         free_jsegdep(WK_JSEGDEP(wk));
11085                         continue;
11086
11087                 case D_JSEG:
11088                         handle_written_jseg(WK_JSEG(wk), bp);
11089                         continue;
11090
11091                 case D_SBDEP:
11092                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11093                                 WORKLIST_INSERT(&reattach, wk);
11094                         continue;
11095
11096                 case D_FREEDEP:
11097                         free_freedep(WK_FREEDEP(wk));
11098                         continue;
11099
11100                 default:
11101                         panic("handle_disk_write_complete: Unknown type %s",
11102                             TYPENAME(wk->wk_type));
11103                         /* NOTREACHED */
11104                 }
11105         }
11106         /*
11107          * Reattach any requests that must be redone.
11108          */
11109         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11110                 WORKLIST_REMOVE(wk);
11111                 WORKLIST_INSERT(&bp->b_dep, wk);
11112         }
11113         FREE_LOCK(ump);
11114         if (sbp)
11115                 brelse(sbp);
11116 }
11117
11118 /*
11119  * Called from within softdep_disk_write_complete above. Note that
11120  * this routine is always called from interrupt level with further
11121  * splbio interrupts blocked.
11122  */
11123 static void 
11124 handle_allocdirect_partdone(adp, wkhd)
11125         struct allocdirect *adp;        /* the completed allocdirect */
11126         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11127 {
11128         struct allocdirectlst *listhead;
11129         struct allocdirect *listadp;
11130         struct inodedep *inodedep;
11131         long bsize;
11132
11133         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11134                 return;
11135         /*
11136          * The on-disk inode cannot claim to be any larger than the last
11137          * fragment that has been written. Otherwise, the on-disk inode
11138          * might have fragments that were not the last block in the file
11139          * which would corrupt the filesystem. Thus, we cannot free any
11140          * allocdirects after one whose ad_oldblkno claims a fragment as
11141          * these blocks must be rolled back to zero before writing the inode.
11142          * We check the currently active set of allocdirects in id_inoupdt
11143          * or id_extupdt as appropriate.
11144          */
11145         inodedep = adp->ad_inodedep;
11146         bsize = inodedep->id_fs->fs_bsize;
11147         if (adp->ad_state & EXTDATA)
11148                 listhead = &inodedep->id_extupdt;
11149         else
11150                 listhead = &inodedep->id_inoupdt;
11151         TAILQ_FOREACH(listadp, listhead, ad_next) {
11152                 /* found our block */
11153                 if (listadp == adp)
11154                         break;
11155                 /* continue if ad_oldlbn is not a fragment */
11156                 if (listadp->ad_oldsize == 0 ||
11157                     listadp->ad_oldsize == bsize)
11158                         continue;
11159                 /* hit a fragment */
11160                 return;
11161         }
11162         /*
11163          * If we have reached the end of the current list without
11164          * finding the just finished dependency, then it must be
11165          * on the future dependency list. Future dependencies cannot
11166          * be freed until they are moved to the current list.
11167          */
11168         if (listadp == NULL) {
11169 #ifdef DEBUG
11170                 if (adp->ad_state & EXTDATA)
11171                         listhead = &inodedep->id_newextupdt;
11172                 else
11173                         listhead = &inodedep->id_newinoupdt;
11174                 TAILQ_FOREACH(listadp, listhead, ad_next)
11175                         /* found our block */
11176                         if (listadp == adp)
11177                                 break;
11178                 if (listadp == NULL)
11179                         panic("handle_allocdirect_partdone: lost dep");
11180 #endif /* DEBUG */
11181                 return;
11182         }
11183         /*
11184          * If we have found the just finished dependency, then queue
11185          * it along with anything that follows it that is complete.
11186          * Since the pointer has not yet been written in the inode
11187          * as the dependency prevents it, place the allocdirect on the
11188          * bufwait list where it will be freed once the pointer is
11189          * valid.
11190          */
11191         if (wkhd == NULL)
11192                 wkhd = &inodedep->id_bufwait;
11193         for (; adp; adp = listadp) {
11194                 listadp = TAILQ_NEXT(adp, ad_next);
11195                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11196                         return;
11197                 TAILQ_REMOVE(listhead, adp, ad_next);
11198                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11199         }
11200 }
11201
11202 /*
11203  * Called from within softdep_disk_write_complete above.  This routine
11204  * completes successfully written allocindirs.
11205  */
11206 static void
11207 handle_allocindir_partdone(aip)
11208         struct allocindir *aip;         /* the completed allocindir */
11209 {
11210         struct indirdep *indirdep;
11211
11212         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11213                 return;
11214         indirdep = aip->ai_indirdep;
11215         LIST_REMOVE(aip, ai_next);
11216         /*
11217          * Don't set a pointer while the buffer is undergoing IO or while
11218          * we have active truncations.
11219          */
11220         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11221                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11222                 return;
11223         }
11224         if (indirdep->ir_state & UFS1FMT)
11225                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11226                     aip->ai_newblkno;
11227         else
11228                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11229                     aip->ai_newblkno;
11230         /*
11231          * Await the pointer write before freeing the allocindir.
11232          */
11233         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11234 }
11235
11236 /*
11237  * Release segments held on a jwork list.
11238  */
11239 static void
11240 handle_jwork(wkhd)
11241         struct workhead *wkhd;
11242 {
11243         struct worklist *wk;
11244
11245         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11246                 WORKLIST_REMOVE(wk);
11247                 switch (wk->wk_type) {
11248                 case D_JSEGDEP:
11249                         free_jsegdep(WK_JSEGDEP(wk));
11250                         continue;
11251                 case D_FREEDEP:
11252                         free_freedep(WK_FREEDEP(wk));
11253                         continue;
11254                 case D_FREEFRAG:
11255                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11256                         WORKITEM_FREE(wk, D_FREEFRAG);
11257                         continue;
11258                 case D_FREEWORK:
11259                         handle_written_freework(WK_FREEWORK(wk));
11260                         continue;
11261                 default:
11262                         panic("handle_jwork: Unknown type %s\n",
11263                             TYPENAME(wk->wk_type));
11264                 }
11265         }
11266 }
11267
11268 /*
11269  * Handle the bufwait list on an inode when it is safe to release items
11270  * held there.  This normally happens after an inode block is written but
11271  * may be delayed and handled later if there are pending journal items that
11272  * are not yet safe to be released.
11273  */
11274 static struct freefile *
11275 handle_bufwait(inodedep, refhd)
11276         struct inodedep *inodedep;
11277         struct workhead *refhd;
11278 {
11279         struct jaddref *jaddref;
11280         struct freefile *freefile;
11281         struct worklist *wk;
11282
11283         freefile = NULL;
11284         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11285                 WORKLIST_REMOVE(wk);
11286                 switch (wk->wk_type) {
11287                 case D_FREEFILE:
11288                         /*
11289                          * We defer adding freefile to the worklist
11290                          * until all other additions have been made to
11291                          * ensure that it will be done after all the
11292                          * old blocks have been freed.
11293                          */
11294                         if (freefile != NULL)
11295                                 panic("handle_bufwait: freefile");
11296                         freefile = WK_FREEFILE(wk);
11297                         continue;
11298
11299                 case D_MKDIR:
11300                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11301                         continue;
11302
11303                 case D_DIRADD:
11304                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11305                         continue;
11306
11307                 case D_FREEFRAG:
11308                         wk->wk_state |= COMPLETE;
11309                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11310                                 add_to_worklist(wk, 0);
11311                         continue;
11312
11313                 case D_DIRREM:
11314                         wk->wk_state |= COMPLETE;
11315                         add_to_worklist(wk, 0);
11316                         continue;
11317
11318                 case D_ALLOCDIRECT:
11319                 case D_ALLOCINDIR:
11320                         free_newblk(WK_NEWBLK(wk));
11321                         continue;
11322
11323                 case D_JNEWBLK:
11324                         wk->wk_state |= COMPLETE;
11325                         free_jnewblk(WK_JNEWBLK(wk));
11326                         continue;
11327
11328                 /*
11329                  * Save freed journal segments and add references on
11330                  * the supplied list which will delay their release
11331                  * until the cg bitmap is cleared on disk.
11332                  */
11333                 case D_JSEGDEP:
11334                         if (refhd == NULL)
11335                                 free_jsegdep(WK_JSEGDEP(wk));
11336                         else
11337                                 WORKLIST_INSERT(refhd, wk);
11338                         continue;
11339
11340                 case D_JADDREF:
11341                         jaddref = WK_JADDREF(wk);
11342                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11343                             if_deps);
11344                         /*
11345                          * Transfer any jaddrefs to the list to be freed with
11346                          * the bitmap if we're handling a removed file.
11347                          */
11348                         if (refhd == NULL) {
11349                                 wk->wk_state |= COMPLETE;
11350                                 free_jaddref(jaddref);
11351                         } else
11352                                 WORKLIST_INSERT(refhd, wk);
11353                         continue;
11354
11355                 default:
11356                         panic("handle_bufwait: Unknown type %p(%s)",
11357                             wk, TYPENAME(wk->wk_type));
11358                         /* NOTREACHED */
11359                 }
11360         }
11361         return (freefile);
11362 }
11363 /*
11364  * Called from within softdep_disk_write_complete above to restore
11365  * in-memory inode block contents to their most up-to-date state. Note
11366  * that this routine is always called from interrupt level with further
11367  * interrupts from this device blocked.
11368  *
11369  * If the write did not succeed, we will do all the roll-forward
11370  * operations, but we will not take the actions that will allow its
11371  * dependencies to be processed.
11372  */
11373 static int 
11374 handle_written_inodeblock(inodedep, bp, flags)
11375         struct inodedep *inodedep;
11376         struct buf *bp;         /* buffer containing the inode block */
11377         int flags;
11378 {
11379         struct freefile *freefile;
11380         struct allocdirect *adp, *nextadp;
11381         struct ufs1_dinode *dp1 = NULL;
11382         struct ufs2_dinode *dp2 = NULL;
11383         struct workhead wkhd;
11384         int hadchanges, fstype;
11385         ino_t freelink;
11386
11387         LIST_INIT(&wkhd);
11388         hadchanges = 0;
11389         freefile = NULL;
11390         if ((inodedep->id_state & IOSTARTED) == 0)
11391                 panic("handle_written_inodeblock: not started");
11392         inodedep->id_state &= ~IOSTARTED;
11393         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11394                 fstype = UFS1;
11395                 dp1 = (struct ufs1_dinode *)bp->b_data +
11396                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11397                 freelink = dp1->di_freelink;
11398         } else {
11399                 fstype = UFS2;
11400                 dp2 = (struct ufs2_dinode *)bp->b_data +
11401                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11402                 freelink = dp2->di_freelink;
11403         }
11404         /*
11405          * Leave this inodeblock dirty until it's in the list.
11406          */
11407         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11408             (flags & WRITESUCCEEDED)) {
11409                 struct inodedep *inon;
11410
11411                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11412                 if ((inon == NULL && freelink == 0) ||
11413                     (inon && inon->id_ino == freelink)) {
11414                         if (inon)
11415                                 inon->id_state |= UNLINKPREV;
11416                         inodedep->id_state |= UNLINKNEXT;
11417                 }
11418                 hadchanges = 1;
11419         }
11420         /*
11421          * If we had to rollback the inode allocation because of
11422          * bitmaps being incomplete, then simply restore it.
11423          * Keep the block dirty so that it will not be reclaimed until
11424          * all associated dependencies have been cleared and the
11425          * corresponding updates written to disk.
11426          */
11427         if (inodedep->id_savedino1 != NULL) {
11428                 hadchanges = 1;
11429                 if (fstype == UFS1)
11430                         *dp1 = *inodedep->id_savedino1;
11431                 else
11432                         *dp2 = *inodedep->id_savedino2;
11433                 free(inodedep->id_savedino1, M_SAVEDINO);
11434                 inodedep->id_savedino1 = NULL;
11435                 if ((bp->b_flags & B_DELWRI) == 0)
11436                         stat_inode_bitmap++;
11437                 bdirty(bp);
11438                 /*
11439                  * If the inode is clear here and GOINGAWAY it will never
11440                  * be written.  Process the bufwait and clear any pending
11441                  * work which may include the freefile.
11442                  */
11443                 if (inodedep->id_state & GOINGAWAY)
11444                         goto bufwait;
11445                 return (1);
11446         }
11447         if (flags & WRITESUCCEEDED)
11448                 inodedep->id_state |= COMPLETE;
11449         /*
11450          * Roll forward anything that had to be rolled back before 
11451          * the inode could be updated.
11452          */
11453         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11454                 nextadp = TAILQ_NEXT(adp, ad_next);
11455                 if (adp->ad_state & ATTACHED)
11456                         panic("handle_written_inodeblock: new entry");
11457                 if (fstype == UFS1) {
11458                         if (adp->ad_offset < UFS_NDADDR) {
11459                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11460                                         panic("%s %s #%jd mismatch %d != %jd",
11461                                             "handle_written_inodeblock:",
11462                                             "direct pointer",
11463                                             (intmax_t)adp->ad_offset,
11464                                             dp1->di_db[adp->ad_offset],
11465                                             (intmax_t)adp->ad_oldblkno);
11466                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11467                         } else {
11468                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11469                                     0)
11470                                         panic("%s: %s #%jd allocated as %d",
11471                                             "handle_written_inodeblock",
11472                                             "indirect pointer",
11473                                             (intmax_t)adp->ad_offset -
11474                                             UFS_NDADDR,
11475                                             dp1->di_ib[adp->ad_offset -
11476                                             UFS_NDADDR]);
11477                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11478                                     adp->ad_newblkno;
11479                         }
11480                 } else {
11481                         if (adp->ad_offset < UFS_NDADDR) {
11482                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11483                                         panic("%s: %s #%jd %s %jd != %jd",
11484                                             "handle_written_inodeblock",
11485                                             "direct pointer",
11486                                             (intmax_t)adp->ad_offset, "mismatch",
11487                                             (intmax_t)dp2->di_db[adp->ad_offset],
11488                                             (intmax_t)adp->ad_oldblkno);
11489                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11490                         } else {
11491                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11492                                     0)
11493                                         panic("%s: %s #%jd allocated as %jd",
11494                                             "handle_written_inodeblock",
11495                                             "indirect pointer",
11496                                             (intmax_t)adp->ad_offset -
11497                                             UFS_NDADDR,
11498                                             (intmax_t)
11499                                             dp2->di_ib[adp->ad_offset -
11500                                             UFS_NDADDR]);
11501                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11502                                     adp->ad_newblkno;
11503                         }
11504                 }
11505                 adp->ad_state &= ~UNDONE;
11506                 adp->ad_state |= ATTACHED;
11507                 hadchanges = 1;
11508         }
11509         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11510                 nextadp = TAILQ_NEXT(adp, ad_next);
11511                 if (adp->ad_state & ATTACHED)
11512                         panic("handle_written_inodeblock: new entry");
11513                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11514                         panic("%s: direct pointers #%jd %s %jd != %jd",
11515                             "handle_written_inodeblock",
11516                             (intmax_t)adp->ad_offset, "mismatch",
11517                             (intmax_t)dp2->di_extb[adp->ad_offset],
11518                             (intmax_t)adp->ad_oldblkno);
11519                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11520                 adp->ad_state &= ~UNDONE;
11521                 adp->ad_state |= ATTACHED;
11522                 hadchanges = 1;
11523         }
11524         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11525                 stat_direct_blk_ptrs++;
11526         /*
11527          * Reset the file size to its most up-to-date value.
11528          */
11529         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11530                 panic("handle_written_inodeblock: bad size");
11531         if (inodedep->id_savednlink > UFS_LINK_MAX)
11532                 panic("handle_written_inodeblock: Invalid link count "
11533                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11534                     inodedep);
11535         if (fstype == UFS1) {
11536                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11537                         dp1->di_nlink = inodedep->id_savednlink;
11538                         hadchanges = 1;
11539                 }
11540                 if (dp1->di_size != inodedep->id_savedsize) {
11541                         dp1->di_size = inodedep->id_savedsize;
11542                         hadchanges = 1;
11543                 }
11544         } else {
11545                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11546                         dp2->di_nlink = inodedep->id_savednlink;
11547                         hadchanges = 1;
11548                 }
11549                 if (dp2->di_size != inodedep->id_savedsize) {
11550                         dp2->di_size = inodedep->id_savedsize;
11551                         hadchanges = 1;
11552                 }
11553                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11554                         dp2->di_extsize = inodedep->id_savedextsize;
11555                         hadchanges = 1;
11556                 }
11557         }
11558         inodedep->id_savedsize = -1;
11559         inodedep->id_savedextsize = -1;
11560         inodedep->id_savednlink = -1;
11561         /*
11562          * If there were any rollbacks in the inode block, then it must be
11563          * marked dirty so that its will eventually get written back in
11564          * its correct form.
11565          */
11566         if (hadchanges)
11567                 bdirty(bp);
11568 bufwait:
11569         /*
11570          * If the write did not succeed, we have done all the roll-forward
11571          * operations, but we cannot take the actions that will allow its
11572          * dependencies to be processed.
11573          */
11574         if ((flags & WRITESUCCEEDED) == 0)
11575                 return (hadchanges);
11576         /*
11577          * Process any allocdirects that completed during the update.
11578          */
11579         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11580                 handle_allocdirect_partdone(adp, &wkhd);
11581         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11582                 handle_allocdirect_partdone(adp, &wkhd);
11583         /*
11584          * Process deallocations that were held pending until the
11585          * inode had been written to disk. Freeing of the inode
11586          * is delayed until after all blocks have been freed to
11587          * avoid creation of new <vfsid, inum, lbn> triples
11588          * before the old ones have been deleted.  Completely
11589          * unlinked inodes are not processed until the unlinked
11590          * inode list is written or the last reference is removed.
11591          */
11592         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11593                 freefile = handle_bufwait(inodedep, NULL);
11594                 if (freefile && !LIST_EMPTY(&wkhd)) {
11595                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11596                         freefile = NULL;
11597                 }
11598         }
11599         /*
11600          * Move rolled forward dependency completions to the bufwait list
11601          * now that those that were already written have been processed.
11602          */
11603         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11604                 panic("handle_written_inodeblock: bufwait but no changes");
11605         jwork_move(&inodedep->id_bufwait, &wkhd);
11606
11607         if (freefile != NULL) {
11608                 /*
11609                  * If the inode is goingaway it was never written.  Fake up
11610                  * the state here so free_inodedep() can succeed.
11611                  */
11612                 if (inodedep->id_state & GOINGAWAY)
11613                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11614                 if (free_inodedep(inodedep) == 0)
11615                         panic("handle_written_inodeblock: live inodedep %p",
11616                             inodedep);
11617                 add_to_worklist(&freefile->fx_list, 0);
11618                 return (0);
11619         }
11620
11621         /*
11622          * If no outstanding dependencies, free it.
11623          */
11624         if (free_inodedep(inodedep) ||
11625             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11626              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11627              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11628              LIST_FIRST(&inodedep->id_bufwait) == 0))
11629                 return (0);
11630         return (hadchanges);
11631 }
11632
11633 /*
11634  * Perform needed roll-forwards and kick off any dependencies that
11635  * can now be processed.
11636  *
11637  * If the write did not succeed, we will do all the roll-forward
11638  * operations, but we will not take the actions that will allow its
11639  * dependencies to be processed.
11640  */
11641 static int
11642 handle_written_indirdep(indirdep, bp, bpp, flags)
11643         struct indirdep *indirdep;
11644         struct buf *bp;
11645         struct buf **bpp;
11646         int flags;
11647 {
11648         struct allocindir *aip;
11649         struct buf *sbp;
11650         int chgs;
11651
11652         if (indirdep->ir_state & GOINGAWAY)
11653                 panic("handle_written_indirdep: indirdep gone");
11654         if ((indirdep->ir_state & IOSTARTED) == 0)
11655                 panic("handle_written_indirdep: IO not started");
11656         chgs = 0;
11657         /*
11658          * If there were rollbacks revert them here.
11659          */
11660         if (indirdep->ir_saveddata) {
11661                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11662                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11663                         free(indirdep->ir_saveddata, M_INDIRDEP);
11664                         indirdep->ir_saveddata = NULL;
11665                 }
11666                 chgs = 1;
11667         }
11668         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11669         indirdep->ir_state |= ATTACHED;
11670         /*
11671          * If the write did not succeed, we have done all the roll-forward
11672          * operations, but we cannot take the actions that will allow its
11673          * dependencies to be processed.
11674          */
11675         if ((flags & WRITESUCCEEDED) == 0) {
11676                 stat_indir_blk_ptrs++;
11677                 bdirty(bp);
11678                 return (1);
11679         }
11680         /*
11681          * Move allocindirs with written pointers to the completehd if
11682          * the indirdep's pointer is not yet written.  Otherwise
11683          * free them here.
11684          */
11685         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11686                 LIST_REMOVE(aip, ai_next);
11687                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11688                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11689                             ai_next);
11690                         newblk_freefrag(&aip->ai_block);
11691                         continue;
11692                 }
11693                 free_newblk(&aip->ai_block);
11694         }
11695         /*
11696          * Move allocindirs that have finished dependency processing from
11697          * the done list to the write list after updating the pointers.
11698          */
11699         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11700                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11701                         handle_allocindir_partdone(aip);
11702                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11703                                 panic("disk_write_complete: not gone");
11704                         chgs = 1;
11705                 }
11706         }
11707         /*
11708          * Preserve the indirdep if there were any changes or if it is not
11709          * yet valid on disk.
11710          */
11711         if (chgs) {
11712                 stat_indir_blk_ptrs++;
11713                 bdirty(bp);
11714                 return (1);
11715         }
11716         /*
11717          * If there were no changes we can discard the savedbp and detach
11718          * ourselves from the buf.  We are only carrying completed pointers
11719          * in this case.
11720          */
11721         sbp = indirdep->ir_savebp;
11722         sbp->b_flags |= B_INVAL | B_NOCACHE;
11723         indirdep->ir_savebp = NULL;
11724         indirdep->ir_bp = NULL;
11725         if (*bpp != NULL)
11726                 panic("handle_written_indirdep: bp already exists.");
11727         *bpp = sbp;
11728         /*
11729          * The indirdep may not be freed until its parent points at it.
11730          */
11731         if (indirdep->ir_state & DEPCOMPLETE)
11732                 free_indirdep(indirdep);
11733
11734         return (0);
11735 }
11736
11737 /*
11738  * Process a diradd entry after its dependent inode has been written.
11739  * This routine must be called with splbio interrupts blocked.
11740  */
11741 static void
11742 diradd_inode_written(dap, inodedep)
11743         struct diradd *dap;
11744         struct inodedep *inodedep;
11745 {
11746
11747         dap->da_state |= COMPLETE;
11748         complete_diradd(dap);
11749         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11750 }
11751
11752 /*
11753  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11754  * be called with the per-filesystem lock and the buf lock on the cg held.
11755  */
11756 static int
11757 bmsafemap_backgroundwrite(bmsafemap, bp)
11758         struct bmsafemap *bmsafemap;
11759         struct buf *bp;
11760 {
11761         int dirty;
11762
11763         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11764         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11765             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11766         /*
11767          * If we're initiating a background write we need to process the
11768          * rollbacks as they exist now, not as they exist when IO starts.
11769          * No other consumers will look at the contents of the shadowed
11770          * buf so this is safe to do here.
11771          */
11772         if (bp->b_xflags & BX_BKGRDMARKER)
11773                 initiate_write_bmsafemap(bmsafemap, bp);
11774
11775         return (dirty);
11776 }
11777
11778 /*
11779  * Re-apply an allocation when a cg write is complete.
11780  */
11781 static int
11782 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11783         struct jnewblk *jnewblk;
11784         struct fs *fs;
11785         struct cg *cgp;
11786         uint8_t *blksfree;
11787 {
11788         ufs1_daddr_t fragno;
11789         ufs2_daddr_t blkno;
11790         long cgbno, bbase;
11791         int frags, blk;
11792         int i;
11793
11794         frags = 0;
11795         cgbno = dtogd(fs, jnewblk->jn_blkno);
11796         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11797                 if (isclr(blksfree, cgbno + i))
11798                         panic("jnewblk_rollforward: re-allocated fragment");
11799                 frags++;
11800         }
11801         if (frags == fs->fs_frag) {
11802                 blkno = fragstoblks(fs, cgbno);
11803                 ffs_clrblock(fs, blksfree, (long)blkno);
11804                 ffs_clusteracct(fs, cgp, blkno, -1);
11805                 cgp->cg_cs.cs_nbfree--;
11806         } else {
11807                 bbase = cgbno - fragnum(fs, cgbno);
11808                 cgbno += jnewblk->jn_oldfrags;
11809                 /* If a complete block had been reassembled, account for it. */
11810                 fragno = fragstoblks(fs, bbase);
11811                 if (ffs_isblock(fs, blksfree, fragno)) {
11812                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11813                         ffs_clusteracct(fs, cgp, fragno, -1);
11814                         cgp->cg_cs.cs_nbfree--;
11815                 }
11816                 /* Decrement the old frags.  */
11817                 blk = blkmap(fs, blksfree, bbase);
11818                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11819                 /* Allocate the fragment */
11820                 for (i = 0; i < frags; i++)
11821                         clrbit(blksfree, cgbno + i);
11822                 cgp->cg_cs.cs_nffree -= frags;
11823                 /* Add back in counts associated with the new frags */
11824                 blk = blkmap(fs, blksfree, bbase);
11825                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11826         }
11827         return (frags);
11828 }
11829
11830 /*
11831  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11832  * changes if it's not a background write.  Set all written dependencies 
11833  * to DEPCOMPLETE and free the structure if possible.
11834  *
11835  * If the write did not succeed, we will do all the roll-forward
11836  * operations, but we will not take the actions that will allow its
11837  * dependencies to be processed.
11838  */
11839 static int
11840 handle_written_bmsafemap(bmsafemap, bp, flags)
11841         struct bmsafemap *bmsafemap;
11842         struct buf *bp;
11843         int flags;
11844 {
11845         struct newblk *newblk;
11846         struct inodedep *inodedep;
11847         struct jaddref *jaddref, *jatmp;
11848         struct jnewblk *jnewblk, *jntmp;
11849         struct ufsmount *ump;
11850         uint8_t *inosused;
11851         uint8_t *blksfree;
11852         struct cg *cgp;
11853         struct fs *fs;
11854         ino_t ino;
11855         int foreground;
11856         int chgs;
11857
11858         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11859                 panic("handle_written_bmsafemap: Not started\n");
11860         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11861         chgs = 0;
11862         bmsafemap->sm_state &= ~IOSTARTED;
11863         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11864         /*
11865          * If write was successful, release journal work that was waiting
11866          * on the write. Otherwise move the work back.
11867          */
11868         if (flags & WRITESUCCEEDED)
11869                 handle_jwork(&bmsafemap->sm_freewr);
11870         else
11871                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11872                     worklist, wk_list);
11873
11874         /*
11875          * Restore unwritten inode allocation pending jaddref writes.
11876          */
11877         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11878                 cgp = (struct cg *)bp->b_data;
11879                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11880                 inosused = cg_inosused(cgp);
11881                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11882                     ja_bmdeps, jatmp) {
11883                         if ((jaddref->ja_state & UNDONE) == 0)
11884                                 continue;
11885                         ino = jaddref->ja_ino % fs->fs_ipg;
11886                         if (isset(inosused, ino))
11887                                 panic("handle_written_bmsafemap: "
11888                                     "re-allocated inode");
11889                         /* Do the roll-forward only if it's a real copy. */
11890                         if (foreground) {
11891                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11892                                         cgp->cg_cs.cs_ndir++;
11893                                 cgp->cg_cs.cs_nifree--;
11894                                 setbit(inosused, ino);
11895                                 chgs = 1;
11896                         }
11897                         jaddref->ja_state &= ~UNDONE;
11898                         jaddref->ja_state |= ATTACHED;
11899                         free_jaddref(jaddref);
11900                 }
11901         }
11902         /*
11903          * Restore any block allocations which are pending journal writes.
11904          */
11905         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11906                 cgp = (struct cg *)bp->b_data;
11907                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11908                 blksfree = cg_blksfree(cgp);
11909                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11910                     jntmp) {
11911                         if ((jnewblk->jn_state & UNDONE) == 0)
11912                                 continue;
11913                         /* Do the roll-forward only if it's a real copy. */
11914                         if (foreground &&
11915                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11916                                 chgs = 1;
11917                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11918                         jnewblk->jn_state |= ATTACHED;
11919                         free_jnewblk(jnewblk);
11920                 }
11921         }
11922         /*
11923          * If the write did not succeed, we have done all the roll-forward
11924          * operations, but we cannot take the actions that will allow its
11925          * dependencies to be processed.
11926          */
11927         if ((flags & WRITESUCCEEDED) == 0) {
11928                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11929                     newblk, nb_deps);
11930                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11931                     worklist, wk_list);
11932                 if (foreground)
11933                         bdirty(bp);
11934                 return (1);
11935         }
11936         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11937                 newblk->nb_state |= DEPCOMPLETE;
11938                 newblk->nb_state &= ~ONDEPLIST;
11939                 newblk->nb_bmsafemap = NULL;
11940                 LIST_REMOVE(newblk, nb_deps);
11941                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11942                         handle_allocdirect_partdone(
11943                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11944                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11945                         handle_allocindir_partdone(
11946                             WK_ALLOCINDIR(&newblk->nb_list));
11947                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11948                         panic("handle_written_bmsafemap: Unexpected type: %s",
11949                             TYPENAME(newblk->nb_list.wk_type));
11950         }
11951         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11952                 inodedep->id_state |= DEPCOMPLETE;
11953                 inodedep->id_state &= ~ONDEPLIST;
11954                 LIST_REMOVE(inodedep, id_deps);
11955                 inodedep->id_bmsafemap = NULL;
11956         }
11957         LIST_REMOVE(bmsafemap, sm_next);
11958         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11959             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11960             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11961             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11962             LIST_EMPTY(&bmsafemap->sm_freehd)) {
11963                 LIST_REMOVE(bmsafemap, sm_hash);
11964                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11965                 return (0);
11966         }
11967         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11968         if (foreground)
11969                 bdirty(bp);
11970         return (1);
11971 }
11972
11973 /*
11974  * Try to free a mkdir dependency.
11975  */
11976 static void
11977 complete_mkdir(mkdir)
11978         struct mkdir *mkdir;
11979 {
11980         struct diradd *dap;
11981
11982         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11983                 return;
11984         LIST_REMOVE(mkdir, md_mkdirs);
11985         dap = mkdir->md_diradd;
11986         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11987         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11988                 dap->da_state |= DEPCOMPLETE;
11989                 complete_diradd(dap);
11990         }
11991         WORKITEM_FREE(mkdir, D_MKDIR);
11992 }
11993
11994 /*
11995  * Handle the completion of a mkdir dependency.
11996  */
11997 static void
11998 handle_written_mkdir(mkdir, type)
11999         struct mkdir *mkdir;
12000         int type;
12001 {
12002
12003         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12004                 panic("handle_written_mkdir: bad type");
12005         mkdir->md_state |= COMPLETE;
12006         complete_mkdir(mkdir);
12007 }
12008
12009 static int
12010 free_pagedep(pagedep)
12011         struct pagedep *pagedep;
12012 {
12013         int i;
12014
12015         if (pagedep->pd_state & NEWBLOCK)
12016                 return (0);
12017         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12018                 return (0);
12019         for (i = 0; i < DAHASHSZ; i++)
12020                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12021                         return (0);
12022         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12023                 return (0);
12024         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12025                 return (0);
12026         if (pagedep->pd_state & ONWORKLIST)
12027                 WORKLIST_REMOVE(&pagedep->pd_list);
12028         LIST_REMOVE(pagedep, pd_hash);
12029         WORKITEM_FREE(pagedep, D_PAGEDEP);
12030
12031         return (1);
12032 }
12033
12034 /*
12035  * Called from within softdep_disk_write_complete above.
12036  * A write operation was just completed. Removed inodes can
12037  * now be freed and associated block pointers may be committed.
12038  * Note that this routine is always called from interrupt level
12039  * with further interrupts from this device blocked.
12040  *
12041  * If the write did not succeed, we will do all the roll-forward
12042  * operations, but we will not take the actions that will allow its
12043  * dependencies to be processed.
12044  */
12045 static int 
12046 handle_written_filepage(pagedep, bp, flags)
12047         struct pagedep *pagedep;
12048         struct buf *bp;         /* buffer containing the written page */
12049         int flags;
12050 {
12051         struct dirrem *dirrem;
12052         struct diradd *dap, *nextdap;
12053         struct direct *ep;
12054         int i, chgs;
12055
12056         if ((pagedep->pd_state & IOSTARTED) == 0)
12057                 panic("handle_written_filepage: not started");
12058         pagedep->pd_state &= ~IOSTARTED;
12059         if ((flags & WRITESUCCEEDED) == 0)
12060                 goto rollforward;
12061         /*
12062          * Process any directory removals that have been committed.
12063          */
12064         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12065                 LIST_REMOVE(dirrem, dm_next);
12066                 dirrem->dm_state |= COMPLETE;
12067                 dirrem->dm_dirinum = pagedep->pd_ino;
12068                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12069                     ("handle_written_filepage: Journal entries not written."));
12070                 add_to_worklist(&dirrem->dm_list, 0);
12071         }
12072         /*
12073          * Free any directory additions that have been committed.
12074          * If it is a newly allocated block, we have to wait until
12075          * the on-disk directory inode claims the new block.
12076          */
12077         if ((pagedep->pd_state & NEWBLOCK) == 0)
12078                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12079                         free_diradd(dap, NULL);
12080 rollforward:
12081         /*
12082          * Uncommitted directory entries must be restored.
12083          */
12084         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12085                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12086                      dap = nextdap) {
12087                         nextdap = LIST_NEXT(dap, da_pdlist);
12088                         if (dap->da_state & ATTACHED)
12089                                 panic("handle_written_filepage: attached");
12090                         ep = (struct direct *)
12091                             ((char *)bp->b_data + dap->da_offset);
12092                         ep->d_ino = dap->da_newinum;
12093                         dap->da_state &= ~UNDONE;
12094                         dap->da_state |= ATTACHED;
12095                         chgs = 1;
12096                         /*
12097                          * If the inode referenced by the directory has
12098                          * been written out, then the dependency can be
12099                          * moved to the pending list.
12100                          */
12101                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12102                                 LIST_REMOVE(dap, da_pdlist);
12103                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12104                                     da_pdlist);
12105                         }
12106                 }
12107         }
12108         /*
12109          * If there were any rollbacks in the directory, then it must be
12110          * marked dirty so that its will eventually get written back in
12111          * its correct form.
12112          */
12113         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12114                 if ((bp->b_flags & B_DELWRI) == 0)
12115                         stat_dir_entry++;
12116                 bdirty(bp);
12117                 return (1);
12118         }
12119         /*
12120          * If we are not waiting for a new directory block to be
12121          * claimed by its inode, then the pagedep will be freed.
12122          * Otherwise it will remain to track any new entries on
12123          * the page in case they are fsync'ed.
12124          */
12125         free_pagedep(pagedep);
12126         return (0);
12127 }
12128
12129 /*
12130  * Writing back in-core inode structures.
12131  * 
12132  * The filesystem only accesses an inode's contents when it occupies an
12133  * "in-core" inode structure.  These "in-core" structures are separate from
12134  * the page frames used to cache inode blocks.  Only the latter are
12135  * transferred to/from the disk.  So, when the updated contents of the
12136  * "in-core" inode structure are copied to the corresponding in-memory inode
12137  * block, the dependencies are also transferred.  The following procedure is
12138  * called when copying a dirty "in-core" inode to a cached inode block.
12139  */
12140
12141 /*
12142  * Called when an inode is loaded from disk. If the effective link count
12143  * differed from the actual link count when it was last flushed, then we
12144  * need to ensure that the correct effective link count is put back.
12145  */
12146 void 
12147 softdep_load_inodeblock(ip)
12148         struct inode *ip;       /* the "in_core" copy of the inode */
12149 {
12150         struct inodedep *inodedep;
12151         struct ufsmount *ump;
12152
12153         ump = ITOUMP(ip);
12154         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12155             ("softdep_load_inodeblock called on non-softdep filesystem"));
12156         /*
12157          * Check for alternate nlink count.
12158          */
12159         ip->i_effnlink = ip->i_nlink;
12160         ACQUIRE_LOCK(ump);
12161         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12162                 FREE_LOCK(ump);
12163                 return;
12164         }
12165         ip->i_effnlink -= inodedep->id_nlinkdelta;
12166         FREE_LOCK(ump);
12167 }
12168
12169 /*
12170  * This routine is called just before the "in-core" inode
12171  * information is to be copied to the in-memory inode block.
12172  * Recall that an inode block contains several inodes. If
12173  * the force flag is set, then the dependencies will be
12174  * cleared so that the update can always be made. Note that
12175  * the buffer is locked when this routine is called, so we
12176  * will never be in the middle of writing the inode block 
12177  * to disk.
12178  */
12179 void 
12180 softdep_update_inodeblock(ip, bp, waitfor)
12181         struct inode *ip;       /* the "in_core" copy of the inode */
12182         struct buf *bp;         /* the buffer containing the inode block */
12183         int waitfor;            /* nonzero => update must be allowed */
12184 {
12185         struct inodedep *inodedep;
12186         struct inoref *inoref;
12187         struct ufsmount *ump;
12188         struct worklist *wk;
12189         struct mount *mp;
12190         struct buf *ibp;
12191         struct fs *fs;
12192         int error;
12193
12194         ump = ITOUMP(ip);
12195         mp = UFSTOVFS(ump);
12196         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12197             ("softdep_update_inodeblock called on non-softdep filesystem"));
12198         fs = ump->um_fs;
12199         /*
12200          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12201          * does not have access to the in-core ip so must write directly into
12202          * the inode block buffer when setting freelink.
12203          */
12204         if (fs->fs_magic == FS_UFS1_MAGIC)
12205                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12206                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12207         else
12208                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12209                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12210         /*
12211          * If the effective link count is not equal to the actual link
12212          * count, then we must track the difference in an inodedep while
12213          * the inode is (potentially) tossed out of the cache. Otherwise,
12214          * if there is no existing inodedep, then there are no dependencies
12215          * to track.
12216          */
12217         ACQUIRE_LOCK(ump);
12218 again:
12219         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12220                 FREE_LOCK(ump);
12221                 if (ip->i_effnlink != ip->i_nlink)
12222                         panic("softdep_update_inodeblock: bad link count");
12223                 return;
12224         }
12225         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12226                 panic("softdep_update_inodeblock: bad delta");
12227         /*
12228          * If we're flushing all dependencies we must also move any waiting
12229          * for journal writes onto the bufwait list prior to I/O.
12230          */
12231         if (waitfor) {
12232                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12233                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12234                             == DEPCOMPLETE) {
12235                                 jwait(&inoref->if_list, MNT_WAIT);
12236                                 goto again;
12237                         }
12238                 }
12239         }
12240         /*
12241          * Changes have been initiated. Anything depending on these
12242          * changes cannot occur until this inode has been written.
12243          */
12244         inodedep->id_state &= ~COMPLETE;
12245         if ((inodedep->id_state & ONWORKLIST) == 0)
12246                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12247         /*
12248          * Any new dependencies associated with the incore inode must 
12249          * now be moved to the list associated with the buffer holding
12250          * the in-memory copy of the inode. Once merged process any
12251          * allocdirects that are completed by the merger.
12252          */
12253         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12254         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12255                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12256                     NULL);
12257         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12258         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12259                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12260                     NULL);
12261         /*
12262          * Now that the inode has been pushed into the buffer, the
12263          * operations dependent on the inode being written to disk
12264          * can be moved to the id_bufwait so that they will be
12265          * processed when the buffer I/O completes.
12266          */
12267         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12268                 WORKLIST_REMOVE(wk);
12269                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12270         }
12271         /*
12272          * Newly allocated inodes cannot be written until the bitmap
12273          * that allocates them have been written (indicated by
12274          * DEPCOMPLETE being set in id_state). If we are doing a
12275          * forced sync (e.g., an fsync on a file), we force the bitmap
12276          * to be written so that the update can be done.
12277          */
12278         if (waitfor == 0) {
12279                 FREE_LOCK(ump);
12280                 return;
12281         }
12282 retry:
12283         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12284                 FREE_LOCK(ump);
12285                 return;
12286         }
12287         ibp = inodedep->id_bmsafemap->sm_buf;
12288         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12289         if (ibp == NULL) {
12290                 /*
12291                  * If ibp came back as NULL, the dependency could have been
12292                  * freed while we slept.  Look it up again, and check to see
12293                  * that it has completed.
12294                  */
12295                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12296                         goto retry;
12297                 FREE_LOCK(ump);
12298                 return;
12299         }
12300         FREE_LOCK(ump);
12301         if ((error = bwrite(ibp)) != 0)
12302                 softdep_error("softdep_update_inodeblock: bwrite", error);
12303 }
12304
12305 /*
12306  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12307  * old inode dependency list (such as id_inoupdt). This routine must be
12308  * called with splbio interrupts blocked.
12309  */
12310 static void
12311 merge_inode_lists(newlisthead, oldlisthead)
12312         struct allocdirectlst *newlisthead;
12313         struct allocdirectlst *oldlisthead;
12314 {
12315         struct allocdirect *listadp, *newadp;
12316
12317         newadp = TAILQ_FIRST(newlisthead);
12318         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12319                 if (listadp->ad_offset < newadp->ad_offset) {
12320                         listadp = TAILQ_NEXT(listadp, ad_next);
12321                         continue;
12322                 }
12323                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12324                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12325                 if (listadp->ad_offset == newadp->ad_offset) {
12326                         allocdirect_merge(oldlisthead, newadp,
12327                             listadp);
12328                         listadp = newadp;
12329                 }
12330                 newadp = TAILQ_FIRST(newlisthead);
12331         }
12332         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12333                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12334                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12335         }
12336 }
12337
12338 /*
12339  * If we are doing an fsync, then we must ensure that any directory
12340  * entries for the inode have been written after the inode gets to disk.
12341  */
12342 int
12343 softdep_fsync(vp)
12344         struct vnode *vp;       /* the "in_core" copy of the inode */
12345 {
12346         struct inodedep *inodedep;
12347         struct pagedep *pagedep;
12348         struct inoref *inoref;
12349         struct ufsmount *ump;
12350         struct worklist *wk;
12351         struct diradd *dap;
12352         struct mount *mp;
12353         struct vnode *pvp;
12354         struct inode *ip;
12355         struct buf *bp;
12356         struct fs *fs;
12357         struct thread *td = curthread;
12358         int error, flushparent, pagedep_new_block;
12359         ino_t parentino;
12360         ufs_lbn_t lbn;
12361
12362         ip = VTOI(vp);
12363         mp = vp->v_mount;
12364         ump = VFSTOUFS(mp);
12365         fs = ump->um_fs;
12366         if (MOUNTEDSOFTDEP(mp) == 0)
12367                 return (0);
12368         ACQUIRE_LOCK(ump);
12369 restart:
12370         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12371                 FREE_LOCK(ump);
12372                 return (0);
12373         }
12374         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12375                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12376                     == DEPCOMPLETE) {
12377                         jwait(&inoref->if_list, MNT_WAIT);
12378                         goto restart;
12379                 }
12380         }
12381         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12382             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12383             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12384             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12385             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12386                 panic("softdep_fsync: pending ops %p", inodedep);
12387         for (error = 0, flushparent = 0; ; ) {
12388                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12389                         break;
12390                 if (wk->wk_type != D_DIRADD)
12391                         panic("softdep_fsync: Unexpected type %s",
12392                             TYPENAME(wk->wk_type));
12393                 dap = WK_DIRADD(wk);
12394                 /*
12395                  * Flush our parent if this directory entry has a MKDIR_PARENT
12396                  * dependency or is contained in a newly allocated block.
12397                  */
12398                 if (dap->da_state & DIRCHG)
12399                         pagedep = dap->da_previous->dm_pagedep;
12400                 else
12401                         pagedep = dap->da_pagedep;
12402                 parentino = pagedep->pd_ino;
12403                 lbn = pagedep->pd_lbn;
12404                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12405                         panic("softdep_fsync: dirty");
12406                 if ((dap->da_state & MKDIR_PARENT) ||
12407                     (pagedep->pd_state & NEWBLOCK))
12408                         flushparent = 1;
12409                 else
12410                         flushparent = 0;
12411                 /*
12412                  * If we are being fsync'ed as part of vgone'ing this vnode,
12413                  * then we will not be able to release and recover the
12414                  * vnode below, so we just have to give up on writing its
12415                  * directory entry out. It will eventually be written, just
12416                  * not now, but then the user was not asking to have it
12417                  * written, so we are not breaking any promises.
12418                  */
12419                 if (vp->v_iflag & VI_DOOMED)
12420                         break;
12421                 /*
12422                  * We prevent deadlock by always fetching inodes from the
12423                  * root, moving down the directory tree. Thus, when fetching
12424                  * our parent directory, we first try to get the lock. If
12425                  * that fails, we must unlock ourselves before requesting
12426                  * the lock on our parent. See the comment in ufs_lookup
12427                  * for details on possible races.
12428                  */
12429                 FREE_LOCK(ump);
12430                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12431                     FFSV_FORCEINSMQ)) {
12432                         error = vfs_busy(mp, MBF_NOWAIT);
12433                         if (error != 0) {
12434                                 vfs_ref(mp);
12435                                 VOP_UNLOCK(vp, 0);
12436                                 error = vfs_busy(mp, 0);
12437                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12438                                 vfs_rel(mp);
12439                                 if (error != 0)
12440                                         return (ENOENT);
12441                                 if (vp->v_iflag & VI_DOOMED) {
12442                                         vfs_unbusy(mp);
12443                                         return (ENOENT);
12444                                 }
12445                         }
12446                         VOP_UNLOCK(vp, 0);
12447                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12448                             &pvp, FFSV_FORCEINSMQ);
12449                         vfs_unbusy(mp);
12450                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12451                         if (vp->v_iflag & VI_DOOMED) {
12452                                 if (error == 0)
12453                                         vput(pvp);
12454                                 error = ENOENT;
12455                         }
12456                         if (error != 0)
12457                                 return (error);
12458                 }
12459                 /*
12460                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12461                  * that are contained in direct blocks will be resolved by 
12462                  * doing a ffs_update. Pagedeps contained in indirect blocks
12463                  * may require a complete sync'ing of the directory. So, we
12464                  * try the cheap and fast ffs_update first, and if that fails,
12465                  * then we do the slower ffs_syncvnode of the directory.
12466                  */
12467                 if (flushparent) {
12468                         int locked;
12469
12470                         if ((error = ffs_update(pvp, 1)) != 0) {
12471                                 vput(pvp);
12472                                 return (error);
12473                         }
12474                         ACQUIRE_LOCK(ump);
12475                         locked = 1;
12476                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12477                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12478                                         if (wk->wk_type != D_DIRADD)
12479                                                 panic("softdep_fsync: Unexpected type %s",
12480                                                       TYPENAME(wk->wk_type));
12481                                         dap = WK_DIRADD(wk);
12482                                         if (dap->da_state & DIRCHG)
12483                                                 pagedep = dap->da_previous->dm_pagedep;
12484                                         else
12485                                                 pagedep = dap->da_pagedep;
12486                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12487                                         FREE_LOCK(ump);
12488                                         locked = 0;
12489                                         if (pagedep_new_block && (error =
12490                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12491                                                 vput(pvp);
12492                                                 return (error);
12493                                         }
12494                                 }
12495                         }
12496                         if (locked)
12497                                 FREE_LOCK(ump);
12498                 }
12499                 /*
12500                  * Flush directory page containing the inode's name.
12501                  */
12502                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12503                     &bp);
12504                 if (error == 0)
12505                         error = bwrite(bp);
12506                 else
12507                         brelse(bp);
12508                 vput(pvp);
12509                 if (error != 0)
12510                         return (error);
12511                 ACQUIRE_LOCK(ump);
12512                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12513                         break;
12514         }
12515         FREE_LOCK(ump);
12516         return (0);
12517 }
12518
12519 /*
12520  * Flush all the dirty bitmaps associated with the block device
12521  * before flushing the rest of the dirty blocks so as to reduce
12522  * the number of dependencies that will have to be rolled back.
12523  *
12524  * XXX Unused?
12525  */
12526 void
12527 softdep_fsync_mountdev(vp)
12528         struct vnode *vp;
12529 {
12530         struct buf *bp, *nbp;
12531         struct worklist *wk;
12532         struct bufobj *bo;
12533
12534         if (!vn_isdisk(vp, NULL))
12535                 panic("softdep_fsync_mountdev: vnode not a disk");
12536         bo = &vp->v_bufobj;
12537 restart:
12538         BO_LOCK(bo);
12539         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12540                 /* 
12541                  * If it is already scheduled, skip to the next buffer.
12542                  */
12543                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12544                         continue;
12545
12546                 if ((bp->b_flags & B_DELWRI) == 0)
12547                         panic("softdep_fsync_mountdev: not dirty");
12548                 /*
12549                  * We are only interested in bitmaps with outstanding
12550                  * dependencies.
12551                  */
12552                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12553                     wk->wk_type != D_BMSAFEMAP ||
12554                     (bp->b_vflags & BV_BKGRDINPROG)) {
12555                         BUF_UNLOCK(bp);
12556                         continue;
12557                 }
12558                 BO_UNLOCK(bo);
12559                 bremfree(bp);
12560                 (void) bawrite(bp);
12561                 goto restart;
12562         }
12563         drain_output(vp);
12564         BO_UNLOCK(bo);
12565 }
12566
12567 /*
12568  * Sync all cylinder groups that were dirty at the time this function is
12569  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12570  * is used to flush freedep activity that may be holding up writes to a
12571  * indirect block.
12572  */
12573 static int
12574 sync_cgs(mp, waitfor)
12575         struct mount *mp;
12576         int waitfor;
12577 {
12578         struct bmsafemap *bmsafemap;
12579         struct bmsafemap *sentinel;
12580         struct ufsmount *ump;
12581         struct buf *bp;
12582         int error;
12583
12584         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12585         sentinel->sm_cg = -1;
12586         ump = VFSTOUFS(mp);
12587         error = 0;
12588         ACQUIRE_LOCK(ump);
12589         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12590         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12591             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12592                 /* Skip sentinels and cgs with no work to release. */
12593                 if (bmsafemap->sm_cg == -1 ||
12594                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12595                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12596                         LIST_REMOVE(sentinel, sm_next);
12597                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12598                         continue;
12599                 }
12600                 /*
12601                  * If we don't get the lock and we're waiting try again, if
12602                  * not move on to the next buf and try to sync it.
12603                  */
12604                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12605                 if (bp == NULL && waitfor == MNT_WAIT)
12606                         continue;
12607                 LIST_REMOVE(sentinel, sm_next);
12608                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12609                 if (bp == NULL)
12610                         continue;
12611                 FREE_LOCK(ump);
12612                 if (waitfor == MNT_NOWAIT)
12613                         bawrite(bp);
12614                 else
12615                         error = bwrite(bp);
12616                 ACQUIRE_LOCK(ump);
12617                 if (error)
12618                         break;
12619         }
12620         LIST_REMOVE(sentinel, sm_next);
12621         FREE_LOCK(ump);
12622         free(sentinel, M_BMSAFEMAP);
12623         return (error);
12624 }
12625
12626 /*
12627  * This routine is called when we are trying to synchronously flush a
12628  * file. This routine must eliminate any filesystem metadata dependencies
12629  * so that the syncing routine can succeed.
12630  */
12631 int
12632 softdep_sync_metadata(struct vnode *vp)
12633 {
12634         struct inode *ip;
12635         int error;
12636
12637         ip = VTOI(vp);
12638         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12639             ("softdep_sync_metadata called on non-softdep filesystem"));
12640         /*
12641          * Ensure that any direct block dependencies have been cleared,
12642          * truncations are started, and inode references are journaled.
12643          */
12644         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12645         /*
12646          * Write all journal records to prevent rollbacks on devvp.
12647          */
12648         if (vp->v_type == VCHR)
12649                 softdep_flushjournal(vp->v_mount);
12650         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12651         /*
12652          * Ensure that all truncates are written so we won't find deps on
12653          * indirect blocks.
12654          */
12655         process_truncates(vp);
12656         FREE_LOCK(VFSTOUFS(vp->v_mount));
12657
12658         return (error);
12659 }
12660
12661 /*
12662  * This routine is called when we are attempting to sync a buf with
12663  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12664  * other IO it can but returns EBUSY if the buffer is not yet able to
12665  * be written.  Dependencies which will not cause rollbacks will always
12666  * return 0.
12667  */
12668 int
12669 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12670 {
12671         struct indirdep *indirdep;
12672         struct pagedep *pagedep;
12673         struct allocindir *aip;
12674         struct newblk *newblk;
12675         struct ufsmount *ump;
12676         struct buf *nbp;
12677         struct worklist *wk;
12678         int i, error;
12679
12680         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12681             ("softdep_sync_buf called on non-softdep filesystem"));
12682         /*
12683          * For VCHR we just don't want to force flush any dependencies that
12684          * will cause rollbacks.
12685          */
12686         if (vp->v_type == VCHR) {
12687                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12688                         return (EBUSY);
12689                 return (0);
12690         }
12691         ump = VFSTOUFS(vp->v_mount);
12692         ACQUIRE_LOCK(ump);
12693         /*
12694          * As we hold the buffer locked, none of its dependencies
12695          * will disappear.
12696          */
12697         error = 0;
12698 top:
12699         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12700                 switch (wk->wk_type) {
12701
12702                 case D_ALLOCDIRECT:
12703                 case D_ALLOCINDIR:
12704                         newblk = WK_NEWBLK(wk);
12705                         if (newblk->nb_jnewblk != NULL) {
12706                                 if (waitfor == MNT_NOWAIT) {
12707                                         error = EBUSY;
12708                                         goto out_unlock;
12709                                 }
12710                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12711                                 goto top;
12712                         }
12713                         if (newblk->nb_state & DEPCOMPLETE ||
12714                             waitfor == MNT_NOWAIT)
12715                                 continue;
12716                         nbp = newblk->nb_bmsafemap->sm_buf;
12717                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12718                         if (nbp == NULL)
12719                                 goto top;
12720                         FREE_LOCK(ump);
12721                         if ((error = bwrite(nbp)) != 0)
12722                                 goto out;
12723                         ACQUIRE_LOCK(ump);
12724                         continue;
12725
12726                 case D_INDIRDEP:
12727                         indirdep = WK_INDIRDEP(wk);
12728                         if (waitfor == MNT_NOWAIT) {
12729                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12730                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12731                                         error = EBUSY;
12732                                         goto out_unlock;
12733                                 }
12734                         }
12735                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12736                                 panic("softdep_sync_buf: truncation pending.");
12737                 restart:
12738                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12739                                 newblk = (struct newblk *)aip;
12740                                 if (newblk->nb_jnewblk != NULL) {
12741                                         jwait(&newblk->nb_jnewblk->jn_list,
12742                                             waitfor);
12743                                         goto restart;
12744                                 }
12745                                 if (newblk->nb_state & DEPCOMPLETE)
12746                                         continue;
12747                                 nbp = newblk->nb_bmsafemap->sm_buf;
12748                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12749                                 if (nbp == NULL)
12750                                         goto restart;
12751                                 FREE_LOCK(ump);
12752                                 if ((error = bwrite(nbp)) != 0)
12753                                         goto out;
12754                                 ACQUIRE_LOCK(ump);
12755                                 goto restart;
12756                         }
12757                         continue;
12758
12759                 case D_PAGEDEP:
12760                         /*
12761                          * Only flush directory entries in synchronous passes.
12762                          */
12763                         if (waitfor != MNT_WAIT) {
12764                                 error = EBUSY;
12765                                 goto out_unlock;
12766                         }
12767                         /*
12768                          * While syncing snapshots, we must allow recursive
12769                          * lookups.
12770                          */
12771                         BUF_AREC(bp);
12772                         /*
12773                          * We are trying to sync a directory that may
12774                          * have dependencies on both its own metadata
12775                          * and/or dependencies on the inodes of any
12776                          * recently allocated files. We walk its diradd
12777                          * lists pushing out the associated inode.
12778                          */
12779                         pagedep = WK_PAGEDEP(wk);
12780                         for (i = 0; i < DAHASHSZ; i++) {
12781                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12782                                         continue;
12783                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12784                                     &pagedep->pd_diraddhd[i]))) {
12785                                         BUF_NOREC(bp);
12786                                         goto out_unlock;
12787                                 }
12788                         }
12789                         BUF_NOREC(bp);
12790                         continue;
12791
12792                 case D_FREEWORK:
12793                 case D_FREEDEP:
12794                 case D_JSEGDEP:
12795                 case D_JNEWBLK:
12796                         continue;
12797
12798                 default:
12799                         panic("softdep_sync_buf: Unknown type %s",
12800                             TYPENAME(wk->wk_type));
12801                         /* NOTREACHED */
12802                 }
12803         }
12804 out_unlock:
12805         FREE_LOCK(ump);
12806 out:
12807         return (error);
12808 }
12809
12810 /*
12811  * Flush the dependencies associated with an inodedep.
12812  * Called with splbio blocked.
12813  */
12814 static int
12815 flush_inodedep_deps(vp, mp, ino)
12816         struct vnode *vp;
12817         struct mount *mp;
12818         ino_t ino;
12819 {
12820         struct inodedep *inodedep;
12821         struct inoref *inoref;
12822         struct ufsmount *ump;
12823         int error, waitfor;
12824
12825         /*
12826          * This work is done in two passes. The first pass grabs most
12827          * of the buffers and begins asynchronously writing them. The
12828          * only way to wait for these asynchronous writes is to sleep
12829          * on the filesystem vnode which may stay busy for a long time
12830          * if the filesystem is active. So, instead, we make a second
12831          * pass over the dependencies blocking on each write. In the
12832          * usual case we will be blocking against a write that we
12833          * initiated, so when it is done the dependency will have been
12834          * resolved. Thus the second pass is expected to end quickly.
12835          * We give a brief window at the top of the loop to allow
12836          * any pending I/O to complete.
12837          */
12838         ump = VFSTOUFS(mp);
12839         LOCK_OWNED(ump);
12840         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12841                 if (error)
12842                         return (error);
12843                 FREE_LOCK(ump);
12844                 ACQUIRE_LOCK(ump);
12845 restart:
12846                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12847                         return (0);
12848                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12849                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12850                             == DEPCOMPLETE) {
12851                                 jwait(&inoref->if_list, MNT_WAIT);
12852                                 goto restart;
12853                         }
12854                 }
12855                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12856                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12857                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12858                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12859                         continue;
12860                 /*
12861                  * If pass2, we are done, otherwise do pass 2.
12862                  */
12863                 if (waitfor == MNT_WAIT)
12864                         break;
12865                 waitfor = MNT_WAIT;
12866         }
12867         /*
12868          * Try freeing inodedep in case all dependencies have been removed.
12869          */
12870         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12871                 (void) free_inodedep(inodedep);
12872         return (0);
12873 }
12874
12875 /*
12876  * Flush an inode dependency list.
12877  * Called with splbio blocked.
12878  */
12879 static int
12880 flush_deplist(listhead, waitfor, errorp)
12881         struct allocdirectlst *listhead;
12882         int waitfor;
12883         int *errorp;
12884 {
12885         struct allocdirect *adp;
12886         struct newblk *newblk;
12887         struct ufsmount *ump;
12888         struct buf *bp;
12889
12890         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12891                 return (0);
12892         ump = VFSTOUFS(adp->ad_list.wk_mp);
12893         LOCK_OWNED(ump);
12894         TAILQ_FOREACH(adp, listhead, ad_next) {
12895                 newblk = (struct newblk *)adp;
12896                 if (newblk->nb_jnewblk != NULL) {
12897                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12898                         return (1);
12899                 }
12900                 if (newblk->nb_state & DEPCOMPLETE)
12901                         continue;
12902                 bp = newblk->nb_bmsafemap->sm_buf;
12903                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12904                 if (bp == NULL) {
12905                         if (waitfor == MNT_NOWAIT)
12906                                 continue;
12907                         return (1);
12908                 }
12909                 FREE_LOCK(ump);
12910                 if (waitfor == MNT_NOWAIT)
12911                         bawrite(bp);
12912                 else 
12913                         *errorp = bwrite(bp);
12914                 ACQUIRE_LOCK(ump);
12915                 return (1);
12916         }
12917         return (0);
12918 }
12919
12920 /*
12921  * Flush dependencies associated with an allocdirect block.
12922  */
12923 static int
12924 flush_newblk_dep(vp, mp, lbn)
12925         struct vnode *vp;
12926         struct mount *mp;
12927         ufs_lbn_t lbn;
12928 {
12929         struct newblk *newblk;
12930         struct ufsmount *ump;
12931         struct bufobj *bo;
12932         struct inode *ip;
12933         struct buf *bp;
12934         ufs2_daddr_t blkno;
12935         int error;
12936
12937         error = 0;
12938         bo = &vp->v_bufobj;
12939         ip = VTOI(vp);
12940         blkno = DIP(ip, i_db[lbn]);
12941         if (blkno == 0)
12942                 panic("flush_newblk_dep: Missing block");
12943         ump = VFSTOUFS(mp);
12944         ACQUIRE_LOCK(ump);
12945         /*
12946          * Loop until all dependencies related to this block are satisfied.
12947          * We must be careful to restart after each sleep in case a write
12948          * completes some part of this process for us.
12949          */
12950         for (;;) {
12951                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12952                         FREE_LOCK(ump);
12953                         break;
12954                 }
12955                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12956                         panic("flush_newblk_deps: Bad newblk %p", newblk);
12957                 /*
12958                  * Flush the journal.
12959                  */
12960                 if (newblk->nb_jnewblk != NULL) {
12961                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12962                         continue;
12963                 }
12964                 /*
12965                  * Write the bitmap dependency.
12966                  */
12967                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12968                         bp = newblk->nb_bmsafemap->sm_buf;
12969                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12970                         if (bp == NULL)
12971                                 continue;
12972                         FREE_LOCK(ump);
12973                         error = bwrite(bp);
12974                         if (error)
12975                                 break;
12976                         ACQUIRE_LOCK(ump);
12977                         continue;
12978                 }
12979                 /*
12980                  * Write the buffer.
12981                  */
12982                 FREE_LOCK(ump);
12983                 BO_LOCK(bo);
12984                 bp = gbincore(bo, lbn);
12985                 if (bp != NULL) {
12986                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12987                             LK_INTERLOCK, BO_LOCKPTR(bo));
12988                         if (error == ENOLCK) {
12989                                 ACQUIRE_LOCK(ump);
12990                                 error = 0;
12991                                 continue; /* Slept, retry */
12992                         }
12993                         if (error != 0)
12994                                 break;  /* Failed */
12995                         if (bp->b_flags & B_DELWRI) {
12996                                 bremfree(bp);
12997                                 error = bwrite(bp);
12998                                 if (error)
12999                                         break;
13000                         } else
13001                                 BUF_UNLOCK(bp);
13002                 } else
13003                         BO_UNLOCK(bo);
13004                 /*
13005                  * We have to wait for the direct pointers to
13006                  * point at the newdirblk before the dependency
13007                  * will go away.
13008                  */
13009                 error = ffs_update(vp, 1);
13010                 if (error)
13011                         break;
13012                 ACQUIRE_LOCK(ump);
13013         }
13014         return (error);
13015 }
13016
13017 /*
13018  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13019  * Called with splbio blocked.
13020  */
13021 static int
13022 flush_pagedep_deps(pvp, mp, diraddhdp)
13023         struct vnode *pvp;
13024         struct mount *mp;
13025         struct diraddhd *diraddhdp;
13026 {
13027         struct inodedep *inodedep;
13028         struct inoref *inoref;
13029         struct ufsmount *ump;
13030         struct diradd *dap;
13031         struct vnode *vp;
13032         int error = 0;
13033         struct buf *bp;
13034         ino_t inum;
13035         struct diraddhd unfinished;
13036
13037         LIST_INIT(&unfinished);
13038         ump = VFSTOUFS(mp);
13039         LOCK_OWNED(ump);
13040 restart:
13041         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13042                 /*
13043                  * Flush ourselves if this directory entry
13044                  * has a MKDIR_PARENT dependency.
13045                  */
13046                 if (dap->da_state & MKDIR_PARENT) {
13047                         FREE_LOCK(ump);
13048                         if ((error = ffs_update(pvp, 1)) != 0)
13049                                 break;
13050                         ACQUIRE_LOCK(ump);
13051                         /*
13052                          * If that cleared dependencies, go on to next.
13053                          */
13054                         if (dap != LIST_FIRST(diraddhdp))
13055                                 continue;
13056                         /*
13057                          * All MKDIR_PARENT dependencies and all the
13058                          * NEWBLOCK pagedeps that are contained in direct
13059                          * blocks were resolved by doing above ffs_update.
13060                          * Pagedeps contained in indirect blocks may
13061                          * require a complete sync'ing of the directory.
13062                          * We are in the midst of doing a complete sync,
13063                          * so if they are not resolved in this pass we
13064                          * defer them for now as they will be sync'ed by
13065                          * our caller shortly.
13066                          */
13067                         LIST_REMOVE(dap, da_pdlist);
13068                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13069                         continue;
13070                 }
13071                 /*
13072                  * A newly allocated directory must have its "." and
13073                  * ".." entries written out before its name can be
13074                  * committed in its parent. 
13075                  */
13076                 inum = dap->da_newinum;
13077                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13078                         panic("flush_pagedep_deps: lost inode1");
13079                 /*
13080                  * Wait for any pending journal adds to complete so we don't
13081                  * cause rollbacks while syncing.
13082                  */
13083                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13084                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13085                             == DEPCOMPLETE) {
13086                                 jwait(&inoref->if_list, MNT_WAIT);
13087                                 goto restart;
13088                         }
13089                 }
13090                 if (dap->da_state & MKDIR_BODY) {
13091                         FREE_LOCK(ump);
13092                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13093                             FFSV_FORCEINSMQ)))
13094                                 break;
13095                         error = flush_newblk_dep(vp, mp, 0);
13096                         /*
13097                          * If we still have the dependency we might need to
13098                          * update the vnode to sync the new link count to
13099                          * disk.
13100                          */
13101                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13102                                 error = ffs_update(vp, 1);
13103                         vput(vp);
13104                         if (error != 0)
13105                                 break;
13106                         ACQUIRE_LOCK(ump);
13107                         /*
13108                          * If that cleared dependencies, go on to next.
13109                          */
13110                         if (dap != LIST_FIRST(diraddhdp))
13111                                 continue;
13112                         if (dap->da_state & MKDIR_BODY) {
13113                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13114                                     &inodedep);
13115                                 panic("flush_pagedep_deps: MKDIR_BODY "
13116                                     "inodedep %p dap %p vp %p",
13117                                     inodedep, dap, vp);
13118                         }
13119                 }
13120                 /*
13121                  * Flush the inode on which the directory entry depends.
13122                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13123                  * the only remaining dependency is that the updated inode
13124                  * count must get pushed to disk. The inode has already
13125                  * been pushed into its inode buffer (via VOP_UPDATE) at
13126                  * the time of the reference count change. So we need only
13127                  * locate that buffer, ensure that there will be no rollback
13128                  * caused by a bitmap dependency, then write the inode buffer.
13129                  */
13130 retry:
13131                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13132                         panic("flush_pagedep_deps: lost inode");
13133                 /*
13134                  * If the inode still has bitmap dependencies,
13135                  * push them to disk.
13136                  */
13137                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13138                         bp = inodedep->id_bmsafemap->sm_buf;
13139                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13140                         if (bp == NULL)
13141                                 goto retry;
13142                         FREE_LOCK(ump);
13143                         if ((error = bwrite(bp)) != 0)
13144                                 break;
13145                         ACQUIRE_LOCK(ump);
13146                         if (dap != LIST_FIRST(diraddhdp))
13147                                 continue;
13148                 }
13149                 /*
13150                  * If the inode is still sitting in a buffer waiting
13151                  * to be written or waiting for the link count to be
13152                  * adjusted update it here to flush it to disk.
13153                  */
13154                 if (dap == LIST_FIRST(diraddhdp)) {
13155                         FREE_LOCK(ump);
13156                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13157                             FFSV_FORCEINSMQ)))
13158                                 break;
13159                         error = ffs_update(vp, 1);
13160                         vput(vp);
13161                         if (error)
13162                                 break;
13163                         ACQUIRE_LOCK(ump);
13164                 }
13165                 /*
13166                  * If we have failed to get rid of all the dependencies
13167                  * then something is seriously wrong.
13168                  */
13169                 if (dap == LIST_FIRST(diraddhdp)) {
13170                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13171                         panic("flush_pagedep_deps: failed to flush " 
13172                             "inodedep %p ino %ju dap %p",
13173                             inodedep, (uintmax_t)inum, dap);
13174                 }
13175         }
13176         if (error)
13177                 ACQUIRE_LOCK(ump);
13178         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13179                 LIST_REMOVE(dap, da_pdlist);
13180                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13181         }
13182         return (error);
13183 }
13184
13185 /*
13186  * A large burst of file addition or deletion activity can drive the
13187  * memory load excessively high. First attempt to slow things down
13188  * using the techniques below. If that fails, this routine requests
13189  * the offending operations to fall back to running synchronously
13190  * until the memory load returns to a reasonable level.
13191  */
13192 int
13193 softdep_slowdown(vp)
13194         struct vnode *vp;
13195 {
13196         struct ufsmount *ump;
13197         int jlow;
13198         int max_softdeps_hard;
13199
13200         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13201             ("softdep_slowdown called on non-softdep filesystem"));
13202         ump = VFSTOUFS(vp->v_mount);
13203         ACQUIRE_LOCK(ump);
13204         jlow = 0;
13205         /*
13206          * Check for journal space if needed.
13207          */
13208         if (DOINGSUJ(vp)) {
13209                 if (journal_space(ump, 0) == 0)
13210                         jlow = 1;
13211         }
13212         /*
13213          * If the system is under its limits and our filesystem is
13214          * not responsible for more than our share of the usage and
13215          * we are not low on journal space, then no need to slow down.
13216          */
13217         max_softdeps_hard = max_softdeps * 11 / 10;
13218         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13219             dep_current[D_INODEDEP] < max_softdeps_hard &&
13220             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13221             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13222             ump->softdep_curdeps[D_DIRREM] <
13223             (max_softdeps_hard / 2) / stat_flush_threads &&
13224             ump->softdep_curdeps[D_INODEDEP] <
13225             max_softdeps_hard / stat_flush_threads &&
13226             ump->softdep_curdeps[D_INDIRDEP] <
13227             (max_softdeps_hard / 1000) / stat_flush_threads &&
13228             ump->softdep_curdeps[D_FREEBLKS] <
13229             max_softdeps_hard / stat_flush_threads) {
13230                 FREE_LOCK(ump);
13231                 return (0);
13232         }
13233         /*
13234          * If the journal is low or our filesystem is over its limit
13235          * then speedup the cleanup.
13236          */
13237         if (ump->softdep_curdeps[D_INDIRDEP] <
13238             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13239                 softdep_speedup(ump);
13240         stat_sync_limit_hit += 1;
13241         FREE_LOCK(ump);
13242         /*
13243          * We only slow down the rate at which new dependencies are
13244          * generated if we are not using journaling. With journaling,
13245          * the cleanup should always be sufficient to keep things
13246          * under control.
13247          */
13248         if (DOINGSUJ(vp))
13249                 return (0);
13250         return (1);
13251 }
13252
13253 /*
13254  * Called by the allocation routines when they are about to fail
13255  * in the hope that we can free up the requested resource (inodes
13256  * or disk space).
13257  * 
13258  * First check to see if the work list has anything on it. If it has,
13259  * clean up entries until we successfully free the requested resource.
13260  * Because this process holds inodes locked, we cannot handle any remove
13261  * requests that might block on a locked inode as that could lead to
13262  * deadlock. If the worklist yields none of the requested resource,
13263  * start syncing out vnodes to free up the needed space.
13264  */
13265 int
13266 softdep_request_cleanup(fs, vp, cred, resource)
13267         struct fs *fs;
13268         struct vnode *vp;
13269         struct ucred *cred;
13270         int resource;
13271 {
13272         struct ufsmount *ump;
13273         struct mount *mp;
13274         long starttime;
13275         ufs2_daddr_t needed;
13276         int error, failed_vnode;
13277
13278         /*
13279          * If we are being called because of a process doing a
13280          * copy-on-write, then it is not safe to process any
13281          * worklist items as we will recurse into the copyonwrite
13282          * routine.  This will result in an incoherent snapshot.
13283          * If the vnode that we hold is a snapshot, we must avoid
13284          * handling other resources that could cause deadlock.
13285          */
13286         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13287                 return (0);
13288
13289         if (resource == FLUSH_BLOCKS_WAIT)
13290                 stat_cleanup_blkrequests += 1;
13291         else
13292                 stat_cleanup_inorequests += 1;
13293
13294         mp = vp->v_mount;
13295         ump = VFSTOUFS(mp);
13296         mtx_assert(UFS_MTX(ump), MA_OWNED);
13297         UFS_UNLOCK(ump);
13298         error = ffs_update(vp, 1);
13299         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13300                 UFS_LOCK(ump);
13301                 return (0);
13302         }
13303         /*
13304          * If we are in need of resources, start by cleaning up
13305          * any block removals associated with our inode.
13306          */
13307         ACQUIRE_LOCK(ump);
13308         process_removes(vp);
13309         process_truncates(vp);
13310         FREE_LOCK(ump);
13311         /*
13312          * Now clean up at least as many resources as we will need.
13313          *
13314          * When requested to clean up inodes, the number that are needed
13315          * is set by the number of simultaneous writers (mnt_writeopcount)
13316          * plus a bit of slop (2) in case some more writers show up while
13317          * we are cleaning.
13318          *
13319          * When requested to free up space, the amount of space that
13320          * we need is enough blocks to allocate a full-sized segment
13321          * (fs_contigsumsize). The number of such segments that will
13322          * be needed is set by the number of simultaneous writers
13323          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13324          * writers show up while we are cleaning.
13325          *
13326          * Additionally, if we are unpriviledged and allocating space,
13327          * we need to ensure that we clean up enough blocks to get the
13328          * needed number of blocks over the threshold of the minimum
13329          * number of blocks required to be kept free by the filesystem
13330          * (fs_minfree).
13331          */
13332         if (resource == FLUSH_INODES_WAIT) {
13333                 needed = vp->v_mount->mnt_writeopcount + 2;
13334         } else if (resource == FLUSH_BLOCKS_WAIT) {
13335                 needed = (vp->v_mount->mnt_writeopcount + 2) *
13336                     fs->fs_contigsumsize;
13337                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13338                         needed += fragstoblks(fs,
13339                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13340                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13341         } else {
13342                 UFS_LOCK(ump);
13343                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13344                     resource);
13345                 return (0);
13346         }
13347         starttime = time_second;
13348 retry:
13349         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13350             fs->fs_cstotal.cs_nbfree <= needed) ||
13351             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13352             fs->fs_cstotal.cs_nifree <= needed)) {
13353                 ACQUIRE_LOCK(ump);
13354                 if (ump->softdep_on_worklist > 0 &&
13355                     process_worklist_item(UFSTOVFS(ump),
13356                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13357                         stat_worklist_push += 1;
13358                 FREE_LOCK(ump);
13359         }
13360         /*
13361          * If we still need resources and there are no more worklist
13362          * entries to process to obtain them, we have to start flushing
13363          * the dirty vnodes to force the release of additional requests
13364          * to the worklist that we can then process to reap addition
13365          * resources. We walk the vnodes associated with the mount point
13366          * until we get the needed worklist requests that we can reap.
13367          *
13368          * If there are several threads all needing to clean the same
13369          * mount point, only one is allowed to walk the mount list.
13370          * When several threads all try to walk the same mount list,
13371          * they end up competing with each other and often end up in
13372          * livelock. This approach ensures that forward progress is
13373          * made at the cost of occational ENOSPC errors being returned
13374          * that might otherwise have been avoided.
13375          */
13376         error = 1;
13377         if ((resource == FLUSH_BLOCKS_WAIT && 
13378              fs->fs_cstotal.cs_nbfree <= needed) ||
13379             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13380              fs->fs_cstotal.cs_nifree <= needed)) {
13381                 ACQUIRE_LOCK(ump);
13382                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13383                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13384                         FREE_LOCK(ump);
13385                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13386                         ACQUIRE_LOCK(ump);
13387                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13388                         FREE_LOCK(ump);
13389                         if (ump->softdep_on_worklist > 0) {
13390                                 stat_cleanup_retries += 1;
13391                                 if (!failed_vnode)
13392                                         goto retry;
13393                         }
13394                 } else {
13395                         FREE_LOCK(ump);
13396                         error = 0;
13397                 }
13398                 stat_cleanup_failures += 1;
13399         }
13400         if (time_second - starttime > stat_cleanup_high_delay)
13401                 stat_cleanup_high_delay = time_second - starttime;
13402         UFS_LOCK(ump);
13403         return (error);
13404 }
13405
13406 /*
13407  * Scan the vnodes for the specified mount point flushing out any
13408  * vnodes that can be locked without waiting. Finally, try to flush
13409  * the device associated with the mount point if it can be locked
13410  * without waiting.
13411  *
13412  * We return 0 if we were able to lock every vnode in our scan.
13413  * If we had to skip one or more vnodes, we return 1.
13414  */
13415 static int
13416 softdep_request_cleanup_flush(mp, ump)
13417         struct mount *mp;
13418         struct ufsmount *ump;
13419 {
13420         struct thread *td;
13421         struct vnode *lvp, *mvp;
13422         int failed_vnode;
13423
13424         failed_vnode = 0;
13425         td = curthread;
13426         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13427                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13428                         VI_UNLOCK(lvp);
13429                         continue;
13430                 }
13431                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13432                     td) != 0) {
13433                         failed_vnode = 1;
13434                         continue;
13435                 }
13436                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13437                         vput(lvp);
13438                         continue;
13439                 }
13440                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13441                 vput(lvp);
13442         }
13443         lvp = ump->um_devvp;
13444         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13445                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13446                 VOP_UNLOCK(lvp, 0);
13447         }
13448         return (failed_vnode);
13449 }
13450
13451 static bool
13452 softdep_excess_items(struct ufsmount *ump, int item)
13453 {
13454
13455         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13456         return (dep_current[item] > max_softdeps &&
13457             ump->softdep_curdeps[item] > max_softdeps /
13458             stat_flush_threads);
13459 }
13460
13461 static void
13462 schedule_cleanup(struct mount *mp)
13463 {
13464         struct ufsmount *ump;
13465         struct thread *td;
13466
13467         ump = VFSTOUFS(mp);
13468         LOCK_OWNED(ump);
13469         FREE_LOCK(ump);
13470         td = curthread;
13471         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13472             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13473                 /*
13474                  * No ast is delivered to kernel threads, so nobody
13475                  * would deref the mp.  Some kernel threads
13476                  * explicitely check for AST, e.g. NFS daemon does
13477                  * this in the serving loop.
13478                  */
13479                 return;
13480         }
13481         if (td->td_su != NULL)
13482                 vfs_rel(td->td_su);
13483         vfs_ref(mp);
13484         td->td_su = mp;
13485         thread_lock(td);
13486         td->td_flags |= TDF_ASTPENDING;
13487         thread_unlock(td);
13488 }
13489
13490 static void
13491 softdep_ast_cleanup_proc(struct thread *td)
13492 {
13493         struct mount *mp;
13494         struct ufsmount *ump;
13495         int error;
13496         bool req;
13497
13498         while ((mp = td->td_su) != NULL) {
13499                 td->td_su = NULL;
13500                 error = vfs_busy(mp, MBF_NOWAIT);
13501                 vfs_rel(mp);
13502                 if (error != 0)
13503                         return;
13504                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13505                         ump = VFSTOUFS(mp);
13506                         for (;;) {
13507                                 req = false;
13508                                 ACQUIRE_LOCK(ump);
13509                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13510                                         req = true;
13511                                         request_cleanup(mp, FLUSH_INODES);
13512                                 }
13513                                 if (softdep_excess_items(ump, D_DIRREM)) {
13514                                         req = true;
13515                                         request_cleanup(mp, FLUSH_BLOCKS);
13516                                 }
13517                                 FREE_LOCK(ump);
13518                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13519                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13520                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13521                                         error = vn_start_write(NULL, &mp,
13522                                             V_WAIT);
13523                                         if (error == 0) {
13524                                                 req = true;
13525                                                 VFS_SYNC(mp, MNT_WAIT);
13526                                                 vn_finished_write(mp);
13527                                         }
13528                                 }
13529                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13530                                         break;
13531                         }
13532                 }
13533                 vfs_unbusy(mp);
13534         }
13535         if ((mp = td->td_su) != NULL) {
13536                 td->td_su = NULL;
13537                 vfs_rel(mp);
13538         }
13539 }
13540
13541 /*
13542  * If memory utilization has gotten too high, deliberately slow things
13543  * down and speed up the I/O processing.
13544  */
13545 static int
13546 request_cleanup(mp, resource)
13547         struct mount *mp;
13548         int resource;
13549 {
13550         struct thread *td = curthread;
13551         struct ufsmount *ump;
13552
13553         ump = VFSTOUFS(mp);
13554         LOCK_OWNED(ump);
13555         /*
13556          * We never hold up the filesystem syncer or buf daemon.
13557          */
13558         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13559                 return (0);
13560         /*
13561          * First check to see if the work list has gotten backlogged.
13562          * If it has, co-opt this process to help clean up two entries.
13563          * Because this process may hold inodes locked, we cannot
13564          * handle any remove requests that might block on a locked
13565          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13566          * to avoid recursively processing the worklist.
13567          */
13568         if (ump->softdep_on_worklist > max_softdeps / 10) {
13569                 td->td_pflags |= TDP_SOFTDEP;
13570                 process_worklist_item(mp, 2, LK_NOWAIT);
13571                 td->td_pflags &= ~TDP_SOFTDEP;
13572                 stat_worklist_push += 2;
13573                 return(1);
13574         }
13575         /*
13576          * Next, we attempt to speed up the syncer process. If that
13577          * is successful, then we allow the process to continue.
13578          */
13579         if (softdep_speedup(ump) &&
13580             resource != FLUSH_BLOCKS_WAIT &&
13581             resource != FLUSH_INODES_WAIT)
13582                 return(0);
13583         /*
13584          * If we are resource constrained on inode dependencies, try
13585          * flushing some dirty inodes. Otherwise, we are constrained
13586          * by file deletions, so try accelerating flushes of directories
13587          * with removal dependencies. We would like to do the cleanup
13588          * here, but we probably hold an inode locked at this point and 
13589          * that might deadlock against one that we try to clean. So,
13590          * the best that we can do is request the syncer daemon to do
13591          * the cleanup for us.
13592          */
13593         switch (resource) {
13594
13595         case FLUSH_INODES:
13596         case FLUSH_INODES_WAIT:
13597                 ACQUIRE_GBLLOCK(&lk);
13598                 stat_ino_limit_push += 1;
13599                 req_clear_inodedeps += 1;
13600                 FREE_GBLLOCK(&lk);
13601                 stat_countp = &stat_ino_limit_hit;
13602                 break;
13603
13604         case FLUSH_BLOCKS:
13605         case FLUSH_BLOCKS_WAIT:
13606                 ACQUIRE_GBLLOCK(&lk);
13607                 stat_blk_limit_push += 1;
13608                 req_clear_remove += 1;
13609                 FREE_GBLLOCK(&lk);
13610                 stat_countp = &stat_blk_limit_hit;
13611                 break;
13612
13613         default:
13614                 panic("request_cleanup: unknown type");
13615         }
13616         /*
13617          * Hopefully the syncer daemon will catch up and awaken us.
13618          * We wait at most tickdelay before proceeding in any case.
13619          */
13620         ACQUIRE_GBLLOCK(&lk);
13621         FREE_LOCK(ump);
13622         proc_waiting += 1;
13623         if (callout_pending(&softdep_callout) == FALSE)
13624                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13625                     pause_timer, 0);
13626
13627         if ((td->td_pflags & TDP_KTHREAD) == 0)
13628                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13629         proc_waiting -= 1;
13630         FREE_GBLLOCK(&lk);
13631         ACQUIRE_LOCK(ump);
13632         return (1);
13633 }
13634
13635 /*
13636  * Awaken processes pausing in request_cleanup and clear proc_waiting
13637  * to indicate that there is no longer a timer running. Pause_timer
13638  * will be called with the global softdep mutex (&lk) locked.
13639  */
13640 static void
13641 pause_timer(arg)
13642         void *arg;
13643 {
13644
13645         GBLLOCK_OWNED(&lk);
13646         /*
13647          * The callout_ API has acquired mtx and will hold it around this
13648          * function call.
13649          */
13650         *stat_countp += proc_waiting;
13651         wakeup(&proc_waiting);
13652 }
13653
13654 /*
13655  * If requested, try removing inode or removal dependencies.
13656  */
13657 static void
13658 check_clear_deps(mp)
13659         struct mount *mp;
13660 {
13661
13662         /*
13663          * If we are suspended, it may be because of our using
13664          * too many inodedeps, so help clear them out.
13665          */
13666         if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13667                 clear_inodedeps(mp);
13668         /*
13669          * General requests for cleanup of backed up dependencies
13670          */
13671         ACQUIRE_GBLLOCK(&lk);
13672         if (req_clear_inodedeps) {
13673                 req_clear_inodedeps -= 1;
13674                 FREE_GBLLOCK(&lk);
13675                 clear_inodedeps(mp);
13676                 ACQUIRE_GBLLOCK(&lk);
13677                 wakeup(&proc_waiting);
13678         }
13679         if (req_clear_remove) {
13680                 req_clear_remove -= 1;
13681                 FREE_GBLLOCK(&lk);
13682                 clear_remove(mp);
13683                 ACQUIRE_GBLLOCK(&lk);
13684                 wakeup(&proc_waiting);
13685         }
13686         FREE_GBLLOCK(&lk);
13687 }
13688
13689 /*
13690  * Flush out a directory with at least one removal dependency in an effort to
13691  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13692  */
13693 static void
13694 clear_remove(mp)
13695         struct mount *mp;
13696 {
13697         struct pagedep_hashhead *pagedephd;
13698         struct pagedep *pagedep;
13699         struct ufsmount *ump;
13700         struct vnode *vp;
13701         struct bufobj *bo;
13702         int error, cnt;
13703         ino_t ino;
13704
13705         ump = VFSTOUFS(mp);
13706         LOCK_OWNED(ump);
13707
13708         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13709                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13710                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13711                         ump->pagedep_nextclean = 0;
13712                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13713                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13714                                 continue;
13715                         ino = pagedep->pd_ino;
13716                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13717                                 continue;
13718                         FREE_LOCK(ump);
13719
13720                         /*
13721                          * Let unmount clear deps
13722                          */
13723                         error = vfs_busy(mp, MBF_NOWAIT);
13724                         if (error != 0)
13725                                 goto finish_write;
13726                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13727                              FFSV_FORCEINSMQ);
13728                         vfs_unbusy(mp);
13729                         if (error != 0) {
13730                                 softdep_error("clear_remove: vget", error);
13731                                 goto finish_write;
13732                         }
13733                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13734                                 softdep_error("clear_remove: fsync", error);
13735                         bo = &vp->v_bufobj;
13736                         BO_LOCK(bo);
13737                         drain_output(vp);
13738                         BO_UNLOCK(bo);
13739                         vput(vp);
13740                 finish_write:
13741                         vn_finished_write(mp);
13742                         ACQUIRE_LOCK(ump);
13743                         return;
13744                 }
13745         }
13746 }
13747
13748 /*
13749  * Clear out a block of dirty inodes in an effort to reduce
13750  * the number of inodedep dependency structures.
13751  */
13752 static void
13753 clear_inodedeps(mp)
13754         struct mount *mp;
13755 {
13756         struct inodedep_hashhead *inodedephd;
13757         struct inodedep *inodedep;
13758         struct ufsmount *ump;
13759         struct vnode *vp;
13760         struct fs *fs;
13761         int error, cnt;
13762         ino_t firstino, lastino, ino;
13763
13764         ump = VFSTOUFS(mp);
13765         fs = ump->um_fs;
13766         LOCK_OWNED(ump);
13767         /*
13768          * Pick a random inode dependency to be cleared.
13769          * We will then gather up all the inodes in its block 
13770          * that have dependencies and flush them out.
13771          */
13772         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13773                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13774                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13775                         ump->inodedep_nextclean = 0;
13776                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13777                         break;
13778         }
13779         if (inodedep == NULL)
13780                 return;
13781         /*
13782          * Find the last inode in the block with dependencies.
13783          */
13784         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13785         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13786                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13787                         break;
13788         /*
13789          * Asynchronously push all but the last inode with dependencies.
13790          * Synchronously push the last inode with dependencies to ensure
13791          * that the inode block gets written to free up the inodedeps.
13792          */
13793         for (ino = firstino; ino <= lastino; ino++) {
13794                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13795                         continue;
13796                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13797                         continue;
13798                 FREE_LOCK(ump);
13799                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13800                 if (error != 0) {
13801                         vn_finished_write(mp);
13802                         ACQUIRE_LOCK(ump);
13803                         return;
13804                 }
13805                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13806                     FFSV_FORCEINSMQ)) != 0) {
13807                         softdep_error("clear_inodedeps: vget", error);
13808                         vfs_unbusy(mp);
13809                         vn_finished_write(mp);
13810                         ACQUIRE_LOCK(ump);
13811                         return;
13812                 }
13813                 vfs_unbusy(mp);
13814                 if (ino == lastino) {
13815                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13816                                 softdep_error("clear_inodedeps: fsync1", error);
13817                 } else {
13818                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13819                                 softdep_error("clear_inodedeps: fsync2", error);
13820                         BO_LOCK(&vp->v_bufobj);
13821                         drain_output(vp);
13822                         BO_UNLOCK(&vp->v_bufobj);
13823                 }
13824                 vput(vp);
13825                 vn_finished_write(mp);
13826                 ACQUIRE_LOCK(ump);
13827         }
13828 }
13829
13830 void
13831 softdep_buf_append(bp, wkhd)
13832         struct buf *bp;
13833         struct workhead *wkhd;
13834 {
13835         struct worklist *wk;
13836         struct ufsmount *ump;
13837
13838         if ((wk = LIST_FIRST(wkhd)) == NULL)
13839                 return;
13840         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13841             ("softdep_buf_append called on non-softdep filesystem"));
13842         ump = VFSTOUFS(wk->wk_mp);
13843         ACQUIRE_LOCK(ump);
13844         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13845                 WORKLIST_REMOVE(wk);
13846                 WORKLIST_INSERT(&bp->b_dep, wk);
13847         }
13848         FREE_LOCK(ump);
13849
13850 }
13851
13852 void
13853 softdep_inode_append(ip, cred, wkhd)
13854         struct inode *ip;
13855         struct ucred *cred;
13856         struct workhead *wkhd;
13857 {
13858         struct buf *bp;
13859         struct fs *fs;
13860         struct ufsmount *ump;
13861         int error;
13862
13863         ump = ITOUMP(ip);
13864         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13865             ("softdep_inode_append called on non-softdep filesystem"));
13866         fs = ump->um_fs;
13867         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13868             (int)fs->fs_bsize, cred, &bp);
13869         if (error) {
13870                 bqrelse(bp);
13871                 softdep_freework(wkhd);
13872                 return;
13873         }
13874         softdep_buf_append(bp, wkhd);
13875         bqrelse(bp);
13876 }
13877
13878 void
13879 softdep_freework(wkhd)
13880         struct workhead *wkhd;
13881 {
13882         struct worklist *wk;
13883         struct ufsmount *ump;
13884
13885         if ((wk = LIST_FIRST(wkhd)) == NULL)
13886                 return;
13887         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13888             ("softdep_freework called on non-softdep filesystem"));
13889         ump = VFSTOUFS(wk->wk_mp);
13890         ACQUIRE_LOCK(ump);
13891         handle_jwork(wkhd);
13892         FREE_LOCK(ump);
13893 }
13894
13895 /*
13896  * Function to determine if the buffer has outstanding dependencies
13897  * that will cause a roll-back if the buffer is written. If wantcount
13898  * is set, return number of dependencies, otherwise just yes or no.
13899  */
13900 static int
13901 softdep_count_dependencies(bp, wantcount)
13902         struct buf *bp;
13903         int wantcount;
13904 {
13905         struct worklist *wk;
13906         struct ufsmount *ump;
13907         struct bmsafemap *bmsafemap;
13908         struct freework *freework;
13909         struct inodedep *inodedep;
13910         struct indirdep *indirdep;
13911         struct freeblks *freeblks;
13912         struct allocindir *aip;
13913         struct pagedep *pagedep;
13914         struct dirrem *dirrem;
13915         struct newblk *newblk;
13916         struct mkdir *mkdir;
13917         struct diradd *dap;
13918         struct vnode *vp;
13919         struct mount *mp;
13920         int i, retval;
13921
13922         retval = 0;
13923         if (LIST_EMPTY(&bp->b_dep))
13924                 return (0);
13925         vp = bp->b_vp;
13926
13927         /*
13928          * The ump mount point is stable after we get a correct
13929          * pointer, since bp is locked and this prevents unmount from
13930          * proceed.  But to get to it, we cannot dereference bp->b_dep
13931          * head wk_mp, because we do not yet own SU ump lock and
13932          * workitem might be freed while dereferenced.
13933          */
13934 retry:
13935         if (vp->v_type == VCHR) {
13936                 VI_LOCK(vp);
13937                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13938                 VI_UNLOCK(vp);
13939                 if (mp == NULL)
13940                         goto retry;
13941         } else if (vp->v_type == VREG) {
13942                 mp = vp->v_mount;
13943         } else {
13944                 return (0);
13945         }
13946         ump = VFSTOUFS(mp);
13947
13948         ACQUIRE_LOCK(ump);
13949         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13950                 switch (wk->wk_type) {
13951
13952                 case D_INODEDEP:
13953                         inodedep = WK_INODEDEP(wk);
13954                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13955                                 /* bitmap allocation dependency */
13956                                 retval += 1;
13957                                 if (!wantcount)
13958                                         goto out;
13959                         }
13960                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13961                                 /* direct block pointer dependency */
13962                                 retval += 1;
13963                                 if (!wantcount)
13964                                         goto out;
13965                         }
13966                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13967                                 /* direct block pointer dependency */
13968                                 retval += 1;
13969                                 if (!wantcount)
13970                                         goto out;
13971                         }
13972                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13973                                 /* Add reference dependency. */
13974                                 retval += 1;
13975                                 if (!wantcount)
13976                                         goto out;
13977                         }
13978                         continue;
13979
13980                 case D_INDIRDEP:
13981                         indirdep = WK_INDIRDEP(wk);
13982
13983                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13984                                 /* indirect truncation dependency */
13985                                 retval += 1;
13986                                 if (!wantcount)
13987                                         goto out;
13988                         }
13989
13990                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13991                                 /* indirect block pointer dependency */
13992                                 retval += 1;
13993                                 if (!wantcount)
13994                                         goto out;
13995                         }
13996                         continue;
13997
13998                 case D_PAGEDEP:
13999                         pagedep = WK_PAGEDEP(wk);
14000                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14001                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14002                                         /* Journal remove ref dependency. */
14003                                         retval += 1;
14004                                         if (!wantcount)
14005                                                 goto out;
14006                                 }
14007                         }
14008                         for (i = 0; i < DAHASHSZ; i++) {
14009
14010                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14011                                         /* directory entry dependency */
14012                                         retval += 1;
14013                                         if (!wantcount)
14014                                                 goto out;
14015                                 }
14016                         }
14017                         continue;
14018
14019                 case D_BMSAFEMAP:
14020                         bmsafemap = WK_BMSAFEMAP(wk);
14021                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14022                                 /* Add reference dependency. */
14023                                 retval += 1;
14024                                 if (!wantcount)
14025                                         goto out;
14026                         }
14027                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14028                                 /* Allocate block dependency. */
14029                                 retval += 1;
14030                                 if (!wantcount)
14031                                         goto out;
14032                         }
14033                         continue;
14034
14035                 case D_FREEBLKS:
14036                         freeblks = WK_FREEBLKS(wk);
14037                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14038                                 /* Freeblk journal dependency. */
14039                                 retval += 1;
14040                                 if (!wantcount)
14041                                         goto out;
14042                         }
14043                         continue;
14044
14045                 case D_ALLOCDIRECT:
14046                 case D_ALLOCINDIR:
14047                         newblk = WK_NEWBLK(wk);
14048                         if (newblk->nb_jnewblk) {
14049                                 /* Journal allocate dependency. */
14050                                 retval += 1;
14051                                 if (!wantcount)
14052                                         goto out;
14053                         }
14054                         continue;
14055
14056                 case D_MKDIR:
14057                         mkdir = WK_MKDIR(wk);
14058                         if (mkdir->md_jaddref) {
14059                                 /* Journal reference dependency. */
14060                                 retval += 1;
14061                                 if (!wantcount)
14062                                         goto out;
14063                         }
14064                         continue;
14065
14066                 case D_FREEWORK:
14067                 case D_FREEDEP:
14068                 case D_JSEGDEP:
14069                 case D_JSEG:
14070                 case D_SBDEP:
14071                         /* never a dependency on these blocks */
14072                         continue;
14073
14074                 default:
14075                         panic("softdep_count_dependencies: Unexpected type %s",
14076                             TYPENAME(wk->wk_type));
14077                         /* NOTREACHED */
14078                 }
14079         }
14080 out:
14081         FREE_LOCK(ump);
14082         return (retval);
14083 }
14084
14085 /*
14086  * Acquire exclusive access to a buffer.
14087  * Must be called with a locked mtx parameter.
14088  * Return acquired buffer or NULL on failure.
14089  */
14090 static struct buf *
14091 getdirtybuf(bp, lock, waitfor)
14092         struct buf *bp;
14093         struct rwlock *lock;
14094         int waitfor;
14095 {
14096         int error;
14097
14098         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14099                 if (waitfor != MNT_WAIT)
14100                         return (NULL);
14101                 error = BUF_LOCK(bp,
14102                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14103                 /*
14104                  * Even if we successfully acquire bp here, we have dropped
14105                  * lock, which may violates our guarantee.
14106                  */
14107                 if (error == 0)
14108                         BUF_UNLOCK(bp);
14109                 else if (error != ENOLCK)
14110                         panic("getdirtybuf: inconsistent lock: %d", error);
14111                 rw_wlock(lock);
14112                 return (NULL);
14113         }
14114         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14115                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14116                         rw_wunlock(lock);
14117                         BO_LOCK(bp->b_bufobj);
14118                         BUF_UNLOCK(bp);
14119                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14120                                 bp->b_vflags |= BV_BKGRDWAIT;
14121                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14122                                        PRIBIO | PDROP, "getbuf", 0);
14123                         } else
14124                                 BO_UNLOCK(bp->b_bufobj);
14125                         rw_wlock(lock);
14126                         return (NULL);
14127                 }
14128                 BUF_UNLOCK(bp);
14129                 if (waitfor != MNT_WAIT)
14130                         return (NULL);
14131                 /*
14132                  * The lock argument must be bp->b_vp's mutex in
14133                  * this case.
14134                  */
14135 #ifdef  DEBUG_VFS_LOCKS
14136                 if (bp->b_vp->v_type != VCHR)
14137                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14138 #endif
14139                 bp->b_vflags |= BV_BKGRDWAIT;
14140                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14141                 return (NULL);
14142         }
14143         if ((bp->b_flags & B_DELWRI) == 0) {
14144                 BUF_UNLOCK(bp);
14145                 return (NULL);
14146         }
14147         bremfree(bp);
14148         return (bp);
14149 }
14150
14151
14152 /*
14153  * Check if it is safe to suspend the file system now.  On entry,
14154  * the vnode interlock for devvp should be held.  Return 0 with
14155  * the mount interlock held if the file system can be suspended now,
14156  * otherwise return EAGAIN with the mount interlock held.
14157  */
14158 int
14159 softdep_check_suspend(struct mount *mp,
14160                       struct vnode *devvp,
14161                       int softdep_depcnt,
14162                       int softdep_accdepcnt,
14163                       int secondary_writes,
14164                       int secondary_accwrites)
14165 {
14166         struct bufobj *bo;
14167         struct ufsmount *ump;
14168         struct inodedep *inodedep;
14169         int error, unlinked;
14170
14171         bo = &devvp->v_bufobj;
14172         ASSERT_BO_WLOCKED(bo);
14173
14174         /*
14175          * If we are not running with soft updates, then we need only
14176          * deal with secondary writes as we try to suspend.
14177          */
14178         if (MOUNTEDSOFTDEP(mp) == 0) {
14179                 MNT_ILOCK(mp);
14180                 while (mp->mnt_secondary_writes != 0) {
14181                         BO_UNLOCK(bo);
14182                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14183                             (PUSER - 1) | PDROP, "secwr", 0);
14184                         BO_LOCK(bo);
14185                         MNT_ILOCK(mp);
14186                 }
14187
14188                 /*
14189                  * Reasons for needing more work before suspend:
14190                  * - Dirty buffers on devvp.
14191                  * - Secondary writes occurred after start of vnode sync loop
14192                  */
14193                 error = 0;
14194                 if (bo->bo_numoutput > 0 ||
14195                     bo->bo_dirty.bv_cnt > 0 ||
14196                     secondary_writes != 0 ||
14197                     mp->mnt_secondary_writes != 0 ||
14198                     secondary_accwrites != mp->mnt_secondary_accwrites)
14199                         error = EAGAIN;
14200                 BO_UNLOCK(bo);
14201                 return (error);
14202         }
14203
14204         /*
14205          * If we are running with soft updates, then we need to coordinate
14206          * with them as we try to suspend.
14207          */
14208         ump = VFSTOUFS(mp);
14209         for (;;) {
14210                 if (!TRY_ACQUIRE_LOCK(ump)) {
14211                         BO_UNLOCK(bo);
14212                         ACQUIRE_LOCK(ump);
14213                         FREE_LOCK(ump);
14214                         BO_LOCK(bo);
14215                         continue;
14216                 }
14217                 MNT_ILOCK(mp);
14218                 if (mp->mnt_secondary_writes != 0) {
14219                         FREE_LOCK(ump);
14220                         BO_UNLOCK(bo);
14221                         msleep(&mp->mnt_secondary_writes,
14222                                MNT_MTX(mp),
14223                                (PUSER - 1) | PDROP, "secwr", 0);
14224                         BO_LOCK(bo);
14225                         continue;
14226                 }
14227                 break;
14228         }
14229
14230         unlinked = 0;
14231         if (MOUNTEDSUJ(mp)) {
14232                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14233                     inodedep != NULL;
14234                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14235                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14236                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14237                             UNLINKONLIST) ||
14238                             !check_inodedep_free(inodedep))
14239                                 continue;
14240                         unlinked++;
14241                 }
14242         }
14243
14244         /*
14245          * Reasons for needing more work before suspend:
14246          * - Dirty buffers on devvp.
14247          * - Softdep activity occurred after start of vnode sync loop
14248          * - Secondary writes occurred after start of vnode sync loop
14249          */
14250         error = 0;
14251         if (bo->bo_numoutput > 0 ||
14252             bo->bo_dirty.bv_cnt > 0 ||
14253             softdep_depcnt != unlinked ||
14254             ump->softdep_deps != unlinked ||
14255             softdep_accdepcnt != ump->softdep_accdeps ||
14256             secondary_writes != 0 ||
14257             mp->mnt_secondary_writes != 0 ||
14258             secondary_accwrites != mp->mnt_secondary_accwrites)
14259                 error = EAGAIN;
14260         FREE_LOCK(ump);
14261         BO_UNLOCK(bo);
14262         return (error);
14263 }
14264
14265
14266 /*
14267  * Get the number of dependency structures for the file system, both
14268  * the current number and the total number allocated.  These will
14269  * later be used to detect that softdep processing has occurred.
14270  */
14271 void
14272 softdep_get_depcounts(struct mount *mp,
14273                       int *softdep_depsp,
14274                       int *softdep_accdepsp)
14275 {
14276         struct ufsmount *ump;
14277
14278         if (MOUNTEDSOFTDEP(mp) == 0) {
14279                 *softdep_depsp = 0;
14280                 *softdep_accdepsp = 0;
14281                 return;
14282         }
14283         ump = VFSTOUFS(mp);
14284         ACQUIRE_LOCK(ump);
14285         *softdep_depsp = ump->softdep_deps;
14286         *softdep_accdepsp = ump->softdep_accdeps;
14287         FREE_LOCK(ump);
14288 }
14289
14290 /*
14291  * Wait for pending output on a vnode to complete.
14292  * Must be called with vnode lock and interlock locked.
14293  *
14294  * XXX: Should just be a call to bufobj_wwait().
14295  */
14296 static void
14297 drain_output(vp)
14298         struct vnode *vp;
14299 {
14300         struct bufobj *bo;
14301
14302         bo = &vp->v_bufobj;
14303         ASSERT_VOP_LOCKED(vp, "drain_output");
14304         ASSERT_BO_WLOCKED(bo);
14305
14306         while (bo->bo_numoutput) {
14307                 bo->bo_flag |= BO_WWAIT;
14308                 msleep((caddr_t)&bo->bo_numoutput,
14309                     BO_LOCKPTR(bo), PRIBIO + 1, "drainvp", 0);
14310         }
14311 }
14312
14313 /*
14314  * Called whenever a buffer that is being invalidated or reallocated
14315  * contains dependencies. This should only happen if an I/O error has
14316  * occurred. The routine is called with the buffer locked.
14317  */ 
14318 static void
14319 softdep_deallocate_dependencies(bp)
14320         struct buf *bp;
14321 {
14322
14323         if ((bp->b_ioflags & BIO_ERROR) == 0)
14324                 panic("softdep_deallocate_dependencies: dangling deps");
14325         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14326                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14327         else
14328                 printf("softdep_deallocate_dependencies: "
14329                     "got error %d while accessing filesystem\n", bp->b_error);
14330         if (bp->b_error != ENXIO)
14331                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14332 }
14333
14334 /*
14335  * Function to handle asynchronous write errors in the filesystem.
14336  */
14337 static void
14338 softdep_error(func, error)
14339         char *func;
14340         int error;
14341 {
14342
14343         /* XXX should do something better! */
14344         printf("%s: got error %d while accessing filesystem\n", func, error);
14345 }
14346
14347 #ifdef DDB
14348
14349 static void
14350 inodedep_print(struct inodedep *inodedep, int verbose)
14351 {
14352         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14353             " saveino %p\n",
14354             inodedep, inodedep->id_fs, inodedep->id_state,
14355             (intmax_t)inodedep->id_ino,
14356             (intmax_t)fsbtodb(inodedep->id_fs,
14357             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14358             (intmax_t)inodedep->id_nlinkdelta,
14359             (intmax_t)inodedep->id_savednlink,
14360             inodedep->id_savedino1);
14361
14362         if (verbose == 0)
14363                 return;
14364
14365         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14366             "mkdiradd %p\n",
14367             LIST_FIRST(&inodedep->id_pendinghd),
14368             LIST_FIRST(&inodedep->id_bufwait),
14369             LIST_FIRST(&inodedep->id_inowait),
14370             TAILQ_FIRST(&inodedep->id_inoreflst),
14371             inodedep->id_mkdiradd);
14372         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14373             TAILQ_FIRST(&inodedep->id_inoupdt),
14374             TAILQ_FIRST(&inodedep->id_newinoupdt),
14375             TAILQ_FIRST(&inodedep->id_extupdt),
14376             TAILQ_FIRST(&inodedep->id_newextupdt));
14377 }
14378
14379 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14380 {
14381
14382         if (have_addr == 0) {
14383                 db_printf("Address required\n");
14384                 return;
14385         }
14386         inodedep_print((struct inodedep*)addr, 1);
14387 }
14388
14389 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14390 {
14391         struct inodedep_hashhead *inodedephd;
14392         struct inodedep *inodedep;
14393         struct ufsmount *ump;
14394         int cnt;
14395
14396         if (have_addr == 0) {
14397                 db_printf("Address required\n");
14398                 return;
14399         }
14400         ump = (struct ufsmount *)addr;
14401         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14402                 inodedephd = &ump->inodedep_hashtbl[cnt];
14403                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14404                         inodedep_print(inodedep, 0);
14405                 }
14406         }
14407 }
14408
14409 DB_SHOW_COMMAND(worklist, db_show_worklist)
14410 {
14411         struct worklist *wk;
14412
14413         if (have_addr == 0) {
14414                 db_printf("Address required\n");
14415                 return;
14416         }
14417         wk = (struct worklist *)addr;
14418         printf("worklist: %p type %s state 0x%X\n",
14419             wk, TYPENAME(wk->wk_type), wk->wk_state);
14420 }
14421
14422 DB_SHOW_COMMAND(workhead, db_show_workhead)
14423 {
14424         struct workhead *wkhd;
14425         struct worklist *wk;
14426         int i;
14427
14428         if (have_addr == 0) {
14429                 db_printf("Address required\n");
14430                 return;
14431         }
14432         wkhd = (struct workhead *)addr;
14433         wk = LIST_FIRST(wkhd);
14434         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14435                 db_printf("worklist: %p type %s state 0x%X",
14436                     wk, TYPENAME(wk->wk_type), wk->wk_state);
14437         if (i == 100)
14438                 db_printf("workhead overflow");
14439         printf("\n");
14440 }
14441
14442
14443 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14444 {
14445         struct mkdirlist *mkdirlisthd;
14446         struct jaddref *jaddref;
14447         struct diradd *diradd;
14448         struct mkdir *mkdir;
14449
14450         if (have_addr == 0) {
14451                 db_printf("Address required\n");
14452                 return;
14453         }
14454         mkdirlisthd = (struct mkdirlist *)addr;
14455         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14456                 diradd = mkdir->md_diradd;
14457                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14458                     mkdir, mkdir->md_state, diradd, diradd->da_state);
14459                 if ((jaddref = mkdir->md_jaddref) != NULL)
14460                         db_printf(" jaddref %p jaddref state 0x%X",
14461                             jaddref, jaddref->ja_state);
14462                 db_printf("\n");
14463         }
14464 }
14465
14466 /* exported to ffs_vfsops.c */
14467 extern void db_print_ffs(struct ufsmount *ump);
14468 void
14469 db_print_ffs(struct ufsmount *ump)
14470 {
14471         db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14472             ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14473             ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14474             ump->softdep_deps, ump->softdep_req);
14475 }
14476
14477 #endif /* DDB */
14478
14479 #endif /* SOFTUPDATES */