]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
MFC of 350490
[FreeBSD/FreeBSD.git] / sys / ufs / ffs / ffs_softdep.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *      Marshall Kirk McKusick          http://www.mckusick.com/softdep/
16  *      1614 Oxford Street              mckusick@mckusick.com
17  *      Berkeley, CA 94709-1608         +1-510-843-9542
18  *      USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *      from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
42  */
43
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50
51 /*
52  * For now we want the safety net that the DEBUG flag provides.
53  */
54 #ifndef DEBUG
55 #define DEBUG
56 #endif
57
58 #include <sys/param.h>
59 #include <sys/kernel.h>
60 #include <sys/systm.h>
61 #include <sys/bio.h>
62 #include <sys/buf.h>
63 #include <sys/kdb.h>
64 #include <sys/kthread.h>
65 #include <sys/ktr.h>
66 #include <sys/limits.h>
67 #include <sys/lock.h>
68 #include <sys/malloc.h>
69 #include <sys/mount.h>
70 #include <sys/mutex.h>
71 #include <sys/namei.h>
72 #include <sys/priv.h>
73 #include <sys/proc.h>
74 #include <sys/racct.h>
75 #include <sys/rwlock.h>
76 #include <sys/stat.h>
77 #include <sys/sysctl.h>
78 #include <sys/syslog.h>
79 #include <sys/vnode.h>
80 #include <sys/conf.h>
81
82 #include <ufs/ufs/dir.h>
83 #include <ufs/ufs/extattr.h>
84 #include <ufs/ufs/quota.h>
85 #include <ufs/ufs/inode.h>
86 #include <ufs/ufs/ufsmount.h>
87 #include <ufs/ffs/fs.h>
88 #include <ufs/ffs/softdep.h>
89 #include <ufs/ffs/ffs_extern.h>
90 #include <ufs/ufs/ufs_extern.h>
91
92 #include <vm/vm.h>
93 #include <vm/vm_extern.h>
94 #include <vm/vm_object.h>
95
96 #include <geom/geom.h>
97
98 #include <ddb/ddb.h>
99
100 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
101
102 #ifndef SOFTUPDATES
103
104 int
105 softdep_flushfiles(oldmnt, flags, td)
106         struct mount *oldmnt;
107         int flags;
108         struct thread *td;
109 {
110
111         panic("softdep_flushfiles called");
112 }
113
114 int
115 softdep_mount(devvp, mp, fs, cred)
116         struct vnode *devvp;
117         struct mount *mp;
118         struct fs *fs;
119         struct ucred *cred;
120 {
121
122         return (0);
123 }
124
125 void
126 softdep_initialize()
127 {
128
129         return;
130 }
131
132 void
133 softdep_uninitialize()
134 {
135
136         return;
137 }
138
139 void
140 softdep_unmount(mp)
141         struct mount *mp;
142 {
143
144         panic("softdep_unmount called");
145 }
146
147 void
148 softdep_setup_sbupdate(ump, fs, bp)
149         struct ufsmount *ump;
150         struct fs *fs;
151         struct buf *bp;
152 {
153
154         panic("softdep_setup_sbupdate called");
155 }
156
157 void
158 softdep_setup_inomapdep(bp, ip, newinum, mode)
159         struct buf *bp;
160         struct inode *ip;
161         ino_t newinum;
162         int mode;
163 {
164
165         panic("softdep_setup_inomapdep called");
166 }
167
168 void
169 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
170         struct buf *bp;
171         struct mount *mp;
172         ufs2_daddr_t newblkno;
173         int frags;
174         int oldfrags;
175 {
176
177         panic("softdep_setup_blkmapdep called");
178 }
179
180 void
181 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
182         struct inode *ip;
183         ufs_lbn_t lbn;
184         ufs2_daddr_t newblkno;
185         ufs2_daddr_t oldblkno;
186         long newsize;
187         long oldsize;
188         struct buf *bp;
189 {
190         
191         panic("softdep_setup_allocdirect called");
192 }
193
194 void
195 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
196         struct inode *ip;
197         ufs_lbn_t lbn;
198         ufs2_daddr_t newblkno;
199         ufs2_daddr_t oldblkno;
200         long newsize;
201         long oldsize;
202         struct buf *bp;
203 {
204         
205         panic("softdep_setup_allocext called");
206 }
207
208 void
209 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
210         struct inode *ip;
211         ufs_lbn_t lbn;
212         struct buf *bp;
213         int ptrno;
214         ufs2_daddr_t newblkno;
215         ufs2_daddr_t oldblkno;
216         struct buf *nbp;
217 {
218
219         panic("softdep_setup_allocindir_page called");
220 }
221
222 void
223 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
224         struct buf *nbp;
225         struct inode *ip;
226         struct buf *bp;
227         int ptrno;
228         ufs2_daddr_t newblkno;
229 {
230
231         panic("softdep_setup_allocindir_meta called");
232 }
233
234 void
235 softdep_journal_freeblocks(ip, cred, length, flags)
236         struct inode *ip;
237         struct ucred *cred;
238         off_t length;
239         int flags;
240 {
241         
242         panic("softdep_journal_freeblocks called");
243 }
244
245 void
246 softdep_journal_fsync(ip)
247         struct inode *ip;
248 {
249
250         panic("softdep_journal_fsync called");
251 }
252
253 void
254 softdep_setup_freeblocks(ip, length, flags)
255         struct inode *ip;
256         off_t length;
257         int flags;
258 {
259         
260         panic("softdep_setup_freeblocks called");
261 }
262
263 void
264 softdep_freefile(pvp, ino, mode)
265                 struct vnode *pvp;
266                 ino_t ino;
267                 int mode;
268 {
269
270         panic("softdep_freefile called");
271 }
272
273 int
274 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
275         struct buf *bp;
276         struct inode *dp;
277         off_t diroffset;
278         ino_t newinum;
279         struct buf *newdirbp;
280         int isnewblk;
281 {
282
283         panic("softdep_setup_directory_add called");
284 }
285
286 void
287 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
288         struct buf *bp;
289         struct inode *dp;
290         caddr_t base;
291         caddr_t oldloc;
292         caddr_t newloc;
293         int entrysize;
294 {
295
296         panic("softdep_change_directoryentry_offset called");
297 }
298
299 void
300 softdep_setup_remove(bp, dp, ip, isrmdir)
301         struct buf *bp;
302         struct inode *dp;
303         struct inode *ip;
304         int isrmdir;
305 {
306         
307         panic("softdep_setup_remove called");
308 }
309
310 void
311 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
312         struct buf *bp;
313         struct inode *dp;
314         struct inode *ip;
315         ino_t newinum;
316         int isrmdir;
317 {
318
319         panic("softdep_setup_directory_change called");
320 }
321
322 void
323 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
324         struct mount *mp;
325         struct buf *bp;
326         ufs2_daddr_t blkno;
327         int frags;
328         struct workhead *wkhd;
329 {
330
331         panic("%s called", __FUNCTION__);
332 }
333
334 void
335 softdep_setup_inofree(mp, bp, ino, wkhd)
336         struct mount *mp;
337         struct buf *bp;
338         ino_t ino;
339         struct workhead *wkhd;
340 {
341
342         panic("%s called", __FUNCTION__);
343 }
344
345 void
346 softdep_setup_unlink(dp, ip)
347         struct inode *dp;
348         struct inode *ip;
349 {
350
351         panic("%s called", __FUNCTION__);
352 }
353
354 void
355 softdep_setup_link(dp, ip)
356         struct inode *dp;
357         struct inode *ip;
358 {
359
360         panic("%s called", __FUNCTION__);
361 }
362
363 void
364 softdep_revert_link(dp, ip)
365         struct inode *dp;
366         struct inode *ip;
367 {
368
369         panic("%s called", __FUNCTION__);
370 }
371
372 void
373 softdep_setup_rmdir(dp, ip)
374         struct inode *dp;
375         struct inode *ip;
376 {
377
378         panic("%s called", __FUNCTION__);
379 }
380
381 void
382 softdep_revert_rmdir(dp, ip)
383         struct inode *dp;
384         struct inode *ip;
385 {
386
387         panic("%s called", __FUNCTION__);
388 }
389
390 void
391 softdep_setup_create(dp, ip)
392         struct inode *dp;
393         struct inode *ip;
394 {
395
396         panic("%s called", __FUNCTION__);
397 }
398
399 void
400 softdep_revert_create(dp, ip)
401         struct inode *dp;
402         struct inode *ip;
403 {
404
405         panic("%s called", __FUNCTION__);
406 }
407
408 void
409 softdep_setup_mkdir(dp, ip)
410         struct inode *dp;
411         struct inode *ip;
412 {
413
414         panic("%s called", __FUNCTION__);
415 }
416
417 void
418 softdep_revert_mkdir(dp, ip)
419         struct inode *dp;
420         struct inode *ip;
421 {
422
423         panic("%s called", __FUNCTION__);
424 }
425
426 void
427 softdep_setup_dotdot_link(dp, ip)
428         struct inode *dp;
429         struct inode *ip;
430 {
431
432         panic("%s called", __FUNCTION__);
433 }
434
435 int
436 softdep_prealloc(vp, waitok)
437         struct vnode *vp;
438         int waitok;
439 {
440
441         panic("%s called", __FUNCTION__);
442 }
443
444 int
445 softdep_journal_lookup(mp, vpp)
446         struct mount *mp;
447         struct vnode **vpp;
448 {
449
450         return (ENOENT);
451 }
452
453 void
454 softdep_change_linkcnt(ip)
455         struct inode *ip;
456 {
457
458         panic("softdep_change_linkcnt called");
459 }
460
461 void 
462 softdep_load_inodeblock(ip)
463         struct inode *ip;
464 {
465
466         panic("softdep_load_inodeblock called");
467 }
468
469 void
470 softdep_update_inodeblock(ip, bp, waitfor)
471         struct inode *ip;
472         struct buf *bp;
473         int waitfor;
474 {
475
476         panic("softdep_update_inodeblock called");
477 }
478
479 int
480 softdep_fsync(vp)
481         struct vnode *vp;       /* the "in_core" copy of the inode */
482 {
483
484         return (0);
485 }
486
487 void
488 softdep_fsync_mountdev(vp)
489         struct vnode *vp;
490 {
491
492         return;
493 }
494
495 int
496 softdep_flushworklist(oldmnt, countp, td)
497         struct mount *oldmnt;
498         int *countp;
499         struct thread *td;
500 {
501
502         *countp = 0;
503         return (0);
504 }
505
506 int
507 softdep_sync_metadata(struct vnode *vp)
508 {
509
510         panic("softdep_sync_metadata called");
511 }
512
513 int
514 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
515 {
516
517         panic("softdep_sync_buf called");
518 }
519
520 int
521 softdep_slowdown(vp)
522         struct vnode *vp;
523 {
524
525         panic("softdep_slowdown called");
526 }
527
528 int
529 softdep_request_cleanup(fs, vp, cred, resource)
530         struct fs *fs;
531         struct vnode *vp;
532         struct ucred *cred;
533         int resource;
534 {
535
536         return (0);
537 }
538
539 int
540 softdep_check_suspend(struct mount *mp,
541                       struct vnode *devvp,
542                       int softdep_depcnt,
543                       int softdep_accdepcnt,
544                       int secondary_writes,
545                       int secondary_accwrites)
546 {
547         struct bufobj *bo;
548         int error;
549         
550         (void) softdep_depcnt,
551         (void) softdep_accdepcnt;
552
553         bo = &devvp->v_bufobj;
554         ASSERT_BO_WLOCKED(bo);
555
556         MNT_ILOCK(mp);
557         while (mp->mnt_secondary_writes != 0) {
558                 BO_UNLOCK(bo);
559                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
560                     (PUSER - 1) | PDROP, "secwr", 0);
561                 BO_LOCK(bo);
562                 MNT_ILOCK(mp);
563         }
564
565         /*
566          * Reasons for needing more work before suspend:
567          * - Dirty buffers on devvp.
568          * - Secondary writes occurred after start of vnode sync loop
569          */
570         error = 0;
571         if (bo->bo_numoutput > 0 ||
572             bo->bo_dirty.bv_cnt > 0 ||
573             secondary_writes != 0 ||
574             mp->mnt_secondary_writes != 0 ||
575             secondary_accwrites != mp->mnt_secondary_accwrites)
576                 error = EAGAIN;
577         BO_UNLOCK(bo);
578         return (error);
579 }
580
581 void
582 softdep_get_depcounts(struct mount *mp,
583                       int *softdepactivep,
584                       int *softdepactiveaccp)
585 {
586         (void) mp;
587         *softdepactivep = 0;
588         *softdepactiveaccp = 0;
589 }
590
591 void
592 softdep_buf_append(bp, wkhd)
593         struct buf *bp;
594         struct workhead *wkhd;
595 {
596
597         panic("softdep_buf_appendwork called");
598 }
599
600 void
601 softdep_inode_append(ip, cred, wkhd)
602         struct inode *ip;
603         struct ucred *cred;
604         struct workhead *wkhd;
605 {
606
607         panic("softdep_inode_appendwork called");
608 }
609
610 void
611 softdep_freework(wkhd)
612         struct workhead *wkhd;
613 {
614
615         panic("softdep_freework called");
616 }
617
618 #else
619
620 FEATURE(softupdates, "FFS soft-updates support");
621
622 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
623     "soft updates stats");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
625     "total dependencies allocated");
626 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
627     "high use dependencies allocated");
628 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
629     "current dependencies allocated");
630 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
631     "current dependencies written");
632
633 unsigned long dep_current[D_LAST + 1];
634 unsigned long dep_highuse[D_LAST + 1];
635 unsigned long dep_total[D_LAST + 1];
636 unsigned long dep_write[D_LAST + 1];
637
638 #define SOFTDEP_TYPE(type, str, long)                                   \
639     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
640     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
641         &dep_total[D_ ## type], 0, "");                                 \
642     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
643         &dep_current[D_ ## type], 0, "");                               \
644     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
645         &dep_highuse[D_ ## type], 0, "");                               \
646     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
647         &dep_write[D_ ## type], 0, "");
648
649 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
650 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
651 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
652     "Block or frag allocated from cyl group map");
653 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
654 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
655 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
656 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
657 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
658 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
659 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
660 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
661 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
662 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
663 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
664 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
665 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
666 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
667 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
668 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
669 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
670 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
671 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
672 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
673 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
674 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
675 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
676 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
677
678 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
679
680 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
681 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
682 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
683
684 #define M_SOFTDEP_FLAGS (M_WAITOK)
685
686 /* 
687  * translate from workitem type to memory type
688  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
689  */
690 static struct malloc_type *memtype[] = {
691         NULL,
692         M_PAGEDEP,
693         M_INODEDEP,
694         M_BMSAFEMAP,
695         M_NEWBLK,
696         M_ALLOCDIRECT,
697         M_INDIRDEP,
698         M_ALLOCINDIR,
699         M_FREEFRAG,
700         M_FREEBLKS,
701         M_FREEFILE,
702         M_DIRADD,
703         M_MKDIR,
704         M_DIRREM,
705         M_NEWDIRBLK,
706         M_FREEWORK,
707         M_FREEDEP,
708         M_JADDREF,
709         M_JREMREF,
710         M_JMVREF,
711         M_JNEWBLK,
712         M_JFREEBLK,
713         M_JFREEFRAG,
714         M_JSEG,
715         M_JSEGDEP,
716         M_SBDEP,
717         M_JTRUNC,
718         M_JFSYNC,
719         M_SENTINEL
720 };
721
722 #define DtoM(type) (memtype[type])
723
724 /*
725  * Names of malloc types.
726  */
727 #define TYPENAME(type)  \
728         ((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
729         memtype[type]->ks_shortdesc : "???")
730 /*
731  * End system adaptation definitions.
732  */
733
734 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
735 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
736
737 /*
738  * Internal function prototypes.
739  */
740 static  void check_clear_deps(struct mount *);
741 static  void softdep_error(char *, int);
742 static  int softdep_process_worklist(struct mount *, int);
743 static  int softdep_waitidle(struct mount *, int);
744 static  void drain_output(struct vnode *);
745 static  struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
746 static  int check_inodedep_free(struct inodedep *);
747 static  void clear_remove(struct mount *);
748 static  void clear_inodedeps(struct mount *);
749 static  void unlinked_inodedep(struct mount *, struct inodedep *);
750 static  void clear_unlinked_inodedep(struct inodedep *);
751 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
752 static  int flush_pagedep_deps(struct vnode *, struct mount *,
753             struct diraddhd *);
754 static  int free_pagedep(struct pagedep *);
755 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
756 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
757 static  int flush_deplist(struct allocdirectlst *, int, int *);
758 static  int sync_cgs(struct mount *, int);
759 static  int handle_written_filepage(struct pagedep *, struct buf *, int);
760 static  int handle_written_sbdep(struct sbdep *, struct buf *);
761 static  void initiate_write_sbdep(struct sbdep *);
762 static  void diradd_inode_written(struct diradd *, struct inodedep *);
763 static  int handle_written_indirdep(struct indirdep *, struct buf *,
764             struct buf**, int);
765 static  int handle_written_inodeblock(struct inodedep *, struct buf *, int);
766 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
767             uint8_t *);
768 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
769 static  void handle_written_jaddref(struct jaddref *);
770 static  void handle_written_jremref(struct jremref *);
771 static  void handle_written_jseg(struct jseg *, struct buf *);
772 static  void handle_written_jnewblk(struct jnewblk *);
773 static  void handle_written_jblkdep(struct jblkdep *);
774 static  void handle_written_jfreefrag(struct jfreefrag *);
775 static  void complete_jseg(struct jseg *);
776 static  void complete_jsegs(struct jseg *);
777 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
778 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
779 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
780 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
781 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
782 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
783 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
784 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
785 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
786 static  inline void inoref_write(struct inoref *, struct jseg *,
787             struct jrefrec *);
788 static  void handle_allocdirect_partdone(struct allocdirect *,
789             struct workhead *);
790 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
791             struct workhead *);
792 static  void indirdep_complete(struct indirdep *);
793 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
794 static  void indirblk_insert(struct freework *);
795 static  void indirblk_remove(struct freework *);
796 static  void handle_allocindir_partdone(struct allocindir *);
797 static  void initiate_write_filepage(struct pagedep *, struct buf *);
798 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
799 static  void handle_written_mkdir(struct mkdir *, int);
800 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
801             uint8_t *);
802 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
803 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
804 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
805 static  void handle_workitem_freefile(struct freefile *);
806 static  int handle_workitem_remove(struct dirrem *, int);
807 static  struct dirrem *newdirrem(struct buf *, struct inode *,
808             struct inode *, int, struct dirrem **);
809 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
810             struct buf *);
811 static  void cancel_indirdep(struct indirdep *, struct buf *,
812             struct freeblks *);
813 static  void free_indirdep(struct indirdep *);
814 static  void free_diradd(struct diradd *, struct workhead *);
815 static  void merge_diradd(struct inodedep *, struct diradd *);
816 static  void complete_diradd(struct diradd *);
817 static  struct diradd *diradd_lookup(struct pagedep *, int);
818 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
819             struct jremref *);
820 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
821             struct jremref *);
822 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
823             struct jremref *, struct jremref *);
824 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
825             struct jremref *);
826 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
827             struct freeblks *, int);
828 static  int setup_trunc_indir(struct freeblks *, struct inode *,
829             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
830 static  void complete_trunc_indir(struct freework *);
831 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
832             int);
833 static  void complete_mkdir(struct mkdir *);
834 static  void free_newdirblk(struct newdirblk *);
835 static  void free_jremref(struct jremref *);
836 static  void free_jaddref(struct jaddref *);
837 static  void free_jsegdep(struct jsegdep *);
838 static  void free_jsegs(struct jblocks *);
839 static  void rele_jseg(struct jseg *);
840 static  void free_jseg(struct jseg *, struct jblocks *);
841 static  void free_jnewblk(struct jnewblk *);
842 static  void free_jblkdep(struct jblkdep *);
843 static  void free_jfreefrag(struct jfreefrag *);
844 static  void free_freedep(struct freedep *);
845 static  void journal_jremref(struct dirrem *, struct jremref *,
846             struct inodedep *);
847 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
848 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
849             struct workhead *);
850 static  void cancel_jfreefrag(struct jfreefrag *);
851 static  inline void setup_freedirect(struct freeblks *, struct inode *,
852             int, int);
853 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
854 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
855             ufs_lbn_t, int);
856 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
857 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
858 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
859 static  ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
860 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
861 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
862             int, int);
863 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
864 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
865 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
866 static  void newblk_freefrag(struct newblk*);
867 static  void free_newblk(struct newblk *);
868 static  void cancel_allocdirect(struct allocdirectlst *,
869             struct allocdirect *, struct freeblks *);
870 static  int check_inode_unwritten(struct inodedep *);
871 static  int free_inodedep(struct inodedep *);
872 static  void freework_freeblock(struct freework *, u_long);
873 static  void freework_enqueue(struct freework *);
874 static  int handle_workitem_freeblocks(struct freeblks *, int);
875 static  int handle_complete_freeblocks(struct freeblks *, int);
876 static  void handle_workitem_indirblk(struct freework *);
877 static  void handle_written_freework(struct freework *);
878 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
879 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
880             struct workhead *);
881 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
882             struct inodedep *, struct allocindir *, ufs_lbn_t);
883 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
884             ufs2_daddr_t, ufs_lbn_t);
885 static  void handle_workitem_freefrag(struct freefrag *);
886 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
887             ufs_lbn_t, u_long);
888 static  void allocdirect_merge(struct allocdirectlst *,
889             struct allocdirect *, struct allocdirect *);
890 static  struct freefrag *allocindir_merge(struct allocindir *,
891             struct allocindir *);
892 static  int bmsafemap_find(struct bmsafemap_hashhead *, int,
893             struct bmsafemap **);
894 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
895             int cg, struct bmsafemap *);
896 static  int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
897             struct newblk **);
898 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
899 static  int inodedep_find(struct inodedep_hashhead *, ino_t,
900             struct inodedep **);
901 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
902 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
903             int, struct pagedep **);
904 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
905             struct pagedep **);
906 static  void pause_timer(void *);
907 static  int request_cleanup(struct mount *, int);
908 static  int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
909 static  void schedule_cleanup(struct mount *);
910 static void softdep_ast_cleanup_proc(struct thread *);
911 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
912 static  int process_worklist_item(struct mount *, int, int);
913 static  void process_removes(struct vnode *);
914 static  void process_truncates(struct vnode *);
915 static  void jwork_move(struct workhead *, struct workhead *);
916 static  void jwork_insert(struct workhead *, struct jsegdep *);
917 static  void add_to_worklist(struct worklist *, int);
918 static  void wake_worklist(struct worklist *);
919 static  void wait_worklist(struct worklist *, char *);
920 static  void remove_from_worklist(struct worklist *);
921 static  void softdep_flush(void *);
922 static  void softdep_flushjournal(struct mount *);
923 static  int softdep_speedup(struct ufsmount *);
924 static  void worklist_speedup(struct mount *);
925 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
926 static  void journal_unmount(struct ufsmount *);
927 static  int journal_space(struct ufsmount *, int);
928 static  void journal_suspend(struct ufsmount *);
929 static  int journal_unsuspend(struct ufsmount *ump);
930 static  void softdep_prelink(struct vnode *, struct vnode *);
931 static  void add_to_journal(struct worklist *);
932 static  void remove_from_journal(struct worklist *);
933 static  bool softdep_excess_items(struct ufsmount *, int);
934 static  void softdep_process_journal(struct mount *, struct worklist *, int);
935 static  struct jremref *newjremref(struct dirrem *, struct inode *,
936             struct inode *ip, off_t, nlink_t);
937 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
938             uint16_t);
939 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
940             uint16_t);
941 static  inline struct jsegdep *inoref_jseg(struct inoref *);
942 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
943 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
944             ufs2_daddr_t, int);
945 static  void adjust_newfreework(struct freeblks *, int);
946 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
947 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
948 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
949 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
950             ufs2_daddr_t, long, ufs_lbn_t);
951 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
952             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
953 static  int jwait(struct worklist *, int);
954 static  struct inodedep *inodedep_lookup_ip(struct inode *);
955 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
956 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
957 static  void handle_jwork(struct workhead *);
958 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
959             struct mkdir **);
960 static  struct jblocks *jblocks_create(void);
961 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
962 static  void jblocks_free(struct jblocks *, struct mount *, int);
963 static  void jblocks_destroy(struct jblocks *);
964 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
965
966 /*
967  * Exported softdep operations.
968  */
969 static  void softdep_disk_io_initiation(struct buf *);
970 static  void softdep_disk_write_complete(struct buf *);
971 static  void softdep_deallocate_dependencies(struct buf *);
972 static  int softdep_count_dependencies(struct buf *bp, int);
973
974 /*
975  * Global lock over all of soft updates.
976  */
977 static struct mtx lk;
978 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
979
980 #define ACQUIRE_GBLLOCK(lk)     mtx_lock(lk)
981 #define FREE_GBLLOCK(lk)        mtx_unlock(lk)
982 #define GBLLOCK_OWNED(lk)       mtx_assert((lk), MA_OWNED)
983
984 /*
985  * Per-filesystem soft-updates locking.
986  */
987 #define LOCK_PTR(ump)           (&(ump)->um_softdep->sd_fslock)
988 #define TRY_ACQUIRE_LOCK(ump)   rw_try_wlock(&(ump)->um_softdep->sd_fslock)
989 #define ACQUIRE_LOCK(ump)       rw_wlock(&(ump)->um_softdep->sd_fslock)
990 #define FREE_LOCK(ump)          rw_wunlock(&(ump)->um_softdep->sd_fslock)
991 #define LOCK_OWNED(ump)         rw_assert(&(ump)->um_softdep->sd_fslock, \
992                                     RA_WLOCKED)
993
994 #define BUF_AREC(bp)            lockallowrecurse(&(bp)->b_lock)
995 #define BUF_NOREC(bp)           lockdisablerecurse(&(bp)->b_lock)
996
997 /*
998  * Worklist queue management.
999  * These routines require that the lock be held.
1000  */
1001 #ifndef /* NOT */ DEBUG
1002 #define WORKLIST_INSERT(head, item) do {        \
1003         (item)->wk_state |= ONWORKLIST;         \
1004         LIST_INSERT_HEAD(head, item, wk_list);  \
1005 } while (0)
1006 #define WORKLIST_REMOVE(item) do {              \
1007         (item)->wk_state &= ~ONWORKLIST;        \
1008         LIST_REMOVE(item, wk_list);             \
1009 } while (0)
1010 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1011 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1012
1013 #else /* DEBUG */
1014 static  void worklist_insert(struct workhead *, struct worklist *, int);
1015 static  void worklist_remove(struct worklist *, int);
1016
1017 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1018 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1019 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1020 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1021
1022 static void
1023 worklist_insert(head, item, locked)
1024         struct workhead *head;
1025         struct worklist *item;
1026         int locked;
1027 {
1028
1029         if (locked)
1030                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1031         if (item->wk_state & ONWORKLIST)
1032                 panic("worklist_insert: %p %s(0x%X) already on list",
1033                     item, TYPENAME(item->wk_type), item->wk_state);
1034         item->wk_state |= ONWORKLIST;
1035         LIST_INSERT_HEAD(head, item, wk_list);
1036 }
1037
1038 static void
1039 worklist_remove(item, locked)
1040         struct worklist *item;
1041         int locked;
1042 {
1043
1044         if (locked)
1045                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1046         if ((item->wk_state & ONWORKLIST) == 0)
1047                 panic("worklist_remove: %p %s(0x%X) not on list",
1048                     item, TYPENAME(item->wk_type), item->wk_state);
1049         item->wk_state &= ~ONWORKLIST;
1050         LIST_REMOVE(item, wk_list);
1051 }
1052 #endif /* DEBUG */
1053
1054 /*
1055  * Merge two jsegdeps keeping only the oldest one as newer references
1056  * can't be discarded until after older references.
1057  */
1058 static inline struct jsegdep *
1059 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1060 {
1061         struct jsegdep *swp;
1062
1063         if (two == NULL)
1064                 return (one);
1065
1066         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1067                 swp = one;
1068                 one = two;
1069                 two = swp;
1070         }
1071         WORKLIST_REMOVE(&two->jd_list);
1072         free_jsegdep(two);
1073
1074         return (one);
1075 }
1076
1077 /*
1078  * If two freedeps are compatible free one to reduce list size.
1079  */
1080 static inline struct freedep *
1081 freedep_merge(struct freedep *one, struct freedep *two)
1082 {
1083         if (two == NULL)
1084                 return (one);
1085
1086         if (one->fd_freework == two->fd_freework) {
1087                 WORKLIST_REMOVE(&two->fd_list);
1088                 free_freedep(two);
1089         }
1090         return (one);
1091 }
1092
1093 /*
1094  * Move journal work from one list to another.  Duplicate freedeps and
1095  * jsegdeps are coalesced to keep the lists as small as possible.
1096  */
1097 static void
1098 jwork_move(dst, src)
1099         struct workhead *dst;
1100         struct workhead *src;
1101 {
1102         struct freedep *freedep;
1103         struct jsegdep *jsegdep;
1104         struct worklist *wkn;
1105         struct worklist *wk;
1106
1107         KASSERT(dst != src,
1108             ("jwork_move: dst == src"));
1109         freedep = NULL;
1110         jsegdep = NULL;
1111         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1112                 if (wk->wk_type == D_JSEGDEP)
1113                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1114                 else if (wk->wk_type == D_FREEDEP)
1115                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1116         }
1117
1118         while ((wk = LIST_FIRST(src)) != NULL) {
1119                 WORKLIST_REMOVE(wk);
1120                 WORKLIST_INSERT(dst, wk);
1121                 if (wk->wk_type == D_JSEGDEP) {
1122                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1123                         continue;
1124                 }
1125                 if (wk->wk_type == D_FREEDEP)
1126                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1127         }
1128 }
1129
1130 static void
1131 jwork_insert(dst, jsegdep)
1132         struct workhead *dst;
1133         struct jsegdep *jsegdep;
1134 {
1135         struct jsegdep *jsegdepn;
1136         struct worklist *wk;
1137
1138         LIST_FOREACH(wk, dst, wk_list)
1139                 if (wk->wk_type == D_JSEGDEP)
1140                         break;
1141         if (wk == NULL) {
1142                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1143                 return;
1144         }
1145         jsegdepn = WK_JSEGDEP(wk);
1146         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1147                 WORKLIST_REMOVE(wk);
1148                 free_jsegdep(jsegdepn);
1149                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1150         } else
1151                 free_jsegdep(jsegdep);
1152 }
1153
1154 /*
1155  * Routines for tracking and managing workitems.
1156  */
1157 static  void workitem_free(struct worklist *, int);
1158 static  void workitem_alloc(struct worklist *, int, struct mount *);
1159 static  void workitem_reassign(struct worklist *, int);
1160
1161 #define WORKITEM_FREE(item, type) \
1162         workitem_free((struct worklist *)(item), (type))
1163 #define WORKITEM_REASSIGN(item, type) \
1164         workitem_reassign((struct worklist *)(item), (type))
1165
1166 static void
1167 workitem_free(item, type)
1168         struct worklist *item;
1169         int type;
1170 {
1171         struct ufsmount *ump;
1172
1173 #ifdef DEBUG
1174         if (item->wk_state & ONWORKLIST)
1175                 panic("workitem_free: %s(0x%X) still on list",
1176                     TYPENAME(item->wk_type), item->wk_state);
1177         if (item->wk_type != type && type != D_NEWBLK)
1178                 panic("workitem_free: type mismatch %s != %s",
1179                     TYPENAME(item->wk_type), TYPENAME(type));
1180 #endif
1181         if (item->wk_state & IOWAITING)
1182                 wakeup(item);
1183         ump = VFSTOUFS(item->wk_mp);
1184         LOCK_OWNED(ump);
1185         KASSERT(ump->softdep_deps > 0,
1186             ("workitem_free: %s: softdep_deps going negative",
1187             ump->um_fs->fs_fsmnt));
1188         if (--ump->softdep_deps == 0 && ump->softdep_req)
1189                 wakeup(&ump->softdep_deps);
1190         KASSERT(dep_current[item->wk_type] > 0,
1191             ("workitem_free: %s: dep_current[%s] going negative",
1192             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1193         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1194             ("workitem_free: %s: softdep_curdeps[%s] going negative",
1195             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1196         atomic_subtract_long(&dep_current[item->wk_type], 1);
1197         ump->softdep_curdeps[item->wk_type] -= 1;
1198         free(item, DtoM(type));
1199 }
1200
1201 static void
1202 workitem_alloc(item, type, mp)
1203         struct worklist *item;
1204         int type;
1205         struct mount *mp;
1206 {
1207         struct ufsmount *ump;
1208
1209         item->wk_type = type;
1210         item->wk_mp = mp;
1211         item->wk_state = 0;
1212
1213         ump = VFSTOUFS(mp);
1214         ACQUIRE_GBLLOCK(&lk);
1215         dep_current[type]++;
1216         if (dep_current[type] > dep_highuse[type])
1217                 dep_highuse[type] = dep_current[type];
1218         dep_total[type]++;
1219         FREE_GBLLOCK(&lk);
1220         ACQUIRE_LOCK(ump);
1221         ump->softdep_curdeps[type] += 1;
1222         ump->softdep_deps++;
1223         ump->softdep_accdeps++;
1224         FREE_LOCK(ump);
1225 }
1226
1227 static void
1228 workitem_reassign(item, newtype)
1229         struct worklist *item;
1230         int newtype;
1231 {
1232         struct ufsmount *ump;
1233
1234         ump = VFSTOUFS(item->wk_mp);
1235         LOCK_OWNED(ump);
1236         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1237             ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1238             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1239         ump->softdep_curdeps[item->wk_type] -= 1;
1240         ump->softdep_curdeps[newtype] += 1;
1241         KASSERT(dep_current[item->wk_type] > 0,
1242             ("workitem_reassign: %s: dep_current[%s] going negative",
1243             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1244         ACQUIRE_GBLLOCK(&lk);
1245         dep_current[newtype]++;
1246         dep_current[item->wk_type]--;
1247         if (dep_current[newtype] > dep_highuse[newtype])
1248                 dep_highuse[newtype] = dep_current[newtype];
1249         dep_total[newtype]++;
1250         FREE_GBLLOCK(&lk);
1251         item->wk_type = newtype;
1252 }
1253
1254 /*
1255  * Workitem queue management
1256  */
1257 static int max_softdeps;        /* maximum number of structs before slowdown */
1258 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1259 static int proc_waiting;        /* tracks whether we have a timeout posted */
1260 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1261 static struct callout softdep_callout;
1262 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1263 static int req_clear_remove;    /* syncer process flush some freeblks */
1264 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1265
1266 /*
1267  * runtime statistics
1268  */
1269 static int stat_flush_threads;  /* number of softdep flushing threads */
1270 static int stat_worklist_push;  /* number of worklist cleanups */
1271 static int stat_blk_limit_push; /* number of times block limit neared */
1272 static int stat_ino_limit_push; /* number of times inode limit neared */
1273 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1274 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1275 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1276 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1277 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1278 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1279 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1280 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1281 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1282 static int stat_journal_min;    /* Times hit journal min threshold */
1283 static int stat_journal_low;    /* Times hit journal low threshold */
1284 static int stat_journal_wait;   /* Times blocked in jwait(). */
1285 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1286 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1287 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1288 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1289 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1290 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1291 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1292 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1293 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1294 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1295
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1297     &max_softdeps, 0, "");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1299     &tickdelay, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1301     &stat_flush_threads, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1303     &stat_worklist_push, 0,"");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1305     &stat_blk_limit_push, 0,"");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1307     &stat_ino_limit_push, 0,"");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1309     &stat_blk_limit_hit, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1311     &stat_ino_limit_hit, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1313     &stat_sync_limit_hit, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1315     &stat_indir_blk_ptrs, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1317     &stat_inode_bitmap, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1319     &stat_direct_blk_ptrs, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1321     &stat_dir_entry, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1323     &stat_jaddref, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1325     &stat_jnewblk, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1327     &stat_journal_low, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1329     &stat_journal_min, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1331     &stat_journal_wait, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1333     &stat_jwait_filepage, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1335     &stat_jwait_freeblks, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1337     &stat_jwait_inode, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1339     &stat_jwait_newblk, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1341     &stat_cleanup_blkrequests, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1343     &stat_cleanup_inorequests, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1345     &stat_cleanup_high_delay, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1347     &stat_cleanup_retries, 0, "");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1349     &stat_cleanup_failures, 0, "");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1351     &softdep_flushcache, 0, "");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1353     &stat_emptyjblocks, 0, "");
1354
1355 SYSCTL_DECL(_vfs_ffs);
1356
1357 /* Whether to recompute the summary at mount time */
1358 static int compute_summary_at_mount = 0;
1359 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1360            &compute_summary_at_mount, 0, "Recompute summary at mount");
1361 static int print_threads = 0;
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1363     &print_threads, 0, "Notify flusher thread start/stop");
1364
1365 /* List of all filesystems mounted with soft updates */
1366 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1367
1368 /*
1369  * This function cleans the worklist for a filesystem.
1370  * Each filesystem running with soft dependencies gets its own
1371  * thread to run in this function. The thread is started up in
1372  * softdep_mount and shutdown in softdep_unmount. They show up
1373  * as part of the kernel "bufdaemon" process whose process
1374  * entry is available in bufdaemonproc.
1375  */
1376 static int searchfailed;
1377 extern struct proc *bufdaemonproc;
1378 static void
1379 softdep_flush(addr)
1380         void *addr;
1381 {
1382         struct mount *mp;
1383         struct thread *td;
1384         struct ufsmount *ump;
1385
1386         td = curthread;
1387         td->td_pflags |= TDP_NORUNNINGBUF;
1388         mp = (struct mount *)addr;
1389         ump = VFSTOUFS(mp);
1390         atomic_add_int(&stat_flush_threads, 1);
1391         ACQUIRE_LOCK(ump);
1392         ump->softdep_flags &= ~FLUSH_STARTING;
1393         wakeup(&ump->softdep_flushtd);
1394         FREE_LOCK(ump);
1395         if (print_threads) {
1396                 if (stat_flush_threads == 1)
1397                         printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1398                             bufdaemonproc->p_pid);
1399                 printf("Start thread %s\n", td->td_name);
1400         }
1401         for (;;) {      
1402                 while (softdep_process_worklist(mp, 0) > 0 ||
1403                     (MOUNTEDSUJ(mp) &&
1404                     VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1405                         kthread_suspend_check();
1406                 ACQUIRE_LOCK(ump);
1407                 if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1408                         msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1409                             "sdflush", hz / 2);
1410                 ump->softdep_flags &= ~FLUSH_CLEANUP;
1411                 /*
1412                  * Check to see if we are done and need to exit.
1413                  */
1414                 if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1415                         FREE_LOCK(ump);
1416                         continue;
1417                 }
1418                 ump->softdep_flags &= ~FLUSH_EXIT;
1419                 FREE_LOCK(ump);
1420                 wakeup(&ump->softdep_flags);
1421                 if (print_threads)
1422                         printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1423                 atomic_subtract_int(&stat_flush_threads, 1);
1424                 kthread_exit();
1425                 panic("kthread_exit failed\n");
1426         }
1427 }
1428
1429 static void
1430 worklist_speedup(mp)
1431         struct mount *mp;
1432 {
1433         struct ufsmount *ump;
1434
1435         ump = VFSTOUFS(mp);
1436         LOCK_OWNED(ump);
1437         if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1438                 ump->softdep_flags |= FLUSH_CLEANUP;
1439         wakeup(&ump->softdep_flushtd);
1440 }
1441
1442 static int
1443 softdep_speedup(ump)
1444         struct ufsmount *ump;
1445 {
1446         struct ufsmount *altump;
1447         struct mount_softdeps *sdp;
1448
1449         LOCK_OWNED(ump);
1450         worklist_speedup(ump->um_mountp);
1451         bd_speedup();
1452         /*
1453          * If we have global shortages, then we need other
1454          * filesystems to help with the cleanup. Here we wakeup a
1455          * flusher thread for a filesystem that is over its fair
1456          * share of resources.
1457          */
1458         if (req_clear_inodedeps || req_clear_remove) {
1459                 ACQUIRE_GBLLOCK(&lk);
1460                 TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1461                         if ((altump = sdp->sd_ump) == ump)
1462                                 continue;
1463                         if (((req_clear_inodedeps &&
1464                             altump->softdep_curdeps[D_INODEDEP] >
1465                             max_softdeps / stat_flush_threads) ||
1466                             (req_clear_remove &&
1467                             altump->softdep_curdeps[D_DIRREM] >
1468                             (max_softdeps / 2) / stat_flush_threads)) &&
1469                             TRY_ACQUIRE_LOCK(altump))
1470                                 break;
1471                 }
1472                 if (sdp == NULL) {
1473                         searchfailed++;
1474                         FREE_GBLLOCK(&lk);
1475                 } else {
1476                         /*
1477                          * Move to the end of the list so we pick a
1478                          * different one on out next try.
1479                          */
1480                         TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1481                         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1482                         FREE_GBLLOCK(&lk);
1483                         if ((altump->softdep_flags &
1484                             (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1485                                 altump->softdep_flags |= FLUSH_CLEANUP;
1486                         altump->um_softdep->sd_cleanups++;
1487                         wakeup(&altump->softdep_flushtd);
1488                         FREE_LOCK(altump);
1489                 }
1490         }
1491         return (speedup_syncer());
1492 }
1493
1494 /*
1495  * Add an item to the end of the work queue.
1496  * This routine requires that the lock be held.
1497  * This is the only routine that adds items to the list.
1498  * The following routine is the only one that removes items
1499  * and does so in order from first to last.
1500  */
1501
1502 #define WK_HEAD         0x0001  /* Add to HEAD. */
1503 #define WK_NODELAY      0x0002  /* Process immediately. */
1504
1505 static void
1506 add_to_worklist(wk, flags)
1507         struct worklist *wk;
1508         int flags;
1509 {
1510         struct ufsmount *ump;
1511
1512         ump = VFSTOUFS(wk->wk_mp);
1513         LOCK_OWNED(ump);
1514         if (wk->wk_state & ONWORKLIST)
1515                 panic("add_to_worklist: %s(0x%X) already on list",
1516                     TYPENAME(wk->wk_type), wk->wk_state);
1517         wk->wk_state |= ONWORKLIST;
1518         if (ump->softdep_on_worklist == 0) {
1519                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1520                 ump->softdep_worklist_tail = wk;
1521         } else if (flags & WK_HEAD) {
1522                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1523         } else {
1524                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1525                 ump->softdep_worklist_tail = wk;
1526         }
1527         ump->softdep_on_worklist += 1;
1528         if (flags & WK_NODELAY)
1529                 worklist_speedup(wk->wk_mp);
1530 }
1531
1532 /*
1533  * Remove the item to be processed. If we are removing the last
1534  * item on the list, we need to recalculate the tail pointer.
1535  */
1536 static void
1537 remove_from_worklist(wk)
1538         struct worklist *wk;
1539 {
1540         struct ufsmount *ump;
1541
1542         ump = VFSTOUFS(wk->wk_mp);
1543         if (ump->softdep_worklist_tail == wk)
1544                 ump->softdep_worklist_tail =
1545                     (struct worklist *)wk->wk_list.le_prev;
1546         WORKLIST_REMOVE(wk);
1547         ump->softdep_on_worklist -= 1;
1548 }
1549
1550 static void
1551 wake_worklist(wk)
1552         struct worklist *wk;
1553 {
1554         if (wk->wk_state & IOWAITING) {
1555                 wk->wk_state &= ~IOWAITING;
1556                 wakeup(wk);
1557         }
1558 }
1559
1560 static void
1561 wait_worklist(wk, wmesg)
1562         struct worklist *wk;
1563         char *wmesg;
1564 {
1565         struct ufsmount *ump;
1566
1567         ump = VFSTOUFS(wk->wk_mp);
1568         wk->wk_state |= IOWAITING;
1569         msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1570 }
1571
1572 /*
1573  * Process that runs once per second to handle items in the background queue.
1574  *
1575  * Note that we ensure that everything is done in the order in which they
1576  * appear in the queue. The code below depends on this property to ensure
1577  * that blocks of a file are freed before the inode itself is freed. This
1578  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1579  * until all the old ones have been purged from the dependency lists.
1580  */
1581 static int 
1582 softdep_process_worklist(mp, full)
1583         struct mount *mp;
1584         int full;
1585 {
1586         int cnt, matchcnt;
1587         struct ufsmount *ump;
1588         long starttime;
1589
1590         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1591         if (MOUNTEDSOFTDEP(mp) == 0)
1592                 return (0);
1593         matchcnt = 0;
1594         ump = VFSTOUFS(mp);
1595         ACQUIRE_LOCK(ump);
1596         starttime = time_second;
1597         softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1598         check_clear_deps(mp);
1599         while (ump->softdep_on_worklist > 0) {
1600                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1601                         break;
1602                 else
1603                         matchcnt += cnt;
1604                 check_clear_deps(mp);
1605                 /*
1606                  * We do not generally want to stop for buffer space, but if
1607                  * we are really being a buffer hog, we will stop and wait.
1608                  */
1609                 if (should_yield()) {
1610                         FREE_LOCK(ump);
1611                         kern_yield(PRI_USER);
1612                         bwillwrite();
1613                         ACQUIRE_LOCK(ump);
1614                 }
1615                 /*
1616                  * Never allow processing to run for more than one
1617                  * second. This gives the syncer thread the opportunity
1618                  * to pause if appropriate.
1619                  */
1620                 if (!full && starttime != time_second)
1621                         break;
1622         }
1623         if (full == 0)
1624                 journal_unsuspend(ump);
1625         FREE_LOCK(ump);
1626         return (matchcnt);
1627 }
1628
1629 /*
1630  * Process all removes associated with a vnode if we are running out of
1631  * journal space.  Any other process which attempts to flush these will
1632  * be unable as we have the vnodes locked.
1633  */
1634 static void
1635 process_removes(vp)
1636         struct vnode *vp;
1637 {
1638         struct inodedep *inodedep;
1639         struct dirrem *dirrem;
1640         struct ufsmount *ump;
1641         struct mount *mp;
1642         ino_t inum;
1643
1644         mp = vp->v_mount;
1645         ump = VFSTOUFS(mp);
1646         LOCK_OWNED(ump);
1647         inum = VTOI(vp)->i_number;
1648         for (;;) {
1649 top:
1650                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1651                         return;
1652                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1653                         /*
1654                          * If another thread is trying to lock this vnode
1655                          * it will fail but we must wait for it to do so
1656                          * before we can proceed.
1657                          */
1658                         if (dirrem->dm_state & INPROGRESS) {
1659                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1660                                 goto top;
1661                         }
1662                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1663                             (COMPLETE | ONWORKLIST))
1664                                 break;
1665                 }
1666                 if (dirrem == NULL)
1667                         return;
1668                 remove_from_worklist(&dirrem->dm_list);
1669                 FREE_LOCK(ump);
1670                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1671                         panic("process_removes: suspended filesystem");
1672                 handle_workitem_remove(dirrem, 0);
1673                 vn_finished_secondary_write(mp);
1674                 ACQUIRE_LOCK(ump);
1675         }
1676 }
1677
1678 /*
1679  * Process all truncations associated with a vnode if we are running out
1680  * of journal space.  This is called when the vnode lock is already held
1681  * and no other process can clear the truncation.  This function returns
1682  * a value greater than zero if it did any work.
1683  */
1684 static void
1685 process_truncates(vp)
1686         struct vnode *vp;
1687 {
1688         struct inodedep *inodedep;
1689         struct freeblks *freeblks;
1690         struct ufsmount *ump;
1691         struct mount *mp;
1692         ino_t inum;
1693         int cgwait;
1694
1695         mp = vp->v_mount;
1696         ump = VFSTOUFS(mp);
1697         LOCK_OWNED(ump);
1698         inum = VTOI(vp)->i_number;
1699         for (;;) {
1700                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1701                         return;
1702                 cgwait = 0;
1703                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1704                         /* Journal entries not yet written.  */
1705                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1706                                 jwait(&LIST_FIRST(
1707                                     &freeblks->fb_jblkdephd)->jb_list,
1708                                     MNT_WAIT);
1709                                 break;
1710                         }
1711                         /* Another thread is executing this item. */
1712                         if (freeblks->fb_state & INPROGRESS) {
1713                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1714                                 break;
1715                         }
1716                         /* Freeblks is waiting on a inode write. */
1717                         if ((freeblks->fb_state & COMPLETE) == 0) {
1718                                 FREE_LOCK(ump);
1719                                 ffs_update(vp, 1);
1720                                 ACQUIRE_LOCK(ump);
1721                                 break;
1722                         }
1723                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1724                             (ALLCOMPLETE | ONWORKLIST)) {
1725                                 remove_from_worklist(&freeblks->fb_list);
1726                                 freeblks->fb_state |= INPROGRESS;
1727                                 FREE_LOCK(ump);
1728                                 if (vn_start_secondary_write(NULL, &mp,
1729                                     V_NOWAIT))
1730                                         panic("process_truncates: "
1731                                             "suspended filesystem");
1732                                 handle_workitem_freeblocks(freeblks, 0);
1733                                 vn_finished_secondary_write(mp);
1734                                 ACQUIRE_LOCK(ump);
1735                                 break;
1736                         }
1737                         if (freeblks->fb_cgwait)
1738                                 cgwait++;
1739                 }
1740                 if (cgwait) {
1741                         FREE_LOCK(ump);
1742                         sync_cgs(mp, MNT_WAIT);
1743                         ffs_sync_snap(mp, MNT_WAIT);
1744                         ACQUIRE_LOCK(ump);
1745                         continue;
1746                 }
1747                 if (freeblks == NULL)
1748                         break;
1749         }
1750         return;
1751 }
1752
1753 /*
1754  * Process one item on the worklist.
1755  */
1756 static int
1757 process_worklist_item(mp, target, flags)
1758         struct mount *mp;
1759         int target;
1760         int flags;
1761 {
1762         struct worklist sentinel;
1763         struct worklist *wk;
1764         struct ufsmount *ump;
1765         int matchcnt;
1766         int error;
1767
1768         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1769         /*
1770          * If we are being called because of a process doing a
1771          * copy-on-write, then it is not safe to write as we may
1772          * recurse into the copy-on-write routine.
1773          */
1774         if (curthread->td_pflags & TDP_COWINPROGRESS)
1775                 return (-1);
1776         PHOLD(curproc); /* Don't let the stack go away. */
1777         ump = VFSTOUFS(mp);
1778         LOCK_OWNED(ump);
1779         matchcnt = 0;
1780         sentinel.wk_mp = NULL;
1781         sentinel.wk_type = D_SENTINEL;
1782         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1783         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1784             wk = LIST_NEXT(&sentinel, wk_list)) {
1785                 if (wk->wk_type == D_SENTINEL) {
1786                         LIST_REMOVE(&sentinel, wk_list);
1787                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1788                         continue;
1789                 }
1790                 if (wk->wk_state & INPROGRESS)
1791                         panic("process_worklist_item: %p already in progress.",
1792                             wk);
1793                 wk->wk_state |= INPROGRESS;
1794                 remove_from_worklist(wk);
1795                 FREE_LOCK(ump);
1796                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1797                         panic("process_worklist_item: suspended filesystem");
1798                 switch (wk->wk_type) {
1799                 case D_DIRREM:
1800                         /* removal of a directory entry */
1801                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1802                         break;
1803
1804                 case D_FREEBLKS:
1805                         /* releasing blocks and/or fragments from a file */
1806                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1807                             flags);
1808                         break;
1809
1810                 case D_FREEFRAG:
1811                         /* releasing a fragment when replaced as a file grows */
1812                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1813                         error = 0;
1814                         break;
1815
1816                 case D_FREEFILE:
1817                         /* releasing an inode when its link count drops to 0 */
1818                         handle_workitem_freefile(WK_FREEFILE(wk));
1819                         error = 0;
1820                         break;
1821
1822                 default:
1823                         panic("%s_process_worklist: Unknown type %s",
1824                             "softdep", TYPENAME(wk->wk_type));
1825                         /* NOTREACHED */
1826                 }
1827                 vn_finished_secondary_write(mp);
1828                 ACQUIRE_LOCK(ump);
1829                 if (error == 0) {
1830                         if (++matchcnt == target)
1831                                 break;
1832                         continue;
1833                 }
1834                 /*
1835                  * We have to retry the worklist item later.  Wake up any
1836                  * waiters who may be able to complete it immediately and
1837                  * add the item back to the head so we don't try to execute
1838                  * it again.
1839                  */
1840                 wk->wk_state &= ~INPROGRESS;
1841                 wake_worklist(wk);
1842                 add_to_worklist(wk, WK_HEAD);
1843         }
1844         /* Sentinal could've become the tail from remove_from_worklist. */
1845         if (ump->softdep_worklist_tail == &sentinel)
1846                 ump->softdep_worklist_tail =
1847                     (struct worklist *)sentinel.wk_list.le_prev;
1848         LIST_REMOVE(&sentinel, wk_list);
1849         PRELE(curproc);
1850         return (matchcnt);
1851 }
1852
1853 /*
1854  * Move dependencies from one buffer to another.
1855  */
1856 int
1857 softdep_move_dependencies(oldbp, newbp)
1858         struct buf *oldbp;
1859         struct buf *newbp;
1860 {
1861         struct worklist *wk, *wktail;
1862         struct ufsmount *ump;
1863         int dirty;
1864
1865         if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1866                 return (0);
1867         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1868             ("softdep_move_dependencies called on non-softdep filesystem"));
1869         dirty = 0;
1870         wktail = NULL;
1871         ump = VFSTOUFS(wk->wk_mp);
1872         ACQUIRE_LOCK(ump);
1873         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1874                 LIST_REMOVE(wk, wk_list);
1875                 if (wk->wk_type == D_BMSAFEMAP &&
1876                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1877                         dirty = 1;
1878                 if (wktail == NULL)
1879                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1880                 else
1881                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1882                 wktail = wk;
1883         }
1884         FREE_LOCK(ump);
1885
1886         return (dirty);
1887 }
1888
1889 /*
1890  * Purge the work list of all items associated with a particular mount point.
1891  */
1892 int
1893 softdep_flushworklist(oldmnt, countp, td)
1894         struct mount *oldmnt;
1895         int *countp;
1896         struct thread *td;
1897 {
1898         struct vnode *devvp;
1899         struct ufsmount *ump;
1900         int count, error;
1901
1902         /*
1903          * Alternately flush the block device associated with the mount
1904          * point and process any dependencies that the flushing
1905          * creates. We continue until no more worklist dependencies
1906          * are found.
1907          */
1908         *countp = 0;
1909         error = 0;
1910         ump = VFSTOUFS(oldmnt);
1911         devvp = ump->um_devvp;
1912         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1913                 *countp += count;
1914                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1915                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1916                 VOP_UNLOCK(devvp, 0);
1917                 if (error != 0)
1918                         break;
1919         }
1920         return (error);
1921 }
1922
1923 #define SU_WAITIDLE_RETRIES     20
1924 static int
1925 softdep_waitidle(struct mount *mp, int flags __unused)
1926 {
1927         struct ufsmount *ump;
1928         struct vnode *devvp;
1929         struct thread *td;
1930         int error, i;
1931
1932         ump = VFSTOUFS(mp);
1933         devvp = ump->um_devvp;
1934         td = curthread;
1935         error = 0;
1936         ACQUIRE_LOCK(ump);
1937         for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1938                 ump->softdep_req = 1;
1939                 KASSERT((flags & FORCECLOSE) == 0 ||
1940                     ump->softdep_on_worklist == 0,
1941                     ("softdep_waitidle: work added after flush"));
1942                 msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1943                     "softdeps", 10 * hz);
1944                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1945                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1946                 VOP_UNLOCK(devvp, 0);
1947                 ACQUIRE_LOCK(ump);
1948                 if (error != 0)
1949                         break;
1950         }
1951         ump->softdep_req = 0;
1952         if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1953                 error = EBUSY;
1954                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1955                     mp);
1956         }
1957         FREE_LOCK(ump);
1958         return (error);
1959 }
1960
1961 /*
1962  * Flush all vnodes and worklist items associated with a specified mount point.
1963  */
1964 int
1965 softdep_flushfiles(oldmnt, flags, td)
1966         struct mount *oldmnt;
1967         int flags;
1968         struct thread *td;
1969 {
1970 #ifdef QUOTA
1971         struct ufsmount *ump;
1972         int i;
1973 #endif
1974         int error, early, depcount, loopcnt, retry_flush_count, retry;
1975         int morework;
1976
1977         KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1978             ("softdep_flushfiles called on non-softdep filesystem"));
1979         loopcnt = 10;
1980         retry_flush_count = 3;
1981 retry_flush:
1982         error = 0;
1983
1984         /*
1985          * Alternately flush the vnodes associated with the mount
1986          * point and process any dependencies that the flushing
1987          * creates. In theory, this loop can happen at most twice,
1988          * but we give it a few extra just to be sure.
1989          */
1990         for (; loopcnt > 0; loopcnt--) {
1991                 /*
1992                  * Do another flush in case any vnodes were brought in
1993                  * as part of the cleanup operations.
1994                  */
1995                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1996                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1997                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1998                         break;
1999                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2000                     depcount == 0)
2001                         break;
2002         }
2003         /*
2004          * If we are unmounting then it is an error to fail. If we
2005          * are simply trying to downgrade to read-only, then filesystem
2006          * activity can keep us busy forever, so we just fail with EBUSY.
2007          */
2008         if (loopcnt == 0) {
2009                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2010                         panic("softdep_flushfiles: looping");
2011                 error = EBUSY;
2012         }
2013         if (!error)
2014                 error = softdep_waitidle(oldmnt, flags);
2015         if (!error) {
2016                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2017                         retry = 0;
2018                         MNT_ILOCK(oldmnt);
2019                         KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2020                             ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2021                         morework = oldmnt->mnt_nvnodelistsize > 0;
2022 #ifdef QUOTA
2023                         ump = VFSTOUFS(oldmnt);
2024                         UFS_LOCK(ump);
2025                         for (i = 0; i < MAXQUOTAS; i++) {
2026                                 if (ump->um_quotas[i] != NULLVP)
2027                                         morework = 1;
2028                         }
2029                         UFS_UNLOCK(ump);
2030 #endif
2031                         if (morework) {
2032                                 if (--retry_flush_count > 0) {
2033                                         retry = 1;
2034                                         loopcnt = 3;
2035                                 } else
2036                                         error = EBUSY;
2037                         }
2038                         MNT_IUNLOCK(oldmnt);
2039                         if (retry)
2040                                 goto retry_flush;
2041                 }
2042         }
2043         return (error);
2044 }
2045
2046 /*
2047  * Structure hashing.
2048  * 
2049  * There are four types of structures that can be looked up:
2050  *      1) pagedep structures identified by mount point, inode number,
2051  *         and logical block.
2052  *      2) inodedep structures identified by mount point and inode number.
2053  *      3) newblk structures identified by mount point and
2054  *         physical block number.
2055  *      4) bmsafemap structures identified by mount point and
2056  *         cylinder group number.
2057  *
2058  * The "pagedep" and "inodedep" dependency structures are hashed
2059  * separately from the file blocks and inodes to which they correspond.
2060  * This separation helps when the in-memory copy of an inode or
2061  * file block must be replaced. It also obviates the need to access
2062  * an inode or file page when simply updating (or de-allocating)
2063  * dependency structures. Lookup of newblk structures is needed to
2064  * find newly allocated blocks when trying to associate them with
2065  * their allocdirect or allocindir structure.
2066  *
2067  * The lookup routines optionally create and hash a new instance when
2068  * an existing entry is not found. The bmsafemap lookup routine always
2069  * allocates a new structure if an existing one is not found.
2070  */
2071 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2072
2073 /*
2074  * Structures and routines associated with pagedep caching.
2075  */
2076 #define PAGEDEP_HASH(ump, inum, lbn) \
2077         (&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2078
2079 static int
2080 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2081         struct pagedep_hashhead *pagedephd;
2082         ino_t ino;
2083         ufs_lbn_t lbn;
2084         struct pagedep **pagedeppp;
2085 {
2086         struct pagedep *pagedep;
2087
2088         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2089                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2090                         *pagedeppp = pagedep;
2091                         return (1);
2092                 }
2093         }
2094         *pagedeppp = NULL;
2095         return (0);
2096 }
2097 /*
2098  * Look up a pagedep. Return 1 if found, 0 otherwise.
2099  * If not found, allocate if DEPALLOC flag is passed.
2100  * Found or allocated entry is returned in pagedeppp.
2101  */
2102 static int
2103 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2104         struct mount *mp;
2105         struct buf *bp;
2106         ino_t ino;
2107         ufs_lbn_t lbn;
2108         int flags;
2109         struct pagedep **pagedeppp;
2110 {
2111         struct pagedep *pagedep;
2112         struct pagedep_hashhead *pagedephd;
2113         struct worklist *wk;
2114         struct ufsmount *ump;
2115         int ret;
2116         int i;
2117
2118         ump = VFSTOUFS(mp);
2119         LOCK_OWNED(ump);
2120         if (bp) {
2121                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2122                         if (wk->wk_type == D_PAGEDEP) {
2123                                 *pagedeppp = WK_PAGEDEP(wk);
2124                                 return (1);
2125                         }
2126                 }
2127         }
2128         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2129         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2130         if (ret) {
2131                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2132                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2133                 return (1);
2134         }
2135         if ((flags & DEPALLOC) == 0)
2136                 return (0);
2137         FREE_LOCK(ump);
2138         pagedep = malloc(sizeof(struct pagedep),
2139             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2140         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2141         ACQUIRE_LOCK(ump);
2142         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2143         if (*pagedeppp) {
2144                 /*
2145                  * This should never happen since we only create pagedeps
2146                  * with the vnode lock held.  Could be an assert.
2147                  */
2148                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2149                 return (ret);
2150         }
2151         pagedep->pd_ino = ino;
2152         pagedep->pd_lbn = lbn;
2153         LIST_INIT(&pagedep->pd_dirremhd);
2154         LIST_INIT(&pagedep->pd_pendinghd);
2155         for (i = 0; i < DAHASHSZ; i++)
2156                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2157         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2158         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2159         *pagedeppp = pagedep;
2160         return (0);
2161 }
2162
2163 /*
2164  * Structures and routines associated with inodedep caching.
2165  */
2166 #define INODEDEP_HASH(ump, inum) \
2167       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2168
2169 static int
2170 inodedep_find(inodedephd, inum, inodedeppp)
2171         struct inodedep_hashhead *inodedephd;
2172         ino_t inum;
2173         struct inodedep **inodedeppp;
2174 {
2175         struct inodedep *inodedep;
2176
2177         LIST_FOREACH(inodedep, inodedephd, id_hash)
2178                 if (inum == inodedep->id_ino)
2179                         break;
2180         if (inodedep) {
2181                 *inodedeppp = inodedep;
2182                 return (1);
2183         }
2184         *inodedeppp = NULL;
2185
2186         return (0);
2187 }
2188 /*
2189  * Look up an inodedep. Return 1 if found, 0 if not found.
2190  * If not found, allocate if DEPALLOC flag is passed.
2191  * Found or allocated entry is returned in inodedeppp.
2192  */
2193 static int
2194 inodedep_lookup(mp, inum, flags, inodedeppp)
2195         struct mount *mp;
2196         ino_t inum;
2197         int flags;
2198         struct inodedep **inodedeppp;
2199 {
2200         struct inodedep *inodedep;
2201         struct inodedep_hashhead *inodedephd;
2202         struct ufsmount *ump;
2203         struct fs *fs;
2204
2205         ump = VFSTOUFS(mp);
2206         LOCK_OWNED(ump);
2207         fs = ump->um_fs;
2208         inodedephd = INODEDEP_HASH(ump, inum);
2209
2210         if (inodedep_find(inodedephd, inum, inodedeppp))
2211                 return (1);
2212         if ((flags & DEPALLOC) == 0)
2213                 return (0);
2214         /*
2215          * If the system is over its limit and our filesystem is
2216          * responsible for more than our share of that usage and
2217          * we are not in a rush, request some inodedep cleanup.
2218          */
2219         if (softdep_excess_items(ump, D_INODEDEP))
2220                 schedule_cleanup(mp);
2221         else
2222                 FREE_LOCK(ump);
2223         inodedep = malloc(sizeof(struct inodedep),
2224                 M_INODEDEP, M_SOFTDEP_FLAGS);
2225         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2226         ACQUIRE_LOCK(ump);
2227         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2228                 WORKITEM_FREE(inodedep, D_INODEDEP);
2229                 return (1);
2230         }
2231         inodedep->id_fs = fs;
2232         inodedep->id_ino = inum;
2233         inodedep->id_state = ALLCOMPLETE;
2234         inodedep->id_nlinkdelta = 0;
2235         inodedep->id_savedino1 = NULL;
2236         inodedep->id_savedsize = -1;
2237         inodedep->id_savedextsize = -1;
2238         inodedep->id_savednlink = -1;
2239         inodedep->id_bmsafemap = NULL;
2240         inodedep->id_mkdiradd = NULL;
2241         LIST_INIT(&inodedep->id_dirremhd);
2242         LIST_INIT(&inodedep->id_pendinghd);
2243         LIST_INIT(&inodedep->id_inowait);
2244         LIST_INIT(&inodedep->id_bufwait);
2245         TAILQ_INIT(&inodedep->id_inoreflst);
2246         TAILQ_INIT(&inodedep->id_inoupdt);
2247         TAILQ_INIT(&inodedep->id_newinoupdt);
2248         TAILQ_INIT(&inodedep->id_extupdt);
2249         TAILQ_INIT(&inodedep->id_newextupdt);
2250         TAILQ_INIT(&inodedep->id_freeblklst);
2251         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2252         *inodedeppp = inodedep;
2253         return (0);
2254 }
2255
2256 /*
2257  * Structures and routines associated with newblk caching.
2258  */
2259 #define NEWBLK_HASH(ump, inum) \
2260         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2261
2262 static int
2263 newblk_find(newblkhd, newblkno, flags, newblkpp)
2264         struct newblk_hashhead *newblkhd;
2265         ufs2_daddr_t newblkno;
2266         int flags;
2267         struct newblk **newblkpp;
2268 {
2269         struct newblk *newblk;
2270
2271         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2272                 if (newblkno != newblk->nb_newblkno)
2273                         continue;
2274                 /*
2275                  * If we're creating a new dependency don't match those that
2276                  * have already been converted to allocdirects.  This is for
2277                  * a frag extend.
2278                  */
2279                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2280                         continue;
2281                 break;
2282         }
2283         if (newblk) {
2284                 *newblkpp = newblk;
2285                 return (1);
2286         }
2287         *newblkpp = NULL;
2288         return (0);
2289 }
2290
2291 /*
2292  * Look up a newblk. Return 1 if found, 0 if not found.
2293  * If not found, allocate if DEPALLOC flag is passed.
2294  * Found or allocated entry is returned in newblkpp.
2295  */
2296 static int
2297 newblk_lookup(mp, newblkno, flags, newblkpp)
2298         struct mount *mp;
2299         ufs2_daddr_t newblkno;
2300         int flags;
2301         struct newblk **newblkpp;
2302 {
2303         struct newblk *newblk;
2304         struct newblk_hashhead *newblkhd;
2305         struct ufsmount *ump;
2306
2307         ump = VFSTOUFS(mp);
2308         LOCK_OWNED(ump);
2309         newblkhd = NEWBLK_HASH(ump, newblkno);
2310         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2311                 return (1);
2312         if ((flags & DEPALLOC) == 0)
2313                 return (0);
2314         if (softdep_excess_items(ump, D_NEWBLK) ||
2315             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2316             softdep_excess_items(ump, D_ALLOCINDIR))
2317                 schedule_cleanup(mp);
2318         else
2319                 FREE_LOCK(ump);
2320         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2321             M_SOFTDEP_FLAGS | M_ZERO);
2322         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2323         ACQUIRE_LOCK(ump);
2324         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2325                 WORKITEM_FREE(newblk, D_NEWBLK);
2326                 return (1);
2327         }
2328         newblk->nb_freefrag = NULL;
2329         LIST_INIT(&newblk->nb_indirdeps);
2330         LIST_INIT(&newblk->nb_newdirblk);
2331         LIST_INIT(&newblk->nb_jwork);
2332         newblk->nb_state = ATTACHED;
2333         newblk->nb_newblkno = newblkno;
2334         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2335         *newblkpp = newblk;
2336         return (0);
2337 }
2338
2339 /*
2340  * Structures and routines associated with freed indirect block caching.
2341  */
2342 #define INDIR_HASH(ump, blkno) \
2343         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2344
2345 /*
2346  * Lookup an indirect block in the indir hash table.  The freework is
2347  * removed and potentially freed.  The caller must do a blocking journal
2348  * write before writing to the blkno.
2349  */
2350 static int
2351 indirblk_lookup(mp, blkno)
2352         struct mount *mp;
2353         ufs2_daddr_t blkno;
2354 {
2355         struct freework *freework;
2356         struct indir_hashhead *wkhd;
2357         struct ufsmount *ump;
2358
2359         ump = VFSTOUFS(mp);
2360         wkhd = INDIR_HASH(ump, blkno);
2361         TAILQ_FOREACH(freework, wkhd, fw_next) {
2362                 if (freework->fw_blkno != blkno)
2363                         continue;
2364                 indirblk_remove(freework);
2365                 return (1);
2366         }
2367         return (0);
2368 }
2369
2370 /*
2371  * Insert an indirect block represented by freework into the indirblk
2372  * hash table so that it may prevent the block from being re-used prior
2373  * to the journal being written.
2374  */
2375 static void
2376 indirblk_insert(freework)
2377         struct freework *freework;
2378 {
2379         struct jblocks *jblocks;
2380         struct jseg *jseg;
2381         struct ufsmount *ump;
2382
2383         ump = VFSTOUFS(freework->fw_list.wk_mp);
2384         jblocks = ump->softdep_jblocks;
2385         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2386         if (jseg == NULL)
2387                 return;
2388         
2389         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2390         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2391             fw_next);
2392         freework->fw_state &= ~DEPCOMPLETE;
2393 }
2394
2395 static void
2396 indirblk_remove(freework)
2397         struct freework *freework;
2398 {
2399         struct ufsmount *ump;
2400
2401         ump = VFSTOUFS(freework->fw_list.wk_mp);
2402         LIST_REMOVE(freework, fw_segs);
2403         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2404         freework->fw_state |= DEPCOMPLETE;
2405         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2406                 WORKITEM_FREE(freework, D_FREEWORK);
2407 }
2408
2409 /*
2410  * Executed during filesystem system initialization before
2411  * mounting any filesystems.
2412  */
2413 void 
2414 softdep_initialize()
2415 {
2416
2417         TAILQ_INIT(&softdepmounts);
2418 #ifdef __LP64__
2419         max_softdeps = desiredvnodes * 4;
2420 #else
2421         max_softdeps = desiredvnodes * 2;
2422 #endif
2423
2424         /* initialise bioops hack */
2425         bioops.io_start = softdep_disk_io_initiation;
2426         bioops.io_complete = softdep_disk_write_complete;
2427         bioops.io_deallocate = softdep_deallocate_dependencies;
2428         bioops.io_countdeps = softdep_count_dependencies;
2429         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2430
2431         /* Initialize the callout with an mtx. */
2432         callout_init_mtx(&softdep_callout, &lk, 0);
2433 }
2434
2435 /*
2436  * Executed after all filesystems have been unmounted during
2437  * filesystem module unload.
2438  */
2439 void
2440 softdep_uninitialize()
2441 {
2442
2443         /* clear bioops hack */
2444         bioops.io_start = NULL;
2445         bioops.io_complete = NULL;
2446         bioops.io_deallocate = NULL;
2447         bioops.io_countdeps = NULL;
2448         softdep_ast_cleanup = NULL;
2449
2450         callout_drain(&softdep_callout);
2451 }
2452
2453 /*
2454  * Called at mount time to notify the dependency code that a
2455  * filesystem wishes to use it.
2456  */
2457 int
2458 softdep_mount(devvp, mp, fs, cred)
2459         struct vnode *devvp;
2460         struct mount *mp;
2461         struct fs *fs;
2462         struct ucred *cred;
2463 {
2464         struct csum_total cstotal;
2465         struct mount_softdeps *sdp;
2466         struct ufsmount *ump;
2467         struct cg *cgp;
2468         struct buf *bp;
2469         u_int cyl, i;
2470         int error;
2471
2472         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2473             M_WAITOK | M_ZERO);
2474         MNT_ILOCK(mp);
2475         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2476         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2477                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2478                         MNTK_SOFTDEP | MNTK_NOASYNC;
2479         }
2480         ump = VFSTOUFS(mp);
2481         ump->um_softdep = sdp;
2482         MNT_IUNLOCK(mp);
2483         rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2484         sdp->sd_ump = ump;
2485         LIST_INIT(&ump->softdep_workitem_pending);
2486         LIST_INIT(&ump->softdep_journal_pending);
2487         TAILQ_INIT(&ump->softdep_unlinked);
2488         LIST_INIT(&ump->softdep_dirtycg);
2489         ump->softdep_worklist_tail = NULL;
2490         ump->softdep_on_worklist = 0;
2491         ump->softdep_deps = 0;
2492         LIST_INIT(&ump->softdep_mkdirlisthd);
2493         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2494             &ump->pagedep_hash_size);
2495         ump->pagedep_nextclean = 0;
2496         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2497             &ump->inodedep_hash_size);
2498         ump->inodedep_nextclean = 0;
2499         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2500             &ump->newblk_hash_size);
2501         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2502             &ump->bmsafemap_hash_size);
2503         i = 1 << (ffs(desiredvnodes / 10) - 1);
2504         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2505             M_FREEWORK, M_WAITOK);
2506         ump->indir_hash_size = i - 1;
2507         for (i = 0; i <= ump->indir_hash_size; i++)
2508                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2509         ACQUIRE_GBLLOCK(&lk);
2510         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2511         FREE_GBLLOCK(&lk);
2512         if ((fs->fs_flags & FS_SUJ) &&
2513             (error = journal_mount(mp, fs, cred)) != 0) {
2514                 printf("Failed to start journal: %d\n", error);
2515                 softdep_unmount(mp);
2516                 return (error);
2517         }
2518         /*
2519          * Start our flushing thread in the bufdaemon process.
2520          */
2521         ACQUIRE_LOCK(ump);
2522         ump->softdep_flags |= FLUSH_STARTING;
2523         FREE_LOCK(ump);
2524         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2525             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2526             mp->mnt_stat.f_mntonname);
2527         ACQUIRE_LOCK(ump);
2528         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2529                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2530                     hz / 2);
2531         }
2532         FREE_LOCK(ump);
2533         /*
2534          * When doing soft updates, the counters in the
2535          * superblock may have gotten out of sync. Recomputation
2536          * can take a long time and can be deferred for background
2537          * fsck.  However, the old behavior of scanning the cylinder
2538          * groups and recalculating them at mount time is available
2539          * by setting vfs.ffs.compute_summary_at_mount to one.
2540          */
2541         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2542                 return (0);
2543         bzero(&cstotal, sizeof cstotal);
2544         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2545                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2546                     fs->fs_cgsize, cred, &bp)) != 0) {
2547                         brelse(bp);
2548                         softdep_unmount(mp);
2549                         return (error);
2550                 }
2551                 cgp = (struct cg *)bp->b_data;
2552                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2553                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2554                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2555                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2556                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2557                 brelse(bp);
2558         }
2559 #ifdef DEBUG
2560         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2561                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2562 #endif
2563         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2564         return (0);
2565 }
2566
2567 void
2568 softdep_unmount(mp)
2569         struct mount *mp;
2570 {
2571         struct ufsmount *ump;
2572 #ifdef INVARIANTS
2573         int i;
2574 #endif
2575
2576         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2577             ("softdep_unmount called on non-softdep filesystem"));
2578         ump = VFSTOUFS(mp);
2579         MNT_ILOCK(mp);
2580         mp->mnt_flag &= ~MNT_SOFTDEP;
2581         if (MOUNTEDSUJ(mp) == 0) {
2582                 MNT_IUNLOCK(mp);
2583         } else {
2584                 mp->mnt_flag &= ~MNT_SUJ;
2585                 MNT_IUNLOCK(mp);
2586                 journal_unmount(ump);
2587         }
2588         /*
2589          * Shut down our flushing thread. Check for NULL is if
2590          * softdep_mount errors out before the thread has been created.
2591          */
2592         if (ump->softdep_flushtd != NULL) {
2593                 ACQUIRE_LOCK(ump);
2594                 ump->softdep_flags |= FLUSH_EXIT;
2595                 wakeup(&ump->softdep_flushtd);
2596                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2597                     "sdwait", 0);
2598                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2599                     ("Thread shutdown failed"));
2600         }
2601         /*
2602          * Free up our resources.
2603          */
2604         ACQUIRE_GBLLOCK(&lk);
2605         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2606         FREE_GBLLOCK(&lk);
2607         rw_destroy(LOCK_PTR(ump));
2608         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2609         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2610         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2611         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2612             ump->bmsafemap_hash_size);
2613         free(ump->indir_hashtbl, M_FREEWORK);
2614 #ifdef INVARIANTS
2615         for (i = 0; i <= D_LAST; i++)
2616                 KASSERT(ump->softdep_curdeps[i] == 0,
2617                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2618                     TYPENAME(i), ump->softdep_curdeps[i]));
2619 #endif
2620         free(ump->um_softdep, M_MOUNTDATA);
2621 }
2622
2623 static struct jblocks *
2624 jblocks_create(void)
2625 {
2626         struct jblocks *jblocks;
2627
2628         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2629         TAILQ_INIT(&jblocks->jb_segs);
2630         jblocks->jb_avail = 10;
2631         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2632             M_JBLOCKS, M_WAITOK | M_ZERO);
2633
2634         return (jblocks);
2635 }
2636
2637 static ufs2_daddr_t
2638 jblocks_alloc(jblocks, bytes, actual)
2639         struct jblocks *jblocks;
2640         int bytes;
2641         int *actual;
2642 {
2643         ufs2_daddr_t daddr;
2644         struct jextent *jext;
2645         int freecnt;
2646         int blocks;
2647
2648         blocks = bytes / DEV_BSIZE;
2649         jext = &jblocks->jb_extent[jblocks->jb_head];
2650         freecnt = jext->je_blocks - jblocks->jb_off;
2651         if (freecnt == 0) {
2652                 jblocks->jb_off = 0;
2653                 if (++jblocks->jb_head > jblocks->jb_used)
2654                         jblocks->jb_head = 0;
2655                 jext = &jblocks->jb_extent[jblocks->jb_head];
2656                 freecnt = jext->je_blocks;
2657         }
2658         if (freecnt > blocks)
2659                 freecnt = blocks;
2660         *actual = freecnt * DEV_BSIZE;
2661         daddr = jext->je_daddr + jblocks->jb_off;
2662         jblocks->jb_off += freecnt;
2663         jblocks->jb_free -= freecnt;
2664
2665         return (daddr);
2666 }
2667
2668 static void
2669 jblocks_free(jblocks, mp, bytes)
2670         struct jblocks *jblocks;
2671         struct mount *mp;
2672         int bytes;
2673 {
2674
2675         LOCK_OWNED(VFSTOUFS(mp));
2676         jblocks->jb_free += bytes / DEV_BSIZE;
2677         if (jblocks->jb_suspended)
2678                 worklist_speedup(mp);
2679         wakeup(jblocks);
2680 }
2681
2682 static void
2683 jblocks_destroy(jblocks)
2684         struct jblocks *jblocks;
2685 {
2686
2687         if (jblocks->jb_extent)
2688                 free(jblocks->jb_extent, M_JBLOCKS);
2689         free(jblocks, M_JBLOCKS);
2690 }
2691
2692 static void
2693 jblocks_add(jblocks, daddr, blocks)
2694         struct jblocks *jblocks;
2695         ufs2_daddr_t daddr;
2696         int blocks;
2697 {
2698         struct jextent *jext;
2699
2700         jblocks->jb_blocks += blocks;
2701         jblocks->jb_free += blocks;
2702         jext = &jblocks->jb_extent[jblocks->jb_used];
2703         /* Adding the first block. */
2704         if (jext->je_daddr == 0) {
2705                 jext->je_daddr = daddr;
2706                 jext->je_blocks = blocks;
2707                 return;
2708         }
2709         /* Extending the last extent. */
2710         if (jext->je_daddr + jext->je_blocks == daddr) {
2711                 jext->je_blocks += blocks;
2712                 return;
2713         }
2714         /* Adding a new extent. */
2715         if (++jblocks->jb_used == jblocks->jb_avail) {
2716                 jblocks->jb_avail *= 2;
2717                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2718                     M_JBLOCKS, M_WAITOK | M_ZERO);
2719                 memcpy(jext, jblocks->jb_extent,
2720                     sizeof(struct jextent) * jblocks->jb_used);
2721                 free(jblocks->jb_extent, M_JBLOCKS);
2722                 jblocks->jb_extent = jext;
2723         }
2724         jext = &jblocks->jb_extent[jblocks->jb_used];
2725         jext->je_daddr = daddr;
2726         jext->je_blocks = blocks;
2727         return;
2728 }
2729
2730 int
2731 softdep_journal_lookup(mp, vpp)
2732         struct mount *mp;
2733         struct vnode **vpp;
2734 {
2735         struct componentname cnp;
2736         struct vnode *dvp;
2737         ino_t sujournal;
2738         int error;
2739
2740         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2741         if (error)
2742                 return (error);
2743         bzero(&cnp, sizeof(cnp));
2744         cnp.cn_nameiop = LOOKUP;
2745         cnp.cn_flags = ISLASTCN;
2746         cnp.cn_thread = curthread;
2747         cnp.cn_cred = curthread->td_ucred;
2748         cnp.cn_pnbuf = SUJ_FILE;
2749         cnp.cn_nameptr = SUJ_FILE;
2750         cnp.cn_namelen = strlen(SUJ_FILE);
2751         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2752         vput(dvp);
2753         if (error != 0)
2754                 return (error);
2755         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2756         return (error);
2757 }
2758
2759 /*
2760  * Open and verify the journal file.
2761  */
2762 static int
2763 journal_mount(mp, fs, cred)
2764         struct mount *mp;
2765         struct fs *fs;
2766         struct ucred *cred;
2767 {
2768         struct jblocks *jblocks;
2769         struct ufsmount *ump;
2770         struct vnode *vp;
2771         struct inode *ip;
2772         ufs2_daddr_t blkno;
2773         int bcount;
2774         int error;
2775         int i;
2776
2777         ump = VFSTOUFS(mp);
2778         ump->softdep_journal_tail = NULL;
2779         ump->softdep_on_journal = 0;
2780         ump->softdep_accdeps = 0;
2781         ump->softdep_req = 0;
2782         ump->softdep_jblocks = NULL;
2783         error = softdep_journal_lookup(mp, &vp);
2784         if (error != 0) {
2785                 printf("Failed to find journal.  Use tunefs to create one\n");
2786                 return (error);
2787         }
2788         ip = VTOI(vp);
2789         if (ip->i_size < SUJ_MIN) {
2790                 error = ENOSPC;
2791                 goto out;
2792         }
2793         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2794         jblocks = jblocks_create();
2795         for (i = 0; i < bcount; i++) {
2796                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2797                 if (error)
2798                         break;
2799                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2800         }
2801         if (error) {
2802                 jblocks_destroy(jblocks);
2803                 goto out;
2804         }
2805         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2806         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2807         ump->softdep_jblocks = jblocks;
2808 out:
2809         if (error == 0) {
2810                 MNT_ILOCK(mp);
2811                 mp->mnt_flag |= MNT_SUJ;
2812                 mp->mnt_flag &= ~MNT_SOFTDEP;
2813                 MNT_IUNLOCK(mp);
2814                 /*
2815                  * Only validate the journal contents if the
2816                  * filesystem is clean, otherwise we write the logs
2817                  * but they'll never be used.  If the filesystem was
2818                  * still dirty when we mounted it the journal is
2819                  * invalid and a new journal can only be valid if it
2820                  * starts from a clean mount.
2821                  */
2822                 if (fs->fs_clean) {
2823                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2824                         ip->i_flags |= IN_MODIFIED;
2825                         ffs_update(vp, 1);
2826                 }
2827         }
2828         vput(vp);
2829         return (error);
2830 }
2831
2832 static void
2833 journal_unmount(ump)
2834         struct ufsmount *ump;
2835 {
2836
2837         if (ump->softdep_jblocks)
2838                 jblocks_destroy(ump->softdep_jblocks);
2839         ump->softdep_jblocks = NULL;
2840 }
2841
2842 /*
2843  * Called when a journal record is ready to be written.  Space is allocated
2844  * and the journal entry is created when the journal is flushed to stable
2845  * store.
2846  */
2847 static void
2848 add_to_journal(wk)
2849         struct worklist *wk;
2850 {
2851         struct ufsmount *ump;
2852
2853         ump = VFSTOUFS(wk->wk_mp);
2854         LOCK_OWNED(ump);
2855         if (wk->wk_state & ONWORKLIST)
2856                 panic("add_to_journal: %s(0x%X) already on list",
2857                     TYPENAME(wk->wk_type), wk->wk_state);
2858         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2859         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2860                 ump->softdep_jblocks->jb_age = ticks;
2861                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2862         } else
2863                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2864         ump->softdep_journal_tail = wk;
2865         ump->softdep_on_journal += 1;
2866 }
2867
2868 /*
2869  * Remove an arbitrary item for the journal worklist maintain the tail
2870  * pointer.  This happens when a new operation obviates the need to
2871  * journal an old operation.
2872  */
2873 static void
2874 remove_from_journal(wk)
2875         struct worklist *wk;
2876 {
2877         struct ufsmount *ump;
2878
2879         ump = VFSTOUFS(wk->wk_mp);
2880         LOCK_OWNED(ump);
2881 #ifdef SUJ_DEBUG
2882         {
2883                 struct worklist *wkn;
2884
2885                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2886                         if (wkn == wk)
2887                                 break;
2888                 if (wkn == NULL)
2889                         panic("remove_from_journal: %p is not in journal", wk);
2890         }
2891 #endif
2892         /*
2893          * We emulate a TAILQ to save space in most structures which do not
2894          * require TAILQ semantics.  Here we must update the tail position
2895          * when removing the tail which is not the final entry. This works
2896          * only if the worklist linkage are at the beginning of the structure.
2897          */
2898         if (ump->softdep_journal_tail == wk)
2899                 ump->softdep_journal_tail =
2900                     (struct worklist *)wk->wk_list.le_prev;
2901         WORKLIST_REMOVE(wk);
2902         ump->softdep_on_journal -= 1;
2903 }
2904
2905 /*
2906  * Check for journal space as well as dependency limits so the prelink
2907  * code can throttle both journaled and non-journaled filesystems.
2908  * Threshold is 0 for low and 1 for min.
2909  */
2910 static int
2911 journal_space(ump, thresh)
2912         struct ufsmount *ump;
2913         int thresh;
2914 {
2915         struct jblocks *jblocks;
2916         int limit, avail;
2917
2918         jblocks = ump->softdep_jblocks;
2919         if (jblocks == NULL)
2920                 return (1);
2921         /*
2922          * We use a tighter restriction here to prevent request_cleanup()
2923          * running in threads from running into locks we currently hold.
2924          * We have to be over the limit and our filesystem has to be
2925          * responsible for more than our share of that usage.
2926          */
2927         limit = (max_softdeps / 10) * 9;
2928         if (dep_current[D_INODEDEP] > limit &&
2929             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2930                 return (0);
2931         if (thresh)
2932                 thresh = jblocks->jb_min;
2933         else
2934                 thresh = jblocks->jb_low;
2935         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2936         avail = jblocks->jb_free - avail;
2937
2938         return (avail > thresh);
2939 }
2940
2941 static void
2942 journal_suspend(ump)
2943         struct ufsmount *ump;
2944 {
2945         struct jblocks *jblocks;
2946         struct mount *mp;
2947
2948         mp = UFSTOVFS(ump);
2949         jblocks = ump->softdep_jblocks;
2950         MNT_ILOCK(mp);
2951         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2952                 stat_journal_min++;
2953                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2954                 mp->mnt_susp_owner = ump->softdep_flushtd;
2955         }
2956         jblocks->jb_suspended = 1;
2957         MNT_IUNLOCK(mp);
2958 }
2959
2960 static int
2961 journal_unsuspend(struct ufsmount *ump)
2962 {
2963         struct jblocks *jblocks;
2964         struct mount *mp;
2965
2966         mp = UFSTOVFS(ump);
2967         jblocks = ump->softdep_jblocks;
2968
2969         if (jblocks != NULL && jblocks->jb_suspended &&
2970             journal_space(ump, jblocks->jb_min)) {
2971                 jblocks->jb_suspended = 0;
2972                 FREE_LOCK(ump);
2973                 mp->mnt_susp_owner = curthread;
2974                 vfs_write_resume(mp, 0);
2975                 ACQUIRE_LOCK(ump);
2976                 return (1);
2977         }
2978         return (0);
2979 }
2980
2981 /*
2982  * Called before any allocation function to be certain that there is
2983  * sufficient space in the journal prior to creating any new records.
2984  * Since in the case of block allocation we may have multiple locked
2985  * buffers at the time of the actual allocation we can not block
2986  * when the journal records are created.  Doing so would create a deadlock
2987  * if any of these buffers needed to be flushed to reclaim space.  Instead
2988  * we require a sufficiently large amount of available space such that
2989  * each thread in the system could have passed this allocation check and
2990  * still have sufficient free space.  With 20% of a minimum journal size
2991  * of 1MB we have 6553 records available.
2992  */
2993 int
2994 softdep_prealloc(vp, waitok)
2995         struct vnode *vp;
2996         int waitok;
2997 {
2998         struct ufsmount *ump;
2999
3000         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3001             ("softdep_prealloc called on non-softdep filesystem"));
3002         /*
3003          * Nothing to do if we are not running journaled soft updates.
3004          * If we currently hold the snapshot lock, we must avoid
3005          * handling other resources that could cause deadlock.  Do not
3006          * touch quotas vnode since it is typically recursed with
3007          * other vnode locks held.
3008          */
3009         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3010             (vp->v_vflag & VV_SYSTEM) != 0)
3011                 return (0);
3012         ump = VFSTOUFS(vp->v_mount);
3013         ACQUIRE_LOCK(ump);
3014         if (journal_space(ump, 0)) {
3015                 FREE_LOCK(ump);
3016                 return (0);
3017         }
3018         stat_journal_low++;
3019         FREE_LOCK(ump);
3020         if (waitok == MNT_NOWAIT)
3021                 return (ENOSPC);
3022         /*
3023          * Attempt to sync this vnode once to flush any journal
3024          * work attached to it.
3025          */
3026         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3027                 ffs_syncvnode(vp, waitok, 0);
3028         ACQUIRE_LOCK(ump);
3029         process_removes(vp);
3030         process_truncates(vp);
3031         if (journal_space(ump, 0) == 0) {
3032                 softdep_speedup(ump);
3033                 if (journal_space(ump, 1) == 0)
3034                         journal_suspend(ump);
3035         }
3036         FREE_LOCK(ump);
3037
3038         return (0);
3039 }
3040
3041 /*
3042  * Before adjusting a link count on a vnode verify that we have sufficient
3043  * journal space.  If not, process operations that depend on the currently
3044  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3045  * and softdep flush threads can not acquire these locks to reclaim space.
3046  */
3047 static void
3048 softdep_prelink(dvp, vp)
3049         struct vnode *dvp;
3050         struct vnode *vp;
3051 {
3052         struct ufsmount *ump;
3053
3054         ump = VFSTOUFS(dvp->v_mount);
3055         LOCK_OWNED(ump);
3056         /*
3057          * Nothing to do if we have sufficient journal space.
3058          * If we currently hold the snapshot lock, we must avoid
3059          * handling other resources that could cause deadlock.
3060          */
3061         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3062                 return;
3063         stat_journal_low++;
3064         FREE_LOCK(ump);
3065         if (vp)
3066                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3067         ffs_syncvnode(dvp, MNT_WAIT, 0);
3068         ACQUIRE_LOCK(ump);
3069         /* Process vp before dvp as it may create .. removes. */
3070         if (vp) {
3071                 process_removes(vp);
3072                 process_truncates(vp);
3073         }
3074         process_removes(dvp);
3075         process_truncates(dvp);
3076         softdep_speedup(ump);
3077         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3078         if (journal_space(ump, 0) == 0) {
3079                 softdep_speedup(ump);
3080                 if (journal_space(ump, 1) == 0)
3081                         journal_suspend(ump);
3082         }
3083 }
3084
3085 static void
3086 jseg_write(ump, jseg, data)
3087         struct ufsmount *ump;
3088         struct jseg *jseg;
3089         uint8_t *data;
3090 {
3091         struct jsegrec *rec;
3092
3093         rec = (struct jsegrec *)data;
3094         rec->jsr_seq = jseg->js_seq;
3095         rec->jsr_oldest = jseg->js_oldseq;
3096         rec->jsr_cnt = jseg->js_cnt;
3097         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3098         rec->jsr_crc = 0;
3099         rec->jsr_time = ump->um_fs->fs_mtime;
3100 }
3101
3102 static inline void
3103 inoref_write(inoref, jseg, rec)
3104         struct inoref *inoref;
3105         struct jseg *jseg;
3106         struct jrefrec *rec;
3107 {
3108
3109         inoref->if_jsegdep->jd_seg = jseg;
3110         rec->jr_ino = inoref->if_ino;
3111         rec->jr_parent = inoref->if_parent;
3112         rec->jr_nlink = inoref->if_nlink;
3113         rec->jr_mode = inoref->if_mode;
3114         rec->jr_diroff = inoref->if_diroff;
3115 }
3116
3117 static void
3118 jaddref_write(jaddref, jseg, data)
3119         struct jaddref *jaddref;
3120         struct jseg *jseg;
3121         uint8_t *data;
3122 {
3123         struct jrefrec *rec;
3124
3125         rec = (struct jrefrec *)data;
3126         rec->jr_op = JOP_ADDREF;
3127         inoref_write(&jaddref->ja_ref, jseg, rec);
3128 }
3129
3130 static void
3131 jremref_write(jremref, jseg, data)
3132         struct jremref *jremref;
3133         struct jseg *jseg;
3134         uint8_t *data;
3135 {
3136         struct jrefrec *rec;
3137
3138         rec = (struct jrefrec *)data;
3139         rec->jr_op = JOP_REMREF;
3140         inoref_write(&jremref->jr_ref, jseg, rec);
3141 }
3142
3143 static void
3144 jmvref_write(jmvref, jseg, data)
3145         struct jmvref *jmvref;
3146         struct jseg *jseg;
3147         uint8_t *data;
3148 {
3149         struct jmvrec *rec;
3150
3151         rec = (struct jmvrec *)data;
3152         rec->jm_op = JOP_MVREF;
3153         rec->jm_ino = jmvref->jm_ino;
3154         rec->jm_parent = jmvref->jm_parent;
3155         rec->jm_oldoff = jmvref->jm_oldoff;
3156         rec->jm_newoff = jmvref->jm_newoff;
3157 }
3158
3159 static void
3160 jnewblk_write(jnewblk, jseg, data)
3161         struct jnewblk *jnewblk;
3162         struct jseg *jseg;
3163         uint8_t *data;
3164 {
3165         struct jblkrec *rec;
3166
3167         jnewblk->jn_jsegdep->jd_seg = jseg;
3168         rec = (struct jblkrec *)data;
3169         rec->jb_op = JOP_NEWBLK;
3170         rec->jb_ino = jnewblk->jn_ino;
3171         rec->jb_blkno = jnewblk->jn_blkno;
3172         rec->jb_lbn = jnewblk->jn_lbn;
3173         rec->jb_frags = jnewblk->jn_frags;
3174         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3175 }
3176
3177 static void
3178 jfreeblk_write(jfreeblk, jseg, data)
3179         struct jfreeblk *jfreeblk;
3180         struct jseg *jseg;
3181         uint8_t *data;
3182 {
3183         struct jblkrec *rec;
3184
3185         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3186         rec = (struct jblkrec *)data;
3187         rec->jb_op = JOP_FREEBLK;
3188         rec->jb_ino = jfreeblk->jf_ino;
3189         rec->jb_blkno = jfreeblk->jf_blkno;
3190         rec->jb_lbn = jfreeblk->jf_lbn;
3191         rec->jb_frags = jfreeblk->jf_frags;
3192         rec->jb_oldfrags = 0;
3193 }
3194
3195 static void
3196 jfreefrag_write(jfreefrag, jseg, data)
3197         struct jfreefrag *jfreefrag;
3198         struct jseg *jseg;
3199         uint8_t *data;
3200 {
3201         struct jblkrec *rec;
3202
3203         jfreefrag->fr_jsegdep->jd_seg = jseg;
3204         rec = (struct jblkrec *)data;
3205         rec->jb_op = JOP_FREEBLK;
3206         rec->jb_ino = jfreefrag->fr_ino;
3207         rec->jb_blkno = jfreefrag->fr_blkno;
3208         rec->jb_lbn = jfreefrag->fr_lbn;
3209         rec->jb_frags = jfreefrag->fr_frags;
3210         rec->jb_oldfrags = 0;
3211 }
3212
3213 static void
3214 jtrunc_write(jtrunc, jseg, data)
3215         struct jtrunc *jtrunc;
3216         struct jseg *jseg;
3217         uint8_t *data;
3218 {
3219         struct jtrncrec *rec;
3220
3221         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3222         rec = (struct jtrncrec *)data;
3223         rec->jt_op = JOP_TRUNC;
3224         rec->jt_ino = jtrunc->jt_ino;
3225         rec->jt_size = jtrunc->jt_size;
3226         rec->jt_extsize = jtrunc->jt_extsize;
3227 }
3228
3229 static void
3230 jfsync_write(jfsync, jseg, data)
3231         struct jfsync *jfsync;
3232         struct jseg *jseg;
3233         uint8_t *data;
3234 {
3235         struct jtrncrec *rec;
3236
3237         rec = (struct jtrncrec *)data;
3238         rec->jt_op = JOP_SYNC;
3239         rec->jt_ino = jfsync->jfs_ino;
3240         rec->jt_size = jfsync->jfs_size;
3241         rec->jt_extsize = jfsync->jfs_extsize;
3242 }
3243
3244 static void
3245 softdep_flushjournal(mp)
3246         struct mount *mp;
3247 {
3248         struct jblocks *jblocks;
3249         struct ufsmount *ump;
3250
3251         if (MOUNTEDSUJ(mp) == 0)
3252                 return;
3253         ump = VFSTOUFS(mp);
3254         jblocks = ump->softdep_jblocks;
3255         ACQUIRE_LOCK(ump);
3256         while (ump->softdep_on_journal) {
3257                 jblocks->jb_needseg = 1;
3258                 softdep_process_journal(mp, NULL, MNT_WAIT);
3259         }
3260         FREE_LOCK(ump);
3261 }
3262
3263 static void softdep_synchronize_completed(struct bio *);
3264 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3265
3266 static void
3267 softdep_synchronize_completed(bp)
3268         struct bio *bp;
3269 {
3270         struct jseg *oldest;
3271         struct jseg *jseg;
3272         struct ufsmount *ump;
3273
3274         /*
3275          * caller1 marks the last segment written before we issued the
3276          * synchronize cache.
3277          */
3278         jseg = bp->bio_caller1;
3279         if (jseg == NULL) {
3280                 g_destroy_bio(bp);
3281                 return;
3282         }
3283         ump = VFSTOUFS(jseg->js_list.wk_mp);
3284         ACQUIRE_LOCK(ump);
3285         oldest = NULL;
3286         /*
3287          * Mark all the journal entries waiting on the synchronize cache
3288          * as completed so they may continue on.
3289          */
3290         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3291                 jseg->js_state |= COMPLETE;
3292                 oldest = jseg;
3293                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3294         }
3295         /*
3296          * Restart deferred journal entry processing from the oldest
3297          * completed jseg.
3298          */
3299         if (oldest)
3300                 complete_jsegs(oldest);
3301
3302         FREE_LOCK(ump);
3303         g_destroy_bio(bp);
3304 }
3305
3306 /*
3307  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3308  * barriers.  The journal must be written prior to any blocks that depend
3309  * on it and the journal can not be released until the blocks have be
3310  * written.  This code handles both barriers simultaneously.
3311  */
3312 static void
3313 softdep_synchronize(bp, ump, caller1)
3314         struct bio *bp;
3315         struct ufsmount *ump;
3316         void *caller1;
3317 {
3318
3319         bp->bio_cmd = BIO_FLUSH;
3320         bp->bio_flags |= BIO_ORDERED;
3321         bp->bio_data = NULL;
3322         bp->bio_offset = ump->um_cp->provider->mediasize;
3323         bp->bio_length = 0;
3324         bp->bio_done = softdep_synchronize_completed;
3325         bp->bio_caller1 = caller1;
3326         g_io_request(bp,
3327             (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3328 }
3329
3330 /*
3331  * Flush some journal records to disk.
3332  */
3333 static void
3334 softdep_process_journal(mp, needwk, flags)
3335         struct mount *mp;
3336         struct worklist *needwk;
3337         int flags;
3338 {
3339         struct jblocks *jblocks;
3340         struct ufsmount *ump;
3341         struct worklist *wk;
3342         struct jseg *jseg;
3343         struct buf *bp;
3344         struct bio *bio;
3345         uint8_t *data;
3346         struct fs *fs;
3347         int shouldflush;
3348         int segwritten;
3349         int jrecmin;    /* Minimum records per block. */
3350         int jrecmax;    /* Maximum records per block. */
3351         int size;
3352         int cnt;
3353         int off;
3354         int devbsize;
3355
3356         if (MOUNTEDSUJ(mp) == 0)
3357                 return;
3358         shouldflush = softdep_flushcache;
3359         bio = NULL;
3360         jseg = NULL;
3361         ump = VFSTOUFS(mp);
3362         LOCK_OWNED(ump);
3363         fs = ump->um_fs;
3364         jblocks = ump->softdep_jblocks;
3365         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3366         /*
3367          * We write anywhere between a disk block and fs block.  The upper
3368          * bound is picked to prevent buffer cache fragmentation and limit
3369          * processing time per I/O.
3370          */
3371         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3372         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3373         segwritten = 0;
3374         for (;;) {
3375                 cnt = ump->softdep_on_journal;
3376                 /*
3377                  * Criteria for writing a segment:
3378                  * 1) We have a full block.
3379                  * 2) We're called from jwait() and haven't found the
3380                  *    journal item yet.
3381                  * 3) Always write if needseg is set.
3382                  * 4) If we are called from process_worklist and have
3383                  *    not yet written anything we write a partial block
3384                  *    to enforce a 1 second maximum latency on journal
3385                  *    entries.
3386                  */
3387                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3388                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3389                         break;
3390                 cnt++;
3391                 /*
3392                  * Verify some free journal space.  softdep_prealloc() should
3393                  * guarantee that we don't run out so this is indicative of
3394                  * a problem with the flow control.  Try to recover
3395                  * gracefully in any event.
3396                  */
3397                 while (jblocks->jb_free == 0) {
3398                         if (flags != MNT_WAIT)
3399                                 break;
3400                         printf("softdep: Out of journal space!\n");
3401                         softdep_speedup(ump);
3402                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3403                 }
3404                 FREE_LOCK(ump);
3405                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3406                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3407                 LIST_INIT(&jseg->js_entries);
3408                 LIST_INIT(&jseg->js_indirs);
3409                 jseg->js_state = ATTACHED;
3410                 if (shouldflush == 0)
3411                         jseg->js_state |= COMPLETE;
3412                 else if (bio == NULL)
3413                         bio = g_alloc_bio();
3414                 jseg->js_jblocks = jblocks;
3415                 bp = geteblk(fs->fs_bsize, 0);
3416                 ACQUIRE_LOCK(ump);
3417                 /*
3418                  * If there was a race while we were allocating the block
3419                  * and jseg the entry we care about was likely written.
3420                  * We bail out in both the WAIT and NOWAIT case and assume
3421                  * the caller will loop if the entry it cares about is
3422                  * not written.
3423                  */
3424                 cnt = ump->softdep_on_journal;
3425                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3426                         bp->b_flags |= B_INVAL | B_NOCACHE;
3427                         WORKITEM_FREE(jseg, D_JSEG);
3428                         FREE_LOCK(ump);
3429                         brelse(bp);
3430                         ACQUIRE_LOCK(ump);
3431                         break;
3432                 }
3433                 /*
3434                  * Calculate the disk block size required for the available
3435                  * records rounded to the min size.
3436                  */
3437                 if (cnt == 0)
3438                         size = devbsize;
3439                 else if (cnt < jrecmax)
3440                         size = howmany(cnt, jrecmin) * devbsize;
3441                 else
3442                         size = fs->fs_bsize;
3443                 /*
3444                  * Allocate a disk block for this journal data and account
3445                  * for truncation of the requested size if enough contiguous
3446                  * space was not available.
3447                  */
3448                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3449                 bp->b_lblkno = bp->b_blkno;
3450                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3451                 bp->b_bcount = size;
3452                 bp->b_flags &= ~B_INVAL;
3453                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3454                 /*
3455                  * Initialize our jseg with cnt records.  Assign the next
3456                  * sequence number to it and link it in-order.
3457                  */
3458                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3459                 jseg->js_buf = bp;
3460                 jseg->js_cnt = cnt;
3461                 jseg->js_refs = cnt + 1;        /* Self ref. */
3462                 jseg->js_size = size;
3463                 jseg->js_seq = jblocks->jb_nextseq++;
3464                 if (jblocks->jb_oldestseg == NULL)
3465                         jblocks->jb_oldestseg = jseg;
3466                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3467                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3468                 if (jblocks->jb_writeseg == NULL)
3469                         jblocks->jb_writeseg = jseg;
3470                 /*
3471                  * Start filling in records from the pending list.
3472                  */
3473                 data = bp->b_data;
3474                 off = 0;
3475
3476                 /*
3477                  * Always put a header on the first block.
3478                  * XXX As with below, there might not be a chance to get
3479                  * into the loop.  Ensure that something valid is written.
3480                  */
3481                 jseg_write(ump, jseg, data);
3482                 off += JREC_SIZE;
3483                 data = bp->b_data + off;
3484
3485                 /*
3486                  * XXX Something is wrong here.  There's no work to do,
3487                  * but we need to perform and I/O and allow it to complete
3488                  * anyways.
3489                  */
3490                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3491                         stat_emptyjblocks++;
3492
3493                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3494                     != NULL) {
3495                         if (cnt == 0)
3496                                 break;
3497                         /* Place a segment header on every device block. */
3498                         if ((off % devbsize) == 0) {
3499                                 jseg_write(ump, jseg, data);
3500                                 off += JREC_SIZE;
3501                                 data = bp->b_data + off;
3502                         }
3503                         if (wk == needwk)
3504                                 needwk = NULL;
3505                         remove_from_journal(wk);
3506                         wk->wk_state |= INPROGRESS;
3507                         WORKLIST_INSERT(&jseg->js_entries, wk);
3508                         switch (wk->wk_type) {
3509                         case D_JADDREF:
3510                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3511                                 break;
3512                         case D_JREMREF:
3513                                 jremref_write(WK_JREMREF(wk), jseg, data);
3514                                 break;
3515                         case D_JMVREF:
3516                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3517                                 break;
3518                         case D_JNEWBLK:
3519                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3520                                 break;
3521                         case D_JFREEBLK:
3522                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3523                                 break;
3524                         case D_JFREEFRAG:
3525                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3526                                 break;
3527                         case D_JTRUNC:
3528                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3529                                 break;
3530                         case D_JFSYNC:
3531                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3532                                 break;
3533                         default:
3534                                 panic("process_journal: Unknown type %s",
3535                                     TYPENAME(wk->wk_type));
3536                                 /* NOTREACHED */
3537                         }
3538                         off += JREC_SIZE;
3539                         data = bp->b_data + off;
3540                         cnt--;
3541                 }
3542
3543                 /* Clear any remaining space so we don't leak kernel data */
3544                 if (size > off)
3545                         bzero(data, size - off);
3546
3547                 /*
3548                  * Write this one buffer and continue.
3549                  */
3550                 segwritten = 1;
3551                 jblocks->jb_needseg = 0;
3552                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3553                 FREE_LOCK(ump);
3554                 pbgetvp(ump->um_devvp, bp);
3555                 /*
3556                  * We only do the blocking wait once we find the journal
3557                  * entry we're looking for.
3558                  */
3559                 if (needwk == NULL && flags == MNT_WAIT)
3560                         bwrite(bp);
3561                 else
3562                         bawrite(bp);
3563                 ACQUIRE_LOCK(ump);
3564         }
3565         /*
3566          * If we wrote a segment issue a synchronize cache so the journal
3567          * is reflected on disk before the data is written.  Since reclaiming
3568          * journal space also requires writing a journal record this
3569          * process also enforces a barrier before reclamation.
3570          */
3571         if (segwritten && shouldflush) {
3572                 softdep_synchronize(bio, ump, 
3573                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3574         } else if (bio)
3575                 g_destroy_bio(bio);
3576         /*
3577          * If we've suspended the filesystem because we ran out of journal
3578          * space either try to sync it here to make some progress or
3579          * unsuspend it if we already have.
3580          */
3581         if (flags == 0 && jblocks->jb_suspended) {
3582                 if (journal_unsuspend(ump))
3583                         return;
3584                 FREE_LOCK(ump);
3585                 VFS_SYNC(mp, MNT_NOWAIT);
3586                 ffs_sbupdate(ump, MNT_WAIT, 0);
3587                 ACQUIRE_LOCK(ump);
3588         }
3589 }
3590
3591 /*
3592  * Complete a jseg, allowing all dependencies awaiting journal writes
3593  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3594  * structures so that the journal segment can be freed to reclaim space.
3595  */
3596 static void
3597 complete_jseg(jseg)
3598         struct jseg *jseg;
3599 {
3600         struct worklist *wk;
3601         struct jmvref *jmvref;
3602 #ifdef INVARIANTS
3603         int i = 0;
3604 #endif
3605
3606         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3607                 WORKLIST_REMOVE(wk);
3608                 wk->wk_state &= ~INPROGRESS;
3609                 wk->wk_state |= COMPLETE;
3610                 KASSERT(i++ < jseg->js_cnt,
3611                     ("handle_written_jseg: overflow %d >= %d",
3612                     i - 1, jseg->js_cnt));
3613                 switch (wk->wk_type) {
3614                 case D_JADDREF:
3615                         handle_written_jaddref(WK_JADDREF(wk));
3616                         break;
3617                 case D_JREMREF:
3618                         handle_written_jremref(WK_JREMREF(wk));
3619                         break;
3620                 case D_JMVREF:
3621                         rele_jseg(jseg);        /* No jsegdep. */
3622                         jmvref = WK_JMVREF(wk);
3623                         LIST_REMOVE(jmvref, jm_deps);
3624                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3625                                 free_pagedep(jmvref->jm_pagedep);
3626                         WORKITEM_FREE(jmvref, D_JMVREF);
3627                         break;
3628                 case D_JNEWBLK:
3629                         handle_written_jnewblk(WK_JNEWBLK(wk));
3630                         break;
3631                 case D_JFREEBLK:
3632                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3633                         break;
3634                 case D_JTRUNC:
3635                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3636                         break;
3637                 case D_JFSYNC:
3638                         rele_jseg(jseg);        /* No jsegdep. */
3639                         WORKITEM_FREE(wk, D_JFSYNC);
3640                         break;
3641                 case D_JFREEFRAG:
3642                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3643                         break;
3644                 default:
3645                         panic("handle_written_jseg: Unknown type %s",
3646                             TYPENAME(wk->wk_type));
3647                         /* NOTREACHED */
3648                 }
3649         }
3650         /* Release the self reference so the structure may be freed. */
3651         rele_jseg(jseg);
3652 }
3653
3654 /*
3655  * Determine which jsegs are ready for completion processing.  Waits for
3656  * synchronize cache to complete as well as forcing in-order completion
3657  * of journal entries.
3658  */
3659 static void
3660 complete_jsegs(jseg)
3661         struct jseg *jseg;
3662 {
3663         struct jblocks *jblocks;
3664         struct jseg *jsegn;
3665
3666         jblocks = jseg->js_jblocks;
3667         /*
3668          * Don't allow out of order completions.  If this isn't the first
3669          * block wait for it to write before we're done.
3670          */
3671         if (jseg != jblocks->jb_writeseg)
3672                 return;
3673         /* Iterate through available jsegs processing their entries. */
3674         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3675                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3676                 jsegn = TAILQ_NEXT(jseg, js_next);
3677                 complete_jseg(jseg);
3678                 jseg = jsegn;
3679         }
3680         jblocks->jb_writeseg = jseg;
3681         /*
3682          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3683          */
3684         free_jsegs(jblocks);
3685 }
3686
3687 /*
3688  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3689  * the final completions.
3690  */
3691 static void
3692 handle_written_jseg(jseg, bp)
3693         struct jseg *jseg;
3694         struct buf *bp;
3695 {
3696
3697         if (jseg->js_refs == 0)
3698                 panic("handle_written_jseg: No self-reference on %p", jseg);
3699         jseg->js_state |= DEPCOMPLETE;
3700         /*
3701          * We'll never need this buffer again, set flags so it will be
3702          * discarded.
3703          */
3704         bp->b_flags |= B_INVAL | B_NOCACHE;
3705         pbrelvp(bp);
3706         complete_jsegs(jseg);
3707 }
3708
3709 static inline struct jsegdep *
3710 inoref_jseg(inoref)
3711         struct inoref *inoref;
3712 {
3713         struct jsegdep *jsegdep;
3714
3715         jsegdep = inoref->if_jsegdep;
3716         inoref->if_jsegdep = NULL;
3717
3718         return (jsegdep);
3719 }
3720
3721 /*
3722  * Called once a jremref has made it to stable store.  The jremref is marked
3723  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3724  * for the jremref to complete will be awoken by free_jremref.
3725  */
3726 static void
3727 handle_written_jremref(jremref)
3728         struct jremref *jremref;
3729 {
3730         struct inodedep *inodedep;
3731         struct jsegdep *jsegdep;
3732         struct dirrem *dirrem;
3733
3734         /* Grab the jsegdep. */
3735         jsegdep = inoref_jseg(&jremref->jr_ref);
3736         /*
3737          * Remove us from the inoref list.
3738          */
3739         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3740             0, &inodedep) == 0)
3741                 panic("handle_written_jremref: Lost inodedep");
3742         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3743         /*
3744          * Complete the dirrem.
3745          */
3746         dirrem = jremref->jr_dirrem;
3747         jremref->jr_dirrem = NULL;
3748         LIST_REMOVE(jremref, jr_deps);
3749         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3750         jwork_insert(&dirrem->dm_jwork, jsegdep);
3751         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3752             (dirrem->dm_state & COMPLETE) != 0)
3753                 add_to_worklist(&dirrem->dm_list, 0);
3754         free_jremref(jremref);
3755 }
3756
3757 /*
3758  * Called once a jaddref has made it to stable store.  The dependency is
3759  * marked complete and any dependent structures are added to the inode
3760  * bufwait list to be completed as soon as it is written.  If a bitmap write
3761  * depends on this entry we move the inode into the inodedephd of the
3762  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3763  */
3764 static void
3765 handle_written_jaddref(jaddref)
3766         struct jaddref *jaddref;
3767 {
3768         struct jsegdep *jsegdep;
3769         struct inodedep *inodedep;
3770         struct diradd *diradd;
3771         struct mkdir *mkdir;
3772
3773         /* Grab the jsegdep. */
3774         jsegdep = inoref_jseg(&jaddref->ja_ref);
3775         mkdir = NULL;
3776         diradd = NULL;
3777         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3778             0, &inodedep) == 0)
3779                 panic("handle_written_jaddref: Lost inodedep.");
3780         if (jaddref->ja_diradd == NULL)
3781                 panic("handle_written_jaddref: No dependency");
3782         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3783                 diradd = jaddref->ja_diradd;
3784                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3785         } else if (jaddref->ja_state & MKDIR_PARENT) {
3786                 mkdir = jaddref->ja_mkdir;
3787                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3788         } else if (jaddref->ja_state & MKDIR_BODY)
3789                 mkdir = jaddref->ja_mkdir;
3790         else
3791                 panic("handle_written_jaddref: Unknown dependency %p",
3792                     jaddref->ja_diradd);
3793         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3794         /*
3795          * Remove us from the inode list.
3796          */
3797         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3798         /*
3799          * The mkdir may be waiting on the jaddref to clear before freeing.
3800          */
3801         if (mkdir) {
3802                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3803                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3804                     TYPENAME(mkdir->md_list.wk_type)));
3805                 mkdir->md_jaddref = NULL;
3806                 diradd = mkdir->md_diradd;
3807                 mkdir->md_state |= DEPCOMPLETE;
3808                 complete_mkdir(mkdir);
3809         }
3810         jwork_insert(&diradd->da_jwork, jsegdep);
3811         if (jaddref->ja_state & NEWBLOCK) {
3812                 inodedep->id_state |= ONDEPLIST;
3813                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3814                     inodedep, id_deps);
3815         }
3816         free_jaddref(jaddref);
3817 }
3818
3819 /*
3820  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3821  * is placed in the bmsafemap to await notification of a written bitmap.  If
3822  * the operation was canceled we add the segdep to the appropriate
3823  * dependency to free the journal space once the canceling operation
3824  * completes.
3825  */
3826 static void
3827 handle_written_jnewblk(jnewblk)
3828         struct jnewblk *jnewblk;
3829 {
3830         struct bmsafemap *bmsafemap;
3831         struct freefrag *freefrag;
3832         struct freework *freework;
3833         struct jsegdep *jsegdep;
3834         struct newblk *newblk;
3835
3836         /* Grab the jsegdep. */
3837         jsegdep = jnewblk->jn_jsegdep;
3838         jnewblk->jn_jsegdep = NULL;
3839         if (jnewblk->jn_dep == NULL) 
3840                 panic("handle_written_jnewblk: No dependency for the segdep.");
3841         switch (jnewblk->jn_dep->wk_type) {
3842         case D_NEWBLK:
3843         case D_ALLOCDIRECT:
3844         case D_ALLOCINDIR:
3845                 /*
3846                  * Add the written block to the bmsafemap so it can
3847                  * be notified when the bitmap is on disk.
3848                  */
3849                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3850                 newblk->nb_jnewblk = NULL;
3851                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3852                         bmsafemap = newblk->nb_bmsafemap;
3853                         newblk->nb_state |= ONDEPLIST;
3854                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3855                             nb_deps);
3856                 }
3857                 jwork_insert(&newblk->nb_jwork, jsegdep);
3858                 break;
3859         case D_FREEFRAG:
3860                 /*
3861                  * A newblock being removed by a freefrag when replaced by
3862                  * frag extension.
3863                  */
3864                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3865                 freefrag->ff_jdep = NULL;
3866                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3867                 break;
3868         case D_FREEWORK:
3869                 /*
3870                  * A direct block was removed by truncate.
3871                  */
3872                 freework = WK_FREEWORK(jnewblk->jn_dep);
3873                 freework->fw_jnewblk = NULL;
3874                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3875                 break;
3876         default:
3877                 panic("handle_written_jnewblk: Unknown type %d.",
3878                     jnewblk->jn_dep->wk_type);
3879         }
3880         jnewblk->jn_dep = NULL;
3881         free_jnewblk(jnewblk);
3882 }
3883
3884 /*
3885  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3886  * an in-flight allocation that has not yet been committed.  Divorce us
3887  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3888  * to the worklist.
3889  */
3890 static void
3891 cancel_jfreefrag(jfreefrag)
3892         struct jfreefrag *jfreefrag;
3893 {
3894         struct freefrag *freefrag;
3895
3896         if (jfreefrag->fr_jsegdep) {
3897                 free_jsegdep(jfreefrag->fr_jsegdep);
3898                 jfreefrag->fr_jsegdep = NULL;
3899         }
3900         freefrag = jfreefrag->fr_freefrag;
3901         jfreefrag->fr_freefrag = NULL;
3902         free_jfreefrag(jfreefrag);
3903         freefrag->ff_state |= DEPCOMPLETE;
3904         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3905 }
3906
3907 /*
3908  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3909  */
3910 static void
3911 free_jfreefrag(jfreefrag)
3912         struct jfreefrag *jfreefrag;
3913 {
3914
3915         if (jfreefrag->fr_state & INPROGRESS)
3916                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3917         else if (jfreefrag->fr_state & ONWORKLIST)
3918                 remove_from_journal(&jfreefrag->fr_list);
3919         if (jfreefrag->fr_freefrag != NULL)
3920                 panic("free_jfreefrag:  Still attached to a freefrag.");
3921         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3922 }
3923
3924 /*
3925  * Called when the journal write for a jfreefrag completes.  The parent
3926  * freefrag is added to the worklist if this completes its dependencies.
3927  */
3928 static void
3929 handle_written_jfreefrag(jfreefrag)
3930         struct jfreefrag *jfreefrag;
3931 {
3932         struct jsegdep *jsegdep;
3933         struct freefrag *freefrag;
3934
3935         /* Grab the jsegdep. */
3936         jsegdep = jfreefrag->fr_jsegdep;
3937         jfreefrag->fr_jsegdep = NULL;
3938         freefrag = jfreefrag->fr_freefrag;
3939         if (freefrag == NULL)
3940                 panic("handle_written_jfreefrag: No freefrag.");
3941         freefrag->ff_state |= DEPCOMPLETE;
3942         freefrag->ff_jdep = NULL;
3943         jwork_insert(&freefrag->ff_jwork, jsegdep);
3944         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3945                 add_to_worklist(&freefrag->ff_list, 0);
3946         jfreefrag->fr_freefrag = NULL;
3947         free_jfreefrag(jfreefrag);
3948 }
3949
3950 /*
3951  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3952  * is removed from the freeblks list of pending journal writes and the
3953  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3954  * have been reclaimed.
3955  */
3956 static void
3957 handle_written_jblkdep(jblkdep)
3958         struct jblkdep *jblkdep;
3959 {
3960         struct freeblks *freeblks;
3961         struct jsegdep *jsegdep;
3962
3963         /* Grab the jsegdep. */
3964         jsegdep = jblkdep->jb_jsegdep;
3965         jblkdep->jb_jsegdep = NULL;
3966         freeblks = jblkdep->jb_freeblks;
3967         LIST_REMOVE(jblkdep, jb_deps);
3968         jwork_insert(&freeblks->fb_jwork, jsegdep);
3969         /*
3970          * If the freeblks is all journaled, we can add it to the worklist.
3971          */
3972         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3973             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3974                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3975
3976         free_jblkdep(jblkdep);
3977 }
3978
3979 static struct jsegdep *
3980 newjsegdep(struct worklist *wk)
3981 {
3982         struct jsegdep *jsegdep;
3983
3984         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3985         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3986         jsegdep->jd_seg = NULL;
3987
3988         return (jsegdep);
3989 }
3990
3991 static struct jmvref *
3992 newjmvref(dp, ino, oldoff, newoff)
3993         struct inode *dp;
3994         ino_t ino;
3995         off_t oldoff;
3996         off_t newoff;
3997 {
3998         struct jmvref *jmvref;
3999
4000         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4001         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4002         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4003         jmvref->jm_parent = dp->i_number;
4004         jmvref->jm_ino = ino;
4005         jmvref->jm_oldoff = oldoff;
4006         jmvref->jm_newoff = newoff;
4007
4008         return (jmvref);
4009 }
4010
4011 /*
4012  * Allocate a new jremref that tracks the removal of ip from dp with the
4013  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4014  * DEPCOMPLETE as we have all the information required for the journal write
4015  * and the directory has already been removed from the buffer.  The caller
4016  * is responsible for linking the jremref into the pagedep and adding it
4017  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4018  * a DOTDOT addition so handle_workitem_remove() can properly assign
4019  * the jsegdep when we're done.
4020  */
4021 static struct jremref *
4022 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4023     off_t diroff, nlink_t nlink)
4024 {
4025         struct jremref *jremref;
4026
4027         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4028         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4029         jremref->jr_state = ATTACHED;
4030         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4031            nlink, ip->i_mode);
4032         jremref->jr_dirrem = dirrem;
4033
4034         return (jremref);
4035 }
4036
4037 static inline void
4038 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4039     nlink_t nlink, uint16_t mode)
4040 {
4041
4042         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4043         inoref->if_diroff = diroff;
4044         inoref->if_ino = ino;
4045         inoref->if_parent = parent;
4046         inoref->if_nlink = nlink;
4047         inoref->if_mode = mode;
4048 }
4049
4050 /*
4051  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4052  * directory offset may not be known until later.  The caller is responsible
4053  * adding the entry to the journal when this information is available.  nlink
4054  * should be the link count prior to the addition and mode is only required
4055  * to have the correct FMT.
4056  */
4057 static struct jaddref *
4058 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4059     uint16_t mode)
4060 {
4061         struct jaddref *jaddref;
4062
4063         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4064         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4065         jaddref->ja_state = ATTACHED;
4066         jaddref->ja_mkdir = NULL;
4067         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4068
4069         return (jaddref);
4070 }
4071
4072 /*
4073  * Create a new free dependency for a freework.  The caller is responsible
4074  * for adjusting the reference count when it has the lock held.  The freedep
4075  * will track an outstanding bitmap write that will ultimately clear the
4076  * freework to continue.
4077  */
4078 static struct freedep *
4079 newfreedep(struct freework *freework)
4080 {
4081         struct freedep *freedep;
4082
4083         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4084         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4085         freedep->fd_freework = freework;
4086
4087         return (freedep);
4088 }
4089
4090 /*
4091  * Free a freedep structure once the buffer it is linked to is written.  If
4092  * this is the last reference to the freework schedule it for completion.
4093  */
4094 static void
4095 free_freedep(freedep)
4096         struct freedep *freedep;
4097 {
4098         struct freework *freework;
4099
4100         freework = freedep->fd_freework;
4101         freework->fw_freeblks->fb_cgwait--;
4102         if (--freework->fw_ref == 0)
4103                 freework_enqueue(freework);
4104         WORKITEM_FREE(freedep, D_FREEDEP);
4105 }
4106
4107 /*
4108  * Allocate a new freework structure that may be a level in an indirect
4109  * when parent is not NULL or a top level block when it is.  The top level
4110  * freework structures are allocated without the per-filesystem lock held
4111  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4112  */
4113 static struct freework *
4114 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4115         struct ufsmount *ump;
4116         struct freeblks *freeblks;
4117         struct freework *parent;
4118         ufs_lbn_t lbn;
4119         ufs2_daddr_t nb;
4120         int frags;
4121         int off;
4122         int journal;
4123 {
4124         struct freework *freework;
4125
4126         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4127         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4128         freework->fw_state = ATTACHED;
4129         freework->fw_jnewblk = NULL;
4130         freework->fw_freeblks = freeblks;
4131         freework->fw_parent = parent;
4132         freework->fw_lbn = lbn;
4133         freework->fw_blkno = nb;
4134         freework->fw_frags = frags;
4135         freework->fw_indir = NULL;
4136         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4137             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4138         freework->fw_start = freework->fw_off = off;
4139         if (journal)
4140                 newjfreeblk(freeblks, lbn, nb, frags);
4141         if (parent == NULL) {
4142                 ACQUIRE_LOCK(ump);
4143                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4144                 freeblks->fb_ref++;
4145                 FREE_LOCK(ump);
4146         }
4147
4148         return (freework);
4149 }
4150
4151 /*
4152  * Eliminate a jfreeblk for a block that does not need journaling.
4153  */
4154 static void
4155 cancel_jfreeblk(freeblks, blkno)
4156         struct freeblks *freeblks;
4157         ufs2_daddr_t blkno;
4158 {
4159         struct jfreeblk *jfreeblk;
4160         struct jblkdep *jblkdep;
4161
4162         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4163                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4164                         continue;
4165                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4166                 if (jfreeblk->jf_blkno == blkno)
4167                         break;
4168         }
4169         if (jblkdep == NULL)
4170                 return;
4171         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4172         free_jsegdep(jblkdep->jb_jsegdep);
4173         LIST_REMOVE(jblkdep, jb_deps);
4174         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4175 }
4176
4177 /*
4178  * Allocate a new jfreeblk to journal top level block pointer when truncating
4179  * a file.  The caller must add this to the worklist when the per-filesystem
4180  * lock is held.
4181  */
4182 static struct jfreeblk *
4183 newjfreeblk(freeblks, lbn, blkno, frags)
4184         struct freeblks *freeblks;
4185         ufs_lbn_t lbn;
4186         ufs2_daddr_t blkno;
4187         int frags;
4188 {
4189         struct jfreeblk *jfreeblk;
4190
4191         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4192         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4193             freeblks->fb_list.wk_mp);
4194         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4195         jfreeblk->jf_dep.jb_freeblks = freeblks;
4196         jfreeblk->jf_ino = freeblks->fb_inum;
4197         jfreeblk->jf_lbn = lbn;
4198         jfreeblk->jf_blkno = blkno;
4199         jfreeblk->jf_frags = frags;
4200         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4201
4202         return (jfreeblk);
4203 }
4204
4205 /*
4206  * The journal is only prepared to handle full-size block numbers, so we
4207  * have to adjust the record to reflect the change to a full-size block.
4208  * For example, suppose we have a block made up of fragments 8-15 and
4209  * want to free its last two fragments. We are given a request that says:
4210  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4211  * where frags are the number of fragments to free and oldfrags are the
4212  * number of fragments to keep. To block align it, we have to change it to
4213  * have a valid full-size blkno, so it becomes:
4214  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4215  */
4216 static void
4217 adjust_newfreework(freeblks, frag_offset)
4218         struct freeblks *freeblks;
4219         int frag_offset;
4220 {
4221         struct jfreeblk *jfreeblk;
4222
4223         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4224             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4225             ("adjust_newfreework: Missing freeblks dependency"));
4226
4227         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4228         jfreeblk->jf_blkno -= frag_offset;
4229         jfreeblk->jf_frags += frag_offset;
4230 }
4231
4232 /*
4233  * Allocate a new jtrunc to track a partial truncation.
4234  */
4235 static struct jtrunc *
4236 newjtrunc(freeblks, size, extsize)
4237         struct freeblks *freeblks;
4238         off_t size;
4239         int extsize;
4240 {
4241         struct jtrunc *jtrunc;
4242
4243         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4244         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4245             freeblks->fb_list.wk_mp);
4246         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4247         jtrunc->jt_dep.jb_freeblks = freeblks;
4248         jtrunc->jt_ino = freeblks->fb_inum;
4249         jtrunc->jt_size = size;
4250         jtrunc->jt_extsize = extsize;
4251         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4252
4253         return (jtrunc);
4254 }
4255
4256 /*
4257  * If we're canceling a new bitmap we have to search for another ref
4258  * to move into the bmsafemap dep.  This might be better expressed
4259  * with another structure.
4260  */
4261 static void
4262 move_newblock_dep(jaddref, inodedep)
4263         struct jaddref *jaddref;
4264         struct inodedep *inodedep;
4265 {
4266         struct inoref *inoref;
4267         struct jaddref *jaddrefn;
4268
4269         jaddrefn = NULL;
4270         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4271             inoref = TAILQ_NEXT(inoref, if_deps)) {
4272                 if ((jaddref->ja_state & NEWBLOCK) &&
4273                     inoref->if_list.wk_type == D_JADDREF) {
4274                         jaddrefn = (struct jaddref *)inoref;
4275                         break;
4276                 }
4277         }
4278         if (jaddrefn == NULL)
4279                 return;
4280         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4281         jaddrefn->ja_state |= jaddref->ja_state &
4282             (ATTACHED | UNDONE | NEWBLOCK);
4283         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4284         jaddref->ja_state |= ATTACHED;
4285         LIST_REMOVE(jaddref, ja_bmdeps);
4286         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4287             ja_bmdeps);
4288 }
4289
4290 /*
4291  * Cancel a jaddref either before it has been written or while it is being
4292  * written.  This happens when a link is removed before the add reaches
4293  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4294  * and inode to prevent the link count or bitmap from reaching the disk
4295  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4296  * required.
4297  *
4298  * Returns 1 if the canceled addref requires journaling of the remove and
4299  * 0 otherwise.
4300  */
4301 static int
4302 cancel_jaddref(jaddref, inodedep, wkhd)
4303         struct jaddref *jaddref;
4304         struct inodedep *inodedep;
4305         struct workhead *wkhd;
4306 {
4307         struct inoref *inoref;
4308         struct jsegdep *jsegdep;
4309         int needsj;
4310
4311         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4312             ("cancel_jaddref: Canceling complete jaddref"));
4313         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4314                 needsj = 1;
4315         else
4316                 needsj = 0;
4317         if (inodedep == NULL)
4318                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4319                     0, &inodedep) == 0)
4320                         panic("cancel_jaddref: Lost inodedep");
4321         /*
4322          * We must adjust the nlink of any reference operation that follows
4323          * us so that it is consistent with the in-memory reference.  This
4324          * ensures that inode nlink rollbacks always have the correct link.
4325          */
4326         if (needsj == 0) {
4327                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4328                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4329                         if (inoref->if_state & GOINGAWAY)
4330                                 break;
4331                         inoref->if_nlink--;
4332                 }
4333         }
4334         jsegdep = inoref_jseg(&jaddref->ja_ref);
4335         if (jaddref->ja_state & NEWBLOCK)
4336                 move_newblock_dep(jaddref, inodedep);
4337         wake_worklist(&jaddref->ja_list);
4338         jaddref->ja_mkdir = NULL;
4339         if (jaddref->ja_state & INPROGRESS) {
4340                 jaddref->ja_state &= ~INPROGRESS;
4341                 WORKLIST_REMOVE(&jaddref->ja_list);
4342                 jwork_insert(wkhd, jsegdep);
4343         } else {
4344                 free_jsegdep(jsegdep);
4345                 if (jaddref->ja_state & DEPCOMPLETE)
4346                         remove_from_journal(&jaddref->ja_list);
4347         }
4348         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4349         /*
4350          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4351          * can arrange for them to be freed with the bitmap.  Otherwise we
4352          * no longer need this addref attached to the inoreflst and it
4353          * will incorrectly adjust nlink if we leave it.
4354          */
4355         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4356                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4357                     if_deps);
4358                 jaddref->ja_state |= COMPLETE;
4359                 free_jaddref(jaddref);
4360                 return (needsj);
4361         }
4362         /*
4363          * Leave the head of the list for jsegdeps for fast merging.
4364          */
4365         if (LIST_FIRST(wkhd) != NULL) {
4366                 jaddref->ja_state |= ONWORKLIST;
4367                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4368         } else
4369                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4370
4371         return (needsj);
4372 }
4373
4374 /* 
4375  * Attempt to free a jaddref structure when some work completes.  This
4376  * should only succeed once the entry is written and all dependencies have
4377  * been notified.
4378  */
4379 static void
4380 free_jaddref(jaddref)
4381         struct jaddref *jaddref;
4382 {
4383
4384         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4385                 return;
4386         if (jaddref->ja_ref.if_jsegdep)
4387                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4388                     jaddref, jaddref->ja_state);
4389         if (jaddref->ja_state & NEWBLOCK)
4390                 LIST_REMOVE(jaddref, ja_bmdeps);
4391         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4392                 panic("free_jaddref: Bad state %p(0x%X)",
4393                     jaddref, jaddref->ja_state);
4394         if (jaddref->ja_mkdir != NULL)
4395                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4396         WORKITEM_FREE(jaddref, D_JADDREF);
4397 }
4398
4399 /*
4400  * Free a jremref structure once it has been written or discarded.
4401  */
4402 static void
4403 free_jremref(jremref)
4404         struct jremref *jremref;
4405 {
4406
4407         if (jremref->jr_ref.if_jsegdep)
4408                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4409         if (jremref->jr_state & INPROGRESS)
4410                 panic("free_jremref: IO still pending");
4411         WORKITEM_FREE(jremref, D_JREMREF);
4412 }
4413
4414 /*
4415  * Free a jnewblk structure.
4416  */
4417 static void
4418 free_jnewblk(jnewblk)
4419         struct jnewblk *jnewblk;
4420 {
4421
4422         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4423                 return;
4424         LIST_REMOVE(jnewblk, jn_deps);
4425         if (jnewblk->jn_dep != NULL)
4426                 panic("free_jnewblk: Dependency still attached.");
4427         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4428 }
4429
4430 /*
4431  * Cancel a jnewblk which has been been made redundant by frag extension.
4432  */
4433 static void
4434 cancel_jnewblk(jnewblk, wkhd)
4435         struct jnewblk *jnewblk;
4436         struct workhead *wkhd;
4437 {
4438         struct jsegdep *jsegdep;
4439
4440         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4441         jsegdep = jnewblk->jn_jsegdep;
4442         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4443                 panic("cancel_jnewblk: Invalid state");
4444         jnewblk->jn_jsegdep  = NULL;
4445         jnewblk->jn_dep = NULL;
4446         jnewblk->jn_state |= GOINGAWAY;
4447         if (jnewblk->jn_state & INPROGRESS) {
4448                 jnewblk->jn_state &= ~INPROGRESS;
4449                 WORKLIST_REMOVE(&jnewblk->jn_list);
4450                 jwork_insert(wkhd, jsegdep);
4451         } else {
4452                 free_jsegdep(jsegdep);
4453                 remove_from_journal(&jnewblk->jn_list);
4454         }
4455         wake_worklist(&jnewblk->jn_list);
4456         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4457 }
4458
4459 static void
4460 free_jblkdep(jblkdep)
4461         struct jblkdep *jblkdep;
4462 {
4463
4464         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4465                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4466         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4467                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4468         else
4469                 panic("free_jblkdep: Unexpected type %s",
4470                     TYPENAME(jblkdep->jb_list.wk_type));
4471 }
4472
4473 /*
4474  * Free a single jseg once it is no longer referenced in memory or on
4475  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4476  * to disappear.
4477  */
4478 static void
4479 free_jseg(jseg, jblocks)
4480         struct jseg *jseg;
4481         struct jblocks *jblocks;
4482 {
4483         struct freework *freework;
4484
4485         /*
4486          * Free freework structures that were lingering to indicate freed
4487          * indirect blocks that forced journal write ordering on reallocate.
4488          */
4489         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4490                 indirblk_remove(freework);
4491         if (jblocks->jb_oldestseg == jseg)
4492                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4493         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4494         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4495         KASSERT(LIST_EMPTY(&jseg->js_entries),
4496             ("free_jseg: Freed jseg has valid entries."));
4497         WORKITEM_FREE(jseg, D_JSEG);
4498 }
4499
4500 /*
4501  * Free all jsegs that meet the criteria for being reclaimed and update
4502  * oldestseg.
4503  */
4504 static void
4505 free_jsegs(jblocks)
4506         struct jblocks *jblocks;
4507 {
4508         struct jseg *jseg;
4509
4510         /*
4511          * Free only those jsegs which have none allocated before them to
4512          * preserve the journal space ordering.
4513          */
4514         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4515                 /*
4516                  * Only reclaim space when nothing depends on this journal
4517                  * set and another set has written that it is no longer
4518                  * valid.
4519                  */
4520                 if (jseg->js_refs != 0) {
4521                         jblocks->jb_oldestseg = jseg;
4522                         return;
4523                 }
4524                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4525                         break;
4526                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4527                         break;
4528                 /*
4529                  * We can free jsegs that didn't write entries when
4530                  * oldestwrseq == js_seq.
4531                  */
4532                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4533                     jseg->js_cnt != 0)
4534                         break;
4535                 free_jseg(jseg, jblocks);
4536         }
4537         /*
4538          * If we exited the loop above we still must discover the
4539          * oldest valid segment.
4540          */
4541         if (jseg)
4542                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4543                      jseg = TAILQ_NEXT(jseg, js_next))
4544                         if (jseg->js_refs != 0)
4545                                 break;
4546         jblocks->jb_oldestseg = jseg;
4547         /*
4548          * The journal has no valid records but some jsegs may still be
4549          * waiting on oldestwrseq to advance.  We force a small record
4550          * out to permit these lingering records to be reclaimed.
4551          */
4552         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4553                 jblocks->jb_needseg = 1;
4554 }
4555
4556 /*
4557  * Release one reference to a jseg and free it if the count reaches 0.  This
4558  * should eventually reclaim journal space as well.
4559  */
4560 static void
4561 rele_jseg(jseg)
4562         struct jseg *jseg;
4563 {
4564
4565         KASSERT(jseg->js_refs > 0,
4566             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4567         if (--jseg->js_refs != 0)
4568                 return;
4569         free_jsegs(jseg->js_jblocks);
4570 }
4571
4572 /*
4573  * Release a jsegdep and decrement the jseg count.
4574  */
4575 static void
4576 free_jsegdep(jsegdep)
4577         struct jsegdep *jsegdep;
4578 {
4579
4580         if (jsegdep->jd_seg)
4581                 rele_jseg(jsegdep->jd_seg);
4582         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4583 }
4584
4585 /*
4586  * Wait for a journal item to make it to disk.  Initiate journal processing
4587  * if required.
4588  */
4589 static int
4590 jwait(wk, waitfor)
4591         struct worklist *wk;
4592         int waitfor;
4593 {
4594
4595         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4596         /*
4597          * Blocking journal waits cause slow synchronous behavior.  Record
4598          * stats on the frequency of these blocking operations.
4599          */
4600         if (waitfor == MNT_WAIT) {
4601                 stat_journal_wait++;
4602                 switch (wk->wk_type) {
4603                 case D_JREMREF:
4604                 case D_JMVREF:
4605                         stat_jwait_filepage++;
4606                         break;
4607                 case D_JTRUNC:
4608                 case D_JFREEBLK:
4609                         stat_jwait_freeblks++;
4610                         break;
4611                 case D_JNEWBLK:
4612                         stat_jwait_newblk++;
4613                         break;
4614                 case D_JADDREF:
4615                         stat_jwait_inode++;
4616                         break;
4617                 default:
4618                         break;
4619                 }
4620         }
4621         /*
4622          * If IO has not started we process the journal.  We can't mark the
4623          * worklist item as IOWAITING because we drop the lock while
4624          * processing the journal and the worklist entry may be freed after
4625          * this point.  The caller may call back in and re-issue the request.
4626          */
4627         if ((wk->wk_state & INPROGRESS) == 0) {
4628                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4629                 if (waitfor != MNT_WAIT)
4630                         return (EBUSY);
4631                 return (0);
4632         }
4633         if (waitfor != MNT_WAIT)
4634                 return (EBUSY);
4635         wait_worklist(wk, "jwait");
4636         return (0);
4637 }
4638
4639 /*
4640  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4641  * appropriate.  This is a convenience function to reduce duplicate code
4642  * for the setup and revert functions below.
4643  */
4644 static struct inodedep *
4645 inodedep_lookup_ip(ip)
4646         struct inode *ip;
4647 {
4648         struct inodedep *inodedep;
4649
4650         KASSERT(ip->i_nlink >= ip->i_effnlink,
4651             ("inodedep_lookup_ip: bad delta"));
4652         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4653             &inodedep);
4654         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4655         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4656
4657         return (inodedep);
4658 }
4659
4660 /*
4661  * Called prior to creating a new inode and linking it to a directory.  The
4662  * jaddref structure must already be allocated by softdep_setup_inomapdep
4663  * and it is discovered here so we can initialize the mode and update
4664  * nlinkdelta.
4665  */
4666 void
4667 softdep_setup_create(dp, ip)
4668         struct inode *dp;
4669         struct inode *ip;
4670 {
4671         struct inodedep *inodedep;
4672         struct jaddref *jaddref;
4673         struct vnode *dvp;
4674
4675         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4676             ("softdep_setup_create called on non-softdep filesystem"));
4677         KASSERT(ip->i_nlink == 1,
4678             ("softdep_setup_create: Invalid link count."));
4679         dvp = ITOV(dp);
4680         ACQUIRE_LOCK(ITOUMP(dp));
4681         inodedep = inodedep_lookup_ip(ip);
4682         if (DOINGSUJ(dvp)) {
4683                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4684                     inoreflst);
4685                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4686                     ("softdep_setup_create: No addref structure present."));
4687         }
4688         softdep_prelink(dvp, NULL);
4689         FREE_LOCK(ITOUMP(dp));
4690 }
4691
4692 /*
4693  * Create a jaddref structure to track the addition of a DOTDOT link when
4694  * we are reparenting an inode as part of a rename.  This jaddref will be
4695  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4696  * non-journaling softdep.
4697  */
4698 void
4699 softdep_setup_dotdot_link(dp, ip)
4700         struct inode *dp;
4701         struct inode *ip;
4702 {
4703         struct inodedep *inodedep;
4704         struct jaddref *jaddref;
4705         struct vnode *dvp;
4706
4707         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4708             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4709         dvp = ITOV(dp);
4710         jaddref = NULL;
4711         /*
4712          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4713          * is used as a normal link would be.
4714          */
4715         if (DOINGSUJ(dvp))
4716                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4717                     dp->i_effnlink - 1, dp->i_mode);
4718         ACQUIRE_LOCK(ITOUMP(dp));
4719         inodedep = inodedep_lookup_ip(dp);
4720         if (jaddref)
4721                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4722                     if_deps);
4723         softdep_prelink(dvp, ITOV(ip));
4724         FREE_LOCK(ITOUMP(dp));
4725 }
4726
4727 /*
4728  * Create a jaddref structure to track a new link to an inode.  The directory
4729  * offset is not known until softdep_setup_directory_add or
4730  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4731  * softdep.
4732  */
4733 void
4734 softdep_setup_link(dp, ip)
4735         struct inode *dp;
4736         struct inode *ip;
4737 {
4738         struct inodedep *inodedep;
4739         struct jaddref *jaddref;
4740         struct vnode *dvp;
4741
4742         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4743             ("softdep_setup_link called on non-softdep filesystem"));
4744         dvp = ITOV(dp);
4745         jaddref = NULL;
4746         if (DOINGSUJ(dvp))
4747                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4748                     ip->i_mode);
4749         ACQUIRE_LOCK(ITOUMP(dp));
4750         inodedep = inodedep_lookup_ip(ip);
4751         if (jaddref)
4752                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4753                     if_deps);
4754         softdep_prelink(dvp, ITOV(ip));
4755         FREE_LOCK(ITOUMP(dp));
4756 }
4757
4758 /*
4759  * Called to create the jaddref structures to track . and .. references as
4760  * well as lookup and further initialize the incomplete jaddref created
4761  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4762  * nlinkdelta for non-journaling softdep.
4763  */
4764 void
4765 softdep_setup_mkdir(dp, ip)
4766         struct inode *dp;
4767         struct inode *ip;
4768 {
4769         struct inodedep *inodedep;
4770         struct jaddref *dotdotaddref;
4771         struct jaddref *dotaddref;
4772         struct jaddref *jaddref;
4773         struct vnode *dvp;
4774
4775         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4776             ("softdep_setup_mkdir called on non-softdep filesystem"));
4777         dvp = ITOV(dp);
4778         dotaddref = dotdotaddref = NULL;
4779         if (DOINGSUJ(dvp)) {
4780                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4781                     ip->i_mode);
4782                 dotaddref->ja_state |= MKDIR_BODY;
4783                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4784                     dp->i_effnlink - 1, dp->i_mode);
4785                 dotdotaddref->ja_state |= MKDIR_PARENT;
4786         }
4787         ACQUIRE_LOCK(ITOUMP(dp));
4788         inodedep = inodedep_lookup_ip(ip);
4789         if (DOINGSUJ(dvp)) {
4790                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4791                     inoreflst);
4792                 KASSERT(jaddref != NULL,
4793                     ("softdep_setup_mkdir: No addref structure present."));
4794                 KASSERT(jaddref->ja_parent == dp->i_number, 
4795                     ("softdep_setup_mkdir: bad parent %ju",
4796                     (uintmax_t)jaddref->ja_parent));
4797                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4798                     if_deps);
4799         }
4800         inodedep = inodedep_lookup_ip(dp);
4801         if (DOINGSUJ(dvp))
4802                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4803                     &dotdotaddref->ja_ref, if_deps);
4804         softdep_prelink(ITOV(dp), NULL);
4805         FREE_LOCK(ITOUMP(dp));
4806 }
4807
4808 /*
4809  * Called to track nlinkdelta of the inode and parent directories prior to
4810  * unlinking a directory.
4811  */
4812 void
4813 softdep_setup_rmdir(dp, ip)
4814         struct inode *dp;
4815         struct inode *ip;
4816 {
4817         struct vnode *dvp;
4818
4819         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4820             ("softdep_setup_rmdir called on non-softdep filesystem"));
4821         dvp = ITOV(dp);
4822         ACQUIRE_LOCK(ITOUMP(dp));
4823         (void) inodedep_lookup_ip(ip);
4824         (void) inodedep_lookup_ip(dp);
4825         softdep_prelink(dvp, ITOV(ip));
4826         FREE_LOCK(ITOUMP(dp));
4827 }
4828
4829 /*
4830  * Called to track nlinkdelta of the inode and parent directories prior to
4831  * unlink.
4832  */
4833 void
4834 softdep_setup_unlink(dp, ip)
4835         struct inode *dp;
4836         struct inode *ip;
4837 {
4838         struct vnode *dvp;
4839
4840         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4841             ("softdep_setup_unlink called on non-softdep filesystem"));
4842         dvp = ITOV(dp);
4843         ACQUIRE_LOCK(ITOUMP(dp));
4844         (void) inodedep_lookup_ip(ip);
4845         (void) inodedep_lookup_ip(dp);
4846         softdep_prelink(dvp, ITOV(ip));
4847         FREE_LOCK(ITOUMP(dp));
4848 }
4849
4850 /*
4851  * Called to release the journal structures created by a failed non-directory
4852  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4853  */
4854 void
4855 softdep_revert_create(dp, ip)
4856         struct inode *dp;
4857         struct inode *ip;
4858 {
4859         struct inodedep *inodedep;
4860         struct jaddref *jaddref;
4861         struct vnode *dvp;
4862
4863         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4864             ("softdep_revert_create called on non-softdep filesystem"));
4865         dvp = ITOV(dp);
4866         ACQUIRE_LOCK(ITOUMP(dp));
4867         inodedep = inodedep_lookup_ip(ip);
4868         if (DOINGSUJ(dvp)) {
4869                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4870                     inoreflst);
4871                 KASSERT(jaddref->ja_parent == dp->i_number,
4872                     ("softdep_revert_create: addref parent mismatch"));
4873                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4874         }
4875         FREE_LOCK(ITOUMP(dp));
4876 }
4877
4878 /*
4879  * Called to release the journal structures created by a failed link
4880  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4881  */
4882 void
4883 softdep_revert_link(dp, ip)
4884         struct inode *dp;
4885         struct inode *ip;
4886 {
4887         struct inodedep *inodedep;
4888         struct jaddref *jaddref;
4889         struct vnode *dvp;
4890
4891         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4892             ("softdep_revert_link called on non-softdep filesystem"));
4893         dvp = ITOV(dp);
4894         ACQUIRE_LOCK(ITOUMP(dp));
4895         inodedep = inodedep_lookup_ip(ip);
4896         if (DOINGSUJ(dvp)) {
4897                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4898                     inoreflst);
4899                 KASSERT(jaddref->ja_parent == dp->i_number,
4900                     ("softdep_revert_link: addref parent mismatch"));
4901                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4902         }
4903         FREE_LOCK(ITOUMP(dp));
4904 }
4905
4906 /*
4907  * Called to release the journal structures created by a failed mkdir
4908  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4909  */
4910 void
4911 softdep_revert_mkdir(dp, ip)
4912         struct inode *dp;
4913         struct inode *ip;
4914 {
4915         struct inodedep *inodedep;
4916         struct jaddref *jaddref;
4917         struct jaddref *dotaddref;
4918         struct vnode *dvp;
4919
4920         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4921             ("softdep_revert_mkdir called on non-softdep filesystem"));
4922         dvp = ITOV(dp);
4923
4924         ACQUIRE_LOCK(ITOUMP(dp));
4925         inodedep = inodedep_lookup_ip(dp);
4926         if (DOINGSUJ(dvp)) {
4927                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4928                     inoreflst);
4929                 KASSERT(jaddref->ja_parent == ip->i_number,
4930                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4931                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4932         }
4933         inodedep = inodedep_lookup_ip(ip);
4934         if (DOINGSUJ(dvp)) {
4935                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4936                     inoreflst);
4937                 KASSERT(jaddref->ja_parent == dp->i_number,
4938                     ("softdep_revert_mkdir: addref parent mismatch"));
4939                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4940                     inoreflst, if_deps);
4941                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4942                 KASSERT(dotaddref->ja_parent == ip->i_number,
4943                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4944                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4945         }
4946         FREE_LOCK(ITOUMP(dp));
4947 }
4948
4949 /* 
4950  * Called to correct nlinkdelta after a failed rmdir.
4951  */
4952 void
4953 softdep_revert_rmdir(dp, ip)
4954         struct inode *dp;
4955         struct inode *ip;
4956 {
4957
4958         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4959             ("softdep_revert_rmdir called on non-softdep filesystem"));
4960         ACQUIRE_LOCK(ITOUMP(dp));
4961         (void) inodedep_lookup_ip(ip);
4962         (void) inodedep_lookup_ip(dp);
4963         FREE_LOCK(ITOUMP(dp));
4964 }
4965
4966 /*
4967  * Protecting the freemaps (or bitmaps).
4968  * 
4969  * To eliminate the need to execute fsck before mounting a filesystem
4970  * after a power failure, one must (conservatively) guarantee that the
4971  * on-disk copy of the bitmaps never indicate that a live inode or block is
4972  * free.  So, when a block or inode is allocated, the bitmap should be
4973  * updated (on disk) before any new pointers.  When a block or inode is
4974  * freed, the bitmap should not be updated until all pointers have been
4975  * reset.  The latter dependency is handled by the delayed de-allocation
4976  * approach described below for block and inode de-allocation.  The former
4977  * dependency is handled by calling the following procedure when a block or
4978  * inode is allocated. When an inode is allocated an "inodedep" is created
4979  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4980  * Each "inodedep" is also inserted into the hash indexing structure so
4981  * that any additional link additions can be made dependent on the inode
4982  * allocation.
4983  * 
4984  * The ufs filesystem maintains a number of free block counts (e.g., per
4985  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4986  * in addition to the bitmaps.  These counts are used to improve efficiency
4987  * during allocation and therefore must be consistent with the bitmaps.
4988  * There is no convenient way to guarantee post-crash consistency of these
4989  * counts with simple update ordering, for two main reasons: (1) The counts
4990  * and bitmaps for a single cylinder group block are not in the same disk
4991  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4992  * be written and the other not.  (2) Some of the counts are located in the
4993  * superblock rather than the cylinder group block. So, we focus our soft
4994  * updates implementation on protecting the bitmaps. When mounting a
4995  * filesystem, we recompute the auxiliary counts from the bitmaps.
4996  */
4997
4998 /*
4999  * Called just after updating the cylinder group block to allocate an inode.
5000  */
5001 void
5002 softdep_setup_inomapdep(bp, ip, newinum, mode)
5003         struct buf *bp;         /* buffer for cylgroup block with inode map */
5004         struct inode *ip;       /* inode related to allocation */
5005         ino_t newinum;          /* new inode number being allocated */
5006         int mode;
5007 {
5008         struct inodedep *inodedep;
5009         struct bmsafemap *bmsafemap;
5010         struct jaddref *jaddref;
5011         struct mount *mp;
5012         struct fs *fs;
5013
5014         mp = ITOVFS(ip);
5015         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5016             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5017         fs = VFSTOUFS(mp)->um_fs;
5018         jaddref = NULL;
5019
5020         /*
5021          * Allocate the journal reference add structure so that the bitmap
5022          * can be dependent on it.
5023          */
5024         if (MOUNTEDSUJ(mp)) {
5025                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5026                 jaddref->ja_state |= NEWBLOCK;
5027         }
5028
5029         /*
5030          * Create a dependency for the newly allocated inode.
5031          * Panic if it already exists as something is seriously wrong.
5032          * Otherwise add it to the dependency list for the buffer holding
5033          * the cylinder group map from which it was allocated.
5034          *
5035          * We have to preallocate a bmsafemap entry in case it is needed
5036          * in bmsafemap_lookup since once we allocate the inodedep, we
5037          * have to finish initializing it before we can FREE_LOCK().
5038          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5039          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5040          * creating the inodedep as it can be freed during the time
5041          * that we FREE_LOCK() while allocating the inodedep. We must
5042          * call workitem_alloc() before entering the locked section as
5043          * it also acquires the lock and we must avoid trying doing so
5044          * recursively.
5045          */
5046         bmsafemap = malloc(sizeof(struct bmsafemap),
5047             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5048         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5049         ACQUIRE_LOCK(ITOUMP(ip));
5050         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5051                 panic("softdep_setup_inomapdep: dependency %p for new"
5052                     "inode already exists", inodedep);
5053         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5054         if (jaddref) {
5055                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5056                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5057                     if_deps);
5058         } else {
5059                 inodedep->id_state |= ONDEPLIST;
5060                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5061         }
5062         inodedep->id_bmsafemap = bmsafemap;
5063         inodedep->id_state &= ~DEPCOMPLETE;
5064         FREE_LOCK(ITOUMP(ip));
5065 }
5066
5067 /*
5068  * Called just after updating the cylinder group block to
5069  * allocate block or fragment.
5070  */
5071 void
5072 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5073         struct buf *bp;         /* buffer for cylgroup block with block map */
5074         struct mount *mp;       /* filesystem doing allocation */
5075         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5076         int frags;              /* Number of fragments. */
5077         int oldfrags;           /* Previous number of fragments for extend. */
5078 {
5079         struct newblk *newblk;
5080         struct bmsafemap *bmsafemap;
5081         struct jnewblk *jnewblk;
5082         struct ufsmount *ump;
5083         struct fs *fs;
5084
5085         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5086             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5087         ump = VFSTOUFS(mp);
5088         fs = ump->um_fs;
5089         jnewblk = NULL;
5090         /*
5091          * Create a dependency for the newly allocated block.
5092          * Add it to the dependency list for the buffer holding
5093          * the cylinder group map from which it was allocated.
5094          */
5095         if (MOUNTEDSUJ(mp)) {
5096                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5097                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5098                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5099                 jnewblk->jn_state = ATTACHED;
5100                 jnewblk->jn_blkno = newblkno;
5101                 jnewblk->jn_frags = frags;
5102                 jnewblk->jn_oldfrags = oldfrags;
5103 #ifdef SUJ_DEBUG
5104                 {
5105                         struct cg *cgp;
5106                         uint8_t *blksfree;
5107                         long bno;
5108                         int i;
5109         
5110                         cgp = (struct cg *)bp->b_data;
5111                         blksfree = cg_blksfree(cgp);
5112                         bno = dtogd(fs, jnewblk->jn_blkno);
5113                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5114                             i++) {
5115                                 if (isset(blksfree, bno + i))
5116                                         panic("softdep_setup_blkmapdep: "
5117                                             "free fragment %d from %d-%d "
5118                                             "state 0x%X dep %p", i,
5119                                             jnewblk->jn_oldfrags,
5120                                             jnewblk->jn_frags,
5121                                             jnewblk->jn_state,
5122                                             jnewblk->jn_dep);
5123                         }
5124                 }
5125 #endif
5126         }
5127
5128         CTR3(KTR_SUJ,
5129             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5130             newblkno, frags, oldfrags);
5131         ACQUIRE_LOCK(ump);
5132         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5133                 panic("softdep_setup_blkmapdep: found block");
5134         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5135             dtog(fs, newblkno), NULL);
5136         if (jnewblk) {
5137                 jnewblk->jn_dep = (struct worklist *)newblk;
5138                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5139         } else {
5140                 newblk->nb_state |= ONDEPLIST;
5141                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5142         }
5143         newblk->nb_bmsafemap = bmsafemap;
5144         newblk->nb_jnewblk = jnewblk;
5145         FREE_LOCK(ump);
5146 }
5147
5148 #define BMSAFEMAP_HASH(ump, cg) \
5149       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5150
5151 static int
5152 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5153         struct bmsafemap_hashhead *bmsafemaphd;
5154         int cg;
5155         struct bmsafemap **bmsafemapp;
5156 {
5157         struct bmsafemap *bmsafemap;
5158
5159         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5160                 if (bmsafemap->sm_cg == cg)
5161                         break;
5162         if (bmsafemap) {
5163                 *bmsafemapp = bmsafemap;
5164                 return (1);
5165         }
5166         *bmsafemapp = NULL;
5167
5168         return (0);
5169 }
5170
5171 /*
5172  * Find the bmsafemap associated with a cylinder group buffer.
5173  * If none exists, create one. The buffer must be locked when
5174  * this routine is called and this routine must be called with
5175  * the softdep lock held. To avoid giving up the lock while
5176  * allocating a new bmsafemap, a preallocated bmsafemap may be
5177  * provided. If it is provided but not needed, it is freed.
5178  */
5179 static struct bmsafemap *
5180 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5181         struct mount *mp;
5182         struct buf *bp;
5183         int cg;
5184         struct bmsafemap *newbmsafemap;
5185 {
5186         struct bmsafemap_hashhead *bmsafemaphd;
5187         struct bmsafemap *bmsafemap, *collision;
5188         struct worklist *wk;
5189         struct ufsmount *ump;
5190
5191         ump = VFSTOUFS(mp);
5192         LOCK_OWNED(ump);
5193         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5194         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5195                 if (wk->wk_type == D_BMSAFEMAP) {
5196                         if (newbmsafemap)
5197                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5198                         return (WK_BMSAFEMAP(wk));
5199                 }
5200         }
5201         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5202         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5203                 if (newbmsafemap)
5204                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5205                 return (bmsafemap);
5206         }
5207         if (newbmsafemap) {
5208                 bmsafemap = newbmsafemap;
5209         } else {
5210                 FREE_LOCK(ump);
5211                 bmsafemap = malloc(sizeof(struct bmsafemap),
5212                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5213                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5214                 ACQUIRE_LOCK(ump);
5215         }
5216         bmsafemap->sm_buf = bp;
5217         LIST_INIT(&bmsafemap->sm_inodedephd);
5218         LIST_INIT(&bmsafemap->sm_inodedepwr);
5219         LIST_INIT(&bmsafemap->sm_newblkhd);
5220         LIST_INIT(&bmsafemap->sm_newblkwr);
5221         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5222         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5223         LIST_INIT(&bmsafemap->sm_freehd);
5224         LIST_INIT(&bmsafemap->sm_freewr);
5225         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5226                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5227                 return (collision);
5228         }
5229         bmsafemap->sm_cg = cg;
5230         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5231         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5232         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5233         return (bmsafemap);
5234 }
5235
5236 /*
5237  * Direct block allocation dependencies.
5238  * 
5239  * When a new block is allocated, the corresponding disk locations must be
5240  * initialized (with zeros or new data) before the on-disk inode points to
5241  * them.  Also, the freemap from which the block was allocated must be
5242  * updated (on disk) before the inode's pointer. These two dependencies are
5243  * independent of each other and are needed for all file blocks and indirect
5244  * blocks that are pointed to directly by the inode.  Just before the
5245  * "in-core" version of the inode is updated with a newly allocated block
5246  * number, a procedure (below) is called to setup allocation dependency
5247  * structures.  These structures are removed when the corresponding
5248  * dependencies are satisfied or when the block allocation becomes obsolete
5249  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5250  * fragment that gets upgraded).  All of these cases are handled in
5251  * procedures described later.
5252  * 
5253  * When a file extension causes a fragment to be upgraded, either to a larger
5254  * fragment or to a full block, the on-disk location may change (if the
5255  * previous fragment could not simply be extended). In this case, the old
5256  * fragment must be de-allocated, but not until after the inode's pointer has
5257  * been updated. In most cases, this is handled by later procedures, which
5258  * will construct a "freefrag" structure to be added to the workitem queue
5259  * when the inode update is complete (or obsolete).  The main exception to
5260  * this is when an allocation occurs while a pending allocation dependency
5261  * (for the same block pointer) remains.  This case is handled in the main
5262  * allocation dependency setup procedure by immediately freeing the
5263  * unreferenced fragments.
5264  */ 
5265 void 
5266 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5267         struct inode *ip;       /* inode to which block is being added */
5268         ufs_lbn_t off;          /* block pointer within inode */
5269         ufs2_daddr_t newblkno;  /* disk block number being added */
5270         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5271         long newsize;           /* size of new block */
5272         long oldsize;           /* size of new block */
5273         struct buf *bp;         /* bp for allocated block */
5274 {
5275         struct allocdirect *adp, *oldadp;
5276         struct allocdirectlst *adphead;
5277         struct freefrag *freefrag;
5278         struct inodedep *inodedep;
5279         struct pagedep *pagedep;
5280         struct jnewblk *jnewblk;
5281         struct newblk *newblk;
5282         struct mount *mp;
5283         ufs_lbn_t lbn;
5284
5285         lbn = bp->b_lblkno;
5286         mp = ITOVFS(ip);
5287         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5288             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5289         if (oldblkno && oldblkno != newblkno)
5290                 /*
5291                  * The usual case is that a smaller fragment that
5292                  * was just allocated has been replaced with a bigger
5293                  * fragment or a full-size block. If it is marked as
5294                  * B_DELWRI, the current contents have not been written
5295                  * to disk. It is possible that the block was written
5296                  * earlier, but very uncommon. If the block has never
5297                  * been written, there is no need to send a BIO_DELETE
5298                  * for it when it is freed. The gain from avoiding the
5299                  * TRIMs for the common case of unwritten blocks far
5300                  * exceeds the cost of the write amplification for the
5301                  * uncommon case of failing to send a TRIM for a block
5302                  * that had been written.
5303                  */
5304                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5305                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5306         else
5307                 freefrag = NULL;
5308
5309         CTR6(KTR_SUJ,
5310             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5311             "off %jd newsize %ld oldsize %d",
5312             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5313         ACQUIRE_LOCK(ITOUMP(ip));
5314         if (off >= UFS_NDADDR) {
5315                 if (lbn > 0)
5316                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5317                             lbn, off);
5318                 /* allocating an indirect block */
5319                 if (oldblkno != 0)
5320                         panic("softdep_setup_allocdirect: non-zero indir");
5321         } else {
5322                 if (off != lbn)
5323                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5324                             lbn, off);
5325                 /*
5326                  * Allocating a direct block.
5327                  *
5328                  * If we are allocating a directory block, then we must
5329                  * allocate an associated pagedep to track additions and
5330                  * deletions.
5331                  */
5332                 if ((ip->i_mode & IFMT) == IFDIR)
5333                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5334                             &pagedep);
5335         }
5336         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5337                 panic("softdep_setup_allocdirect: lost block");
5338         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5339             ("softdep_setup_allocdirect: newblk already initialized"));
5340         /*
5341          * Convert the newblk to an allocdirect.
5342          */
5343         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5344         adp = (struct allocdirect *)newblk;
5345         newblk->nb_freefrag = freefrag;
5346         adp->ad_offset = off;
5347         adp->ad_oldblkno = oldblkno;
5348         adp->ad_newsize = newsize;
5349         adp->ad_oldsize = oldsize;
5350
5351         /*
5352          * Finish initializing the journal.
5353          */
5354         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5355                 jnewblk->jn_ino = ip->i_number;
5356                 jnewblk->jn_lbn = lbn;
5357                 add_to_journal(&jnewblk->jn_list);
5358         }
5359         if (freefrag && freefrag->ff_jdep != NULL &&
5360             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5361                 add_to_journal(freefrag->ff_jdep);
5362         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5363         adp->ad_inodedep = inodedep;
5364
5365         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5366         /*
5367          * The list of allocdirects must be kept in sorted and ascending
5368          * order so that the rollback routines can quickly determine the
5369          * first uncommitted block (the size of the file stored on disk
5370          * ends at the end of the lowest committed fragment, or if there
5371          * are no fragments, at the end of the highest committed block).
5372          * Since files generally grow, the typical case is that the new
5373          * block is to be added at the end of the list. We speed this
5374          * special case by checking against the last allocdirect in the
5375          * list before laboriously traversing the list looking for the
5376          * insertion point.
5377          */
5378         adphead = &inodedep->id_newinoupdt;
5379         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5380         if (oldadp == NULL || oldadp->ad_offset <= off) {
5381                 /* insert at end of list */
5382                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5383                 if (oldadp != NULL && oldadp->ad_offset == off)
5384                         allocdirect_merge(adphead, adp, oldadp);
5385                 FREE_LOCK(ITOUMP(ip));
5386                 return;
5387         }
5388         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5389                 if (oldadp->ad_offset >= off)
5390                         break;
5391         }
5392         if (oldadp == NULL)
5393                 panic("softdep_setup_allocdirect: lost entry");
5394         /* insert in middle of list */
5395         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5396         if (oldadp->ad_offset == off)
5397                 allocdirect_merge(adphead, adp, oldadp);
5398
5399         FREE_LOCK(ITOUMP(ip));
5400 }
5401
5402 /*
5403  * Merge a newer and older journal record to be stored either in a
5404  * newblock or freefrag.  This handles aggregating journal records for
5405  * fragment allocation into a second record as well as replacing a
5406  * journal free with an aborted journal allocation.  A segment for the
5407  * oldest record will be placed on wkhd if it has been written.  If not
5408  * the segment for the newer record will suffice.
5409  */
5410 static struct worklist *
5411 jnewblk_merge(new, old, wkhd)
5412         struct worklist *new;
5413         struct worklist *old;
5414         struct workhead *wkhd;
5415 {
5416         struct jnewblk *njnewblk;
5417         struct jnewblk *jnewblk;
5418
5419         /* Handle NULLs to simplify callers. */
5420         if (new == NULL)
5421                 return (old);
5422         if (old == NULL)
5423                 return (new);
5424         /* Replace a jfreefrag with a jnewblk. */
5425         if (new->wk_type == D_JFREEFRAG) {
5426                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5427                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5428                             old, new);
5429                 cancel_jfreefrag(WK_JFREEFRAG(new));
5430                 return (old);
5431         }
5432         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5433                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5434                     old->wk_type, new->wk_type);
5435         /*
5436          * Handle merging of two jnewblk records that describe
5437          * different sets of fragments in the same block.
5438          */
5439         jnewblk = WK_JNEWBLK(old);
5440         njnewblk = WK_JNEWBLK(new);
5441         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5442                 panic("jnewblk_merge: Merging disparate blocks.");
5443         /*
5444          * The record may be rolled back in the cg.
5445          */
5446         if (jnewblk->jn_state & UNDONE) {
5447                 jnewblk->jn_state &= ~UNDONE;
5448                 njnewblk->jn_state |= UNDONE;
5449                 njnewblk->jn_state &= ~ATTACHED;
5450         }
5451         /*
5452          * We modify the newer addref and free the older so that if neither
5453          * has been written the most up-to-date copy will be on disk.  If
5454          * both have been written but rolled back we only temporarily need
5455          * one of them to fix the bits when the cg write completes.
5456          */
5457         jnewblk->jn_state |= ATTACHED | COMPLETE;
5458         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5459         cancel_jnewblk(jnewblk, wkhd);
5460         WORKLIST_REMOVE(&jnewblk->jn_list);
5461         free_jnewblk(jnewblk);
5462         return (new);
5463 }
5464
5465 /*
5466  * Replace an old allocdirect dependency with a newer one.
5467  */
5468 static void
5469 allocdirect_merge(adphead, newadp, oldadp)
5470         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5471         struct allocdirect *newadp;     /* allocdirect being added */
5472         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5473 {
5474         struct worklist *wk;
5475         struct freefrag *freefrag;
5476
5477         freefrag = NULL;
5478         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5479         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5480             newadp->ad_oldsize != oldadp->ad_newsize ||
5481             newadp->ad_offset >= UFS_NDADDR)
5482                 panic("%s %jd != new %jd || old size %ld != new %ld",
5483                     "allocdirect_merge: old blkno",
5484                     (intmax_t)newadp->ad_oldblkno,
5485                     (intmax_t)oldadp->ad_newblkno,
5486                     newadp->ad_oldsize, oldadp->ad_newsize);
5487         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5488         newadp->ad_oldsize = oldadp->ad_oldsize;
5489         /*
5490          * If the old dependency had a fragment to free or had never
5491          * previously had a block allocated, then the new dependency
5492          * can immediately post its freefrag and adopt the old freefrag.
5493          * This action is done by swapping the freefrag dependencies.
5494          * The new dependency gains the old one's freefrag, and the
5495          * old one gets the new one and then immediately puts it on
5496          * the worklist when it is freed by free_newblk. It is
5497          * not possible to do this swap when the old dependency had a
5498          * non-zero size but no previous fragment to free. This condition
5499          * arises when the new block is an extension of the old block.
5500          * Here, the first part of the fragment allocated to the new
5501          * dependency is part of the block currently claimed on disk by
5502          * the old dependency, so cannot legitimately be freed until the
5503          * conditions for the new dependency are fulfilled.
5504          */
5505         freefrag = newadp->ad_freefrag;
5506         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5507                 newadp->ad_freefrag = oldadp->ad_freefrag;
5508                 oldadp->ad_freefrag = freefrag;
5509         }
5510         /*
5511          * If we are tracking a new directory-block allocation,
5512          * move it from the old allocdirect to the new allocdirect.
5513          */
5514         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5515                 WORKLIST_REMOVE(wk);
5516                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5517                         panic("allocdirect_merge: extra newdirblk");
5518                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5519         }
5520         TAILQ_REMOVE(adphead, oldadp, ad_next);
5521         /*
5522          * We need to move any journal dependencies over to the freefrag
5523          * that releases this block if it exists.  Otherwise we are
5524          * extending an existing block and we'll wait until that is
5525          * complete to release the journal space and extend the
5526          * new journal to cover this old space as well.
5527          */
5528         if (freefrag == NULL) {
5529                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5530                         panic("allocdirect_merge: %jd != %jd",
5531                             oldadp->ad_newblkno, newadp->ad_newblkno);
5532                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5533                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5534                     &oldadp->ad_block.nb_jnewblk->jn_list,
5535                     &newadp->ad_block.nb_jwork);
5536                 oldadp->ad_block.nb_jnewblk = NULL;
5537                 cancel_newblk(&oldadp->ad_block, NULL,
5538                     &newadp->ad_block.nb_jwork);
5539         } else {
5540                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5541                     &freefrag->ff_list, &freefrag->ff_jwork);
5542                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5543                     &freefrag->ff_jwork);
5544         }
5545         free_newblk(&oldadp->ad_block);
5546 }
5547
5548 /*
5549  * Allocate a jfreefrag structure to journal a single block free.
5550  */
5551 static struct jfreefrag *
5552 newjfreefrag(freefrag, ip, blkno, size, lbn)
5553         struct freefrag *freefrag;
5554         struct inode *ip;
5555         ufs2_daddr_t blkno;
5556         long size;
5557         ufs_lbn_t lbn;
5558 {
5559         struct jfreefrag *jfreefrag;
5560         struct fs *fs;
5561
5562         fs = ITOFS(ip);
5563         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5564             M_SOFTDEP_FLAGS);
5565         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5566         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5567         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5568         jfreefrag->fr_ino = ip->i_number;
5569         jfreefrag->fr_lbn = lbn;
5570         jfreefrag->fr_blkno = blkno;
5571         jfreefrag->fr_frags = numfrags(fs, size);
5572         jfreefrag->fr_freefrag = freefrag;
5573
5574         return (jfreefrag);
5575 }
5576
5577 /*
5578  * Allocate a new freefrag structure.
5579  */
5580 static struct freefrag *
5581 newfreefrag(ip, blkno, size, lbn, key)
5582         struct inode *ip;
5583         ufs2_daddr_t blkno;
5584         long size;
5585         ufs_lbn_t lbn;
5586         u_long key;
5587 {
5588         struct freefrag *freefrag;
5589         struct ufsmount *ump;
5590         struct fs *fs;
5591
5592         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5593             ip->i_number, blkno, size, lbn);
5594         ump = ITOUMP(ip);
5595         fs = ump->um_fs;
5596         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5597                 panic("newfreefrag: frag size");
5598         freefrag = malloc(sizeof(struct freefrag),
5599             M_FREEFRAG, M_SOFTDEP_FLAGS);
5600         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5601         freefrag->ff_state = ATTACHED;
5602         LIST_INIT(&freefrag->ff_jwork);
5603         freefrag->ff_inum = ip->i_number;
5604         freefrag->ff_vtype = ITOV(ip)->v_type;
5605         freefrag->ff_blkno = blkno;
5606         freefrag->ff_fragsize = size;
5607         freefrag->ff_key = key;
5608
5609         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5610                 freefrag->ff_jdep = (struct worklist *)
5611                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5612         } else {
5613                 freefrag->ff_state |= DEPCOMPLETE;
5614                 freefrag->ff_jdep = NULL;
5615         }
5616
5617         return (freefrag);
5618 }
5619
5620 /*
5621  * This workitem de-allocates fragments that were replaced during
5622  * file block allocation.
5623  */
5624 static void 
5625 handle_workitem_freefrag(freefrag)
5626         struct freefrag *freefrag;
5627 {
5628         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5629         struct workhead wkhd;
5630
5631         CTR3(KTR_SUJ,
5632             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5633             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5634         /*
5635          * It would be illegal to add new completion items to the
5636          * freefrag after it was schedule to be done so it must be
5637          * safe to modify the list head here.
5638          */
5639         LIST_INIT(&wkhd);
5640         ACQUIRE_LOCK(ump);
5641         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5642         /*
5643          * If the journal has not been written we must cancel it here.
5644          */
5645         if (freefrag->ff_jdep) {
5646                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5647                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5648                             freefrag->ff_jdep->wk_type);
5649                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5650         }
5651         FREE_LOCK(ump);
5652         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5653            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5654            &wkhd, freefrag->ff_key);
5655         ACQUIRE_LOCK(ump);
5656         WORKITEM_FREE(freefrag, D_FREEFRAG);
5657         FREE_LOCK(ump);
5658 }
5659
5660 /*
5661  * Set up a dependency structure for an external attributes data block.
5662  * This routine follows much of the structure of softdep_setup_allocdirect.
5663  * See the description of softdep_setup_allocdirect above for details.
5664  */
5665 void 
5666 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5667         struct inode *ip;
5668         ufs_lbn_t off;
5669         ufs2_daddr_t newblkno;
5670         ufs2_daddr_t oldblkno;
5671         long newsize;
5672         long oldsize;
5673         struct buf *bp;
5674 {
5675         struct allocdirect *adp, *oldadp;
5676         struct allocdirectlst *adphead;
5677         struct freefrag *freefrag;
5678         struct inodedep *inodedep;
5679         struct jnewblk *jnewblk;
5680         struct newblk *newblk;
5681         struct mount *mp;
5682         struct ufsmount *ump;
5683         ufs_lbn_t lbn;
5684
5685         mp = ITOVFS(ip);
5686         ump = VFSTOUFS(mp);
5687         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5688             ("softdep_setup_allocext called on non-softdep filesystem"));
5689         KASSERT(off < UFS_NXADDR,
5690             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5691
5692         lbn = bp->b_lblkno;
5693         if (oldblkno && oldblkno != newblkno)
5694                 /*
5695                  * The usual case is that a smaller fragment that
5696                  * was just allocated has been replaced with a bigger
5697                  * fragment or a full-size block. If it is marked as
5698                  * B_DELWRI, the current contents have not been written
5699                  * to disk. It is possible that the block was written
5700                  * earlier, but very uncommon. If the block has never
5701                  * been written, there is no need to send a BIO_DELETE
5702                  * for it when it is freed. The gain from avoiding the
5703                  * TRIMs for the common case of unwritten blocks far
5704                  * exceeds the cost of the write amplification for the
5705                  * uncommon case of failing to send a TRIM for a block
5706                  * that had been written.
5707                  */
5708                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5709                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5710         else
5711                 freefrag = NULL;
5712
5713         ACQUIRE_LOCK(ump);
5714         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5715                 panic("softdep_setup_allocext: lost block");
5716         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5717             ("softdep_setup_allocext: newblk already initialized"));
5718         /*
5719          * Convert the newblk to an allocdirect.
5720          */
5721         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5722         adp = (struct allocdirect *)newblk;
5723         newblk->nb_freefrag = freefrag;
5724         adp->ad_offset = off;
5725         adp->ad_oldblkno = oldblkno;
5726         adp->ad_newsize = newsize;
5727         adp->ad_oldsize = oldsize;
5728         adp->ad_state |=  EXTDATA;
5729
5730         /*
5731          * Finish initializing the journal.
5732          */
5733         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5734                 jnewblk->jn_ino = ip->i_number;
5735                 jnewblk->jn_lbn = lbn;
5736                 add_to_journal(&jnewblk->jn_list);
5737         }
5738         if (freefrag && freefrag->ff_jdep != NULL &&
5739             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5740                 add_to_journal(freefrag->ff_jdep);
5741         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5742         adp->ad_inodedep = inodedep;
5743
5744         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5745         /*
5746          * The list of allocdirects must be kept in sorted and ascending
5747          * order so that the rollback routines can quickly determine the
5748          * first uncommitted block (the size of the file stored on disk
5749          * ends at the end of the lowest committed fragment, or if there
5750          * are no fragments, at the end of the highest committed block).
5751          * Since files generally grow, the typical case is that the new
5752          * block is to be added at the end of the list. We speed this
5753          * special case by checking against the last allocdirect in the
5754          * list before laboriously traversing the list looking for the
5755          * insertion point.
5756          */
5757         adphead = &inodedep->id_newextupdt;
5758         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5759         if (oldadp == NULL || oldadp->ad_offset <= off) {
5760                 /* insert at end of list */
5761                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5762                 if (oldadp != NULL && oldadp->ad_offset == off)
5763                         allocdirect_merge(adphead, adp, oldadp);
5764                 FREE_LOCK(ump);
5765                 return;
5766         }
5767         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5768                 if (oldadp->ad_offset >= off)
5769                         break;
5770         }
5771         if (oldadp == NULL)
5772                 panic("softdep_setup_allocext: lost entry");
5773         /* insert in middle of list */
5774         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5775         if (oldadp->ad_offset == off)
5776                 allocdirect_merge(adphead, adp, oldadp);
5777         FREE_LOCK(ump);
5778 }
5779
5780 /*
5781  * Indirect block allocation dependencies.
5782  * 
5783  * The same dependencies that exist for a direct block also exist when
5784  * a new block is allocated and pointed to by an entry in a block of
5785  * indirect pointers. The undo/redo states described above are also
5786  * used here. Because an indirect block contains many pointers that
5787  * may have dependencies, a second copy of the entire in-memory indirect
5788  * block is kept. The buffer cache copy is always completely up-to-date.
5789  * The second copy, which is used only as a source for disk writes,
5790  * contains only the safe pointers (i.e., those that have no remaining
5791  * update dependencies). The second copy is freed when all pointers
5792  * are safe. The cache is not allowed to replace indirect blocks with
5793  * pending update dependencies. If a buffer containing an indirect
5794  * block with dependencies is written, these routines will mark it
5795  * dirty again. It can only be successfully written once all the
5796  * dependencies are removed. The ffs_fsync routine in conjunction with
5797  * softdep_sync_metadata work together to get all the dependencies
5798  * removed so that a file can be successfully written to disk. Three
5799  * procedures are used when setting up indirect block pointer
5800  * dependencies. The division is necessary because of the organization
5801  * of the "balloc" routine and because of the distinction between file
5802  * pages and file metadata blocks.
5803  */
5804
5805 /*
5806  * Allocate a new allocindir structure.
5807  */
5808 static struct allocindir *
5809 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5810         struct inode *ip;       /* inode for file being extended */
5811         int ptrno;              /* offset of pointer in indirect block */
5812         ufs2_daddr_t newblkno;  /* disk block number being added */
5813         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5814         ufs_lbn_t lbn;
5815 {
5816         struct newblk *newblk;
5817         struct allocindir *aip;
5818         struct freefrag *freefrag;
5819         struct jnewblk *jnewblk;
5820
5821         if (oldblkno)
5822                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5823                     SINGLETON_KEY);
5824         else
5825                 freefrag = NULL;
5826         ACQUIRE_LOCK(ITOUMP(ip));
5827         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5828                 panic("new_allocindir: lost block");
5829         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5830             ("newallocindir: newblk already initialized"));
5831         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5832         newblk->nb_freefrag = freefrag;
5833         aip = (struct allocindir *)newblk;
5834         aip->ai_offset = ptrno;
5835         aip->ai_oldblkno = oldblkno;
5836         aip->ai_lbn = lbn;
5837         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5838                 jnewblk->jn_ino = ip->i_number;
5839                 jnewblk->jn_lbn = lbn;
5840                 add_to_journal(&jnewblk->jn_list);
5841         }
5842         if (freefrag && freefrag->ff_jdep != NULL &&
5843             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5844                 add_to_journal(freefrag->ff_jdep);
5845         return (aip);
5846 }
5847
5848 /*
5849  * Called just before setting an indirect block pointer
5850  * to a newly allocated file page.
5851  */
5852 void
5853 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5854         struct inode *ip;       /* inode for file being extended */
5855         ufs_lbn_t lbn;          /* allocated block number within file */
5856         struct buf *bp;         /* buffer with indirect blk referencing page */
5857         int ptrno;              /* offset of pointer in indirect block */
5858         ufs2_daddr_t newblkno;  /* disk block number being added */
5859         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5860         struct buf *nbp;        /* buffer holding allocated page */
5861 {
5862         struct inodedep *inodedep;
5863         struct freefrag *freefrag;
5864         struct allocindir *aip;
5865         struct pagedep *pagedep;
5866         struct mount *mp;
5867         struct ufsmount *ump;
5868
5869         mp = ITOVFS(ip);
5870         ump = VFSTOUFS(mp);
5871         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5872             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5873         KASSERT(lbn == nbp->b_lblkno,
5874             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5875             lbn, bp->b_lblkno));
5876         CTR4(KTR_SUJ,
5877             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5878             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5879         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5880         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5881         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5882         /*
5883          * If we are allocating a directory page, then we must
5884          * allocate an associated pagedep to track additions and
5885          * deletions.
5886          */
5887         if ((ip->i_mode & IFMT) == IFDIR)
5888                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5889         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5890         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5891         FREE_LOCK(ump);
5892         if (freefrag)
5893                 handle_workitem_freefrag(freefrag);
5894 }
5895
5896 /*
5897  * Called just before setting an indirect block pointer to a
5898  * newly allocated indirect block.
5899  */
5900 void
5901 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5902         struct buf *nbp;        /* newly allocated indirect block */
5903         struct inode *ip;       /* inode for file being extended */
5904         struct buf *bp;         /* indirect block referencing allocated block */
5905         int ptrno;              /* offset of pointer in indirect block */
5906         ufs2_daddr_t newblkno;  /* disk block number being added */
5907 {
5908         struct inodedep *inodedep;
5909         struct allocindir *aip;
5910         struct ufsmount *ump;
5911         ufs_lbn_t lbn;
5912
5913         ump = ITOUMP(ip);
5914         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5915             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5916         CTR3(KTR_SUJ,
5917             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5918             ip->i_number, newblkno, ptrno);
5919         lbn = nbp->b_lblkno;
5920         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5921         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5922         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5923         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5924         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5925                 panic("softdep_setup_allocindir_meta: Block already existed");
5926         FREE_LOCK(ump);
5927 }
5928
5929 static void
5930 indirdep_complete(indirdep)
5931         struct indirdep *indirdep;
5932 {
5933         struct allocindir *aip;
5934
5935         LIST_REMOVE(indirdep, ir_next);
5936         indirdep->ir_state |= DEPCOMPLETE;
5937
5938         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5939                 LIST_REMOVE(aip, ai_next);
5940                 free_newblk(&aip->ai_block);
5941         }
5942         /*
5943          * If this indirdep is not attached to a buf it was simply waiting
5944          * on completion to clear completehd.  free_indirdep() asserts
5945          * that nothing is dangling.
5946          */
5947         if ((indirdep->ir_state & ONWORKLIST) == 0)
5948                 free_indirdep(indirdep);
5949 }
5950
5951 static struct indirdep *
5952 indirdep_lookup(mp, ip, bp)
5953         struct mount *mp;
5954         struct inode *ip;
5955         struct buf *bp;
5956 {
5957         struct indirdep *indirdep, *newindirdep;
5958         struct newblk *newblk;
5959         struct ufsmount *ump;
5960         struct worklist *wk;
5961         struct fs *fs;
5962         ufs2_daddr_t blkno;
5963
5964         ump = VFSTOUFS(mp);
5965         LOCK_OWNED(ump);
5966         indirdep = NULL;
5967         newindirdep = NULL;
5968         fs = ump->um_fs;
5969         for (;;) {
5970                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5971                         if (wk->wk_type != D_INDIRDEP)
5972                                 continue;
5973                         indirdep = WK_INDIRDEP(wk);
5974                         break;
5975                 }
5976                 /* Found on the buffer worklist, no new structure to free. */
5977                 if (indirdep != NULL && newindirdep == NULL)
5978                         return (indirdep);
5979                 if (indirdep != NULL && newindirdep != NULL)
5980                         panic("indirdep_lookup: simultaneous create");
5981                 /* None found on the buffer and a new structure is ready. */
5982                 if (indirdep == NULL && newindirdep != NULL)
5983                         break;
5984                 /* None found and no new structure available. */
5985                 FREE_LOCK(ump);
5986                 newindirdep = malloc(sizeof(struct indirdep),
5987                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5988                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5989                 newindirdep->ir_state = ATTACHED;
5990                 if (I_IS_UFS1(ip))
5991                         newindirdep->ir_state |= UFS1FMT;
5992                 TAILQ_INIT(&newindirdep->ir_trunc);
5993                 newindirdep->ir_saveddata = NULL;
5994                 LIST_INIT(&newindirdep->ir_deplisthd);
5995                 LIST_INIT(&newindirdep->ir_donehd);
5996                 LIST_INIT(&newindirdep->ir_writehd);
5997                 LIST_INIT(&newindirdep->ir_completehd);
5998                 if (bp->b_blkno == bp->b_lblkno) {
5999                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6000                             NULL, NULL);
6001                         bp->b_blkno = blkno;
6002                 }
6003                 newindirdep->ir_freeblks = NULL;
6004                 newindirdep->ir_savebp =
6005                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6006                 newindirdep->ir_bp = bp;
6007                 BUF_KERNPROC(newindirdep->ir_savebp);
6008                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6009                 ACQUIRE_LOCK(ump);
6010         }
6011         indirdep = newindirdep;
6012         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6013         /*
6014          * If the block is not yet allocated we don't set DEPCOMPLETE so
6015          * that we don't free dependencies until the pointers are valid.
6016          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6017          * than using the hash.
6018          */
6019         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6020                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6021         else
6022                 indirdep->ir_state |= DEPCOMPLETE;
6023         return (indirdep);
6024 }
6025
6026 /*
6027  * Called to finish the allocation of the "aip" allocated
6028  * by one of the two routines above.
6029  */
6030 static struct freefrag *
6031 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6032         struct buf *bp;         /* in-memory copy of the indirect block */
6033         struct inode *ip;       /* inode for file being extended */
6034         struct inodedep *inodedep; /* Inodedep for ip */
6035         struct allocindir *aip; /* allocindir allocated by the above routines */
6036         ufs_lbn_t lbn;          /* Logical block number for this block. */
6037 {
6038         struct fs *fs;
6039         struct indirdep *indirdep;
6040         struct allocindir *oldaip;
6041         struct freefrag *freefrag;
6042         struct mount *mp;
6043         struct ufsmount *ump;
6044
6045         mp = ITOVFS(ip);
6046         ump = VFSTOUFS(mp);
6047         LOCK_OWNED(ump);
6048         fs = ump->um_fs;
6049         if (bp->b_lblkno >= 0)
6050                 panic("setup_allocindir_phase2: not indir blk");
6051         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6052             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6053         indirdep = indirdep_lookup(mp, ip, bp);
6054         KASSERT(indirdep->ir_savebp != NULL,
6055             ("setup_allocindir_phase2 NULL ir_savebp"));
6056         aip->ai_indirdep = indirdep;
6057         /*
6058          * Check for an unwritten dependency for this indirect offset.  If
6059          * there is, merge the old dependency into the new one.  This happens
6060          * as a result of reallocblk only.
6061          */
6062         freefrag = NULL;
6063         if (aip->ai_oldblkno != 0) {
6064                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6065                         if (oldaip->ai_offset == aip->ai_offset) {
6066                                 freefrag = allocindir_merge(aip, oldaip);
6067                                 goto done;
6068                         }
6069                 }
6070                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6071                         if (oldaip->ai_offset == aip->ai_offset) {
6072                                 freefrag = allocindir_merge(aip, oldaip);
6073                                 goto done;
6074                         }
6075                 }
6076         }
6077 done:
6078         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6079         return (freefrag);
6080 }
6081
6082 /*
6083  * Merge two allocindirs which refer to the same block.  Move newblock
6084  * dependencies and setup the freefrags appropriately.
6085  */
6086 static struct freefrag *
6087 allocindir_merge(aip, oldaip)
6088         struct allocindir *aip;
6089         struct allocindir *oldaip;
6090 {
6091         struct freefrag *freefrag;
6092         struct worklist *wk;
6093
6094         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6095                 panic("allocindir_merge: blkno");
6096         aip->ai_oldblkno = oldaip->ai_oldblkno;
6097         freefrag = aip->ai_freefrag;
6098         aip->ai_freefrag = oldaip->ai_freefrag;
6099         oldaip->ai_freefrag = NULL;
6100         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6101         /*
6102          * If we are tracking a new directory-block allocation,
6103          * move it from the old allocindir to the new allocindir.
6104          */
6105         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6106                 WORKLIST_REMOVE(wk);
6107                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6108                         panic("allocindir_merge: extra newdirblk");
6109                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6110         }
6111         /*
6112          * We can skip journaling for this freefrag and just complete
6113          * any pending journal work for the allocindir that is being
6114          * removed after the freefrag completes.
6115          */
6116         if (freefrag->ff_jdep)
6117                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6118         LIST_REMOVE(oldaip, ai_next);
6119         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6120             &freefrag->ff_list, &freefrag->ff_jwork);
6121         free_newblk(&oldaip->ai_block);
6122
6123         return (freefrag);
6124 }
6125
6126 static inline void
6127 setup_freedirect(freeblks, ip, i, needj)
6128         struct freeblks *freeblks;
6129         struct inode *ip;
6130         int i;
6131         int needj;
6132 {
6133         struct ufsmount *ump;
6134         ufs2_daddr_t blkno;
6135         int frags;
6136
6137         blkno = DIP(ip, i_db[i]);
6138         if (blkno == 0)
6139                 return;
6140         DIP_SET(ip, i_db[i], 0);
6141         ump = ITOUMP(ip);
6142         frags = sblksize(ump->um_fs, ip->i_size, i);
6143         frags = numfrags(ump->um_fs, frags);
6144         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6145 }
6146
6147 static inline void
6148 setup_freeext(freeblks, ip, i, needj)
6149         struct freeblks *freeblks;
6150         struct inode *ip;
6151         int i;
6152         int needj;
6153 {
6154         struct ufsmount *ump;
6155         ufs2_daddr_t blkno;
6156         int frags;
6157
6158         blkno = ip->i_din2->di_extb[i];
6159         if (blkno == 0)
6160                 return;
6161         ip->i_din2->di_extb[i] = 0;
6162         ump = ITOUMP(ip);
6163         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6164         frags = numfrags(ump->um_fs, frags);
6165         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6166 }
6167
6168 static inline void
6169 setup_freeindir(freeblks, ip, i, lbn, needj)
6170         struct freeblks *freeblks;
6171         struct inode *ip;
6172         int i;
6173         ufs_lbn_t lbn;
6174         int needj;
6175 {
6176         struct ufsmount *ump;
6177         ufs2_daddr_t blkno;
6178
6179         blkno = DIP(ip, i_ib[i]);
6180         if (blkno == 0)
6181                 return;
6182         DIP_SET(ip, i_ib[i], 0);
6183         ump = ITOUMP(ip);
6184         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6185             0, needj);
6186 }
6187
6188 static inline struct freeblks *
6189 newfreeblks(mp, ip)
6190         struct mount *mp;
6191         struct inode *ip;
6192 {
6193         struct freeblks *freeblks;
6194
6195         freeblks = malloc(sizeof(struct freeblks),
6196                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6197         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6198         LIST_INIT(&freeblks->fb_jblkdephd);
6199         LIST_INIT(&freeblks->fb_jwork);
6200         freeblks->fb_ref = 0;
6201         freeblks->fb_cgwait = 0;
6202         freeblks->fb_state = ATTACHED;
6203         freeblks->fb_uid = ip->i_uid;
6204         freeblks->fb_inum = ip->i_number;
6205         freeblks->fb_vtype = ITOV(ip)->v_type;
6206         freeblks->fb_modrev = DIP(ip, i_modrev);
6207         freeblks->fb_devvp = ITODEVVP(ip);
6208         freeblks->fb_chkcnt = 0;
6209         freeblks->fb_len = 0;
6210
6211         return (freeblks);
6212 }
6213
6214 static void
6215 trunc_indirdep(indirdep, freeblks, bp, off)
6216         struct indirdep *indirdep;
6217         struct freeblks *freeblks;
6218         struct buf *bp;
6219         int off;
6220 {
6221         struct allocindir *aip, *aipn;
6222
6223         /*
6224          * The first set of allocindirs won't be in savedbp.
6225          */
6226         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6227                 if (aip->ai_offset > off)
6228                         cancel_allocindir(aip, bp, freeblks, 1);
6229         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6230                 if (aip->ai_offset > off)
6231                         cancel_allocindir(aip, bp, freeblks, 1);
6232         /*
6233          * These will exist in savedbp.
6234          */
6235         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6236                 if (aip->ai_offset > off)
6237                         cancel_allocindir(aip, NULL, freeblks, 0);
6238         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6239                 if (aip->ai_offset > off)
6240                         cancel_allocindir(aip, NULL, freeblks, 0);
6241 }
6242
6243 /*
6244  * Follow the chain of indirects down to lastlbn creating a freework
6245  * structure for each.  This will be used to start indir_trunc() at
6246  * the right offset and create the journal records for the parrtial
6247  * truncation.  A second step will handle the truncated dependencies.
6248  */
6249 static int
6250 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6251         struct freeblks *freeblks;
6252         struct inode *ip;
6253         ufs_lbn_t lbn;
6254         ufs_lbn_t lastlbn;
6255         ufs2_daddr_t blkno;
6256 {
6257         struct indirdep *indirdep;
6258         struct indirdep *indirn;
6259         struct freework *freework;
6260         struct newblk *newblk;
6261         struct mount *mp;
6262         struct ufsmount *ump;
6263         struct buf *bp;
6264         uint8_t *start;
6265         uint8_t *end;
6266         ufs_lbn_t lbnadd;
6267         int level;
6268         int error;
6269         int off;
6270
6271
6272         freework = NULL;
6273         if (blkno == 0)
6274                 return (0);
6275         mp = freeblks->fb_list.wk_mp;
6276         ump = VFSTOUFS(mp);
6277         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6278         if ((bp->b_flags & B_CACHE) == 0) {
6279                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6280                 bp->b_iocmd = BIO_READ;
6281                 bp->b_flags &= ~B_INVAL;
6282                 bp->b_ioflags &= ~BIO_ERROR;
6283                 vfs_busy_pages(bp, 0);
6284                 bp->b_iooffset = dbtob(bp->b_blkno);
6285                 bstrategy(bp);
6286 #ifdef RACCT
6287                 if (racct_enable) {
6288                         PROC_LOCK(curproc);
6289                         racct_add_buf(curproc, bp, 0);
6290                         PROC_UNLOCK(curproc);
6291                 }
6292 #endif /* RACCT */
6293                 curthread->td_ru.ru_inblock++;
6294                 error = bufwait(bp);
6295                 if (error) {
6296                         brelse(bp);
6297                         return (error);
6298                 }
6299         }
6300         level = lbn_level(lbn);
6301         lbnadd = lbn_offset(ump->um_fs, level);
6302         /*
6303          * Compute the offset of the last block we want to keep.  Store
6304          * in the freework the first block we want to completely free.
6305          */
6306         off = (lastlbn - -(lbn + level)) / lbnadd;
6307         if (off + 1 == NINDIR(ump->um_fs))
6308                 goto nowork;
6309         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6310         /*
6311          * Link the freework into the indirdep.  This will prevent any new
6312          * allocations from proceeding until we are finished with the
6313          * truncate and the block is written.
6314          */
6315         ACQUIRE_LOCK(ump);
6316         indirdep = indirdep_lookup(mp, ip, bp);
6317         if (indirdep->ir_freeblks)
6318                 panic("setup_trunc_indir: indirdep already truncated.");
6319         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6320         freework->fw_indir = indirdep;
6321         /*
6322          * Cancel any allocindirs that will not make it to disk.
6323          * We have to do this for all copies of the indirdep that
6324          * live on this newblk.
6325          */
6326         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6327                 if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6328                     &newblk) == 0)
6329                         panic("setup_trunc_indir: lost block");
6330                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6331                         trunc_indirdep(indirn, freeblks, bp, off);
6332         } else
6333                 trunc_indirdep(indirdep, freeblks, bp, off);
6334         FREE_LOCK(ump);
6335         /*
6336          * Creation is protected by the buf lock. The saveddata is only
6337          * needed if a full truncation follows a partial truncation but it
6338          * is difficult to allocate in that case so we fetch it anyway.
6339          */
6340         if (indirdep->ir_saveddata == NULL)
6341                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6342                     M_SOFTDEP_FLAGS);
6343 nowork:
6344         /* Fetch the blkno of the child and the zero start offset. */
6345         if (I_IS_UFS1(ip)) {
6346                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6347                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6348         } else {
6349                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6350                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6351         }
6352         if (freework) {
6353                 /* Zero the truncated pointers. */
6354                 end = bp->b_data + bp->b_bcount;
6355                 bzero(start, end - start);
6356                 bdwrite(bp);
6357         } else
6358                 bqrelse(bp);
6359         if (level == 0)
6360                 return (0);
6361         lbn++; /* adjust level */
6362         lbn -= (off * lbnadd);
6363         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6364 }
6365
6366 /*
6367  * Complete the partial truncation of an indirect block setup by
6368  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6369  * copy and writes them to disk before the freeblks is allowed to complete.
6370  */
6371 static void
6372 complete_trunc_indir(freework)
6373         struct freework *freework;
6374 {
6375         struct freework *fwn;
6376         struct indirdep *indirdep;
6377         struct ufsmount *ump;
6378         struct buf *bp;
6379         uintptr_t start;
6380         int count;
6381
6382         ump = VFSTOUFS(freework->fw_list.wk_mp);
6383         LOCK_OWNED(ump);
6384         indirdep = freework->fw_indir;
6385         for (;;) {
6386                 bp = indirdep->ir_bp;
6387                 /* See if the block was discarded. */
6388                 if (bp == NULL)
6389                         break;
6390                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6391                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6392                         break;
6393                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6394                     LOCK_PTR(ump)) == 0)
6395                         BUF_UNLOCK(bp);
6396                 ACQUIRE_LOCK(ump);
6397         }
6398         freework->fw_state |= DEPCOMPLETE;
6399         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6400         /*
6401          * Zero the pointers in the saved copy.
6402          */
6403         if (indirdep->ir_state & UFS1FMT)
6404                 start = sizeof(ufs1_daddr_t);
6405         else
6406                 start = sizeof(ufs2_daddr_t);
6407         start *= freework->fw_start;
6408         count = indirdep->ir_savebp->b_bcount - start;
6409         start += (uintptr_t)indirdep->ir_savebp->b_data;
6410         bzero((char *)start, count);
6411         /*
6412          * We need to start the next truncation in the list if it has not
6413          * been started yet.
6414          */
6415         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6416         if (fwn != NULL) {
6417                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6418                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6419                 if ((fwn->fw_state & ONWORKLIST) == 0)
6420                         freework_enqueue(fwn);
6421         }
6422         /*
6423          * If bp is NULL the block was fully truncated, restore
6424          * the saved block list otherwise free it if it is no
6425          * longer needed.
6426          */
6427         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6428                 if (bp == NULL)
6429                         bcopy(indirdep->ir_saveddata,
6430                             indirdep->ir_savebp->b_data,
6431                             indirdep->ir_savebp->b_bcount);
6432                 free(indirdep->ir_saveddata, M_INDIRDEP);
6433                 indirdep->ir_saveddata = NULL;
6434         }
6435         /*
6436          * When bp is NULL there is a full truncation pending.  We
6437          * must wait for this full truncation to be journaled before
6438          * we can release this freework because the disk pointers will
6439          * never be written as zero.
6440          */
6441         if (bp == NULL)  {
6442                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6443                         handle_written_freework(freework);
6444                 else
6445                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6446                            &freework->fw_list);
6447         } else {
6448                 /* Complete when the real copy is written. */
6449                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6450                 BUF_UNLOCK(bp);
6451         }
6452 }
6453
6454 /*
6455  * Calculate the number of blocks we are going to release where datablocks
6456  * is the current total and length is the new file size.
6457  */
6458 static ufs2_daddr_t
6459 blkcount(fs, datablocks, length)
6460         struct fs *fs;
6461         ufs2_daddr_t datablocks;
6462         off_t length;
6463 {
6464         off_t totblks, numblks;
6465
6466         totblks = 0;
6467         numblks = howmany(length, fs->fs_bsize);
6468         if (numblks <= UFS_NDADDR) {
6469                 totblks = howmany(length, fs->fs_fsize);
6470                 goto out;
6471         }
6472         totblks = blkstofrags(fs, numblks);
6473         numblks -= UFS_NDADDR;
6474         /*
6475          * Count all single, then double, then triple indirects required.
6476          * Subtracting one indirects worth of blocks for each pass
6477          * acknowledges one of each pointed to by the inode.
6478          */
6479         for (;;) {
6480                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6481                 numblks -= NINDIR(fs);
6482                 if (numblks <= 0)
6483                         break;
6484                 numblks = howmany(numblks, NINDIR(fs));
6485         }
6486 out:
6487         totblks = fsbtodb(fs, totblks);
6488         /*
6489          * Handle sparse files.  We can't reclaim more blocks than the inode
6490          * references.  We will correct it later in handle_complete_freeblks()
6491          * when we know the real count.
6492          */
6493         if (totblks > datablocks)
6494                 return (0);
6495         return (datablocks - totblks);
6496 }
6497
6498 /*
6499  * Handle freeblocks for journaled softupdate filesystems.
6500  *
6501  * Contrary to normal softupdates, we must preserve the block pointers in
6502  * indirects until their subordinates are free.  This is to avoid journaling
6503  * every block that is freed which may consume more space than the journal
6504  * itself.  The recovery program will see the free block journals at the
6505  * base of the truncated area and traverse them to reclaim space.  The
6506  * pointers in the inode may be cleared immediately after the journal
6507  * records are written because each direct and indirect pointer in the
6508  * inode is recorded in a journal.  This permits full truncation to proceed
6509  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6510  *
6511  * The algorithm is as follows:
6512  * 1) Traverse the in-memory state and create journal entries to release
6513  *    the relevant blocks and full indirect trees.
6514  * 2) Traverse the indirect block chain adding partial truncation freework
6515  *    records to indirects in the path to lastlbn.  The freework will
6516  *    prevent new allocation dependencies from being satisfied in this
6517  *    indirect until the truncation completes.
6518  * 3) Read and lock the inode block, performing an update with the new size
6519  *    and pointers.  This prevents truncated data from becoming valid on
6520  *    disk through step 4.
6521  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6522  *    eliminate journal work for those records that do not require it.
6523  * 5) Schedule the journal records to be written followed by the inode block.
6524  * 6) Allocate any necessary frags for the end of file.
6525  * 7) Zero any partially truncated blocks.
6526  *
6527  * From this truncation proceeds asynchronously using the freework and
6528  * indir_trunc machinery.  The file will not be extended again into a
6529  * partially truncated indirect block until all work is completed but
6530  * the normal dependency mechanism ensures that it is rolled back/forward
6531  * as appropriate.  Further truncation may occur without delay and is
6532  * serialized in indir_trunc().
6533  */
6534 void
6535 softdep_journal_freeblocks(ip, cred, length, flags)
6536         struct inode *ip;       /* The inode whose length is to be reduced */
6537         struct ucred *cred;
6538         off_t length;           /* The new length for the file */
6539         int flags;              /* IO_EXT and/or IO_NORMAL */
6540 {
6541         struct freeblks *freeblks, *fbn;
6542         struct worklist *wk, *wkn;
6543         struct inodedep *inodedep;
6544         struct jblkdep *jblkdep;
6545         struct allocdirect *adp, *adpn;
6546         struct ufsmount *ump;
6547         struct fs *fs;
6548         struct buf *bp;
6549         struct vnode *vp;
6550         struct mount *mp;
6551         ufs2_daddr_t extblocks, datablocks;
6552         ufs_lbn_t tmpval, lbn, lastlbn;
6553         int frags, lastoff, iboff, allocblock, needj, error, i;
6554
6555         ump = ITOUMP(ip);
6556         mp = UFSTOVFS(ump);
6557         fs = ump->um_fs;
6558         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6559             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6560         vp = ITOV(ip);
6561         needj = 1;
6562         iboff = -1;
6563         allocblock = 0;
6564         extblocks = 0;
6565         datablocks = 0;
6566         frags = 0;
6567         freeblks = newfreeblks(mp, ip);
6568         ACQUIRE_LOCK(ump);
6569         /*
6570          * If we're truncating a removed file that will never be written
6571          * we don't need to journal the block frees.  The canceled journals
6572          * for the allocations will suffice.
6573          */
6574         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6575         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6576             length == 0)
6577                 needj = 0;
6578         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6579             ip->i_number, length, needj);
6580         FREE_LOCK(ump);
6581         /*
6582          * Calculate the lbn that we are truncating to.  This results in -1
6583          * if we're truncating the 0 bytes.  So it is the last lbn we want
6584          * to keep, not the first lbn we want to truncate.
6585          */
6586         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6587         lastoff = blkoff(fs, length);
6588         /*
6589          * Compute frags we are keeping in lastlbn.  0 means all.
6590          */
6591         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6592                 frags = fragroundup(fs, lastoff);
6593                 /* adp offset of last valid allocdirect. */
6594                 iboff = lastlbn;
6595         } else if (lastlbn > 0)
6596                 iboff = UFS_NDADDR;
6597         if (fs->fs_magic == FS_UFS2_MAGIC)
6598                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6599         /*
6600          * Handle normal data blocks and indirects.  This section saves
6601          * values used after the inode update to complete frag and indirect
6602          * truncation.
6603          */
6604         if ((flags & IO_NORMAL) != 0) {
6605                 /*
6606                  * Handle truncation of whole direct and indirect blocks.
6607                  */
6608                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6609                         setup_freedirect(freeblks, ip, i, needj);
6610                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6611                     i < UFS_NIADDR;
6612                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6613                         /* Release a whole indirect tree. */
6614                         if (lbn > lastlbn) {
6615                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6616                                     needj);
6617                                 continue;
6618                         }
6619                         iboff = i + UFS_NDADDR;
6620                         /*
6621                          * Traverse partially truncated indirect tree.
6622                          */
6623                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6624                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6625                                     lastlbn, DIP(ip, i_ib[i]));
6626                 }
6627                 /*
6628                  * Handle partial truncation to a frag boundary.
6629                  */
6630                 if (frags) {
6631                         ufs2_daddr_t blkno;
6632                         long oldfrags;
6633
6634                         oldfrags = blksize(fs, ip, lastlbn);
6635                         blkno = DIP(ip, i_db[lastlbn]);
6636                         if (blkno && oldfrags != frags) {
6637                                 oldfrags -= frags;
6638                                 oldfrags = numfrags(fs, oldfrags);
6639                                 blkno += numfrags(fs, frags);
6640                                 newfreework(ump, freeblks, NULL, lastlbn,
6641                                     blkno, oldfrags, 0, needj);
6642                                 if (needj)
6643                                         adjust_newfreework(freeblks,
6644                                             numfrags(fs, frags));
6645                         } else if (blkno == 0)
6646                                 allocblock = 1;
6647                 }
6648                 /*
6649                  * Add a journal record for partial truncate if we are
6650                  * handling indirect blocks.  Non-indirects need no extra
6651                  * journaling.
6652                  */
6653                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6654                         ip->i_flag |= IN_TRUNCATED;
6655                         newjtrunc(freeblks, length, 0);
6656                 }
6657                 ip->i_size = length;
6658                 DIP_SET(ip, i_size, ip->i_size);
6659                 datablocks = DIP(ip, i_blocks) - extblocks;
6660                 if (length != 0)
6661                         datablocks = blkcount(fs, datablocks, length);
6662                 freeblks->fb_len = length;
6663         }
6664         if ((flags & IO_EXT) != 0) {
6665                 for (i = 0; i < UFS_NXADDR; i++)
6666                         setup_freeext(freeblks, ip, i, needj);
6667                 ip->i_din2->di_extsize = 0;
6668                 datablocks += extblocks;
6669         }
6670 #ifdef QUOTA
6671         /* Reference the quotas in case the block count is wrong in the end. */
6672         quotaref(vp, freeblks->fb_quota);
6673         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6674 #endif
6675         freeblks->fb_chkcnt = -datablocks;
6676         UFS_LOCK(ump);
6677         fs->fs_pendingblocks += datablocks;
6678         UFS_UNLOCK(ump);
6679         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6680         /*
6681          * Handle truncation of incomplete alloc direct dependencies.  We
6682          * hold the inode block locked to prevent incomplete dependencies
6683          * from reaching the disk while we are eliminating those that
6684          * have been truncated.  This is a partially inlined ffs_update().
6685          */
6686         ufs_itimes(vp);
6687         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6688         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6689             (int)fs->fs_bsize, cred, &bp);
6690         if (error) {
6691                 brelse(bp);
6692                 softdep_error("softdep_journal_freeblocks", error);
6693                 return;
6694         }
6695         if (bp->b_bufsize == fs->fs_bsize)
6696                 bp->b_flags |= B_CLUSTEROK;
6697         softdep_update_inodeblock(ip, bp, 0);
6698         if (ump->um_fstype == UFS1)
6699                 *((struct ufs1_dinode *)bp->b_data +
6700                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6701         else
6702                 *((struct ufs2_dinode *)bp->b_data +
6703                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6704         ACQUIRE_LOCK(ump);
6705         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6706         if ((inodedep->id_state & IOSTARTED) != 0)
6707                 panic("softdep_setup_freeblocks: inode busy");
6708         /*
6709          * Add the freeblks structure to the list of operations that
6710          * must await the zero'ed inode being written to disk. If we
6711          * still have a bitmap dependency (needj), then the inode
6712          * has never been written to disk, so we can process the
6713          * freeblks below once we have deleted the dependencies.
6714          */
6715         if (needj)
6716                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6717         else
6718                 freeblks->fb_state |= COMPLETE;
6719         if ((flags & IO_NORMAL) != 0) {
6720                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6721                         if (adp->ad_offset > iboff)
6722                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6723                                     freeblks);
6724                         /*
6725                          * Truncate the allocdirect.  We could eliminate
6726                          * or modify journal records as well.
6727                          */
6728                         else if (adp->ad_offset == iboff && frags)
6729                                 adp->ad_newsize = frags;
6730                 }
6731         }
6732         if ((flags & IO_EXT) != 0)
6733                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6734                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6735                             freeblks);
6736         /*
6737          * Scan the bufwait list for newblock dependencies that will never
6738          * make it to disk.
6739          */
6740         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6741                 if (wk->wk_type != D_ALLOCDIRECT)
6742                         continue;
6743                 adp = WK_ALLOCDIRECT(wk);
6744                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6745                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6746                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6747                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6748                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6749                 }
6750         }
6751         /*
6752          * Add journal work.
6753          */
6754         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6755                 add_to_journal(&jblkdep->jb_list);
6756         FREE_LOCK(ump);
6757         bdwrite(bp);
6758         /*
6759          * Truncate dependency structures beyond length.
6760          */
6761         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6762         /*
6763          * This is only set when we need to allocate a fragment because
6764          * none existed at the end of a frag-sized file.  It handles only
6765          * allocating a new, zero filled block.
6766          */
6767         if (allocblock) {
6768                 ip->i_size = length - lastoff;
6769                 DIP_SET(ip, i_size, ip->i_size);
6770                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6771                 if (error != 0) {
6772                         softdep_error("softdep_journal_freeblks", error);
6773                         return;
6774                 }
6775                 ip->i_size = length;
6776                 DIP_SET(ip, i_size, length);
6777                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6778                 allocbuf(bp, frags);
6779                 ffs_update(vp, 0);
6780                 bawrite(bp);
6781         } else if (lastoff != 0 && vp->v_type != VDIR) {
6782                 int size;
6783
6784                 /*
6785                  * Zero the end of a truncated frag or block.
6786                  */
6787                 size = sblksize(fs, length, lastlbn);
6788                 error = bread(vp, lastlbn, size, cred, &bp);
6789                 if (error) {
6790                         softdep_error("softdep_journal_freeblks", error);
6791                         return;
6792                 }
6793                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6794                 bawrite(bp);
6795
6796         }
6797         ACQUIRE_LOCK(ump);
6798         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6799         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6800         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6801         /*
6802          * We zero earlier truncations so they don't erroneously
6803          * update i_blocks.
6804          */
6805         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6806                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6807                         fbn->fb_len = 0;
6808         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6809             LIST_EMPTY(&freeblks->fb_jblkdephd))
6810                 freeblks->fb_state |= INPROGRESS;
6811         else
6812                 freeblks = NULL;
6813         FREE_LOCK(ump);
6814         if (freeblks)
6815                 handle_workitem_freeblocks(freeblks, 0);
6816         trunc_pages(ip, length, extblocks, flags);
6817
6818 }
6819
6820 /*
6821  * Flush a JOP_SYNC to the journal.
6822  */
6823 void
6824 softdep_journal_fsync(ip)
6825         struct inode *ip;
6826 {
6827         struct jfsync *jfsync;
6828         struct ufsmount *ump;
6829
6830         ump = ITOUMP(ip);
6831         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6832             ("softdep_journal_fsync called on non-softdep filesystem"));
6833         if ((ip->i_flag & IN_TRUNCATED) == 0)
6834                 return;
6835         ip->i_flag &= ~IN_TRUNCATED;
6836         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6837         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6838         jfsync->jfs_size = ip->i_size;
6839         jfsync->jfs_ino = ip->i_number;
6840         ACQUIRE_LOCK(ump);
6841         add_to_journal(&jfsync->jfs_list);
6842         jwait(&jfsync->jfs_list, MNT_WAIT);
6843         FREE_LOCK(ump);
6844 }
6845
6846 /*
6847  * Block de-allocation dependencies.
6848  * 
6849  * When blocks are de-allocated, the on-disk pointers must be nullified before
6850  * the blocks are made available for use by other files.  (The true
6851  * requirement is that old pointers must be nullified before new on-disk
6852  * pointers are set.  We chose this slightly more stringent requirement to
6853  * reduce complexity.) Our implementation handles this dependency by updating
6854  * the inode (or indirect block) appropriately but delaying the actual block
6855  * de-allocation (i.e., freemap and free space count manipulation) until
6856  * after the updated versions reach stable storage.  After the disk is
6857  * updated, the blocks can be safely de-allocated whenever it is convenient.
6858  * This implementation handles only the common case of reducing a file's
6859  * length to zero. Other cases are handled by the conventional synchronous
6860  * write approach.
6861  *
6862  * The ffs implementation with which we worked double-checks
6863  * the state of the block pointers and file size as it reduces
6864  * a file's length.  Some of this code is replicated here in our
6865  * soft updates implementation.  The freeblks->fb_chkcnt field is
6866  * used to transfer a part of this information to the procedure
6867  * that eventually de-allocates the blocks.
6868  *
6869  * This routine should be called from the routine that shortens
6870  * a file's length, before the inode's size or block pointers
6871  * are modified. It will save the block pointer information for
6872  * later release and zero the inode so that the calling routine
6873  * can release it.
6874  */
6875 void
6876 softdep_setup_freeblocks(ip, length, flags)
6877         struct inode *ip;       /* The inode whose length is to be reduced */
6878         off_t length;           /* The new length for the file */
6879         int flags;              /* IO_EXT and/or IO_NORMAL */
6880 {
6881         struct ufs1_dinode *dp1;
6882         struct ufs2_dinode *dp2;
6883         struct freeblks *freeblks;
6884         struct inodedep *inodedep;
6885         struct allocdirect *adp;
6886         struct ufsmount *ump;
6887         struct buf *bp;
6888         struct fs *fs;
6889         ufs2_daddr_t extblocks, datablocks;
6890         struct mount *mp;
6891         int i, delay, error;
6892         ufs_lbn_t tmpval;
6893         ufs_lbn_t lbn;
6894
6895         ump = ITOUMP(ip);
6896         mp = UFSTOVFS(ump);
6897         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6898             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6899         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6900             ip->i_number, length);
6901         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6902         fs = ump->um_fs;
6903         if ((error = bread(ump->um_devvp,
6904             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6905             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6906                 brelse(bp);
6907                 softdep_error("softdep_setup_freeblocks", error);
6908                 return;
6909         }
6910         freeblks = newfreeblks(mp, ip);
6911         extblocks = 0;
6912         datablocks = 0;
6913         if (fs->fs_magic == FS_UFS2_MAGIC)
6914                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6915         if ((flags & IO_NORMAL) != 0) {
6916                 for (i = 0; i < UFS_NDADDR; i++)
6917                         setup_freedirect(freeblks, ip, i, 0);
6918                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6919                     i < UFS_NIADDR;
6920                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6921                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6922                 ip->i_size = 0;
6923                 DIP_SET(ip, i_size, 0);
6924                 datablocks = DIP(ip, i_blocks) - extblocks;
6925         }
6926         if ((flags & IO_EXT) != 0) {
6927                 for (i = 0; i < UFS_NXADDR; i++)
6928                         setup_freeext(freeblks, ip, i, 0);
6929                 ip->i_din2->di_extsize = 0;
6930                 datablocks += extblocks;
6931         }
6932 #ifdef QUOTA
6933         /* Reference the quotas in case the block count is wrong in the end. */
6934         quotaref(ITOV(ip), freeblks->fb_quota);
6935         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6936 #endif
6937         freeblks->fb_chkcnt = -datablocks;
6938         UFS_LOCK(ump);
6939         fs->fs_pendingblocks += datablocks;
6940         UFS_UNLOCK(ump);
6941         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6942         /*
6943          * Push the zero'ed inode to its disk buffer so that we are free
6944          * to delete its dependencies below. Once the dependencies are gone
6945          * the buffer can be safely released.
6946          */
6947         if (ump->um_fstype == UFS1) {
6948                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6949                     ino_to_fsbo(fs, ip->i_number));
6950                 ip->i_din1->di_freelink = dp1->di_freelink;
6951                 *dp1 = *ip->i_din1;
6952         } else {
6953                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6954                     ino_to_fsbo(fs, ip->i_number));
6955                 ip->i_din2->di_freelink = dp2->di_freelink;
6956                 *dp2 = *ip->i_din2;
6957         }
6958         /*
6959          * Find and eliminate any inode dependencies.
6960          */
6961         ACQUIRE_LOCK(ump);
6962         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6963         if ((inodedep->id_state & IOSTARTED) != 0)
6964                 panic("softdep_setup_freeblocks: inode busy");
6965         /*
6966          * Add the freeblks structure to the list of operations that
6967          * must await the zero'ed inode being written to disk. If we
6968          * still have a bitmap dependency (delay == 0), then the inode
6969          * has never been written to disk, so we can process the
6970          * freeblks below once we have deleted the dependencies.
6971          */
6972         delay = (inodedep->id_state & DEPCOMPLETE);
6973         if (delay)
6974                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6975         else
6976                 freeblks->fb_state |= COMPLETE;
6977         /*
6978          * Because the file length has been truncated to zero, any
6979          * pending block allocation dependency structures associated
6980          * with this inode are obsolete and can simply be de-allocated.
6981          * We must first merge the two dependency lists to get rid of
6982          * any duplicate freefrag structures, then purge the merged list.
6983          * If we still have a bitmap dependency, then the inode has never
6984          * been written to disk, so we can free any fragments without delay.
6985          */
6986         if (flags & IO_NORMAL) {
6987                 merge_inode_lists(&inodedep->id_newinoupdt,
6988                     &inodedep->id_inoupdt);
6989                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6990                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6991                             freeblks);
6992         }
6993         if (flags & IO_EXT) {
6994                 merge_inode_lists(&inodedep->id_newextupdt,
6995                     &inodedep->id_extupdt);
6996                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6997                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6998                             freeblks);
6999         }
7000         FREE_LOCK(ump);
7001         bdwrite(bp);
7002         trunc_dependencies(ip, freeblks, -1, 0, flags);
7003         ACQUIRE_LOCK(ump);
7004         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7005                 (void) free_inodedep(inodedep);
7006         freeblks->fb_state |= DEPCOMPLETE;
7007         /*
7008          * If the inode with zeroed block pointers is now on disk
7009          * we can start freeing blocks.
7010          */  
7011         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7012                 freeblks->fb_state |= INPROGRESS;
7013         else
7014                 freeblks = NULL;
7015         FREE_LOCK(ump);
7016         if (freeblks)
7017                 handle_workitem_freeblocks(freeblks, 0);
7018         trunc_pages(ip, length, extblocks, flags);
7019 }
7020
7021 /*
7022  * Eliminate pages from the page cache that back parts of this inode and
7023  * adjust the vnode pager's idea of our size.  This prevents stale data
7024  * from hanging around in the page cache.
7025  */
7026 static void
7027 trunc_pages(ip, length, extblocks, flags)
7028         struct inode *ip;
7029         off_t length;
7030         ufs2_daddr_t extblocks;
7031         int flags;
7032 {
7033         struct vnode *vp;
7034         struct fs *fs;
7035         ufs_lbn_t lbn;
7036         off_t end, extend;
7037
7038         vp = ITOV(ip);
7039         fs = ITOFS(ip);
7040         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7041         if ((flags & IO_EXT) != 0)
7042                 vn_pages_remove(vp, extend, 0);
7043         if ((flags & IO_NORMAL) == 0)
7044                 return;
7045         BO_LOCK(&vp->v_bufobj);
7046         drain_output(vp);
7047         BO_UNLOCK(&vp->v_bufobj);
7048         /*
7049          * The vnode pager eliminates file pages we eliminate indirects
7050          * below.
7051          */
7052         vnode_pager_setsize(vp, length);
7053         /*
7054          * Calculate the end based on the last indirect we want to keep.  If
7055          * the block extends into indirects we can just use the negative of
7056          * its lbn.  Doubles and triples exist at lower numbers so we must
7057          * be careful not to remove those, if they exist.  double and triple
7058          * indirect lbns do not overlap with others so it is not important
7059          * to verify how many levels are required.
7060          */
7061         lbn = lblkno(fs, length);
7062         if (lbn >= UFS_NDADDR) {
7063                 /* Calculate the virtual lbn of the triple indirect. */
7064                 lbn = -lbn - (UFS_NIADDR - 1);
7065                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7066         } else
7067                 end = extend;
7068         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7069 }
7070
7071 /*
7072  * See if the buf bp is in the range eliminated by truncation.
7073  */
7074 static int
7075 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7076         struct buf *bp;
7077         int *blkoffp;
7078         ufs_lbn_t lastlbn;
7079         int lastoff;
7080         int flags;
7081 {
7082         ufs_lbn_t lbn;
7083
7084         *blkoffp = 0;
7085         /* Only match ext/normal blocks as appropriate. */
7086         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7087             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7088                 return (0);
7089         /* ALTDATA is always a full truncation. */
7090         if ((bp->b_xflags & BX_ALTDATA) != 0)
7091                 return (1);
7092         /* -1 is full truncation. */
7093         if (lastlbn == -1)
7094                 return (1);
7095         /*
7096          * If this is a partial truncate we only want those
7097          * blocks and indirect blocks that cover the range
7098          * we're after.
7099          */
7100         lbn = bp->b_lblkno;
7101         if (lbn < 0)
7102                 lbn = -(lbn + lbn_level(lbn));
7103         if (lbn < lastlbn)
7104                 return (0);
7105         /* Here we only truncate lblkno if it's partial. */
7106         if (lbn == lastlbn) {
7107                 if (lastoff == 0)
7108                         return (0);
7109                 *blkoffp = lastoff;
7110         }
7111         return (1);
7112 }
7113
7114 /*
7115  * Eliminate any dependencies that exist in memory beyond lblkno:off
7116  */
7117 static void
7118 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7119         struct inode *ip;
7120         struct freeblks *freeblks;
7121         ufs_lbn_t lastlbn;
7122         int lastoff;
7123         int flags;
7124 {
7125         struct bufobj *bo;
7126         struct vnode *vp;
7127         struct buf *bp;
7128         int blkoff;
7129
7130         /*
7131          * We must wait for any I/O in progress to finish so that
7132          * all potential buffers on the dirty list will be visible.
7133          * Once they are all there, walk the list and get rid of
7134          * any dependencies.
7135          */
7136         vp = ITOV(ip);
7137         bo = &vp->v_bufobj;
7138         BO_LOCK(bo);
7139         drain_output(vp);
7140         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7141                 bp->b_vflags &= ~BV_SCANNED;
7142 restart:
7143         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7144                 if (bp->b_vflags & BV_SCANNED)
7145                         continue;
7146                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7147                         bp->b_vflags |= BV_SCANNED;
7148                         continue;
7149                 }
7150                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7151                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7152                         goto restart;
7153                 BO_UNLOCK(bo);
7154                 if (deallocate_dependencies(bp, freeblks, blkoff))
7155                         bqrelse(bp);
7156                 else
7157                         brelse(bp);
7158                 BO_LOCK(bo);
7159                 goto restart;
7160         }
7161         /*
7162          * Now do the work of vtruncbuf while also matching indirect blocks.
7163          */
7164         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7165                 bp->b_vflags &= ~BV_SCANNED;
7166 cleanrestart:
7167         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7168                 if (bp->b_vflags & BV_SCANNED)
7169                         continue;
7170                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7171                         bp->b_vflags |= BV_SCANNED;
7172                         continue;
7173                 }
7174                 if (BUF_LOCK(bp,
7175                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7176                     BO_LOCKPTR(bo)) == ENOLCK) {
7177                         BO_LOCK(bo);
7178                         goto cleanrestart;
7179                 }
7180                 bp->b_vflags |= BV_SCANNED;
7181                 bremfree(bp);
7182                 if (blkoff != 0) {
7183                         allocbuf(bp, blkoff);
7184                         bqrelse(bp);
7185                 } else {
7186                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7187                         brelse(bp);
7188                 }
7189                 BO_LOCK(bo);
7190                 goto cleanrestart;
7191         }
7192         drain_output(vp);
7193         BO_UNLOCK(bo);
7194 }
7195
7196 static int
7197 cancel_pagedep(pagedep, freeblks, blkoff)
7198         struct pagedep *pagedep;
7199         struct freeblks *freeblks;
7200         int blkoff;
7201 {
7202         struct jremref *jremref;
7203         struct jmvref *jmvref;
7204         struct dirrem *dirrem, *tmp;
7205         int i;
7206
7207         /*
7208          * Copy any directory remove dependencies to the list
7209          * to be processed after the freeblks proceeds.  If
7210          * directory entry never made it to disk they
7211          * can be dumped directly onto the work list.
7212          */
7213         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7214                 /* Skip this directory removal if it is intended to remain. */
7215                 if (dirrem->dm_offset < blkoff)
7216                         continue;
7217                 /*
7218                  * If there are any dirrems we wait for the journal write
7219                  * to complete and then restart the buf scan as the lock
7220                  * has been dropped.
7221                  */
7222                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7223                         jwait(&jremref->jr_list, MNT_WAIT);
7224                         return (ERESTART);
7225                 }
7226                 LIST_REMOVE(dirrem, dm_next);
7227                 dirrem->dm_dirinum = pagedep->pd_ino;
7228                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7229         }
7230         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7231                 jwait(&jmvref->jm_list, MNT_WAIT);
7232                 return (ERESTART);
7233         }
7234         /*
7235          * When we're partially truncating a pagedep we just want to flush
7236          * journal entries and return.  There can not be any adds in the
7237          * truncated portion of the directory and newblk must remain if
7238          * part of the block remains.
7239          */
7240         if (blkoff != 0) {
7241                 struct diradd *dap;
7242
7243                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7244                         if (dap->da_offset > blkoff)
7245                                 panic("cancel_pagedep: diradd %p off %d > %d",
7246                                     dap, dap->da_offset, blkoff);
7247                 for (i = 0; i < DAHASHSZ; i++)
7248                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7249                                 if (dap->da_offset > blkoff)
7250                                         panic("cancel_pagedep: diradd %p off %d > %d",
7251                                             dap, dap->da_offset, blkoff);
7252                 return (0);
7253         }
7254         /*
7255          * There should be no directory add dependencies present
7256          * as the directory could not be truncated until all
7257          * children were removed.
7258          */
7259         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7260             ("deallocate_dependencies: pendinghd != NULL"));
7261         for (i = 0; i < DAHASHSZ; i++)
7262                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7263                     ("deallocate_dependencies: diraddhd != NULL"));
7264         if ((pagedep->pd_state & NEWBLOCK) != 0)
7265                 free_newdirblk(pagedep->pd_newdirblk);
7266         if (free_pagedep(pagedep) == 0)
7267                 panic("Failed to free pagedep %p", pagedep);
7268         return (0);
7269 }
7270
7271 /*
7272  * Reclaim any dependency structures from a buffer that is about to
7273  * be reallocated to a new vnode. The buffer must be locked, thus,
7274  * no I/O completion operations can occur while we are manipulating
7275  * its associated dependencies. The mutex is held so that other I/O's
7276  * associated with related dependencies do not occur.
7277  */
7278 static int
7279 deallocate_dependencies(bp, freeblks, off)
7280         struct buf *bp;
7281         struct freeblks *freeblks;
7282         int off;
7283 {
7284         struct indirdep *indirdep;
7285         struct pagedep *pagedep;
7286         struct worklist *wk, *wkn;
7287         struct ufsmount *ump;
7288
7289         ump = softdep_bp_to_mp(bp);
7290         if (ump == NULL)
7291                 goto done;
7292         ACQUIRE_LOCK(ump);
7293         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7294                 switch (wk->wk_type) {
7295                 case D_INDIRDEP:
7296                         indirdep = WK_INDIRDEP(wk);
7297                         if (bp->b_lblkno >= 0 ||
7298                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7299                                 panic("deallocate_dependencies: not indir");
7300                         cancel_indirdep(indirdep, bp, freeblks);
7301                         continue;
7302
7303                 case D_PAGEDEP:
7304                         pagedep = WK_PAGEDEP(wk);
7305                         if (cancel_pagedep(pagedep, freeblks, off)) {
7306                                 FREE_LOCK(ump);
7307                                 return (ERESTART);
7308                         }
7309                         continue;
7310
7311                 case D_ALLOCINDIR:
7312                         /*
7313                          * Simply remove the allocindir, we'll find it via
7314                          * the indirdep where we can clear pointers if
7315                          * needed.
7316                          */
7317                         WORKLIST_REMOVE(wk);
7318                         continue;
7319
7320                 case D_FREEWORK:
7321                         /*
7322                          * A truncation is waiting for the zero'd pointers
7323                          * to be written.  It can be freed when the freeblks
7324                          * is journaled.
7325                          */
7326                         WORKLIST_REMOVE(wk);
7327                         wk->wk_state |= ONDEPLIST;
7328                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7329                         break;
7330
7331                 case D_ALLOCDIRECT:
7332                         if (off != 0)
7333                                 continue;
7334                         /* FALLTHROUGH */
7335                 default:
7336                         panic("deallocate_dependencies: Unexpected type %s",
7337                             TYPENAME(wk->wk_type));
7338                         /* NOTREACHED */
7339                 }
7340         }
7341         FREE_LOCK(ump);
7342 done:
7343         /*
7344          * Don't throw away this buf, we were partially truncating and
7345          * some deps may always remain.
7346          */
7347         if (off) {
7348                 allocbuf(bp, off);
7349                 bp->b_vflags |= BV_SCANNED;
7350                 return (EBUSY);
7351         }
7352         bp->b_flags |= B_INVAL | B_NOCACHE;
7353
7354         return (0);
7355 }
7356
7357 /*
7358  * An allocdirect is being canceled due to a truncate.  We must make sure
7359  * the journal entry is released in concert with the blkfree that releases
7360  * the storage.  Completed journal entries must not be released until the
7361  * space is no longer pointed to by the inode or in the bitmap.
7362  */
7363 static void
7364 cancel_allocdirect(adphead, adp, freeblks)
7365         struct allocdirectlst *adphead;
7366         struct allocdirect *adp;
7367         struct freeblks *freeblks;
7368 {
7369         struct freework *freework;
7370         struct newblk *newblk;
7371         struct worklist *wk;
7372
7373         TAILQ_REMOVE(adphead, adp, ad_next);
7374         newblk = (struct newblk *)adp;
7375         freework = NULL;
7376         /*
7377          * Find the correct freework structure.
7378          */
7379         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7380                 if (wk->wk_type != D_FREEWORK)
7381                         continue;
7382                 freework = WK_FREEWORK(wk);
7383                 if (freework->fw_blkno == newblk->nb_newblkno)
7384                         break;
7385         }
7386         if (freework == NULL)
7387                 panic("cancel_allocdirect: Freework not found");
7388         /*
7389          * If a newblk exists at all we still have the journal entry that
7390          * initiated the allocation so we do not need to journal the free.
7391          */
7392         cancel_jfreeblk(freeblks, freework->fw_blkno);
7393         /*
7394          * If the journal hasn't been written the jnewblk must be passed
7395          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7396          * this by linking the journal dependency into the freework to be
7397          * freed when freework_freeblock() is called.  If the journal has
7398          * been written we can simply reclaim the journal space when the
7399          * freeblks work is complete.
7400          */
7401         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7402             &freeblks->fb_jwork);
7403         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7404 }
7405
7406
7407 /*
7408  * Cancel a new block allocation.  May be an indirect or direct block.  We
7409  * remove it from various lists and return any journal record that needs to
7410  * be resolved by the caller.
7411  *
7412  * A special consideration is made for indirects which were never pointed
7413  * at on disk and will never be found once this block is released.
7414  */
7415 static struct jnewblk *
7416 cancel_newblk(newblk, wk, wkhd)
7417         struct newblk *newblk;
7418         struct worklist *wk;
7419         struct workhead *wkhd;
7420 {
7421         struct jnewblk *jnewblk;
7422
7423         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7424             
7425         newblk->nb_state |= GOINGAWAY;
7426         /*
7427          * Previously we traversed the completedhd on each indirdep
7428          * attached to this newblk to cancel them and gather journal
7429          * work.  Since we need only the oldest journal segment and
7430          * the lowest point on the tree will always have the oldest
7431          * journal segment we are free to release the segments
7432          * of any subordinates and may leave the indirdep list to
7433          * indirdep_complete() when this newblk is freed.
7434          */
7435         if (newblk->nb_state & ONDEPLIST) {
7436                 newblk->nb_state &= ~ONDEPLIST;
7437                 LIST_REMOVE(newblk, nb_deps);
7438         }
7439         if (newblk->nb_state & ONWORKLIST)
7440                 WORKLIST_REMOVE(&newblk->nb_list);
7441         /*
7442          * If the journal entry hasn't been written we save a pointer to
7443          * the dependency that frees it until it is written or the
7444          * superseding operation completes.
7445          */
7446         jnewblk = newblk->nb_jnewblk;
7447         if (jnewblk != NULL && wk != NULL) {
7448                 newblk->nb_jnewblk = NULL;
7449                 jnewblk->jn_dep = wk;
7450         }
7451         if (!LIST_EMPTY(&newblk->nb_jwork))
7452                 jwork_move(wkhd, &newblk->nb_jwork);
7453         /*
7454          * When truncating we must free the newdirblk early to remove
7455          * the pagedep from the hash before returning.
7456          */
7457         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7458                 free_newdirblk(WK_NEWDIRBLK(wk));
7459         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7460                 panic("cancel_newblk: extra newdirblk");
7461
7462         return (jnewblk);
7463 }
7464
7465 /*
7466  * Schedule the freefrag associated with a newblk to be released once
7467  * the pointers are written and the previous block is no longer needed.
7468  */
7469 static void
7470 newblk_freefrag(newblk)
7471         struct newblk *newblk;
7472 {
7473         struct freefrag *freefrag;
7474
7475         if (newblk->nb_freefrag == NULL)
7476                 return;
7477         freefrag = newblk->nb_freefrag;
7478         newblk->nb_freefrag = NULL;
7479         freefrag->ff_state |= COMPLETE;
7480         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7481                 add_to_worklist(&freefrag->ff_list, 0);
7482 }
7483
7484 /*
7485  * Free a newblk. Generate a new freefrag work request if appropriate.
7486  * This must be called after the inode pointer and any direct block pointers
7487  * are valid or fully removed via truncate or frag extension.
7488  */
7489 static void
7490 free_newblk(newblk)
7491         struct newblk *newblk;
7492 {
7493         struct indirdep *indirdep;
7494         struct worklist *wk;
7495
7496         KASSERT(newblk->nb_jnewblk == NULL,
7497             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7498         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7499             ("free_newblk: unclaimed newblk"));
7500         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7501         newblk_freefrag(newblk);
7502         if (newblk->nb_state & ONDEPLIST)
7503                 LIST_REMOVE(newblk, nb_deps);
7504         if (newblk->nb_state & ONWORKLIST)
7505                 WORKLIST_REMOVE(&newblk->nb_list);
7506         LIST_REMOVE(newblk, nb_hash);
7507         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7508                 free_newdirblk(WK_NEWDIRBLK(wk));
7509         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7510                 panic("free_newblk: extra newdirblk");
7511         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7512                 indirdep_complete(indirdep);
7513         handle_jwork(&newblk->nb_jwork);
7514         WORKITEM_FREE(newblk, D_NEWBLK);
7515 }
7516
7517 /*
7518  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7519  */
7520 static void
7521 free_newdirblk(newdirblk)
7522         struct newdirblk *newdirblk;
7523 {
7524         struct pagedep *pagedep;
7525         struct diradd *dap;
7526         struct worklist *wk;
7527
7528         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7529         WORKLIST_REMOVE(&newdirblk->db_list);
7530         /*
7531          * If the pagedep is still linked onto the directory buffer
7532          * dependency chain, then some of the entries on the
7533          * pd_pendinghd list may not be committed to disk yet. In
7534          * this case, we will simply clear the NEWBLOCK flag and
7535          * let the pd_pendinghd list be processed when the pagedep
7536          * is next written. If the pagedep is no longer on the buffer
7537          * dependency chain, then all the entries on the pd_pending
7538          * list are committed to disk and we can free them here.
7539          */
7540         pagedep = newdirblk->db_pagedep;
7541         pagedep->pd_state &= ~NEWBLOCK;
7542         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7543                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7544                         free_diradd(dap, NULL);
7545                 /*
7546                  * If no dependencies remain, the pagedep will be freed.
7547                  */
7548                 free_pagedep(pagedep);
7549         }
7550         /* Should only ever be one item in the list. */
7551         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7552                 WORKLIST_REMOVE(wk);
7553                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7554         }
7555         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7556 }
7557
7558 /*
7559  * Prepare an inode to be freed. The actual free operation is not
7560  * done until the zero'ed inode has been written to disk.
7561  */
7562 void
7563 softdep_freefile(pvp, ino, mode)
7564         struct vnode *pvp;
7565         ino_t ino;
7566         int mode;
7567 {
7568         struct inode *ip = VTOI(pvp);
7569         struct inodedep *inodedep;
7570         struct freefile *freefile;
7571         struct freeblks *freeblks;
7572         struct ufsmount *ump;
7573
7574         ump = ITOUMP(ip);
7575         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7576             ("softdep_freefile called on non-softdep filesystem"));
7577         /*
7578          * This sets up the inode de-allocation dependency.
7579          */
7580         freefile = malloc(sizeof(struct freefile),
7581                 M_FREEFILE, M_SOFTDEP_FLAGS);
7582         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7583         freefile->fx_mode = mode;
7584         freefile->fx_oldinum = ino;
7585         freefile->fx_devvp = ump->um_devvp;
7586         LIST_INIT(&freefile->fx_jwork);
7587         UFS_LOCK(ump);
7588         ump->um_fs->fs_pendinginodes += 1;
7589         UFS_UNLOCK(ump);
7590
7591         /*
7592          * If the inodedep does not exist, then the zero'ed inode has
7593          * been written to disk. If the allocated inode has never been
7594          * written to disk, then the on-disk inode is zero'ed. In either
7595          * case we can free the file immediately.  If the journal was
7596          * canceled before being written the inode will never make it to
7597          * disk and we must send the canceled journal entrys to
7598          * ffs_freefile() to be cleared in conjunction with the bitmap.
7599          * Any blocks waiting on the inode to write can be safely freed
7600          * here as it will never been written.
7601          */
7602         ACQUIRE_LOCK(ump);
7603         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7604         if (inodedep) {
7605                 /*
7606                  * Clear out freeblks that no longer need to reference
7607                  * this inode.
7608                  */
7609                 while ((freeblks =
7610                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7611                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7612                             fb_next);
7613                         freeblks->fb_state &= ~ONDEPLIST;
7614                 }
7615                 /*
7616                  * Remove this inode from the unlinked list.
7617                  */
7618                 if (inodedep->id_state & UNLINKED) {
7619                         /*
7620                          * Save the journal work to be freed with the bitmap
7621                          * before we clear UNLINKED.  Otherwise it can be lost
7622                          * if the inode block is written.
7623                          */
7624                         handle_bufwait(inodedep, &freefile->fx_jwork);
7625                         clear_unlinked_inodedep(inodedep);
7626                         /*
7627                          * Re-acquire inodedep as we've dropped the
7628                          * per-filesystem lock in clear_unlinked_inodedep().
7629                          */
7630                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7631                 }
7632         }
7633         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7634                 FREE_LOCK(ump);
7635                 handle_workitem_freefile(freefile);
7636                 return;
7637         }
7638         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7639                 inodedep->id_state |= GOINGAWAY;
7640         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7641         FREE_LOCK(ump);
7642         if (ip->i_number == ino)
7643                 ip->i_flag |= IN_MODIFIED;
7644 }
7645
7646 /*
7647  * Check to see if an inode has never been written to disk. If
7648  * so free the inodedep and return success, otherwise return failure.
7649  *
7650  * If we still have a bitmap dependency, then the inode has never
7651  * been written to disk. Drop the dependency as it is no longer
7652  * necessary since the inode is being deallocated. We set the
7653  * ALLCOMPLETE flags since the bitmap now properly shows that the
7654  * inode is not allocated. Even if the inode is actively being
7655  * written, it has been rolled back to its zero'ed state, so we
7656  * are ensured that a zero inode is what is on the disk. For short
7657  * lived files, this change will usually result in removing all the
7658  * dependencies from the inode so that it can be freed immediately.
7659  */
7660 static int
7661 check_inode_unwritten(inodedep)
7662         struct inodedep *inodedep;
7663 {
7664
7665         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7666
7667         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7668             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7669             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7670             !LIST_EMPTY(&inodedep->id_bufwait) ||
7671             !LIST_EMPTY(&inodedep->id_inowait) ||
7672             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7673             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7674             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7675             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7676             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7677             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7678             inodedep->id_mkdiradd != NULL || 
7679             inodedep->id_nlinkdelta != 0)
7680                 return (0);
7681         /*
7682          * Another process might be in initiate_write_inodeblock_ufs[12]
7683          * trying to allocate memory without holding "Softdep Lock".
7684          */
7685         if ((inodedep->id_state & IOSTARTED) != 0 &&
7686             inodedep->id_savedino1 == NULL)
7687                 return (0);
7688
7689         if (inodedep->id_state & ONDEPLIST)
7690                 LIST_REMOVE(inodedep, id_deps);
7691         inodedep->id_state &= ~ONDEPLIST;
7692         inodedep->id_state |= ALLCOMPLETE;
7693         inodedep->id_bmsafemap = NULL;
7694         if (inodedep->id_state & ONWORKLIST)
7695                 WORKLIST_REMOVE(&inodedep->id_list);
7696         if (inodedep->id_savedino1 != NULL) {
7697                 free(inodedep->id_savedino1, M_SAVEDINO);
7698                 inodedep->id_savedino1 = NULL;
7699         }
7700         if (free_inodedep(inodedep) == 0)
7701                 panic("check_inode_unwritten: busy inode");
7702         return (1);
7703 }
7704
7705 static int
7706 check_inodedep_free(inodedep)
7707         struct inodedep *inodedep;
7708 {
7709
7710         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7711         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7712             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7713             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7714             !LIST_EMPTY(&inodedep->id_bufwait) ||
7715             !LIST_EMPTY(&inodedep->id_inowait) ||
7716             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7717             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7718             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7719             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7720             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7721             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7722             inodedep->id_mkdiradd != NULL ||
7723             inodedep->id_nlinkdelta != 0 ||
7724             inodedep->id_savedino1 != NULL)
7725                 return (0);
7726         return (1);
7727 }
7728
7729 /*
7730  * Try to free an inodedep structure. Return 1 if it could be freed.
7731  */
7732 static int
7733 free_inodedep(inodedep)
7734         struct inodedep *inodedep;
7735 {
7736
7737         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7738         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7739             !check_inodedep_free(inodedep))
7740                 return (0);
7741         if (inodedep->id_state & ONDEPLIST)
7742                 LIST_REMOVE(inodedep, id_deps);
7743         LIST_REMOVE(inodedep, id_hash);
7744         WORKITEM_FREE(inodedep, D_INODEDEP);
7745         return (1);
7746 }
7747
7748 /*
7749  * Free the block referenced by a freework structure.  The parent freeblks
7750  * structure is released and completed when the final cg bitmap reaches
7751  * the disk.  This routine may be freeing a jnewblk which never made it to
7752  * disk in which case we do not have to wait as the operation is undone
7753  * in memory immediately.
7754  */
7755 static void
7756 freework_freeblock(freework, key)
7757         struct freework *freework;
7758         u_long key;
7759 {
7760         struct freeblks *freeblks;
7761         struct jnewblk *jnewblk;
7762         struct ufsmount *ump;
7763         struct workhead wkhd;
7764         struct fs *fs;
7765         int bsize;
7766         int needj;
7767
7768         ump = VFSTOUFS(freework->fw_list.wk_mp);
7769         LOCK_OWNED(ump);
7770         /*
7771          * Handle partial truncate separately.
7772          */
7773         if (freework->fw_indir) {
7774                 complete_trunc_indir(freework);
7775                 return;
7776         }
7777         freeblks = freework->fw_freeblks;
7778         fs = ump->um_fs;
7779         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7780         bsize = lfragtosize(fs, freework->fw_frags);
7781         LIST_INIT(&wkhd);
7782         /*
7783          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7784          * on the indirblk hashtable and prevents premature freeing.
7785          */
7786         freework->fw_state |= DEPCOMPLETE;
7787         /*
7788          * SUJ needs to wait for the segment referencing freed indirect
7789          * blocks to expire so that we know the checker will not confuse
7790          * a re-allocated indirect block with its old contents.
7791          */
7792         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7793                 indirblk_insert(freework);
7794         /*
7795          * If we are canceling an existing jnewblk pass it to the free
7796          * routine, otherwise pass the freeblk which will ultimately
7797          * release the freeblks.  If we're not journaling, we can just
7798          * free the freeblks immediately.
7799          */
7800         jnewblk = freework->fw_jnewblk;
7801         if (jnewblk != NULL) {
7802                 cancel_jnewblk(jnewblk, &wkhd);
7803                 needj = 0;
7804         } else if (needj) {
7805                 freework->fw_state |= DELAYEDFREE;
7806                 freeblks->fb_cgwait++;
7807                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7808         }
7809         FREE_LOCK(ump);
7810         freeblks_free(ump, freeblks, btodb(bsize));
7811         CTR4(KTR_SUJ,
7812             "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7813             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7814         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7815             freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7816         ACQUIRE_LOCK(ump);
7817         /*
7818          * The jnewblk will be discarded and the bits in the map never
7819          * made it to disk.  We can immediately free the freeblk.
7820          */
7821         if (needj == 0)
7822                 handle_written_freework(freework);
7823 }
7824
7825 /*
7826  * We enqueue freework items that need processing back on the freeblks and
7827  * add the freeblks to the worklist.  This makes it easier to find all work
7828  * required to flush a truncation in process_truncates().
7829  */
7830 static void
7831 freework_enqueue(freework)
7832         struct freework *freework;
7833 {
7834         struct freeblks *freeblks;
7835
7836         freeblks = freework->fw_freeblks;
7837         if ((freework->fw_state & INPROGRESS) == 0)
7838                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7839         if ((freeblks->fb_state &
7840             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7841             LIST_EMPTY(&freeblks->fb_jblkdephd))
7842                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7843 }
7844
7845 /*
7846  * Start, continue, or finish the process of freeing an indirect block tree.
7847  * The free operation may be paused at any point with fw_off containing the
7848  * offset to restart from.  This enables us to implement some flow control
7849  * for large truncates which may fan out and generate a huge number of
7850  * dependencies.
7851  */
7852 static void
7853 handle_workitem_indirblk(freework)
7854         struct freework *freework;
7855 {
7856         struct freeblks *freeblks;
7857         struct ufsmount *ump;
7858         struct fs *fs;
7859
7860         freeblks = freework->fw_freeblks;
7861         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7862         fs = ump->um_fs;
7863         if (freework->fw_state & DEPCOMPLETE) {
7864                 handle_written_freework(freework);
7865                 return;
7866         }
7867         if (freework->fw_off == NINDIR(fs)) {
7868                 freework_freeblock(freework, SINGLETON_KEY);
7869                 return;
7870         }
7871         freework->fw_state |= INPROGRESS;
7872         FREE_LOCK(ump);
7873         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7874             freework->fw_lbn);
7875         ACQUIRE_LOCK(ump);
7876 }
7877
7878 /*
7879  * Called when a freework structure attached to a cg buf is written.  The
7880  * ref on either the parent or the freeblks structure is released and
7881  * the freeblks is added back to the worklist if there is more work to do.
7882  */
7883 static void
7884 handle_written_freework(freework)
7885         struct freework *freework;
7886 {
7887         struct freeblks *freeblks;
7888         struct freework *parent;
7889
7890         freeblks = freework->fw_freeblks;
7891         parent = freework->fw_parent;
7892         if (freework->fw_state & DELAYEDFREE)
7893                 freeblks->fb_cgwait--;
7894         freework->fw_state |= COMPLETE;
7895         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7896                 WORKITEM_FREE(freework, D_FREEWORK);
7897         if (parent) {
7898                 if (--parent->fw_ref == 0)
7899                         freework_enqueue(parent);
7900                 return;
7901         }
7902         if (--freeblks->fb_ref != 0)
7903                 return;
7904         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7905             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7906                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7907 }
7908
7909 /*
7910  * This workitem routine performs the block de-allocation.
7911  * The workitem is added to the pending list after the updated
7912  * inode block has been written to disk.  As mentioned above,
7913  * checks regarding the number of blocks de-allocated (compared
7914  * to the number of blocks allocated for the file) are also
7915  * performed in this function.
7916  */
7917 static int
7918 handle_workitem_freeblocks(freeblks, flags)
7919         struct freeblks *freeblks;
7920         int flags;
7921 {
7922         struct freework *freework;
7923         struct newblk *newblk;
7924         struct allocindir *aip;
7925         struct ufsmount *ump;
7926         struct worklist *wk;
7927         u_long key;
7928
7929         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7930             ("handle_workitem_freeblocks: Journal entries not written."));
7931         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7932         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7933         ACQUIRE_LOCK(ump);
7934         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7935                 WORKLIST_REMOVE(wk);
7936                 switch (wk->wk_type) {
7937                 case D_DIRREM:
7938                         wk->wk_state |= COMPLETE;
7939                         add_to_worklist(wk, 0);
7940                         continue;
7941
7942                 case D_ALLOCDIRECT:
7943                         free_newblk(WK_NEWBLK(wk));
7944                         continue;
7945
7946                 case D_ALLOCINDIR:
7947                         aip = WK_ALLOCINDIR(wk);
7948                         freework = NULL;
7949                         if (aip->ai_state & DELAYEDFREE) {
7950                                 FREE_LOCK(ump);
7951                                 freework = newfreework(ump, freeblks, NULL,
7952                                     aip->ai_lbn, aip->ai_newblkno,
7953                                     ump->um_fs->fs_frag, 0, 0);
7954                                 ACQUIRE_LOCK(ump);
7955                         }
7956                         newblk = WK_NEWBLK(wk);
7957                         if (newblk->nb_jnewblk) {
7958                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7959                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7960                                 newblk->nb_jnewblk = NULL;
7961                         }
7962                         free_newblk(newblk);
7963                         continue;
7964
7965                 case D_FREEWORK:
7966                         freework = WK_FREEWORK(wk);
7967                         if (freework->fw_lbn <= -UFS_NDADDR)
7968                                 handle_workitem_indirblk(freework);
7969                         else
7970                                 freework_freeblock(freework, key);
7971                         continue;
7972                 default:
7973                         panic("handle_workitem_freeblocks: Unknown type %s",
7974                             TYPENAME(wk->wk_type));
7975                 }
7976         }
7977         if (freeblks->fb_ref != 0) {
7978                 freeblks->fb_state &= ~INPROGRESS;
7979                 wake_worklist(&freeblks->fb_list);
7980                 freeblks = NULL;
7981         }
7982         FREE_LOCK(ump);
7983         ffs_blkrelease_finish(ump, key);
7984         if (freeblks)
7985                 return handle_complete_freeblocks(freeblks, flags);
7986         return (0);
7987 }
7988
7989 /*
7990  * Handle completion of block free via truncate.  This allows fs_pending
7991  * to track the actual free block count more closely than if we only updated
7992  * it at the end.  We must be careful to handle cases where the block count
7993  * on free was incorrect.
7994  */
7995 static void
7996 freeblks_free(ump, freeblks, blocks)
7997         struct ufsmount *ump;
7998         struct freeblks *freeblks;
7999         int blocks;
8000 {
8001         struct fs *fs;
8002         ufs2_daddr_t remain;
8003
8004         UFS_LOCK(ump);
8005         remain = -freeblks->fb_chkcnt;
8006         freeblks->fb_chkcnt += blocks;
8007         if (remain > 0) {
8008                 if (remain < blocks)
8009                         blocks = remain;
8010                 fs = ump->um_fs;
8011                 fs->fs_pendingblocks -= blocks;
8012         }
8013         UFS_UNLOCK(ump);
8014 }
8015
8016 /*
8017  * Once all of the freework workitems are complete we can retire the
8018  * freeblocks dependency and any journal work awaiting completion.  This
8019  * can not be called until all other dependencies are stable on disk.
8020  */
8021 static int
8022 handle_complete_freeblocks(freeblks, flags)
8023         struct freeblks *freeblks;
8024         int flags;
8025 {
8026         struct inodedep *inodedep;
8027         struct inode *ip;
8028         struct vnode *vp;
8029         struct fs *fs;
8030         struct ufsmount *ump;
8031         ufs2_daddr_t spare;
8032
8033         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8034         fs = ump->um_fs;
8035         flags = LK_EXCLUSIVE | flags;
8036         spare = freeblks->fb_chkcnt;
8037
8038         /*
8039          * If we did not release the expected number of blocks we may have
8040          * to adjust the inode block count here.  Only do so if it wasn't
8041          * a truncation to zero and the modrev still matches.
8042          */
8043         if (spare && freeblks->fb_len != 0) {
8044                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8045                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8046                         return (EBUSY);
8047                 ip = VTOI(vp);
8048                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8049                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8050                         ip->i_flag |= IN_CHANGE;
8051                         /*
8052                          * We must wait so this happens before the
8053                          * journal is reclaimed.
8054                          */
8055                         ffs_update(vp, 1);
8056                 }
8057                 vput(vp);
8058         }
8059         if (spare < 0) {
8060                 UFS_LOCK(ump);
8061                 fs->fs_pendingblocks += spare;
8062                 UFS_UNLOCK(ump);
8063         }
8064 #ifdef QUOTA
8065         /* Handle spare. */
8066         if (spare)
8067                 quotaadj(freeblks->fb_quota, ump, -spare);
8068         quotarele(freeblks->fb_quota);
8069 #endif
8070         ACQUIRE_LOCK(ump);
8071         if (freeblks->fb_state & ONDEPLIST) {
8072                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8073                     0, &inodedep);
8074                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8075                 freeblks->fb_state &= ~ONDEPLIST;
8076                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8077                         free_inodedep(inodedep);
8078         }
8079         /*
8080          * All of the freeblock deps must be complete prior to this call
8081          * so it's now safe to complete earlier outstanding journal entries.
8082          */
8083         handle_jwork(&freeblks->fb_jwork);
8084         WORKITEM_FREE(freeblks, D_FREEBLKS);
8085         FREE_LOCK(ump);
8086         return (0);
8087 }
8088
8089 /*
8090  * Release blocks associated with the freeblks and stored in the indirect
8091  * block dbn. If level is greater than SINGLE, the block is an indirect block
8092  * and recursive calls to indirtrunc must be used to cleanse other indirect
8093  * blocks.
8094  *
8095  * This handles partial and complete truncation of blocks.  Partial is noted
8096  * with goingaway == 0.  In this case the freework is completed after the
8097  * zero'd indirects are written to disk.  For full truncation the freework
8098  * is completed after the block is freed.
8099  */
8100 static void
8101 indir_trunc(freework, dbn, lbn)
8102         struct freework *freework;
8103         ufs2_daddr_t dbn;
8104         ufs_lbn_t lbn;
8105 {
8106         struct freework *nfreework;
8107         struct workhead wkhd;
8108         struct freeblks *freeblks;
8109         struct buf *bp;
8110         struct fs *fs;
8111         struct indirdep *indirdep;
8112         struct mount *mp;
8113         struct ufsmount *ump;
8114         ufs1_daddr_t *bap1;
8115         ufs2_daddr_t nb, nnb, *bap2;
8116         ufs_lbn_t lbnadd, nlbn;
8117         u_long key;
8118         int nblocks, ufs1fmt, freedblocks;
8119         int goingaway, freedeps, needj, level, cnt, i;
8120
8121         freeblks = freework->fw_freeblks;
8122         mp = freeblks->fb_list.wk_mp;
8123         ump = VFSTOUFS(mp);
8124         fs = ump->um_fs;
8125         /*
8126          * Get buffer of block pointers to be freed.  There are three cases:
8127          * 
8128          * 1) Partial truncate caches the indirdep pointer in the freework
8129          *    which provides us a back copy to the save bp which holds the
8130          *    pointers we want to clear.  When this completes the zero
8131          *    pointers are written to the real copy.
8132          * 2) The indirect is being completely truncated, cancel_indirdep()
8133          *    eliminated the real copy and placed the indirdep on the saved
8134          *    copy.  The indirdep and buf are discarded when this completes.
8135          * 3) The indirect was not in memory, we read a copy off of the disk
8136          *    using the devvp and drop and invalidate the buffer when we're
8137          *    done.
8138          */
8139         goingaway = 1;
8140         indirdep = NULL;
8141         if (freework->fw_indir != NULL) {
8142                 goingaway = 0;
8143                 indirdep = freework->fw_indir;
8144                 bp = indirdep->ir_savebp;
8145                 if (bp == NULL || bp->b_blkno != dbn)
8146                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8147                             bp, (intmax_t)dbn);
8148         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8149                 /*
8150                  * The lock prevents the buf dep list from changing and
8151                  * indirects on devvp should only ever have one dependency.
8152                  */
8153                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8154                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8155                         panic("indir_trunc: Bad indirdep %p from buf %p",
8156                             indirdep, bp);
8157         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8158             NOCRED, &bp) != 0) {
8159                 brelse(bp);
8160                 return;
8161         }
8162         ACQUIRE_LOCK(ump);
8163         /* Protects against a race with complete_trunc_indir(). */
8164         freework->fw_state &= ~INPROGRESS;
8165         /*
8166          * If we have an indirdep we need to enforce the truncation order
8167          * and discard it when it is complete.
8168          */
8169         if (indirdep) {
8170                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8171                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8172                         /*
8173                          * Add the complete truncate to the list on the
8174                          * indirdep to enforce in-order processing.
8175                          */
8176                         if (freework->fw_indir == NULL)
8177                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8178                                     freework, fw_next);
8179                         FREE_LOCK(ump);
8180                         return;
8181                 }
8182                 /*
8183                  * If we're goingaway, free the indirdep.  Otherwise it will
8184                  * linger until the write completes.
8185                  */
8186                 if (goingaway)
8187                         free_indirdep(indirdep);
8188         }
8189         FREE_LOCK(ump);
8190         /* Initialize pointers depending on block size. */
8191         if (ump->um_fstype == UFS1) {
8192                 bap1 = (ufs1_daddr_t *)bp->b_data;
8193                 nb = bap1[freework->fw_off];
8194                 ufs1fmt = 1;
8195                 bap2 = NULL;
8196         } else {
8197                 bap2 = (ufs2_daddr_t *)bp->b_data;
8198                 nb = bap2[freework->fw_off];
8199                 ufs1fmt = 0;
8200                 bap1 = NULL;
8201         }
8202         level = lbn_level(lbn);
8203         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8204         lbnadd = lbn_offset(fs, level);
8205         nblocks = btodb(fs->fs_bsize);
8206         nfreework = freework;
8207         freedeps = 0;
8208         cnt = 0;
8209         /*
8210          * Reclaim blocks.  Traverses into nested indirect levels and
8211          * arranges for the current level to be freed when subordinates
8212          * are free when journaling.
8213          */
8214         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8215         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8216                 if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8217                     fs->fs_bsize) != 0)
8218                         nb = 0;
8219                 if (i != NINDIR(fs) - 1) {
8220                         if (ufs1fmt)
8221                                 nnb = bap1[i+1];
8222                         else
8223                                 nnb = bap2[i+1];
8224                 } else
8225                         nnb = 0;
8226                 if (nb == 0)
8227                         continue;
8228                 cnt++;
8229                 if (level != 0) {
8230                         nlbn = (lbn + 1) - (i * lbnadd);
8231                         if (needj != 0) {
8232                                 nfreework = newfreework(ump, freeblks, freework,
8233                                     nlbn, nb, fs->fs_frag, 0, 0);
8234                                 freedeps++;
8235                         }
8236                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8237                 } else {
8238                         struct freedep *freedep;
8239
8240                         /*
8241                          * Attempt to aggregate freedep dependencies for
8242                          * all blocks being released to the same CG.
8243                          */
8244                         LIST_INIT(&wkhd);
8245                         if (needj != 0 &&
8246                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8247                                 freedep = newfreedep(freework);
8248                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8249                                     &freedep->fd_list);
8250                                 freedeps++;
8251                         }
8252                         CTR3(KTR_SUJ,
8253                             "indir_trunc: ino %jd blkno %jd size %d",
8254                             freeblks->fb_inum, nb, fs->fs_bsize);
8255                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8256                             fs->fs_bsize, freeblks->fb_inum,
8257                             freeblks->fb_vtype, &wkhd, key);
8258                 }
8259         }
8260         ffs_blkrelease_finish(ump, key);
8261         if (goingaway) {
8262                 bp->b_flags |= B_INVAL | B_NOCACHE;
8263                 brelse(bp);
8264         }
8265         freedblocks = 0;
8266         if (level == 0)
8267                 freedblocks = (nblocks * cnt);
8268         if (needj == 0)
8269                 freedblocks += nblocks;
8270         freeblks_free(ump, freeblks, freedblocks);
8271         /*
8272          * If we are journaling set up the ref counts and offset so this
8273          * indirect can be completed when its children are free.
8274          */
8275         if (needj) {
8276                 ACQUIRE_LOCK(ump);
8277                 freework->fw_off = i;
8278                 freework->fw_ref += freedeps;
8279                 freework->fw_ref -= NINDIR(fs) + 1;
8280                 if (level == 0)
8281                         freeblks->fb_cgwait += freedeps;
8282                 if (freework->fw_ref == 0)
8283                         freework_freeblock(freework, SINGLETON_KEY);
8284                 FREE_LOCK(ump);
8285                 return;
8286         }
8287         /*
8288          * If we're not journaling we can free the indirect now.
8289          */
8290         dbn = dbtofsb(fs, dbn);
8291         CTR3(KTR_SUJ,
8292             "indir_trunc 2: ino %jd blkno %jd size %d",
8293             freeblks->fb_inum, dbn, fs->fs_bsize);
8294         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8295             freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8296         /* Non SUJ softdep does single-threaded truncations. */
8297         if (freework->fw_blkno == dbn) {
8298                 freework->fw_state |= ALLCOMPLETE;
8299                 ACQUIRE_LOCK(ump);
8300                 handle_written_freework(freework);
8301                 FREE_LOCK(ump);
8302         }
8303         return;
8304 }
8305
8306 /*
8307  * Cancel an allocindir when it is removed via truncation.  When bp is not
8308  * NULL the indirect never appeared on disk and is scheduled to be freed
8309  * independently of the indir so we can more easily track journal work.
8310  */
8311 static void
8312 cancel_allocindir(aip, bp, freeblks, trunc)
8313         struct allocindir *aip;
8314         struct buf *bp;
8315         struct freeblks *freeblks;
8316         int trunc;
8317 {
8318         struct indirdep *indirdep;
8319         struct freefrag *freefrag;
8320         struct newblk *newblk;
8321
8322         newblk = (struct newblk *)aip;
8323         LIST_REMOVE(aip, ai_next);
8324         /*
8325          * We must eliminate the pointer in bp if it must be freed on its
8326          * own due to partial truncate or pending journal work.
8327          */
8328         if (bp && (trunc || newblk->nb_jnewblk)) {
8329                 /*
8330                  * Clear the pointer and mark the aip to be freed
8331                  * directly if it never existed on disk.
8332                  */
8333                 aip->ai_state |= DELAYEDFREE;
8334                 indirdep = aip->ai_indirdep;
8335                 if (indirdep->ir_state & UFS1FMT)
8336                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8337                 else
8338                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8339         }
8340         /*
8341          * When truncating the previous pointer will be freed via
8342          * savedbp.  Eliminate the freefrag which would dup free.
8343          */
8344         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8345                 newblk->nb_freefrag = NULL;
8346                 if (freefrag->ff_jdep)
8347                         cancel_jfreefrag(
8348                             WK_JFREEFRAG(freefrag->ff_jdep));
8349                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8350                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8351         }
8352         /*
8353          * If the journal hasn't been written the jnewblk must be passed
8354          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8355          * this by leaving the journal dependency on the newblk to be freed
8356          * when a freework is created in handle_workitem_freeblocks().
8357          */
8358         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8359         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8360 }
8361
8362 /*
8363  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8364  * in to a newdirblk so any subsequent additions are tracked properly.  The
8365  * caller is responsible for adding the mkdir1 dependency to the journal
8366  * and updating id_mkdiradd.  This function returns with the per-filesystem
8367  * lock held.
8368  */
8369 static struct mkdir *
8370 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8371         struct diradd *dap;
8372         ino_t newinum;
8373         ino_t dinum;
8374         struct buf *newdirbp;
8375         struct mkdir **mkdirp;
8376 {
8377         struct newblk *newblk;
8378         struct pagedep *pagedep;
8379         struct inodedep *inodedep;
8380         struct newdirblk *newdirblk;
8381         struct mkdir *mkdir1, *mkdir2;
8382         struct worklist *wk;
8383         struct jaddref *jaddref;
8384         struct ufsmount *ump;
8385         struct mount *mp;
8386
8387         mp = dap->da_list.wk_mp;
8388         ump = VFSTOUFS(mp);
8389         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8390             M_SOFTDEP_FLAGS);
8391         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8392         LIST_INIT(&newdirblk->db_mkdir);
8393         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8394         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8395         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8396         mkdir1->md_diradd = dap;
8397         mkdir1->md_jaddref = NULL;
8398         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8399         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8400         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8401         mkdir2->md_diradd = dap;
8402         mkdir2->md_jaddref = NULL;
8403         if (MOUNTEDSUJ(mp) == 0) {
8404                 mkdir1->md_state |= DEPCOMPLETE;
8405                 mkdir2->md_state |= DEPCOMPLETE;
8406         }
8407         /*
8408          * Dependency on "." and ".." being written to disk.
8409          */
8410         mkdir1->md_buf = newdirbp;
8411         ACQUIRE_LOCK(VFSTOUFS(mp));
8412         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8413         /*
8414          * We must link the pagedep, allocdirect, and newdirblk for
8415          * the initial file page so the pointer to the new directory
8416          * is not written until the directory contents are live and
8417          * any subsequent additions are not marked live until the
8418          * block is reachable via the inode.
8419          */
8420         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8421                 panic("setup_newdir: lost pagedep");
8422         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8423                 if (wk->wk_type == D_ALLOCDIRECT)
8424                         break;
8425         if (wk == NULL)
8426                 panic("setup_newdir: lost allocdirect");
8427         if (pagedep->pd_state & NEWBLOCK)
8428                 panic("setup_newdir: NEWBLOCK already set");
8429         newblk = WK_NEWBLK(wk);
8430         pagedep->pd_state |= NEWBLOCK;
8431         pagedep->pd_newdirblk = newdirblk;
8432         newdirblk->db_pagedep = pagedep;
8433         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8434         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8435         /*
8436          * Look up the inodedep for the parent directory so that we
8437          * can link mkdir2 into the pending dotdot jaddref or
8438          * the inode write if there is none.  If the inode is
8439          * ALLCOMPLETE and no jaddref is present all dependencies have
8440          * been satisfied and mkdir2 can be freed.
8441          */
8442         inodedep_lookup(mp, dinum, 0, &inodedep);
8443         if (MOUNTEDSUJ(mp)) {
8444                 if (inodedep == NULL)
8445                         panic("setup_newdir: Lost parent.");
8446                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8447                     inoreflst);
8448                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8449                     (jaddref->ja_state & MKDIR_PARENT),
8450                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8451                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8452                 mkdir2->md_jaddref = jaddref;
8453                 jaddref->ja_mkdir = mkdir2;
8454         } else if (inodedep == NULL ||
8455             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8456                 dap->da_state &= ~MKDIR_PARENT;
8457                 WORKITEM_FREE(mkdir2, D_MKDIR);
8458                 mkdir2 = NULL;
8459         } else {
8460                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8461                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8462         }
8463         *mkdirp = mkdir2;
8464
8465         return (mkdir1);
8466 }
8467
8468 /*
8469  * Directory entry addition dependencies.
8470  * 
8471  * When adding a new directory entry, the inode (with its incremented link
8472  * count) must be written to disk before the directory entry's pointer to it.
8473  * Also, if the inode is newly allocated, the corresponding freemap must be
8474  * updated (on disk) before the directory entry's pointer. These requirements
8475  * are met via undo/redo on the directory entry's pointer, which consists
8476  * simply of the inode number.
8477  * 
8478  * As directory entries are added and deleted, the free space within a
8479  * directory block can become fragmented.  The ufs filesystem will compact
8480  * a fragmented directory block to make space for a new entry. When this
8481  * occurs, the offsets of previously added entries change. Any "diradd"
8482  * dependency structures corresponding to these entries must be updated with
8483  * the new offsets.
8484  */
8485
8486 /*
8487  * This routine is called after the in-memory inode's link
8488  * count has been incremented, but before the directory entry's
8489  * pointer to the inode has been set.
8490  */
8491 int
8492 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8493         struct buf *bp;         /* buffer containing directory block */
8494         struct inode *dp;       /* inode for directory */
8495         off_t diroffset;        /* offset of new entry in directory */
8496         ino_t newinum;          /* inode referenced by new directory entry */
8497         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8498         int isnewblk;           /* entry is in a newly allocated block */
8499 {
8500         int offset;             /* offset of new entry within directory block */
8501         ufs_lbn_t lbn;          /* block in directory containing new entry */
8502         struct fs *fs;
8503         struct diradd *dap;
8504         struct newblk *newblk;
8505         struct pagedep *pagedep;
8506         struct inodedep *inodedep;
8507         struct newdirblk *newdirblk;
8508         struct mkdir *mkdir1, *mkdir2;
8509         struct jaddref *jaddref;
8510         struct ufsmount *ump;
8511         struct mount *mp;
8512         int isindir;
8513
8514         mp = ITOVFS(dp);
8515         ump = VFSTOUFS(mp);
8516         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8517             ("softdep_setup_directory_add called on non-softdep filesystem"));
8518         /*
8519          * Whiteouts have no dependencies.
8520          */
8521         if (newinum == UFS_WINO) {
8522                 if (newdirbp != NULL)
8523                         bdwrite(newdirbp);
8524                 return (0);
8525         }
8526         jaddref = NULL;
8527         mkdir1 = mkdir2 = NULL;
8528         fs = ump->um_fs;
8529         lbn = lblkno(fs, diroffset);
8530         offset = blkoff(fs, diroffset);
8531         dap = malloc(sizeof(struct diradd), M_DIRADD,
8532                 M_SOFTDEP_FLAGS|M_ZERO);
8533         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8534         dap->da_offset = offset;
8535         dap->da_newinum = newinum;
8536         dap->da_state = ATTACHED;
8537         LIST_INIT(&dap->da_jwork);
8538         isindir = bp->b_lblkno >= UFS_NDADDR;
8539         newdirblk = NULL;
8540         if (isnewblk &&
8541             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8542                 newdirblk = malloc(sizeof(struct newdirblk),
8543                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8544                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8545                 LIST_INIT(&newdirblk->db_mkdir);
8546         }
8547         /*
8548          * If we're creating a new directory setup the dependencies and set
8549          * the dap state to wait for them.  Otherwise it's COMPLETE and
8550          * we can move on.
8551          */
8552         if (newdirbp == NULL) {
8553                 dap->da_state |= DEPCOMPLETE;
8554                 ACQUIRE_LOCK(ump);
8555         } else {
8556                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8557                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8558                     &mkdir2);
8559         }
8560         /*
8561          * Link into parent directory pagedep to await its being written.
8562          */
8563         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8564 #ifdef DEBUG
8565         if (diradd_lookup(pagedep, offset) != NULL)
8566                 panic("softdep_setup_directory_add: %p already at off %d\n",
8567                     diradd_lookup(pagedep, offset), offset);
8568 #endif
8569         dap->da_pagedep = pagedep;
8570         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8571             da_pdlist);
8572         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8573         /*
8574          * If we're journaling, link the diradd into the jaddref so it
8575          * may be completed after the journal entry is written.  Otherwise,
8576          * link the diradd into its inodedep.  If the inode is not yet
8577          * written place it on the bufwait list, otherwise do the post-inode
8578          * write processing to put it on the id_pendinghd list.
8579          */
8580         if (MOUNTEDSUJ(mp)) {
8581                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8582                     inoreflst);
8583                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8584                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8585                 jaddref->ja_diroff = diroffset;
8586                 jaddref->ja_diradd = dap;
8587                 add_to_journal(&jaddref->ja_list);
8588         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8589                 diradd_inode_written(dap, inodedep);
8590         else
8591                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8592         /*
8593          * Add the journal entries for . and .. links now that the primary
8594          * link is written.
8595          */
8596         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8597                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8598                     inoreflst, if_deps);
8599                 KASSERT(jaddref != NULL &&
8600                     jaddref->ja_ino == jaddref->ja_parent &&
8601                     (jaddref->ja_state & MKDIR_BODY),
8602                     ("softdep_setup_directory_add: bad dot jaddref %p",
8603                     jaddref));
8604                 mkdir1->md_jaddref = jaddref;
8605                 jaddref->ja_mkdir = mkdir1;
8606                 /*
8607                  * It is important that the dotdot journal entry
8608                  * is added prior to the dot entry since dot writes
8609                  * both the dot and dotdot links.  These both must
8610                  * be added after the primary link for the journal
8611                  * to remain consistent.
8612                  */
8613                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8614                 add_to_journal(&jaddref->ja_list);
8615         }
8616         /*
8617          * If we are adding a new directory remember this diradd so that if
8618          * we rename it we can keep the dot and dotdot dependencies.  If
8619          * we are adding a new name for an inode that has a mkdiradd we
8620          * must be in rename and we have to move the dot and dotdot
8621          * dependencies to this new name.  The old name is being orphaned
8622          * soon.
8623          */
8624         if (mkdir1 != NULL) {
8625                 if (inodedep->id_mkdiradd != NULL)
8626                         panic("softdep_setup_directory_add: Existing mkdir");
8627                 inodedep->id_mkdiradd = dap;
8628         } else if (inodedep->id_mkdiradd)
8629                 merge_diradd(inodedep, dap);
8630         if (newdirblk != NULL) {
8631                 /*
8632                  * There is nothing to do if we are already tracking
8633                  * this block.
8634                  */
8635                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8636                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8637                         FREE_LOCK(ump);
8638                         return (0);
8639                 }
8640                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8641                     == 0)
8642                         panic("softdep_setup_directory_add: lost entry");
8643                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8644                 pagedep->pd_state |= NEWBLOCK;
8645                 pagedep->pd_newdirblk = newdirblk;
8646                 newdirblk->db_pagedep = pagedep;
8647                 FREE_LOCK(ump);
8648                 /*
8649                  * If we extended into an indirect signal direnter to sync.
8650                  */
8651                 if (isindir)
8652                         return (1);
8653                 return (0);
8654         }
8655         FREE_LOCK(ump);
8656         return (0);
8657 }
8658
8659 /*
8660  * This procedure is called to change the offset of a directory
8661  * entry when compacting a directory block which must be owned
8662  * exclusively by the caller. Note that the actual entry movement
8663  * must be done in this procedure to ensure that no I/O completions
8664  * occur while the move is in progress.
8665  */
8666 void 
8667 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8668         struct buf *bp;         /* Buffer holding directory block. */
8669         struct inode *dp;       /* inode for directory */
8670         caddr_t base;           /* address of dp->i_offset */
8671         caddr_t oldloc;         /* address of old directory location */
8672         caddr_t newloc;         /* address of new directory location */
8673         int entrysize;          /* size of directory entry */
8674 {
8675         int offset, oldoffset, newoffset;
8676         struct pagedep *pagedep;
8677         struct jmvref *jmvref;
8678         struct diradd *dap;
8679         struct direct *de;
8680         struct mount *mp;
8681         struct ufsmount *ump;
8682         ufs_lbn_t lbn;
8683         int flags;
8684
8685         mp = ITOVFS(dp);
8686         ump = VFSTOUFS(mp);
8687         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8688             ("softdep_change_directoryentry_offset called on "
8689              "non-softdep filesystem"));
8690         de = (struct direct *)oldloc;
8691         jmvref = NULL;
8692         flags = 0;
8693         /*
8694          * Moves are always journaled as it would be too complex to
8695          * determine if any affected adds or removes are present in the
8696          * journal.
8697          */
8698         if (MOUNTEDSUJ(mp)) {
8699                 flags = DEPALLOC;
8700                 jmvref = newjmvref(dp, de->d_ino,
8701                     dp->i_offset + (oldloc - base),
8702                     dp->i_offset + (newloc - base));
8703         }
8704         lbn = lblkno(ump->um_fs, dp->i_offset);
8705         offset = blkoff(ump->um_fs, dp->i_offset);
8706         oldoffset = offset + (oldloc - base);
8707         newoffset = offset + (newloc - base);
8708         ACQUIRE_LOCK(ump);
8709         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8710                 goto done;
8711         dap = diradd_lookup(pagedep, oldoffset);
8712         if (dap) {
8713                 dap->da_offset = newoffset;
8714                 newoffset = DIRADDHASH(newoffset);
8715                 oldoffset = DIRADDHASH(oldoffset);
8716                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8717                     newoffset != oldoffset) {
8718                         LIST_REMOVE(dap, da_pdlist);
8719                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8720                             dap, da_pdlist);
8721                 }
8722         }
8723 done:
8724         if (jmvref) {
8725                 jmvref->jm_pagedep = pagedep;
8726                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8727                 add_to_journal(&jmvref->jm_list);
8728         }
8729         bcopy(oldloc, newloc, entrysize);
8730         FREE_LOCK(ump);
8731 }
8732
8733 /*
8734  * Move the mkdir dependencies and journal work from one diradd to another
8735  * when renaming a directory.  The new name must depend on the mkdir deps
8736  * completing as the old name did.  Directories can only have one valid link
8737  * at a time so one must be canonical.
8738  */
8739 static void
8740 merge_diradd(inodedep, newdap)
8741         struct inodedep *inodedep;
8742         struct diradd *newdap;
8743 {
8744         struct diradd *olddap;
8745         struct mkdir *mkdir, *nextmd;
8746         struct ufsmount *ump;
8747         short state;
8748
8749         olddap = inodedep->id_mkdiradd;
8750         inodedep->id_mkdiradd = newdap;
8751         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8752                 newdap->da_state &= ~DEPCOMPLETE;
8753                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8754                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8755                      mkdir = nextmd) {
8756                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8757                         if (mkdir->md_diradd != olddap)
8758                                 continue;
8759                         mkdir->md_diradd = newdap;
8760                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8761                         newdap->da_state |= state;
8762                         olddap->da_state &= ~state;
8763                         if ((olddap->da_state &
8764                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8765                                 break;
8766                 }
8767                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8768                         panic("merge_diradd: unfound ref");
8769         }
8770         /*
8771          * Any mkdir related journal items are not safe to be freed until
8772          * the new name is stable.
8773          */
8774         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8775         olddap->da_state |= DEPCOMPLETE;
8776         complete_diradd(olddap);
8777 }
8778
8779 /*
8780  * Move the diradd to the pending list when all diradd dependencies are
8781  * complete.
8782  */
8783 static void
8784 complete_diradd(dap)
8785         struct diradd *dap;
8786 {
8787         struct pagedep *pagedep;
8788
8789         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8790                 if (dap->da_state & DIRCHG)
8791                         pagedep = dap->da_previous->dm_pagedep;
8792                 else
8793                         pagedep = dap->da_pagedep;
8794                 LIST_REMOVE(dap, da_pdlist);
8795                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8796         }
8797 }
8798
8799 /*
8800  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8801  * add entries and conditonally journal the remove.
8802  */
8803 static void
8804 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8805         struct diradd *dap;
8806         struct dirrem *dirrem;
8807         struct jremref *jremref;
8808         struct jremref *dotremref;
8809         struct jremref *dotdotremref;
8810 {
8811         struct inodedep *inodedep;
8812         struct jaddref *jaddref;
8813         struct inoref *inoref;
8814         struct ufsmount *ump;
8815         struct mkdir *mkdir;
8816
8817         /*
8818          * If no remove references were allocated we're on a non-journaled
8819          * filesystem and can skip the cancel step.
8820          */
8821         if (jremref == NULL) {
8822                 free_diradd(dap, NULL);
8823                 return;
8824         }
8825         /*
8826          * Cancel the primary name an free it if it does not require
8827          * journaling.
8828          */
8829         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8830             0, &inodedep) != 0) {
8831                 /* Abort the addref that reference this diradd.  */
8832                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8833                         if (inoref->if_list.wk_type != D_JADDREF)
8834                                 continue;
8835                         jaddref = (struct jaddref *)inoref;
8836                         if (jaddref->ja_diradd != dap)
8837                                 continue;
8838                         if (cancel_jaddref(jaddref, inodedep,
8839                             &dirrem->dm_jwork) == 0) {
8840                                 free_jremref(jremref);
8841                                 jremref = NULL;
8842                         }
8843                         break;
8844                 }
8845         }
8846         /*
8847          * Cancel subordinate names and free them if they do not require
8848          * journaling.
8849          */
8850         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8851                 ump = VFSTOUFS(dap->da_list.wk_mp);
8852                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8853                         if (mkdir->md_diradd != dap)
8854                                 continue;
8855                         if ((jaddref = mkdir->md_jaddref) == NULL)
8856                                 continue;
8857                         mkdir->md_jaddref = NULL;
8858                         if (mkdir->md_state & MKDIR_PARENT) {
8859                                 if (cancel_jaddref(jaddref, NULL,
8860                                     &dirrem->dm_jwork) == 0) {
8861                                         free_jremref(dotdotremref);
8862                                         dotdotremref = NULL;
8863                                 }
8864                         } else {
8865                                 if (cancel_jaddref(jaddref, inodedep,
8866                                     &dirrem->dm_jwork) == 0) {
8867                                         free_jremref(dotremref);
8868                                         dotremref = NULL;
8869                                 }
8870                         }
8871                 }
8872         }
8873
8874         if (jremref)
8875                 journal_jremref(dirrem, jremref, inodedep);
8876         if (dotremref)
8877                 journal_jremref(dirrem, dotremref, inodedep);
8878         if (dotdotremref)
8879                 journal_jremref(dirrem, dotdotremref, NULL);
8880         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8881         free_diradd(dap, &dirrem->dm_jwork);
8882 }
8883
8884 /*
8885  * Free a diradd dependency structure.
8886  */
8887 static void
8888 free_diradd(dap, wkhd)
8889         struct diradd *dap;
8890         struct workhead *wkhd;
8891 {
8892         struct dirrem *dirrem;
8893         struct pagedep *pagedep;
8894         struct inodedep *inodedep;
8895         struct mkdir *mkdir, *nextmd;
8896         struct ufsmount *ump;
8897
8898         ump = VFSTOUFS(dap->da_list.wk_mp);
8899         LOCK_OWNED(ump);
8900         LIST_REMOVE(dap, da_pdlist);
8901         if (dap->da_state & ONWORKLIST)
8902                 WORKLIST_REMOVE(&dap->da_list);
8903         if ((dap->da_state & DIRCHG) == 0) {
8904                 pagedep = dap->da_pagedep;
8905         } else {
8906                 dirrem = dap->da_previous;
8907                 pagedep = dirrem->dm_pagedep;
8908                 dirrem->dm_dirinum = pagedep->pd_ino;
8909                 dirrem->dm_state |= COMPLETE;
8910                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8911                         add_to_worklist(&dirrem->dm_list, 0);
8912         }
8913         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8914             0, &inodedep) != 0)
8915                 if (inodedep->id_mkdiradd == dap)
8916                         inodedep->id_mkdiradd = NULL;
8917         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8918                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8919                      mkdir = nextmd) {
8920                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8921                         if (mkdir->md_diradd != dap)
8922                                 continue;
8923                         dap->da_state &=
8924                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8925                         LIST_REMOVE(mkdir, md_mkdirs);
8926                         if (mkdir->md_state & ONWORKLIST)
8927                                 WORKLIST_REMOVE(&mkdir->md_list);
8928                         if (mkdir->md_jaddref != NULL)
8929                                 panic("free_diradd: Unexpected jaddref");
8930                         WORKITEM_FREE(mkdir, D_MKDIR);
8931                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8932                                 break;
8933                 }
8934                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8935                         panic("free_diradd: unfound ref");
8936         }
8937         if (inodedep)
8938                 free_inodedep(inodedep);
8939         /*
8940          * Free any journal segments waiting for the directory write.
8941          */
8942         handle_jwork(&dap->da_jwork);
8943         WORKITEM_FREE(dap, D_DIRADD);
8944 }
8945
8946 /*
8947  * Directory entry removal dependencies.
8948  * 
8949  * When removing a directory entry, the entry's inode pointer must be
8950  * zero'ed on disk before the corresponding inode's link count is decremented
8951  * (possibly freeing the inode for re-use). This dependency is handled by
8952  * updating the directory entry but delaying the inode count reduction until
8953  * after the directory block has been written to disk. After this point, the
8954  * inode count can be decremented whenever it is convenient.
8955  */
8956
8957 /*
8958  * This routine should be called immediately after removing
8959  * a directory entry.  The inode's link count should not be
8960  * decremented by the calling procedure -- the soft updates
8961  * code will do this task when it is safe.
8962  */
8963 void 
8964 softdep_setup_remove(bp, dp, ip, isrmdir)
8965         struct buf *bp;         /* buffer containing directory block */
8966         struct inode *dp;       /* inode for the directory being modified */
8967         struct inode *ip;       /* inode for directory entry being removed */
8968         int isrmdir;            /* indicates if doing RMDIR */
8969 {
8970         struct dirrem *dirrem, *prevdirrem;
8971         struct inodedep *inodedep;
8972         struct ufsmount *ump;
8973         int direct;
8974
8975         ump = ITOUMP(ip);
8976         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8977             ("softdep_setup_remove called on non-softdep filesystem"));
8978         /*
8979          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8980          * newdirrem() to setup the full directory remove which requires
8981          * isrmdir > 1.
8982          */
8983         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8984         /*
8985          * Add the dirrem to the inodedep's pending remove list for quick
8986          * discovery later.
8987          */
8988         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8989                 panic("softdep_setup_remove: Lost inodedep.");
8990         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8991         dirrem->dm_state |= ONDEPLIST;
8992         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8993
8994         /*
8995          * If the COMPLETE flag is clear, then there were no active
8996          * entries and we want to roll back to a zeroed entry until
8997          * the new inode is committed to disk. If the COMPLETE flag is
8998          * set then we have deleted an entry that never made it to
8999          * disk. If the entry we deleted resulted from a name change,
9000          * then the old name still resides on disk. We cannot delete
9001          * its inode (returned to us in prevdirrem) until the zeroed
9002          * directory entry gets to disk. The new inode has never been
9003          * referenced on the disk, so can be deleted immediately.
9004          */
9005         if ((dirrem->dm_state & COMPLETE) == 0) {
9006                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9007                     dm_next);
9008                 FREE_LOCK(ump);
9009         } else {
9010                 if (prevdirrem != NULL)
9011                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9012                             prevdirrem, dm_next);
9013                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9014                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9015                 FREE_LOCK(ump);
9016                 if (direct)
9017                         handle_workitem_remove(dirrem, 0);
9018         }
9019 }
9020
9021 /*
9022  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9023  * pd_pendinghd list of a pagedep.
9024  */
9025 static struct diradd *
9026 diradd_lookup(pagedep, offset)
9027         struct pagedep *pagedep;
9028         int offset;
9029 {
9030         struct diradd *dap;
9031
9032         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9033                 if (dap->da_offset == offset)
9034                         return (dap);
9035         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9036                 if (dap->da_offset == offset)
9037                         return (dap);
9038         return (NULL);
9039 }
9040
9041 /*
9042  * Search for a .. diradd dependency in a directory that is being removed.
9043  * If the directory was renamed to a new parent we have a diradd rather
9044  * than a mkdir for the .. entry.  We need to cancel it now before
9045  * it is found in truncate().
9046  */
9047 static struct jremref *
9048 cancel_diradd_dotdot(ip, dirrem, jremref)
9049         struct inode *ip;
9050         struct dirrem *dirrem;
9051         struct jremref *jremref;
9052 {
9053         struct pagedep *pagedep;
9054         struct diradd *dap;
9055         struct worklist *wk;
9056
9057         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9058                 return (jremref);
9059         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9060         if (dap == NULL)
9061                 return (jremref);
9062         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9063         /*
9064          * Mark any journal work as belonging to the parent so it is freed
9065          * with the .. reference.
9066          */
9067         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9068                 wk->wk_state |= MKDIR_PARENT;
9069         return (NULL);
9070 }
9071
9072 /*
9073  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9074  * replace it with a dirrem/diradd pair as a result of re-parenting a
9075  * directory.  This ensures that we don't simultaneously have a mkdir and
9076  * a diradd for the same .. entry.
9077  */
9078 static struct jremref *
9079 cancel_mkdir_dotdot(ip, dirrem, jremref)
9080         struct inode *ip;
9081         struct dirrem *dirrem;
9082         struct jremref *jremref;
9083 {
9084         struct inodedep *inodedep;
9085         struct jaddref *jaddref;
9086         struct ufsmount *ump;
9087         struct mkdir *mkdir;
9088         struct diradd *dap;
9089         struct mount *mp;
9090
9091         mp = ITOVFS(ip);
9092         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9093                 return (jremref);
9094         dap = inodedep->id_mkdiradd;
9095         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9096                 return (jremref);
9097         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9098         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9099             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9100                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9101                         break;
9102         if (mkdir == NULL)
9103                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9104         if ((jaddref = mkdir->md_jaddref) != NULL) {
9105                 mkdir->md_jaddref = NULL;
9106                 jaddref->ja_state &= ~MKDIR_PARENT;
9107                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9108                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9109                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9110                         journal_jremref(dirrem, jremref, inodedep);
9111                         jremref = NULL;
9112                 }
9113         }
9114         if (mkdir->md_state & ONWORKLIST)
9115                 WORKLIST_REMOVE(&mkdir->md_list);
9116         mkdir->md_state |= ALLCOMPLETE;
9117         complete_mkdir(mkdir);
9118         return (jremref);
9119 }
9120
9121 static void
9122 journal_jremref(dirrem, jremref, inodedep)
9123         struct dirrem *dirrem;
9124         struct jremref *jremref;
9125         struct inodedep *inodedep;
9126 {
9127
9128         if (inodedep == NULL)
9129                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9130                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9131                         panic("journal_jremref: Lost inodedep");
9132         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9133         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9134         add_to_journal(&jremref->jr_list);
9135 }
9136
9137 static void
9138 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9139         struct dirrem *dirrem;
9140         struct jremref *jremref;
9141         struct jremref *dotremref;
9142         struct jremref *dotdotremref;
9143 {
9144         struct inodedep *inodedep;
9145
9146
9147         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9148             &inodedep) == 0)
9149                 panic("dirrem_journal: Lost inodedep");
9150         journal_jremref(dirrem, jremref, inodedep);
9151         if (dotremref)
9152                 journal_jremref(dirrem, dotremref, inodedep);
9153         if (dotdotremref)
9154                 journal_jremref(dirrem, dotdotremref, NULL);
9155 }
9156
9157 /*
9158  * Allocate a new dirrem if appropriate and return it along with
9159  * its associated pagedep. Called without a lock, returns with lock.
9160  */
9161 static struct dirrem *
9162 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9163         struct buf *bp;         /* buffer containing directory block */
9164         struct inode *dp;       /* inode for the directory being modified */
9165         struct inode *ip;       /* inode for directory entry being removed */
9166         int isrmdir;            /* indicates if doing RMDIR */
9167         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9168 {
9169         int offset;
9170         ufs_lbn_t lbn;
9171         struct diradd *dap;
9172         struct dirrem *dirrem;
9173         struct pagedep *pagedep;
9174         struct jremref *jremref;
9175         struct jremref *dotremref;
9176         struct jremref *dotdotremref;
9177         struct vnode *dvp;
9178         struct ufsmount *ump;
9179
9180         /*
9181          * Whiteouts have no deletion dependencies.
9182          */
9183         if (ip == NULL)
9184                 panic("newdirrem: whiteout");
9185         dvp = ITOV(dp);
9186         ump = ITOUMP(dp);
9187
9188         /*
9189          * If the system is over its limit and our filesystem is
9190          * responsible for more than our share of that usage and
9191          * we are not a snapshot, request some inodedep cleanup.
9192          * Limiting the number of dirrem structures will also limit
9193          * the number of freefile and freeblks structures.
9194          */
9195         ACQUIRE_LOCK(ump);
9196         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9197                 schedule_cleanup(UFSTOVFS(ump));
9198         else
9199                 FREE_LOCK(ump);
9200         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9201             M_ZERO);
9202         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9203         LIST_INIT(&dirrem->dm_jremrefhd);
9204         LIST_INIT(&dirrem->dm_jwork);
9205         dirrem->dm_state = isrmdir ? RMDIR : 0;
9206         dirrem->dm_oldinum = ip->i_number;
9207         *prevdirremp = NULL;
9208         /*
9209          * Allocate remove reference structures to track journal write
9210          * dependencies.  We will always have one for the link and
9211          * when doing directories we will always have one more for dot.
9212          * When renaming a directory we skip the dotdot link change so
9213          * this is not needed.
9214          */
9215         jremref = dotremref = dotdotremref = NULL;
9216         if (DOINGSUJ(dvp)) {
9217                 if (isrmdir) {
9218                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9219                             ip->i_effnlink + 2);
9220                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9221                             ip->i_effnlink + 1);
9222                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9223                             dp->i_effnlink + 1);
9224                         dotdotremref->jr_state |= MKDIR_PARENT;
9225                 } else
9226                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9227                             ip->i_effnlink + 1);
9228         }
9229         ACQUIRE_LOCK(ump);
9230         lbn = lblkno(ump->um_fs, dp->i_offset);
9231         offset = blkoff(ump->um_fs, dp->i_offset);
9232         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9233             &pagedep);
9234         dirrem->dm_pagedep = pagedep;
9235         dirrem->dm_offset = offset;
9236         /*
9237          * If we're renaming a .. link to a new directory, cancel any
9238          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9239          * the jremref is preserved for any potential diradd in this
9240          * location.  This can not coincide with a rmdir.
9241          */
9242         if (dp->i_offset == DOTDOT_OFFSET) {
9243                 if (isrmdir)
9244                         panic("newdirrem: .. directory change during remove?");
9245                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9246         }
9247         /*
9248          * If we're removing a directory search for the .. dependency now and
9249          * cancel it.  Any pending journal work will be added to the dirrem
9250          * to be completed when the workitem remove completes.
9251          */
9252         if (isrmdir)
9253                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9254         /*
9255          * Check for a diradd dependency for the same directory entry.
9256          * If present, then both dependencies become obsolete and can
9257          * be de-allocated.
9258          */
9259         dap = diradd_lookup(pagedep, offset);
9260         if (dap == NULL) {
9261                 /*
9262                  * Link the jremref structures into the dirrem so they are
9263                  * written prior to the pagedep.
9264                  */
9265                 if (jremref)
9266                         dirrem_journal(dirrem, jremref, dotremref,
9267                             dotdotremref);
9268                 return (dirrem);
9269         }
9270         /*
9271          * Must be ATTACHED at this point.
9272          */
9273         if ((dap->da_state & ATTACHED) == 0)
9274                 panic("newdirrem: not ATTACHED");
9275         if (dap->da_newinum != ip->i_number)
9276                 panic("newdirrem: inum %ju should be %ju",
9277                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9278         /*
9279          * If we are deleting a changed name that never made it to disk,
9280          * then return the dirrem describing the previous inode (which
9281          * represents the inode currently referenced from this entry on disk).
9282          */
9283         if ((dap->da_state & DIRCHG) != 0) {
9284                 *prevdirremp = dap->da_previous;
9285                 dap->da_state &= ~DIRCHG;
9286                 dap->da_pagedep = pagedep;
9287         }
9288         /*
9289          * We are deleting an entry that never made it to disk.
9290          * Mark it COMPLETE so we can delete its inode immediately.
9291          */
9292         dirrem->dm_state |= COMPLETE;
9293         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9294 #ifdef SUJ_DEBUG
9295         if (isrmdir == 0) {
9296                 struct worklist *wk;
9297
9298                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9299                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9300                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9301         }
9302 #endif
9303
9304         return (dirrem);
9305 }
9306
9307 /*
9308  * Directory entry change dependencies.
9309  * 
9310  * Changing an existing directory entry requires that an add operation
9311  * be completed first followed by a deletion. The semantics for the addition
9312  * are identical to the description of adding a new entry above except
9313  * that the rollback is to the old inode number rather than zero. Once
9314  * the addition dependency is completed, the removal is done as described
9315  * in the removal routine above.
9316  */
9317
9318 /*
9319  * This routine should be called immediately after changing
9320  * a directory entry.  The inode's link count should not be
9321  * decremented by the calling procedure -- the soft updates
9322  * code will perform this task when it is safe.
9323  */
9324 void 
9325 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9326         struct buf *bp;         /* buffer containing directory block */
9327         struct inode *dp;       /* inode for the directory being modified */
9328         struct inode *ip;       /* inode for directory entry being removed */
9329         ino_t newinum;          /* new inode number for changed entry */
9330         int isrmdir;            /* indicates if doing RMDIR */
9331 {
9332         int offset;
9333         struct diradd *dap = NULL;
9334         struct dirrem *dirrem, *prevdirrem;
9335         struct pagedep *pagedep;
9336         struct inodedep *inodedep;
9337         struct jaddref *jaddref;
9338         struct mount *mp;
9339         struct ufsmount *ump;
9340
9341         mp = ITOVFS(dp);
9342         ump = VFSTOUFS(mp);
9343         offset = blkoff(ump->um_fs, dp->i_offset);
9344         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9345            ("softdep_setup_directory_change called on non-softdep filesystem"));
9346
9347         /*
9348          * Whiteouts do not need diradd dependencies.
9349          */
9350         if (newinum != UFS_WINO) {
9351                 dap = malloc(sizeof(struct diradd),
9352                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9353                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9354                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9355                 dap->da_offset = offset;
9356                 dap->da_newinum = newinum;
9357                 LIST_INIT(&dap->da_jwork);
9358         }
9359
9360         /*
9361          * Allocate a new dirrem and ACQUIRE_LOCK.
9362          */
9363         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9364         pagedep = dirrem->dm_pagedep;
9365         /*
9366          * The possible values for isrmdir:
9367          *      0 - non-directory file rename
9368          *      1 - directory rename within same directory
9369          *   inum - directory rename to new directory of given inode number
9370          * When renaming to a new directory, we are both deleting and
9371          * creating a new directory entry, so the link count on the new
9372          * directory should not change. Thus we do not need the followup
9373          * dirrem which is usually done in handle_workitem_remove. We set
9374          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9375          * followup dirrem.
9376          */
9377         if (isrmdir > 1)
9378                 dirrem->dm_state |= DIRCHG;
9379
9380         /*
9381          * Whiteouts have no additional dependencies,
9382          * so just put the dirrem on the correct list.
9383          */
9384         if (newinum == UFS_WINO) {
9385                 if ((dirrem->dm_state & COMPLETE) == 0) {
9386                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9387                             dm_next);
9388                 } else {
9389                         dirrem->dm_dirinum = pagedep->pd_ino;
9390                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9391                                 add_to_worklist(&dirrem->dm_list, 0);
9392                 }
9393                 FREE_LOCK(ump);
9394                 return;
9395         }
9396         /*
9397          * Add the dirrem to the inodedep's pending remove list for quick
9398          * discovery later.  A valid nlinkdelta ensures that this lookup
9399          * will not fail.
9400          */
9401         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9402                 panic("softdep_setup_directory_change: Lost inodedep.");
9403         dirrem->dm_state |= ONDEPLIST;
9404         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9405
9406         /*
9407          * If the COMPLETE flag is clear, then there were no active
9408          * entries and we want to roll back to the previous inode until
9409          * the new inode is committed to disk. If the COMPLETE flag is
9410          * set, then we have deleted an entry that never made it to disk.
9411          * If the entry we deleted resulted from a name change, then the old
9412          * inode reference still resides on disk. Any rollback that we do
9413          * needs to be to that old inode (returned to us in prevdirrem). If
9414          * the entry we deleted resulted from a create, then there is
9415          * no entry on the disk, so we want to roll back to zero rather
9416          * than the uncommitted inode. In either of the COMPLETE cases we
9417          * want to immediately free the unwritten and unreferenced inode.
9418          */
9419         if ((dirrem->dm_state & COMPLETE) == 0) {
9420                 dap->da_previous = dirrem;
9421         } else {
9422                 if (prevdirrem != NULL) {
9423                         dap->da_previous = prevdirrem;
9424                 } else {
9425                         dap->da_state &= ~DIRCHG;
9426                         dap->da_pagedep = pagedep;
9427                 }
9428                 dirrem->dm_dirinum = pagedep->pd_ino;
9429                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9430                         add_to_worklist(&dirrem->dm_list, 0);
9431         }
9432         /*
9433          * Lookup the jaddref for this journal entry.  We must finish
9434          * initializing it and make the diradd write dependent on it.
9435          * If we're not journaling, put it on the id_bufwait list if the
9436          * inode is not yet written. If it is written, do the post-inode
9437          * write processing to put it on the id_pendinghd list.
9438          */
9439         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9440         if (MOUNTEDSUJ(mp)) {
9441                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9442                     inoreflst);
9443                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9444                     ("softdep_setup_directory_change: bad jaddref %p",
9445                     jaddref));
9446                 jaddref->ja_diroff = dp->i_offset;
9447                 jaddref->ja_diradd = dap;
9448                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9449                     dap, da_pdlist);
9450                 add_to_journal(&jaddref->ja_list);
9451         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9452                 dap->da_state |= COMPLETE;
9453                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9454                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9455         } else {
9456                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9457                     dap, da_pdlist);
9458                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9459         }
9460         /*
9461          * If we're making a new name for a directory that has not been
9462          * committed when need to move the dot and dotdot references to
9463          * this new name.
9464          */
9465         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9466                 merge_diradd(inodedep, dap);
9467         FREE_LOCK(ump);
9468 }
9469
9470 /*
9471  * Called whenever the link count on an inode is changed.
9472  * It creates an inode dependency so that the new reference(s)
9473  * to the inode cannot be committed to disk until the updated
9474  * inode has been written.
9475  */
9476 void
9477 softdep_change_linkcnt(ip)
9478         struct inode *ip;       /* the inode with the increased link count */
9479 {
9480         struct inodedep *inodedep;
9481         struct ufsmount *ump;
9482
9483         ump = ITOUMP(ip);
9484         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9485             ("softdep_change_linkcnt called on non-softdep filesystem"));
9486         ACQUIRE_LOCK(ump);
9487         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9488         if (ip->i_nlink < ip->i_effnlink)
9489                 panic("softdep_change_linkcnt: bad delta");
9490         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9491         FREE_LOCK(ump);
9492 }
9493
9494 /*
9495  * Attach a sbdep dependency to the superblock buf so that we can keep
9496  * track of the head of the linked list of referenced but unlinked inodes.
9497  */
9498 void
9499 softdep_setup_sbupdate(ump, fs, bp)
9500         struct ufsmount *ump;
9501         struct fs *fs;
9502         struct buf *bp;
9503 {
9504         struct sbdep *sbdep;
9505         struct worklist *wk;
9506
9507         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9508             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9509         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9510                 if (wk->wk_type == D_SBDEP)
9511                         break;
9512         if (wk != NULL)
9513                 return;
9514         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9515         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9516         sbdep->sb_fs = fs;
9517         sbdep->sb_ump = ump;
9518         ACQUIRE_LOCK(ump);
9519         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9520         FREE_LOCK(ump);
9521 }
9522
9523 /*
9524  * Return the first unlinked inodedep which is ready to be the head of the
9525  * list.  The inodedep and all those after it must have valid next pointers.
9526  */
9527 static struct inodedep *
9528 first_unlinked_inodedep(ump)
9529         struct ufsmount *ump;
9530 {
9531         struct inodedep *inodedep;
9532         struct inodedep *idp;
9533
9534         LOCK_OWNED(ump);
9535         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9536             inodedep; inodedep = idp) {
9537                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9538                         return (NULL);
9539                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9540                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9541                         break;
9542                 if ((inodedep->id_state & UNLINKPREV) == 0)
9543                         break;
9544         }
9545         return (inodedep);
9546 }
9547
9548 /*
9549  * Set the sujfree unlinked head pointer prior to writing a superblock.
9550  */
9551 static void
9552 initiate_write_sbdep(sbdep)
9553         struct sbdep *sbdep;
9554 {
9555         struct inodedep *inodedep;
9556         struct fs *bpfs;
9557         struct fs *fs;
9558
9559         bpfs = sbdep->sb_fs;
9560         fs = sbdep->sb_ump->um_fs;
9561         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9562         if (inodedep) {
9563                 fs->fs_sujfree = inodedep->id_ino;
9564                 inodedep->id_state |= UNLINKPREV;
9565         } else
9566                 fs->fs_sujfree = 0;
9567         bpfs->fs_sujfree = fs->fs_sujfree;
9568 }
9569
9570 /*
9571  * After a superblock is written determine whether it must be written again
9572  * due to a changing unlinked list head.
9573  */
9574 static int
9575 handle_written_sbdep(sbdep, bp)
9576         struct sbdep *sbdep;
9577         struct buf *bp;
9578 {
9579         struct inodedep *inodedep;
9580         struct fs *fs;
9581
9582         LOCK_OWNED(sbdep->sb_ump);
9583         fs = sbdep->sb_fs;
9584         /*
9585          * If the superblock doesn't match the in-memory list start over.
9586          */
9587         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9588         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9589             (inodedep == NULL && fs->fs_sujfree != 0)) {
9590                 bdirty(bp);
9591                 return (1);
9592         }
9593         WORKITEM_FREE(sbdep, D_SBDEP);
9594         if (fs->fs_sujfree == 0)
9595                 return (0);
9596         /*
9597          * Now that we have a record of this inode in stable store allow it
9598          * to be written to free up pending work.  Inodes may see a lot of
9599          * write activity after they are unlinked which we must not hold up.
9600          */
9601         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9602                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9603                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9604                             inodedep, inodedep->id_state);
9605                 if (inodedep->id_state & UNLINKONLIST)
9606                         break;
9607                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9608         }
9609
9610         return (0);
9611 }
9612
9613 /*
9614  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9615  */
9616 static void
9617 unlinked_inodedep(mp, inodedep)
9618         struct mount *mp;
9619         struct inodedep *inodedep;
9620 {
9621         struct ufsmount *ump;
9622
9623         ump = VFSTOUFS(mp);
9624         LOCK_OWNED(ump);
9625         if (MOUNTEDSUJ(mp) == 0)
9626                 return;
9627         ump->um_fs->fs_fmod = 1;
9628         if (inodedep->id_state & UNLINKED)
9629                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9630         inodedep->id_state |= UNLINKED;
9631         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9632 }
9633
9634 /*
9635  * Remove an inodedep from the unlinked inodedep list.  This may require
9636  * disk writes if the inode has made it that far.
9637  */
9638 static void
9639 clear_unlinked_inodedep(inodedep)
9640         struct inodedep *inodedep;
9641 {
9642         struct ufsmount *ump;
9643         struct inodedep *idp;
9644         struct inodedep *idn;
9645         struct fs *fs;
9646         struct buf *bp;
9647         ino_t ino;
9648         ino_t nino;
9649         ino_t pino;
9650         int error;
9651
9652         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9653         fs = ump->um_fs;
9654         ino = inodedep->id_ino;
9655         error = 0;
9656         for (;;) {
9657                 LOCK_OWNED(ump);
9658                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9659                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9660                     inodedep));
9661                 /*
9662                  * If nothing has yet been written simply remove us from
9663                  * the in memory list and return.  This is the most common
9664                  * case where handle_workitem_remove() loses the final
9665                  * reference.
9666                  */
9667                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9668                         break;
9669                 /*
9670                  * If we have a NEXT pointer and no PREV pointer we can simply
9671                  * clear NEXT's PREV and remove ourselves from the list.  Be
9672                  * careful not to clear PREV if the superblock points at
9673                  * next as well.
9674                  */
9675                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9676                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9677                         if (idn && fs->fs_sujfree != idn->id_ino)
9678                                 idn->id_state &= ~UNLINKPREV;
9679                         break;
9680                 }
9681                 /*
9682                  * Here we have an inodedep which is actually linked into
9683                  * the list.  We must remove it by forcing a write to the
9684                  * link before us, whether it be the superblock or an inode.
9685                  * Unfortunately the list may change while we're waiting
9686                  * on the buf lock for either resource so we must loop until
9687                  * we lock the right one.  If both the superblock and an
9688                  * inode point to this inode we must clear the inode first
9689                  * followed by the superblock.
9690                  */
9691                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9692                 pino = 0;
9693                 if (idp && (idp->id_state & UNLINKNEXT))
9694                         pino = idp->id_ino;
9695                 FREE_LOCK(ump);
9696                 if (pino == 0) {
9697                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9698                             (int)fs->fs_sbsize, 0, 0, 0);
9699                 } else {
9700                         error = bread(ump->um_devvp,
9701                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9702                             (int)fs->fs_bsize, NOCRED, &bp);
9703                         if (error)
9704                                 brelse(bp);
9705                 }
9706                 ACQUIRE_LOCK(ump);
9707                 if (error)
9708                         break;
9709                 /* If the list has changed restart the loop. */
9710                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9711                 nino = 0;
9712                 if (idp && (idp->id_state & UNLINKNEXT))
9713                         nino = idp->id_ino;
9714                 if (nino != pino ||
9715                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9716                         FREE_LOCK(ump);
9717                         brelse(bp);
9718                         ACQUIRE_LOCK(ump);
9719                         continue;
9720                 }
9721                 nino = 0;
9722                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9723                 if (idn)
9724                         nino = idn->id_ino;
9725                 /*
9726                  * Remove us from the in memory list.  After this we cannot
9727                  * access the inodedep.
9728                  */
9729                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9730                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9731                     inodedep));
9732                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9733                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9734                 FREE_LOCK(ump);
9735                 /*
9736                  * The predecessor's next pointer is manually updated here
9737                  * so that the NEXT flag is never cleared for an element
9738                  * that is in the list.
9739                  */
9740                 if (pino == 0) {
9741                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9742                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9743                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9744                             bp);
9745                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9746                         ((struct ufs1_dinode *)bp->b_data +
9747                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9748                 else
9749                         ((struct ufs2_dinode *)bp->b_data +
9750                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9751                 /*
9752                  * If the bwrite fails we have no recourse to recover.  The
9753                  * filesystem is corrupted already.
9754                  */
9755                 bwrite(bp);
9756                 ACQUIRE_LOCK(ump);
9757                 /*
9758                  * If the superblock pointer still needs to be cleared force
9759                  * a write here.
9760                  */
9761                 if (fs->fs_sujfree == ino) {
9762                         FREE_LOCK(ump);
9763                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9764                             (int)fs->fs_sbsize, 0, 0, 0);
9765                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9766                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9767                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9768                             bp);
9769                         bwrite(bp);
9770                         ACQUIRE_LOCK(ump);
9771                 }
9772
9773                 if (fs->fs_sujfree != ino)
9774                         return;
9775                 panic("clear_unlinked_inodedep: Failed to clear free head");
9776         }
9777         if (inodedep->id_ino == fs->fs_sujfree)
9778                 panic("clear_unlinked_inodedep: Freeing head of free list");
9779         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9780         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9781         return;
9782 }
9783
9784 /*
9785  * This workitem decrements the inode's link count.
9786  * If the link count reaches zero, the file is removed.
9787  */
9788 static int
9789 handle_workitem_remove(dirrem, flags)
9790         struct dirrem *dirrem;
9791         int flags;
9792 {
9793         struct inodedep *inodedep;
9794         struct workhead dotdotwk;
9795         struct worklist *wk;
9796         struct ufsmount *ump;
9797         struct mount *mp;
9798         struct vnode *vp;
9799         struct inode *ip;
9800         ino_t oldinum;
9801
9802         if (dirrem->dm_state & ONWORKLIST)
9803                 panic("handle_workitem_remove: dirrem %p still on worklist",
9804                     dirrem);
9805         oldinum = dirrem->dm_oldinum;
9806         mp = dirrem->dm_list.wk_mp;
9807         ump = VFSTOUFS(mp);
9808         flags |= LK_EXCLUSIVE;
9809         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9810                 return (EBUSY);
9811         ip = VTOI(vp);
9812         ACQUIRE_LOCK(ump);
9813         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9814                 panic("handle_workitem_remove: lost inodedep");
9815         if (dirrem->dm_state & ONDEPLIST)
9816                 LIST_REMOVE(dirrem, dm_inonext);
9817         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9818             ("handle_workitem_remove:  Journal entries not written."));
9819
9820         /*
9821          * Move all dependencies waiting on the remove to complete
9822          * from the dirrem to the inode inowait list to be completed
9823          * after the inode has been updated and written to disk.  Any
9824          * marked MKDIR_PARENT are saved to be completed when the .. ref
9825          * is removed.
9826          */
9827         LIST_INIT(&dotdotwk);
9828         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9829                 WORKLIST_REMOVE(wk);
9830                 if (wk->wk_state & MKDIR_PARENT) {
9831                         wk->wk_state &= ~MKDIR_PARENT;
9832                         WORKLIST_INSERT(&dotdotwk, wk);
9833                         continue;
9834                 }
9835                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9836         }
9837         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9838         /*
9839          * Normal file deletion.
9840          */
9841         if ((dirrem->dm_state & RMDIR) == 0) {
9842                 ip->i_nlink--;
9843                 DIP_SET(ip, i_nlink, ip->i_nlink);
9844                 ip->i_flag |= IN_CHANGE;
9845                 if (ip->i_nlink < ip->i_effnlink)
9846                         panic("handle_workitem_remove: bad file delta");
9847                 if (ip->i_nlink == 0) 
9848                         unlinked_inodedep(mp, inodedep);
9849                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9850                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9851                     ("handle_workitem_remove: worklist not empty. %s",
9852                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9853                 WORKITEM_FREE(dirrem, D_DIRREM);
9854                 FREE_LOCK(ump);
9855                 goto out;
9856         }
9857         /*
9858          * Directory deletion. Decrement reference count for both the
9859          * just deleted parent directory entry and the reference for ".".
9860          * Arrange to have the reference count on the parent decremented
9861          * to account for the loss of "..".
9862          */
9863         ip->i_nlink -= 2;
9864         DIP_SET(ip, i_nlink, ip->i_nlink);
9865         ip->i_flag |= IN_CHANGE;
9866         if (ip->i_nlink < ip->i_effnlink)
9867                 panic("handle_workitem_remove: bad dir delta");
9868         if (ip->i_nlink == 0)
9869                 unlinked_inodedep(mp, inodedep);
9870         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9871         /*
9872          * Rename a directory to a new parent. Since, we are both deleting
9873          * and creating a new directory entry, the link count on the new
9874          * directory should not change. Thus we skip the followup dirrem.
9875          */
9876         if (dirrem->dm_state & DIRCHG) {
9877                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9878                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9879                 WORKITEM_FREE(dirrem, D_DIRREM);
9880                 FREE_LOCK(ump);
9881                 goto out;
9882         }
9883         dirrem->dm_state = ONDEPLIST;
9884         dirrem->dm_oldinum = dirrem->dm_dirinum;
9885         /*
9886          * Place the dirrem on the parent's diremhd list.
9887          */
9888         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9889                 panic("handle_workitem_remove: lost dir inodedep");
9890         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9891         /*
9892          * If the allocated inode has never been written to disk, then
9893          * the on-disk inode is zero'ed and we can remove the file
9894          * immediately.  When journaling if the inode has been marked
9895          * unlinked and not DEPCOMPLETE we know it can never be written.
9896          */
9897         inodedep_lookup(mp, oldinum, 0, &inodedep);
9898         if (inodedep == NULL ||
9899             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9900             check_inode_unwritten(inodedep)) {
9901                 FREE_LOCK(ump);
9902                 vput(vp);
9903                 return handle_workitem_remove(dirrem, flags);
9904         }
9905         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9906         FREE_LOCK(ump);
9907         ip->i_flag |= IN_CHANGE;
9908 out:
9909         ffs_update(vp, 0);
9910         vput(vp);
9911         return (0);
9912 }
9913
9914 /*
9915  * Inode de-allocation dependencies.
9916  * 
9917  * When an inode's link count is reduced to zero, it can be de-allocated. We
9918  * found it convenient to postpone de-allocation until after the inode is
9919  * written to disk with its new link count (zero).  At this point, all of the
9920  * on-disk inode's block pointers are nullified and, with careful dependency
9921  * list ordering, all dependencies related to the inode will be satisfied and
9922  * the corresponding dependency structures de-allocated.  So, if/when the
9923  * inode is reused, there will be no mixing of old dependencies with new
9924  * ones.  This artificial dependency is set up by the block de-allocation
9925  * procedure above (softdep_setup_freeblocks) and completed by the
9926  * following procedure.
9927  */
9928 static void 
9929 handle_workitem_freefile(freefile)
9930         struct freefile *freefile;
9931 {
9932         struct workhead wkhd;
9933         struct fs *fs;
9934         struct inodedep *idp;
9935         struct ufsmount *ump;
9936         int error;
9937
9938         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9939         fs = ump->um_fs;
9940 #ifdef DEBUG
9941         ACQUIRE_LOCK(ump);
9942         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9943         FREE_LOCK(ump);
9944         if (error)
9945                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9946 #endif
9947         UFS_LOCK(ump);
9948         fs->fs_pendinginodes -= 1;
9949         UFS_UNLOCK(ump);
9950         LIST_INIT(&wkhd);
9951         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9952         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9953             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9954                 softdep_error("handle_workitem_freefile", error);
9955         ACQUIRE_LOCK(ump);
9956         WORKITEM_FREE(freefile, D_FREEFILE);
9957         FREE_LOCK(ump);
9958 }
9959
9960
9961 /*
9962  * Helper function which unlinks marker element from work list and returns
9963  * the next element on the list.
9964  */
9965 static __inline struct worklist *
9966 markernext(struct worklist *marker)
9967 {
9968         struct worklist *next;
9969         
9970         next = LIST_NEXT(marker, wk_list);
9971         LIST_REMOVE(marker, wk_list);
9972         return next;
9973 }
9974
9975 /*
9976  * Disk writes.
9977  * 
9978  * The dependency structures constructed above are most actively used when file
9979  * system blocks are written to disk.  No constraints are placed on when a
9980  * block can be written, but unsatisfied update dependencies are made safe by
9981  * modifying (or replacing) the source memory for the duration of the disk
9982  * write.  When the disk write completes, the memory block is again brought
9983  * up-to-date.
9984  *
9985  * In-core inode structure reclamation.
9986  * 
9987  * Because there are a finite number of "in-core" inode structures, they are
9988  * reused regularly.  By transferring all inode-related dependencies to the
9989  * in-memory inode block and indexing them separately (via "inodedep"s), we
9990  * can allow "in-core" inode structures to be reused at any time and avoid
9991  * any increase in contention.
9992  *
9993  * Called just before entering the device driver to initiate a new disk I/O.
9994  * The buffer must be locked, thus, no I/O completion operations can occur
9995  * while we are manipulating its associated dependencies.
9996  */
9997 static void 
9998 softdep_disk_io_initiation(bp)
9999         struct buf *bp;         /* structure describing disk write to occur */
10000 {
10001         struct worklist *wk;
10002         struct worklist marker;
10003         struct inodedep *inodedep;
10004         struct freeblks *freeblks;
10005         struct jblkdep *jblkdep;
10006         struct newblk *newblk;
10007         struct ufsmount *ump;
10008
10009         /*
10010          * We only care about write operations. There should never
10011          * be dependencies for reads.
10012          */
10013         if (bp->b_iocmd != BIO_WRITE)
10014                 panic("softdep_disk_io_initiation: not write");
10015
10016         if (bp->b_vflags & BV_BKGRDINPROG)
10017                 panic("softdep_disk_io_initiation: Writing buffer with "
10018                     "background write in progress: %p", bp);
10019
10020         ump = softdep_bp_to_mp(bp);
10021         if (ump == NULL)
10022                 return;
10023
10024         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
10025         PHOLD(curproc);                 /* Don't swap out kernel stack */
10026         ACQUIRE_LOCK(ump);
10027         /*
10028          * Do any necessary pre-I/O processing.
10029          */
10030         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10031              wk = markernext(&marker)) {
10032                 LIST_INSERT_AFTER(wk, &marker, wk_list);
10033                 switch (wk->wk_type) {
10034
10035                 case D_PAGEDEP:
10036                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10037                         continue;
10038
10039                 case D_INODEDEP:
10040                         inodedep = WK_INODEDEP(wk);
10041                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10042                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10043                         else
10044                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10045                         continue;
10046
10047                 case D_INDIRDEP:
10048                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10049                         continue;
10050
10051                 case D_BMSAFEMAP:
10052                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10053                         continue;
10054
10055                 case D_JSEG:
10056                         WK_JSEG(wk)->js_buf = NULL;
10057                         continue;
10058
10059                 case D_FREEBLKS:
10060                         freeblks = WK_FREEBLKS(wk);
10061                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10062                         /*
10063                          * We have to wait for the freeblks to be journaled
10064                          * before we can write an inodeblock with updated
10065                          * pointers.  Be careful to arrange the marker so
10066                          * we revisit the freeblks if it's not removed by
10067                          * the first jwait().
10068                          */
10069                         if (jblkdep != NULL) {
10070                                 LIST_REMOVE(&marker, wk_list);
10071                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10072                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10073                         }
10074                         continue;
10075                 case D_ALLOCDIRECT:
10076                 case D_ALLOCINDIR:
10077                         /*
10078                          * We have to wait for the jnewblk to be journaled
10079                          * before we can write to a block if the contents
10080                          * may be confused with an earlier file's indirect
10081                          * at recovery time.  Handle the marker as described
10082                          * above.
10083                          */
10084                         newblk = WK_NEWBLK(wk);
10085                         if (newblk->nb_jnewblk != NULL &&
10086                             indirblk_lookup(newblk->nb_list.wk_mp,
10087                             newblk->nb_newblkno)) {
10088                                 LIST_REMOVE(&marker, wk_list);
10089                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10090                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10091                         }
10092                         continue;
10093
10094                 case D_SBDEP:
10095                         initiate_write_sbdep(WK_SBDEP(wk));
10096                         continue;
10097
10098                 case D_MKDIR:
10099                 case D_FREEWORK:
10100                 case D_FREEDEP:
10101                 case D_JSEGDEP:
10102                         continue;
10103
10104                 default:
10105                         panic("handle_disk_io_initiation: Unexpected type %s",
10106                             TYPENAME(wk->wk_type));
10107                         /* NOTREACHED */
10108                 }
10109         }
10110         FREE_LOCK(ump);
10111         PRELE(curproc);                 /* Allow swapout of kernel stack */
10112 }
10113
10114 /*
10115  * Called from within the procedure above to deal with unsatisfied
10116  * allocation dependencies in a directory. The buffer must be locked,
10117  * thus, no I/O completion operations can occur while we are
10118  * manipulating its associated dependencies.
10119  */
10120 static void
10121 initiate_write_filepage(pagedep, bp)
10122         struct pagedep *pagedep;
10123         struct buf *bp;
10124 {
10125         struct jremref *jremref;
10126         struct jmvref *jmvref;
10127         struct dirrem *dirrem;
10128         struct diradd *dap;
10129         struct direct *ep;
10130         int i;
10131
10132         if (pagedep->pd_state & IOSTARTED) {
10133                 /*
10134                  * This can only happen if there is a driver that does not
10135                  * understand chaining. Here biodone will reissue the call
10136                  * to strategy for the incomplete buffers.
10137                  */
10138                 printf("initiate_write_filepage: already started\n");
10139                 return;
10140         }
10141         pagedep->pd_state |= IOSTARTED;
10142         /*
10143          * Wait for all journal remove dependencies to hit the disk.
10144          * We can not allow any potentially conflicting directory adds
10145          * to be visible before removes and rollback is too difficult.
10146          * The per-filesystem lock may be dropped and re-acquired, however 
10147          * we hold the buf locked so the dependency can not go away.
10148          */
10149         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10150                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10151                         jwait(&jremref->jr_list, MNT_WAIT);
10152         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10153                 jwait(&jmvref->jm_list, MNT_WAIT);
10154         for (i = 0; i < DAHASHSZ; i++) {
10155                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10156                         ep = (struct direct *)
10157                             ((char *)bp->b_data + dap->da_offset);
10158                         if (ep->d_ino != dap->da_newinum)
10159                                 panic("%s: dir inum %ju != new %ju",
10160                                     "initiate_write_filepage",
10161                                     (uintmax_t)ep->d_ino,
10162                                     (uintmax_t)dap->da_newinum);
10163                         if (dap->da_state & DIRCHG)
10164                                 ep->d_ino = dap->da_previous->dm_oldinum;
10165                         else
10166                                 ep->d_ino = 0;
10167                         dap->da_state &= ~ATTACHED;
10168                         dap->da_state |= UNDONE;
10169                 }
10170         }
10171 }
10172
10173 /*
10174  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10175  * Note that any bug fixes made to this routine must be done in the
10176  * version found below.
10177  *
10178  * Called from within the procedure above to deal with unsatisfied
10179  * allocation dependencies in an inodeblock. The buffer must be
10180  * locked, thus, no I/O completion operations can occur while we
10181  * are manipulating its associated dependencies.
10182  */
10183 static void 
10184 initiate_write_inodeblock_ufs1(inodedep, bp)
10185         struct inodedep *inodedep;
10186         struct buf *bp;                 /* The inode block */
10187 {
10188         struct allocdirect *adp, *lastadp;
10189         struct ufs1_dinode *dp;
10190         struct ufs1_dinode *sip;
10191         struct inoref *inoref;
10192         struct ufsmount *ump;
10193         struct fs *fs;
10194         ufs_lbn_t i;
10195 #ifdef INVARIANTS
10196         ufs_lbn_t prevlbn = 0;
10197 #endif
10198         int deplist;
10199
10200         if (inodedep->id_state & IOSTARTED)
10201                 panic("initiate_write_inodeblock_ufs1: already started");
10202         inodedep->id_state |= IOSTARTED;
10203         fs = inodedep->id_fs;
10204         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10205         LOCK_OWNED(ump);
10206         dp = (struct ufs1_dinode *)bp->b_data +
10207             ino_to_fsbo(fs, inodedep->id_ino);
10208
10209         /*
10210          * If we're on the unlinked list but have not yet written our
10211          * next pointer initialize it here.
10212          */
10213         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10214                 struct inodedep *inon;
10215
10216                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10217                 dp->di_freelink = inon ? inon->id_ino : 0;
10218         }
10219         /*
10220          * If the bitmap is not yet written, then the allocated
10221          * inode cannot be written to disk.
10222          */
10223         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10224                 if (inodedep->id_savedino1 != NULL)
10225                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10226                 FREE_LOCK(ump);
10227                 sip = malloc(sizeof(struct ufs1_dinode),
10228                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10229                 ACQUIRE_LOCK(ump);
10230                 inodedep->id_savedino1 = sip;
10231                 *inodedep->id_savedino1 = *dp;
10232                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10233                 dp->di_gen = inodedep->id_savedino1->di_gen;
10234                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10235                 return;
10236         }
10237         /*
10238          * If no dependencies, then there is nothing to roll back.
10239          */
10240         inodedep->id_savedsize = dp->di_size;
10241         inodedep->id_savedextsize = 0;
10242         inodedep->id_savednlink = dp->di_nlink;
10243         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10244             TAILQ_EMPTY(&inodedep->id_inoreflst))
10245                 return;
10246         /*
10247          * Revert the link count to that of the first unwritten journal entry.
10248          */
10249         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10250         if (inoref)
10251                 dp->di_nlink = inoref->if_nlink;
10252         /*
10253          * Set the dependencies to busy.
10254          */
10255         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10256              adp = TAILQ_NEXT(adp, ad_next)) {
10257 #ifdef INVARIANTS
10258                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10259                         panic("softdep_write_inodeblock: lbn order");
10260                 prevlbn = adp->ad_offset;
10261                 if (adp->ad_offset < UFS_NDADDR &&
10262                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10263                         panic("initiate_write_inodeblock_ufs1: "
10264                             "direct pointer #%jd mismatch %d != %jd",
10265                             (intmax_t)adp->ad_offset,
10266                             dp->di_db[adp->ad_offset],
10267                             (intmax_t)adp->ad_newblkno);
10268                 if (adp->ad_offset >= UFS_NDADDR &&
10269                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10270                         panic("initiate_write_inodeblock_ufs1: "
10271                             "indirect pointer #%jd mismatch %d != %jd",
10272                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10273                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10274                             (intmax_t)adp->ad_newblkno);
10275                 deplist |= 1 << adp->ad_offset;
10276                 if ((adp->ad_state & ATTACHED) == 0)
10277                         panic("initiate_write_inodeblock_ufs1: "
10278                             "Unknown state 0x%x", adp->ad_state);
10279 #endif /* INVARIANTS */
10280                 adp->ad_state &= ~ATTACHED;
10281                 adp->ad_state |= UNDONE;
10282         }
10283         /*
10284          * The on-disk inode cannot claim to be any larger than the last
10285          * fragment that has been written. Otherwise, the on-disk inode
10286          * might have fragments that were not the last block in the file
10287          * which would corrupt the filesystem.
10288          */
10289         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10290              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10291                 if (adp->ad_offset >= UFS_NDADDR)
10292                         break;
10293                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10294                 /* keep going until hitting a rollback to a frag */
10295                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10296                         continue;
10297                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10298                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10299 #ifdef INVARIANTS
10300                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10301                                 panic("initiate_write_inodeblock_ufs1: "
10302                                     "lost dep1");
10303 #endif /* INVARIANTS */
10304                         dp->di_db[i] = 0;
10305                 }
10306                 for (i = 0; i < UFS_NIADDR; i++) {
10307 #ifdef INVARIANTS
10308                         if (dp->di_ib[i] != 0 &&
10309                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10310                                 panic("initiate_write_inodeblock_ufs1: "
10311                                     "lost dep2");
10312 #endif /* INVARIANTS */
10313                         dp->di_ib[i] = 0;
10314                 }
10315                 return;
10316         }
10317         /*
10318          * If we have zero'ed out the last allocated block of the file,
10319          * roll back the size to the last currently allocated block.
10320          * We know that this last allocated block is a full-sized as
10321          * we already checked for fragments in the loop above.
10322          */
10323         if (lastadp != NULL &&
10324             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10325                 for (i = lastadp->ad_offset; i >= 0; i--)
10326                         if (dp->di_db[i] != 0)
10327                                 break;
10328                 dp->di_size = (i + 1) * fs->fs_bsize;
10329         }
10330         /*
10331          * The only dependencies are for indirect blocks.
10332          *
10333          * The file size for indirect block additions is not guaranteed.
10334          * Such a guarantee would be non-trivial to achieve. The conventional
10335          * synchronous write implementation also does not make this guarantee.
10336          * Fsck should catch and fix discrepancies. Arguably, the file size
10337          * can be over-estimated without destroying integrity when the file
10338          * moves into the indirect blocks (i.e., is large). If we want to
10339          * postpone fsck, we are stuck with this argument.
10340          */
10341         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10342                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10343 }
10344                 
10345 /*
10346  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10347  * Note that any bug fixes made to this routine must be done in the
10348  * version found above.
10349  *
10350  * Called from within the procedure above to deal with unsatisfied
10351  * allocation dependencies in an inodeblock. The buffer must be
10352  * locked, thus, no I/O completion operations can occur while we
10353  * are manipulating its associated dependencies.
10354  */
10355 static void 
10356 initiate_write_inodeblock_ufs2(inodedep, bp)
10357         struct inodedep *inodedep;
10358         struct buf *bp;                 /* The inode block */
10359 {
10360         struct allocdirect *adp, *lastadp;
10361         struct ufs2_dinode *dp;
10362         struct ufs2_dinode *sip;
10363         struct inoref *inoref;
10364         struct ufsmount *ump;
10365         struct fs *fs;
10366         ufs_lbn_t i;
10367 #ifdef INVARIANTS
10368         ufs_lbn_t prevlbn = 0;
10369 #endif
10370         int deplist;
10371
10372         if (inodedep->id_state & IOSTARTED)
10373                 panic("initiate_write_inodeblock_ufs2: already started");
10374         inodedep->id_state |= IOSTARTED;
10375         fs = inodedep->id_fs;
10376         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10377         LOCK_OWNED(ump);
10378         dp = (struct ufs2_dinode *)bp->b_data +
10379             ino_to_fsbo(fs, inodedep->id_ino);
10380
10381         /*
10382          * If we're on the unlinked list but have not yet written our
10383          * next pointer initialize it here.
10384          */
10385         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10386                 struct inodedep *inon;
10387
10388                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10389                 dp->di_freelink = inon ? inon->id_ino : 0;
10390         }
10391         /*
10392          * If the bitmap is not yet written, then the allocated
10393          * inode cannot be written to disk.
10394          */
10395         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10396                 if (inodedep->id_savedino2 != NULL)
10397                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10398                 FREE_LOCK(ump);
10399                 sip = malloc(sizeof(struct ufs2_dinode),
10400                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10401                 ACQUIRE_LOCK(ump);
10402                 inodedep->id_savedino2 = sip;
10403                 *inodedep->id_savedino2 = *dp;
10404                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10405                 dp->di_gen = inodedep->id_savedino2->di_gen;
10406                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10407                 return;
10408         }
10409         /*
10410          * If no dependencies, then there is nothing to roll back.
10411          */
10412         inodedep->id_savedsize = dp->di_size;
10413         inodedep->id_savedextsize = dp->di_extsize;
10414         inodedep->id_savednlink = dp->di_nlink;
10415         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10416             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10417             TAILQ_EMPTY(&inodedep->id_inoreflst))
10418                 return;
10419         /*
10420          * Revert the link count to that of the first unwritten journal entry.
10421          */
10422         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10423         if (inoref)
10424                 dp->di_nlink = inoref->if_nlink;
10425
10426         /*
10427          * Set the ext data dependencies to busy.
10428          */
10429         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10430              adp = TAILQ_NEXT(adp, ad_next)) {
10431 #ifdef INVARIANTS
10432                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10433                         panic("initiate_write_inodeblock_ufs2: lbn order");
10434                 prevlbn = adp->ad_offset;
10435                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10436                         panic("initiate_write_inodeblock_ufs2: "
10437                             "ext pointer #%jd mismatch %jd != %jd",
10438                             (intmax_t)adp->ad_offset,
10439                             (intmax_t)dp->di_extb[adp->ad_offset],
10440                             (intmax_t)adp->ad_newblkno);
10441                 deplist |= 1 << adp->ad_offset;
10442                 if ((adp->ad_state & ATTACHED) == 0)
10443                         panic("initiate_write_inodeblock_ufs2: Unknown "
10444                             "state 0x%x", adp->ad_state);
10445 #endif /* INVARIANTS */
10446                 adp->ad_state &= ~ATTACHED;
10447                 adp->ad_state |= UNDONE;
10448         }
10449         /*
10450          * The on-disk inode cannot claim to be any larger than the last
10451          * fragment that has been written. Otherwise, the on-disk inode
10452          * might have fragments that were not the last block in the ext
10453          * data which would corrupt the filesystem.
10454          */
10455         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10456              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10457                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10458                 /* keep going until hitting a rollback to a frag */
10459                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10460                         continue;
10461                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10462                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10463 #ifdef INVARIANTS
10464                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10465                                 panic("initiate_write_inodeblock_ufs2: "
10466                                     "lost dep1");
10467 #endif /* INVARIANTS */
10468                         dp->di_extb[i] = 0;
10469                 }
10470                 lastadp = NULL;
10471                 break;
10472         }
10473         /*
10474          * If we have zero'ed out the last allocated block of the ext
10475          * data, roll back the size to the last currently allocated block.
10476          * We know that this last allocated block is a full-sized as
10477          * we already checked for fragments in the loop above.
10478          */
10479         if (lastadp != NULL &&
10480             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10481                 for (i = lastadp->ad_offset; i >= 0; i--)
10482                         if (dp->di_extb[i] != 0)
10483                                 break;
10484                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10485         }
10486         /*
10487          * Set the file data dependencies to busy.
10488          */
10489         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10490              adp = TAILQ_NEXT(adp, ad_next)) {
10491 #ifdef INVARIANTS
10492                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10493                         panic("softdep_write_inodeblock: lbn order");
10494                 if ((adp->ad_state & ATTACHED) == 0)
10495                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10496                 prevlbn = adp->ad_offset;
10497                 if (adp->ad_offset < UFS_NDADDR &&
10498                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10499                         panic("initiate_write_inodeblock_ufs2: "
10500                             "direct pointer #%jd mismatch %jd != %jd",
10501                             (intmax_t)adp->ad_offset,
10502                             (intmax_t)dp->di_db[adp->ad_offset],
10503                             (intmax_t)adp->ad_newblkno);
10504                 if (adp->ad_offset >= UFS_NDADDR &&
10505                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10506                         panic("initiate_write_inodeblock_ufs2: "
10507                             "indirect pointer #%jd mismatch %jd != %jd",
10508                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10509                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10510                             (intmax_t)adp->ad_newblkno);
10511                 deplist |= 1 << adp->ad_offset;
10512                 if ((adp->ad_state & ATTACHED) == 0)
10513                         panic("initiate_write_inodeblock_ufs2: Unknown "
10514                              "state 0x%x", adp->ad_state);
10515 #endif /* INVARIANTS */
10516                 adp->ad_state &= ~ATTACHED;
10517                 adp->ad_state |= UNDONE;
10518         }
10519         /*
10520          * The on-disk inode cannot claim to be any larger than the last
10521          * fragment that has been written. Otherwise, the on-disk inode
10522          * might have fragments that were not the last block in the file
10523          * which would corrupt the filesystem.
10524          */
10525         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10526              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10527                 if (adp->ad_offset >= UFS_NDADDR)
10528                         break;
10529                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10530                 /* keep going until hitting a rollback to a frag */
10531                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10532                         continue;
10533                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10534                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10535 #ifdef INVARIANTS
10536                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10537                                 panic("initiate_write_inodeblock_ufs2: "
10538                                     "lost dep2");
10539 #endif /* INVARIANTS */
10540                         dp->di_db[i] = 0;
10541                 }
10542                 for (i = 0; i < UFS_NIADDR; i++) {
10543 #ifdef INVARIANTS
10544                         if (dp->di_ib[i] != 0 &&
10545                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10546                                 panic("initiate_write_inodeblock_ufs2: "
10547                                     "lost dep3");
10548 #endif /* INVARIANTS */
10549                         dp->di_ib[i] = 0;
10550                 }
10551                 return;
10552         }
10553         /*
10554          * If we have zero'ed out the last allocated block of the file,
10555          * roll back the size to the last currently allocated block.
10556          * We know that this last allocated block is a full-sized as
10557          * we already checked for fragments in the loop above.
10558          */
10559         if (lastadp != NULL &&
10560             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10561                 for (i = lastadp->ad_offset; i >= 0; i--)
10562                         if (dp->di_db[i] != 0)
10563                                 break;
10564                 dp->di_size = (i + 1) * fs->fs_bsize;
10565         }
10566         /*
10567          * The only dependencies are for indirect blocks.
10568          *
10569          * The file size for indirect block additions is not guaranteed.
10570          * Such a guarantee would be non-trivial to achieve. The conventional
10571          * synchronous write implementation also does not make this guarantee.
10572          * Fsck should catch and fix discrepancies. Arguably, the file size
10573          * can be over-estimated without destroying integrity when the file
10574          * moves into the indirect blocks (i.e., is large). If we want to
10575          * postpone fsck, we are stuck with this argument.
10576          */
10577         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10578                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10579 }
10580
10581 /*
10582  * Cancel an indirdep as a result of truncation.  Release all of the
10583  * children allocindirs and place their journal work on the appropriate
10584  * list.
10585  */
10586 static void
10587 cancel_indirdep(indirdep, bp, freeblks)
10588         struct indirdep *indirdep;
10589         struct buf *bp;
10590         struct freeblks *freeblks;
10591 {
10592         struct allocindir *aip;
10593
10594         /*
10595          * None of the indirect pointers will ever be visible,
10596          * so they can simply be tossed. GOINGAWAY ensures
10597          * that allocated pointers will be saved in the buffer
10598          * cache until they are freed. Note that they will
10599          * only be able to be found by their physical address
10600          * since the inode mapping the logical address will
10601          * be gone. The save buffer used for the safe copy
10602          * was allocated in setup_allocindir_phase2 using
10603          * the physical address so it could be used for this
10604          * purpose. Hence we swap the safe copy with the real
10605          * copy, allowing the safe copy to be freed and holding
10606          * on to the real copy for later use in indir_trunc.
10607          */
10608         if (indirdep->ir_state & GOINGAWAY)
10609                 panic("cancel_indirdep: already gone");
10610         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10611                 indirdep->ir_state |= DEPCOMPLETE;
10612                 LIST_REMOVE(indirdep, ir_next);
10613         }
10614         indirdep->ir_state |= GOINGAWAY;
10615         /*
10616          * Pass in bp for blocks still have journal writes
10617          * pending so we can cancel them on their own.
10618          */
10619         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10620                 cancel_allocindir(aip, bp, freeblks, 0);
10621         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10622                 cancel_allocindir(aip, NULL, freeblks, 0);
10623         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10624                 cancel_allocindir(aip, NULL, freeblks, 0);
10625         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10626                 cancel_allocindir(aip, NULL, freeblks, 0);
10627         /*
10628          * If there are pending partial truncations we need to keep the
10629          * old block copy around until they complete.  This is because
10630          * the current b_data is not a perfect superset of the available
10631          * blocks.
10632          */
10633         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10634                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10635         else
10636                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10637         WORKLIST_REMOVE(&indirdep->ir_list);
10638         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10639         indirdep->ir_bp = NULL;
10640         indirdep->ir_freeblks = freeblks;
10641 }
10642
10643 /*
10644  * Free an indirdep once it no longer has new pointers to track.
10645  */
10646 static void
10647 free_indirdep(indirdep)
10648         struct indirdep *indirdep;
10649 {
10650
10651         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10652             ("free_indirdep: Indir trunc list not empty."));
10653         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10654             ("free_indirdep: Complete head not empty."));
10655         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10656             ("free_indirdep: write head not empty."));
10657         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10658             ("free_indirdep: done head not empty."));
10659         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10660             ("free_indirdep: deplist head not empty."));
10661         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10662             ("free_indirdep: %p still on newblk list.", indirdep));
10663         KASSERT(indirdep->ir_saveddata == NULL,
10664             ("free_indirdep: %p still has saved data.", indirdep));
10665         if (indirdep->ir_state & ONWORKLIST)
10666                 WORKLIST_REMOVE(&indirdep->ir_list);
10667         WORKITEM_FREE(indirdep, D_INDIRDEP);
10668 }
10669
10670 /*
10671  * Called before a write to an indirdep.  This routine is responsible for
10672  * rolling back pointers to a safe state which includes only those
10673  * allocindirs which have been completed.
10674  */
10675 static void
10676 initiate_write_indirdep(indirdep, bp)
10677         struct indirdep *indirdep;
10678         struct buf *bp;
10679 {
10680         struct ufsmount *ump;
10681
10682         indirdep->ir_state |= IOSTARTED;
10683         if (indirdep->ir_state & GOINGAWAY)
10684                 panic("disk_io_initiation: indirdep gone");
10685         /*
10686          * If there are no remaining dependencies, this will be writing
10687          * the real pointers.
10688          */
10689         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10690             TAILQ_EMPTY(&indirdep->ir_trunc))
10691                 return;
10692         /*
10693          * Replace up-to-date version with safe version.
10694          */
10695         if (indirdep->ir_saveddata == NULL) {
10696                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10697                 LOCK_OWNED(ump);
10698                 FREE_LOCK(ump);
10699                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10700                     M_SOFTDEP_FLAGS);
10701                 ACQUIRE_LOCK(ump);
10702         }
10703         indirdep->ir_state &= ~ATTACHED;
10704         indirdep->ir_state |= UNDONE;
10705         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10706         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10707             bp->b_bcount);
10708 }
10709
10710 /*
10711  * Called when an inode has been cleared in a cg bitmap.  This finally
10712  * eliminates any canceled jaddrefs
10713  */
10714 void
10715 softdep_setup_inofree(mp, bp, ino, wkhd)
10716         struct mount *mp;
10717         struct buf *bp;
10718         ino_t ino;
10719         struct workhead *wkhd;
10720 {
10721         struct worklist *wk, *wkn;
10722         struct inodedep *inodedep;
10723         struct ufsmount *ump;
10724         uint8_t *inosused;
10725         struct cg *cgp;
10726         struct fs *fs;
10727
10728         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10729             ("softdep_setup_inofree called on non-softdep filesystem"));
10730         ump = VFSTOUFS(mp);
10731         ACQUIRE_LOCK(ump);
10732         fs = ump->um_fs;
10733         cgp = (struct cg *)bp->b_data;
10734         inosused = cg_inosused(cgp);
10735         if (isset(inosused, ino % fs->fs_ipg))
10736                 panic("softdep_setup_inofree: inode %ju not freed.",
10737                     (uintmax_t)ino);
10738         if (inodedep_lookup(mp, ino, 0, &inodedep))
10739                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10740                     (uintmax_t)ino, inodedep);
10741         if (wkhd) {
10742                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10743                         if (wk->wk_type != D_JADDREF)
10744                                 continue;
10745                         WORKLIST_REMOVE(wk);
10746                         /*
10747                          * We can free immediately even if the jaddref
10748                          * isn't attached in a background write as now
10749                          * the bitmaps are reconciled.
10750                          */
10751                         wk->wk_state |= COMPLETE | ATTACHED;
10752                         free_jaddref(WK_JADDREF(wk));
10753                 }
10754                 jwork_move(&bp->b_dep, wkhd);
10755         }
10756         FREE_LOCK(ump);
10757 }
10758
10759
10760 /*
10761  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10762  * map.  Any dependencies waiting for the write to clear are added to the
10763  * buf's list and any jnewblks that are being canceled are discarded
10764  * immediately.
10765  */
10766 void
10767 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10768         struct mount *mp;
10769         struct buf *bp;
10770         ufs2_daddr_t blkno;
10771         int frags;
10772         struct workhead *wkhd;
10773 {
10774         struct bmsafemap *bmsafemap;
10775         struct jnewblk *jnewblk;
10776         struct ufsmount *ump;
10777         struct worklist *wk;
10778         struct fs *fs;
10779 #ifdef SUJ_DEBUG
10780         uint8_t *blksfree;
10781         struct cg *cgp;
10782         ufs2_daddr_t jstart;
10783         ufs2_daddr_t jend;
10784         ufs2_daddr_t end;
10785         long bno;
10786         int i;
10787 #endif
10788
10789         CTR3(KTR_SUJ,
10790             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10791             blkno, frags, wkhd);
10792
10793         ump = VFSTOUFS(mp);
10794         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10795             ("softdep_setup_blkfree called on non-softdep filesystem"));
10796         ACQUIRE_LOCK(ump);
10797         /* Lookup the bmsafemap so we track when it is dirty. */
10798         fs = ump->um_fs;
10799         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10800         /*
10801          * Detach any jnewblks which have been canceled.  They must linger
10802          * until the bitmap is cleared again by ffs_blkfree() to prevent
10803          * an unjournaled allocation from hitting the disk.
10804          */
10805         if (wkhd) {
10806                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10807                         CTR2(KTR_SUJ,
10808                             "softdep_setup_blkfree: blkno %jd wk type %d",
10809                             blkno, wk->wk_type);
10810                         WORKLIST_REMOVE(wk);
10811                         if (wk->wk_type != D_JNEWBLK) {
10812                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10813                                 continue;
10814                         }
10815                         jnewblk = WK_JNEWBLK(wk);
10816                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10817                             ("softdep_setup_blkfree: jnewblk not canceled."));
10818 #ifdef SUJ_DEBUG
10819                         /*
10820                          * Assert that this block is free in the bitmap
10821                          * before we discard the jnewblk.
10822                          */
10823                         cgp = (struct cg *)bp->b_data;
10824                         blksfree = cg_blksfree(cgp);
10825                         bno = dtogd(fs, jnewblk->jn_blkno);
10826                         for (i = jnewblk->jn_oldfrags;
10827                             i < jnewblk->jn_frags; i++) {
10828                                 if (isset(blksfree, bno + i))
10829                                         continue;
10830                                 panic("softdep_setup_blkfree: not free");
10831                         }
10832 #endif
10833                         /*
10834                          * Even if it's not attached we can free immediately
10835                          * as the new bitmap is correct.
10836                          */
10837                         wk->wk_state |= COMPLETE | ATTACHED;
10838                         free_jnewblk(jnewblk);
10839                 }
10840         }
10841
10842 #ifdef SUJ_DEBUG
10843         /*
10844          * Assert that we are not freeing a block which has an outstanding
10845          * allocation dependency.
10846          */
10847         fs = VFSTOUFS(mp)->um_fs;
10848         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10849         end = blkno + frags;
10850         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10851                 /*
10852                  * Don't match against blocks that will be freed when the
10853                  * background write is done.
10854                  */
10855                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10856                     (COMPLETE | DEPCOMPLETE))
10857                         continue;
10858                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10859                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10860                 if ((blkno >= jstart && blkno < jend) ||
10861                     (end > jstart && end <= jend)) {
10862                         printf("state 0x%X %jd - %d %d dep %p\n",
10863                             jnewblk->jn_state, jnewblk->jn_blkno,
10864                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10865                             jnewblk->jn_dep);
10866                         panic("softdep_setup_blkfree: "
10867                             "%jd-%jd(%d) overlaps with %jd-%jd",
10868                             blkno, end, frags, jstart, jend);
10869                 }
10870         }
10871 #endif
10872         FREE_LOCK(ump);
10873 }
10874
10875 /*
10876  * Revert a block allocation when the journal record that describes it
10877  * is not yet written.
10878  */
10879 static int
10880 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10881         struct jnewblk *jnewblk;
10882         struct fs *fs;
10883         struct cg *cgp;
10884         uint8_t *blksfree;
10885 {
10886         ufs1_daddr_t fragno;
10887         long cgbno, bbase;
10888         int frags, blk;
10889         int i;
10890
10891         frags = 0;
10892         cgbno = dtogd(fs, jnewblk->jn_blkno);
10893         /*
10894          * We have to test which frags need to be rolled back.  We may
10895          * be operating on a stale copy when doing background writes.
10896          */
10897         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10898                 if (isclr(blksfree, cgbno + i))
10899                         frags++;
10900         if (frags == 0)
10901                 return (0);
10902         /*
10903          * This is mostly ffs_blkfree() sans some validation and
10904          * superblock updates.
10905          */
10906         if (frags == fs->fs_frag) {
10907                 fragno = fragstoblks(fs, cgbno);
10908                 ffs_setblock(fs, blksfree, fragno);
10909                 ffs_clusteracct(fs, cgp, fragno, 1);
10910                 cgp->cg_cs.cs_nbfree++;
10911         } else {
10912                 cgbno += jnewblk->jn_oldfrags;
10913                 bbase = cgbno - fragnum(fs, cgbno);
10914                 /* Decrement the old frags.  */
10915                 blk = blkmap(fs, blksfree, bbase);
10916                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10917                 /* Deallocate the fragment */
10918                 for (i = 0; i < frags; i++)
10919                         setbit(blksfree, cgbno + i);
10920                 cgp->cg_cs.cs_nffree += frags;
10921                 /* Add back in counts associated with the new frags */
10922                 blk = blkmap(fs, blksfree, bbase);
10923                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10924                 /* If a complete block has been reassembled, account for it. */
10925                 fragno = fragstoblks(fs, bbase);
10926                 if (ffs_isblock(fs, blksfree, fragno)) {
10927                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10928                         ffs_clusteracct(fs, cgp, fragno, 1);
10929                         cgp->cg_cs.cs_nbfree++;
10930                 }
10931         }
10932         stat_jnewblk++;
10933         jnewblk->jn_state &= ~ATTACHED;
10934         jnewblk->jn_state |= UNDONE;
10935
10936         return (frags);
10937 }
10938
10939 static void
10940 initiate_write_bmsafemap(bmsafemap, bp)
10941         struct bmsafemap *bmsafemap;
10942         struct buf *bp;                 /* The cg block. */
10943 {
10944         struct jaddref *jaddref;
10945         struct jnewblk *jnewblk;
10946         uint8_t *inosused;
10947         uint8_t *blksfree;
10948         struct cg *cgp;
10949         struct fs *fs;
10950         ino_t ino;
10951
10952         /*
10953          * If this is a background write, we did this at the time that
10954          * the copy was made, so do not need to do it again.
10955          */
10956         if (bmsafemap->sm_state & IOSTARTED)
10957                 return;
10958         bmsafemap->sm_state |= IOSTARTED;
10959         /*
10960          * Clear any inode allocations which are pending journal writes.
10961          */
10962         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10963                 cgp = (struct cg *)bp->b_data;
10964                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10965                 inosused = cg_inosused(cgp);
10966                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10967                         ino = jaddref->ja_ino % fs->fs_ipg;
10968                         if (isset(inosused, ino)) {
10969                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10970                                         cgp->cg_cs.cs_ndir--;
10971                                 cgp->cg_cs.cs_nifree++;
10972                                 clrbit(inosused, ino);
10973                                 jaddref->ja_state &= ~ATTACHED;
10974                                 jaddref->ja_state |= UNDONE;
10975                                 stat_jaddref++;
10976                         } else
10977                                 panic("initiate_write_bmsafemap: inode %ju "
10978                                     "marked free", (uintmax_t)jaddref->ja_ino);
10979                 }
10980         }
10981         /*
10982          * Clear any block allocations which are pending journal writes.
10983          */
10984         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10985                 cgp = (struct cg *)bp->b_data;
10986                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10987                 blksfree = cg_blksfree(cgp);
10988                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10989                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10990                                 continue;
10991                         panic("initiate_write_bmsafemap: block %jd "
10992                             "marked free", jnewblk->jn_blkno);
10993                 }
10994         }
10995         /*
10996          * Move allocation lists to the written lists so they can be
10997          * cleared once the block write is complete.
10998          */
10999         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11000             inodedep, id_deps);
11001         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11002             newblk, nb_deps);
11003         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11004             wk_list);
11005 }
11006
11007 /*
11008  * This routine is called during the completion interrupt
11009  * service routine for a disk write (from the procedure called
11010  * by the device driver to inform the filesystem caches of
11011  * a request completion).  It should be called early in this
11012  * procedure, before the block is made available to other
11013  * processes or other routines are called.
11014  *
11015  */
11016 static void 
11017 softdep_disk_write_complete(bp)
11018         struct buf *bp;         /* describes the completed disk write */
11019 {
11020         struct worklist *wk;
11021         struct worklist *owk;
11022         struct ufsmount *ump;
11023         struct workhead reattach;
11024         struct freeblks *freeblks;
11025         struct buf *sbp;
11026
11027         ump = softdep_bp_to_mp(bp);
11028         if (ump == NULL)
11029                 return;
11030
11031         sbp = NULL;
11032
11033         /*
11034          * If an error occurred while doing the write, then the data
11035          * has not hit the disk and the dependencies cannot be processed.
11036          * But we do have to go through and roll forward any dependencies
11037          * that were rolled back before the disk write.
11038          */
11039         ACQUIRE_LOCK(ump);
11040         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11041                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11042                         switch (wk->wk_type) {
11043
11044                         case D_PAGEDEP:
11045                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11046                                 continue;
11047
11048                         case D_INODEDEP:
11049                                 handle_written_inodeblock(WK_INODEDEP(wk),
11050                                     bp, 0);
11051                                 continue;
11052
11053                         case D_BMSAFEMAP:
11054                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11055                                     bp, 0);
11056                                 continue;
11057
11058                         case D_INDIRDEP:
11059                                 handle_written_indirdep(WK_INDIRDEP(wk),
11060                                     bp, &sbp, 0);
11061                                 continue;
11062                         default:
11063                                 /* nothing to roll forward */
11064                                 continue;
11065                         }
11066                 }
11067                 FREE_LOCK(ump);
11068                 return;
11069         }
11070         LIST_INIT(&reattach);
11071
11072         /*
11073          * Ump SU lock must not be released anywhere in this code segment.
11074          */
11075         owk = NULL;
11076         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11077                 WORKLIST_REMOVE(wk);
11078                 atomic_add_long(&dep_write[wk->wk_type], 1);
11079                 if (wk == owk)
11080                         panic("duplicate worklist: %p\n", wk);
11081                 owk = wk;
11082                 switch (wk->wk_type) {
11083
11084                 case D_PAGEDEP:
11085                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11086                             WRITESUCCEEDED))
11087                                 WORKLIST_INSERT(&reattach, wk);
11088                         continue;
11089
11090                 case D_INODEDEP:
11091                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11092                             WRITESUCCEEDED))
11093                                 WORKLIST_INSERT(&reattach, wk);
11094                         continue;
11095
11096                 case D_BMSAFEMAP:
11097                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11098                             WRITESUCCEEDED))
11099                                 WORKLIST_INSERT(&reattach, wk);
11100                         continue;
11101
11102                 case D_MKDIR:
11103                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11104                         continue;
11105
11106                 case D_ALLOCDIRECT:
11107                         wk->wk_state |= COMPLETE;
11108                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11109                         continue;
11110
11111                 case D_ALLOCINDIR:
11112                         wk->wk_state |= COMPLETE;
11113                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11114                         continue;
11115
11116                 case D_INDIRDEP:
11117                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11118                             WRITESUCCEEDED))
11119                                 WORKLIST_INSERT(&reattach, wk);
11120                         continue;
11121
11122                 case D_FREEBLKS:
11123                         wk->wk_state |= COMPLETE;
11124                         freeblks = WK_FREEBLKS(wk);
11125                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11126                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11127                                 add_to_worklist(wk, WK_NODELAY);
11128                         continue;
11129
11130                 case D_FREEWORK:
11131                         handle_written_freework(WK_FREEWORK(wk));
11132                         break;
11133
11134                 case D_JSEGDEP:
11135                         free_jsegdep(WK_JSEGDEP(wk));
11136                         continue;
11137
11138                 case D_JSEG:
11139                         handle_written_jseg(WK_JSEG(wk), bp);
11140                         continue;
11141
11142                 case D_SBDEP:
11143                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11144                                 WORKLIST_INSERT(&reattach, wk);
11145                         continue;
11146
11147                 case D_FREEDEP:
11148                         free_freedep(WK_FREEDEP(wk));
11149                         continue;
11150
11151                 default:
11152                         panic("handle_disk_write_complete: Unknown type %s",
11153                             TYPENAME(wk->wk_type));
11154                         /* NOTREACHED */
11155                 }
11156         }
11157         /*
11158          * Reattach any requests that must be redone.
11159          */
11160         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11161                 WORKLIST_REMOVE(wk);
11162                 WORKLIST_INSERT(&bp->b_dep, wk);
11163         }
11164         FREE_LOCK(ump);
11165         if (sbp)
11166                 brelse(sbp);
11167 }
11168
11169 /*
11170  * Called from within softdep_disk_write_complete above.
11171  */
11172 static void 
11173 handle_allocdirect_partdone(adp, wkhd)
11174         struct allocdirect *adp;        /* the completed allocdirect */
11175         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11176 {
11177         struct allocdirectlst *listhead;
11178         struct allocdirect *listadp;
11179         struct inodedep *inodedep;
11180         long bsize;
11181
11182         LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11183         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11184                 return;
11185         /*
11186          * The on-disk inode cannot claim to be any larger than the last
11187          * fragment that has been written. Otherwise, the on-disk inode
11188          * might have fragments that were not the last block in the file
11189          * which would corrupt the filesystem. Thus, we cannot free any
11190          * allocdirects after one whose ad_oldblkno claims a fragment as
11191          * these blocks must be rolled back to zero before writing the inode.
11192          * We check the currently active set of allocdirects in id_inoupdt
11193          * or id_extupdt as appropriate.
11194          */
11195         inodedep = adp->ad_inodedep;
11196         bsize = inodedep->id_fs->fs_bsize;
11197         if (adp->ad_state & EXTDATA)
11198                 listhead = &inodedep->id_extupdt;
11199         else
11200                 listhead = &inodedep->id_inoupdt;
11201         TAILQ_FOREACH(listadp, listhead, ad_next) {
11202                 /* found our block */
11203                 if (listadp == adp)
11204                         break;
11205                 /* continue if ad_oldlbn is not a fragment */
11206                 if (listadp->ad_oldsize == 0 ||
11207                     listadp->ad_oldsize == bsize)
11208                         continue;
11209                 /* hit a fragment */
11210                 return;
11211         }
11212         /*
11213          * If we have reached the end of the current list without
11214          * finding the just finished dependency, then it must be
11215          * on the future dependency list. Future dependencies cannot
11216          * be freed until they are moved to the current list.
11217          */
11218         if (listadp == NULL) {
11219 #ifdef DEBUG
11220                 if (adp->ad_state & EXTDATA)
11221                         listhead = &inodedep->id_newextupdt;
11222                 else
11223                         listhead = &inodedep->id_newinoupdt;
11224                 TAILQ_FOREACH(listadp, listhead, ad_next)
11225                         /* found our block */
11226                         if (listadp == adp)
11227                                 break;
11228                 if (listadp == NULL)
11229                         panic("handle_allocdirect_partdone: lost dep");
11230 #endif /* DEBUG */
11231                 return;
11232         }
11233         /*
11234          * If we have found the just finished dependency, then queue
11235          * it along with anything that follows it that is complete.
11236          * Since the pointer has not yet been written in the inode
11237          * as the dependency prevents it, place the allocdirect on the
11238          * bufwait list where it will be freed once the pointer is
11239          * valid.
11240          */
11241         if (wkhd == NULL)
11242                 wkhd = &inodedep->id_bufwait;
11243         for (; adp; adp = listadp) {
11244                 listadp = TAILQ_NEXT(adp, ad_next);
11245                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11246                         return;
11247                 TAILQ_REMOVE(listhead, adp, ad_next);
11248                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11249         }
11250 }
11251
11252 /*
11253  * Called from within softdep_disk_write_complete above.  This routine
11254  * completes successfully written allocindirs.
11255  */
11256 static void
11257 handle_allocindir_partdone(aip)
11258         struct allocindir *aip;         /* the completed allocindir */
11259 {
11260         struct indirdep *indirdep;
11261
11262         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11263                 return;
11264         indirdep = aip->ai_indirdep;
11265         LIST_REMOVE(aip, ai_next);
11266         /*
11267          * Don't set a pointer while the buffer is undergoing IO or while
11268          * we have active truncations.
11269          */
11270         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11271                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11272                 return;
11273         }
11274         if (indirdep->ir_state & UFS1FMT)
11275                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11276                     aip->ai_newblkno;
11277         else
11278                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11279                     aip->ai_newblkno;
11280         /*
11281          * Await the pointer write before freeing the allocindir.
11282          */
11283         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11284 }
11285
11286 /*
11287  * Release segments held on a jwork list.
11288  */
11289 static void
11290 handle_jwork(wkhd)
11291         struct workhead *wkhd;
11292 {
11293         struct worklist *wk;
11294
11295         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11296                 WORKLIST_REMOVE(wk);
11297                 switch (wk->wk_type) {
11298                 case D_JSEGDEP:
11299                         free_jsegdep(WK_JSEGDEP(wk));
11300                         continue;
11301                 case D_FREEDEP:
11302                         free_freedep(WK_FREEDEP(wk));
11303                         continue;
11304                 case D_FREEFRAG:
11305                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11306                         WORKITEM_FREE(wk, D_FREEFRAG);
11307                         continue;
11308                 case D_FREEWORK:
11309                         handle_written_freework(WK_FREEWORK(wk));
11310                         continue;
11311                 default:
11312                         panic("handle_jwork: Unknown type %s\n",
11313                             TYPENAME(wk->wk_type));
11314                 }
11315         }
11316 }
11317
11318 /*
11319  * Handle the bufwait list on an inode when it is safe to release items
11320  * held there.  This normally happens after an inode block is written but
11321  * may be delayed and handled later if there are pending journal items that
11322  * are not yet safe to be released.
11323  */
11324 static struct freefile *
11325 handle_bufwait(inodedep, refhd)
11326         struct inodedep *inodedep;
11327         struct workhead *refhd;
11328 {
11329         struct jaddref *jaddref;
11330         struct freefile *freefile;
11331         struct worklist *wk;
11332
11333         freefile = NULL;
11334         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11335                 WORKLIST_REMOVE(wk);
11336                 switch (wk->wk_type) {
11337                 case D_FREEFILE:
11338                         /*
11339                          * We defer adding freefile to the worklist
11340                          * until all other additions have been made to
11341                          * ensure that it will be done after all the
11342                          * old blocks have been freed.
11343                          */
11344                         if (freefile != NULL)
11345                                 panic("handle_bufwait: freefile");
11346                         freefile = WK_FREEFILE(wk);
11347                         continue;
11348
11349                 case D_MKDIR:
11350                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11351                         continue;
11352
11353                 case D_DIRADD:
11354                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11355                         continue;
11356
11357                 case D_FREEFRAG:
11358                         wk->wk_state |= COMPLETE;
11359                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11360                                 add_to_worklist(wk, 0);
11361                         continue;
11362
11363                 case D_DIRREM:
11364                         wk->wk_state |= COMPLETE;
11365                         add_to_worklist(wk, 0);
11366                         continue;
11367
11368                 case D_ALLOCDIRECT:
11369                 case D_ALLOCINDIR:
11370                         free_newblk(WK_NEWBLK(wk));
11371                         continue;
11372
11373                 case D_JNEWBLK:
11374                         wk->wk_state |= COMPLETE;
11375                         free_jnewblk(WK_JNEWBLK(wk));
11376                         continue;
11377
11378                 /*
11379                  * Save freed journal segments and add references on
11380                  * the supplied list which will delay their release
11381                  * until the cg bitmap is cleared on disk.
11382                  */
11383                 case D_JSEGDEP:
11384                         if (refhd == NULL)
11385                                 free_jsegdep(WK_JSEGDEP(wk));
11386                         else
11387                                 WORKLIST_INSERT(refhd, wk);
11388                         continue;
11389
11390                 case D_JADDREF:
11391                         jaddref = WK_JADDREF(wk);
11392                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11393                             if_deps);
11394                         /*
11395                          * Transfer any jaddrefs to the list to be freed with
11396                          * the bitmap if we're handling a removed file.
11397                          */
11398                         if (refhd == NULL) {
11399                                 wk->wk_state |= COMPLETE;
11400                                 free_jaddref(jaddref);
11401                         } else
11402                                 WORKLIST_INSERT(refhd, wk);
11403                         continue;
11404
11405                 default:
11406                         panic("handle_bufwait: Unknown type %p(%s)",
11407                             wk, TYPENAME(wk->wk_type));
11408                         /* NOTREACHED */
11409                 }
11410         }
11411         return (freefile);
11412 }
11413 /*
11414  * Called from within softdep_disk_write_complete above to restore
11415  * in-memory inode block contents to their most up-to-date state. Note
11416  * that this routine is always called from interrupt level with further
11417  * interrupts from this device blocked.
11418  *
11419  * If the write did not succeed, we will do all the roll-forward
11420  * operations, but we will not take the actions that will allow its
11421  * dependencies to be processed.
11422  */
11423 static int 
11424 handle_written_inodeblock(inodedep, bp, flags)
11425         struct inodedep *inodedep;
11426         struct buf *bp;         /* buffer containing the inode block */
11427         int flags;
11428 {
11429         struct freefile *freefile;
11430         struct allocdirect *adp, *nextadp;
11431         struct ufs1_dinode *dp1 = NULL;
11432         struct ufs2_dinode *dp2 = NULL;
11433         struct workhead wkhd;
11434         int hadchanges, fstype;
11435         ino_t freelink;
11436
11437         LIST_INIT(&wkhd);
11438         hadchanges = 0;
11439         freefile = NULL;
11440         if ((inodedep->id_state & IOSTARTED) == 0)
11441                 panic("handle_written_inodeblock: not started");
11442         inodedep->id_state &= ~IOSTARTED;
11443         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11444                 fstype = UFS1;
11445                 dp1 = (struct ufs1_dinode *)bp->b_data +
11446                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11447                 freelink = dp1->di_freelink;
11448         } else {
11449                 fstype = UFS2;
11450                 dp2 = (struct ufs2_dinode *)bp->b_data +
11451                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11452                 freelink = dp2->di_freelink;
11453         }
11454         /*
11455          * Leave this inodeblock dirty until it's in the list.
11456          */
11457         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11458             (flags & WRITESUCCEEDED)) {
11459                 struct inodedep *inon;
11460
11461                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11462                 if ((inon == NULL && freelink == 0) ||
11463                     (inon && inon->id_ino == freelink)) {
11464                         if (inon)
11465                                 inon->id_state |= UNLINKPREV;
11466                         inodedep->id_state |= UNLINKNEXT;
11467                 }
11468                 hadchanges = 1;
11469         }
11470         /*
11471          * If we had to rollback the inode allocation because of
11472          * bitmaps being incomplete, then simply restore it.
11473          * Keep the block dirty so that it will not be reclaimed until
11474          * all associated dependencies have been cleared and the
11475          * corresponding updates written to disk.
11476          */
11477         if (inodedep->id_savedino1 != NULL) {
11478                 hadchanges = 1;
11479                 if (fstype == UFS1)
11480                         *dp1 = *inodedep->id_savedino1;
11481                 else
11482                         *dp2 = *inodedep->id_savedino2;
11483                 free(inodedep->id_savedino1, M_SAVEDINO);
11484                 inodedep->id_savedino1 = NULL;
11485                 if ((bp->b_flags & B_DELWRI) == 0)
11486                         stat_inode_bitmap++;
11487                 bdirty(bp);
11488                 /*
11489                  * If the inode is clear here and GOINGAWAY it will never
11490                  * be written.  Process the bufwait and clear any pending
11491                  * work which may include the freefile.
11492                  */
11493                 if (inodedep->id_state & GOINGAWAY)
11494                         goto bufwait;
11495                 return (1);
11496         }
11497         if (flags & WRITESUCCEEDED)
11498                 inodedep->id_state |= COMPLETE;
11499         /*
11500          * Roll forward anything that had to be rolled back before 
11501          * the inode could be updated.
11502          */
11503         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11504                 nextadp = TAILQ_NEXT(adp, ad_next);
11505                 if (adp->ad_state & ATTACHED)
11506                         panic("handle_written_inodeblock: new entry");
11507                 if (fstype == UFS1) {
11508                         if (adp->ad_offset < UFS_NDADDR) {
11509                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11510                                         panic("%s %s #%jd mismatch %d != %jd",
11511                                             "handle_written_inodeblock:",
11512                                             "direct pointer",
11513                                             (intmax_t)adp->ad_offset,
11514                                             dp1->di_db[adp->ad_offset],
11515                                             (intmax_t)adp->ad_oldblkno);
11516                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11517                         } else {
11518                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11519                                     0)
11520                                         panic("%s: %s #%jd allocated as %d",
11521                                             "handle_written_inodeblock",
11522                                             "indirect pointer",
11523                                             (intmax_t)adp->ad_offset -
11524                                             UFS_NDADDR,
11525                                             dp1->di_ib[adp->ad_offset -
11526                                             UFS_NDADDR]);
11527                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11528                                     adp->ad_newblkno;
11529                         }
11530                 } else {
11531                         if (adp->ad_offset < UFS_NDADDR) {
11532                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11533                                         panic("%s: %s #%jd %s %jd != %jd",
11534                                             "handle_written_inodeblock",
11535                                             "direct pointer",
11536                                             (intmax_t)adp->ad_offset, "mismatch",
11537                                             (intmax_t)dp2->di_db[adp->ad_offset],
11538                                             (intmax_t)adp->ad_oldblkno);
11539                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11540                         } else {
11541                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11542                                     0)
11543                                         panic("%s: %s #%jd allocated as %jd",
11544                                             "handle_written_inodeblock",
11545                                             "indirect pointer",
11546                                             (intmax_t)adp->ad_offset -
11547                                             UFS_NDADDR,
11548                                             (intmax_t)
11549                                             dp2->di_ib[adp->ad_offset -
11550                                             UFS_NDADDR]);
11551                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11552                                     adp->ad_newblkno;
11553                         }
11554                 }
11555                 adp->ad_state &= ~UNDONE;
11556                 adp->ad_state |= ATTACHED;
11557                 hadchanges = 1;
11558         }
11559         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11560                 nextadp = TAILQ_NEXT(adp, ad_next);
11561                 if (adp->ad_state & ATTACHED)
11562                         panic("handle_written_inodeblock: new entry");
11563                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11564                         panic("%s: direct pointers #%jd %s %jd != %jd",
11565                             "handle_written_inodeblock",
11566                             (intmax_t)adp->ad_offset, "mismatch",
11567                             (intmax_t)dp2->di_extb[adp->ad_offset],
11568                             (intmax_t)adp->ad_oldblkno);
11569                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11570                 adp->ad_state &= ~UNDONE;
11571                 adp->ad_state |= ATTACHED;
11572                 hadchanges = 1;
11573         }
11574         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11575                 stat_direct_blk_ptrs++;
11576         /*
11577          * Reset the file size to its most up-to-date value.
11578          */
11579         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11580                 panic("handle_written_inodeblock: bad size");
11581         if (inodedep->id_savednlink > UFS_LINK_MAX)
11582                 panic("handle_written_inodeblock: Invalid link count "
11583                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11584                     inodedep);
11585         if (fstype == UFS1) {
11586                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11587                         dp1->di_nlink = inodedep->id_savednlink;
11588                         hadchanges = 1;
11589                 }
11590                 if (dp1->di_size != inodedep->id_savedsize) {
11591                         dp1->di_size = inodedep->id_savedsize;
11592                         hadchanges = 1;
11593                 }
11594         } else {
11595                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11596                         dp2->di_nlink = inodedep->id_savednlink;
11597                         hadchanges = 1;
11598                 }
11599                 if (dp2->di_size != inodedep->id_savedsize) {
11600                         dp2->di_size = inodedep->id_savedsize;
11601                         hadchanges = 1;
11602                 }
11603                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11604                         dp2->di_extsize = inodedep->id_savedextsize;
11605                         hadchanges = 1;
11606                 }
11607         }
11608         inodedep->id_savedsize = -1;
11609         inodedep->id_savedextsize = -1;
11610         inodedep->id_savednlink = -1;
11611         /*
11612          * If there were any rollbacks in the inode block, then it must be
11613          * marked dirty so that its will eventually get written back in
11614          * its correct form.
11615          */
11616         if (hadchanges)
11617                 bdirty(bp);
11618 bufwait:
11619         /*
11620          * If the write did not succeed, we have done all the roll-forward
11621          * operations, but we cannot take the actions that will allow its
11622          * dependencies to be processed.
11623          */
11624         if ((flags & WRITESUCCEEDED) == 0)
11625                 return (hadchanges);
11626         /*
11627          * Process any allocdirects that completed during the update.
11628          */
11629         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11630                 handle_allocdirect_partdone(adp, &wkhd);
11631         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11632                 handle_allocdirect_partdone(adp, &wkhd);
11633         /*
11634          * Process deallocations that were held pending until the
11635          * inode had been written to disk. Freeing of the inode
11636          * is delayed until after all blocks have been freed to
11637          * avoid creation of new <vfsid, inum, lbn> triples
11638          * before the old ones have been deleted.  Completely
11639          * unlinked inodes are not processed until the unlinked
11640          * inode list is written or the last reference is removed.
11641          */
11642         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11643                 freefile = handle_bufwait(inodedep, NULL);
11644                 if (freefile && !LIST_EMPTY(&wkhd)) {
11645                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11646                         freefile = NULL;
11647                 }
11648         }
11649         /*
11650          * Move rolled forward dependency completions to the bufwait list
11651          * now that those that were already written have been processed.
11652          */
11653         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11654                 panic("handle_written_inodeblock: bufwait but no changes");
11655         jwork_move(&inodedep->id_bufwait, &wkhd);
11656
11657         if (freefile != NULL) {
11658                 /*
11659                  * If the inode is goingaway it was never written.  Fake up
11660                  * the state here so free_inodedep() can succeed.
11661                  */
11662                 if (inodedep->id_state & GOINGAWAY)
11663                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11664                 if (free_inodedep(inodedep) == 0)
11665                         panic("handle_written_inodeblock: live inodedep %p",
11666                             inodedep);
11667                 add_to_worklist(&freefile->fx_list, 0);
11668                 return (0);
11669         }
11670
11671         /*
11672          * If no outstanding dependencies, free it.
11673          */
11674         if (free_inodedep(inodedep) ||
11675             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11676              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11677              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11678              LIST_FIRST(&inodedep->id_bufwait) == 0))
11679                 return (0);
11680         return (hadchanges);
11681 }
11682
11683 /*
11684  * Perform needed roll-forwards and kick off any dependencies that
11685  * can now be processed.
11686  *
11687  * If the write did not succeed, we will do all the roll-forward
11688  * operations, but we will not take the actions that will allow its
11689  * dependencies to be processed.
11690  */
11691 static int
11692 handle_written_indirdep(indirdep, bp, bpp, flags)
11693         struct indirdep *indirdep;
11694         struct buf *bp;
11695         struct buf **bpp;
11696         int flags;
11697 {
11698         struct allocindir *aip;
11699         struct buf *sbp;
11700         int chgs;
11701
11702         if (indirdep->ir_state & GOINGAWAY)
11703                 panic("handle_written_indirdep: indirdep gone");
11704         if ((indirdep->ir_state & IOSTARTED) == 0)
11705                 panic("handle_written_indirdep: IO not started");
11706         chgs = 0;
11707         /*
11708          * If there were rollbacks revert them here.
11709          */
11710         if (indirdep->ir_saveddata) {
11711                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11712                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11713                         free(indirdep->ir_saveddata, M_INDIRDEP);
11714                         indirdep->ir_saveddata = NULL;
11715                 }
11716                 chgs = 1;
11717         }
11718         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11719         indirdep->ir_state |= ATTACHED;
11720         /*
11721          * If the write did not succeed, we have done all the roll-forward
11722          * operations, but we cannot take the actions that will allow its
11723          * dependencies to be processed.
11724          */
11725         if ((flags & WRITESUCCEEDED) == 0) {
11726                 stat_indir_blk_ptrs++;
11727                 bdirty(bp);
11728                 return (1);
11729         }
11730         /*
11731          * Move allocindirs with written pointers to the completehd if
11732          * the indirdep's pointer is not yet written.  Otherwise
11733          * free them here.
11734          */
11735         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11736                 LIST_REMOVE(aip, ai_next);
11737                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11738                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11739                             ai_next);
11740                         newblk_freefrag(&aip->ai_block);
11741                         continue;
11742                 }
11743                 free_newblk(&aip->ai_block);
11744         }
11745         /*
11746          * Move allocindirs that have finished dependency processing from
11747          * the done list to the write list after updating the pointers.
11748          */
11749         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11750                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11751                         handle_allocindir_partdone(aip);
11752                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11753                                 panic("disk_write_complete: not gone");
11754                         chgs = 1;
11755                 }
11756         }
11757         /*
11758          * Preserve the indirdep if there were any changes or if it is not
11759          * yet valid on disk.
11760          */
11761         if (chgs) {
11762                 stat_indir_blk_ptrs++;
11763                 bdirty(bp);
11764                 return (1);
11765         }
11766         /*
11767          * If there were no changes we can discard the savedbp and detach
11768          * ourselves from the buf.  We are only carrying completed pointers
11769          * in this case.
11770          */
11771         sbp = indirdep->ir_savebp;
11772         sbp->b_flags |= B_INVAL | B_NOCACHE;
11773         indirdep->ir_savebp = NULL;
11774         indirdep->ir_bp = NULL;
11775         if (*bpp != NULL)
11776                 panic("handle_written_indirdep: bp already exists.");
11777         *bpp = sbp;
11778         /*
11779          * The indirdep may not be freed until its parent points at it.
11780          */
11781         if (indirdep->ir_state & DEPCOMPLETE)
11782                 free_indirdep(indirdep);
11783
11784         return (0);
11785 }
11786
11787 /*
11788  * Process a diradd entry after its dependent inode has been written.
11789  */
11790 static void
11791 diradd_inode_written(dap, inodedep)
11792         struct diradd *dap;
11793         struct inodedep *inodedep;
11794 {
11795
11796         LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11797         dap->da_state |= COMPLETE;
11798         complete_diradd(dap);
11799         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11800 }
11801
11802 /*
11803  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11804  * be called with the per-filesystem lock and the buf lock on the cg held.
11805  */
11806 static int
11807 bmsafemap_backgroundwrite(bmsafemap, bp)
11808         struct bmsafemap *bmsafemap;
11809         struct buf *bp;
11810 {
11811         int dirty;
11812
11813         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11814         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11815             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11816         /*
11817          * If we're initiating a background write we need to process the
11818          * rollbacks as they exist now, not as they exist when IO starts.
11819          * No other consumers will look at the contents of the shadowed
11820          * buf so this is safe to do here.
11821          */
11822         if (bp->b_xflags & BX_BKGRDMARKER)
11823                 initiate_write_bmsafemap(bmsafemap, bp);
11824
11825         return (dirty);
11826 }
11827
11828 /*
11829  * Re-apply an allocation when a cg write is complete.
11830  */
11831 static int
11832 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11833         struct jnewblk *jnewblk;
11834         struct fs *fs;
11835         struct cg *cgp;
11836         uint8_t *blksfree;
11837 {
11838         ufs1_daddr_t fragno;
11839         ufs2_daddr_t blkno;
11840         long cgbno, bbase;
11841         int frags, blk;
11842         int i;
11843
11844         frags = 0;
11845         cgbno = dtogd(fs, jnewblk->jn_blkno);
11846         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11847                 if (isclr(blksfree, cgbno + i))
11848                         panic("jnewblk_rollforward: re-allocated fragment");
11849                 frags++;
11850         }
11851         if (frags == fs->fs_frag) {
11852                 blkno = fragstoblks(fs, cgbno);
11853                 ffs_clrblock(fs, blksfree, (long)blkno);
11854                 ffs_clusteracct(fs, cgp, blkno, -1);
11855                 cgp->cg_cs.cs_nbfree--;
11856         } else {
11857                 bbase = cgbno - fragnum(fs, cgbno);
11858                 cgbno += jnewblk->jn_oldfrags;
11859                 /* If a complete block had been reassembled, account for it. */
11860                 fragno = fragstoblks(fs, bbase);
11861                 if (ffs_isblock(fs, blksfree, fragno)) {
11862                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11863                         ffs_clusteracct(fs, cgp, fragno, -1);
11864                         cgp->cg_cs.cs_nbfree--;
11865                 }
11866                 /* Decrement the old frags.  */
11867                 blk = blkmap(fs, blksfree, bbase);
11868                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11869                 /* Allocate the fragment */
11870                 for (i = 0; i < frags; i++)
11871                         clrbit(blksfree, cgbno + i);
11872                 cgp->cg_cs.cs_nffree -= frags;
11873                 /* Add back in counts associated with the new frags */
11874                 blk = blkmap(fs, blksfree, bbase);
11875                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11876         }
11877         return (frags);
11878 }
11879
11880 /*
11881  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11882  * changes if it's not a background write.  Set all written dependencies 
11883  * to DEPCOMPLETE and free the structure if possible.
11884  *
11885  * If the write did not succeed, we will do all the roll-forward
11886  * operations, but we will not take the actions that will allow its
11887  * dependencies to be processed.
11888  */
11889 static int
11890 handle_written_bmsafemap(bmsafemap, bp, flags)
11891         struct bmsafemap *bmsafemap;
11892         struct buf *bp;
11893         int flags;
11894 {
11895         struct newblk *newblk;
11896         struct inodedep *inodedep;
11897         struct jaddref *jaddref, *jatmp;
11898         struct jnewblk *jnewblk, *jntmp;
11899         struct ufsmount *ump;
11900         uint8_t *inosused;
11901         uint8_t *blksfree;
11902         struct cg *cgp;
11903         struct fs *fs;
11904         ino_t ino;
11905         int foreground;
11906         int chgs;
11907
11908         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11909                 panic("handle_written_bmsafemap: Not started\n");
11910         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11911         chgs = 0;
11912         bmsafemap->sm_state &= ~IOSTARTED;
11913         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11914         /*
11915          * If write was successful, release journal work that was waiting
11916          * on the write. Otherwise move the work back.
11917          */
11918         if (flags & WRITESUCCEEDED)
11919                 handle_jwork(&bmsafemap->sm_freewr);
11920         else
11921                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11922                     worklist, wk_list);
11923
11924         /*
11925          * Restore unwritten inode allocation pending jaddref writes.
11926          */
11927         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11928                 cgp = (struct cg *)bp->b_data;
11929                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11930                 inosused = cg_inosused(cgp);
11931                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11932                     ja_bmdeps, jatmp) {
11933                         if ((jaddref->ja_state & UNDONE) == 0)
11934                                 continue;
11935                         ino = jaddref->ja_ino % fs->fs_ipg;
11936                         if (isset(inosused, ino))
11937                                 panic("handle_written_bmsafemap: "
11938                                     "re-allocated inode");
11939                         /* Do the roll-forward only if it's a real copy. */
11940                         if (foreground) {
11941                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11942                                         cgp->cg_cs.cs_ndir++;
11943                                 cgp->cg_cs.cs_nifree--;
11944                                 setbit(inosused, ino);
11945                                 chgs = 1;
11946                         }
11947                         jaddref->ja_state &= ~UNDONE;
11948                         jaddref->ja_state |= ATTACHED;
11949                         free_jaddref(jaddref);
11950                 }
11951         }
11952         /*
11953          * Restore any block allocations which are pending journal writes.
11954          */
11955         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11956                 cgp = (struct cg *)bp->b_data;
11957                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11958                 blksfree = cg_blksfree(cgp);
11959                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11960                     jntmp) {
11961                         if ((jnewblk->jn_state & UNDONE) == 0)
11962                                 continue;
11963                         /* Do the roll-forward only if it's a real copy. */
11964                         if (foreground &&
11965                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11966                                 chgs = 1;
11967                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11968                         jnewblk->jn_state |= ATTACHED;
11969                         free_jnewblk(jnewblk);
11970                 }
11971         }
11972         /*
11973          * If the write did not succeed, we have done all the roll-forward
11974          * operations, but we cannot take the actions that will allow its
11975          * dependencies to be processed.
11976          */
11977         if ((flags & WRITESUCCEEDED) == 0) {
11978                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11979                     newblk, nb_deps);
11980                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11981                     worklist, wk_list);
11982                 if (foreground)
11983                         bdirty(bp);
11984                 return (1);
11985         }
11986         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11987                 newblk->nb_state |= DEPCOMPLETE;
11988                 newblk->nb_state &= ~ONDEPLIST;
11989                 newblk->nb_bmsafemap = NULL;
11990                 LIST_REMOVE(newblk, nb_deps);
11991                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11992                         handle_allocdirect_partdone(
11993                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11994                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11995                         handle_allocindir_partdone(
11996                             WK_ALLOCINDIR(&newblk->nb_list));
11997                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11998                         panic("handle_written_bmsafemap: Unexpected type: %s",
11999                             TYPENAME(newblk->nb_list.wk_type));
12000         }
12001         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12002                 inodedep->id_state |= DEPCOMPLETE;
12003                 inodedep->id_state &= ~ONDEPLIST;
12004                 LIST_REMOVE(inodedep, id_deps);
12005                 inodedep->id_bmsafemap = NULL;
12006         }
12007         LIST_REMOVE(bmsafemap, sm_next);
12008         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12009             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12010             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12011             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12012             LIST_EMPTY(&bmsafemap->sm_freehd)) {
12013                 LIST_REMOVE(bmsafemap, sm_hash);
12014                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12015                 return (0);
12016         }
12017         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12018         if (foreground)
12019                 bdirty(bp);
12020         return (1);
12021 }
12022
12023 /*
12024  * Try to free a mkdir dependency.
12025  */
12026 static void
12027 complete_mkdir(mkdir)
12028         struct mkdir *mkdir;
12029 {
12030         struct diradd *dap;
12031
12032         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12033                 return;
12034         LIST_REMOVE(mkdir, md_mkdirs);
12035         dap = mkdir->md_diradd;
12036         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12037         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12038                 dap->da_state |= DEPCOMPLETE;
12039                 complete_diradd(dap);
12040         }
12041         WORKITEM_FREE(mkdir, D_MKDIR);
12042 }
12043
12044 /*
12045  * Handle the completion of a mkdir dependency.
12046  */
12047 static void
12048 handle_written_mkdir(mkdir, type)
12049         struct mkdir *mkdir;
12050         int type;
12051 {
12052
12053         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12054                 panic("handle_written_mkdir: bad type");
12055         mkdir->md_state |= COMPLETE;
12056         complete_mkdir(mkdir);
12057 }
12058
12059 static int
12060 free_pagedep(pagedep)
12061         struct pagedep *pagedep;
12062 {
12063         int i;
12064
12065         if (pagedep->pd_state & NEWBLOCK)
12066                 return (0);
12067         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12068                 return (0);
12069         for (i = 0; i < DAHASHSZ; i++)
12070                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12071                         return (0);
12072         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12073                 return (0);
12074         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12075                 return (0);
12076         if (pagedep->pd_state & ONWORKLIST)
12077                 WORKLIST_REMOVE(&pagedep->pd_list);
12078         LIST_REMOVE(pagedep, pd_hash);
12079         WORKITEM_FREE(pagedep, D_PAGEDEP);
12080
12081         return (1);
12082 }
12083
12084 /*
12085  * Called from within softdep_disk_write_complete above.
12086  * A write operation was just completed. Removed inodes can
12087  * now be freed and associated block pointers may be committed.
12088  * Note that this routine is always called from interrupt level
12089  * with further interrupts from this device blocked.
12090  *
12091  * If the write did not succeed, we will do all the roll-forward
12092  * operations, but we will not take the actions that will allow its
12093  * dependencies to be processed.
12094  */
12095 static int 
12096 handle_written_filepage(pagedep, bp, flags)
12097         struct pagedep *pagedep;
12098         struct buf *bp;         /* buffer containing the written page */
12099         int flags;
12100 {
12101         struct dirrem *dirrem;
12102         struct diradd *dap, *nextdap;
12103         struct direct *ep;
12104         int i, chgs;
12105
12106         if ((pagedep->pd_state & IOSTARTED) == 0)
12107                 panic("handle_written_filepage: not started");
12108         pagedep->pd_state &= ~IOSTARTED;
12109         if ((flags & WRITESUCCEEDED) == 0)
12110                 goto rollforward;
12111         /*
12112          * Process any directory removals that have been committed.
12113          */
12114         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12115                 LIST_REMOVE(dirrem, dm_next);
12116                 dirrem->dm_state |= COMPLETE;
12117                 dirrem->dm_dirinum = pagedep->pd_ino;
12118                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12119                     ("handle_written_filepage: Journal entries not written."));
12120                 add_to_worklist(&dirrem->dm_list, 0);
12121         }
12122         /*
12123          * Free any directory additions that have been committed.
12124          * If it is a newly allocated block, we have to wait until
12125          * the on-disk directory inode claims the new block.
12126          */
12127         if ((pagedep->pd_state & NEWBLOCK) == 0)
12128                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12129                         free_diradd(dap, NULL);
12130 rollforward:
12131         /*
12132          * Uncommitted directory entries must be restored.
12133          */
12134         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12135                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12136                      dap = nextdap) {
12137                         nextdap = LIST_NEXT(dap, da_pdlist);
12138                         if (dap->da_state & ATTACHED)
12139                                 panic("handle_written_filepage: attached");
12140                         ep = (struct direct *)
12141                             ((char *)bp->b_data + dap->da_offset);
12142                         ep->d_ino = dap->da_newinum;
12143                         dap->da_state &= ~UNDONE;
12144                         dap->da_state |= ATTACHED;
12145                         chgs = 1;
12146                         /*
12147                          * If the inode referenced by the directory has
12148                          * been written out, then the dependency can be
12149                          * moved to the pending list.
12150                          */
12151                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12152                                 LIST_REMOVE(dap, da_pdlist);
12153                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12154                                     da_pdlist);
12155                         }
12156                 }
12157         }
12158         /*
12159          * If there were any rollbacks in the directory, then it must be
12160          * marked dirty so that its will eventually get written back in
12161          * its correct form.
12162          */
12163         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12164                 if ((bp->b_flags & B_DELWRI) == 0)
12165                         stat_dir_entry++;
12166                 bdirty(bp);
12167                 return (1);
12168         }
12169         /*
12170          * If we are not waiting for a new directory block to be
12171          * claimed by its inode, then the pagedep will be freed.
12172          * Otherwise it will remain to track any new entries on
12173          * the page in case they are fsync'ed.
12174          */
12175         free_pagedep(pagedep);
12176         return (0);
12177 }
12178
12179 /*
12180  * Writing back in-core inode structures.
12181  * 
12182  * The filesystem only accesses an inode's contents when it occupies an
12183  * "in-core" inode structure.  These "in-core" structures are separate from
12184  * the page frames used to cache inode blocks.  Only the latter are
12185  * transferred to/from the disk.  So, when the updated contents of the
12186  * "in-core" inode structure are copied to the corresponding in-memory inode
12187  * block, the dependencies are also transferred.  The following procedure is
12188  * called when copying a dirty "in-core" inode to a cached inode block.
12189  */
12190
12191 /*
12192  * Called when an inode is loaded from disk. If the effective link count
12193  * differed from the actual link count when it was last flushed, then we
12194  * need to ensure that the correct effective link count is put back.
12195  */
12196 void 
12197 softdep_load_inodeblock(ip)
12198         struct inode *ip;       /* the "in_core" copy of the inode */
12199 {
12200         struct inodedep *inodedep;
12201         struct ufsmount *ump;
12202
12203         ump = ITOUMP(ip);
12204         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12205             ("softdep_load_inodeblock called on non-softdep filesystem"));
12206         /*
12207          * Check for alternate nlink count.
12208          */
12209         ip->i_effnlink = ip->i_nlink;
12210         ACQUIRE_LOCK(ump);
12211         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12212                 FREE_LOCK(ump);
12213                 return;
12214         }
12215         ip->i_effnlink -= inodedep->id_nlinkdelta;
12216         FREE_LOCK(ump);
12217 }
12218
12219 /*
12220  * This routine is called just before the "in-core" inode
12221  * information is to be copied to the in-memory inode block.
12222  * Recall that an inode block contains several inodes. If
12223  * the force flag is set, then the dependencies will be
12224  * cleared so that the update can always be made. Note that
12225  * the buffer is locked when this routine is called, so we
12226  * will never be in the middle of writing the inode block 
12227  * to disk.
12228  */
12229 void 
12230 softdep_update_inodeblock(ip, bp, waitfor)
12231         struct inode *ip;       /* the "in_core" copy of the inode */
12232         struct buf *bp;         /* the buffer containing the inode block */
12233         int waitfor;            /* nonzero => update must be allowed */
12234 {
12235         struct inodedep *inodedep;
12236         struct inoref *inoref;
12237         struct ufsmount *ump;
12238         struct worklist *wk;
12239         struct mount *mp;
12240         struct buf *ibp;
12241         struct fs *fs;
12242         int error;
12243
12244         ump = ITOUMP(ip);
12245         mp = UFSTOVFS(ump);
12246         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12247             ("softdep_update_inodeblock called on non-softdep filesystem"));
12248         fs = ump->um_fs;
12249         /*
12250          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12251          * does not have access to the in-core ip so must write directly into
12252          * the inode block buffer when setting freelink.
12253          */
12254         if (fs->fs_magic == FS_UFS1_MAGIC)
12255                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12256                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12257         else
12258                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12259                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12260         /*
12261          * If the effective link count is not equal to the actual link
12262          * count, then we must track the difference in an inodedep while
12263          * the inode is (potentially) tossed out of the cache. Otherwise,
12264          * if there is no existing inodedep, then there are no dependencies
12265          * to track.
12266          */
12267         ACQUIRE_LOCK(ump);
12268 again:
12269         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12270                 FREE_LOCK(ump);
12271                 if (ip->i_effnlink != ip->i_nlink)
12272                         panic("softdep_update_inodeblock: bad link count");
12273                 return;
12274         }
12275         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12276                 panic("softdep_update_inodeblock: bad delta");
12277         /*
12278          * If we're flushing all dependencies we must also move any waiting
12279          * for journal writes onto the bufwait list prior to I/O.
12280          */
12281         if (waitfor) {
12282                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12283                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12284                             == DEPCOMPLETE) {
12285                                 jwait(&inoref->if_list, MNT_WAIT);
12286                                 goto again;
12287                         }
12288                 }
12289         }
12290         /*
12291          * Changes have been initiated. Anything depending on these
12292          * changes cannot occur until this inode has been written.
12293          */
12294         inodedep->id_state &= ~COMPLETE;
12295         if ((inodedep->id_state & ONWORKLIST) == 0)
12296                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12297         /*
12298          * Any new dependencies associated with the incore inode must 
12299          * now be moved to the list associated with the buffer holding
12300          * the in-memory copy of the inode. Once merged process any
12301          * allocdirects that are completed by the merger.
12302          */
12303         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12304         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12305                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12306                     NULL);
12307         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12308         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12309                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12310                     NULL);
12311         /*
12312          * Now that the inode has been pushed into the buffer, the
12313          * operations dependent on the inode being written to disk
12314          * can be moved to the id_bufwait so that they will be
12315          * processed when the buffer I/O completes.
12316          */
12317         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12318                 WORKLIST_REMOVE(wk);
12319                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12320         }
12321         /*
12322          * Newly allocated inodes cannot be written until the bitmap
12323          * that allocates them have been written (indicated by
12324          * DEPCOMPLETE being set in id_state). If we are doing a
12325          * forced sync (e.g., an fsync on a file), we force the bitmap
12326          * to be written so that the update can be done.
12327          */
12328         if (waitfor == 0) {
12329                 FREE_LOCK(ump);
12330                 return;
12331         }
12332 retry:
12333         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12334                 FREE_LOCK(ump);
12335                 return;
12336         }
12337         ibp = inodedep->id_bmsafemap->sm_buf;
12338         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12339         if (ibp == NULL) {
12340                 /*
12341                  * If ibp came back as NULL, the dependency could have been
12342                  * freed while we slept.  Look it up again, and check to see
12343                  * that it has completed.
12344                  */
12345                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12346                         goto retry;
12347                 FREE_LOCK(ump);
12348                 return;
12349         }
12350         FREE_LOCK(ump);
12351         if ((error = bwrite(ibp)) != 0)
12352                 softdep_error("softdep_update_inodeblock: bwrite", error);
12353 }
12354
12355 /*
12356  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12357  * old inode dependency list (such as id_inoupdt).
12358  */
12359 static void
12360 merge_inode_lists(newlisthead, oldlisthead)
12361         struct allocdirectlst *newlisthead;
12362         struct allocdirectlst *oldlisthead;
12363 {
12364         struct allocdirect *listadp, *newadp;
12365
12366         newadp = TAILQ_FIRST(newlisthead);
12367         if (newadp != NULL)
12368                 LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12369         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12370                 if (listadp->ad_offset < newadp->ad_offset) {
12371                         listadp = TAILQ_NEXT(listadp, ad_next);
12372                         continue;
12373                 }
12374                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12375                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12376                 if (listadp->ad_offset == newadp->ad_offset) {
12377                         allocdirect_merge(oldlisthead, newadp,
12378                             listadp);
12379                         listadp = newadp;
12380                 }
12381                 newadp = TAILQ_FIRST(newlisthead);
12382         }
12383         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12384                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12385                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12386         }
12387 }
12388
12389 /*
12390  * If we are doing an fsync, then we must ensure that any directory
12391  * entries for the inode have been written after the inode gets to disk.
12392  */
12393 int
12394 softdep_fsync(vp)
12395         struct vnode *vp;       /* the "in_core" copy of the inode */
12396 {
12397         struct inodedep *inodedep;
12398         struct pagedep *pagedep;
12399         struct inoref *inoref;
12400         struct ufsmount *ump;
12401         struct worklist *wk;
12402         struct diradd *dap;
12403         struct mount *mp;
12404         struct vnode *pvp;
12405         struct inode *ip;
12406         struct buf *bp;
12407         struct fs *fs;
12408         struct thread *td = curthread;
12409         int error, flushparent, pagedep_new_block;
12410         ino_t parentino;
12411         ufs_lbn_t lbn;
12412
12413         ip = VTOI(vp);
12414         mp = vp->v_mount;
12415         ump = VFSTOUFS(mp);
12416         fs = ump->um_fs;
12417         if (MOUNTEDSOFTDEP(mp) == 0)
12418                 return (0);
12419         ACQUIRE_LOCK(ump);
12420 restart:
12421         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12422                 FREE_LOCK(ump);
12423                 return (0);
12424         }
12425         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12426                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12427                     == DEPCOMPLETE) {
12428                         jwait(&inoref->if_list, MNT_WAIT);
12429                         goto restart;
12430                 }
12431         }
12432         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12433             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12434             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12435             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12436             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12437                 panic("softdep_fsync: pending ops %p", inodedep);
12438         for (error = 0, flushparent = 0; ; ) {
12439                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12440                         break;
12441                 if (wk->wk_type != D_DIRADD)
12442                         panic("softdep_fsync: Unexpected type %s",
12443                             TYPENAME(wk->wk_type));
12444                 dap = WK_DIRADD(wk);
12445                 /*
12446                  * Flush our parent if this directory entry has a MKDIR_PARENT
12447                  * dependency or is contained in a newly allocated block.
12448                  */
12449                 if (dap->da_state & DIRCHG)
12450                         pagedep = dap->da_previous->dm_pagedep;
12451                 else
12452                         pagedep = dap->da_pagedep;
12453                 parentino = pagedep->pd_ino;
12454                 lbn = pagedep->pd_lbn;
12455                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12456                         panic("softdep_fsync: dirty");
12457                 if ((dap->da_state & MKDIR_PARENT) ||
12458                     (pagedep->pd_state & NEWBLOCK))
12459                         flushparent = 1;
12460                 else
12461                         flushparent = 0;
12462                 /*
12463                  * If we are being fsync'ed as part of vgone'ing this vnode,
12464                  * then we will not be able to release and recover the
12465                  * vnode below, so we just have to give up on writing its
12466                  * directory entry out. It will eventually be written, just
12467                  * not now, but then the user was not asking to have it
12468                  * written, so we are not breaking any promises.
12469                  */
12470                 if (vp->v_iflag & VI_DOOMED)
12471                         break;
12472                 /*
12473                  * We prevent deadlock by always fetching inodes from the
12474                  * root, moving down the directory tree. Thus, when fetching
12475                  * our parent directory, we first try to get the lock. If
12476                  * that fails, we must unlock ourselves before requesting
12477                  * the lock on our parent. See the comment in ufs_lookup
12478                  * for details on possible races.
12479                  */
12480                 FREE_LOCK(ump);
12481                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12482                     FFSV_FORCEINSMQ)) {
12483                         error = vfs_busy(mp, MBF_NOWAIT);
12484                         if (error != 0) {
12485                                 vfs_ref(mp);
12486                                 VOP_UNLOCK(vp, 0);
12487                                 error = vfs_busy(mp, 0);
12488                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12489                                 vfs_rel(mp);
12490                                 if (error != 0)
12491                                         return (ENOENT);
12492                                 if (vp->v_iflag & VI_DOOMED) {
12493                                         vfs_unbusy(mp);
12494                                         return (ENOENT);
12495                                 }
12496                         }
12497                         VOP_UNLOCK(vp, 0);
12498                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12499                             &pvp, FFSV_FORCEINSMQ);
12500                         vfs_unbusy(mp);
12501                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12502                         if (vp->v_iflag & VI_DOOMED) {
12503                                 if (error == 0)
12504                                         vput(pvp);
12505                                 error = ENOENT;
12506                         }
12507                         if (error != 0)
12508                                 return (error);
12509                 }
12510                 /*
12511                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12512                  * that are contained in direct blocks will be resolved by 
12513                  * doing a ffs_update. Pagedeps contained in indirect blocks
12514                  * may require a complete sync'ing of the directory. So, we
12515                  * try the cheap and fast ffs_update first, and if that fails,
12516                  * then we do the slower ffs_syncvnode of the directory.
12517                  */
12518                 if (flushparent) {
12519                         int locked;
12520
12521                         if ((error = ffs_update(pvp, 1)) != 0) {
12522                                 vput(pvp);
12523                                 return (error);
12524                         }
12525                         ACQUIRE_LOCK(ump);
12526                         locked = 1;
12527                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12528                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12529                                         if (wk->wk_type != D_DIRADD)
12530                                                 panic("softdep_fsync: Unexpected type %s",
12531                                                       TYPENAME(wk->wk_type));
12532                                         dap = WK_DIRADD(wk);
12533                                         if (dap->da_state & DIRCHG)
12534                                                 pagedep = dap->da_previous->dm_pagedep;
12535                                         else
12536                                                 pagedep = dap->da_pagedep;
12537                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12538                                         FREE_LOCK(ump);
12539                                         locked = 0;
12540                                         if (pagedep_new_block && (error =
12541                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12542                                                 vput(pvp);
12543                                                 return (error);
12544                                         }
12545                                 }
12546                         }
12547                         if (locked)
12548                                 FREE_LOCK(ump);
12549                 }
12550                 /*
12551                  * Flush directory page containing the inode's name.
12552                  */
12553                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12554                     &bp);
12555                 if (error == 0)
12556                         error = bwrite(bp);
12557                 else
12558                         brelse(bp);
12559                 vput(pvp);
12560                 if (error != 0)
12561                         return (error);
12562                 ACQUIRE_LOCK(ump);
12563                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12564                         break;
12565         }
12566         FREE_LOCK(ump);
12567         return (0);
12568 }
12569
12570 /*
12571  * Flush all the dirty bitmaps associated with the block device
12572  * before flushing the rest of the dirty blocks so as to reduce
12573  * the number of dependencies that will have to be rolled back.
12574  *
12575  * XXX Unused?
12576  */
12577 void
12578 softdep_fsync_mountdev(vp)
12579         struct vnode *vp;
12580 {
12581         struct buf *bp, *nbp;
12582         struct worklist *wk;
12583         struct bufobj *bo;
12584
12585         if (!vn_isdisk(vp, NULL))
12586                 panic("softdep_fsync_mountdev: vnode not a disk");
12587         bo = &vp->v_bufobj;
12588 restart:
12589         BO_LOCK(bo);
12590         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12591                 /* 
12592                  * If it is already scheduled, skip to the next buffer.
12593                  */
12594                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12595                         continue;
12596
12597                 if ((bp->b_flags & B_DELWRI) == 0)
12598                         panic("softdep_fsync_mountdev: not dirty");
12599                 /*
12600                  * We are only interested in bitmaps with outstanding
12601                  * dependencies.
12602                  */
12603                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12604                     wk->wk_type != D_BMSAFEMAP ||
12605                     (bp->b_vflags & BV_BKGRDINPROG)) {
12606                         BUF_UNLOCK(bp);
12607                         continue;
12608                 }
12609                 BO_UNLOCK(bo);
12610                 bremfree(bp);
12611                 (void) bawrite(bp);
12612                 goto restart;
12613         }
12614         drain_output(vp);
12615         BO_UNLOCK(bo);
12616 }
12617
12618 /*
12619  * Sync all cylinder groups that were dirty at the time this function is
12620  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12621  * is used to flush freedep activity that may be holding up writes to a
12622  * indirect block.
12623  */
12624 static int
12625 sync_cgs(mp, waitfor)
12626         struct mount *mp;
12627         int waitfor;
12628 {
12629         struct bmsafemap *bmsafemap;
12630         struct bmsafemap *sentinel;
12631         struct ufsmount *ump;
12632         struct buf *bp;
12633         int error;
12634
12635         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12636         sentinel->sm_cg = -1;
12637         ump = VFSTOUFS(mp);
12638         error = 0;
12639         ACQUIRE_LOCK(ump);
12640         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12641         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12642             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12643                 /* Skip sentinels and cgs with no work to release. */
12644                 if (bmsafemap->sm_cg == -1 ||
12645                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12646                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12647                         LIST_REMOVE(sentinel, sm_next);
12648                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12649                         continue;
12650                 }
12651                 /*
12652                  * If we don't get the lock and we're waiting try again, if
12653                  * not move on to the next buf and try to sync it.
12654                  */
12655                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12656                 if (bp == NULL && waitfor == MNT_WAIT)
12657                         continue;
12658                 LIST_REMOVE(sentinel, sm_next);
12659                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12660                 if (bp == NULL)
12661                         continue;
12662                 FREE_LOCK(ump);
12663                 if (waitfor == MNT_NOWAIT)
12664                         bawrite(bp);
12665                 else
12666                         error = bwrite(bp);
12667                 ACQUIRE_LOCK(ump);
12668                 if (error)
12669                         break;
12670         }
12671         LIST_REMOVE(sentinel, sm_next);
12672         FREE_LOCK(ump);
12673         free(sentinel, M_BMSAFEMAP);
12674         return (error);
12675 }
12676
12677 /*
12678  * This routine is called when we are trying to synchronously flush a
12679  * file. This routine must eliminate any filesystem metadata dependencies
12680  * so that the syncing routine can succeed.
12681  */
12682 int
12683 softdep_sync_metadata(struct vnode *vp)
12684 {
12685         struct inode *ip;
12686         int error;
12687
12688         ip = VTOI(vp);
12689         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12690             ("softdep_sync_metadata called on non-softdep filesystem"));
12691         /*
12692          * Ensure that any direct block dependencies have been cleared,
12693          * truncations are started, and inode references are journaled.
12694          */
12695         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12696         /*
12697          * Write all journal records to prevent rollbacks on devvp.
12698          */
12699         if (vp->v_type == VCHR)
12700                 softdep_flushjournal(vp->v_mount);
12701         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12702         /*
12703          * Ensure that all truncates are written so we won't find deps on
12704          * indirect blocks.
12705          */
12706         process_truncates(vp);
12707         FREE_LOCK(VFSTOUFS(vp->v_mount));
12708
12709         return (error);
12710 }
12711
12712 /*
12713  * This routine is called when we are attempting to sync a buf with
12714  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12715  * other IO it can but returns EBUSY if the buffer is not yet able to
12716  * be written.  Dependencies which will not cause rollbacks will always
12717  * return 0.
12718  */
12719 int
12720 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12721 {
12722         struct indirdep *indirdep;
12723         struct pagedep *pagedep;
12724         struct allocindir *aip;
12725         struct newblk *newblk;
12726         struct ufsmount *ump;
12727         struct buf *nbp;
12728         struct worklist *wk;
12729         int i, error;
12730
12731         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12732             ("softdep_sync_buf called on non-softdep filesystem"));
12733         /*
12734          * For VCHR we just don't want to force flush any dependencies that
12735          * will cause rollbacks.
12736          */
12737         if (vp->v_type == VCHR) {
12738                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12739                         return (EBUSY);
12740                 return (0);
12741         }
12742         ump = VFSTOUFS(vp->v_mount);
12743         ACQUIRE_LOCK(ump);
12744         /*
12745          * As we hold the buffer locked, none of its dependencies
12746          * will disappear.
12747          */
12748         error = 0;
12749 top:
12750         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12751                 switch (wk->wk_type) {
12752
12753                 case D_ALLOCDIRECT:
12754                 case D_ALLOCINDIR:
12755                         newblk = WK_NEWBLK(wk);
12756                         if (newblk->nb_jnewblk != NULL) {
12757                                 if (waitfor == MNT_NOWAIT) {
12758                                         error = EBUSY;
12759                                         goto out_unlock;
12760                                 }
12761                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12762                                 goto top;
12763                         }
12764                         if (newblk->nb_state & DEPCOMPLETE ||
12765                             waitfor == MNT_NOWAIT)
12766                                 continue;
12767                         nbp = newblk->nb_bmsafemap->sm_buf;
12768                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12769                         if (nbp == NULL)
12770                                 goto top;
12771                         FREE_LOCK(ump);
12772                         if ((error = bwrite(nbp)) != 0)
12773                                 goto out;
12774                         ACQUIRE_LOCK(ump);
12775                         continue;
12776
12777                 case D_INDIRDEP:
12778                         indirdep = WK_INDIRDEP(wk);
12779                         if (waitfor == MNT_NOWAIT) {
12780                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12781                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12782                                         error = EBUSY;
12783                                         goto out_unlock;
12784                                 }
12785                         }
12786                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12787                                 panic("softdep_sync_buf: truncation pending.");
12788                 restart:
12789                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12790                                 newblk = (struct newblk *)aip;
12791                                 if (newblk->nb_jnewblk != NULL) {
12792                                         jwait(&newblk->nb_jnewblk->jn_list,
12793                                             waitfor);
12794                                         goto restart;
12795                                 }
12796                                 if (newblk->nb_state & DEPCOMPLETE)
12797                                         continue;
12798                                 nbp = newblk->nb_bmsafemap->sm_buf;
12799                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12800                                 if (nbp == NULL)
12801                                         goto restart;
12802                                 FREE_LOCK(ump);
12803                                 if ((error = bwrite(nbp)) != 0)
12804                                         goto out;
12805                                 ACQUIRE_LOCK(ump);
12806                                 goto restart;
12807                         }
12808                         continue;
12809
12810                 case D_PAGEDEP:
12811                         /*
12812                          * Only flush directory entries in synchronous passes.
12813                          */
12814                         if (waitfor != MNT_WAIT) {
12815                                 error = EBUSY;
12816                                 goto out_unlock;
12817                         }
12818                         /*
12819                          * While syncing snapshots, we must allow recursive
12820                          * lookups.
12821                          */
12822                         BUF_AREC(bp);
12823                         /*
12824                          * We are trying to sync a directory that may
12825                          * have dependencies on both its own metadata
12826                          * and/or dependencies on the inodes of any
12827                          * recently allocated files. We walk its diradd
12828                          * lists pushing out the associated inode.
12829                          */
12830                         pagedep = WK_PAGEDEP(wk);
12831                         for (i = 0; i < DAHASHSZ; i++) {
12832                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12833                                         continue;
12834                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12835                                     &pagedep->pd_diraddhd[i]))) {
12836                                         BUF_NOREC(bp);
12837                                         goto out_unlock;
12838                                 }
12839                         }
12840                         BUF_NOREC(bp);
12841                         continue;
12842
12843                 case D_FREEWORK:
12844                 case D_FREEDEP:
12845                 case D_JSEGDEP:
12846                 case D_JNEWBLK:
12847                         continue;
12848
12849                 default:
12850                         panic("softdep_sync_buf: Unknown type %s",
12851                             TYPENAME(wk->wk_type));
12852                         /* NOTREACHED */
12853                 }
12854         }
12855 out_unlock:
12856         FREE_LOCK(ump);
12857 out:
12858         return (error);
12859 }
12860
12861 /*
12862  * Flush the dependencies associated with an inodedep.
12863  */
12864 static int
12865 flush_inodedep_deps(vp, mp, ino)
12866         struct vnode *vp;
12867         struct mount *mp;
12868         ino_t ino;
12869 {
12870         struct inodedep *inodedep;
12871         struct inoref *inoref;
12872         struct ufsmount *ump;
12873         int error, waitfor;
12874
12875         /*
12876          * This work is done in two passes. The first pass grabs most
12877          * of the buffers and begins asynchronously writing them. The
12878          * only way to wait for these asynchronous writes is to sleep
12879          * on the filesystem vnode which may stay busy for a long time
12880          * if the filesystem is active. So, instead, we make a second
12881          * pass over the dependencies blocking on each write. In the
12882          * usual case we will be blocking against a write that we
12883          * initiated, so when it is done the dependency will have been
12884          * resolved. Thus the second pass is expected to end quickly.
12885          * We give a brief window at the top of the loop to allow
12886          * any pending I/O to complete.
12887          */
12888         ump = VFSTOUFS(mp);
12889         LOCK_OWNED(ump);
12890         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12891                 if (error)
12892                         return (error);
12893                 FREE_LOCK(ump);
12894                 ACQUIRE_LOCK(ump);
12895 restart:
12896                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12897                         return (0);
12898                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12899                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12900                             == DEPCOMPLETE) {
12901                                 jwait(&inoref->if_list, MNT_WAIT);
12902                                 goto restart;
12903                         }
12904                 }
12905                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12906                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12907                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12908                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12909                         continue;
12910                 /*
12911                  * If pass2, we are done, otherwise do pass 2.
12912                  */
12913                 if (waitfor == MNT_WAIT)
12914                         break;
12915                 waitfor = MNT_WAIT;
12916         }
12917         /*
12918          * Try freeing inodedep in case all dependencies have been removed.
12919          */
12920         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12921                 (void) free_inodedep(inodedep);
12922         return (0);
12923 }
12924
12925 /*
12926  * Flush an inode dependency list.
12927  */
12928 static int
12929 flush_deplist(listhead, waitfor, errorp)
12930         struct allocdirectlst *listhead;
12931         int waitfor;
12932         int *errorp;
12933 {
12934         struct allocdirect *adp;
12935         struct newblk *newblk;
12936         struct ufsmount *ump;
12937         struct buf *bp;
12938
12939         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12940                 return (0);
12941         ump = VFSTOUFS(adp->ad_list.wk_mp);
12942         LOCK_OWNED(ump);
12943         TAILQ_FOREACH(adp, listhead, ad_next) {
12944                 newblk = (struct newblk *)adp;
12945                 if (newblk->nb_jnewblk != NULL) {
12946                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12947                         return (1);
12948                 }
12949                 if (newblk->nb_state & DEPCOMPLETE)
12950                         continue;
12951                 bp = newblk->nb_bmsafemap->sm_buf;
12952                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12953                 if (bp == NULL) {
12954                         if (waitfor == MNT_NOWAIT)
12955                                 continue;
12956                         return (1);
12957                 }
12958                 FREE_LOCK(ump);
12959                 if (waitfor == MNT_NOWAIT)
12960                         bawrite(bp);
12961                 else 
12962                         *errorp = bwrite(bp);
12963                 ACQUIRE_LOCK(ump);
12964                 return (1);
12965         }
12966         return (0);
12967 }
12968
12969 /*
12970  * Flush dependencies associated with an allocdirect block.
12971  */
12972 static int
12973 flush_newblk_dep(vp, mp, lbn)
12974         struct vnode *vp;
12975         struct mount *mp;
12976         ufs_lbn_t lbn;
12977 {
12978         struct newblk *newblk;
12979         struct ufsmount *ump;
12980         struct bufobj *bo;
12981         struct inode *ip;
12982         struct buf *bp;
12983         ufs2_daddr_t blkno;
12984         int error;
12985
12986         error = 0;
12987         bo = &vp->v_bufobj;
12988         ip = VTOI(vp);
12989         blkno = DIP(ip, i_db[lbn]);
12990         if (blkno == 0)
12991                 panic("flush_newblk_dep: Missing block");
12992         ump = VFSTOUFS(mp);
12993         ACQUIRE_LOCK(ump);
12994         /*
12995          * Loop until all dependencies related to this block are satisfied.
12996          * We must be careful to restart after each sleep in case a write
12997          * completes some part of this process for us.
12998          */
12999         for (;;) {
13000                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13001                         FREE_LOCK(ump);
13002                         break;
13003                 }
13004                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13005                         panic("flush_newblk_dep: Bad newblk %p", newblk);
13006                 /*
13007                  * Flush the journal.
13008                  */
13009                 if (newblk->nb_jnewblk != NULL) {
13010                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13011                         continue;
13012                 }
13013                 /*
13014                  * Write the bitmap dependency.
13015                  */
13016                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13017                         bp = newblk->nb_bmsafemap->sm_buf;
13018                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13019                         if (bp == NULL)
13020                                 continue;
13021                         FREE_LOCK(ump);
13022                         error = bwrite(bp);
13023                         if (error)
13024                                 break;
13025                         ACQUIRE_LOCK(ump);
13026                         continue;
13027                 }
13028                 /*
13029                  * Write the buffer.
13030                  */
13031                 FREE_LOCK(ump);
13032                 BO_LOCK(bo);
13033                 bp = gbincore(bo, lbn);
13034                 if (bp != NULL) {
13035                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13036                             LK_INTERLOCK, BO_LOCKPTR(bo));
13037                         if (error == ENOLCK) {
13038                                 ACQUIRE_LOCK(ump);
13039                                 error = 0;
13040                                 continue; /* Slept, retry */
13041                         }
13042                         if (error != 0)
13043                                 break;  /* Failed */
13044                         if (bp->b_flags & B_DELWRI) {
13045                                 bremfree(bp);
13046                                 error = bwrite(bp);
13047                                 if (error)
13048                                         break;
13049                         } else
13050                                 BUF_UNLOCK(bp);
13051                 } else
13052                         BO_UNLOCK(bo);
13053                 /*
13054                  * We have to wait for the direct pointers to
13055                  * point at the newdirblk before the dependency
13056                  * will go away.
13057                  */
13058                 error = ffs_update(vp, 1);
13059                 if (error)
13060                         break;
13061                 ACQUIRE_LOCK(ump);
13062         }
13063         return (error);
13064 }
13065
13066 /*
13067  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13068  */
13069 static int
13070 flush_pagedep_deps(pvp, mp, diraddhdp)
13071         struct vnode *pvp;
13072         struct mount *mp;
13073         struct diraddhd *diraddhdp;
13074 {
13075         struct inodedep *inodedep;
13076         struct inoref *inoref;
13077         struct ufsmount *ump;
13078         struct diradd *dap;
13079         struct vnode *vp;
13080         int error = 0;
13081         struct buf *bp;
13082         ino_t inum;
13083         struct diraddhd unfinished;
13084
13085         LIST_INIT(&unfinished);
13086         ump = VFSTOUFS(mp);
13087         LOCK_OWNED(ump);
13088 restart:
13089         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13090                 /*
13091                  * Flush ourselves if this directory entry
13092                  * has a MKDIR_PARENT dependency.
13093                  */
13094                 if (dap->da_state & MKDIR_PARENT) {
13095                         FREE_LOCK(ump);
13096                         if ((error = ffs_update(pvp, 1)) != 0)
13097                                 break;
13098                         ACQUIRE_LOCK(ump);
13099                         /*
13100                          * If that cleared dependencies, go on to next.
13101                          */
13102                         if (dap != LIST_FIRST(diraddhdp))
13103                                 continue;
13104                         /*
13105                          * All MKDIR_PARENT dependencies and all the
13106                          * NEWBLOCK pagedeps that are contained in direct
13107                          * blocks were resolved by doing above ffs_update.
13108                          * Pagedeps contained in indirect blocks may
13109                          * require a complete sync'ing of the directory.
13110                          * We are in the midst of doing a complete sync,
13111                          * so if they are not resolved in this pass we
13112                          * defer them for now as they will be sync'ed by
13113                          * our caller shortly.
13114                          */
13115                         LIST_REMOVE(dap, da_pdlist);
13116                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13117                         continue;
13118                 }
13119                 /*
13120                  * A newly allocated directory must have its "." and
13121                  * ".." entries written out before its name can be
13122                  * committed in its parent. 
13123                  */
13124                 inum = dap->da_newinum;
13125                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13126                         panic("flush_pagedep_deps: lost inode1");
13127                 /*
13128                  * Wait for any pending journal adds to complete so we don't
13129                  * cause rollbacks while syncing.
13130                  */
13131                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13132                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13133                             == DEPCOMPLETE) {
13134                                 jwait(&inoref->if_list, MNT_WAIT);
13135                                 goto restart;
13136                         }
13137                 }
13138                 if (dap->da_state & MKDIR_BODY) {
13139                         FREE_LOCK(ump);
13140                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13141                             FFSV_FORCEINSMQ)))
13142                                 break;
13143                         error = flush_newblk_dep(vp, mp, 0);
13144                         /*
13145                          * If we still have the dependency we might need to
13146                          * update the vnode to sync the new link count to
13147                          * disk.
13148                          */
13149                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13150                                 error = ffs_update(vp, 1);
13151                         vput(vp);
13152                         if (error != 0)
13153                                 break;
13154                         ACQUIRE_LOCK(ump);
13155                         /*
13156                          * If that cleared dependencies, go on to next.
13157                          */
13158                         if (dap != LIST_FIRST(diraddhdp))
13159                                 continue;
13160                         if (dap->da_state & MKDIR_BODY) {
13161                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13162                                     &inodedep);
13163                                 panic("flush_pagedep_deps: MKDIR_BODY "
13164                                     "inodedep %p dap %p vp %p",
13165                                     inodedep, dap, vp);
13166                         }
13167                 }
13168                 /*
13169                  * Flush the inode on which the directory entry depends.
13170                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13171                  * the only remaining dependency is that the updated inode
13172                  * count must get pushed to disk. The inode has already
13173                  * been pushed into its inode buffer (via VOP_UPDATE) at
13174                  * the time of the reference count change. So we need only
13175                  * locate that buffer, ensure that there will be no rollback
13176                  * caused by a bitmap dependency, then write the inode buffer.
13177                  */
13178 retry:
13179                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13180                         panic("flush_pagedep_deps: lost inode");
13181                 /*
13182                  * If the inode still has bitmap dependencies,
13183                  * push them to disk.
13184                  */
13185                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13186                         bp = inodedep->id_bmsafemap->sm_buf;
13187                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13188                         if (bp == NULL)
13189                                 goto retry;
13190                         FREE_LOCK(ump);
13191                         if ((error = bwrite(bp)) != 0)
13192                                 break;
13193                         ACQUIRE_LOCK(ump);
13194                         if (dap != LIST_FIRST(diraddhdp))
13195                                 continue;
13196                 }
13197                 /*
13198                  * If the inode is still sitting in a buffer waiting
13199                  * to be written or waiting for the link count to be
13200                  * adjusted update it here to flush it to disk.
13201                  */
13202                 if (dap == LIST_FIRST(diraddhdp)) {
13203                         FREE_LOCK(ump);
13204                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13205                             FFSV_FORCEINSMQ)))
13206                                 break;
13207                         error = ffs_update(vp, 1);
13208                         vput(vp);
13209                         if (error)
13210                                 break;
13211                         ACQUIRE_LOCK(ump);
13212                 }
13213                 /*
13214                  * If we have failed to get rid of all the dependencies
13215                  * then something is seriously wrong.
13216                  */
13217                 if (dap == LIST_FIRST(diraddhdp)) {
13218                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13219                         panic("flush_pagedep_deps: failed to flush " 
13220                             "inodedep %p ino %ju dap %p",
13221                             inodedep, (uintmax_t)inum, dap);
13222                 }
13223         }
13224         if (error)
13225                 ACQUIRE_LOCK(ump);
13226         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13227                 LIST_REMOVE(dap, da_pdlist);
13228                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13229         }
13230         return (error);
13231 }
13232
13233 /*
13234  * A large burst of file addition or deletion activity can drive the
13235  * memory load excessively high. First attempt to slow things down
13236  * using the techniques below. If that fails, this routine requests
13237  * the offending operations to fall back to running synchronously
13238  * until the memory load returns to a reasonable level.
13239  */
13240 int
13241 softdep_slowdown(vp)
13242         struct vnode *vp;
13243 {
13244         struct ufsmount *ump;
13245         int jlow;
13246         int max_softdeps_hard;
13247
13248         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13249             ("softdep_slowdown called on non-softdep filesystem"));
13250         ump = VFSTOUFS(vp->v_mount);
13251         ACQUIRE_LOCK(ump);
13252         jlow = 0;
13253         /*
13254          * Check for journal space if needed.
13255          */
13256         if (DOINGSUJ(vp)) {
13257                 if (journal_space(ump, 0) == 0)
13258                         jlow = 1;
13259         }
13260         /*
13261          * If the system is under its limits and our filesystem is
13262          * not responsible for more than our share of the usage and
13263          * we are not low on journal space, then no need to slow down.
13264          */
13265         max_softdeps_hard = max_softdeps * 11 / 10;
13266         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13267             dep_current[D_INODEDEP] < max_softdeps_hard &&
13268             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13269             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13270             ump->softdep_curdeps[D_DIRREM] <
13271             (max_softdeps_hard / 2) / stat_flush_threads &&
13272             ump->softdep_curdeps[D_INODEDEP] <
13273             max_softdeps_hard / stat_flush_threads &&
13274             ump->softdep_curdeps[D_INDIRDEP] <
13275             (max_softdeps_hard / 1000) / stat_flush_threads &&
13276             ump->softdep_curdeps[D_FREEBLKS] <
13277             max_softdeps_hard / stat_flush_threads) {
13278                 FREE_LOCK(ump);
13279                 return (0);
13280         }
13281         /*
13282          * If the journal is low or our filesystem is over its limit
13283          * then speedup the cleanup.
13284          */
13285         if (ump->softdep_curdeps[D_INDIRDEP] <
13286             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13287                 softdep_speedup(ump);
13288         stat_sync_limit_hit += 1;
13289         FREE_LOCK(ump);
13290         /*
13291          * We only slow down the rate at which new dependencies are
13292          * generated if we are not using journaling. With journaling,
13293          * the cleanup should always be sufficient to keep things
13294          * under control.
13295          */
13296         if (DOINGSUJ(vp))
13297                 return (0);
13298         return (1);
13299 }
13300
13301 /*
13302  * Called by the allocation routines when they are about to fail
13303  * in the hope that we can free up the requested resource (inodes
13304  * or disk space).
13305  * 
13306  * First check to see if the work list has anything on it. If it has,
13307  * clean up entries until we successfully free the requested resource.
13308  * Because this process holds inodes locked, we cannot handle any remove
13309  * requests that might block on a locked inode as that could lead to
13310  * deadlock. If the worklist yields none of the requested resource,
13311  * start syncing out vnodes to free up the needed space.
13312  */
13313 int
13314 softdep_request_cleanup(fs, vp, cred, resource)
13315         struct fs *fs;
13316         struct vnode *vp;
13317         struct ucred *cred;
13318         int resource;
13319 {
13320         struct ufsmount *ump;
13321         struct mount *mp;
13322         long starttime;
13323         ufs2_daddr_t needed;
13324         int error, failed_vnode;
13325
13326         /*
13327          * If we are being called because of a process doing a
13328          * copy-on-write, then it is not safe to process any
13329          * worklist items as we will recurse into the copyonwrite
13330          * routine.  This will result in an incoherent snapshot.
13331          * If the vnode that we hold is a snapshot, we must avoid
13332          * handling other resources that could cause deadlock.
13333          */
13334         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13335                 return (0);
13336
13337         if (resource == FLUSH_BLOCKS_WAIT)
13338                 stat_cleanup_blkrequests += 1;
13339         else
13340                 stat_cleanup_inorequests += 1;
13341
13342         mp = vp->v_mount;
13343         ump = VFSTOUFS(mp);
13344         mtx_assert(UFS_MTX(ump), MA_OWNED);
13345         UFS_UNLOCK(ump);
13346         error = ffs_update(vp, 1);
13347         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13348                 UFS_LOCK(ump);
13349                 return (0);
13350         }
13351         /*
13352          * If we are in need of resources, start by cleaning up
13353          * any block removals associated with our inode.
13354          */
13355         ACQUIRE_LOCK(ump);
13356         process_removes(vp);
13357         process_truncates(vp);
13358         FREE_LOCK(ump);
13359         /*
13360          * Now clean up at least as many resources as we will need.
13361          *
13362          * When requested to clean up inodes, the number that are needed
13363          * is set by the number of simultaneous writers (mnt_writeopcount)
13364          * plus a bit of slop (2) in case some more writers show up while
13365          * we are cleaning.
13366          *
13367          * When requested to free up space, the amount of space that
13368          * we need is enough blocks to allocate a full-sized segment
13369          * (fs_contigsumsize). The number of such segments that will
13370          * be needed is set by the number of simultaneous writers
13371          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13372          * writers show up while we are cleaning.
13373          *
13374          * Additionally, if we are unpriviledged and allocating space,
13375          * we need to ensure that we clean up enough blocks to get the
13376          * needed number of blocks over the threshold of the minimum
13377          * number of blocks required to be kept free by the filesystem
13378          * (fs_minfree).
13379          */
13380         if (resource == FLUSH_INODES_WAIT) {
13381                 needed = vp->v_mount->mnt_writeopcount + 2;
13382         } else if (resource == FLUSH_BLOCKS_WAIT) {
13383                 needed = (vp->v_mount->mnt_writeopcount + 2) *
13384                     fs->fs_contigsumsize;
13385                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13386                         needed += fragstoblks(fs,
13387                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13388                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13389         } else {
13390                 UFS_LOCK(ump);
13391                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13392                     resource);
13393                 return (0);
13394         }
13395         starttime = time_second;
13396 retry:
13397         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13398             fs->fs_cstotal.cs_nbfree <= needed) ||
13399             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13400             fs->fs_cstotal.cs_nifree <= needed)) {
13401                 ACQUIRE_LOCK(ump);
13402                 if (ump->softdep_on_worklist > 0 &&
13403                     process_worklist_item(UFSTOVFS(ump),
13404                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13405                         stat_worklist_push += 1;
13406                 FREE_LOCK(ump);
13407         }
13408         /*
13409          * If we still need resources and there are no more worklist
13410          * entries to process to obtain them, we have to start flushing
13411          * the dirty vnodes to force the release of additional requests
13412          * to the worklist that we can then process to reap addition
13413          * resources. We walk the vnodes associated with the mount point
13414          * until we get the needed worklist requests that we can reap.
13415          *
13416          * If there are several threads all needing to clean the same
13417          * mount point, only one is allowed to walk the mount list.
13418          * When several threads all try to walk the same mount list,
13419          * they end up competing with each other and often end up in
13420          * livelock. This approach ensures that forward progress is
13421          * made at the cost of occational ENOSPC errors being returned
13422          * that might otherwise have been avoided.
13423          */
13424         error = 1;
13425         if ((resource == FLUSH_BLOCKS_WAIT && 
13426              fs->fs_cstotal.cs_nbfree <= needed) ||
13427             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13428              fs->fs_cstotal.cs_nifree <= needed)) {
13429                 ACQUIRE_LOCK(ump);
13430                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13431                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13432                         FREE_LOCK(ump);
13433                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13434                         ACQUIRE_LOCK(ump);
13435                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13436                         FREE_LOCK(ump);
13437                         if (ump->softdep_on_worklist > 0) {
13438                                 stat_cleanup_retries += 1;
13439                                 if (!failed_vnode)
13440                                         goto retry;
13441                         }
13442                 } else {
13443                         FREE_LOCK(ump);
13444                         error = 0;
13445                 }
13446                 stat_cleanup_failures += 1;
13447         }
13448         if (time_second - starttime > stat_cleanup_high_delay)
13449                 stat_cleanup_high_delay = time_second - starttime;
13450         UFS_LOCK(ump);
13451         return (error);
13452 }
13453
13454 /*
13455  * Scan the vnodes for the specified mount point flushing out any
13456  * vnodes that can be locked without waiting. Finally, try to flush
13457  * the device associated with the mount point if it can be locked
13458  * without waiting.
13459  *
13460  * We return 0 if we were able to lock every vnode in our scan.
13461  * If we had to skip one or more vnodes, we return 1.
13462  */
13463 static int
13464 softdep_request_cleanup_flush(mp, ump)
13465         struct mount *mp;
13466         struct ufsmount *ump;
13467 {
13468         struct thread *td;
13469         struct vnode *lvp, *mvp;
13470         int failed_vnode;
13471
13472         failed_vnode = 0;
13473         td = curthread;
13474         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13475                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13476                         VI_UNLOCK(lvp);
13477                         continue;
13478                 }
13479                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13480                     td) != 0) {
13481                         failed_vnode = 1;
13482                         continue;
13483                 }
13484                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13485                         vput(lvp);
13486                         continue;
13487                 }
13488                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13489                 vput(lvp);
13490         }
13491         lvp = ump->um_devvp;
13492         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13493                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13494                 VOP_UNLOCK(lvp, 0);
13495         }
13496         return (failed_vnode);
13497 }
13498
13499 static bool
13500 softdep_excess_items(struct ufsmount *ump, int item)
13501 {
13502
13503         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13504         return (dep_current[item] > max_softdeps &&
13505             ump->softdep_curdeps[item] > max_softdeps /
13506             stat_flush_threads);
13507 }
13508
13509 static void
13510 schedule_cleanup(struct mount *mp)
13511 {
13512         struct ufsmount *ump;
13513         struct thread *td;
13514
13515         ump = VFSTOUFS(mp);
13516         LOCK_OWNED(ump);
13517         FREE_LOCK(ump);
13518         td = curthread;
13519         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13520             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13521                 /*
13522                  * No ast is delivered to kernel threads, so nobody
13523                  * would deref the mp.  Some kernel threads
13524                  * explicitely check for AST, e.g. NFS daemon does
13525                  * this in the serving loop.
13526                  */
13527                 return;
13528         }
13529         if (td->td_su != NULL)
13530                 vfs_rel(td->td_su);
13531         vfs_ref(mp);
13532         td->td_su = mp;
13533         thread_lock(td);
13534         td->td_flags |= TDF_ASTPENDING;
13535         thread_unlock(td);
13536 }
13537
13538 static void
13539 softdep_ast_cleanup_proc(struct thread *td)
13540 {
13541         struct mount *mp;
13542         struct ufsmount *ump;
13543         int error;
13544         bool req;
13545
13546         while ((mp = td->td_su) != NULL) {
13547                 td->td_su = NULL;
13548                 error = vfs_busy(mp, MBF_NOWAIT);
13549                 vfs_rel(mp);
13550                 if (error != 0)
13551                         return;
13552                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13553                         ump = VFSTOUFS(mp);
13554                         for (;;) {
13555                                 req = false;
13556                                 ACQUIRE_LOCK(ump);
13557                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13558                                         req = true;
13559                                         request_cleanup(mp, FLUSH_INODES);
13560                                 }
13561                                 if (softdep_excess_items(ump, D_DIRREM)) {
13562                                         req = true;
13563                                         request_cleanup(mp, FLUSH_BLOCKS);
13564                                 }
13565                                 FREE_LOCK(ump);
13566                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13567                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13568                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13569                                         error = vn_start_write(NULL, &mp,
13570                                             V_WAIT);
13571                                         if (error == 0) {
13572                                                 req = true;
13573                                                 VFS_SYNC(mp, MNT_WAIT);
13574                                                 vn_finished_write(mp);
13575                                         }
13576                                 }
13577                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13578                                         break;
13579                         }
13580                 }
13581                 vfs_unbusy(mp);
13582         }
13583         if ((mp = td->td_su) != NULL) {
13584                 td->td_su = NULL;
13585                 vfs_rel(mp);
13586         }
13587 }
13588
13589 /*
13590  * If memory utilization has gotten too high, deliberately slow things
13591  * down and speed up the I/O processing.
13592  */
13593 static int
13594 request_cleanup(mp, resource)
13595         struct mount *mp;
13596         int resource;
13597 {
13598         struct thread *td = curthread;
13599         struct ufsmount *ump;
13600
13601         ump = VFSTOUFS(mp);
13602         LOCK_OWNED(ump);
13603         /*
13604          * We never hold up the filesystem syncer or buf daemon.
13605          */
13606         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13607                 return (0);
13608         /*
13609          * First check to see if the work list has gotten backlogged.
13610          * If it has, co-opt this process to help clean up two entries.
13611          * Because this process may hold inodes locked, we cannot
13612          * handle any remove requests that might block on a locked
13613          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13614          * to avoid recursively processing the worklist.
13615          */
13616         if (ump->softdep_on_worklist > max_softdeps / 10) {
13617                 td->td_pflags |= TDP_SOFTDEP;
13618                 process_worklist_item(mp, 2, LK_NOWAIT);
13619                 td->td_pflags &= ~TDP_SOFTDEP;
13620                 stat_worklist_push += 2;
13621                 return(1);
13622         }
13623         /*
13624          * Next, we attempt to speed up the syncer process. If that
13625          * is successful, then we allow the process to continue.
13626          */
13627         if (softdep_speedup(ump) &&
13628             resource != FLUSH_BLOCKS_WAIT &&
13629             resource != FLUSH_INODES_WAIT)
13630                 return(0);
13631         /*
13632          * If we are resource constrained on inode dependencies, try
13633          * flushing some dirty inodes. Otherwise, we are constrained
13634          * by file deletions, so try accelerating flushes of directories
13635          * with removal dependencies. We would like to do the cleanup
13636          * here, but we probably hold an inode locked at this point and 
13637          * that might deadlock against one that we try to clean. So,
13638          * the best that we can do is request the syncer daemon to do
13639          * the cleanup for us.
13640          */
13641         switch (resource) {
13642
13643         case FLUSH_INODES:
13644         case FLUSH_INODES_WAIT:
13645                 ACQUIRE_GBLLOCK(&lk);
13646                 stat_ino_limit_push += 1;
13647                 req_clear_inodedeps += 1;
13648                 FREE_GBLLOCK(&lk);
13649                 stat_countp = &stat_ino_limit_hit;
13650                 break;
13651
13652         case FLUSH_BLOCKS:
13653         case FLUSH_BLOCKS_WAIT:
13654                 ACQUIRE_GBLLOCK(&lk);
13655                 stat_blk_limit_push += 1;
13656                 req_clear_remove += 1;
13657                 FREE_GBLLOCK(&lk);
13658                 stat_countp = &stat_blk_limit_hit;
13659                 break;
13660
13661         default:
13662                 panic("request_cleanup: unknown type");
13663         }
13664         /*
13665          * Hopefully the syncer daemon will catch up and awaken us.
13666          * We wait at most tickdelay before proceeding in any case.
13667          */
13668         ACQUIRE_GBLLOCK(&lk);
13669         FREE_LOCK(ump);
13670         proc_waiting += 1;
13671         if (callout_pending(&softdep_callout) == FALSE)
13672                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13673                     pause_timer, 0);
13674
13675         if ((td->td_pflags & TDP_KTHREAD) == 0)
13676                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13677         proc_waiting -= 1;
13678         FREE_GBLLOCK(&lk);
13679         ACQUIRE_LOCK(ump);
13680         return (1);
13681 }
13682
13683 /*
13684  * Awaken processes pausing in request_cleanup and clear proc_waiting
13685  * to indicate that there is no longer a timer running. Pause_timer
13686  * will be called with the global softdep mutex (&lk) locked.
13687  */
13688 static void
13689 pause_timer(arg)
13690         void *arg;
13691 {
13692
13693         GBLLOCK_OWNED(&lk);
13694         /*
13695          * The callout_ API has acquired mtx and will hold it around this
13696          * function call.
13697          */
13698         *stat_countp += proc_waiting;
13699         wakeup(&proc_waiting);
13700 }
13701
13702 /*
13703  * If requested, try removing inode or removal dependencies.
13704  */
13705 static void
13706 check_clear_deps(mp)
13707         struct mount *mp;
13708 {
13709
13710         /*
13711          * If we are suspended, it may be because of our using
13712          * too many inodedeps, so help clear them out.
13713          */
13714         if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13715                 clear_inodedeps(mp);
13716         /*
13717          * General requests for cleanup of backed up dependencies
13718          */
13719         ACQUIRE_GBLLOCK(&lk);
13720         if (req_clear_inodedeps) {
13721                 req_clear_inodedeps -= 1;
13722                 FREE_GBLLOCK(&lk);
13723                 clear_inodedeps(mp);
13724                 ACQUIRE_GBLLOCK(&lk);
13725                 wakeup(&proc_waiting);
13726         }
13727         if (req_clear_remove) {
13728                 req_clear_remove -= 1;
13729                 FREE_GBLLOCK(&lk);
13730                 clear_remove(mp);
13731                 ACQUIRE_GBLLOCK(&lk);
13732                 wakeup(&proc_waiting);
13733         }
13734         FREE_GBLLOCK(&lk);
13735 }
13736
13737 /*
13738  * Flush out a directory with at least one removal dependency in an effort to
13739  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13740  */
13741 static void
13742 clear_remove(mp)
13743         struct mount *mp;
13744 {
13745         struct pagedep_hashhead *pagedephd;
13746         struct pagedep *pagedep;
13747         struct ufsmount *ump;
13748         struct vnode *vp;
13749         struct bufobj *bo;
13750         int error, cnt;
13751         ino_t ino;
13752
13753         ump = VFSTOUFS(mp);
13754         LOCK_OWNED(ump);
13755
13756         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13757                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13758                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13759                         ump->pagedep_nextclean = 0;
13760                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13761                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13762                                 continue;
13763                         ino = pagedep->pd_ino;
13764                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13765                                 continue;
13766                         FREE_LOCK(ump);
13767
13768                         /*
13769                          * Let unmount clear deps
13770                          */
13771                         error = vfs_busy(mp, MBF_NOWAIT);
13772                         if (error != 0)
13773                                 goto finish_write;
13774                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13775                              FFSV_FORCEINSMQ);
13776                         vfs_unbusy(mp);
13777                         if (error != 0) {
13778                                 softdep_error("clear_remove: vget", error);
13779                                 goto finish_write;
13780                         }
13781                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13782                                 softdep_error("clear_remove: fsync", error);
13783                         bo = &vp->v_bufobj;
13784                         BO_LOCK(bo);
13785                         drain_output(vp);
13786                         BO_UNLOCK(bo);
13787                         vput(vp);
13788                 finish_write:
13789                         vn_finished_write(mp);
13790                         ACQUIRE_LOCK(ump);
13791                         return;
13792                 }
13793         }
13794 }
13795
13796 /*
13797  * Clear out a block of dirty inodes in an effort to reduce
13798  * the number of inodedep dependency structures.
13799  */
13800 static void
13801 clear_inodedeps(mp)
13802         struct mount *mp;
13803 {
13804         struct inodedep_hashhead *inodedephd;
13805         struct inodedep *inodedep;
13806         struct ufsmount *ump;
13807         struct vnode *vp;
13808         struct fs *fs;
13809         int error, cnt;
13810         ino_t firstino, lastino, ino;
13811
13812         ump = VFSTOUFS(mp);
13813         fs = ump->um_fs;
13814         LOCK_OWNED(ump);
13815         /*
13816          * Pick a random inode dependency to be cleared.
13817          * We will then gather up all the inodes in its block 
13818          * that have dependencies and flush them out.
13819          */
13820         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13821                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13822                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13823                         ump->inodedep_nextclean = 0;
13824                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13825                         break;
13826         }
13827         if (inodedep == NULL)
13828                 return;
13829         /*
13830          * Find the last inode in the block with dependencies.
13831          */
13832         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13833         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13834                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13835                         break;
13836         /*
13837          * Asynchronously push all but the last inode with dependencies.
13838          * Synchronously push the last inode with dependencies to ensure
13839          * that the inode block gets written to free up the inodedeps.
13840          */
13841         for (ino = firstino; ino <= lastino; ino++) {
13842                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13843                         continue;
13844                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13845                         continue;
13846                 FREE_LOCK(ump);
13847                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13848                 if (error != 0) {
13849                         vn_finished_write(mp);
13850                         ACQUIRE_LOCK(ump);
13851                         return;
13852                 }
13853                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13854                     FFSV_FORCEINSMQ)) != 0) {
13855                         softdep_error("clear_inodedeps: vget", error);
13856                         vfs_unbusy(mp);
13857                         vn_finished_write(mp);
13858                         ACQUIRE_LOCK(ump);
13859                         return;
13860                 }
13861                 vfs_unbusy(mp);
13862                 if (ino == lastino) {
13863                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13864                                 softdep_error("clear_inodedeps: fsync1", error);
13865                 } else {
13866                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13867                                 softdep_error("clear_inodedeps: fsync2", error);
13868                         BO_LOCK(&vp->v_bufobj);
13869                         drain_output(vp);
13870                         BO_UNLOCK(&vp->v_bufobj);
13871                 }
13872                 vput(vp);
13873                 vn_finished_write(mp);
13874                 ACQUIRE_LOCK(ump);
13875         }
13876 }
13877
13878 void
13879 softdep_buf_append(bp, wkhd)
13880         struct buf *bp;
13881         struct workhead *wkhd;
13882 {
13883         struct worklist *wk;
13884         struct ufsmount *ump;
13885
13886         if ((wk = LIST_FIRST(wkhd)) == NULL)
13887                 return;
13888         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13889             ("softdep_buf_append called on non-softdep filesystem"));
13890         ump = VFSTOUFS(wk->wk_mp);
13891         ACQUIRE_LOCK(ump);
13892         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13893                 WORKLIST_REMOVE(wk);
13894                 WORKLIST_INSERT(&bp->b_dep, wk);
13895         }
13896         FREE_LOCK(ump);
13897
13898 }
13899
13900 void
13901 softdep_inode_append(ip, cred, wkhd)
13902         struct inode *ip;
13903         struct ucred *cred;
13904         struct workhead *wkhd;
13905 {
13906         struct buf *bp;
13907         struct fs *fs;
13908         struct ufsmount *ump;
13909         int error;
13910
13911         ump = ITOUMP(ip);
13912         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13913             ("softdep_inode_append called on non-softdep filesystem"));
13914         fs = ump->um_fs;
13915         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13916             (int)fs->fs_bsize, cred, &bp);
13917         if (error) {
13918                 bqrelse(bp);
13919                 softdep_freework(wkhd);
13920                 return;
13921         }
13922         softdep_buf_append(bp, wkhd);
13923         bqrelse(bp);
13924 }
13925
13926 void
13927 softdep_freework(wkhd)
13928         struct workhead *wkhd;
13929 {
13930         struct worklist *wk;
13931         struct ufsmount *ump;
13932
13933         if ((wk = LIST_FIRST(wkhd)) == NULL)
13934                 return;
13935         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13936             ("softdep_freework called on non-softdep filesystem"));
13937         ump = VFSTOUFS(wk->wk_mp);
13938         ACQUIRE_LOCK(ump);
13939         handle_jwork(wkhd);
13940         FREE_LOCK(ump);
13941 }
13942
13943 static struct ufsmount *
13944 softdep_bp_to_mp(bp)
13945         struct buf *bp;
13946 {
13947         struct mount *mp;
13948         struct vnode *vp;
13949
13950         if (LIST_EMPTY(&bp->b_dep))
13951                 return (NULL);
13952         vp = bp->b_vp;
13953         KASSERT(vp != NULL,
13954             ("%s, buffer with dependencies lacks vnode", __func__));
13955
13956         /*
13957          * The ump mount point is stable after we get a correct
13958          * pointer, since bp is locked and this prevents unmount from
13959          * proceeding.  But to get to it, we cannot dereference bp->b_dep
13960          * head wk_mp, because we do not yet own SU ump lock and
13961          * workitem might be freed while dereferenced.
13962          */
13963 retry:
13964         switch (vp->v_type) {
13965         case VCHR:
13966                 VI_LOCK(vp);
13967                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13968                 VI_UNLOCK(vp);
13969                 if (mp == NULL)
13970                         goto retry;
13971                 break;
13972         case VREG:
13973         case VDIR:
13974         case VLNK:
13975         case VFIFO:
13976         case VSOCK:
13977                 mp = vp->v_mount;
13978                 break;
13979         case VBLK:
13980                 vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
13981                 /* FALLTHROUGH */
13982         case VNON:
13983         case VBAD:
13984         case VMARKER:
13985                 mp = NULL;
13986                 break;
13987         default:
13988                 vn_printf(vp, "unknown vnode type");
13989                 mp = NULL;
13990                 break;
13991         }
13992         return (VFSTOUFS(mp));
13993 }
13994
13995 /*
13996  * Function to determine if the buffer has outstanding dependencies
13997  * that will cause a roll-back if the buffer is written. If wantcount
13998  * is set, return number of dependencies, otherwise just yes or no.
13999  */
14000 static int
14001 softdep_count_dependencies(bp, wantcount)
14002         struct buf *bp;
14003         int wantcount;
14004 {
14005         struct worklist *wk;
14006         struct ufsmount *ump;
14007         struct bmsafemap *bmsafemap;
14008         struct freework *freework;
14009         struct inodedep *inodedep;
14010         struct indirdep *indirdep;
14011         struct freeblks *freeblks;
14012         struct allocindir *aip;
14013         struct pagedep *pagedep;
14014         struct dirrem *dirrem;
14015         struct newblk *newblk;
14016         struct mkdir *mkdir;
14017         struct diradd *dap;
14018         int i, retval;
14019
14020         ump = softdep_bp_to_mp(bp);
14021         if (ump == NULL)
14022                 return (0);
14023         retval = 0;
14024         ACQUIRE_LOCK(ump);
14025         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14026                 switch (wk->wk_type) {
14027
14028                 case D_INODEDEP:
14029                         inodedep = WK_INODEDEP(wk);
14030                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14031                                 /* bitmap allocation dependency */
14032                                 retval += 1;
14033                                 if (!wantcount)
14034                                         goto out;
14035                         }
14036                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14037                                 /* direct block pointer dependency */
14038                                 retval += 1;
14039                                 if (!wantcount)
14040                                         goto out;
14041                         }
14042                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14043                                 /* direct block pointer dependency */
14044                                 retval += 1;
14045                                 if (!wantcount)
14046                                         goto out;
14047                         }
14048                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14049                                 /* Add reference dependency. */
14050                                 retval += 1;
14051                                 if (!wantcount)
14052                                         goto out;
14053                         }
14054                         continue;
14055
14056                 case D_INDIRDEP:
14057                         indirdep = WK_INDIRDEP(wk);
14058
14059                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14060                                 /* indirect truncation dependency */
14061                                 retval += 1;
14062                                 if (!wantcount)
14063                                         goto out;
14064                         }
14065
14066                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14067                                 /* indirect block pointer dependency */
14068                                 retval += 1;
14069                                 if (!wantcount)
14070                                         goto out;
14071                         }
14072                         continue;
14073
14074                 case D_PAGEDEP:
14075                         pagedep = WK_PAGEDEP(wk);
14076                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14077                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14078                                         /* Journal remove ref dependency. */
14079                                         retval += 1;
14080                                         if (!wantcount)
14081                                                 goto out;
14082                                 }
14083                         }
14084                         for (i = 0; i < DAHASHSZ; i++) {
14085
14086                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14087                                         /* directory entry dependency */
14088                                         retval += 1;
14089                                         if (!wantcount)
14090                                                 goto out;
14091                                 }
14092                         }
14093                         continue;
14094
14095                 case D_BMSAFEMAP:
14096                         bmsafemap = WK_BMSAFEMAP(wk);
14097                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14098                                 /* Add reference dependency. */
14099                                 retval += 1;
14100                                 if (!wantcount)
14101                                         goto out;
14102                         }
14103                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14104                                 /* Allocate block dependency. */
14105                                 retval += 1;
14106                                 if (!wantcount)
14107                                         goto out;
14108                         }
14109                         continue;
14110
14111                 case D_FREEBLKS:
14112                         freeblks = WK_FREEBLKS(wk);
14113                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14114                                 /* Freeblk journal dependency. */
14115                                 retval += 1;
14116                                 if (!wantcount)
14117                                         goto out;
14118                         }
14119                         continue;
14120
14121                 case D_ALLOCDIRECT:
14122                 case D_ALLOCINDIR:
14123                         newblk = WK_NEWBLK(wk);
14124                         if (newblk->nb_jnewblk) {
14125                                 /* Journal allocate dependency. */
14126                                 retval += 1;
14127                                 if (!wantcount)
14128                                         goto out;
14129                         }
14130                         continue;
14131
14132                 case D_MKDIR:
14133                         mkdir = WK_MKDIR(wk);
14134                         if (mkdir->md_jaddref) {
14135                                 /* Journal reference dependency. */
14136                                 retval += 1;
14137                                 if (!wantcount)
14138                                         goto out;
14139                         }
14140                         continue;
14141
14142                 case D_FREEWORK:
14143                 case D_FREEDEP:
14144                 case D_JSEGDEP:
14145                 case D_JSEG:
14146                 case D_SBDEP:
14147                         /* never a dependency on these blocks */
14148                         continue;
14149
14150                 default:
14151                         panic("softdep_count_dependencies: Unexpected type %s",
14152                             TYPENAME(wk->wk_type));
14153                         /* NOTREACHED */
14154                 }
14155         }
14156 out:
14157         FREE_LOCK(ump);
14158         return (retval);
14159 }
14160
14161 /*
14162  * Acquire exclusive access to a buffer.
14163  * Must be called with a locked mtx parameter.
14164  * Return acquired buffer or NULL on failure.
14165  */
14166 static struct buf *
14167 getdirtybuf(bp, lock, waitfor)
14168         struct buf *bp;
14169         struct rwlock *lock;
14170         int waitfor;
14171 {
14172         int error;
14173
14174         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14175                 if (waitfor != MNT_WAIT)
14176                         return (NULL);
14177                 error = BUF_LOCK(bp,
14178                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14179                 /*
14180                  * Even if we successfully acquire bp here, we have dropped
14181                  * lock, which may violates our guarantee.
14182                  */
14183                 if (error == 0)
14184                         BUF_UNLOCK(bp);
14185                 else if (error != ENOLCK)
14186                         panic("getdirtybuf: inconsistent lock: %d", error);
14187                 rw_wlock(lock);
14188                 return (NULL);
14189         }
14190         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14191                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14192                         rw_wunlock(lock);
14193                         BO_LOCK(bp->b_bufobj);
14194                         BUF_UNLOCK(bp);
14195                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14196                                 bp->b_vflags |= BV_BKGRDWAIT;
14197                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14198                                        PRIBIO | PDROP, "getbuf", 0);
14199                         } else
14200                                 BO_UNLOCK(bp->b_bufobj);
14201                         rw_wlock(lock);
14202                         return (NULL);
14203                 }
14204                 BUF_UNLOCK(bp);
14205                 if (waitfor != MNT_WAIT)
14206                         return (NULL);
14207 #ifdef DEBUG_VFS_LOCKS
14208                 if (bp->b_vp->v_type != VCHR)
14209                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14210 #endif
14211                 bp->b_vflags |= BV_BKGRDWAIT;
14212                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14213                 return (NULL);
14214         }
14215         if ((bp->b_flags & B_DELWRI) == 0) {
14216                 BUF_UNLOCK(bp);
14217                 return (NULL);
14218         }
14219         bremfree(bp);
14220         return (bp);
14221 }
14222
14223
14224 /*
14225  * Check if it is safe to suspend the file system now.  On entry,
14226  * the vnode interlock for devvp should be held.  Return 0 with
14227  * the mount interlock held if the file system can be suspended now,
14228  * otherwise return EAGAIN with the mount interlock held.
14229  */
14230 int
14231 softdep_check_suspend(struct mount *mp,
14232                       struct vnode *devvp,
14233                       int softdep_depcnt,
14234                       int softdep_accdepcnt,
14235                       int secondary_writes,
14236                       int secondary_accwrites)
14237 {
14238         struct bufobj *bo;
14239         struct ufsmount *ump;
14240         struct inodedep *inodedep;
14241         int error, unlinked;
14242
14243         bo = &devvp->v_bufobj;
14244         ASSERT_BO_WLOCKED(bo);
14245
14246         /*
14247          * If we are not running with soft updates, then we need only
14248          * deal with secondary writes as we try to suspend.
14249          */
14250         if (MOUNTEDSOFTDEP(mp) == 0) {
14251                 MNT_ILOCK(mp);
14252                 while (mp->mnt_secondary_writes != 0) {
14253                         BO_UNLOCK(bo);
14254                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14255                             (PUSER - 1) | PDROP, "secwr", 0);
14256                         BO_LOCK(bo);
14257                         MNT_ILOCK(mp);
14258                 }
14259
14260                 /*
14261                  * Reasons for needing more work before suspend:
14262                  * - Dirty buffers on devvp.
14263                  * - Secondary writes occurred after start of vnode sync loop
14264                  */
14265                 error = 0;
14266                 if (bo->bo_numoutput > 0 ||
14267                     bo->bo_dirty.bv_cnt > 0 ||
14268                     secondary_writes != 0 ||
14269                     mp->mnt_secondary_writes != 0 ||
14270                     secondary_accwrites != mp->mnt_secondary_accwrites)
14271                         error = EAGAIN;
14272                 BO_UNLOCK(bo);
14273                 return (error);
14274         }
14275
14276         /*
14277          * If we are running with soft updates, then we need to coordinate
14278          * with them as we try to suspend.
14279          */
14280         ump = VFSTOUFS(mp);
14281         for (;;) {
14282                 if (!TRY_ACQUIRE_LOCK(ump)) {
14283                         BO_UNLOCK(bo);
14284                         ACQUIRE_LOCK(ump);
14285                         FREE_LOCK(ump);
14286                         BO_LOCK(bo);
14287                         continue;
14288                 }
14289                 MNT_ILOCK(mp);
14290                 if (mp->mnt_secondary_writes != 0) {
14291                         FREE_LOCK(ump);
14292                         BO_UNLOCK(bo);
14293                         msleep(&mp->mnt_secondary_writes,
14294                                MNT_MTX(mp),
14295                                (PUSER - 1) | PDROP, "secwr", 0);
14296                         BO_LOCK(bo);
14297                         continue;
14298                 }
14299                 break;
14300         }
14301
14302         unlinked = 0;
14303         if (MOUNTEDSUJ(mp)) {
14304                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14305                     inodedep != NULL;
14306                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14307                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14308                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14309                             UNLINKONLIST) ||
14310                             !check_inodedep_free(inodedep))
14311                                 continue;
14312                         unlinked++;
14313                 }
14314         }
14315
14316         /*
14317          * Reasons for needing more work before suspend:
14318          * - Dirty buffers on devvp.
14319          * - Softdep activity occurred after start of vnode sync loop
14320          * - Secondary writes occurred after start of vnode sync loop
14321          */
14322         error = 0;
14323         if (bo->bo_numoutput > 0 ||
14324             bo->bo_dirty.bv_cnt > 0 ||
14325             softdep_depcnt != unlinked ||
14326             ump->softdep_deps != unlinked ||
14327             softdep_accdepcnt != ump->softdep_accdeps ||
14328             secondary_writes != 0 ||
14329             mp->mnt_secondary_writes != 0 ||
14330             secondary_accwrites != mp->mnt_secondary_accwrites)
14331                 error = EAGAIN;
14332         FREE_LOCK(ump);
14333         BO_UNLOCK(bo);
14334         return (error);
14335 }
14336
14337
14338 /*
14339  * Get the number of dependency structures for the file system, both
14340  * the current number and the total number allocated.  These will
14341  * later be used to detect that softdep processing has occurred.
14342  */
14343 void
14344 softdep_get_depcounts(struct mount *mp,
14345                       int *softdep_depsp,
14346                       int *softdep_accdepsp)
14347 {
14348         struct ufsmount *ump;
14349
14350         if (MOUNTEDSOFTDEP(mp) == 0) {
14351                 *softdep_depsp = 0;
14352                 *softdep_accdepsp = 0;
14353                 return;
14354         }
14355         ump = VFSTOUFS(mp);
14356         ACQUIRE_LOCK(ump);
14357         *softdep_depsp = ump->softdep_deps;
14358         *softdep_accdepsp = ump->softdep_accdeps;
14359         FREE_LOCK(ump);
14360 }
14361
14362 /*
14363  * Wait for pending output on a vnode to complete.
14364  */
14365 static void
14366 drain_output(vp)
14367         struct vnode *vp;
14368 {
14369
14370         ASSERT_VOP_LOCKED(vp, "drain_output");
14371         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14372 }
14373
14374 /*
14375  * Called whenever a buffer that is being invalidated or reallocated
14376  * contains dependencies. This should only happen if an I/O error has
14377  * occurred. The routine is called with the buffer locked.
14378  */ 
14379 static void
14380 softdep_deallocate_dependencies(bp)
14381         struct buf *bp;
14382 {
14383
14384         if ((bp->b_ioflags & BIO_ERROR) == 0)
14385                 panic("softdep_deallocate_dependencies: dangling deps");
14386         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14387                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14388         else
14389                 printf("softdep_deallocate_dependencies: "
14390                     "got error %d while accessing filesystem\n", bp->b_error);
14391         if (bp->b_error != ENXIO)
14392                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14393 }
14394
14395 /*
14396  * Function to handle asynchronous write errors in the filesystem.
14397  */
14398 static void
14399 softdep_error(func, error)
14400         char *func;
14401         int error;
14402 {
14403
14404         /* XXX should do something better! */
14405         printf("%s: got error %d while accessing filesystem\n", func, error);
14406 }
14407
14408 #ifdef DDB
14409
14410 static void
14411 inodedep_print(struct inodedep *inodedep, int verbose)
14412 {
14413         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14414             " saveino %p\n",
14415             inodedep, inodedep->id_fs, inodedep->id_state,
14416             (intmax_t)inodedep->id_ino,
14417             (intmax_t)fsbtodb(inodedep->id_fs,
14418             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14419             (intmax_t)inodedep->id_nlinkdelta,
14420             (intmax_t)inodedep->id_savednlink,
14421             inodedep->id_savedino1);
14422
14423         if (verbose == 0)
14424                 return;
14425
14426         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14427             "mkdiradd %p\n",
14428             LIST_FIRST(&inodedep->id_pendinghd),
14429             LIST_FIRST(&inodedep->id_bufwait),
14430             LIST_FIRST(&inodedep->id_inowait),
14431             TAILQ_FIRST(&inodedep->id_inoreflst),
14432             inodedep->id_mkdiradd);
14433         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14434             TAILQ_FIRST(&inodedep->id_inoupdt),
14435             TAILQ_FIRST(&inodedep->id_newinoupdt),
14436             TAILQ_FIRST(&inodedep->id_extupdt),
14437             TAILQ_FIRST(&inodedep->id_newextupdt));
14438 }
14439
14440 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14441 {
14442
14443         if (have_addr == 0) {
14444                 db_printf("Address required\n");
14445                 return;
14446         }
14447         inodedep_print((struct inodedep*)addr, 1);
14448 }
14449
14450 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14451 {
14452         struct inodedep_hashhead *inodedephd;
14453         struct inodedep *inodedep;
14454         struct ufsmount *ump;
14455         int cnt;
14456
14457         if (have_addr == 0) {
14458                 db_printf("Address required\n");
14459                 return;
14460         }
14461         ump = (struct ufsmount *)addr;
14462         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14463                 inodedephd = &ump->inodedep_hashtbl[cnt];
14464                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14465                         inodedep_print(inodedep, 0);
14466                 }
14467         }
14468 }
14469
14470 DB_SHOW_COMMAND(worklist, db_show_worklist)
14471 {
14472         struct worklist *wk;
14473
14474         if (have_addr == 0) {
14475                 db_printf("Address required\n");
14476                 return;
14477         }
14478         wk = (struct worklist *)addr;
14479         printf("worklist: %p type %s state 0x%X\n",
14480             wk, TYPENAME(wk->wk_type), wk->wk_state);
14481 }
14482
14483 DB_SHOW_COMMAND(workhead, db_show_workhead)
14484 {
14485         struct workhead *wkhd;
14486         struct worklist *wk;
14487         int i;
14488
14489         if (have_addr == 0) {
14490                 db_printf("Address required\n");
14491                 return;
14492         }
14493         wkhd = (struct workhead *)addr;
14494         wk = LIST_FIRST(wkhd);
14495         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14496                 db_printf("worklist: %p type %s state 0x%X",
14497                     wk, TYPENAME(wk->wk_type), wk->wk_state);
14498         if (i == 100)
14499                 db_printf("workhead overflow");
14500         printf("\n");
14501 }
14502
14503
14504 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14505 {
14506         struct mkdirlist *mkdirlisthd;
14507         struct jaddref *jaddref;
14508         struct diradd *diradd;
14509         struct mkdir *mkdir;
14510
14511         if (have_addr == 0) {
14512                 db_printf("Address required\n");
14513                 return;
14514         }
14515         mkdirlisthd = (struct mkdirlist *)addr;
14516         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14517                 diradd = mkdir->md_diradd;
14518                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14519                     mkdir, mkdir->md_state, diradd, diradd->da_state);
14520                 if ((jaddref = mkdir->md_jaddref) != NULL)
14521                         db_printf(" jaddref %p jaddref state 0x%X",
14522                             jaddref, jaddref->ja_state);
14523                 db_printf("\n");
14524         }
14525 }
14526
14527 /* exported to ffs_vfsops.c */
14528 extern void db_print_ffs(struct ufsmount *ump);
14529 void
14530 db_print_ffs(struct ufsmount *ump)
14531 {
14532         db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14533             ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14534             ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14535             ump->softdep_deps, ump->softdep_req);
14536 }
14537
14538 #endif /* DDB */
14539
14540 #endif /* SOFTUPDATES */