]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
Update OpenSSL to 1.1.1.
[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  * This routine must be called with splbio interrupts blocked.
2102  */
2103 static int
2104 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2105         struct mount *mp;
2106         struct buf *bp;
2107         ino_t ino;
2108         ufs_lbn_t lbn;
2109         int flags;
2110         struct pagedep **pagedeppp;
2111 {
2112         struct pagedep *pagedep;
2113         struct pagedep_hashhead *pagedephd;
2114         struct worklist *wk;
2115         struct ufsmount *ump;
2116         int ret;
2117         int i;
2118
2119         ump = VFSTOUFS(mp);
2120         LOCK_OWNED(ump);
2121         if (bp) {
2122                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2123                         if (wk->wk_type == D_PAGEDEP) {
2124                                 *pagedeppp = WK_PAGEDEP(wk);
2125                                 return (1);
2126                         }
2127                 }
2128         }
2129         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2130         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2131         if (ret) {
2132                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2133                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2134                 return (1);
2135         }
2136         if ((flags & DEPALLOC) == 0)
2137                 return (0);
2138         FREE_LOCK(ump);
2139         pagedep = malloc(sizeof(struct pagedep),
2140             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2141         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2142         ACQUIRE_LOCK(ump);
2143         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2144         if (*pagedeppp) {
2145                 /*
2146                  * This should never happen since we only create pagedeps
2147                  * with the vnode lock held.  Could be an assert.
2148                  */
2149                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2150                 return (ret);
2151         }
2152         pagedep->pd_ino = ino;
2153         pagedep->pd_lbn = lbn;
2154         LIST_INIT(&pagedep->pd_dirremhd);
2155         LIST_INIT(&pagedep->pd_pendinghd);
2156         for (i = 0; i < DAHASHSZ; i++)
2157                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2158         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2159         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2160         *pagedeppp = pagedep;
2161         return (0);
2162 }
2163
2164 /*
2165  * Structures and routines associated with inodedep caching.
2166  */
2167 #define INODEDEP_HASH(ump, inum) \
2168       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2169
2170 static int
2171 inodedep_find(inodedephd, inum, inodedeppp)
2172         struct inodedep_hashhead *inodedephd;
2173         ino_t inum;
2174         struct inodedep **inodedeppp;
2175 {
2176         struct inodedep *inodedep;
2177
2178         LIST_FOREACH(inodedep, inodedephd, id_hash)
2179                 if (inum == inodedep->id_ino)
2180                         break;
2181         if (inodedep) {
2182                 *inodedeppp = inodedep;
2183                 return (1);
2184         }
2185         *inodedeppp = NULL;
2186
2187         return (0);
2188 }
2189 /*
2190  * Look up an inodedep. Return 1 if found, 0 if not found.
2191  * If not found, allocate if DEPALLOC flag is passed.
2192  * Found or allocated entry is returned in inodedeppp.
2193  * This routine must be called with splbio interrupts blocked.
2194  */
2195 static int
2196 inodedep_lookup(mp, inum, flags, inodedeppp)
2197         struct mount *mp;
2198         ino_t inum;
2199         int flags;
2200         struct inodedep **inodedeppp;
2201 {
2202         struct inodedep *inodedep;
2203         struct inodedep_hashhead *inodedephd;
2204         struct ufsmount *ump;
2205         struct fs *fs;
2206
2207         ump = VFSTOUFS(mp);
2208         LOCK_OWNED(ump);
2209         fs = ump->um_fs;
2210         inodedephd = INODEDEP_HASH(ump, inum);
2211
2212         if (inodedep_find(inodedephd, inum, inodedeppp))
2213                 return (1);
2214         if ((flags & DEPALLOC) == 0)
2215                 return (0);
2216         /*
2217          * If the system is over its limit and our filesystem is
2218          * responsible for more than our share of that usage and
2219          * we are not in a rush, request some inodedep cleanup.
2220          */
2221         if (softdep_excess_items(ump, D_INODEDEP))
2222                 schedule_cleanup(mp);
2223         else
2224                 FREE_LOCK(ump);
2225         inodedep = malloc(sizeof(struct inodedep),
2226                 M_INODEDEP, M_SOFTDEP_FLAGS);
2227         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2228         ACQUIRE_LOCK(ump);
2229         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2230                 WORKITEM_FREE(inodedep, D_INODEDEP);
2231                 return (1);
2232         }
2233         inodedep->id_fs = fs;
2234         inodedep->id_ino = inum;
2235         inodedep->id_state = ALLCOMPLETE;
2236         inodedep->id_nlinkdelta = 0;
2237         inodedep->id_savedino1 = NULL;
2238         inodedep->id_savedsize = -1;
2239         inodedep->id_savedextsize = -1;
2240         inodedep->id_savednlink = -1;
2241         inodedep->id_bmsafemap = NULL;
2242         inodedep->id_mkdiradd = NULL;
2243         LIST_INIT(&inodedep->id_dirremhd);
2244         LIST_INIT(&inodedep->id_pendinghd);
2245         LIST_INIT(&inodedep->id_inowait);
2246         LIST_INIT(&inodedep->id_bufwait);
2247         TAILQ_INIT(&inodedep->id_inoreflst);
2248         TAILQ_INIT(&inodedep->id_inoupdt);
2249         TAILQ_INIT(&inodedep->id_newinoupdt);
2250         TAILQ_INIT(&inodedep->id_extupdt);
2251         TAILQ_INIT(&inodedep->id_newextupdt);
2252         TAILQ_INIT(&inodedep->id_freeblklst);
2253         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2254         *inodedeppp = inodedep;
2255         return (0);
2256 }
2257
2258 /*
2259  * Structures and routines associated with newblk caching.
2260  */
2261 #define NEWBLK_HASH(ump, inum) \
2262         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2263
2264 static int
2265 newblk_find(newblkhd, newblkno, flags, newblkpp)
2266         struct newblk_hashhead *newblkhd;
2267         ufs2_daddr_t newblkno;
2268         int flags;
2269         struct newblk **newblkpp;
2270 {
2271         struct newblk *newblk;
2272
2273         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2274                 if (newblkno != newblk->nb_newblkno)
2275                         continue;
2276                 /*
2277                  * If we're creating a new dependency don't match those that
2278                  * have already been converted to allocdirects.  This is for
2279                  * a frag extend.
2280                  */
2281                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2282                         continue;
2283                 break;
2284         }
2285         if (newblk) {
2286                 *newblkpp = newblk;
2287                 return (1);
2288         }
2289         *newblkpp = NULL;
2290         return (0);
2291 }
2292
2293 /*
2294  * Look up a newblk. Return 1 if found, 0 if not found.
2295  * If not found, allocate if DEPALLOC flag is passed.
2296  * Found or allocated entry is returned in newblkpp.
2297  */
2298 static int
2299 newblk_lookup(mp, newblkno, flags, newblkpp)
2300         struct mount *mp;
2301         ufs2_daddr_t newblkno;
2302         int flags;
2303         struct newblk **newblkpp;
2304 {
2305         struct newblk *newblk;
2306         struct newblk_hashhead *newblkhd;
2307         struct ufsmount *ump;
2308
2309         ump = VFSTOUFS(mp);
2310         LOCK_OWNED(ump);
2311         newblkhd = NEWBLK_HASH(ump, newblkno);
2312         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2313                 return (1);
2314         if ((flags & DEPALLOC) == 0)
2315                 return (0);
2316         if (softdep_excess_items(ump, D_NEWBLK) ||
2317             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2318             softdep_excess_items(ump, D_ALLOCINDIR))
2319                 schedule_cleanup(mp);
2320         else
2321                 FREE_LOCK(ump);
2322         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2323             M_SOFTDEP_FLAGS | M_ZERO);
2324         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2325         ACQUIRE_LOCK(ump);
2326         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2327                 WORKITEM_FREE(newblk, D_NEWBLK);
2328                 return (1);
2329         }
2330         newblk->nb_freefrag = NULL;
2331         LIST_INIT(&newblk->nb_indirdeps);
2332         LIST_INIT(&newblk->nb_newdirblk);
2333         LIST_INIT(&newblk->nb_jwork);
2334         newblk->nb_state = ATTACHED;
2335         newblk->nb_newblkno = newblkno;
2336         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2337         *newblkpp = newblk;
2338         return (0);
2339 }
2340
2341 /*
2342  * Structures and routines associated with freed indirect block caching.
2343  */
2344 #define INDIR_HASH(ump, blkno) \
2345         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2346
2347 /*
2348  * Lookup an indirect block in the indir hash table.  The freework is
2349  * removed and potentially freed.  The caller must do a blocking journal
2350  * write before writing to the blkno.
2351  */
2352 static int
2353 indirblk_lookup(mp, blkno)
2354         struct mount *mp;
2355         ufs2_daddr_t blkno;
2356 {
2357         struct freework *freework;
2358         struct indir_hashhead *wkhd;
2359         struct ufsmount *ump;
2360
2361         ump = VFSTOUFS(mp);
2362         wkhd = INDIR_HASH(ump, blkno);
2363         TAILQ_FOREACH(freework, wkhd, fw_next) {
2364                 if (freework->fw_blkno != blkno)
2365                         continue;
2366                 indirblk_remove(freework);
2367                 return (1);
2368         }
2369         return (0);
2370 }
2371
2372 /*
2373  * Insert an indirect block represented by freework into the indirblk
2374  * hash table so that it may prevent the block from being re-used prior
2375  * to the journal being written.
2376  */
2377 static void
2378 indirblk_insert(freework)
2379         struct freework *freework;
2380 {
2381         struct jblocks *jblocks;
2382         struct jseg *jseg;
2383         struct ufsmount *ump;
2384
2385         ump = VFSTOUFS(freework->fw_list.wk_mp);
2386         jblocks = ump->softdep_jblocks;
2387         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2388         if (jseg == NULL)
2389                 return;
2390         
2391         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2392         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2393             fw_next);
2394         freework->fw_state &= ~DEPCOMPLETE;
2395 }
2396
2397 static void
2398 indirblk_remove(freework)
2399         struct freework *freework;
2400 {
2401         struct ufsmount *ump;
2402
2403         ump = VFSTOUFS(freework->fw_list.wk_mp);
2404         LIST_REMOVE(freework, fw_segs);
2405         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2406         freework->fw_state |= DEPCOMPLETE;
2407         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2408                 WORKITEM_FREE(freework, D_FREEWORK);
2409 }
2410
2411 /*
2412  * Executed during filesystem system initialization before
2413  * mounting any filesystems.
2414  */
2415 void 
2416 softdep_initialize()
2417 {
2418
2419         TAILQ_INIT(&softdepmounts);
2420 #ifdef __LP64__
2421         max_softdeps = desiredvnodes * 4;
2422 #else
2423         max_softdeps = desiredvnodes * 2;
2424 #endif
2425
2426         /* initialise bioops hack */
2427         bioops.io_start = softdep_disk_io_initiation;
2428         bioops.io_complete = softdep_disk_write_complete;
2429         bioops.io_deallocate = softdep_deallocate_dependencies;
2430         bioops.io_countdeps = softdep_count_dependencies;
2431         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2432
2433         /* Initialize the callout with an mtx. */
2434         callout_init_mtx(&softdep_callout, &lk, 0);
2435 }
2436
2437 /*
2438  * Executed after all filesystems have been unmounted during
2439  * filesystem module unload.
2440  */
2441 void
2442 softdep_uninitialize()
2443 {
2444
2445         /* clear bioops hack */
2446         bioops.io_start = NULL;
2447         bioops.io_complete = NULL;
2448         bioops.io_deallocate = NULL;
2449         bioops.io_countdeps = NULL;
2450         softdep_ast_cleanup = NULL;
2451
2452         callout_drain(&softdep_callout);
2453 }
2454
2455 /*
2456  * Called at mount time to notify the dependency code that a
2457  * filesystem wishes to use it.
2458  */
2459 int
2460 softdep_mount(devvp, mp, fs, cred)
2461         struct vnode *devvp;
2462         struct mount *mp;
2463         struct fs *fs;
2464         struct ucred *cred;
2465 {
2466         struct csum_total cstotal;
2467         struct mount_softdeps *sdp;
2468         struct ufsmount *ump;
2469         struct cg *cgp;
2470         struct buf *bp;
2471         u_int cyl, i;
2472         int error;
2473
2474         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2475             M_WAITOK | M_ZERO);
2476         MNT_ILOCK(mp);
2477         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2478         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2479                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2480                         MNTK_SOFTDEP | MNTK_NOASYNC;
2481         }
2482         ump = VFSTOUFS(mp);
2483         ump->um_softdep = sdp;
2484         MNT_IUNLOCK(mp);
2485         rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2486         sdp->sd_ump = ump;
2487         LIST_INIT(&ump->softdep_workitem_pending);
2488         LIST_INIT(&ump->softdep_journal_pending);
2489         TAILQ_INIT(&ump->softdep_unlinked);
2490         LIST_INIT(&ump->softdep_dirtycg);
2491         ump->softdep_worklist_tail = NULL;
2492         ump->softdep_on_worklist = 0;
2493         ump->softdep_deps = 0;
2494         LIST_INIT(&ump->softdep_mkdirlisthd);
2495         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2496             &ump->pagedep_hash_size);
2497         ump->pagedep_nextclean = 0;
2498         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2499             &ump->inodedep_hash_size);
2500         ump->inodedep_nextclean = 0;
2501         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2502             &ump->newblk_hash_size);
2503         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2504             &ump->bmsafemap_hash_size);
2505         i = 1 << (ffs(desiredvnodes / 10) - 1);
2506         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2507             M_FREEWORK, M_WAITOK);
2508         ump->indir_hash_size = i - 1;
2509         for (i = 0; i <= ump->indir_hash_size; i++)
2510                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2511         ACQUIRE_GBLLOCK(&lk);
2512         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2513         FREE_GBLLOCK(&lk);
2514         if ((fs->fs_flags & FS_SUJ) &&
2515             (error = journal_mount(mp, fs, cred)) != 0) {
2516                 printf("Failed to start journal: %d\n", error);
2517                 softdep_unmount(mp);
2518                 return (error);
2519         }
2520         /*
2521          * Start our flushing thread in the bufdaemon process.
2522          */
2523         ACQUIRE_LOCK(ump);
2524         ump->softdep_flags |= FLUSH_STARTING;
2525         FREE_LOCK(ump);
2526         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2527             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2528             mp->mnt_stat.f_mntonname);
2529         ACQUIRE_LOCK(ump);
2530         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2531                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2532                     hz / 2);
2533         }
2534         FREE_LOCK(ump);
2535         /*
2536          * When doing soft updates, the counters in the
2537          * superblock may have gotten out of sync. Recomputation
2538          * can take a long time and can be deferred for background
2539          * fsck.  However, the old behavior of scanning the cylinder
2540          * groups and recalculating them at mount time is available
2541          * by setting vfs.ffs.compute_summary_at_mount to one.
2542          */
2543         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2544                 return (0);
2545         bzero(&cstotal, sizeof cstotal);
2546         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2547                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2548                     fs->fs_cgsize, cred, &bp)) != 0) {
2549                         brelse(bp);
2550                         softdep_unmount(mp);
2551                         return (error);
2552                 }
2553                 cgp = (struct cg *)bp->b_data;
2554                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2555                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2556                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2557                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2558                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2559                 brelse(bp);
2560         }
2561 #ifdef DEBUG
2562         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2563                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2564 #endif
2565         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2566         return (0);
2567 }
2568
2569 void
2570 softdep_unmount(mp)
2571         struct mount *mp;
2572 {
2573         struct ufsmount *ump;
2574 #ifdef INVARIANTS
2575         int i;
2576 #endif
2577
2578         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2579             ("softdep_unmount called on non-softdep filesystem"));
2580         ump = VFSTOUFS(mp);
2581         MNT_ILOCK(mp);
2582         mp->mnt_flag &= ~MNT_SOFTDEP;
2583         if (MOUNTEDSUJ(mp) == 0) {
2584                 MNT_IUNLOCK(mp);
2585         } else {
2586                 mp->mnt_flag &= ~MNT_SUJ;
2587                 MNT_IUNLOCK(mp);
2588                 journal_unmount(ump);
2589         }
2590         /*
2591          * Shut down our flushing thread. Check for NULL is if
2592          * softdep_mount errors out before the thread has been created.
2593          */
2594         if (ump->softdep_flushtd != NULL) {
2595                 ACQUIRE_LOCK(ump);
2596                 ump->softdep_flags |= FLUSH_EXIT;
2597                 wakeup(&ump->softdep_flushtd);
2598                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2599                     "sdwait", 0);
2600                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2601                     ("Thread shutdown failed"));
2602         }
2603         /*
2604          * Free up our resources.
2605          */
2606         ACQUIRE_GBLLOCK(&lk);
2607         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2608         FREE_GBLLOCK(&lk);
2609         rw_destroy(LOCK_PTR(ump));
2610         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2611         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2612         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2613         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2614             ump->bmsafemap_hash_size);
2615         free(ump->indir_hashtbl, M_FREEWORK);
2616 #ifdef INVARIANTS
2617         for (i = 0; i <= D_LAST; i++)
2618                 KASSERT(ump->softdep_curdeps[i] == 0,
2619                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2620                     TYPENAME(i), ump->softdep_curdeps[i]));
2621 #endif
2622         free(ump->um_softdep, M_MOUNTDATA);
2623 }
2624
2625 static struct jblocks *
2626 jblocks_create(void)
2627 {
2628         struct jblocks *jblocks;
2629
2630         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2631         TAILQ_INIT(&jblocks->jb_segs);
2632         jblocks->jb_avail = 10;
2633         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2634             M_JBLOCKS, M_WAITOK | M_ZERO);
2635
2636         return (jblocks);
2637 }
2638
2639 static ufs2_daddr_t
2640 jblocks_alloc(jblocks, bytes, actual)
2641         struct jblocks *jblocks;
2642         int bytes;
2643         int *actual;
2644 {
2645         ufs2_daddr_t daddr;
2646         struct jextent *jext;
2647         int freecnt;
2648         int blocks;
2649
2650         blocks = bytes / DEV_BSIZE;
2651         jext = &jblocks->jb_extent[jblocks->jb_head];
2652         freecnt = jext->je_blocks - jblocks->jb_off;
2653         if (freecnt == 0) {
2654                 jblocks->jb_off = 0;
2655                 if (++jblocks->jb_head > jblocks->jb_used)
2656                         jblocks->jb_head = 0;
2657                 jext = &jblocks->jb_extent[jblocks->jb_head];
2658                 freecnt = jext->je_blocks;
2659         }
2660         if (freecnt > blocks)
2661                 freecnt = blocks;
2662         *actual = freecnt * DEV_BSIZE;
2663         daddr = jext->je_daddr + jblocks->jb_off;
2664         jblocks->jb_off += freecnt;
2665         jblocks->jb_free -= freecnt;
2666
2667         return (daddr);
2668 }
2669
2670 static void
2671 jblocks_free(jblocks, mp, bytes)
2672         struct jblocks *jblocks;
2673         struct mount *mp;
2674         int bytes;
2675 {
2676
2677         LOCK_OWNED(VFSTOUFS(mp));
2678         jblocks->jb_free += bytes / DEV_BSIZE;
2679         if (jblocks->jb_suspended)
2680                 worklist_speedup(mp);
2681         wakeup(jblocks);
2682 }
2683
2684 static void
2685 jblocks_destroy(jblocks)
2686         struct jblocks *jblocks;
2687 {
2688
2689         if (jblocks->jb_extent)
2690                 free(jblocks->jb_extent, M_JBLOCKS);
2691         free(jblocks, M_JBLOCKS);
2692 }
2693
2694 static void
2695 jblocks_add(jblocks, daddr, blocks)
2696         struct jblocks *jblocks;
2697         ufs2_daddr_t daddr;
2698         int blocks;
2699 {
2700         struct jextent *jext;
2701
2702         jblocks->jb_blocks += blocks;
2703         jblocks->jb_free += blocks;
2704         jext = &jblocks->jb_extent[jblocks->jb_used];
2705         /* Adding the first block. */
2706         if (jext->je_daddr == 0) {
2707                 jext->je_daddr = daddr;
2708                 jext->je_blocks = blocks;
2709                 return;
2710         }
2711         /* Extending the last extent. */
2712         if (jext->je_daddr + jext->je_blocks == daddr) {
2713                 jext->je_blocks += blocks;
2714                 return;
2715         }
2716         /* Adding a new extent. */
2717         if (++jblocks->jb_used == jblocks->jb_avail) {
2718                 jblocks->jb_avail *= 2;
2719                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2720                     M_JBLOCKS, M_WAITOK | M_ZERO);
2721                 memcpy(jext, jblocks->jb_extent,
2722                     sizeof(struct jextent) * jblocks->jb_used);
2723                 free(jblocks->jb_extent, M_JBLOCKS);
2724                 jblocks->jb_extent = jext;
2725         }
2726         jext = &jblocks->jb_extent[jblocks->jb_used];
2727         jext->je_daddr = daddr;
2728         jext->je_blocks = blocks;
2729         return;
2730 }
2731
2732 int
2733 softdep_journal_lookup(mp, vpp)
2734         struct mount *mp;
2735         struct vnode **vpp;
2736 {
2737         struct componentname cnp;
2738         struct vnode *dvp;
2739         ino_t sujournal;
2740         int error;
2741
2742         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2743         if (error)
2744                 return (error);
2745         bzero(&cnp, sizeof(cnp));
2746         cnp.cn_nameiop = LOOKUP;
2747         cnp.cn_flags = ISLASTCN;
2748         cnp.cn_thread = curthread;
2749         cnp.cn_cred = curthread->td_ucred;
2750         cnp.cn_pnbuf = SUJ_FILE;
2751         cnp.cn_nameptr = SUJ_FILE;
2752         cnp.cn_namelen = strlen(SUJ_FILE);
2753         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2754         vput(dvp);
2755         if (error != 0)
2756                 return (error);
2757         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2758         return (error);
2759 }
2760
2761 /*
2762  * Open and verify the journal file.
2763  */
2764 static int
2765 journal_mount(mp, fs, cred)
2766         struct mount *mp;
2767         struct fs *fs;
2768         struct ucred *cred;
2769 {
2770         struct jblocks *jblocks;
2771         struct ufsmount *ump;
2772         struct vnode *vp;
2773         struct inode *ip;
2774         ufs2_daddr_t blkno;
2775         int bcount;
2776         int error;
2777         int i;
2778
2779         ump = VFSTOUFS(mp);
2780         ump->softdep_journal_tail = NULL;
2781         ump->softdep_on_journal = 0;
2782         ump->softdep_accdeps = 0;
2783         ump->softdep_req = 0;
2784         ump->softdep_jblocks = NULL;
2785         error = softdep_journal_lookup(mp, &vp);
2786         if (error != 0) {
2787                 printf("Failed to find journal.  Use tunefs to create one\n");
2788                 return (error);
2789         }
2790         ip = VTOI(vp);
2791         if (ip->i_size < SUJ_MIN) {
2792                 error = ENOSPC;
2793                 goto out;
2794         }
2795         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2796         jblocks = jblocks_create();
2797         for (i = 0; i < bcount; i++) {
2798                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2799                 if (error)
2800                         break;
2801                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2802         }
2803         if (error) {
2804                 jblocks_destroy(jblocks);
2805                 goto out;
2806         }
2807         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2808         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2809         ump->softdep_jblocks = jblocks;
2810 out:
2811         if (error == 0) {
2812                 MNT_ILOCK(mp);
2813                 mp->mnt_flag |= MNT_SUJ;
2814                 mp->mnt_flag &= ~MNT_SOFTDEP;
2815                 MNT_IUNLOCK(mp);
2816                 /*
2817                  * Only validate the journal contents if the
2818                  * filesystem is clean, otherwise we write the logs
2819                  * but they'll never be used.  If the filesystem was
2820                  * still dirty when we mounted it the journal is
2821                  * invalid and a new journal can only be valid if it
2822                  * starts from a clean mount.
2823                  */
2824                 if (fs->fs_clean) {
2825                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2826                         ip->i_flags |= IN_MODIFIED;
2827                         ffs_update(vp, 1);
2828                 }
2829         }
2830         vput(vp);
2831         return (error);
2832 }
2833
2834 static void
2835 journal_unmount(ump)
2836         struct ufsmount *ump;
2837 {
2838
2839         if (ump->softdep_jblocks)
2840                 jblocks_destroy(ump->softdep_jblocks);
2841         ump->softdep_jblocks = NULL;
2842 }
2843
2844 /*
2845  * Called when a journal record is ready to be written.  Space is allocated
2846  * and the journal entry is created when the journal is flushed to stable
2847  * store.
2848  */
2849 static void
2850 add_to_journal(wk)
2851         struct worklist *wk;
2852 {
2853         struct ufsmount *ump;
2854
2855         ump = VFSTOUFS(wk->wk_mp);
2856         LOCK_OWNED(ump);
2857         if (wk->wk_state & ONWORKLIST)
2858                 panic("add_to_journal: %s(0x%X) already on list",
2859                     TYPENAME(wk->wk_type), wk->wk_state);
2860         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2861         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2862                 ump->softdep_jblocks->jb_age = ticks;
2863                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2864         } else
2865                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2866         ump->softdep_journal_tail = wk;
2867         ump->softdep_on_journal += 1;
2868 }
2869
2870 /*
2871  * Remove an arbitrary item for the journal worklist maintain the tail
2872  * pointer.  This happens when a new operation obviates the need to
2873  * journal an old operation.
2874  */
2875 static void
2876 remove_from_journal(wk)
2877         struct worklist *wk;
2878 {
2879         struct ufsmount *ump;
2880
2881         ump = VFSTOUFS(wk->wk_mp);
2882         LOCK_OWNED(ump);
2883 #ifdef SUJ_DEBUG
2884         {
2885                 struct worklist *wkn;
2886
2887                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2888                         if (wkn == wk)
2889                                 break;
2890                 if (wkn == NULL)
2891                         panic("remove_from_journal: %p is not in journal", wk);
2892         }
2893 #endif
2894         /*
2895          * We emulate a TAILQ to save space in most structures which do not
2896          * require TAILQ semantics.  Here we must update the tail position
2897          * when removing the tail which is not the final entry. This works
2898          * only if the worklist linkage are at the beginning of the structure.
2899          */
2900         if (ump->softdep_journal_tail == wk)
2901                 ump->softdep_journal_tail =
2902                     (struct worklist *)wk->wk_list.le_prev;
2903         WORKLIST_REMOVE(wk);
2904         ump->softdep_on_journal -= 1;
2905 }
2906
2907 /*
2908  * Check for journal space as well as dependency limits so the prelink
2909  * code can throttle both journaled and non-journaled filesystems.
2910  * Threshold is 0 for low and 1 for min.
2911  */
2912 static int
2913 journal_space(ump, thresh)
2914         struct ufsmount *ump;
2915         int thresh;
2916 {
2917         struct jblocks *jblocks;
2918         int limit, avail;
2919
2920         jblocks = ump->softdep_jblocks;
2921         if (jblocks == NULL)
2922                 return (1);
2923         /*
2924          * We use a tighter restriction here to prevent request_cleanup()
2925          * running in threads from running into locks we currently hold.
2926          * We have to be over the limit and our filesystem has to be
2927          * responsible for more than our share of that usage.
2928          */
2929         limit = (max_softdeps / 10) * 9;
2930         if (dep_current[D_INODEDEP] > limit &&
2931             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2932                 return (0);
2933         if (thresh)
2934                 thresh = jblocks->jb_min;
2935         else
2936                 thresh = jblocks->jb_low;
2937         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2938         avail = jblocks->jb_free - avail;
2939
2940         return (avail > thresh);
2941 }
2942
2943 static void
2944 journal_suspend(ump)
2945         struct ufsmount *ump;
2946 {
2947         struct jblocks *jblocks;
2948         struct mount *mp;
2949
2950         mp = UFSTOVFS(ump);
2951         jblocks = ump->softdep_jblocks;
2952         MNT_ILOCK(mp);
2953         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2954                 stat_journal_min++;
2955                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2956                 mp->mnt_susp_owner = ump->softdep_flushtd;
2957         }
2958         jblocks->jb_suspended = 1;
2959         MNT_IUNLOCK(mp);
2960 }
2961
2962 static int
2963 journal_unsuspend(struct ufsmount *ump)
2964 {
2965         struct jblocks *jblocks;
2966         struct mount *mp;
2967
2968         mp = UFSTOVFS(ump);
2969         jblocks = ump->softdep_jblocks;
2970
2971         if (jblocks != NULL && jblocks->jb_suspended &&
2972             journal_space(ump, jblocks->jb_min)) {
2973                 jblocks->jb_suspended = 0;
2974                 FREE_LOCK(ump);
2975                 mp->mnt_susp_owner = curthread;
2976                 vfs_write_resume(mp, 0);
2977                 ACQUIRE_LOCK(ump);
2978                 return (1);
2979         }
2980         return (0);
2981 }
2982
2983 /*
2984  * Called before any allocation function to be certain that there is
2985  * sufficient space in the journal prior to creating any new records.
2986  * Since in the case of block allocation we may have multiple locked
2987  * buffers at the time of the actual allocation we can not block
2988  * when the journal records are created.  Doing so would create a deadlock
2989  * if any of these buffers needed to be flushed to reclaim space.  Instead
2990  * we require a sufficiently large amount of available space such that
2991  * each thread in the system could have passed this allocation check and
2992  * still have sufficient free space.  With 20% of a minimum journal size
2993  * of 1MB we have 6553 records available.
2994  */
2995 int
2996 softdep_prealloc(vp, waitok)
2997         struct vnode *vp;
2998         int waitok;
2999 {
3000         struct ufsmount *ump;
3001
3002         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3003             ("softdep_prealloc called on non-softdep filesystem"));
3004         /*
3005          * Nothing to do if we are not running journaled soft updates.
3006          * If we currently hold the snapshot lock, we must avoid
3007          * handling other resources that could cause deadlock.  Do not
3008          * touch quotas vnode since it is typically recursed with
3009          * other vnode locks held.
3010          */
3011         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3012             (vp->v_vflag & VV_SYSTEM) != 0)
3013                 return (0);
3014         ump = VFSTOUFS(vp->v_mount);
3015         ACQUIRE_LOCK(ump);
3016         if (journal_space(ump, 0)) {
3017                 FREE_LOCK(ump);
3018                 return (0);
3019         }
3020         stat_journal_low++;
3021         FREE_LOCK(ump);
3022         if (waitok == MNT_NOWAIT)
3023                 return (ENOSPC);
3024         /*
3025          * Attempt to sync this vnode once to flush any journal
3026          * work attached to it.
3027          */
3028         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3029                 ffs_syncvnode(vp, waitok, 0);
3030         ACQUIRE_LOCK(ump);
3031         process_removes(vp);
3032         process_truncates(vp);
3033         if (journal_space(ump, 0) == 0) {
3034                 softdep_speedup(ump);
3035                 if (journal_space(ump, 1) == 0)
3036                         journal_suspend(ump);
3037         }
3038         FREE_LOCK(ump);
3039
3040         return (0);
3041 }
3042
3043 /*
3044  * Before adjusting a link count on a vnode verify that we have sufficient
3045  * journal space.  If not, process operations that depend on the currently
3046  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3047  * and softdep flush threads can not acquire these locks to reclaim space.
3048  */
3049 static void
3050 softdep_prelink(dvp, vp)
3051         struct vnode *dvp;
3052         struct vnode *vp;
3053 {
3054         struct ufsmount *ump;
3055
3056         ump = VFSTOUFS(dvp->v_mount);
3057         LOCK_OWNED(ump);
3058         /*
3059          * Nothing to do if we have sufficient journal space.
3060          * If we currently hold the snapshot lock, we must avoid
3061          * handling other resources that could cause deadlock.
3062          */
3063         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3064                 return;
3065         stat_journal_low++;
3066         FREE_LOCK(ump);
3067         if (vp)
3068                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3069         ffs_syncvnode(dvp, MNT_WAIT, 0);
3070         ACQUIRE_LOCK(ump);
3071         /* Process vp before dvp as it may create .. removes. */
3072         if (vp) {
3073                 process_removes(vp);
3074                 process_truncates(vp);
3075         }
3076         process_removes(dvp);
3077         process_truncates(dvp);
3078         softdep_speedup(ump);
3079         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3080         if (journal_space(ump, 0) == 0) {
3081                 softdep_speedup(ump);
3082                 if (journal_space(ump, 1) == 0)
3083                         journal_suspend(ump);
3084         }
3085 }
3086
3087 static void
3088 jseg_write(ump, jseg, data)
3089         struct ufsmount *ump;
3090         struct jseg *jseg;
3091         uint8_t *data;
3092 {
3093         struct jsegrec *rec;
3094
3095         rec = (struct jsegrec *)data;
3096         rec->jsr_seq = jseg->js_seq;
3097         rec->jsr_oldest = jseg->js_oldseq;
3098         rec->jsr_cnt = jseg->js_cnt;
3099         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3100         rec->jsr_crc = 0;
3101         rec->jsr_time = ump->um_fs->fs_mtime;
3102 }
3103
3104 static inline void
3105 inoref_write(inoref, jseg, rec)
3106         struct inoref *inoref;
3107         struct jseg *jseg;
3108         struct jrefrec *rec;
3109 {
3110
3111         inoref->if_jsegdep->jd_seg = jseg;
3112         rec->jr_ino = inoref->if_ino;
3113         rec->jr_parent = inoref->if_parent;
3114         rec->jr_nlink = inoref->if_nlink;
3115         rec->jr_mode = inoref->if_mode;
3116         rec->jr_diroff = inoref->if_diroff;
3117 }
3118
3119 static void
3120 jaddref_write(jaddref, jseg, data)
3121         struct jaddref *jaddref;
3122         struct jseg *jseg;
3123         uint8_t *data;
3124 {
3125         struct jrefrec *rec;
3126
3127         rec = (struct jrefrec *)data;
3128         rec->jr_op = JOP_ADDREF;
3129         inoref_write(&jaddref->ja_ref, jseg, rec);
3130 }
3131
3132 static void
3133 jremref_write(jremref, jseg, data)
3134         struct jremref *jremref;
3135         struct jseg *jseg;
3136         uint8_t *data;
3137 {
3138         struct jrefrec *rec;
3139
3140         rec = (struct jrefrec *)data;
3141         rec->jr_op = JOP_REMREF;
3142         inoref_write(&jremref->jr_ref, jseg, rec);
3143 }
3144
3145 static void
3146 jmvref_write(jmvref, jseg, data)
3147         struct jmvref *jmvref;
3148         struct jseg *jseg;
3149         uint8_t *data;
3150 {
3151         struct jmvrec *rec;
3152
3153         rec = (struct jmvrec *)data;
3154         rec->jm_op = JOP_MVREF;
3155         rec->jm_ino = jmvref->jm_ino;
3156         rec->jm_parent = jmvref->jm_parent;
3157         rec->jm_oldoff = jmvref->jm_oldoff;
3158         rec->jm_newoff = jmvref->jm_newoff;
3159 }
3160
3161 static void
3162 jnewblk_write(jnewblk, jseg, data)
3163         struct jnewblk *jnewblk;
3164         struct jseg *jseg;
3165         uint8_t *data;
3166 {
3167         struct jblkrec *rec;
3168
3169         jnewblk->jn_jsegdep->jd_seg = jseg;
3170         rec = (struct jblkrec *)data;
3171         rec->jb_op = JOP_NEWBLK;
3172         rec->jb_ino = jnewblk->jn_ino;
3173         rec->jb_blkno = jnewblk->jn_blkno;
3174         rec->jb_lbn = jnewblk->jn_lbn;
3175         rec->jb_frags = jnewblk->jn_frags;
3176         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3177 }
3178
3179 static void
3180 jfreeblk_write(jfreeblk, jseg, data)
3181         struct jfreeblk *jfreeblk;
3182         struct jseg *jseg;
3183         uint8_t *data;
3184 {
3185         struct jblkrec *rec;
3186
3187         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3188         rec = (struct jblkrec *)data;
3189         rec->jb_op = JOP_FREEBLK;
3190         rec->jb_ino = jfreeblk->jf_ino;
3191         rec->jb_blkno = jfreeblk->jf_blkno;
3192         rec->jb_lbn = jfreeblk->jf_lbn;
3193         rec->jb_frags = jfreeblk->jf_frags;
3194         rec->jb_oldfrags = 0;
3195 }
3196
3197 static void
3198 jfreefrag_write(jfreefrag, jseg, data)
3199         struct jfreefrag *jfreefrag;
3200         struct jseg *jseg;
3201         uint8_t *data;
3202 {
3203         struct jblkrec *rec;
3204
3205         jfreefrag->fr_jsegdep->jd_seg = jseg;
3206         rec = (struct jblkrec *)data;
3207         rec->jb_op = JOP_FREEBLK;
3208         rec->jb_ino = jfreefrag->fr_ino;
3209         rec->jb_blkno = jfreefrag->fr_blkno;
3210         rec->jb_lbn = jfreefrag->fr_lbn;
3211         rec->jb_frags = jfreefrag->fr_frags;
3212         rec->jb_oldfrags = 0;
3213 }
3214
3215 static void
3216 jtrunc_write(jtrunc, jseg, data)
3217         struct jtrunc *jtrunc;
3218         struct jseg *jseg;
3219         uint8_t *data;
3220 {
3221         struct jtrncrec *rec;
3222
3223         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3224         rec = (struct jtrncrec *)data;
3225         rec->jt_op = JOP_TRUNC;
3226         rec->jt_ino = jtrunc->jt_ino;
3227         rec->jt_size = jtrunc->jt_size;
3228         rec->jt_extsize = jtrunc->jt_extsize;
3229 }
3230
3231 static void
3232 jfsync_write(jfsync, jseg, data)
3233         struct jfsync *jfsync;
3234         struct jseg *jseg;
3235         uint8_t *data;
3236 {
3237         struct jtrncrec *rec;
3238
3239         rec = (struct jtrncrec *)data;
3240         rec->jt_op = JOP_SYNC;
3241         rec->jt_ino = jfsync->jfs_ino;
3242         rec->jt_size = jfsync->jfs_size;
3243         rec->jt_extsize = jfsync->jfs_extsize;
3244 }
3245
3246 static void
3247 softdep_flushjournal(mp)
3248         struct mount *mp;
3249 {
3250         struct jblocks *jblocks;
3251         struct ufsmount *ump;
3252
3253         if (MOUNTEDSUJ(mp) == 0)
3254                 return;
3255         ump = VFSTOUFS(mp);
3256         jblocks = ump->softdep_jblocks;
3257         ACQUIRE_LOCK(ump);
3258         while (ump->softdep_on_journal) {
3259                 jblocks->jb_needseg = 1;
3260                 softdep_process_journal(mp, NULL, MNT_WAIT);
3261         }
3262         FREE_LOCK(ump);
3263 }
3264
3265 static void softdep_synchronize_completed(struct bio *);
3266 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3267
3268 static void
3269 softdep_synchronize_completed(bp)
3270         struct bio *bp;
3271 {
3272         struct jseg *oldest;
3273         struct jseg *jseg;
3274         struct ufsmount *ump;
3275
3276         /*
3277          * caller1 marks the last segment written before we issued the
3278          * synchronize cache.
3279          */
3280         jseg = bp->bio_caller1;
3281         if (jseg == NULL) {
3282                 g_destroy_bio(bp);
3283                 return;
3284         }
3285         ump = VFSTOUFS(jseg->js_list.wk_mp);
3286         ACQUIRE_LOCK(ump);
3287         oldest = NULL;
3288         /*
3289          * Mark all the journal entries waiting on the synchronize cache
3290          * as completed so they may continue on.
3291          */
3292         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3293                 jseg->js_state |= COMPLETE;
3294                 oldest = jseg;
3295                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3296         }
3297         /*
3298          * Restart deferred journal entry processing from the oldest
3299          * completed jseg.
3300          */
3301         if (oldest)
3302                 complete_jsegs(oldest);
3303
3304         FREE_LOCK(ump);
3305         g_destroy_bio(bp);
3306 }
3307
3308 /*
3309  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3310  * barriers.  The journal must be written prior to any blocks that depend
3311  * on it and the journal can not be released until the blocks have be
3312  * written.  This code handles both barriers simultaneously.
3313  */
3314 static void
3315 softdep_synchronize(bp, ump, caller1)
3316         struct bio *bp;
3317         struct ufsmount *ump;
3318         void *caller1;
3319 {
3320
3321         bp->bio_cmd = BIO_FLUSH;
3322         bp->bio_flags |= BIO_ORDERED;
3323         bp->bio_data = NULL;
3324         bp->bio_offset = ump->um_cp->provider->mediasize;
3325         bp->bio_length = 0;
3326         bp->bio_done = softdep_synchronize_completed;
3327         bp->bio_caller1 = caller1;
3328         g_io_request(bp,
3329             (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3330 }
3331
3332 /*
3333  * Flush some journal records to disk.
3334  */
3335 static void
3336 softdep_process_journal(mp, needwk, flags)
3337         struct mount *mp;
3338         struct worklist *needwk;
3339         int flags;
3340 {
3341         struct jblocks *jblocks;
3342         struct ufsmount *ump;
3343         struct worklist *wk;
3344         struct jseg *jseg;
3345         struct buf *bp;
3346         struct bio *bio;
3347         uint8_t *data;
3348         struct fs *fs;
3349         int shouldflush;
3350         int segwritten;
3351         int jrecmin;    /* Minimum records per block. */
3352         int jrecmax;    /* Maximum records per block. */
3353         int size;
3354         int cnt;
3355         int off;
3356         int devbsize;
3357
3358         if (MOUNTEDSUJ(mp) == 0)
3359                 return;
3360         shouldflush = softdep_flushcache;
3361         bio = NULL;
3362         jseg = NULL;
3363         ump = VFSTOUFS(mp);
3364         LOCK_OWNED(ump);
3365         fs = ump->um_fs;
3366         jblocks = ump->softdep_jblocks;
3367         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3368         /*
3369          * We write anywhere between a disk block and fs block.  The upper
3370          * bound is picked to prevent buffer cache fragmentation and limit
3371          * processing time per I/O.
3372          */
3373         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3374         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3375         segwritten = 0;
3376         for (;;) {
3377                 cnt = ump->softdep_on_journal;
3378                 /*
3379                  * Criteria for writing a segment:
3380                  * 1) We have a full block.
3381                  * 2) We're called from jwait() and haven't found the
3382                  *    journal item yet.
3383                  * 3) Always write if needseg is set.
3384                  * 4) If we are called from process_worklist and have
3385                  *    not yet written anything we write a partial block
3386                  *    to enforce a 1 second maximum latency on journal
3387                  *    entries.
3388                  */
3389                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3390                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3391                         break;
3392                 cnt++;
3393                 /*
3394                  * Verify some free journal space.  softdep_prealloc() should
3395                  * guarantee that we don't run out so this is indicative of
3396                  * a problem with the flow control.  Try to recover
3397                  * gracefully in any event.
3398                  */
3399                 while (jblocks->jb_free == 0) {
3400                         if (flags != MNT_WAIT)
3401                                 break;
3402                         printf("softdep: Out of journal space!\n");
3403                         softdep_speedup(ump);
3404                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3405                 }
3406                 FREE_LOCK(ump);
3407                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3408                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3409                 LIST_INIT(&jseg->js_entries);
3410                 LIST_INIT(&jseg->js_indirs);
3411                 jseg->js_state = ATTACHED;
3412                 if (shouldflush == 0)
3413                         jseg->js_state |= COMPLETE;
3414                 else if (bio == NULL)
3415                         bio = g_alloc_bio();
3416                 jseg->js_jblocks = jblocks;
3417                 bp = geteblk(fs->fs_bsize, 0);
3418                 ACQUIRE_LOCK(ump);
3419                 /*
3420                  * If there was a race while we were allocating the block
3421                  * and jseg the entry we care about was likely written.
3422                  * We bail out in both the WAIT and NOWAIT case and assume
3423                  * the caller will loop if the entry it cares about is
3424                  * not written.
3425                  */
3426                 cnt = ump->softdep_on_journal;
3427                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3428                         bp->b_flags |= B_INVAL | B_NOCACHE;
3429                         WORKITEM_FREE(jseg, D_JSEG);
3430                         FREE_LOCK(ump);
3431                         brelse(bp);
3432                         ACQUIRE_LOCK(ump);
3433                         break;
3434                 }
3435                 /*
3436                  * Calculate the disk block size required for the available
3437                  * records rounded to the min size.
3438                  */
3439                 if (cnt == 0)
3440                         size = devbsize;
3441                 else if (cnt < jrecmax)
3442                         size = howmany(cnt, jrecmin) * devbsize;
3443                 else
3444                         size = fs->fs_bsize;
3445                 /*
3446                  * Allocate a disk block for this journal data and account
3447                  * for truncation of the requested size if enough contiguous
3448                  * space was not available.
3449                  */
3450                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3451                 bp->b_lblkno = bp->b_blkno;
3452                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3453                 bp->b_bcount = size;
3454                 bp->b_flags &= ~B_INVAL;
3455                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3456                 /*
3457                  * Initialize our jseg with cnt records.  Assign the next
3458                  * sequence number to it and link it in-order.
3459                  */
3460                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3461                 jseg->js_buf = bp;
3462                 jseg->js_cnt = cnt;
3463                 jseg->js_refs = cnt + 1;        /* Self ref. */
3464                 jseg->js_size = size;
3465                 jseg->js_seq = jblocks->jb_nextseq++;
3466                 if (jblocks->jb_oldestseg == NULL)
3467                         jblocks->jb_oldestseg = jseg;
3468                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3469                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3470                 if (jblocks->jb_writeseg == NULL)
3471                         jblocks->jb_writeseg = jseg;
3472                 /*
3473                  * Start filling in records from the pending list.
3474                  */
3475                 data = bp->b_data;
3476                 off = 0;
3477
3478                 /*
3479                  * Always put a header on the first block.
3480                  * XXX As with below, there might not be a chance to get
3481                  * into the loop.  Ensure that something valid is written.
3482                  */
3483                 jseg_write(ump, jseg, data);
3484                 off += JREC_SIZE;
3485                 data = bp->b_data + off;
3486
3487                 /*
3488                  * XXX Something is wrong here.  There's no work to do,
3489                  * but we need to perform and I/O and allow it to complete
3490                  * anyways.
3491                  */
3492                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3493                         stat_emptyjblocks++;
3494
3495                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3496                     != NULL) {
3497                         if (cnt == 0)
3498                                 break;
3499                         /* Place a segment header on every device block. */
3500                         if ((off % devbsize) == 0) {
3501                                 jseg_write(ump, jseg, data);
3502                                 off += JREC_SIZE;
3503                                 data = bp->b_data + off;
3504                         }
3505                         if (wk == needwk)
3506                                 needwk = NULL;
3507                         remove_from_journal(wk);
3508                         wk->wk_state |= INPROGRESS;
3509                         WORKLIST_INSERT(&jseg->js_entries, wk);
3510                         switch (wk->wk_type) {
3511                         case D_JADDREF:
3512                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3513                                 break;
3514                         case D_JREMREF:
3515                                 jremref_write(WK_JREMREF(wk), jseg, data);
3516                                 break;
3517                         case D_JMVREF:
3518                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3519                                 break;
3520                         case D_JNEWBLK:
3521                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3522                                 break;
3523                         case D_JFREEBLK:
3524                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3525                                 break;
3526                         case D_JFREEFRAG:
3527                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3528                                 break;
3529                         case D_JTRUNC:
3530                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3531                                 break;
3532                         case D_JFSYNC:
3533                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3534                                 break;
3535                         default:
3536                                 panic("process_journal: Unknown type %s",
3537                                     TYPENAME(wk->wk_type));
3538                                 /* NOTREACHED */
3539                         }
3540                         off += JREC_SIZE;
3541                         data = bp->b_data + off;
3542                         cnt--;
3543                 }
3544
3545                 /* Clear any remaining space so we don't leak kernel data */
3546                 if (size > off)
3547                         bzero(data, size - off);
3548
3549                 /*
3550                  * Write this one buffer and continue.
3551                  */
3552                 segwritten = 1;
3553                 jblocks->jb_needseg = 0;
3554                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3555                 FREE_LOCK(ump);
3556                 pbgetvp(ump->um_devvp, bp);
3557                 /*
3558                  * We only do the blocking wait once we find the journal
3559                  * entry we're looking for.
3560                  */
3561                 if (needwk == NULL && flags == MNT_WAIT)
3562                         bwrite(bp);
3563                 else
3564                         bawrite(bp);
3565                 ACQUIRE_LOCK(ump);
3566         }
3567         /*
3568          * If we wrote a segment issue a synchronize cache so the journal
3569          * is reflected on disk before the data is written.  Since reclaiming
3570          * journal space also requires writing a journal record this
3571          * process also enforces a barrier before reclamation.
3572          */
3573         if (segwritten && shouldflush) {
3574                 softdep_synchronize(bio, ump, 
3575                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3576         } else if (bio)
3577                 g_destroy_bio(bio);
3578         /*
3579          * If we've suspended the filesystem because we ran out of journal
3580          * space either try to sync it here to make some progress or
3581          * unsuspend it if we already have.
3582          */
3583         if (flags == 0 && jblocks->jb_suspended) {
3584                 if (journal_unsuspend(ump))
3585                         return;
3586                 FREE_LOCK(ump);
3587                 VFS_SYNC(mp, MNT_NOWAIT);
3588                 ffs_sbupdate(ump, MNT_WAIT, 0);
3589                 ACQUIRE_LOCK(ump);
3590         }
3591 }
3592
3593 /*
3594  * Complete a jseg, allowing all dependencies awaiting journal writes
3595  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3596  * structures so that the journal segment can be freed to reclaim space.
3597  */
3598 static void
3599 complete_jseg(jseg)
3600         struct jseg *jseg;
3601 {
3602         struct worklist *wk;
3603         struct jmvref *jmvref;
3604 #ifdef INVARIANTS
3605         int i = 0;
3606 #endif
3607
3608         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3609                 WORKLIST_REMOVE(wk);
3610                 wk->wk_state &= ~INPROGRESS;
3611                 wk->wk_state |= COMPLETE;
3612                 KASSERT(i++ < jseg->js_cnt,
3613                     ("handle_written_jseg: overflow %d >= %d",
3614                     i - 1, jseg->js_cnt));
3615                 switch (wk->wk_type) {
3616                 case D_JADDREF:
3617                         handle_written_jaddref(WK_JADDREF(wk));
3618                         break;
3619                 case D_JREMREF:
3620                         handle_written_jremref(WK_JREMREF(wk));
3621                         break;
3622                 case D_JMVREF:
3623                         rele_jseg(jseg);        /* No jsegdep. */
3624                         jmvref = WK_JMVREF(wk);
3625                         LIST_REMOVE(jmvref, jm_deps);
3626                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3627                                 free_pagedep(jmvref->jm_pagedep);
3628                         WORKITEM_FREE(jmvref, D_JMVREF);
3629                         break;
3630                 case D_JNEWBLK:
3631                         handle_written_jnewblk(WK_JNEWBLK(wk));
3632                         break;
3633                 case D_JFREEBLK:
3634                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3635                         break;
3636                 case D_JTRUNC:
3637                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3638                         break;
3639                 case D_JFSYNC:
3640                         rele_jseg(jseg);        /* No jsegdep. */
3641                         WORKITEM_FREE(wk, D_JFSYNC);
3642                         break;
3643                 case D_JFREEFRAG:
3644                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3645                         break;
3646                 default:
3647                         panic("handle_written_jseg: Unknown type %s",
3648                             TYPENAME(wk->wk_type));
3649                         /* NOTREACHED */
3650                 }
3651         }
3652         /* Release the self reference so the structure may be freed. */
3653         rele_jseg(jseg);
3654 }
3655
3656 /*
3657  * Determine which jsegs are ready for completion processing.  Waits for
3658  * synchronize cache to complete as well as forcing in-order completion
3659  * of journal entries.
3660  */
3661 static void
3662 complete_jsegs(jseg)
3663         struct jseg *jseg;
3664 {
3665         struct jblocks *jblocks;
3666         struct jseg *jsegn;
3667
3668         jblocks = jseg->js_jblocks;
3669         /*
3670          * Don't allow out of order completions.  If this isn't the first
3671          * block wait for it to write before we're done.
3672          */
3673         if (jseg != jblocks->jb_writeseg)
3674                 return;
3675         /* Iterate through available jsegs processing their entries. */
3676         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3677                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3678                 jsegn = TAILQ_NEXT(jseg, js_next);
3679                 complete_jseg(jseg);
3680                 jseg = jsegn;
3681         }
3682         jblocks->jb_writeseg = jseg;
3683         /*
3684          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3685          */
3686         free_jsegs(jblocks);
3687 }
3688
3689 /*
3690  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3691  * the final completions.
3692  */
3693 static void
3694 handle_written_jseg(jseg, bp)
3695         struct jseg *jseg;
3696         struct buf *bp;
3697 {
3698
3699         if (jseg->js_refs == 0)
3700                 panic("handle_written_jseg: No self-reference on %p", jseg);
3701         jseg->js_state |= DEPCOMPLETE;
3702         /*
3703          * We'll never need this buffer again, set flags so it will be
3704          * discarded.
3705          */
3706         bp->b_flags |= B_INVAL | B_NOCACHE;
3707         pbrelvp(bp);
3708         complete_jsegs(jseg);
3709 }
3710
3711 static inline struct jsegdep *
3712 inoref_jseg(inoref)
3713         struct inoref *inoref;
3714 {
3715         struct jsegdep *jsegdep;
3716
3717         jsegdep = inoref->if_jsegdep;
3718         inoref->if_jsegdep = NULL;
3719
3720         return (jsegdep);
3721 }
3722
3723 /*
3724  * Called once a jremref has made it to stable store.  The jremref is marked
3725  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3726  * for the jremref to complete will be awoken by free_jremref.
3727  */
3728 static void
3729 handle_written_jremref(jremref)
3730         struct jremref *jremref;
3731 {
3732         struct inodedep *inodedep;
3733         struct jsegdep *jsegdep;
3734         struct dirrem *dirrem;
3735
3736         /* Grab the jsegdep. */
3737         jsegdep = inoref_jseg(&jremref->jr_ref);
3738         /*
3739          * Remove us from the inoref list.
3740          */
3741         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3742             0, &inodedep) == 0)
3743                 panic("handle_written_jremref: Lost inodedep");
3744         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3745         /*
3746          * Complete the dirrem.
3747          */
3748         dirrem = jremref->jr_dirrem;
3749         jremref->jr_dirrem = NULL;
3750         LIST_REMOVE(jremref, jr_deps);
3751         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3752         jwork_insert(&dirrem->dm_jwork, jsegdep);
3753         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3754             (dirrem->dm_state & COMPLETE) != 0)
3755                 add_to_worklist(&dirrem->dm_list, 0);
3756         free_jremref(jremref);
3757 }
3758
3759 /*
3760  * Called once a jaddref has made it to stable store.  The dependency is
3761  * marked complete and any dependent structures are added to the inode
3762  * bufwait list to be completed as soon as it is written.  If a bitmap write
3763  * depends on this entry we move the inode into the inodedephd of the
3764  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3765  */
3766 static void
3767 handle_written_jaddref(jaddref)
3768         struct jaddref *jaddref;
3769 {
3770         struct jsegdep *jsegdep;
3771         struct inodedep *inodedep;
3772         struct diradd *diradd;
3773         struct mkdir *mkdir;
3774
3775         /* Grab the jsegdep. */
3776         jsegdep = inoref_jseg(&jaddref->ja_ref);
3777         mkdir = NULL;
3778         diradd = NULL;
3779         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3780             0, &inodedep) == 0)
3781                 panic("handle_written_jaddref: Lost inodedep.");
3782         if (jaddref->ja_diradd == NULL)
3783                 panic("handle_written_jaddref: No dependency");
3784         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3785                 diradd = jaddref->ja_diradd;
3786                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3787         } else if (jaddref->ja_state & MKDIR_PARENT) {
3788                 mkdir = jaddref->ja_mkdir;
3789                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3790         } else if (jaddref->ja_state & MKDIR_BODY)
3791                 mkdir = jaddref->ja_mkdir;
3792         else
3793                 panic("handle_written_jaddref: Unknown dependency %p",
3794                     jaddref->ja_diradd);
3795         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3796         /*
3797          * Remove us from the inode list.
3798          */
3799         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3800         /*
3801          * The mkdir may be waiting on the jaddref to clear before freeing.
3802          */
3803         if (mkdir) {
3804                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3805                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3806                     TYPENAME(mkdir->md_list.wk_type)));
3807                 mkdir->md_jaddref = NULL;
3808                 diradd = mkdir->md_diradd;
3809                 mkdir->md_state |= DEPCOMPLETE;
3810                 complete_mkdir(mkdir);
3811         }
3812         jwork_insert(&diradd->da_jwork, jsegdep);
3813         if (jaddref->ja_state & NEWBLOCK) {
3814                 inodedep->id_state |= ONDEPLIST;
3815                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3816                     inodedep, id_deps);
3817         }
3818         free_jaddref(jaddref);
3819 }
3820
3821 /*
3822  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3823  * is placed in the bmsafemap to await notification of a written bitmap.  If
3824  * the operation was canceled we add the segdep to the appropriate
3825  * dependency to free the journal space once the canceling operation
3826  * completes.
3827  */
3828 static void
3829 handle_written_jnewblk(jnewblk)
3830         struct jnewblk *jnewblk;
3831 {
3832         struct bmsafemap *bmsafemap;
3833         struct freefrag *freefrag;
3834         struct freework *freework;
3835         struct jsegdep *jsegdep;
3836         struct newblk *newblk;
3837
3838         /* Grab the jsegdep. */
3839         jsegdep = jnewblk->jn_jsegdep;
3840         jnewblk->jn_jsegdep = NULL;
3841         if (jnewblk->jn_dep == NULL) 
3842                 panic("handle_written_jnewblk: No dependency for the segdep.");
3843         switch (jnewblk->jn_dep->wk_type) {
3844         case D_NEWBLK:
3845         case D_ALLOCDIRECT:
3846         case D_ALLOCINDIR:
3847                 /*
3848                  * Add the written block to the bmsafemap so it can
3849                  * be notified when the bitmap is on disk.
3850                  */
3851                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3852                 newblk->nb_jnewblk = NULL;
3853                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3854                         bmsafemap = newblk->nb_bmsafemap;
3855                         newblk->nb_state |= ONDEPLIST;
3856                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3857                             nb_deps);
3858                 }
3859                 jwork_insert(&newblk->nb_jwork, jsegdep);
3860                 break;
3861         case D_FREEFRAG:
3862                 /*
3863                  * A newblock being removed by a freefrag when replaced by
3864                  * frag extension.
3865                  */
3866                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3867                 freefrag->ff_jdep = NULL;
3868                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3869                 break;
3870         case D_FREEWORK:
3871                 /*
3872                  * A direct block was removed by truncate.
3873                  */
3874                 freework = WK_FREEWORK(jnewblk->jn_dep);
3875                 freework->fw_jnewblk = NULL;
3876                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3877                 break;
3878         default:
3879                 panic("handle_written_jnewblk: Unknown type %d.",
3880                     jnewblk->jn_dep->wk_type);
3881         }
3882         jnewblk->jn_dep = NULL;
3883         free_jnewblk(jnewblk);
3884 }
3885
3886 /*
3887  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3888  * an in-flight allocation that has not yet been committed.  Divorce us
3889  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3890  * to the worklist.
3891  */
3892 static void
3893 cancel_jfreefrag(jfreefrag)
3894         struct jfreefrag *jfreefrag;
3895 {
3896         struct freefrag *freefrag;
3897
3898         if (jfreefrag->fr_jsegdep) {
3899                 free_jsegdep(jfreefrag->fr_jsegdep);
3900                 jfreefrag->fr_jsegdep = NULL;
3901         }
3902         freefrag = jfreefrag->fr_freefrag;
3903         jfreefrag->fr_freefrag = NULL;
3904         free_jfreefrag(jfreefrag);
3905         freefrag->ff_state |= DEPCOMPLETE;
3906         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3907 }
3908
3909 /*
3910  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3911  */
3912 static void
3913 free_jfreefrag(jfreefrag)
3914         struct jfreefrag *jfreefrag;
3915 {
3916
3917         if (jfreefrag->fr_state & INPROGRESS)
3918                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3919         else if (jfreefrag->fr_state & ONWORKLIST)
3920                 remove_from_journal(&jfreefrag->fr_list);
3921         if (jfreefrag->fr_freefrag != NULL)
3922                 panic("free_jfreefrag:  Still attached to a freefrag.");
3923         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3924 }
3925
3926 /*
3927  * Called when the journal write for a jfreefrag completes.  The parent
3928  * freefrag is added to the worklist if this completes its dependencies.
3929  */
3930 static void
3931 handle_written_jfreefrag(jfreefrag)
3932         struct jfreefrag *jfreefrag;
3933 {
3934         struct jsegdep *jsegdep;
3935         struct freefrag *freefrag;
3936
3937         /* Grab the jsegdep. */
3938         jsegdep = jfreefrag->fr_jsegdep;
3939         jfreefrag->fr_jsegdep = NULL;
3940         freefrag = jfreefrag->fr_freefrag;
3941         if (freefrag == NULL)
3942                 panic("handle_written_jfreefrag: No freefrag.");
3943         freefrag->ff_state |= DEPCOMPLETE;
3944         freefrag->ff_jdep = NULL;
3945         jwork_insert(&freefrag->ff_jwork, jsegdep);
3946         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3947                 add_to_worklist(&freefrag->ff_list, 0);
3948         jfreefrag->fr_freefrag = NULL;
3949         free_jfreefrag(jfreefrag);
3950 }
3951
3952 /*
3953  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3954  * is removed from the freeblks list of pending journal writes and the
3955  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3956  * have been reclaimed.
3957  */
3958 static void
3959 handle_written_jblkdep(jblkdep)
3960         struct jblkdep *jblkdep;
3961 {
3962         struct freeblks *freeblks;
3963         struct jsegdep *jsegdep;
3964
3965         /* Grab the jsegdep. */
3966         jsegdep = jblkdep->jb_jsegdep;
3967         jblkdep->jb_jsegdep = NULL;
3968         freeblks = jblkdep->jb_freeblks;
3969         LIST_REMOVE(jblkdep, jb_deps);
3970         jwork_insert(&freeblks->fb_jwork, jsegdep);
3971         /*
3972          * If the freeblks is all journaled, we can add it to the worklist.
3973          */
3974         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3975             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3976                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3977
3978         free_jblkdep(jblkdep);
3979 }
3980
3981 static struct jsegdep *
3982 newjsegdep(struct worklist *wk)
3983 {
3984         struct jsegdep *jsegdep;
3985
3986         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3987         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3988         jsegdep->jd_seg = NULL;
3989
3990         return (jsegdep);
3991 }
3992
3993 static struct jmvref *
3994 newjmvref(dp, ino, oldoff, newoff)
3995         struct inode *dp;
3996         ino_t ino;
3997         off_t oldoff;
3998         off_t newoff;
3999 {
4000         struct jmvref *jmvref;
4001
4002         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4003         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4004         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4005         jmvref->jm_parent = dp->i_number;
4006         jmvref->jm_ino = ino;
4007         jmvref->jm_oldoff = oldoff;
4008         jmvref->jm_newoff = newoff;
4009
4010         return (jmvref);
4011 }
4012
4013 /*
4014  * Allocate a new jremref that tracks the removal of ip from dp with the
4015  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4016  * DEPCOMPLETE as we have all the information required for the journal write
4017  * and the directory has already been removed from the buffer.  The caller
4018  * is responsible for linking the jremref into the pagedep and adding it
4019  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4020  * a DOTDOT addition so handle_workitem_remove() can properly assign
4021  * the jsegdep when we're done.
4022  */
4023 static struct jremref *
4024 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4025     off_t diroff, nlink_t nlink)
4026 {
4027         struct jremref *jremref;
4028
4029         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4030         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4031         jremref->jr_state = ATTACHED;
4032         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4033            nlink, ip->i_mode);
4034         jremref->jr_dirrem = dirrem;
4035
4036         return (jremref);
4037 }
4038
4039 static inline void
4040 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4041     nlink_t nlink, uint16_t mode)
4042 {
4043
4044         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4045         inoref->if_diroff = diroff;
4046         inoref->if_ino = ino;
4047         inoref->if_parent = parent;
4048         inoref->if_nlink = nlink;
4049         inoref->if_mode = mode;
4050 }
4051
4052 /*
4053  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4054  * directory offset may not be known until later.  The caller is responsible
4055  * adding the entry to the journal when this information is available.  nlink
4056  * should be the link count prior to the addition and mode is only required
4057  * to have the correct FMT.
4058  */
4059 static struct jaddref *
4060 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4061     uint16_t mode)
4062 {
4063         struct jaddref *jaddref;
4064
4065         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4066         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4067         jaddref->ja_state = ATTACHED;
4068         jaddref->ja_mkdir = NULL;
4069         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4070
4071         return (jaddref);
4072 }
4073
4074 /*
4075  * Create a new free dependency for a freework.  The caller is responsible
4076  * for adjusting the reference count when it has the lock held.  The freedep
4077  * will track an outstanding bitmap write that will ultimately clear the
4078  * freework to continue.
4079  */
4080 static struct freedep *
4081 newfreedep(struct freework *freework)
4082 {
4083         struct freedep *freedep;
4084
4085         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4086         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4087         freedep->fd_freework = freework;
4088
4089         return (freedep);
4090 }
4091
4092 /*
4093  * Free a freedep structure once the buffer it is linked to is written.  If
4094  * this is the last reference to the freework schedule it for completion.
4095  */
4096 static void
4097 free_freedep(freedep)
4098         struct freedep *freedep;
4099 {
4100         struct freework *freework;
4101
4102         freework = freedep->fd_freework;
4103         freework->fw_freeblks->fb_cgwait--;
4104         if (--freework->fw_ref == 0)
4105                 freework_enqueue(freework);
4106         WORKITEM_FREE(freedep, D_FREEDEP);
4107 }
4108
4109 /*
4110  * Allocate a new freework structure that may be a level in an indirect
4111  * when parent is not NULL or a top level block when it is.  The top level
4112  * freework structures are allocated without the per-filesystem lock held
4113  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4114  */
4115 static struct freework *
4116 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4117         struct ufsmount *ump;
4118         struct freeblks *freeblks;
4119         struct freework *parent;
4120         ufs_lbn_t lbn;
4121         ufs2_daddr_t nb;
4122         int frags;
4123         int off;
4124         int journal;
4125 {
4126         struct freework *freework;
4127
4128         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4129         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4130         freework->fw_state = ATTACHED;
4131         freework->fw_jnewblk = NULL;
4132         freework->fw_freeblks = freeblks;
4133         freework->fw_parent = parent;
4134         freework->fw_lbn = lbn;
4135         freework->fw_blkno = nb;
4136         freework->fw_frags = frags;
4137         freework->fw_indir = NULL;
4138         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4139             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4140         freework->fw_start = freework->fw_off = off;
4141         if (journal)
4142                 newjfreeblk(freeblks, lbn, nb, frags);
4143         if (parent == NULL) {
4144                 ACQUIRE_LOCK(ump);
4145                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4146                 freeblks->fb_ref++;
4147                 FREE_LOCK(ump);
4148         }
4149
4150         return (freework);
4151 }
4152
4153 /*
4154  * Eliminate a jfreeblk for a block that does not need journaling.
4155  */
4156 static void
4157 cancel_jfreeblk(freeblks, blkno)
4158         struct freeblks *freeblks;
4159         ufs2_daddr_t blkno;
4160 {
4161         struct jfreeblk *jfreeblk;
4162         struct jblkdep *jblkdep;
4163
4164         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4165                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4166                         continue;
4167                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4168                 if (jfreeblk->jf_blkno == blkno)
4169                         break;
4170         }
4171         if (jblkdep == NULL)
4172                 return;
4173         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4174         free_jsegdep(jblkdep->jb_jsegdep);
4175         LIST_REMOVE(jblkdep, jb_deps);
4176         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4177 }
4178
4179 /*
4180  * Allocate a new jfreeblk to journal top level block pointer when truncating
4181  * a file.  The caller must add this to the worklist when the per-filesystem
4182  * lock is held.
4183  */
4184 static struct jfreeblk *
4185 newjfreeblk(freeblks, lbn, blkno, frags)
4186         struct freeblks *freeblks;
4187         ufs_lbn_t lbn;
4188         ufs2_daddr_t blkno;
4189         int frags;
4190 {
4191         struct jfreeblk *jfreeblk;
4192
4193         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4194         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4195             freeblks->fb_list.wk_mp);
4196         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4197         jfreeblk->jf_dep.jb_freeblks = freeblks;
4198         jfreeblk->jf_ino = freeblks->fb_inum;
4199         jfreeblk->jf_lbn = lbn;
4200         jfreeblk->jf_blkno = blkno;
4201         jfreeblk->jf_frags = frags;
4202         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4203
4204         return (jfreeblk);
4205 }
4206
4207 /*
4208  * The journal is only prepared to handle full-size block numbers, so we
4209  * have to adjust the record to reflect the change to a full-size block.
4210  * For example, suppose we have a block made up of fragments 8-15 and
4211  * want to free its last two fragments. We are given a request that says:
4212  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4213  * where frags are the number of fragments to free and oldfrags are the
4214  * number of fragments to keep. To block align it, we have to change it to
4215  * have a valid full-size blkno, so it becomes:
4216  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4217  */
4218 static void
4219 adjust_newfreework(freeblks, frag_offset)
4220         struct freeblks *freeblks;
4221         int frag_offset;
4222 {
4223         struct jfreeblk *jfreeblk;
4224
4225         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4226             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4227             ("adjust_newfreework: Missing freeblks dependency"));
4228
4229         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4230         jfreeblk->jf_blkno -= frag_offset;
4231         jfreeblk->jf_frags += frag_offset;
4232 }
4233
4234 /*
4235  * Allocate a new jtrunc to track a partial truncation.
4236  */
4237 static struct jtrunc *
4238 newjtrunc(freeblks, size, extsize)
4239         struct freeblks *freeblks;
4240         off_t size;
4241         int extsize;
4242 {
4243         struct jtrunc *jtrunc;
4244
4245         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4246         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4247             freeblks->fb_list.wk_mp);
4248         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4249         jtrunc->jt_dep.jb_freeblks = freeblks;
4250         jtrunc->jt_ino = freeblks->fb_inum;
4251         jtrunc->jt_size = size;
4252         jtrunc->jt_extsize = extsize;
4253         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4254
4255         return (jtrunc);
4256 }
4257
4258 /*
4259  * If we're canceling a new bitmap we have to search for another ref
4260  * to move into the bmsafemap dep.  This might be better expressed
4261  * with another structure.
4262  */
4263 static void
4264 move_newblock_dep(jaddref, inodedep)
4265         struct jaddref *jaddref;
4266         struct inodedep *inodedep;
4267 {
4268         struct inoref *inoref;
4269         struct jaddref *jaddrefn;
4270
4271         jaddrefn = NULL;
4272         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4273             inoref = TAILQ_NEXT(inoref, if_deps)) {
4274                 if ((jaddref->ja_state & NEWBLOCK) &&
4275                     inoref->if_list.wk_type == D_JADDREF) {
4276                         jaddrefn = (struct jaddref *)inoref;
4277                         break;
4278                 }
4279         }
4280         if (jaddrefn == NULL)
4281                 return;
4282         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4283         jaddrefn->ja_state |= jaddref->ja_state &
4284             (ATTACHED | UNDONE | NEWBLOCK);
4285         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4286         jaddref->ja_state |= ATTACHED;
4287         LIST_REMOVE(jaddref, ja_bmdeps);
4288         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4289             ja_bmdeps);
4290 }
4291
4292 /*
4293  * Cancel a jaddref either before it has been written or while it is being
4294  * written.  This happens when a link is removed before the add reaches
4295  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4296  * and inode to prevent the link count or bitmap from reaching the disk
4297  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4298  * required.
4299  *
4300  * Returns 1 if the canceled addref requires journaling of the remove and
4301  * 0 otherwise.
4302  */
4303 static int
4304 cancel_jaddref(jaddref, inodedep, wkhd)
4305         struct jaddref *jaddref;
4306         struct inodedep *inodedep;
4307         struct workhead *wkhd;
4308 {
4309         struct inoref *inoref;
4310         struct jsegdep *jsegdep;
4311         int needsj;
4312
4313         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4314             ("cancel_jaddref: Canceling complete jaddref"));
4315         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4316                 needsj = 1;
4317         else
4318                 needsj = 0;
4319         if (inodedep == NULL)
4320                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4321                     0, &inodedep) == 0)
4322                         panic("cancel_jaddref: Lost inodedep");
4323         /*
4324          * We must adjust the nlink of any reference operation that follows
4325          * us so that it is consistent with the in-memory reference.  This
4326          * ensures that inode nlink rollbacks always have the correct link.
4327          */
4328         if (needsj == 0) {
4329                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4330                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4331                         if (inoref->if_state & GOINGAWAY)
4332                                 break;
4333                         inoref->if_nlink--;
4334                 }
4335         }
4336         jsegdep = inoref_jseg(&jaddref->ja_ref);
4337         if (jaddref->ja_state & NEWBLOCK)
4338                 move_newblock_dep(jaddref, inodedep);
4339         wake_worklist(&jaddref->ja_list);
4340         jaddref->ja_mkdir = NULL;
4341         if (jaddref->ja_state & INPROGRESS) {
4342                 jaddref->ja_state &= ~INPROGRESS;
4343                 WORKLIST_REMOVE(&jaddref->ja_list);
4344                 jwork_insert(wkhd, jsegdep);
4345         } else {
4346                 free_jsegdep(jsegdep);
4347                 if (jaddref->ja_state & DEPCOMPLETE)
4348                         remove_from_journal(&jaddref->ja_list);
4349         }
4350         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4351         /*
4352          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4353          * can arrange for them to be freed with the bitmap.  Otherwise we
4354          * no longer need this addref attached to the inoreflst and it
4355          * will incorrectly adjust nlink if we leave it.
4356          */
4357         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4358                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4359                     if_deps);
4360                 jaddref->ja_state |= COMPLETE;
4361                 free_jaddref(jaddref);
4362                 return (needsj);
4363         }
4364         /*
4365          * Leave the head of the list for jsegdeps for fast merging.
4366          */
4367         if (LIST_FIRST(wkhd) != NULL) {
4368                 jaddref->ja_state |= ONWORKLIST;
4369                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4370         } else
4371                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4372
4373         return (needsj);
4374 }
4375
4376 /* 
4377  * Attempt to free a jaddref structure when some work completes.  This
4378  * should only succeed once the entry is written and all dependencies have
4379  * been notified.
4380  */
4381 static void
4382 free_jaddref(jaddref)
4383         struct jaddref *jaddref;
4384 {
4385
4386         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4387                 return;
4388         if (jaddref->ja_ref.if_jsegdep)
4389                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4390                     jaddref, jaddref->ja_state);
4391         if (jaddref->ja_state & NEWBLOCK)
4392                 LIST_REMOVE(jaddref, ja_bmdeps);
4393         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4394                 panic("free_jaddref: Bad state %p(0x%X)",
4395                     jaddref, jaddref->ja_state);
4396         if (jaddref->ja_mkdir != NULL)
4397                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4398         WORKITEM_FREE(jaddref, D_JADDREF);
4399 }
4400
4401 /*
4402  * Free a jremref structure once it has been written or discarded.
4403  */
4404 static void
4405 free_jremref(jremref)
4406         struct jremref *jremref;
4407 {
4408
4409         if (jremref->jr_ref.if_jsegdep)
4410                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4411         if (jremref->jr_state & INPROGRESS)
4412                 panic("free_jremref: IO still pending");
4413         WORKITEM_FREE(jremref, D_JREMREF);
4414 }
4415
4416 /*
4417  * Free a jnewblk structure.
4418  */
4419 static void
4420 free_jnewblk(jnewblk)
4421         struct jnewblk *jnewblk;
4422 {
4423
4424         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4425                 return;
4426         LIST_REMOVE(jnewblk, jn_deps);
4427         if (jnewblk->jn_dep != NULL)
4428                 panic("free_jnewblk: Dependency still attached.");
4429         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4430 }
4431
4432 /*
4433  * Cancel a jnewblk which has been been made redundant by frag extension.
4434  */
4435 static void
4436 cancel_jnewblk(jnewblk, wkhd)
4437         struct jnewblk *jnewblk;
4438         struct workhead *wkhd;
4439 {
4440         struct jsegdep *jsegdep;
4441
4442         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4443         jsegdep = jnewblk->jn_jsegdep;
4444         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4445                 panic("cancel_jnewblk: Invalid state");
4446         jnewblk->jn_jsegdep  = NULL;
4447         jnewblk->jn_dep = NULL;
4448         jnewblk->jn_state |= GOINGAWAY;
4449         if (jnewblk->jn_state & INPROGRESS) {
4450                 jnewblk->jn_state &= ~INPROGRESS;
4451                 WORKLIST_REMOVE(&jnewblk->jn_list);
4452                 jwork_insert(wkhd, jsegdep);
4453         } else {
4454                 free_jsegdep(jsegdep);
4455                 remove_from_journal(&jnewblk->jn_list);
4456         }
4457         wake_worklist(&jnewblk->jn_list);
4458         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4459 }
4460
4461 static void
4462 free_jblkdep(jblkdep)
4463         struct jblkdep *jblkdep;
4464 {
4465
4466         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4467                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4468         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4469                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4470         else
4471                 panic("free_jblkdep: Unexpected type %s",
4472                     TYPENAME(jblkdep->jb_list.wk_type));
4473 }
4474
4475 /*
4476  * Free a single jseg once it is no longer referenced in memory or on
4477  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4478  * to disappear.
4479  */
4480 static void
4481 free_jseg(jseg, jblocks)
4482         struct jseg *jseg;
4483         struct jblocks *jblocks;
4484 {
4485         struct freework *freework;
4486
4487         /*
4488          * Free freework structures that were lingering to indicate freed
4489          * indirect blocks that forced journal write ordering on reallocate.
4490          */
4491         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4492                 indirblk_remove(freework);
4493         if (jblocks->jb_oldestseg == jseg)
4494                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4495         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4496         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4497         KASSERT(LIST_EMPTY(&jseg->js_entries),
4498             ("free_jseg: Freed jseg has valid entries."));
4499         WORKITEM_FREE(jseg, D_JSEG);
4500 }
4501
4502 /*
4503  * Free all jsegs that meet the criteria for being reclaimed and update
4504  * oldestseg.
4505  */
4506 static void
4507 free_jsegs(jblocks)
4508         struct jblocks *jblocks;
4509 {
4510         struct jseg *jseg;
4511
4512         /*
4513          * Free only those jsegs which have none allocated before them to
4514          * preserve the journal space ordering.
4515          */
4516         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4517                 /*
4518                  * Only reclaim space when nothing depends on this journal
4519                  * set and another set has written that it is no longer
4520                  * valid.
4521                  */
4522                 if (jseg->js_refs != 0) {
4523                         jblocks->jb_oldestseg = jseg;
4524                         return;
4525                 }
4526                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4527                         break;
4528                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4529                         break;
4530                 /*
4531                  * We can free jsegs that didn't write entries when
4532                  * oldestwrseq == js_seq.
4533                  */
4534                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4535                     jseg->js_cnt != 0)
4536                         break;
4537                 free_jseg(jseg, jblocks);
4538         }
4539         /*
4540          * If we exited the loop above we still must discover the
4541          * oldest valid segment.
4542          */
4543         if (jseg)
4544                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4545                      jseg = TAILQ_NEXT(jseg, js_next))
4546                         if (jseg->js_refs != 0)
4547                                 break;
4548         jblocks->jb_oldestseg = jseg;
4549         /*
4550          * The journal has no valid records but some jsegs may still be
4551          * waiting on oldestwrseq to advance.  We force a small record
4552          * out to permit these lingering records to be reclaimed.
4553          */
4554         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4555                 jblocks->jb_needseg = 1;
4556 }
4557
4558 /*
4559  * Release one reference to a jseg and free it if the count reaches 0.  This
4560  * should eventually reclaim journal space as well.
4561  */
4562 static void
4563 rele_jseg(jseg)
4564         struct jseg *jseg;
4565 {
4566
4567         KASSERT(jseg->js_refs > 0,
4568             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4569         if (--jseg->js_refs != 0)
4570                 return;
4571         free_jsegs(jseg->js_jblocks);
4572 }
4573
4574 /*
4575  * Release a jsegdep and decrement the jseg count.
4576  */
4577 static void
4578 free_jsegdep(jsegdep)
4579         struct jsegdep *jsegdep;
4580 {
4581
4582         if (jsegdep->jd_seg)
4583                 rele_jseg(jsegdep->jd_seg);
4584         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4585 }
4586
4587 /*
4588  * Wait for a journal item to make it to disk.  Initiate journal processing
4589  * if required.
4590  */
4591 static int
4592 jwait(wk, waitfor)
4593         struct worklist *wk;
4594         int waitfor;
4595 {
4596
4597         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4598         /*
4599          * Blocking journal waits cause slow synchronous behavior.  Record
4600          * stats on the frequency of these blocking operations.
4601          */
4602         if (waitfor == MNT_WAIT) {
4603                 stat_journal_wait++;
4604                 switch (wk->wk_type) {
4605                 case D_JREMREF:
4606                 case D_JMVREF:
4607                         stat_jwait_filepage++;
4608                         break;
4609                 case D_JTRUNC:
4610                 case D_JFREEBLK:
4611                         stat_jwait_freeblks++;
4612                         break;
4613                 case D_JNEWBLK:
4614                         stat_jwait_newblk++;
4615                         break;
4616                 case D_JADDREF:
4617                         stat_jwait_inode++;
4618                         break;
4619                 default:
4620                         break;
4621                 }
4622         }
4623         /*
4624          * If IO has not started we process the journal.  We can't mark the
4625          * worklist item as IOWAITING because we drop the lock while
4626          * processing the journal and the worklist entry may be freed after
4627          * this point.  The caller may call back in and re-issue the request.
4628          */
4629         if ((wk->wk_state & INPROGRESS) == 0) {
4630                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4631                 if (waitfor != MNT_WAIT)
4632                         return (EBUSY);
4633                 return (0);
4634         }
4635         if (waitfor != MNT_WAIT)
4636                 return (EBUSY);
4637         wait_worklist(wk, "jwait");
4638         return (0);
4639 }
4640
4641 /*
4642  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4643  * appropriate.  This is a convenience function to reduce duplicate code
4644  * for the setup and revert functions below.
4645  */
4646 static struct inodedep *
4647 inodedep_lookup_ip(ip)
4648         struct inode *ip;
4649 {
4650         struct inodedep *inodedep;
4651
4652         KASSERT(ip->i_nlink >= ip->i_effnlink,
4653             ("inodedep_lookup_ip: bad delta"));
4654         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4655             &inodedep);
4656         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4657         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4658
4659         return (inodedep);
4660 }
4661
4662 /*
4663  * Called prior to creating a new inode and linking it to a directory.  The
4664  * jaddref structure must already be allocated by softdep_setup_inomapdep
4665  * and it is discovered here so we can initialize the mode and update
4666  * nlinkdelta.
4667  */
4668 void
4669 softdep_setup_create(dp, ip)
4670         struct inode *dp;
4671         struct inode *ip;
4672 {
4673         struct inodedep *inodedep;
4674         struct jaddref *jaddref;
4675         struct vnode *dvp;
4676
4677         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4678             ("softdep_setup_create called on non-softdep filesystem"));
4679         KASSERT(ip->i_nlink == 1,
4680             ("softdep_setup_create: Invalid link count."));
4681         dvp = ITOV(dp);
4682         ACQUIRE_LOCK(ITOUMP(dp));
4683         inodedep = inodedep_lookup_ip(ip);
4684         if (DOINGSUJ(dvp)) {
4685                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4686                     inoreflst);
4687                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4688                     ("softdep_setup_create: No addref structure present."));
4689         }
4690         softdep_prelink(dvp, NULL);
4691         FREE_LOCK(ITOUMP(dp));
4692 }
4693
4694 /*
4695  * Create a jaddref structure to track the addition of a DOTDOT link when
4696  * we are reparenting an inode as part of a rename.  This jaddref will be
4697  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4698  * non-journaling softdep.
4699  */
4700 void
4701 softdep_setup_dotdot_link(dp, ip)
4702         struct inode *dp;
4703         struct inode *ip;
4704 {
4705         struct inodedep *inodedep;
4706         struct jaddref *jaddref;
4707         struct vnode *dvp;
4708
4709         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4710             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4711         dvp = ITOV(dp);
4712         jaddref = NULL;
4713         /*
4714          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4715          * is used as a normal link would be.
4716          */
4717         if (DOINGSUJ(dvp))
4718                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4719                     dp->i_effnlink - 1, dp->i_mode);
4720         ACQUIRE_LOCK(ITOUMP(dp));
4721         inodedep = inodedep_lookup_ip(dp);
4722         if (jaddref)
4723                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4724                     if_deps);
4725         softdep_prelink(dvp, ITOV(ip));
4726         FREE_LOCK(ITOUMP(dp));
4727 }
4728
4729 /*
4730  * Create a jaddref structure to track a new link to an inode.  The directory
4731  * offset is not known until softdep_setup_directory_add or
4732  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4733  * softdep.
4734  */
4735 void
4736 softdep_setup_link(dp, ip)
4737         struct inode *dp;
4738         struct inode *ip;
4739 {
4740         struct inodedep *inodedep;
4741         struct jaddref *jaddref;
4742         struct vnode *dvp;
4743
4744         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4745             ("softdep_setup_link called on non-softdep filesystem"));
4746         dvp = ITOV(dp);
4747         jaddref = NULL;
4748         if (DOINGSUJ(dvp))
4749                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4750                     ip->i_mode);
4751         ACQUIRE_LOCK(ITOUMP(dp));
4752         inodedep = inodedep_lookup_ip(ip);
4753         if (jaddref)
4754                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4755                     if_deps);
4756         softdep_prelink(dvp, ITOV(ip));
4757         FREE_LOCK(ITOUMP(dp));
4758 }
4759
4760 /*
4761  * Called to create the jaddref structures to track . and .. references as
4762  * well as lookup and further initialize the incomplete jaddref created
4763  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4764  * nlinkdelta for non-journaling softdep.
4765  */
4766 void
4767 softdep_setup_mkdir(dp, ip)
4768         struct inode *dp;
4769         struct inode *ip;
4770 {
4771         struct inodedep *inodedep;
4772         struct jaddref *dotdotaddref;
4773         struct jaddref *dotaddref;
4774         struct jaddref *jaddref;
4775         struct vnode *dvp;
4776
4777         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4778             ("softdep_setup_mkdir called on non-softdep filesystem"));
4779         dvp = ITOV(dp);
4780         dotaddref = dotdotaddref = NULL;
4781         if (DOINGSUJ(dvp)) {
4782                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4783                     ip->i_mode);
4784                 dotaddref->ja_state |= MKDIR_BODY;
4785                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4786                     dp->i_effnlink - 1, dp->i_mode);
4787                 dotdotaddref->ja_state |= MKDIR_PARENT;
4788         }
4789         ACQUIRE_LOCK(ITOUMP(dp));
4790         inodedep = inodedep_lookup_ip(ip);
4791         if (DOINGSUJ(dvp)) {
4792                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4793                     inoreflst);
4794                 KASSERT(jaddref != NULL,
4795                     ("softdep_setup_mkdir: No addref structure present."));
4796                 KASSERT(jaddref->ja_parent == dp->i_number, 
4797                     ("softdep_setup_mkdir: bad parent %ju",
4798                     (uintmax_t)jaddref->ja_parent));
4799                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4800                     if_deps);
4801         }
4802         inodedep = inodedep_lookup_ip(dp);
4803         if (DOINGSUJ(dvp))
4804                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4805                     &dotdotaddref->ja_ref, if_deps);
4806         softdep_prelink(ITOV(dp), NULL);
4807         FREE_LOCK(ITOUMP(dp));
4808 }
4809
4810 /*
4811  * Called to track nlinkdelta of the inode and parent directories prior to
4812  * unlinking a directory.
4813  */
4814 void
4815 softdep_setup_rmdir(dp, ip)
4816         struct inode *dp;
4817         struct inode *ip;
4818 {
4819         struct vnode *dvp;
4820
4821         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4822             ("softdep_setup_rmdir called on non-softdep filesystem"));
4823         dvp = ITOV(dp);
4824         ACQUIRE_LOCK(ITOUMP(dp));
4825         (void) inodedep_lookup_ip(ip);
4826         (void) inodedep_lookup_ip(dp);
4827         softdep_prelink(dvp, ITOV(ip));
4828         FREE_LOCK(ITOUMP(dp));
4829 }
4830
4831 /*
4832  * Called to track nlinkdelta of the inode and parent directories prior to
4833  * unlink.
4834  */
4835 void
4836 softdep_setup_unlink(dp, ip)
4837         struct inode *dp;
4838         struct inode *ip;
4839 {
4840         struct vnode *dvp;
4841
4842         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4843             ("softdep_setup_unlink called on non-softdep filesystem"));
4844         dvp = ITOV(dp);
4845         ACQUIRE_LOCK(ITOUMP(dp));
4846         (void) inodedep_lookup_ip(ip);
4847         (void) inodedep_lookup_ip(dp);
4848         softdep_prelink(dvp, ITOV(ip));
4849         FREE_LOCK(ITOUMP(dp));
4850 }
4851
4852 /*
4853  * Called to release the journal structures created by a failed non-directory
4854  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4855  */
4856 void
4857 softdep_revert_create(dp, ip)
4858         struct inode *dp;
4859         struct inode *ip;
4860 {
4861         struct inodedep *inodedep;
4862         struct jaddref *jaddref;
4863         struct vnode *dvp;
4864
4865         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4866             ("softdep_revert_create called on non-softdep filesystem"));
4867         dvp = ITOV(dp);
4868         ACQUIRE_LOCK(ITOUMP(dp));
4869         inodedep = inodedep_lookup_ip(ip);
4870         if (DOINGSUJ(dvp)) {
4871                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4872                     inoreflst);
4873                 KASSERT(jaddref->ja_parent == dp->i_number,
4874                     ("softdep_revert_create: addref parent mismatch"));
4875                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4876         }
4877         FREE_LOCK(ITOUMP(dp));
4878 }
4879
4880 /*
4881  * Called to release the journal structures created by a failed link
4882  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4883  */
4884 void
4885 softdep_revert_link(dp, ip)
4886         struct inode *dp;
4887         struct inode *ip;
4888 {
4889         struct inodedep *inodedep;
4890         struct jaddref *jaddref;
4891         struct vnode *dvp;
4892
4893         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4894             ("softdep_revert_link called on non-softdep filesystem"));
4895         dvp = ITOV(dp);
4896         ACQUIRE_LOCK(ITOUMP(dp));
4897         inodedep = inodedep_lookup_ip(ip);
4898         if (DOINGSUJ(dvp)) {
4899                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4900                     inoreflst);
4901                 KASSERT(jaddref->ja_parent == dp->i_number,
4902                     ("softdep_revert_link: addref parent mismatch"));
4903                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4904         }
4905         FREE_LOCK(ITOUMP(dp));
4906 }
4907
4908 /*
4909  * Called to release the journal structures created by a failed mkdir
4910  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4911  */
4912 void
4913 softdep_revert_mkdir(dp, ip)
4914         struct inode *dp;
4915         struct inode *ip;
4916 {
4917         struct inodedep *inodedep;
4918         struct jaddref *jaddref;
4919         struct jaddref *dotaddref;
4920         struct vnode *dvp;
4921
4922         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4923             ("softdep_revert_mkdir called on non-softdep filesystem"));
4924         dvp = ITOV(dp);
4925
4926         ACQUIRE_LOCK(ITOUMP(dp));
4927         inodedep = inodedep_lookup_ip(dp);
4928         if (DOINGSUJ(dvp)) {
4929                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4930                     inoreflst);
4931                 KASSERT(jaddref->ja_parent == ip->i_number,
4932                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4933                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4934         }
4935         inodedep = inodedep_lookup_ip(ip);
4936         if (DOINGSUJ(dvp)) {
4937                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4938                     inoreflst);
4939                 KASSERT(jaddref->ja_parent == dp->i_number,
4940                     ("softdep_revert_mkdir: addref parent mismatch"));
4941                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4942                     inoreflst, if_deps);
4943                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4944                 KASSERT(dotaddref->ja_parent == ip->i_number,
4945                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4946                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4947         }
4948         FREE_LOCK(ITOUMP(dp));
4949 }
4950
4951 /* 
4952  * Called to correct nlinkdelta after a failed rmdir.
4953  */
4954 void
4955 softdep_revert_rmdir(dp, ip)
4956         struct inode *dp;
4957         struct inode *ip;
4958 {
4959
4960         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4961             ("softdep_revert_rmdir called on non-softdep filesystem"));
4962         ACQUIRE_LOCK(ITOUMP(dp));
4963         (void) inodedep_lookup_ip(ip);
4964         (void) inodedep_lookup_ip(dp);
4965         FREE_LOCK(ITOUMP(dp));
4966 }
4967
4968 /*
4969  * Protecting the freemaps (or bitmaps).
4970  * 
4971  * To eliminate the need to execute fsck before mounting a filesystem
4972  * after a power failure, one must (conservatively) guarantee that the
4973  * on-disk copy of the bitmaps never indicate that a live inode or block is
4974  * free.  So, when a block or inode is allocated, the bitmap should be
4975  * updated (on disk) before any new pointers.  When a block or inode is
4976  * freed, the bitmap should not be updated until all pointers have been
4977  * reset.  The latter dependency is handled by the delayed de-allocation
4978  * approach described below for block and inode de-allocation.  The former
4979  * dependency is handled by calling the following procedure when a block or
4980  * inode is allocated. When an inode is allocated an "inodedep" is created
4981  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4982  * Each "inodedep" is also inserted into the hash indexing structure so
4983  * that any additional link additions can be made dependent on the inode
4984  * allocation.
4985  * 
4986  * The ufs filesystem maintains a number of free block counts (e.g., per
4987  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4988  * in addition to the bitmaps.  These counts are used to improve efficiency
4989  * during allocation and therefore must be consistent with the bitmaps.
4990  * There is no convenient way to guarantee post-crash consistency of these
4991  * counts with simple update ordering, for two main reasons: (1) The counts
4992  * and bitmaps for a single cylinder group block are not in the same disk
4993  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4994  * be written and the other not.  (2) Some of the counts are located in the
4995  * superblock rather than the cylinder group block. So, we focus our soft
4996  * updates implementation on protecting the bitmaps. When mounting a
4997  * filesystem, we recompute the auxiliary counts from the bitmaps.
4998  */
4999
5000 /*
5001  * Called just after updating the cylinder group block to allocate an inode.
5002  */
5003 void
5004 softdep_setup_inomapdep(bp, ip, newinum, mode)
5005         struct buf *bp;         /* buffer for cylgroup block with inode map */
5006         struct inode *ip;       /* inode related to allocation */
5007         ino_t newinum;          /* new inode number being allocated */
5008         int mode;
5009 {
5010         struct inodedep *inodedep;
5011         struct bmsafemap *bmsafemap;
5012         struct jaddref *jaddref;
5013         struct mount *mp;
5014         struct fs *fs;
5015
5016         mp = ITOVFS(ip);
5017         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5018             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5019         fs = VFSTOUFS(mp)->um_fs;
5020         jaddref = NULL;
5021
5022         /*
5023          * Allocate the journal reference add structure so that the bitmap
5024          * can be dependent on it.
5025          */
5026         if (MOUNTEDSUJ(mp)) {
5027                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5028                 jaddref->ja_state |= NEWBLOCK;
5029         }
5030
5031         /*
5032          * Create a dependency for the newly allocated inode.
5033          * Panic if it already exists as something is seriously wrong.
5034          * Otherwise add it to the dependency list for the buffer holding
5035          * the cylinder group map from which it was allocated.
5036          *
5037          * We have to preallocate a bmsafemap entry in case it is needed
5038          * in bmsafemap_lookup since once we allocate the inodedep, we
5039          * have to finish initializing it before we can FREE_LOCK().
5040          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5041          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5042          * creating the inodedep as it can be freed during the time
5043          * that we FREE_LOCK() while allocating the inodedep. We must
5044          * call workitem_alloc() before entering the locked section as
5045          * it also acquires the lock and we must avoid trying doing so
5046          * recursively.
5047          */
5048         bmsafemap = malloc(sizeof(struct bmsafemap),
5049             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5050         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5051         ACQUIRE_LOCK(ITOUMP(ip));
5052         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5053                 panic("softdep_setup_inomapdep: dependency %p for new"
5054                     "inode already exists", inodedep);
5055         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5056         if (jaddref) {
5057                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5058                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5059                     if_deps);
5060         } else {
5061                 inodedep->id_state |= ONDEPLIST;
5062                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5063         }
5064         inodedep->id_bmsafemap = bmsafemap;
5065         inodedep->id_state &= ~DEPCOMPLETE;
5066         FREE_LOCK(ITOUMP(ip));
5067 }
5068
5069 /*
5070  * Called just after updating the cylinder group block to
5071  * allocate block or fragment.
5072  */
5073 void
5074 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5075         struct buf *bp;         /* buffer for cylgroup block with block map */
5076         struct mount *mp;       /* filesystem doing allocation */
5077         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5078         int frags;              /* Number of fragments. */
5079         int oldfrags;           /* Previous number of fragments for extend. */
5080 {
5081         struct newblk *newblk;
5082         struct bmsafemap *bmsafemap;
5083         struct jnewblk *jnewblk;
5084         struct ufsmount *ump;
5085         struct fs *fs;
5086
5087         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5088             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5089         ump = VFSTOUFS(mp);
5090         fs = ump->um_fs;
5091         jnewblk = NULL;
5092         /*
5093          * Create a dependency for the newly allocated block.
5094          * Add it to the dependency list for the buffer holding
5095          * the cylinder group map from which it was allocated.
5096          */
5097         if (MOUNTEDSUJ(mp)) {
5098                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5099                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5100                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5101                 jnewblk->jn_state = ATTACHED;
5102                 jnewblk->jn_blkno = newblkno;
5103                 jnewblk->jn_frags = frags;
5104                 jnewblk->jn_oldfrags = oldfrags;
5105 #ifdef SUJ_DEBUG
5106                 {
5107                         struct cg *cgp;
5108                         uint8_t *blksfree;
5109                         long bno;
5110                         int i;
5111         
5112                         cgp = (struct cg *)bp->b_data;
5113                         blksfree = cg_blksfree(cgp);
5114                         bno = dtogd(fs, jnewblk->jn_blkno);
5115                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5116                             i++) {
5117                                 if (isset(blksfree, bno + i))
5118                                         panic("softdep_setup_blkmapdep: "
5119                                             "free fragment %d from %d-%d "
5120                                             "state 0x%X dep %p", i,
5121                                             jnewblk->jn_oldfrags,
5122                                             jnewblk->jn_frags,
5123                                             jnewblk->jn_state,
5124                                             jnewblk->jn_dep);
5125                         }
5126                 }
5127 #endif
5128         }
5129
5130         CTR3(KTR_SUJ,
5131             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5132             newblkno, frags, oldfrags);
5133         ACQUIRE_LOCK(ump);
5134         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5135                 panic("softdep_setup_blkmapdep: found block");
5136         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5137             dtog(fs, newblkno), NULL);
5138         if (jnewblk) {
5139                 jnewblk->jn_dep = (struct worklist *)newblk;
5140                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5141         } else {
5142                 newblk->nb_state |= ONDEPLIST;
5143                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5144         }
5145         newblk->nb_bmsafemap = bmsafemap;
5146         newblk->nb_jnewblk = jnewblk;
5147         FREE_LOCK(ump);
5148 }
5149
5150 #define BMSAFEMAP_HASH(ump, cg) \
5151       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5152
5153 static int
5154 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5155         struct bmsafemap_hashhead *bmsafemaphd;
5156         int cg;
5157         struct bmsafemap **bmsafemapp;
5158 {
5159         struct bmsafemap *bmsafemap;
5160
5161         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5162                 if (bmsafemap->sm_cg == cg)
5163                         break;
5164         if (bmsafemap) {
5165                 *bmsafemapp = bmsafemap;
5166                 return (1);
5167         }
5168         *bmsafemapp = NULL;
5169
5170         return (0);
5171 }
5172
5173 /*
5174  * Find the bmsafemap associated with a cylinder group buffer.
5175  * If none exists, create one. The buffer must be locked when
5176  * this routine is called and this routine must be called with
5177  * the softdep lock held. To avoid giving up the lock while
5178  * allocating a new bmsafemap, a preallocated bmsafemap may be
5179  * provided. If it is provided but not needed, it is freed.
5180  */
5181 static struct bmsafemap *
5182 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5183         struct mount *mp;
5184         struct buf *bp;
5185         int cg;
5186         struct bmsafemap *newbmsafemap;
5187 {
5188         struct bmsafemap_hashhead *bmsafemaphd;
5189         struct bmsafemap *bmsafemap, *collision;
5190         struct worklist *wk;
5191         struct ufsmount *ump;
5192
5193         ump = VFSTOUFS(mp);
5194         LOCK_OWNED(ump);
5195         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5196         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5197                 if (wk->wk_type == D_BMSAFEMAP) {
5198                         if (newbmsafemap)
5199                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5200                         return (WK_BMSAFEMAP(wk));
5201                 }
5202         }
5203         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5204         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5205                 if (newbmsafemap)
5206                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5207                 return (bmsafemap);
5208         }
5209         if (newbmsafemap) {
5210                 bmsafemap = newbmsafemap;
5211         } else {
5212                 FREE_LOCK(ump);
5213                 bmsafemap = malloc(sizeof(struct bmsafemap),
5214                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5215                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5216                 ACQUIRE_LOCK(ump);
5217         }
5218         bmsafemap->sm_buf = bp;
5219         LIST_INIT(&bmsafemap->sm_inodedephd);
5220         LIST_INIT(&bmsafemap->sm_inodedepwr);
5221         LIST_INIT(&bmsafemap->sm_newblkhd);
5222         LIST_INIT(&bmsafemap->sm_newblkwr);
5223         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5224         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5225         LIST_INIT(&bmsafemap->sm_freehd);
5226         LIST_INIT(&bmsafemap->sm_freewr);
5227         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5228                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5229                 return (collision);
5230         }
5231         bmsafemap->sm_cg = cg;
5232         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5233         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5234         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5235         return (bmsafemap);
5236 }
5237
5238 /*
5239  * Direct block allocation dependencies.
5240  * 
5241  * When a new block is allocated, the corresponding disk locations must be
5242  * initialized (with zeros or new data) before the on-disk inode points to
5243  * them.  Also, the freemap from which the block was allocated must be
5244  * updated (on disk) before the inode's pointer. These two dependencies are
5245  * independent of each other and are needed for all file blocks and indirect
5246  * blocks that are pointed to directly by the inode.  Just before the
5247  * "in-core" version of the inode is updated with a newly allocated block
5248  * number, a procedure (below) is called to setup allocation dependency
5249  * structures.  These structures are removed when the corresponding
5250  * dependencies are satisfied or when the block allocation becomes obsolete
5251  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5252  * fragment that gets upgraded).  All of these cases are handled in
5253  * procedures described later.
5254  * 
5255  * When a file extension causes a fragment to be upgraded, either to a larger
5256  * fragment or to a full block, the on-disk location may change (if the
5257  * previous fragment could not simply be extended). In this case, the old
5258  * fragment must be de-allocated, but not until after the inode's pointer has
5259  * been updated. In most cases, this is handled by later procedures, which
5260  * will construct a "freefrag" structure to be added to the workitem queue
5261  * when the inode update is complete (or obsolete).  The main exception to
5262  * this is when an allocation occurs while a pending allocation dependency
5263  * (for the same block pointer) remains.  This case is handled in the main
5264  * allocation dependency setup procedure by immediately freeing the
5265  * unreferenced fragments.
5266  */ 
5267 void 
5268 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5269         struct inode *ip;       /* inode to which block is being added */
5270         ufs_lbn_t off;          /* block pointer within inode */
5271         ufs2_daddr_t newblkno;  /* disk block number being added */
5272         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5273         long newsize;           /* size of new block */
5274         long oldsize;           /* size of new block */
5275         struct buf *bp;         /* bp for allocated block */
5276 {
5277         struct allocdirect *adp, *oldadp;
5278         struct allocdirectlst *adphead;
5279         struct freefrag *freefrag;
5280         struct inodedep *inodedep;
5281         struct pagedep *pagedep;
5282         struct jnewblk *jnewblk;
5283         struct newblk *newblk;
5284         struct mount *mp;
5285         ufs_lbn_t lbn;
5286
5287         lbn = bp->b_lblkno;
5288         mp = ITOVFS(ip);
5289         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5290             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5291         if (oldblkno && oldblkno != newblkno)
5292                 /*
5293                  * The usual case is that a smaller fragment that
5294                  * was just allocated has been replaced with a bigger
5295                  * fragment or a full-size block. If it is marked as
5296                  * B_DELWRI, the current contents have not been written
5297                  * to disk. It is possible that the block was written
5298                  * earlier, but very uncommon. If the block has never
5299                  * been written, there is no need to send a BIO_DELETE
5300                  * for it when it is freed. The gain from avoiding the
5301                  * TRIMs for the common case of unwritten blocks far
5302                  * exceeds the cost of the write amplification for the
5303                  * uncommon case of failing to send a TRIM for a block
5304                  * that had been written.
5305                  */
5306                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5307                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5308         else
5309                 freefrag = NULL;
5310
5311         CTR6(KTR_SUJ,
5312             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5313             "off %jd newsize %ld oldsize %d",
5314             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5315         ACQUIRE_LOCK(ITOUMP(ip));
5316         if (off >= UFS_NDADDR) {
5317                 if (lbn > 0)
5318                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5319                             lbn, off);
5320                 /* allocating an indirect block */
5321                 if (oldblkno != 0)
5322                         panic("softdep_setup_allocdirect: non-zero indir");
5323         } else {
5324                 if (off != lbn)
5325                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5326                             lbn, off);
5327                 /*
5328                  * Allocating a direct block.
5329                  *
5330                  * If we are allocating a directory block, then we must
5331                  * allocate an associated pagedep to track additions and
5332                  * deletions.
5333                  */
5334                 if ((ip->i_mode & IFMT) == IFDIR)
5335                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5336                             &pagedep);
5337         }
5338         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5339                 panic("softdep_setup_allocdirect: lost block");
5340         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5341             ("softdep_setup_allocdirect: newblk already initialized"));
5342         /*
5343          * Convert the newblk to an allocdirect.
5344          */
5345         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5346         adp = (struct allocdirect *)newblk;
5347         newblk->nb_freefrag = freefrag;
5348         adp->ad_offset = off;
5349         adp->ad_oldblkno = oldblkno;
5350         adp->ad_newsize = newsize;
5351         adp->ad_oldsize = oldsize;
5352
5353         /*
5354          * Finish initializing the journal.
5355          */
5356         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5357                 jnewblk->jn_ino = ip->i_number;
5358                 jnewblk->jn_lbn = lbn;
5359                 add_to_journal(&jnewblk->jn_list);
5360         }
5361         if (freefrag && freefrag->ff_jdep != NULL &&
5362             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5363                 add_to_journal(freefrag->ff_jdep);
5364         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5365         adp->ad_inodedep = inodedep;
5366
5367         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5368         /*
5369          * The list of allocdirects must be kept in sorted and ascending
5370          * order so that the rollback routines can quickly determine the
5371          * first uncommitted block (the size of the file stored on disk
5372          * ends at the end of the lowest committed fragment, or if there
5373          * are no fragments, at the end of the highest committed block).
5374          * Since files generally grow, the typical case is that the new
5375          * block is to be added at the end of the list. We speed this
5376          * special case by checking against the last allocdirect in the
5377          * list before laboriously traversing the list looking for the
5378          * insertion point.
5379          */
5380         adphead = &inodedep->id_newinoupdt;
5381         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5382         if (oldadp == NULL || oldadp->ad_offset <= off) {
5383                 /* insert at end of list */
5384                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5385                 if (oldadp != NULL && oldadp->ad_offset == off)
5386                         allocdirect_merge(adphead, adp, oldadp);
5387                 FREE_LOCK(ITOUMP(ip));
5388                 return;
5389         }
5390         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5391                 if (oldadp->ad_offset >= off)
5392                         break;
5393         }
5394         if (oldadp == NULL)
5395                 panic("softdep_setup_allocdirect: lost entry");
5396         /* insert in middle of list */
5397         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5398         if (oldadp->ad_offset == off)
5399                 allocdirect_merge(adphead, adp, oldadp);
5400
5401         FREE_LOCK(ITOUMP(ip));
5402 }
5403
5404 /*
5405  * Merge a newer and older journal record to be stored either in a
5406  * newblock or freefrag.  This handles aggregating journal records for
5407  * fragment allocation into a second record as well as replacing a
5408  * journal free with an aborted journal allocation.  A segment for the
5409  * oldest record will be placed on wkhd if it has been written.  If not
5410  * the segment for the newer record will suffice.
5411  */
5412 static struct worklist *
5413 jnewblk_merge(new, old, wkhd)
5414         struct worklist *new;
5415         struct worklist *old;
5416         struct workhead *wkhd;
5417 {
5418         struct jnewblk *njnewblk;
5419         struct jnewblk *jnewblk;
5420
5421         /* Handle NULLs to simplify callers. */
5422         if (new == NULL)
5423                 return (old);
5424         if (old == NULL)
5425                 return (new);
5426         /* Replace a jfreefrag with a jnewblk. */
5427         if (new->wk_type == D_JFREEFRAG) {
5428                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5429                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5430                             old, new);
5431                 cancel_jfreefrag(WK_JFREEFRAG(new));
5432                 return (old);
5433         }
5434         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5435                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5436                     old->wk_type, new->wk_type);
5437         /*
5438          * Handle merging of two jnewblk records that describe
5439          * different sets of fragments in the same block.
5440          */
5441         jnewblk = WK_JNEWBLK(old);
5442         njnewblk = WK_JNEWBLK(new);
5443         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5444                 panic("jnewblk_merge: Merging disparate blocks.");
5445         /*
5446          * The record may be rolled back in the cg.
5447          */
5448         if (jnewblk->jn_state & UNDONE) {
5449                 jnewblk->jn_state &= ~UNDONE;
5450                 njnewblk->jn_state |= UNDONE;
5451                 njnewblk->jn_state &= ~ATTACHED;
5452         }
5453         /*
5454          * We modify the newer addref and free the older so that if neither
5455          * has been written the most up-to-date copy will be on disk.  If
5456          * both have been written but rolled back we only temporarily need
5457          * one of them to fix the bits when the cg write completes.
5458          */
5459         jnewblk->jn_state |= ATTACHED | COMPLETE;
5460         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5461         cancel_jnewblk(jnewblk, wkhd);
5462         WORKLIST_REMOVE(&jnewblk->jn_list);
5463         free_jnewblk(jnewblk);
5464         return (new);
5465 }
5466
5467 /*
5468  * Replace an old allocdirect dependency with a newer one.
5469  * This routine must be called with splbio interrupts blocked.
5470  */
5471 static void
5472 allocdirect_merge(adphead, newadp, oldadp)
5473         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5474         struct allocdirect *newadp;     /* allocdirect being added */
5475         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5476 {
5477         struct worklist *wk;
5478         struct freefrag *freefrag;
5479
5480         freefrag = NULL;
5481         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5482         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5483             newadp->ad_oldsize != oldadp->ad_newsize ||
5484             newadp->ad_offset >= UFS_NDADDR)
5485                 panic("%s %jd != new %jd || old size %ld != new %ld",
5486                     "allocdirect_merge: old blkno",
5487                     (intmax_t)newadp->ad_oldblkno,
5488                     (intmax_t)oldadp->ad_newblkno,
5489                     newadp->ad_oldsize, oldadp->ad_newsize);
5490         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5491         newadp->ad_oldsize = oldadp->ad_oldsize;
5492         /*
5493          * If the old dependency had a fragment to free or had never
5494          * previously had a block allocated, then the new dependency
5495          * can immediately post its freefrag and adopt the old freefrag.
5496          * This action is done by swapping the freefrag dependencies.
5497          * The new dependency gains the old one's freefrag, and the
5498          * old one gets the new one and then immediately puts it on
5499          * the worklist when it is freed by free_newblk. It is
5500          * not possible to do this swap when the old dependency had a
5501          * non-zero size but no previous fragment to free. This condition
5502          * arises when the new block is an extension of the old block.
5503          * Here, the first part of the fragment allocated to the new
5504          * dependency is part of the block currently claimed on disk by
5505          * the old dependency, so cannot legitimately be freed until the
5506          * conditions for the new dependency are fulfilled.
5507          */
5508         freefrag = newadp->ad_freefrag;
5509         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5510                 newadp->ad_freefrag = oldadp->ad_freefrag;
5511                 oldadp->ad_freefrag = freefrag;
5512         }
5513         /*
5514          * If we are tracking a new directory-block allocation,
5515          * move it from the old allocdirect to the new allocdirect.
5516          */
5517         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5518                 WORKLIST_REMOVE(wk);
5519                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5520                         panic("allocdirect_merge: extra newdirblk");
5521                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5522         }
5523         TAILQ_REMOVE(adphead, oldadp, ad_next);
5524         /*
5525          * We need to move any journal dependencies over to the freefrag
5526          * that releases this block if it exists.  Otherwise we are
5527          * extending an existing block and we'll wait until that is
5528          * complete to release the journal space and extend the
5529          * new journal to cover this old space as well.
5530          */
5531         if (freefrag == NULL) {
5532                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5533                         panic("allocdirect_merge: %jd != %jd",
5534                             oldadp->ad_newblkno, newadp->ad_newblkno);
5535                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5536                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5537                     &oldadp->ad_block.nb_jnewblk->jn_list,
5538                     &newadp->ad_block.nb_jwork);
5539                 oldadp->ad_block.nb_jnewblk = NULL;
5540                 cancel_newblk(&oldadp->ad_block, NULL,
5541                     &newadp->ad_block.nb_jwork);
5542         } else {
5543                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5544                     &freefrag->ff_list, &freefrag->ff_jwork);
5545                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5546                     &freefrag->ff_jwork);
5547         }
5548         free_newblk(&oldadp->ad_block);
5549 }
5550
5551 /*
5552  * Allocate a jfreefrag structure to journal a single block free.
5553  */
5554 static struct jfreefrag *
5555 newjfreefrag(freefrag, ip, blkno, size, lbn)
5556         struct freefrag *freefrag;
5557         struct inode *ip;
5558         ufs2_daddr_t blkno;
5559         long size;
5560         ufs_lbn_t lbn;
5561 {
5562         struct jfreefrag *jfreefrag;
5563         struct fs *fs;
5564
5565         fs = ITOFS(ip);
5566         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5567             M_SOFTDEP_FLAGS);
5568         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5569         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5570         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5571         jfreefrag->fr_ino = ip->i_number;
5572         jfreefrag->fr_lbn = lbn;
5573         jfreefrag->fr_blkno = blkno;
5574         jfreefrag->fr_frags = numfrags(fs, size);
5575         jfreefrag->fr_freefrag = freefrag;
5576
5577         return (jfreefrag);
5578 }
5579
5580 /*
5581  * Allocate a new freefrag structure.
5582  */
5583 static struct freefrag *
5584 newfreefrag(ip, blkno, size, lbn, key)
5585         struct inode *ip;
5586         ufs2_daddr_t blkno;
5587         long size;
5588         ufs_lbn_t lbn;
5589         u_long key;
5590 {
5591         struct freefrag *freefrag;
5592         struct ufsmount *ump;
5593         struct fs *fs;
5594
5595         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5596             ip->i_number, blkno, size, lbn);
5597         ump = ITOUMP(ip);
5598         fs = ump->um_fs;
5599         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5600                 panic("newfreefrag: frag size");
5601         freefrag = malloc(sizeof(struct freefrag),
5602             M_FREEFRAG, M_SOFTDEP_FLAGS);
5603         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5604         freefrag->ff_state = ATTACHED;
5605         LIST_INIT(&freefrag->ff_jwork);
5606         freefrag->ff_inum = ip->i_number;
5607         freefrag->ff_vtype = ITOV(ip)->v_type;
5608         freefrag->ff_blkno = blkno;
5609         freefrag->ff_fragsize = size;
5610         freefrag->ff_key = key;
5611
5612         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5613                 freefrag->ff_jdep = (struct worklist *)
5614                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5615         } else {
5616                 freefrag->ff_state |= DEPCOMPLETE;
5617                 freefrag->ff_jdep = NULL;
5618         }
5619
5620         return (freefrag);
5621 }
5622
5623 /*
5624  * This workitem de-allocates fragments that were replaced during
5625  * file block allocation.
5626  */
5627 static void 
5628 handle_workitem_freefrag(freefrag)
5629         struct freefrag *freefrag;
5630 {
5631         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5632         struct workhead wkhd;
5633
5634         CTR3(KTR_SUJ,
5635             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5636             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5637         /*
5638          * It would be illegal to add new completion items to the
5639          * freefrag after it was schedule to be done so it must be
5640          * safe to modify the list head here.
5641          */
5642         LIST_INIT(&wkhd);
5643         ACQUIRE_LOCK(ump);
5644         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5645         /*
5646          * If the journal has not been written we must cancel it here.
5647          */
5648         if (freefrag->ff_jdep) {
5649                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5650                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5651                             freefrag->ff_jdep->wk_type);
5652                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5653         }
5654         FREE_LOCK(ump);
5655         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5656            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5657            &wkhd, freefrag->ff_key);
5658         ACQUIRE_LOCK(ump);
5659         WORKITEM_FREE(freefrag, D_FREEFRAG);
5660         FREE_LOCK(ump);
5661 }
5662
5663 /*
5664  * Set up a dependency structure for an external attributes data block.
5665  * This routine follows much of the structure of softdep_setup_allocdirect.
5666  * See the description of softdep_setup_allocdirect above for details.
5667  */
5668 void 
5669 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5670         struct inode *ip;
5671         ufs_lbn_t off;
5672         ufs2_daddr_t newblkno;
5673         ufs2_daddr_t oldblkno;
5674         long newsize;
5675         long oldsize;
5676         struct buf *bp;
5677 {
5678         struct allocdirect *adp, *oldadp;
5679         struct allocdirectlst *adphead;
5680         struct freefrag *freefrag;
5681         struct inodedep *inodedep;
5682         struct jnewblk *jnewblk;
5683         struct newblk *newblk;
5684         struct mount *mp;
5685         struct ufsmount *ump;
5686         ufs_lbn_t lbn;
5687
5688         mp = ITOVFS(ip);
5689         ump = VFSTOUFS(mp);
5690         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5691             ("softdep_setup_allocext called on non-softdep filesystem"));
5692         KASSERT(off < UFS_NXADDR,
5693             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5694
5695         lbn = bp->b_lblkno;
5696         if (oldblkno && oldblkno != newblkno)
5697                 /*
5698                  * The usual case is that a smaller fragment that
5699                  * was just allocated has been replaced with a bigger
5700                  * fragment or a full-size block. If it is marked as
5701                  * B_DELWRI, the current contents have not been written
5702                  * to disk. It is possible that the block was written
5703                  * earlier, but very uncommon. If the block has never
5704                  * been written, there is no need to send a BIO_DELETE
5705                  * for it when it is freed. The gain from avoiding the
5706                  * TRIMs for the common case of unwritten blocks far
5707                  * exceeds the cost of the write amplification for the
5708                  * uncommon case of failing to send a TRIM for a block
5709                  * that had been written.
5710                  */
5711                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5712                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5713         else
5714                 freefrag = NULL;
5715
5716         ACQUIRE_LOCK(ump);
5717         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5718                 panic("softdep_setup_allocext: lost block");
5719         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5720             ("softdep_setup_allocext: newblk already initialized"));
5721         /*
5722          * Convert the newblk to an allocdirect.
5723          */
5724         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5725         adp = (struct allocdirect *)newblk;
5726         newblk->nb_freefrag = freefrag;
5727         adp->ad_offset = off;
5728         adp->ad_oldblkno = oldblkno;
5729         adp->ad_newsize = newsize;
5730         adp->ad_oldsize = oldsize;
5731         adp->ad_state |=  EXTDATA;
5732
5733         /*
5734          * Finish initializing the journal.
5735          */
5736         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5737                 jnewblk->jn_ino = ip->i_number;
5738                 jnewblk->jn_lbn = lbn;
5739                 add_to_journal(&jnewblk->jn_list);
5740         }
5741         if (freefrag && freefrag->ff_jdep != NULL &&
5742             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5743                 add_to_journal(freefrag->ff_jdep);
5744         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5745         adp->ad_inodedep = inodedep;
5746
5747         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5748         /*
5749          * The list of allocdirects must be kept in sorted and ascending
5750          * order so that the rollback routines can quickly determine the
5751          * first uncommitted block (the size of the file stored on disk
5752          * ends at the end of the lowest committed fragment, or if there
5753          * are no fragments, at the end of the highest committed block).
5754          * Since files generally grow, the typical case is that the new
5755          * block is to be added at the end of the list. We speed this
5756          * special case by checking against the last allocdirect in the
5757          * list before laboriously traversing the list looking for the
5758          * insertion point.
5759          */
5760         adphead = &inodedep->id_newextupdt;
5761         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5762         if (oldadp == NULL || oldadp->ad_offset <= off) {
5763                 /* insert at end of list */
5764                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5765                 if (oldadp != NULL && oldadp->ad_offset == off)
5766                         allocdirect_merge(adphead, adp, oldadp);
5767                 FREE_LOCK(ump);
5768                 return;
5769         }
5770         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5771                 if (oldadp->ad_offset >= off)
5772                         break;
5773         }
5774         if (oldadp == NULL)
5775                 panic("softdep_setup_allocext: lost entry");
5776         /* insert in middle of list */
5777         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5778         if (oldadp->ad_offset == off)
5779                 allocdirect_merge(adphead, adp, oldadp);
5780         FREE_LOCK(ump);
5781 }
5782
5783 /*
5784  * Indirect block allocation dependencies.
5785  * 
5786  * The same dependencies that exist for a direct block also exist when
5787  * a new block is allocated and pointed to by an entry in a block of
5788  * indirect pointers. The undo/redo states described above are also
5789  * used here. Because an indirect block contains many pointers that
5790  * may have dependencies, a second copy of the entire in-memory indirect
5791  * block is kept. The buffer cache copy is always completely up-to-date.
5792  * The second copy, which is used only as a source for disk writes,
5793  * contains only the safe pointers (i.e., those that have no remaining
5794  * update dependencies). The second copy is freed when all pointers
5795  * are safe. The cache is not allowed to replace indirect blocks with
5796  * pending update dependencies. If a buffer containing an indirect
5797  * block with dependencies is written, these routines will mark it
5798  * dirty again. It can only be successfully written once all the
5799  * dependencies are removed. The ffs_fsync routine in conjunction with
5800  * softdep_sync_metadata work together to get all the dependencies
5801  * removed so that a file can be successfully written to disk. Three
5802  * procedures are used when setting up indirect block pointer
5803  * dependencies. The division is necessary because of the organization
5804  * of the "balloc" routine and because of the distinction between file
5805  * pages and file metadata blocks.
5806  */
5807
5808 /*
5809  * Allocate a new allocindir structure.
5810  */
5811 static struct allocindir *
5812 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5813         struct inode *ip;       /* inode for file being extended */
5814         int ptrno;              /* offset of pointer in indirect block */
5815         ufs2_daddr_t newblkno;  /* disk block number being added */
5816         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5817         ufs_lbn_t lbn;
5818 {
5819         struct newblk *newblk;
5820         struct allocindir *aip;
5821         struct freefrag *freefrag;
5822         struct jnewblk *jnewblk;
5823
5824         if (oldblkno)
5825                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5826                     SINGLETON_KEY);
5827         else
5828                 freefrag = NULL;
5829         ACQUIRE_LOCK(ITOUMP(ip));
5830         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5831                 panic("new_allocindir: lost block");
5832         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5833             ("newallocindir: newblk already initialized"));
5834         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5835         newblk->nb_freefrag = freefrag;
5836         aip = (struct allocindir *)newblk;
5837         aip->ai_offset = ptrno;
5838         aip->ai_oldblkno = oldblkno;
5839         aip->ai_lbn = lbn;
5840         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5841                 jnewblk->jn_ino = ip->i_number;
5842                 jnewblk->jn_lbn = lbn;
5843                 add_to_journal(&jnewblk->jn_list);
5844         }
5845         if (freefrag && freefrag->ff_jdep != NULL &&
5846             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5847                 add_to_journal(freefrag->ff_jdep);
5848         return (aip);
5849 }
5850
5851 /*
5852  * Called just before setting an indirect block pointer
5853  * to a newly allocated file page.
5854  */
5855 void
5856 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5857         struct inode *ip;       /* inode for file being extended */
5858         ufs_lbn_t lbn;          /* allocated block number within file */
5859         struct buf *bp;         /* buffer with indirect blk referencing page */
5860         int ptrno;              /* offset of pointer in indirect block */
5861         ufs2_daddr_t newblkno;  /* disk block number being added */
5862         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5863         struct buf *nbp;        /* buffer holding allocated page */
5864 {
5865         struct inodedep *inodedep;
5866         struct freefrag *freefrag;
5867         struct allocindir *aip;
5868         struct pagedep *pagedep;
5869         struct mount *mp;
5870         struct ufsmount *ump;
5871
5872         mp = ITOVFS(ip);
5873         ump = VFSTOUFS(mp);
5874         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5875             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5876         KASSERT(lbn == nbp->b_lblkno,
5877             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5878             lbn, bp->b_lblkno));
5879         CTR4(KTR_SUJ,
5880             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5881             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5882         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5883         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5884         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5885         /*
5886          * If we are allocating a directory page, then we must
5887          * allocate an associated pagedep to track additions and
5888          * deletions.
5889          */
5890         if ((ip->i_mode & IFMT) == IFDIR)
5891                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5892         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5893         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5894         FREE_LOCK(ump);
5895         if (freefrag)
5896                 handle_workitem_freefrag(freefrag);
5897 }
5898
5899 /*
5900  * Called just before setting an indirect block pointer to a
5901  * newly allocated indirect block.
5902  */
5903 void
5904 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5905         struct buf *nbp;        /* newly allocated indirect block */
5906         struct inode *ip;       /* inode for file being extended */
5907         struct buf *bp;         /* indirect block referencing allocated block */
5908         int ptrno;              /* offset of pointer in indirect block */
5909         ufs2_daddr_t newblkno;  /* disk block number being added */
5910 {
5911         struct inodedep *inodedep;
5912         struct allocindir *aip;
5913         struct ufsmount *ump;
5914         ufs_lbn_t lbn;
5915
5916         ump = ITOUMP(ip);
5917         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5918             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5919         CTR3(KTR_SUJ,
5920             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5921             ip->i_number, newblkno, ptrno);
5922         lbn = nbp->b_lblkno;
5923         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5924         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5925         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5926         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5927         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5928                 panic("softdep_setup_allocindir_meta: Block already existed");
5929         FREE_LOCK(ump);
5930 }
5931
5932 static void
5933 indirdep_complete(indirdep)
5934         struct indirdep *indirdep;
5935 {
5936         struct allocindir *aip;
5937
5938         LIST_REMOVE(indirdep, ir_next);
5939         indirdep->ir_state |= DEPCOMPLETE;
5940
5941         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5942                 LIST_REMOVE(aip, ai_next);
5943                 free_newblk(&aip->ai_block);
5944         }
5945         /*
5946          * If this indirdep is not attached to a buf it was simply waiting
5947          * on completion to clear completehd.  free_indirdep() asserts
5948          * that nothing is dangling.
5949          */
5950         if ((indirdep->ir_state & ONWORKLIST) == 0)
5951                 free_indirdep(indirdep);
5952 }
5953
5954 static struct indirdep *
5955 indirdep_lookup(mp, ip, bp)
5956         struct mount *mp;
5957         struct inode *ip;
5958         struct buf *bp;
5959 {
5960         struct indirdep *indirdep, *newindirdep;
5961         struct newblk *newblk;
5962         struct ufsmount *ump;
5963         struct worklist *wk;
5964         struct fs *fs;
5965         ufs2_daddr_t blkno;
5966
5967         ump = VFSTOUFS(mp);
5968         LOCK_OWNED(ump);
5969         indirdep = NULL;
5970         newindirdep = NULL;
5971         fs = ump->um_fs;
5972         for (;;) {
5973                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5974                         if (wk->wk_type != D_INDIRDEP)
5975                                 continue;
5976                         indirdep = WK_INDIRDEP(wk);
5977                         break;
5978                 }
5979                 /* Found on the buffer worklist, no new structure to free. */
5980                 if (indirdep != NULL && newindirdep == NULL)
5981                         return (indirdep);
5982                 if (indirdep != NULL && newindirdep != NULL)
5983                         panic("indirdep_lookup: simultaneous create");
5984                 /* None found on the buffer and a new structure is ready. */
5985                 if (indirdep == NULL && newindirdep != NULL)
5986                         break;
5987                 /* None found and no new structure available. */
5988                 FREE_LOCK(ump);
5989                 newindirdep = malloc(sizeof(struct indirdep),
5990                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5991                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5992                 newindirdep->ir_state = ATTACHED;
5993                 if (I_IS_UFS1(ip))
5994                         newindirdep->ir_state |= UFS1FMT;
5995                 TAILQ_INIT(&newindirdep->ir_trunc);
5996                 newindirdep->ir_saveddata = NULL;
5997                 LIST_INIT(&newindirdep->ir_deplisthd);
5998                 LIST_INIT(&newindirdep->ir_donehd);
5999                 LIST_INIT(&newindirdep->ir_writehd);
6000                 LIST_INIT(&newindirdep->ir_completehd);
6001                 if (bp->b_blkno == bp->b_lblkno) {
6002                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6003                             NULL, NULL);
6004                         bp->b_blkno = blkno;
6005                 }
6006                 newindirdep->ir_freeblks = NULL;
6007                 newindirdep->ir_savebp =
6008                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6009                 newindirdep->ir_bp = bp;
6010                 BUF_KERNPROC(newindirdep->ir_savebp);
6011                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6012                 ACQUIRE_LOCK(ump);
6013         }
6014         indirdep = newindirdep;
6015         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6016         /*
6017          * If the block is not yet allocated we don't set DEPCOMPLETE so
6018          * that we don't free dependencies until the pointers are valid.
6019          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6020          * than using the hash.
6021          */
6022         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6023                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6024         else
6025                 indirdep->ir_state |= DEPCOMPLETE;
6026         return (indirdep);
6027 }
6028
6029 /*
6030  * Called to finish the allocation of the "aip" allocated
6031  * by one of the two routines above.
6032  */
6033 static struct freefrag *
6034 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6035         struct buf *bp;         /* in-memory copy of the indirect block */
6036         struct inode *ip;       /* inode for file being extended */
6037         struct inodedep *inodedep; /* Inodedep for ip */
6038         struct allocindir *aip; /* allocindir allocated by the above routines */
6039         ufs_lbn_t lbn;          /* Logical block number for this block. */
6040 {
6041         struct fs *fs;
6042         struct indirdep *indirdep;
6043         struct allocindir *oldaip;
6044         struct freefrag *freefrag;
6045         struct mount *mp;
6046         struct ufsmount *ump;
6047
6048         mp = ITOVFS(ip);
6049         ump = VFSTOUFS(mp);
6050         LOCK_OWNED(ump);
6051         fs = ump->um_fs;
6052         if (bp->b_lblkno >= 0)
6053                 panic("setup_allocindir_phase2: not indir blk");
6054         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6055             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6056         indirdep = indirdep_lookup(mp, ip, bp);
6057         KASSERT(indirdep->ir_savebp != NULL,
6058             ("setup_allocindir_phase2 NULL ir_savebp"));
6059         aip->ai_indirdep = indirdep;
6060         /*
6061          * Check for an unwritten dependency for this indirect offset.  If
6062          * there is, merge the old dependency into the new one.  This happens
6063          * as a result of reallocblk only.
6064          */
6065         freefrag = NULL;
6066         if (aip->ai_oldblkno != 0) {
6067                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6068                         if (oldaip->ai_offset == aip->ai_offset) {
6069                                 freefrag = allocindir_merge(aip, oldaip);
6070                                 goto done;
6071                         }
6072                 }
6073                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6074                         if (oldaip->ai_offset == aip->ai_offset) {
6075                                 freefrag = allocindir_merge(aip, oldaip);
6076                                 goto done;
6077                         }
6078                 }
6079         }
6080 done:
6081         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6082         return (freefrag);
6083 }
6084
6085 /*
6086  * Merge two allocindirs which refer to the same block.  Move newblock
6087  * dependencies and setup the freefrags appropriately.
6088  */
6089 static struct freefrag *
6090 allocindir_merge(aip, oldaip)
6091         struct allocindir *aip;
6092         struct allocindir *oldaip;
6093 {
6094         struct freefrag *freefrag;
6095         struct worklist *wk;
6096
6097         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6098                 panic("allocindir_merge: blkno");
6099         aip->ai_oldblkno = oldaip->ai_oldblkno;
6100         freefrag = aip->ai_freefrag;
6101         aip->ai_freefrag = oldaip->ai_freefrag;
6102         oldaip->ai_freefrag = NULL;
6103         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6104         /*
6105          * If we are tracking a new directory-block allocation,
6106          * move it from the old allocindir to the new allocindir.
6107          */
6108         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6109                 WORKLIST_REMOVE(wk);
6110                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6111                         panic("allocindir_merge: extra newdirblk");
6112                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6113         }
6114         /*
6115          * We can skip journaling for this freefrag and just complete
6116          * any pending journal work for the allocindir that is being
6117          * removed after the freefrag completes.
6118          */
6119         if (freefrag->ff_jdep)
6120                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6121         LIST_REMOVE(oldaip, ai_next);
6122         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6123             &freefrag->ff_list, &freefrag->ff_jwork);
6124         free_newblk(&oldaip->ai_block);
6125
6126         return (freefrag);
6127 }
6128
6129 static inline void
6130 setup_freedirect(freeblks, ip, i, needj)
6131         struct freeblks *freeblks;
6132         struct inode *ip;
6133         int i;
6134         int needj;
6135 {
6136         struct ufsmount *ump;
6137         ufs2_daddr_t blkno;
6138         int frags;
6139
6140         blkno = DIP(ip, i_db[i]);
6141         if (blkno == 0)
6142                 return;
6143         DIP_SET(ip, i_db[i], 0);
6144         ump = ITOUMP(ip);
6145         frags = sblksize(ump->um_fs, ip->i_size, i);
6146         frags = numfrags(ump->um_fs, frags);
6147         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6148 }
6149
6150 static inline void
6151 setup_freeext(freeblks, ip, i, needj)
6152         struct freeblks *freeblks;
6153         struct inode *ip;
6154         int i;
6155         int needj;
6156 {
6157         struct ufsmount *ump;
6158         ufs2_daddr_t blkno;
6159         int frags;
6160
6161         blkno = ip->i_din2->di_extb[i];
6162         if (blkno == 0)
6163                 return;
6164         ip->i_din2->di_extb[i] = 0;
6165         ump = ITOUMP(ip);
6166         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6167         frags = numfrags(ump->um_fs, frags);
6168         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6169 }
6170
6171 static inline void
6172 setup_freeindir(freeblks, ip, i, lbn, needj)
6173         struct freeblks *freeblks;
6174         struct inode *ip;
6175         int i;
6176         ufs_lbn_t lbn;
6177         int needj;
6178 {
6179         struct ufsmount *ump;
6180         ufs2_daddr_t blkno;
6181
6182         blkno = DIP(ip, i_ib[i]);
6183         if (blkno == 0)
6184                 return;
6185         DIP_SET(ip, i_ib[i], 0);
6186         ump = ITOUMP(ip);
6187         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6188             0, needj);
6189 }
6190
6191 static inline struct freeblks *
6192 newfreeblks(mp, ip)
6193         struct mount *mp;
6194         struct inode *ip;
6195 {
6196         struct freeblks *freeblks;
6197
6198         freeblks = malloc(sizeof(struct freeblks),
6199                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6200         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6201         LIST_INIT(&freeblks->fb_jblkdephd);
6202         LIST_INIT(&freeblks->fb_jwork);
6203         freeblks->fb_ref = 0;
6204         freeblks->fb_cgwait = 0;
6205         freeblks->fb_state = ATTACHED;
6206         freeblks->fb_uid = ip->i_uid;
6207         freeblks->fb_inum = ip->i_number;
6208         freeblks->fb_vtype = ITOV(ip)->v_type;
6209         freeblks->fb_modrev = DIP(ip, i_modrev);
6210         freeblks->fb_devvp = ITODEVVP(ip);
6211         freeblks->fb_chkcnt = 0;
6212         freeblks->fb_len = 0;
6213
6214         return (freeblks);
6215 }
6216
6217 static void
6218 trunc_indirdep(indirdep, freeblks, bp, off)
6219         struct indirdep *indirdep;
6220         struct freeblks *freeblks;
6221         struct buf *bp;
6222         int off;
6223 {
6224         struct allocindir *aip, *aipn;
6225
6226         /*
6227          * The first set of allocindirs won't be in savedbp.
6228          */
6229         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6230                 if (aip->ai_offset > off)
6231                         cancel_allocindir(aip, bp, freeblks, 1);
6232         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6233                 if (aip->ai_offset > off)
6234                         cancel_allocindir(aip, bp, freeblks, 1);
6235         /*
6236          * These will exist in savedbp.
6237          */
6238         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6239                 if (aip->ai_offset > off)
6240                         cancel_allocindir(aip, NULL, freeblks, 0);
6241         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6242                 if (aip->ai_offset > off)
6243                         cancel_allocindir(aip, NULL, freeblks, 0);
6244 }
6245
6246 /*
6247  * Follow the chain of indirects down to lastlbn creating a freework
6248  * structure for each.  This will be used to start indir_trunc() at
6249  * the right offset and create the journal records for the parrtial
6250  * truncation.  A second step will handle the truncated dependencies.
6251  */
6252 static int
6253 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6254         struct freeblks *freeblks;
6255         struct inode *ip;
6256         ufs_lbn_t lbn;
6257         ufs_lbn_t lastlbn;
6258         ufs2_daddr_t blkno;
6259 {
6260         struct indirdep *indirdep;
6261         struct indirdep *indirn;
6262         struct freework *freework;
6263         struct newblk *newblk;
6264         struct mount *mp;
6265         struct ufsmount *ump;
6266         struct buf *bp;
6267         uint8_t *start;
6268         uint8_t *end;
6269         ufs_lbn_t lbnadd;
6270         int level;
6271         int error;
6272         int off;
6273
6274
6275         freework = NULL;
6276         if (blkno == 0)
6277                 return (0);
6278         mp = freeblks->fb_list.wk_mp;
6279         ump = VFSTOUFS(mp);
6280         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6281         if ((bp->b_flags & B_CACHE) == 0) {
6282                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6283                 bp->b_iocmd = BIO_READ;
6284                 bp->b_flags &= ~B_INVAL;
6285                 bp->b_ioflags &= ~BIO_ERROR;
6286                 vfs_busy_pages(bp, 0);
6287                 bp->b_iooffset = dbtob(bp->b_blkno);
6288                 bstrategy(bp);
6289 #ifdef RACCT
6290                 if (racct_enable) {
6291                         PROC_LOCK(curproc);
6292                         racct_add_buf(curproc, bp, 0);
6293                         PROC_UNLOCK(curproc);
6294                 }
6295 #endif /* RACCT */
6296                 curthread->td_ru.ru_inblock++;
6297                 error = bufwait(bp);
6298                 if (error) {
6299                         brelse(bp);
6300                         return (error);
6301                 }
6302         }
6303         level = lbn_level(lbn);
6304         lbnadd = lbn_offset(ump->um_fs, level);
6305         /*
6306          * Compute the offset of the last block we want to keep.  Store
6307          * in the freework the first block we want to completely free.
6308          */
6309         off = (lastlbn - -(lbn + level)) / lbnadd;
6310         if (off + 1 == NINDIR(ump->um_fs))
6311                 goto nowork;
6312         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6313         /*
6314          * Link the freework into the indirdep.  This will prevent any new
6315          * allocations from proceeding until we are finished with the
6316          * truncate and the block is written.
6317          */
6318         ACQUIRE_LOCK(ump);
6319         indirdep = indirdep_lookup(mp, ip, bp);
6320         if (indirdep->ir_freeblks)
6321                 panic("setup_trunc_indir: indirdep already truncated.");
6322         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6323         freework->fw_indir = indirdep;
6324         /*
6325          * Cancel any allocindirs that will not make it to disk.
6326          * We have to do this for all copies of the indirdep that
6327          * live on this newblk.
6328          */
6329         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6330                 if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6331                     &newblk) == 0)
6332                         panic("setup_trunc_indir: lost block");
6333                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6334                         trunc_indirdep(indirn, freeblks, bp, off);
6335         } else
6336                 trunc_indirdep(indirdep, freeblks, bp, off);
6337         FREE_LOCK(ump);
6338         /*
6339          * Creation is protected by the buf lock. The saveddata is only
6340          * needed if a full truncation follows a partial truncation but it
6341          * is difficult to allocate in that case so we fetch it anyway.
6342          */
6343         if (indirdep->ir_saveddata == NULL)
6344                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6345                     M_SOFTDEP_FLAGS);
6346 nowork:
6347         /* Fetch the blkno of the child and the zero start offset. */
6348         if (I_IS_UFS1(ip)) {
6349                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6350                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6351         } else {
6352                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6353                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6354         }
6355         if (freework) {
6356                 /* Zero the truncated pointers. */
6357                 end = bp->b_data + bp->b_bcount;
6358                 bzero(start, end - start);
6359                 bdwrite(bp);
6360         } else
6361                 bqrelse(bp);
6362         if (level == 0)
6363                 return (0);
6364         lbn++; /* adjust level */
6365         lbn -= (off * lbnadd);
6366         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6367 }
6368
6369 /*
6370  * Complete the partial truncation of an indirect block setup by
6371  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6372  * copy and writes them to disk before the freeblks is allowed to complete.
6373  */
6374 static void
6375 complete_trunc_indir(freework)
6376         struct freework *freework;
6377 {
6378         struct freework *fwn;
6379         struct indirdep *indirdep;
6380         struct ufsmount *ump;
6381         struct buf *bp;
6382         uintptr_t start;
6383         int count;
6384
6385         ump = VFSTOUFS(freework->fw_list.wk_mp);
6386         LOCK_OWNED(ump);
6387         indirdep = freework->fw_indir;
6388         for (;;) {
6389                 bp = indirdep->ir_bp;
6390                 /* See if the block was discarded. */
6391                 if (bp == NULL)
6392                         break;
6393                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6394                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6395                         break;
6396                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6397                     LOCK_PTR(ump)) == 0)
6398                         BUF_UNLOCK(bp);
6399                 ACQUIRE_LOCK(ump);
6400         }
6401         freework->fw_state |= DEPCOMPLETE;
6402         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6403         /*
6404          * Zero the pointers in the saved copy.
6405          */
6406         if (indirdep->ir_state & UFS1FMT)
6407                 start = sizeof(ufs1_daddr_t);
6408         else
6409                 start = sizeof(ufs2_daddr_t);
6410         start *= freework->fw_start;
6411         count = indirdep->ir_savebp->b_bcount - start;
6412         start += (uintptr_t)indirdep->ir_savebp->b_data;
6413         bzero((char *)start, count);
6414         /*
6415          * We need to start the next truncation in the list if it has not
6416          * been started yet.
6417          */
6418         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6419         if (fwn != NULL) {
6420                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6421                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6422                 if ((fwn->fw_state & ONWORKLIST) == 0)
6423                         freework_enqueue(fwn);
6424         }
6425         /*
6426          * If bp is NULL the block was fully truncated, restore
6427          * the saved block list otherwise free it if it is no
6428          * longer needed.
6429          */
6430         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6431                 if (bp == NULL)
6432                         bcopy(indirdep->ir_saveddata,
6433                             indirdep->ir_savebp->b_data,
6434                             indirdep->ir_savebp->b_bcount);
6435                 free(indirdep->ir_saveddata, M_INDIRDEP);
6436                 indirdep->ir_saveddata = NULL;
6437         }
6438         /*
6439          * When bp is NULL there is a full truncation pending.  We
6440          * must wait for this full truncation to be journaled before
6441          * we can release this freework because the disk pointers will
6442          * never be written as zero.
6443          */
6444         if (bp == NULL)  {
6445                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6446                         handle_written_freework(freework);
6447                 else
6448                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6449                            &freework->fw_list);
6450         } else {
6451                 /* Complete when the real copy is written. */
6452                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6453                 BUF_UNLOCK(bp);
6454         }
6455 }
6456
6457 /*
6458  * Calculate the number of blocks we are going to release where datablocks
6459  * is the current total and length is the new file size.
6460  */
6461 static ufs2_daddr_t
6462 blkcount(fs, datablocks, length)
6463         struct fs *fs;
6464         ufs2_daddr_t datablocks;
6465         off_t length;
6466 {
6467         off_t totblks, numblks;
6468
6469         totblks = 0;
6470         numblks = howmany(length, fs->fs_bsize);
6471         if (numblks <= UFS_NDADDR) {
6472                 totblks = howmany(length, fs->fs_fsize);
6473                 goto out;
6474         }
6475         totblks = blkstofrags(fs, numblks);
6476         numblks -= UFS_NDADDR;
6477         /*
6478          * Count all single, then double, then triple indirects required.
6479          * Subtracting one indirects worth of blocks for each pass
6480          * acknowledges one of each pointed to by the inode.
6481          */
6482         for (;;) {
6483                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6484                 numblks -= NINDIR(fs);
6485                 if (numblks <= 0)
6486                         break;
6487                 numblks = howmany(numblks, NINDIR(fs));
6488         }
6489 out:
6490         totblks = fsbtodb(fs, totblks);
6491         /*
6492          * Handle sparse files.  We can't reclaim more blocks than the inode
6493          * references.  We will correct it later in handle_complete_freeblks()
6494          * when we know the real count.
6495          */
6496         if (totblks > datablocks)
6497                 return (0);
6498         return (datablocks - totblks);
6499 }
6500
6501 /*
6502  * Handle freeblocks for journaled softupdate filesystems.
6503  *
6504  * Contrary to normal softupdates, we must preserve the block pointers in
6505  * indirects until their subordinates are free.  This is to avoid journaling
6506  * every block that is freed which may consume more space than the journal
6507  * itself.  The recovery program will see the free block journals at the
6508  * base of the truncated area and traverse them to reclaim space.  The
6509  * pointers in the inode may be cleared immediately after the journal
6510  * records are written because each direct and indirect pointer in the
6511  * inode is recorded in a journal.  This permits full truncation to proceed
6512  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6513  *
6514  * The algorithm is as follows:
6515  * 1) Traverse the in-memory state and create journal entries to release
6516  *    the relevant blocks and full indirect trees.
6517  * 2) Traverse the indirect block chain adding partial truncation freework
6518  *    records to indirects in the path to lastlbn.  The freework will
6519  *    prevent new allocation dependencies from being satisfied in this
6520  *    indirect until the truncation completes.
6521  * 3) Read and lock the inode block, performing an update with the new size
6522  *    and pointers.  This prevents truncated data from becoming valid on
6523  *    disk through step 4.
6524  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6525  *    eliminate journal work for those records that do not require it.
6526  * 5) Schedule the journal records to be written followed by the inode block.
6527  * 6) Allocate any necessary frags for the end of file.
6528  * 7) Zero any partially truncated blocks.
6529  *
6530  * From this truncation proceeds asynchronously using the freework and
6531  * indir_trunc machinery.  The file will not be extended again into a
6532  * partially truncated indirect block until all work is completed but
6533  * the normal dependency mechanism ensures that it is rolled back/forward
6534  * as appropriate.  Further truncation may occur without delay and is
6535  * serialized in indir_trunc().
6536  */
6537 void
6538 softdep_journal_freeblocks(ip, cred, length, flags)
6539         struct inode *ip;       /* The inode whose length is to be reduced */
6540         struct ucred *cred;
6541         off_t length;           /* The new length for the file */
6542         int flags;              /* IO_EXT and/or IO_NORMAL */
6543 {
6544         struct freeblks *freeblks, *fbn;
6545         struct worklist *wk, *wkn;
6546         struct inodedep *inodedep;
6547         struct jblkdep *jblkdep;
6548         struct allocdirect *adp, *adpn;
6549         struct ufsmount *ump;
6550         struct fs *fs;
6551         struct buf *bp;
6552         struct vnode *vp;
6553         struct mount *mp;
6554         ufs2_daddr_t extblocks, datablocks;
6555         ufs_lbn_t tmpval, lbn, lastlbn;
6556         int frags, lastoff, iboff, allocblock, needj, error, i;
6557
6558         ump = ITOUMP(ip);
6559         mp = UFSTOVFS(ump);
6560         fs = ump->um_fs;
6561         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6562             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6563         vp = ITOV(ip);
6564         needj = 1;
6565         iboff = -1;
6566         allocblock = 0;
6567         extblocks = 0;
6568         datablocks = 0;
6569         frags = 0;
6570         freeblks = newfreeblks(mp, ip);
6571         ACQUIRE_LOCK(ump);
6572         /*
6573          * If we're truncating a removed file that will never be written
6574          * we don't need to journal the block frees.  The canceled journals
6575          * for the allocations will suffice.
6576          */
6577         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6578         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6579             length == 0)
6580                 needj = 0;
6581         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6582             ip->i_number, length, needj);
6583         FREE_LOCK(ump);
6584         /*
6585          * Calculate the lbn that we are truncating to.  This results in -1
6586          * if we're truncating the 0 bytes.  So it is the last lbn we want
6587          * to keep, not the first lbn we want to truncate.
6588          */
6589         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6590         lastoff = blkoff(fs, length);
6591         /*
6592          * Compute frags we are keeping in lastlbn.  0 means all.
6593          */
6594         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6595                 frags = fragroundup(fs, lastoff);
6596                 /* adp offset of last valid allocdirect. */
6597                 iboff = lastlbn;
6598         } else if (lastlbn > 0)
6599                 iboff = UFS_NDADDR;
6600         if (fs->fs_magic == FS_UFS2_MAGIC)
6601                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6602         /*
6603          * Handle normal data blocks and indirects.  This section saves
6604          * values used after the inode update to complete frag and indirect
6605          * truncation.
6606          */
6607         if ((flags & IO_NORMAL) != 0) {
6608                 /*
6609                  * Handle truncation of whole direct and indirect blocks.
6610                  */
6611                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6612                         setup_freedirect(freeblks, ip, i, needj);
6613                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6614                     i < UFS_NIADDR;
6615                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6616                         /* Release a whole indirect tree. */
6617                         if (lbn > lastlbn) {
6618                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6619                                     needj);
6620                                 continue;
6621                         }
6622                         iboff = i + UFS_NDADDR;
6623                         /*
6624                          * Traverse partially truncated indirect tree.
6625                          */
6626                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6627                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6628                                     lastlbn, DIP(ip, i_ib[i]));
6629                 }
6630                 /*
6631                  * Handle partial truncation to a frag boundary.
6632                  */
6633                 if (frags) {
6634                         ufs2_daddr_t blkno;
6635                         long oldfrags;
6636
6637                         oldfrags = blksize(fs, ip, lastlbn);
6638                         blkno = DIP(ip, i_db[lastlbn]);
6639                         if (blkno && oldfrags != frags) {
6640                                 oldfrags -= frags;
6641                                 oldfrags = numfrags(fs, oldfrags);
6642                                 blkno += numfrags(fs, frags);
6643                                 newfreework(ump, freeblks, NULL, lastlbn,
6644                                     blkno, oldfrags, 0, needj);
6645                                 if (needj)
6646                                         adjust_newfreework(freeblks,
6647                                             numfrags(fs, frags));
6648                         } else if (blkno == 0)
6649                                 allocblock = 1;
6650                 }
6651                 /*
6652                  * Add a journal record for partial truncate if we are
6653                  * handling indirect blocks.  Non-indirects need no extra
6654                  * journaling.
6655                  */
6656                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6657                         ip->i_flag |= IN_TRUNCATED;
6658                         newjtrunc(freeblks, length, 0);
6659                 }
6660                 ip->i_size = length;
6661                 DIP_SET(ip, i_size, ip->i_size);
6662                 datablocks = DIP(ip, i_blocks) - extblocks;
6663                 if (length != 0)
6664                         datablocks = blkcount(fs, datablocks, length);
6665                 freeblks->fb_len = length;
6666         }
6667         if ((flags & IO_EXT) != 0) {
6668                 for (i = 0; i < UFS_NXADDR; i++)
6669                         setup_freeext(freeblks, ip, i, needj);
6670                 ip->i_din2->di_extsize = 0;
6671                 datablocks += extblocks;
6672         }
6673 #ifdef QUOTA
6674         /* Reference the quotas in case the block count is wrong in the end. */
6675         quotaref(vp, freeblks->fb_quota);
6676         (void) chkdq(ip, -datablocks, NOCRED, 0);
6677 #endif
6678         freeblks->fb_chkcnt = -datablocks;
6679         UFS_LOCK(ump);
6680         fs->fs_pendingblocks += datablocks;
6681         UFS_UNLOCK(ump);
6682         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6683         /*
6684          * Handle truncation of incomplete alloc direct dependencies.  We
6685          * hold the inode block locked to prevent incomplete dependencies
6686          * from reaching the disk while we are eliminating those that
6687          * have been truncated.  This is a partially inlined ffs_update().
6688          */
6689         ufs_itimes(vp);
6690         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6691         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6692             (int)fs->fs_bsize, cred, &bp);
6693         if (error) {
6694                 brelse(bp);
6695                 softdep_error("softdep_journal_freeblocks", error);
6696                 return;
6697         }
6698         if (bp->b_bufsize == fs->fs_bsize)
6699                 bp->b_flags |= B_CLUSTEROK;
6700         softdep_update_inodeblock(ip, bp, 0);
6701         if (ump->um_fstype == UFS1)
6702                 *((struct ufs1_dinode *)bp->b_data +
6703                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6704         else
6705                 *((struct ufs2_dinode *)bp->b_data +
6706                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6707         ACQUIRE_LOCK(ump);
6708         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6709         if ((inodedep->id_state & IOSTARTED) != 0)
6710                 panic("softdep_setup_freeblocks: inode busy");
6711         /*
6712          * Add the freeblks structure to the list of operations that
6713          * must await the zero'ed inode being written to disk. If we
6714          * still have a bitmap dependency (needj), then the inode
6715          * has never been written to disk, so we can process the
6716          * freeblks below once we have deleted the dependencies.
6717          */
6718         if (needj)
6719                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6720         else
6721                 freeblks->fb_state |= COMPLETE;
6722         if ((flags & IO_NORMAL) != 0) {
6723                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6724                         if (adp->ad_offset > iboff)
6725                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6726                                     freeblks);
6727                         /*
6728                          * Truncate the allocdirect.  We could eliminate
6729                          * or modify journal records as well.
6730                          */
6731                         else if (adp->ad_offset == iboff && frags)
6732                                 adp->ad_newsize = frags;
6733                 }
6734         }
6735         if ((flags & IO_EXT) != 0)
6736                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6737                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6738                             freeblks);
6739         /*
6740          * Scan the bufwait list for newblock dependencies that will never
6741          * make it to disk.
6742          */
6743         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6744                 if (wk->wk_type != D_ALLOCDIRECT)
6745                         continue;
6746                 adp = WK_ALLOCDIRECT(wk);
6747                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6748                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6749                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6750                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6751                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6752                 }
6753         }
6754         /*
6755          * Add journal work.
6756          */
6757         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6758                 add_to_journal(&jblkdep->jb_list);
6759         FREE_LOCK(ump);
6760         bdwrite(bp);
6761         /*
6762          * Truncate dependency structures beyond length.
6763          */
6764         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6765         /*
6766          * This is only set when we need to allocate a fragment because
6767          * none existed at the end of a frag-sized file.  It handles only
6768          * allocating a new, zero filled block.
6769          */
6770         if (allocblock) {
6771                 ip->i_size = length - lastoff;
6772                 DIP_SET(ip, i_size, ip->i_size);
6773                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6774                 if (error != 0) {
6775                         softdep_error("softdep_journal_freeblks", error);
6776                         return;
6777                 }
6778                 ip->i_size = length;
6779                 DIP_SET(ip, i_size, length);
6780                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6781                 allocbuf(bp, frags);
6782                 ffs_update(vp, 0);
6783                 bawrite(bp);
6784         } else if (lastoff != 0 && vp->v_type != VDIR) {
6785                 int size;
6786
6787                 /*
6788                  * Zero the end of a truncated frag or block.
6789                  */
6790                 size = sblksize(fs, length, lastlbn);
6791                 error = bread(vp, lastlbn, size, cred, &bp);
6792                 if (error) {
6793                         softdep_error("softdep_journal_freeblks", error);
6794                         return;
6795                 }
6796                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6797                 bawrite(bp);
6798
6799         }
6800         ACQUIRE_LOCK(ump);
6801         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6802         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6803         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6804         /*
6805          * We zero earlier truncations so they don't erroneously
6806          * update i_blocks.
6807          */
6808         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6809                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6810                         fbn->fb_len = 0;
6811         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6812             LIST_EMPTY(&freeblks->fb_jblkdephd))
6813                 freeblks->fb_state |= INPROGRESS;
6814         else
6815                 freeblks = NULL;
6816         FREE_LOCK(ump);
6817         if (freeblks)
6818                 handle_workitem_freeblocks(freeblks, 0);
6819         trunc_pages(ip, length, extblocks, flags);
6820
6821 }
6822
6823 /*
6824  * Flush a JOP_SYNC to the journal.
6825  */
6826 void
6827 softdep_journal_fsync(ip)
6828         struct inode *ip;
6829 {
6830         struct jfsync *jfsync;
6831         struct ufsmount *ump;
6832
6833         ump = ITOUMP(ip);
6834         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6835             ("softdep_journal_fsync called on non-softdep filesystem"));
6836         if ((ip->i_flag & IN_TRUNCATED) == 0)
6837                 return;
6838         ip->i_flag &= ~IN_TRUNCATED;
6839         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6840         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6841         jfsync->jfs_size = ip->i_size;
6842         jfsync->jfs_ino = ip->i_number;
6843         ACQUIRE_LOCK(ump);
6844         add_to_journal(&jfsync->jfs_list);
6845         jwait(&jfsync->jfs_list, MNT_WAIT);
6846         FREE_LOCK(ump);
6847 }
6848
6849 /*
6850  * Block de-allocation dependencies.
6851  * 
6852  * When blocks are de-allocated, the on-disk pointers must be nullified before
6853  * the blocks are made available for use by other files.  (The true
6854  * requirement is that old pointers must be nullified before new on-disk
6855  * pointers are set.  We chose this slightly more stringent requirement to
6856  * reduce complexity.) Our implementation handles this dependency by updating
6857  * the inode (or indirect block) appropriately but delaying the actual block
6858  * de-allocation (i.e., freemap and free space count manipulation) until
6859  * after the updated versions reach stable storage.  After the disk is
6860  * updated, the blocks can be safely de-allocated whenever it is convenient.
6861  * This implementation handles only the common case of reducing a file's
6862  * length to zero. Other cases are handled by the conventional synchronous
6863  * write approach.
6864  *
6865  * The ffs implementation with which we worked double-checks
6866  * the state of the block pointers and file size as it reduces
6867  * a file's length.  Some of this code is replicated here in our
6868  * soft updates implementation.  The freeblks->fb_chkcnt field is
6869  * used to transfer a part of this information to the procedure
6870  * that eventually de-allocates the blocks.
6871  *
6872  * This routine should be called from the routine that shortens
6873  * a file's length, before the inode's size or block pointers
6874  * are modified. It will save the block pointer information for
6875  * later release and zero the inode so that the calling routine
6876  * can release it.
6877  */
6878 void
6879 softdep_setup_freeblocks(ip, length, flags)
6880         struct inode *ip;       /* The inode whose length is to be reduced */
6881         off_t length;           /* The new length for the file */
6882         int flags;              /* IO_EXT and/or IO_NORMAL */
6883 {
6884         struct ufs1_dinode *dp1;
6885         struct ufs2_dinode *dp2;
6886         struct freeblks *freeblks;
6887         struct inodedep *inodedep;
6888         struct allocdirect *adp;
6889         struct ufsmount *ump;
6890         struct buf *bp;
6891         struct fs *fs;
6892         ufs2_daddr_t extblocks, datablocks;
6893         struct mount *mp;
6894         int i, delay, error;
6895         ufs_lbn_t tmpval;
6896         ufs_lbn_t lbn;
6897
6898         ump = ITOUMP(ip);
6899         mp = UFSTOVFS(ump);
6900         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6901             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6902         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6903             ip->i_number, length);
6904         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6905         fs = ump->um_fs;
6906         if ((error = bread(ump->um_devvp,
6907             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6908             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6909                 brelse(bp);
6910                 softdep_error("softdep_setup_freeblocks", error);
6911                 return;
6912         }
6913         freeblks = newfreeblks(mp, ip);
6914         extblocks = 0;
6915         datablocks = 0;
6916         if (fs->fs_magic == FS_UFS2_MAGIC)
6917                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6918         if ((flags & IO_NORMAL) != 0) {
6919                 for (i = 0; i < UFS_NDADDR; i++)
6920                         setup_freedirect(freeblks, ip, i, 0);
6921                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6922                     i < UFS_NIADDR;
6923                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6924                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6925                 ip->i_size = 0;
6926                 DIP_SET(ip, i_size, 0);
6927                 datablocks = DIP(ip, i_blocks) - extblocks;
6928         }
6929         if ((flags & IO_EXT) != 0) {
6930                 for (i = 0; i < UFS_NXADDR; i++)
6931                         setup_freeext(freeblks, ip, i, 0);
6932                 ip->i_din2->di_extsize = 0;
6933                 datablocks += extblocks;
6934         }
6935 #ifdef QUOTA
6936         /* Reference the quotas in case the block count is wrong in the end. */
6937         quotaref(ITOV(ip), freeblks->fb_quota);
6938         (void) chkdq(ip, -datablocks, NOCRED, 0);
6939 #endif
6940         freeblks->fb_chkcnt = -datablocks;
6941         UFS_LOCK(ump);
6942         fs->fs_pendingblocks += datablocks;
6943         UFS_UNLOCK(ump);
6944         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6945         /*
6946          * Push the zero'ed inode to its disk buffer so that we are free
6947          * to delete its dependencies below. Once the dependencies are gone
6948          * the buffer can be safely released.
6949          */
6950         if (ump->um_fstype == UFS1) {
6951                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6952                     ino_to_fsbo(fs, ip->i_number));
6953                 ip->i_din1->di_freelink = dp1->di_freelink;
6954                 *dp1 = *ip->i_din1;
6955         } else {
6956                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6957                     ino_to_fsbo(fs, ip->i_number));
6958                 ip->i_din2->di_freelink = dp2->di_freelink;
6959                 *dp2 = *ip->i_din2;
6960         }
6961         /*
6962          * Find and eliminate any inode dependencies.
6963          */
6964         ACQUIRE_LOCK(ump);
6965         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6966         if ((inodedep->id_state & IOSTARTED) != 0)
6967                 panic("softdep_setup_freeblocks: inode busy");
6968         /*
6969          * Add the freeblks structure to the list of operations that
6970          * must await the zero'ed inode being written to disk. If we
6971          * still have a bitmap dependency (delay == 0), then the inode
6972          * has never been written to disk, so we can process the
6973          * freeblks below once we have deleted the dependencies.
6974          */
6975         delay = (inodedep->id_state & DEPCOMPLETE);
6976         if (delay)
6977                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6978         else
6979                 freeblks->fb_state |= COMPLETE;
6980         /*
6981          * Because the file length has been truncated to zero, any
6982          * pending block allocation dependency structures associated
6983          * with this inode are obsolete and can simply be de-allocated.
6984          * We must first merge the two dependency lists to get rid of
6985          * any duplicate freefrag structures, then purge the merged list.
6986          * If we still have a bitmap dependency, then the inode has never
6987          * been written to disk, so we can free any fragments without delay.
6988          */
6989         if (flags & IO_NORMAL) {
6990                 merge_inode_lists(&inodedep->id_newinoupdt,
6991                     &inodedep->id_inoupdt);
6992                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6993                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6994                             freeblks);
6995         }
6996         if (flags & IO_EXT) {
6997                 merge_inode_lists(&inodedep->id_newextupdt,
6998                     &inodedep->id_extupdt);
6999                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7000                         cancel_allocdirect(&inodedep->id_extupdt, adp,
7001                             freeblks);
7002         }
7003         FREE_LOCK(ump);
7004         bdwrite(bp);
7005         trunc_dependencies(ip, freeblks, -1, 0, flags);
7006         ACQUIRE_LOCK(ump);
7007         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7008                 (void) free_inodedep(inodedep);
7009         freeblks->fb_state |= DEPCOMPLETE;
7010         /*
7011          * If the inode with zeroed block pointers is now on disk
7012          * we can start freeing blocks.
7013          */  
7014         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7015                 freeblks->fb_state |= INPROGRESS;
7016         else
7017                 freeblks = NULL;
7018         FREE_LOCK(ump);
7019         if (freeblks)
7020                 handle_workitem_freeblocks(freeblks, 0);
7021         trunc_pages(ip, length, extblocks, flags);
7022 }
7023
7024 /*
7025  * Eliminate pages from the page cache that back parts of this inode and
7026  * adjust the vnode pager's idea of our size.  This prevents stale data
7027  * from hanging around in the page cache.
7028  */
7029 static void
7030 trunc_pages(ip, length, extblocks, flags)
7031         struct inode *ip;
7032         off_t length;
7033         ufs2_daddr_t extblocks;
7034         int flags;
7035 {
7036         struct vnode *vp;
7037         struct fs *fs;
7038         ufs_lbn_t lbn;
7039         off_t end, extend;
7040
7041         vp = ITOV(ip);
7042         fs = ITOFS(ip);
7043         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7044         if ((flags & IO_EXT) != 0)
7045                 vn_pages_remove(vp, extend, 0);
7046         if ((flags & IO_NORMAL) == 0)
7047                 return;
7048         BO_LOCK(&vp->v_bufobj);
7049         drain_output(vp);
7050         BO_UNLOCK(&vp->v_bufobj);
7051         /*
7052          * The vnode pager eliminates file pages we eliminate indirects
7053          * below.
7054          */
7055         vnode_pager_setsize(vp, length);
7056         /*
7057          * Calculate the end based on the last indirect we want to keep.  If
7058          * the block extends into indirects we can just use the negative of
7059          * its lbn.  Doubles and triples exist at lower numbers so we must
7060          * be careful not to remove those, if they exist.  double and triple
7061          * indirect lbns do not overlap with others so it is not important
7062          * to verify how many levels are required.
7063          */
7064         lbn = lblkno(fs, length);
7065         if (lbn >= UFS_NDADDR) {
7066                 /* Calculate the virtual lbn of the triple indirect. */
7067                 lbn = -lbn - (UFS_NIADDR - 1);
7068                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7069         } else
7070                 end = extend;
7071         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7072 }
7073
7074 /*
7075  * See if the buf bp is in the range eliminated by truncation.
7076  */
7077 static int
7078 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7079         struct buf *bp;
7080         int *blkoffp;
7081         ufs_lbn_t lastlbn;
7082         int lastoff;
7083         int flags;
7084 {
7085         ufs_lbn_t lbn;
7086
7087         *blkoffp = 0;
7088         /* Only match ext/normal blocks as appropriate. */
7089         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7090             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7091                 return (0);
7092         /* ALTDATA is always a full truncation. */
7093         if ((bp->b_xflags & BX_ALTDATA) != 0)
7094                 return (1);
7095         /* -1 is full truncation. */
7096         if (lastlbn == -1)
7097                 return (1);
7098         /*
7099          * If this is a partial truncate we only want those
7100          * blocks and indirect blocks that cover the range
7101          * we're after.
7102          */
7103         lbn = bp->b_lblkno;
7104         if (lbn < 0)
7105                 lbn = -(lbn + lbn_level(lbn));
7106         if (lbn < lastlbn)
7107                 return (0);
7108         /* Here we only truncate lblkno if it's partial. */
7109         if (lbn == lastlbn) {
7110                 if (lastoff == 0)
7111                         return (0);
7112                 *blkoffp = lastoff;
7113         }
7114         return (1);
7115 }
7116
7117 /*
7118  * Eliminate any dependencies that exist in memory beyond lblkno:off
7119  */
7120 static void
7121 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7122         struct inode *ip;
7123         struct freeblks *freeblks;
7124         ufs_lbn_t lastlbn;
7125         int lastoff;
7126         int flags;
7127 {
7128         struct bufobj *bo;
7129         struct vnode *vp;
7130         struct buf *bp;
7131         int blkoff;
7132
7133         /*
7134          * We must wait for any I/O in progress to finish so that
7135          * all potential buffers on the dirty list will be visible.
7136          * Once they are all there, walk the list and get rid of
7137          * any dependencies.
7138          */
7139         vp = ITOV(ip);
7140         bo = &vp->v_bufobj;
7141         BO_LOCK(bo);
7142         drain_output(vp);
7143         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7144                 bp->b_vflags &= ~BV_SCANNED;
7145 restart:
7146         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7147                 if (bp->b_vflags & BV_SCANNED)
7148                         continue;
7149                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7150                         bp->b_vflags |= BV_SCANNED;
7151                         continue;
7152                 }
7153                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7154                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7155                         goto restart;
7156                 BO_UNLOCK(bo);
7157                 if (deallocate_dependencies(bp, freeblks, blkoff))
7158                         bqrelse(bp);
7159                 else
7160                         brelse(bp);
7161                 BO_LOCK(bo);
7162                 goto restart;
7163         }
7164         /*
7165          * Now do the work of vtruncbuf while also matching indirect blocks.
7166          */
7167         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7168                 bp->b_vflags &= ~BV_SCANNED;
7169 cleanrestart:
7170         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7171                 if (bp->b_vflags & BV_SCANNED)
7172                         continue;
7173                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7174                         bp->b_vflags |= BV_SCANNED;
7175                         continue;
7176                 }
7177                 if (BUF_LOCK(bp,
7178                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7179                     BO_LOCKPTR(bo)) == ENOLCK) {
7180                         BO_LOCK(bo);
7181                         goto cleanrestart;
7182                 }
7183                 bp->b_vflags |= BV_SCANNED;
7184                 bremfree(bp);
7185                 if (blkoff != 0) {
7186                         allocbuf(bp, blkoff);
7187                         bqrelse(bp);
7188                 } else {
7189                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7190                         brelse(bp);
7191                 }
7192                 BO_LOCK(bo);
7193                 goto cleanrestart;
7194         }
7195         drain_output(vp);
7196         BO_UNLOCK(bo);
7197 }
7198
7199 static int
7200 cancel_pagedep(pagedep, freeblks, blkoff)
7201         struct pagedep *pagedep;
7202         struct freeblks *freeblks;
7203         int blkoff;
7204 {
7205         struct jremref *jremref;
7206         struct jmvref *jmvref;
7207         struct dirrem *dirrem, *tmp;
7208         int i;
7209
7210         /*
7211          * Copy any directory remove dependencies to the list
7212          * to be processed after the freeblks proceeds.  If
7213          * directory entry never made it to disk they
7214          * can be dumped directly onto the work list.
7215          */
7216         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7217                 /* Skip this directory removal if it is intended to remain. */
7218                 if (dirrem->dm_offset < blkoff)
7219                         continue;
7220                 /*
7221                  * If there are any dirrems we wait for the journal write
7222                  * to complete and then restart the buf scan as the lock
7223                  * has been dropped.
7224                  */
7225                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7226                         jwait(&jremref->jr_list, MNT_WAIT);
7227                         return (ERESTART);
7228                 }
7229                 LIST_REMOVE(dirrem, dm_next);
7230                 dirrem->dm_dirinum = pagedep->pd_ino;
7231                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7232         }
7233         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7234                 jwait(&jmvref->jm_list, MNT_WAIT);
7235                 return (ERESTART);
7236         }
7237         /*
7238          * When we're partially truncating a pagedep we just want to flush
7239          * journal entries and return.  There can not be any adds in the
7240          * truncated portion of the directory and newblk must remain if
7241          * part of the block remains.
7242          */
7243         if (blkoff != 0) {
7244                 struct diradd *dap;
7245
7246                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7247                         if (dap->da_offset > blkoff)
7248                                 panic("cancel_pagedep: diradd %p off %d > %d",
7249                                     dap, dap->da_offset, blkoff);
7250                 for (i = 0; i < DAHASHSZ; i++)
7251                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7252                                 if (dap->da_offset > blkoff)
7253                                         panic("cancel_pagedep: diradd %p off %d > %d",
7254                                             dap, dap->da_offset, blkoff);
7255                 return (0);
7256         }
7257         /*
7258          * There should be no directory add dependencies present
7259          * as the directory could not be truncated until all
7260          * children were removed.
7261          */
7262         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7263             ("deallocate_dependencies: pendinghd != NULL"));
7264         for (i = 0; i < DAHASHSZ; i++)
7265                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7266                     ("deallocate_dependencies: diraddhd != NULL"));
7267         if ((pagedep->pd_state & NEWBLOCK) != 0)
7268                 free_newdirblk(pagedep->pd_newdirblk);
7269         if (free_pagedep(pagedep) == 0)
7270                 panic("Failed to free pagedep %p", pagedep);
7271         return (0);
7272 }
7273
7274 /*
7275  * Reclaim any dependency structures from a buffer that is about to
7276  * be reallocated to a new vnode. The buffer must be locked, thus,
7277  * no I/O completion operations can occur while we are manipulating
7278  * its associated dependencies. The mutex is held so that other I/O's
7279  * associated with related dependencies do not occur.
7280  */
7281 static int
7282 deallocate_dependencies(bp, freeblks, off)
7283         struct buf *bp;
7284         struct freeblks *freeblks;
7285         int off;
7286 {
7287         struct indirdep *indirdep;
7288         struct pagedep *pagedep;
7289         struct worklist *wk, *wkn;
7290         struct ufsmount *ump;
7291
7292         ump = softdep_bp_to_mp(bp);
7293         if (ump == NULL)
7294                 goto done;
7295         ACQUIRE_LOCK(ump);
7296         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7297                 switch (wk->wk_type) {
7298                 case D_INDIRDEP:
7299                         indirdep = WK_INDIRDEP(wk);
7300                         if (bp->b_lblkno >= 0 ||
7301                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7302                                 panic("deallocate_dependencies: not indir");
7303                         cancel_indirdep(indirdep, bp, freeblks);
7304                         continue;
7305
7306                 case D_PAGEDEP:
7307                         pagedep = WK_PAGEDEP(wk);
7308                         if (cancel_pagedep(pagedep, freeblks, off)) {
7309                                 FREE_LOCK(ump);
7310                                 return (ERESTART);
7311                         }
7312                         continue;
7313
7314                 case D_ALLOCINDIR:
7315                         /*
7316                          * Simply remove the allocindir, we'll find it via
7317                          * the indirdep where we can clear pointers if
7318                          * needed.
7319                          */
7320                         WORKLIST_REMOVE(wk);
7321                         continue;
7322
7323                 case D_FREEWORK:
7324                         /*
7325                          * A truncation is waiting for the zero'd pointers
7326                          * to be written.  It can be freed when the freeblks
7327                          * is journaled.
7328                          */
7329                         WORKLIST_REMOVE(wk);
7330                         wk->wk_state |= ONDEPLIST;
7331                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7332                         break;
7333
7334                 case D_ALLOCDIRECT:
7335                         if (off != 0)
7336                                 continue;
7337                         /* FALLTHROUGH */
7338                 default:
7339                         panic("deallocate_dependencies: Unexpected type %s",
7340                             TYPENAME(wk->wk_type));
7341                         /* NOTREACHED */
7342                 }
7343         }
7344         FREE_LOCK(ump);
7345 done:
7346         /*
7347          * Don't throw away this buf, we were partially truncating and
7348          * some deps may always remain.
7349          */
7350         if (off) {
7351                 allocbuf(bp, off);
7352                 bp->b_vflags |= BV_SCANNED;
7353                 return (EBUSY);
7354         }
7355         bp->b_flags |= B_INVAL | B_NOCACHE;
7356
7357         return (0);
7358 }
7359
7360 /*
7361  * An allocdirect is being canceled due to a truncate.  We must make sure
7362  * the journal entry is released in concert with the blkfree that releases
7363  * the storage.  Completed journal entries must not be released until the
7364  * space is no longer pointed to by the inode or in the bitmap.
7365  */
7366 static void
7367 cancel_allocdirect(adphead, adp, freeblks)
7368         struct allocdirectlst *adphead;
7369         struct allocdirect *adp;
7370         struct freeblks *freeblks;
7371 {
7372         struct freework *freework;
7373         struct newblk *newblk;
7374         struct worklist *wk;
7375
7376         TAILQ_REMOVE(adphead, adp, ad_next);
7377         newblk = (struct newblk *)adp;
7378         freework = NULL;
7379         /*
7380          * Find the correct freework structure.
7381          */
7382         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7383                 if (wk->wk_type != D_FREEWORK)
7384                         continue;
7385                 freework = WK_FREEWORK(wk);
7386                 if (freework->fw_blkno == newblk->nb_newblkno)
7387                         break;
7388         }
7389         if (freework == NULL)
7390                 panic("cancel_allocdirect: Freework not found");
7391         /*
7392          * If a newblk exists at all we still have the journal entry that
7393          * initiated the allocation so we do not need to journal the free.
7394          */
7395         cancel_jfreeblk(freeblks, freework->fw_blkno);
7396         /*
7397          * If the journal hasn't been written the jnewblk must be passed
7398          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7399          * this by linking the journal dependency into the freework to be
7400          * freed when freework_freeblock() is called.  If the journal has
7401          * been written we can simply reclaim the journal space when the
7402          * freeblks work is complete.
7403          */
7404         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7405             &freeblks->fb_jwork);
7406         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7407 }
7408
7409
7410 /*
7411  * Cancel a new block allocation.  May be an indirect or direct block.  We
7412  * remove it from various lists and return any journal record that needs to
7413  * be resolved by the caller.
7414  *
7415  * A special consideration is made for indirects which were never pointed
7416  * at on disk and will never be found once this block is released.
7417  */
7418 static struct jnewblk *
7419 cancel_newblk(newblk, wk, wkhd)
7420         struct newblk *newblk;
7421         struct worklist *wk;
7422         struct workhead *wkhd;
7423 {
7424         struct jnewblk *jnewblk;
7425
7426         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7427             
7428         newblk->nb_state |= GOINGAWAY;
7429         /*
7430          * Previously we traversed the completedhd on each indirdep
7431          * attached to this newblk to cancel them and gather journal
7432          * work.  Since we need only the oldest journal segment and
7433          * the lowest point on the tree will always have the oldest
7434          * journal segment we are free to release the segments
7435          * of any subordinates and may leave the indirdep list to
7436          * indirdep_complete() when this newblk is freed.
7437          */
7438         if (newblk->nb_state & ONDEPLIST) {
7439                 newblk->nb_state &= ~ONDEPLIST;
7440                 LIST_REMOVE(newblk, nb_deps);
7441         }
7442         if (newblk->nb_state & ONWORKLIST)
7443                 WORKLIST_REMOVE(&newblk->nb_list);
7444         /*
7445          * If the journal entry hasn't been written we save a pointer to
7446          * the dependency that frees it until it is written or the
7447          * superseding operation completes.
7448          */
7449         jnewblk = newblk->nb_jnewblk;
7450         if (jnewblk != NULL && wk != NULL) {
7451                 newblk->nb_jnewblk = NULL;
7452                 jnewblk->jn_dep = wk;
7453         }
7454         if (!LIST_EMPTY(&newblk->nb_jwork))
7455                 jwork_move(wkhd, &newblk->nb_jwork);
7456         /*
7457          * When truncating we must free the newdirblk early to remove
7458          * the pagedep from the hash before returning.
7459          */
7460         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7461                 free_newdirblk(WK_NEWDIRBLK(wk));
7462         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7463                 panic("cancel_newblk: extra newdirblk");
7464
7465         return (jnewblk);
7466 }
7467
7468 /*
7469  * Schedule the freefrag associated with a newblk to be released once
7470  * the pointers are written and the previous block is no longer needed.
7471  */
7472 static void
7473 newblk_freefrag(newblk)
7474         struct newblk *newblk;
7475 {
7476         struct freefrag *freefrag;
7477
7478         if (newblk->nb_freefrag == NULL)
7479                 return;
7480         freefrag = newblk->nb_freefrag;
7481         newblk->nb_freefrag = NULL;
7482         freefrag->ff_state |= COMPLETE;
7483         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7484                 add_to_worklist(&freefrag->ff_list, 0);
7485 }
7486
7487 /*
7488  * Free a newblk. Generate a new freefrag work request if appropriate.
7489  * This must be called after the inode pointer and any direct block pointers
7490  * are valid or fully removed via truncate or frag extension.
7491  */
7492 static void
7493 free_newblk(newblk)
7494         struct newblk *newblk;
7495 {
7496         struct indirdep *indirdep;
7497         struct worklist *wk;
7498
7499         KASSERT(newblk->nb_jnewblk == NULL,
7500             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7501         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7502             ("free_newblk: unclaimed newblk"));
7503         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7504         newblk_freefrag(newblk);
7505         if (newblk->nb_state & ONDEPLIST)
7506                 LIST_REMOVE(newblk, nb_deps);
7507         if (newblk->nb_state & ONWORKLIST)
7508                 WORKLIST_REMOVE(&newblk->nb_list);
7509         LIST_REMOVE(newblk, nb_hash);
7510         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7511                 free_newdirblk(WK_NEWDIRBLK(wk));
7512         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7513                 panic("free_newblk: extra newdirblk");
7514         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7515                 indirdep_complete(indirdep);
7516         handle_jwork(&newblk->nb_jwork);
7517         WORKITEM_FREE(newblk, D_NEWBLK);
7518 }
7519
7520 /*
7521  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7522  * This routine must be called with splbio interrupts blocked.
7523  */
7524 static void
7525 free_newdirblk(newdirblk)
7526         struct newdirblk *newdirblk;
7527 {
7528         struct pagedep *pagedep;
7529         struct diradd *dap;
7530         struct worklist *wk;
7531
7532         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7533         WORKLIST_REMOVE(&newdirblk->db_list);
7534         /*
7535          * If the pagedep is still linked onto the directory buffer
7536          * dependency chain, then some of the entries on the
7537          * pd_pendinghd list may not be committed to disk yet. In
7538          * this case, we will simply clear the NEWBLOCK flag and
7539          * let the pd_pendinghd list be processed when the pagedep
7540          * is next written. If the pagedep is no longer on the buffer
7541          * dependency chain, then all the entries on the pd_pending
7542          * list are committed to disk and we can free them here.
7543          */
7544         pagedep = newdirblk->db_pagedep;
7545         pagedep->pd_state &= ~NEWBLOCK;
7546         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7547                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7548                         free_diradd(dap, NULL);
7549                 /*
7550                  * If no dependencies remain, the pagedep will be freed.
7551                  */
7552                 free_pagedep(pagedep);
7553         }
7554         /* Should only ever be one item in the list. */
7555         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7556                 WORKLIST_REMOVE(wk);
7557                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7558         }
7559         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7560 }
7561
7562 /*
7563  * Prepare an inode to be freed. The actual free operation is not
7564  * done until the zero'ed inode has been written to disk.
7565  */
7566 void
7567 softdep_freefile(pvp, ino, mode)
7568         struct vnode *pvp;
7569         ino_t ino;
7570         int mode;
7571 {
7572         struct inode *ip = VTOI(pvp);
7573         struct inodedep *inodedep;
7574         struct freefile *freefile;
7575         struct freeblks *freeblks;
7576         struct ufsmount *ump;
7577
7578         ump = ITOUMP(ip);
7579         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7580             ("softdep_freefile called on non-softdep filesystem"));
7581         /*
7582          * This sets up the inode de-allocation dependency.
7583          */
7584         freefile = malloc(sizeof(struct freefile),
7585                 M_FREEFILE, M_SOFTDEP_FLAGS);
7586         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7587         freefile->fx_mode = mode;
7588         freefile->fx_oldinum = ino;
7589         freefile->fx_devvp = ump->um_devvp;
7590         LIST_INIT(&freefile->fx_jwork);
7591         UFS_LOCK(ump);
7592         ump->um_fs->fs_pendinginodes += 1;
7593         UFS_UNLOCK(ump);
7594
7595         /*
7596          * If the inodedep does not exist, then the zero'ed inode has
7597          * been written to disk. If the allocated inode has never been
7598          * written to disk, then the on-disk inode is zero'ed. In either
7599          * case we can free the file immediately.  If the journal was
7600          * canceled before being written the inode will never make it to
7601          * disk and we must send the canceled journal entrys to
7602          * ffs_freefile() to be cleared in conjunction with the bitmap.
7603          * Any blocks waiting on the inode to write can be safely freed
7604          * here as it will never been written.
7605          */
7606         ACQUIRE_LOCK(ump);
7607         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7608         if (inodedep) {
7609                 /*
7610                  * Clear out freeblks that no longer need to reference
7611                  * this inode.
7612                  */
7613                 while ((freeblks =
7614                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7615                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7616                             fb_next);
7617                         freeblks->fb_state &= ~ONDEPLIST;
7618                 }
7619                 /*
7620                  * Remove this inode from the unlinked list.
7621                  */
7622                 if (inodedep->id_state & UNLINKED) {
7623                         /*
7624                          * Save the journal work to be freed with the bitmap
7625                          * before we clear UNLINKED.  Otherwise it can be lost
7626                          * if the inode block is written.
7627                          */
7628                         handle_bufwait(inodedep, &freefile->fx_jwork);
7629                         clear_unlinked_inodedep(inodedep);
7630                         /*
7631                          * Re-acquire inodedep as we've dropped the
7632                          * per-filesystem lock in clear_unlinked_inodedep().
7633                          */
7634                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7635                 }
7636         }
7637         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7638                 FREE_LOCK(ump);
7639                 handle_workitem_freefile(freefile);
7640                 return;
7641         }
7642         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7643                 inodedep->id_state |= GOINGAWAY;
7644         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7645         FREE_LOCK(ump);
7646         if (ip->i_number == ino)
7647                 ip->i_flag |= IN_MODIFIED;
7648 }
7649
7650 /*
7651  * Check to see if an inode has never been written to disk. If
7652  * so free the inodedep and return success, otherwise return failure.
7653  * This routine must be called with splbio interrupts blocked.
7654  *
7655  * If we still have a bitmap dependency, then the inode has never
7656  * been written to disk. Drop the dependency as it is no longer
7657  * necessary since the inode is being deallocated. We set the
7658  * ALLCOMPLETE flags since the bitmap now properly shows that the
7659  * inode is not allocated. Even if the inode is actively being
7660  * written, it has been rolled back to its zero'ed state, so we
7661  * are ensured that a zero inode is what is on the disk. For short
7662  * lived files, this change will usually result in removing all the
7663  * dependencies from the inode so that it can be freed immediately.
7664  */
7665 static int
7666 check_inode_unwritten(inodedep)
7667         struct inodedep *inodedep;
7668 {
7669
7670         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7671
7672         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7673             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7674             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7675             !LIST_EMPTY(&inodedep->id_bufwait) ||
7676             !LIST_EMPTY(&inodedep->id_inowait) ||
7677             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7678             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7679             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7680             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7681             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7682             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7683             inodedep->id_mkdiradd != NULL || 
7684             inodedep->id_nlinkdelta != 0)
7685                 return (0);
7686         /*
7687          * Another process might be in initiate_write_inodeblock_ufs[12]
7688          * trying to allocate memory without holding "Softdep Lock".
7689          */
7690         if ((inodedep->id_state & IOSTARTED) != 0 &&
7691             inodedep->id_savedino1 == NULL)
7692                 return (0);
7693
7694         if (inodedep->id_state & ONDEPLIST)
7695                 LIST_REMOVE(inodedep, id_deps);
7696         inodedep->id_state &= ~ONDEPLIST;
7697         inodedep->id_state |= ALLCOMPLETE;
7698         inodedep->id_bmsafemap = NULL;
7699         if (inodedep->id_state & ONWORKLIST)
7700                 WORKLIST_REMOVE(&inodedep->id_list);
7701         if (inodedep->id_savedino1 != NULL) {
7702                 free(inodedep->id_savedino1, M_SAVEDINO);
7703                 inodedep->id_savedino1 = NULL;
7704         }
7705         if (free_inodedep(inodedep) == 0)
7706                 panic("check_inode_unwritten: busy inode");
7707         return (1);
7708 }
7709
7710 static int
7711 check_inodedep_free(inodedep)
7712         struct inodedep *inodedep;
7713 {
7714
7715         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7716         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7717             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7718             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7719             !LIST_EMPTY(&inodedep->id_bufwait) ||
7720             !LIST_EMPTY(&inodedep->id_inowait) ||
7721             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7722             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7723             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7724             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7725             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7726             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7727             inodedep->id_mkdiradd != NULL ||
7728             inodedep->id_nlinkdelta != 0 ||
7729             inodedep->id_savedino1 != NULL)
7730                 return (0);
7731         return (1);
7732 }
7733
7734 /*
7735  * Try to free an inodedep structure. Return 1 if it could be freed.
7736  */
7737 static int
7738 free_inodedep(inodedep)
7739         struct inodedep *inodedep;
7740 {
7741
7742         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7743         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7744             !check_inodedep_free(inodedep))
7745                 return (0);
7746         if (inodedep->id_state & ONDEPLIST)
7747                 LIST_REMOVE(inodedep, id_deps);
7748         LIST_REMOVE(inodedep, id_hash);
7749         WORKITEM_FREE(inodedep, D_INODEDEP);
7750         return (1);
7751 }
7752
7753 /*
7754  * Free the block referenced by a freework structure.  The parent freeblks
7755  * structure is released and completed when the final cg bitmap reaches
7756  * the disk.  This routine may be freeing a jnewblk which never made it to
7757  * disk in which case we do not have to wait as the operation is undone
7758  * in memory immediately.
7759  */
7760 static void
7761 freework_freeblock(freework, key)
7762         struct freework *freework;
7763         u_long key;
7764 {
7765         struct freeblks *freeblks;
7766         struct jnewblk *jnewblk;
7767         struct ufsmount *ump;
7768         struct workhead wkhd;
7769         struct fs *fs;
7770         int bsize;
7771         int needj;
7772
7773         ump = VFSTOUFS(freework->fw_list.wk_mp);
7774         LOCK_OWNED(ump);
7775         /*
7776          * Handle partial truncate separately.
7777          */
7778         if (freework->fw_indir) {
7779                 complete_trunc_indir(freework);
7780                 return;
7781         }
7782         freeblks = freework->fw_freeblks;
7783         fs = ump->um_fs;
7784         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7785         bsize = lfragtosize(fs, freework->fw_frags);
7786         LIST_INIT(&wkhd);
7787         /*
7788          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7789          * on the indirblk hashtable and prevents premature freeing.
7790          */
7791         freework->fw_state |= DEPCOMPLETE;
7792         /*
7793          * SUJ needs to wait for the segment referencing freed indirect
7794          * blocks to expire so that we know the checker will not confuse
7795          * a re-allocated indirect block with its old contents.
7796          */
7797         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7798                 indirblk_insert(freework);
7799         /*
7800          * If we are canceling an existing jnewblk pass it to the free
7801          * routine, otherwise pass the freeblk which will ultimately
7802          * release the freeblks.  If we're not journaling, we can just
7803          * free the freeblks immediately.
7804          */
7805         jnewblk = freework->fw_jnewblk;
7806         if (jnewblk != NULL) {
7807                 cancel_jnewblk(jnewblk, &wkhd);
7808                 needj = 0;
7809         } else if (needj) {
7810                 freework->fw_state |= DELAYEDFREE;
7811                 freeblks->fb_cgwait++;
7812                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7813         }
7814         FREE_LOCK(ump);
7815         freeblks_free(ump, freeblks, btodb(bsize));
7816         CTR4(KTR_SUJ,
7817             "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7818             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7819         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7820             freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7821         ACQUIRE_LOCK(ump);
7822         /*
7823          * The jnewblk will be discarded and the bits in the map never
7824          * made it to disk.  We can immediately free the freeblk.
7825          */
7826         if (needj == 0)
7827                 handle_written_freework(freework);
7828 }
7829
7830 /*
7831  * We enqueue freework items that need processing back on the freeblks and
7832  * add the freeblks to the worklist.  This makes it easier to find all work
7833  * required to flush a truncation in process_truncates().
7834  */
7835 static void
7836 freework_enqueue(freework)
7837         struct freework *freework;
7838 {
7839         struct freeblks *freeblks;
7840
7841         freeblks = freework->fw_freeblks;
7842         if ((freework->fw_state & INPROGRESS) == 0)
7843                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7844         if ((freeblks->fb_state &
7845             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7846             LIST_EMPTY(&freeblks->fb_jblkdephd))
7847                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7848 }
7849
7850 /*
7851  * Start, continue, or finish the process of freeing an indirect block tree.
7852  * The free operation may be paused at any point with fw_off containing the
7853  * offset to restart from.  This enables us to implement some flow control
7854  * for large truncates which may fan out and generate a huge number of
7855  * dependencies.
7856  */
7857 static void
7858 handle_workitem_indirblk(freework)
7859         struct freework *freework;
7860 {
7861         struct freeblks *freeblks;
7862         struct ufsmount *ump;
7863         struct fs *fs;
7864
7865         freeblks = freework->fw_freeblks;
7866         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7867         fs = ump->um_fs;
7868         if (freework->fw_state & DEPCOMPLETE) {
7869                 handle_written_freework(freework);
7870                 return;
7871         }
7872         if (freework->fw_off == NINDIR(fs)) {
7873                 freework_freeblock(freework, SINGLETON_KEY);
7874                 return;
7875         }
7876         freework->fw_state |= INPROGRESS;
7877         FREE_LOCK(ump);
7878         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7879             freework->fw_lbn);
7880         ACQUIRE_LOCK(ump);
7881 }
7882
7883 /*
7884  * Called when a freework structure attached to a cg buf is written.  The
7885  * ref on either the parent or the freeblks structure is released and
7886  * the freeblks is added back to the worklist if there is more work to do.
7887  */
7888 static void
7889 handle_written_freework(freework)
7890         struct freework *freework;
7891 {
7892         struct freeblks *freeblks;
7893         struct freework *parent;
7894
7895         freeblks = freework->fw_freeblks;
7896         parent = freework->fw_parent;
7897         if (freework->fw_state & DELAYEDFREE)
7898                 freeblks->fb_cgwait--;
7899         freework->fw_state |= COMPLETE;
7900         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7901                 WORKITEM_FREE(freework, D_FREEWORK);
7902         if (parent) {
7903                 if (--parent->fw_ref == 0)
7904                         freework_enqueue(parent);
7905                 return;
7906         }
7907         if (--freeblks->fb_ref != 0)
7908                 return;
7909         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7910             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7911                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7912 }
7913
7914 /*
7915  * This workitem routine performs the block de-allocation.
7916  * The workitem is added to the pending list after the updated
7917  * inode block has been written to disk.  As mentioned above,
7918  * checks regarding the number of blocks de-allocated (compared
7919  * to the number of blocks allocated for the file) are also
7920  * performed in this function.
7921  */
7922 static int
7923 handle_workitem_freeblocks(freeblks, flags)
7924         struct freeblks *freeblks;
7925         int flags;
7926 {
7927         struct freework *freework;
7928         struct newblk *newblk;
7929         struct allocindir *aip;
7930         struct ufsmount *ump;
7931         struct worklist *wk;
7932         u_long key;
7933
7934         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7935             ("handle_workitem_freeblocks: Journal entries not written."));
7936         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7937         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7938         ACQUIRE_LOCK(ump);
7939         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7940                 WORKLIST_REMOVE(wk);
7941                 switch (wk->wk_type) {
7942                 case D_DIRREM:
7943                         wk->wk_state |= COMPLETE;
7944                         add_to_worklist(wk, 0);
7945                         continue;
7946
7947                 case D_ALLOCDIRECT:
7948                         free_newblk(WK_NEWBLK(wk));
7949                         continue;
7950
7951                 case D_ALLOCINDIR:
7952                         aip = WK_ALLOCINDIR(wk);
7953                         freework = NULL;
7954                         if (aip->ai_state & DELAYEDFREE) {
7955                                 FREE_LOCK(ump);
7956                                 freework = newfreework(ump, freeblks, NULL,
7957                                     aip->ai_lbn, aip->ai_newblkno,
7958                                     ump->um_fs->fs_frag, 0, 0);
7959                                 ACQUIRE_LOCK(ump);
7960                         }
7961                         newblk = WK_NEWBLK(wk);
7962                         if (newblk->nb_jnewblk) {
7963                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7964                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7965                                 newblk->nb_jnewblk = NULL;
7966                         }
7967                         free_newblk(newblk);
7968                         continue;
7969
7970                 case D_FREEWORK:
7971                         freework = WK_FREEWORK(wk);
7972                         if (freework->fw_lbn <= -UFS_NDADDR)
7973                                 handle_workitem_indirblk(freework);
7974                         else
7975                                 freework_freeblock(freework, key);
7976                         continue;
7977                 default:
7978                         panic("handle_workitem_freeblocks: Unknown type %s",
7979                             TYPENAME(wk->wk_type));
7980                 }
7981         }
7982         if (freeblks->fb_ref != 0) {
7983                 freeblks->fb_state &= ~INPROGRESS;
7984                 wake_worklist(&freeblks->fb_list);
7985                 freeblks = NULL;
7986         }
7987         FREE_LOCK(ump);
7988         ffs_blkrelease_finish(ump, key);
7989         if (freeblks)
7990                 return handle_complete_freeblocks(freeblks, flags);
7991         return (0);
7992 }
7993
7994 /*
7995  * Handle completion of block free via truncate.  This allows fs_pending
7996  * to track the actual free block count more closely than if we only updated
7997  * it at the end.  We must be careful to handle cases where the block count
7998  * on free was incorrect.
7999  */
8000 static void
8001 freeblks_free(ump, freeblks, blocks)
8002         struct ufsmount *ump;
8003         struct freeblks *freeblks;
8004         int blocks;
8005 {
8006         struct fs *fs;
8007         ufs2_daddr_t remain;
8008
8009         UFS_LOCK(ump);
8010         remain = -freeblks->fb_chkcnt;
8011         freeblks->fb_chkcnt += blocks;
8012         if (remain > 0) {
8013                 if (remain < blocks)
8014                         blocks = remain;
8015                 fs = ump->um_fs;
8016                 fs->fs_pendingblocks -= blocks;
8017         }
8018         UFS_UNLOCK(ump);
8019 }
8020
8021 /*
8022  * Once all of the freework workitems are complete we can retire the
8023  * freeblocks dependency and any journal work awaiting completion.  This
8024  * can not be called until all other dependencies are stable on disk.
8025  */
8026 static int
8027 handle_complete_freeblocks(freeblks, flags)
8028         struct freeblks *freeblks;
8029         int flags;
8030 {
8031         struct inodedep *inodedep;
8032         struct inode *ip;
8033         struct vnode *vp;
8034         struct fs *fs;
8035         struct ufsmount *ump;
8036         ufs2_daddr_t spare;
8037
8038         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8039         fs = ump->um_fs;
8040         flags = LK_EXCLUSIVE | flags;
8041         spare = freeblks->fb_chkcnt;
8042
8043         /*
8044          * If we did not release the expected number of blocks we may have
8045          * to adjust the inode block count here.  Only do so if it wasn't
8046          * a truncation to zero and the modrev still matches.
8047          */
8048         if (spare && freeblks->fb_len != 0) {
8049                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8050                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8051                         return (EBUSY);
8052                 ip = VTOI(vp);
8053                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8054                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8055                         ip->i_flag |= IN_CHANGE;
8056                         /*
8057                          * We must wait so this happens before the
8058                          * journal is reclaimed.
8059                          */
8060                         ffs_update(vp, 1);
8061                 }
8062                 vput(vp);
8063         }
8064         if (spare < 0) {
8065                 UFS_LOCK(ump);
8066                 fs->fs_pendingblocks += spare;
8067                 UFS_UNLOCK(ump);
8068         }
8069 #ifdef QUOTA
8070         /* Handle spare. */
8071         if (spare)
8072                 quotaadj(freeblks->fb_quota, ump, -spare);
8073         quotarele(freeblks->fb_quota);
8074 #endif
8075         ACQUIRE_LOCK(ump);
8076         if (freeblks->fb_state & ONDEPLIST) {
8077                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8078                     0, &inodedep);
8079                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8080                 freeblks->fb_state &= ~ONDEPLIST;
8081                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8082                         free_inodedep(inodedep);
8083         }
8084         /*
8085          * All of the freeblock deps must be complete prior to this call
8086          * so it's now safe to complete earlier outstanding journal entries.
8087          */
8088         handle_jwork(&freeblks->fb_jwork);
8089         WORKITEM_FREE(freeblks, D_FREEBLKS);
8090         FREE_LOCK(ump);
8091         return (0);
8092 }
8093
8094 /*
8095  * Release blocks associated with the freeblks and stored in the indirect
8096  * block dbn. If level is greater than SINGLE, the block is an indirect block
8097  * and recursive calls to indirtrunc must be used to cleanse other indirect
8098  * blocks.
8099  *
8100  * This handles partial and complete truncation of blocks.  Partial is noted
8101  * with goingaway == 0.  In this case the freework is completed after the
8102  * zero'd indirects are written to disk.  For full truncation the freework
8103  * is completed after the block is freed.
8104  */
8105 static void
8106 indir_trunc(freework, dbn, lbn)
8107         struct freework *freework;
8108         ufs2_daddr_t dbn;
8109         ufs_lbn_t lbn;
8110 {
8111         struct freework *nfreework;
8112         struct workhead wkhd;
8113         struct freeblks *freeblks;
8114         struct buf *bp;
8115         struct fs *fs;
8116         struct indirdep *indirdep;
8117         struct ufsmount *ump;
8118         ufs1_daddr_t *bap1;
8119         ufs2_daddr_t nb, nnb, *bap2;
8120         ufs_lbn_t lbnadd, nlbn;
8121         u_long key;
8122         int nblocks, ufs1fmt, freedblocks;
8123         int goingaway, freedeps, needj, level, cnt, i;
8124
8125         freeblks = freework->fw_freeblks;
8126         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8127         fs = ump->um_fs;
8128         /*
8129          * Get buffer of block pointers to be freed.  There are three cases:
8130          * 
8131          * 1) Partial truncate caches the indirdep pointer in the freework
8132          *    which provides us a back copy to the save bp which holds the
8133          *    pointers we want to clear.  When this completes the zero
8134          *    pointers are written to the real copy.
8135          * 2) The indirect is being completely truncated, cancel_indirdep()
8136          *    eliminated the real copy and placed the indirdep on the saved
8137          *    copy.  The indirdep and buf are discarded when this completes.
8138          * 3) The indirect was not in memory, we read a copy off of the disk
8139          *    using the devvp and drop and invalidate the buffer when we're
8140          *    done.
8141          */
8142         goingaway = 1;
8143         indirdep = NULL;
8144         if (freework->fw_indir != NULL) {
8145                 goingaway = 0;
8146                 indirdep = freework->fw_indir;
8147                 bp = indirdep->ir_savebp;
8148                 if (bp == NULL || bp->b_blkno != dbn)
8149                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8150                             bp, (intmax_t)dbn);
8151         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8152                 /*
8153                  * The lock prevents the buf dep list from changing and
8154                  * indirects on devvp should only ever have one dependency.
8155                  */
8156                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8157                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8158                         panic("indir_trunc: Bad indirdep %p from buf %p",
8159                             indirdep, bp);
8160         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8161             NOCRED, &bp) != 0) {
8162                 brelse(bp);
8163                 return;
8164         }
8165         ACQUIRE_LOCK(ump);
8166         /* Protects against a race with complete_trunc_indir(). */
8167         freework->fw_state &= ~INPROGRESS;
8168         /*
8169          * If we have an indirdep we need to enforce the truncation order
8170          * and discard it when it is complete.
8171          */
8172         if (indirdep) {
8173                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8174                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8175                         /*
8176                          * Add the complete truncate to the list on the
8177                          * indirdep to enforce in-order processing.
8178                          */
8179                         if (freework->fw_indir == NULL)
8180                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8181                                     freework, fw_next);
8182                         FREE_LOCK(ump);
8183                         return;
8184                 }
8185                 /*
8186                  * If we're goingaway, free the indirdep.  Otherwise it will
8187                  * linger until the write completes.
8188                  */
8189                 if (goingaway)
8190                         free_indirdep(indirdep);
8191         }
8192         FREE_LOCK(ump);
8193         /* Initialize pointers depending on block size. */
8194         if (ump->um_fstype == UFS1) {
8195                 bap1 = (ufs1_daddr_t *)bp->b_data;
8196                 nb = bap1[freework->fw_off];
8197                 ufs1fmt = 1;
8198                 bap2 = NULL;
8199         } else {
8200                 bap2 = (ufs2_daddr_t *)bp->b_data;
8201                 nb = bap2[freework->fw_off];
8202                 ufs1fmt = 0;
8203                 bap1 = NULL;
8204         }
8205         level = lbn_level(lbn);
8206         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8207         lbnadd = lbn_offset(fs, level);
8208         nblocks = btodb(fs->fs_bsize);
8209         nfreework = freework;
8210         freedeps = 0;
8211         cnt = 0;
8212         /*
8213          * Reclaim blocks.  Traverses into nested indirect levels and
8214          * arranges for the current level to be freed when subordinates
8215          * are free when journaling.
8216          */
8217         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8218         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
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. This routine must be called
8886  * with splbio interrupts blocked.
8887  */
8888 static void
8889 free_diradd(dap, wkhd)
8890         struct diradd *dap;
8891         struct workhead *wkhd;
8892 {
8893         struct dirrem *dirrem;
8894         struct pagedep *pagedep;
8895         struct inodedep *inodedep;
8896         struct mkdir *mkdir, *nextmd;
8897         struct ufsmount *ump;
8898
8899         ump = VFSTOUFS(dap->da_list.wk_mp);
8900         LOCK_OWNED(ump);
8901         LIST_REMOVE(dap, da_pdlist);
8902         if (dap->da_state & ONWORKLIST)
8903                 WORKLIST_REMOVE(&dap->da_list);
8904         if ((dap->da_state & DIRCHG) == 0) {
8905                 pagedep = dap->da_pagedep;
8906         } else {
8907                 dirrem = dap->da_previous;
8908                 pagedep = dirrem->dm_pagedep;
8909                 dirrem->dm_dirinum = pagedep->pd_ino;
8910                 dirrem->dm_state |= COMPLETE;
8911                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8912                         add_to_worklist(&dirrem->dm_list, 0);
8913         }
8914         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8915             0, &inodedep) != 0)
8916                 if (inodedep->id_mkdiradd == dap)
8917                         inodedep->id_mkdiradd = NULL;
8918         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8919                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8920                      mkdir = nextmd) {
8921                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8922                         if (mkdir->md_diradd != dap)
8923                                 continue;
8924                         dap->da_state &=
8925                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8926                         LIST_REMOVE(mkdir, md_mkdirs);
8927                         if (mkdir->md_state & ONWORKLIST)
8928                                 WORKLIST_REMOVE(&mkdir->md_list);
8929                         if (mkdir->md_jaddref != NULL)
8930                                 panic("free_diradd: Unexpected jaddref");
8931                         WORKITEM_FREE(mkdir, D_MKDIR);
8932                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8933                                 break;
8934                 }
8935                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8936                         panic("free_diradd: unfound ref");
8937         }
8938         if (inodedep)
8939                 free_inodedep(inodedep);
8940         /*
8941          * Free any journal segments waiting for the directory write.
8942          */
8943         handle_jwork(&dap->da_jwork);
8944         WORKITEM_FREE(dap, D_DIRADD);
8945 }
8946
8947 /*
8948  * Directory entry removal dependencies.
8949  * 
8950  * When removing a directory entry, the entry's inode pointer must be
8951  * zero'ed on disk before the corresponding inode's link count is decremented
8952  * (possibly freeing the inode for re-use). This dependency is handled by
8953  * updating the directory entry but delaying the inode count reduction until
8954  * after the directory block has been written to disk. After this point, the
8955  * inode count can be decremented whenever it is convenient.
8956  */
8957
8958 /*
8959  * This routine should be called immediately after removing
8960  * a directory entry.  The inode's link count should not be
8961  * decremented by the calling procedure -- the soft updates
8962  * code will do this task when it is safe.
8963  */
8964 void 
8965 softdep_setup_remove(bp, dp, ip, isrmdir)
8966         struct buf *bp;         /* buffer containing directory block */
8967         struct inode *dp;       /* inode for the directory being modified */
8968         struct inode *ip;       /* inode for directory entry being removed */
8969         int isrmdir;            /* indicates if doing RMDIR */
8970 {
8971         struct dirrem *dirrem, *prevdirrem;
8972         struct inodedep *inodedep;
8973         struct ufsmount *ump;
8974         int direct;
8975
8976         ump = ITOUMP(ip);
8977         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8978             ("softdep_setup_remove called on non-softdep filesystem"));
8979         /*
8980          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8981          * newdirrem() to setup the full directory remove which requires
8982          * isrmdir > 1.
8983          */
8984         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8985         /*
8986          * Add the dirrem to the inodedep's pending remove list for quick
8987          * discovery later.
8988          */
8989         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8990                 panic("softdep_setup_remove: Lost inodedep.");
8991         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8992         dirrem->dm_state |= ONDEPLIST;
8993         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8994
8995         /*
8996          * If the COMPLETE flag is clear, then there were no active
8997          * entries and we want to roll back to a zeroed entry until
8998          * the new inode is committed to disk. If the COMPLETE flag is
8999          * set then we have deleted an entry that never made it to
9000          * disk. If the entry we deleted resulted from a name change,
9001          * then the old name still resides on disk. We cannot delete
9002          * its inode (returned to us in prevdirrem) until the zeroed
9003          * directory entry gets to disk. The new inode has never been
9004          * referenced on the disk, so can be deleted immediately.
9005          */
9006         if ((dirrem->dm_state & COMPLETE) == 0) {
9007                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9008                     dm_next);
9009                 FREE_LOCK(ump);
9010         } else {
9011                 if (prevdirrem != NULL)
9012                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9013                             prevdirrem, dm_next);
9014                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9015                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9016                 FREE_LOCK(ump);
9017                 if (direct)
9018                         handle_workitem_remove(dirrem, 0);
9019         }
9020 }
9021
9022 /*
9023  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9024  * pd_pendinghd list of a pagedep.
9025  */
9026 static struct diradd *
9027 diradd_lookup(pagedep, offset)
9028         struct pagedep *pagedep;
9029         int offset;
9030 {
9031         struct diradd *dap;
9032
9033         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9034                 if (dap->da_offset == offset)
9035                         return (dap);
9036         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9037                 if (dap->da_offset == offset)
9038                         return (dap);
9039         return (NULL);
9040 }
9041
9042 /*
9043  * Search for a .. diradd dependency in a directory that is being removed.
9044  * If the directory was renamed to a new parent we have a diradd rather
9045  * than a mkdir for the .. entry.  We need to cancel it now before
9046  * it is found in truncate().
9047  */
9048 static struct jremref *
9049 cancel_diradd_dotdot(ip, dirrem, jremref)
9050         struct inode *ip;
9051         struct dirrem *dirrem;
9052         struct jremref *jremref;
9053 {
9054         struct pagedep *pagedep;
9055         struct diradd *dap;
9056         struct worklist *wk;
9057
9058         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9059                 return (jremref);
9060         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9061         if (dap == NULL)
9062                 return (jremref);
9063         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9064         /*
9065          * Mark any journal work as belonging to the parent so it is freed
9066          * with the .. reference.
9067          */
9068         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9069                 wk->wk_state |= MKDIR_PARENT;
9070         return (NULL);
9071 }
9072
9073 /*
9074  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9075  * replace it with a dirrem/diradd pair as a result of re-parenting a
9076  * directory.  This ensures that we don't simultaneously have a mkdir and
9077  * a diradd for the same .. entry.
9078  */
9079 static struct jremref *
9080 cancel_mkdir_dotdot(ip, dirrem, jremref)
9081         struct inode *ip;
9082         struct dirrem *dirrem;
9083         struct jremref *jremref;
9084 {
9085         struct inodedep *inodedep;
9086         struct jaddref *jaddref;
9087         struct ufsmount *ump;
9088         struct mkdir *mkdir;
9089         struct diradd *dap;
9090         struct mount *mp;
9091
9092         mp = ITOVFS(ip);
9093         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9094                 return (jremref);
9095         dap = inodedep->id_mkdiradd;
9096         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9097                 return (jremref);
9098         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9099         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9100             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9101                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9102                         break;
9103         if (mkdir == NULL)
9104                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9105         if ((jaddref = mkdir->md_jaddref) != NULL) {
9106                 mkdir->md_jaddref = NULL;
9107                 jaddref->ja_state &= ~MKDIR_PARENT;
9108                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9109                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9110                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9111                         journal_jremref(dirrem, jremref, inodedep);
9112                         jremref = NULL;
9113                 }
9114         }
9115         if (mkdir->md_state & ONWORKLIST)
9116                 WORKLIST_REMOVE(&mkdir->md_list);
9117         mkdir->md_state |= ALLCOMPLETE;
9118         complete_mkdir(mkdir);
9119         return (jremref);
9120 }
9121
9122 static void
9123 journal_jremref(dirrem, jremref, inodedep)
9124         struct dirrem *dirrem;
9125         struct jremref *jremref;
9126         struct inodedep *inodedep;
9127 {
9128
9129         if (inodedep == NULL)
9130                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9131                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9132                         panic("journal_jremref: Lost inodedep");
9133         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9134         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9135         add_to_journal(&jremref->jr_list);
9136 }
9137
9138 static void
9139 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9140         struct dirrem *dirrem;
9141         struct jremref *jremref;
9142         struct jremref *dotremref;
9143         struct jremref *dotdotremref;
9144 {
9145         struct inodedep *inodedep;
9146
9147
9148         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9149             &inodedep) == 0)
9150                 panic("dirrem_journal: Lost inodedep");
9151         journal_jremref(dirrem, jremref, inodedep);
9152         if (dotremref)
9153                 journal_jremref(dirrem, dotremref, inodedep);
9154         if (dotdotremref)
9155                 journal_jremref(dirrem, dotdotremref, NULL);
9156 }
9157
9158 /*
9159  * Allocate a new dirrem if appropriate and return it along with
9160  * its associated pagedep. Called without a lock, returns with lock.
9161  */
9162 static struct dirrem *
9163 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9164         struct buf *bp;         /* buffer containing directory block */
9165         struct inode *dp;       /* inode for the directory being modified */
9166         struct inode *ip;       /* inode for directory entry being removed */
9167         int isrmdir;            /* indicates if doing RMDIR */
9168         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9169 {
9170         int offset;
9171         ufs_lbn_t lbn;
9172         struct diradd *dap;
9173         struct dirrem *dirrem;
9174         struct pagedep *pagedep;
9175         struct jremref *jremref;
9176         struct jremref *dotremref;
9177         struct jremref *dotdotremref;
9178         struct vnode *dvp;
9179         struct ufsmount *ump;
9180
9181         /*
9182          * Whiteouts have no deletion dependencies.
9183          */
9184         if (ip == NULL)
9185                 panic("newdirrem: whiteout");
9186         dvp = ITOV(dp);
9187         ump = ITOUMP(dp);
9188
9189         /*
9190          * If the system is over its limit and our filesystem is
9191          * responsible for more than our share of that usage and
9192          * we are not a snapshot, request some inodedep cleanup.
9193          * Limiting the number of dirrem structures will also limit
9194          * the number of freefile and freeblks structures.
9195          */
9196         ACQUIRE_LOCK(ump);
9197         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9198                 schedule_cleanup(UFSTOVFS(ump));
9199         else
9200                 FREE_LOCK(ump);
9201         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9202             M_ZERO);
9203         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9204         LIST_INIT(&dirrem->dm_jremrefhd);
9205         LIST_INIT(&dirrem->dm_jwork);
9206         dirrem->dm_state = isrmdir ? RMDIR : 0;
9207         dirrem->dm_oldinum = ip->i_number;
9208         *prevdirremp = NULL;
9209         /*
9210          * Allocate remove reference structures to track journal write
9211          * dependencies.  We will always have one for the link and
9212          * when doing directories we will always have one more for dot.
9213          * When renaming a directory we skip the dotdot link change so
9214          * this is not needed.
9215          */
9216         jremref = dotremref = dotdotremref = NULL;
9217         if (DOINGSUJ(dvp)) {
9218                 if (isrmdir) {
9219                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9220                             ip->i_effnlink + 2);
9221                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9222                             ip->i_effnlink + 1);
9223                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9224                             dp->i_effnlink + 1);
9225                         dotdotremref->jr_state |= MKDIR_PARENT;
9226                 } else
9227                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9228                             ip->i_effnlink + 1);
9229         }
9230         ACQUIRE_LOCK(ump);
9231         lbn = lblkno(ump->um_fs, dp->i_offset);
9232         offset = blkoff(ump->um_fs, dp->i_offset);
9233         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9234             &pagedep);
9235         dirrem->dm_pagedep = pagedep;
9236         dirrem->dm_offset = offset;
9237         /*
9238          * If we're renaming a .. link to a new directory, cancel any
9239          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9240          * the jremref is preserved for any potential diradd in this
9241          * location.  This can not coincide with a rmdir.
9242          */
9243         if (dp->i_offset == DOTDOT_OFFSET) {
9244                 if (isrmdir)
9245                         panic("newdirrem: .. directory change during remove?");
9246                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9247         }
9248         /*
9249          * If we're removing a directory search for the .. dependency now and
9250          * cancel it.  Any pending journal work will be added to the dirrem
9251          * to be completed when the workitem remove completes.
9252          */
9253         if (isrmdir)
9254                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9255         /*
9256          * Check for a diradd dependency for the same directory entry.
9257          * If present, then both dependencies become obsolete and can
9258          * be de-allocated.
9259          */
9260         dap = diradd_lookup(pagedep, offset);
9261         if (dap == NULL) {
9262                 /*
9263                  * Link the jremref structures into the dirrem so they are
9264                  * written prior to the pagedep.
9265                  */
9266                 if (jremref)
9267                         dirrem_journal(dirrem, jremref, dotremref,
9268                             dotdotremref);
9269                 return (dirrem);
9270         }
9271         /*
9272          * Must be ATTACHED at this point.
9273          */
9274         if ((dap->da_state & ATTACHED) == 0)
9275                 panic("newdirrem: not ATTACHED");
9276         if (dap->da_newinum != ip->i_number)
9277                 panic("newdirrem: inum %ju should be %ju",
9278                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9279         /*
9280          * If we are deleting a changed name that never made it to disk,
9281          * then return the dirrem describing the previous inode (which
9282          * represents the inode currently referenced from this entry on disk).
9283          */
9284         if ((dap->da_state & DIRCHG) != 0) {
9285                 *prevdirremp = dap->da_previous;
9286                 dap->da_state &= ~DIRCHG;
9287                 dap->da_pagedep = pagedep;
9288         }
9289         /*
9290          * We are deleting an entry that never made it to disk.
9291          * Mark it COMPLETE so we can delete its inode immediately.
9292          */
9293         dirrem->dm_state |= COMPLETE;
9294         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9295 #ifdef SUJ_DEBUG
9296         if (isrmdir == 0) {
9297                 struct worklist *wk;
9298
9299                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9300                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9301                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9302         }
9303 #endif
9304
9305         return (dirrem);
9306 }
9307
9308 /*
9309  * Directory entry change dependencies.
9310  * 
9311  * Changing an existing directory entry requires that an add operation
9312  * be completed first followed by a deletion. The semantics for the addition
9313  * are identical to the description of adding a new entry above except
9314  * that the rollback is to the old inode number rather than zero. Once
9315  * the addition dependency is completed, the removal is done as described
9316  * in the removal routine above.
9317  */
9318
9319 /*
9320  * This routine should be called immediately after changing
9321  * a directory entry.  The inode's link count should not be
9322  * decremented by the calling procedure -- the soft updates
9323  * code will perform this task when it is safe.
9324  */
9325 void 
9326 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9327         struct buf *bp;         /* buffer containing directory block */
9328         struct inode *dp;       /* inode for the directory being modified */
9329         struct inode *ip;       /* inode for directory entry being removed */
9330         ino_t newinum;          /* new inode number for changed entry */
9331         int isrmdir;            /* indicates if doing RMDIR */
9332 {
9333         int offset;
9334         struct diradd *dap = NULL;
9335         struct dirrem *dirrem, *prevdirrem;
9336         struct pagedep *pagedep;
9337         struct inodedep *inodedep;
9338         struct jaddref *jaddref;
9339         struct mount *mp;
9340         struct ufsmount *ump;
9341
9342         mp = ITOVFS(dp);
9343         ump = VFSTOUFS(mp);
9344         offset = blkoff(ump->um_fs, dp->i_offset);
9345         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9346            ("softdep_setup_directory_change called on non-softdep filesystem"));
9347
9348         /*
9349          * Whiteouts do not need diradd dependencies.
9350          */
9351         if (newinum != UFS_WINO) {
9352                 dap = malloc(sizeof(struct diradd),
9353                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9354                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9355                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9356                 dap->da_offset = offset;
9357                 dap->da_newinum = newinum;
9358                 LIST_INIT(&dap->da_jwork);
9359         }
9360
9361         /*
9362          * Allocate a new dirrem and ACQUIRE_LOCK.
9363          */
9364         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9365         pagedep = dirrem->dm_pagedep;
9366         /*
9367          * The possible values for isrmdir:
9368          *      0 - non-directory file rename
9369          *      1 - directory rename within same directory
9370          *   inum - directory rename to new directory of given inode number
9371          * When renaming to a new directory, we are both deleting and
9372          * creating a new directory entry, so the link count on the new
9373          * directory should not change. Thus we do not need the followup
9374          * dirrem which is usually done in handle_workitem_remove. We set
9375          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9376          * followup dirrem.
9377          */
9378         if (isrmdir > 1)
9379                 dirrem->dm_state |= DIRCHG;
9380
9381         /*
9382          * Whiteouts have no additional dependencies,
9383          * so just put the dirrem on the correct list.
9384          */
9385         if (newinum == UFS_WINO) {
9386                 if ((dirrem->dm_state & COMPLETE) == 0) {
9387                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9388                             dm_next);
9389                 } else {
9390                         dirrem->dm_dirinum = pagedep->pd_ino;
9391                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9392                                 add_to_worklist(&dirrem->dm_list, 0);
9393                 }
9394                 FREE_LOCK(ump);
9395                 return;
9396         }
9397         /*
9398          * Add the dirrem to the inodedep's pending remove list for quick
9399          * discovery later.  A valid nlinkdelta ensures that this lookup
9400          * will not fail.
9401          */
9402         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9403                 panic("softdep_setup_directory_change: Lost inodedep.");
9404         dirrem->dm_state |= ONDEPLIST;
9405         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9406
9407         /*
9408          * If the COMPLETE flag is clear, then there were no active
9409          * entries and we want to roll back to the previous inode until
9410          * the new inode is committed to disk. If the COMPLETE flag is
9411          * set, then we have deleted an entry that never made it to disk.
9412          * If the entry we deleted resulted from a name change, then the old
9413          * inode reference still resides on disk. Any rollback that we do
9414          * needs to be to that old inode (returned to us in prevdirrem). If
9415          * the entry we deleted resulted from a create, then there is
9416          * no entry on the disk, so we want to roll back to zero rather
9417          * than the uncommitted inode. In either of the COMPLETE cases we
9418          * want to immediately free the unwritten and unreferenced inode.
9419          */
9420         if ((dirrem->dm_state & COMPLETE) == 0) {
9421                 dap->da_previous = dirrem;
9422         } else {
9423                 if (prevdirrem != NULL) {
9424                         dap->da_previous = prevdirrem;
9425                 } else {
9426                         dap->da_state &= ~DIRCHG;
9427                         dap->da_pagedep = pagedep;
9428                 }
9429                 dirrem->dm_dirinum = pagedep->pd_ino;
9430                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9431                         add_to_worklist(&dirrem->dm_list, 0);
9432         }
9433         /*
9434          * Lookup the jaddref for this journal entry.  We must finish
9435          * initializing it and make the diradd write dependent on it.
9436          * If we're not journaling, put it on the id_bufwait list if the
9437          * inode is not yet written. If it is written, do the post-inode
9438          * write processing to put it on the id_pendinghd list.
9439          */
9440         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9441         if (MOUNTEDSUJ(mp)) {
9442                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9443                     inoreflst);
9444                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9445                     ("softdep_setup_directory_change: bad jaddref %p",
9446                     jaddref));
9447                 jaddref->ja_diroff = dp->i_offset;
9448                 jaddref->ja_diradd = dap;
9449                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9450                     dap, da_pdlist);
9451                 add_to_journal(&jaddref->ja_list);
9452         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9453                 dap->da_state |= COMPLETE;
9454                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9455                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9456         } else {
9457                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9458                     dap, da_pdlist);
9459                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9460         }
9461         /*
9462          * If we're making a new name for a directory that has not been
9463          * committed when need to move the dot and dotdot references to
9464          * this new name.
9465          */
9466         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9467                 merge_diradd(inodedep, dap);
9468         FREE_LOCK(ump);
9469 }
9470
9471 /*
9472  * Called whenever the link count on an inode is changed.
9473  * It creates an inode dependency so that the new reference(s)
9474  * to the inode cannot be committed to disk until the updated
9475  * inode has been written.
9476  */
9477 void
9478 softdep_change_linkcnt(ip)
9479         struct inode *ip;       /* the inode with the increased link count */
9480 {
9481         struct inodedep *inodedep;
9482         struct ufsmount *ump;
9483
9484         ump = ITOUMP(ip);
9485         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9486             ("softdep_change_linkcnt called on non-softdep filesystem"));
9487         ACQUIRE_LOCK(ump);
9488         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9489         if (ip->i_nlink < ip->i_effnlink)
9490                 panic("softdep_change_linkcnt: bad delta");
9491         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9492         FREE_LOCK(ump);
9493 }
9494
9495 /*
9496  * Attach a sbdep dependency to the superblock buf so that we can keep
9497  * track of the head of the linked list of referenced but unlinked inodes.
9498  */
9499 void
9500 softdep_setup_sbupdate(ump, fs, bp)
9501         struct ufsmount *ump;
9502         struct fs *fs;
9503         struct buf *bp;
9504 {
9505         struct sbdep *sbdep;
9506         struct worklist *wk;
9507
9508         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9509             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9510         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9511                 if (wk->wk_type == D_SBDEP)
9512                         break;
9513         if (wk != NULL)
9514                 return;
9515         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9516         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9517         sbdep->sb_fs = fs;
9518         sbdep->sb_ump = ump;
9519         ACQUIRE_LOCK(ump);
9520         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9521         FREE_LOCK(ump);
9522 }
9523
9524 /*
9525  * Return the first unlinked inodedep which is ready to be the head of the
9526  * list.  The inodedep and all those after it must have valid next pointers.
9527  */
9528 static struct inodedep *
9529 first_unlinked_inodedep(ump)
9530         struct ufsmount *ump;
9531 {
9532         struct inodedep *inodedep;
9533         struct inodedep *idp;
9534
9535         LOCK_OWNED(ump);
9536         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9537             inodedep; inodedep = idp) {
9538                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9539                         return (NULL);
9540                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9541                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9542                         break;
9543                 if ((inodedep->id_state & UNLINKPREV) == 0)
9544                         break;
9545         }
9546         return (inodedep);
9547 }
9548
9549 /*
9550  * Set the sujfree unlinked head pointer prior to writing a superblock.
9551  */
9552 static void
9553 initiate_write_sbdep(sbdep)
9554         struct sbdep *sbdep;
9555 {
9556         struct inodedep *inodedep;
9557         struct fs *bpfs;
9558         struct fs *fs;
9559
9560         bpfs = sbdep->sb_fs;
9561         fs = sbdep->sb_ump->um_fs;
9562         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9563         if (inodedep) {
9564                 fs->fs_sujfree = inodedep->id_ino;
9565                 inodedep->id_state |= UNLINKPREV;
9566         } else
9567                 fs->fs_sujfree = 0;
9568         bpfs->fs_sujfree = fs->fs_sujfree;
9569 }
9570
9571 /*
9572  * After a superblock is written determine whether it must be written again
9573  * due to a changing unlinked list head.
9574  */
9575 static int
9576 handle_written_sbdep(sbdep, bp)
9577         struct sbdep *sbdep;
9578         struct buf *bp;
9579 {
9580         struct inodedep *inodedep;
9581         struct fs *fs;
9582
9583         LOCK_OWNED(sbdep->sb_ump);
9584         fs = sbdep->sb_fs;
9585         /*
9586          * If the superblock doesn't match the in-memory list start over.
9587          */
9588         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9589         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9590             (inodedep == NULL && fs->fs_sujfree != 0)) {
9591                 bdirty(bp);
9592                 return (1);
9593         }
9594         WORKITEM_FREE(sbdep, D_SBDEP);
9595         if (fs->fs_sujfree == 0)
9596                 return (0);
9597         /*
9598          * Now that we have a record of this inode in stable store allow it
9599          * to be written to free up pending work.  Inodes may see a lot of
9600          * write activity after they are unlinked which we must not hold up.
9601          */
9602         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9603                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9604                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9605                             inodedep, inodedep->id_state);
9606                 if (inodedep->id_state & UNLINKONLIST)
9607                         break;
9608                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9609         }
9610
9611         return (0);
9612 }
9613
9614 /*
9615  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9616  */
9617 static void
9618 unlinked_inodedep(mp, inodedep)
9619         struct mount *mp;
9620         struct inodedep *inodedep;
9621 {
9622         struct ufsmount *ump;
9623
9624         ump = VFSTOUFS(mp);
9625         LOCK_OWNED(ump);
9626         if (MOUNTEDSUJ(mp) == 0)
9627                 return;
9628         ump->um_fs->fs_fmod = 1;
9629         if (inodedep->id_state & UNLINKED)
9630                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9631         inodedep->id_state |= UNLINKED;
9632         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9633 }
9634
9635 /*
9636  * Remove an inodedep from the unlinked inodedep list.  This may require
9637  * disk writes if the inode has made it that far.
9638  */
9639 static void
9640 clear_unlinked_inodedep(inodedep)
9641         struct inodedep *inodedep;
9642 {
9643         struct ufsmount *ump;
9644         struct inodedep *idp;
9645         struct inodedep *idn;
9646         struct fs *fs;
9647         struct buf *bp;
9648         ino_t ino;
9649         ino_t nino;
9650         ino_t pino;
9651         int error;
9652
9653         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9654         fs = ump->um_fs;
9655         ino = inodedep->id_ino;
9656         error = 0;
9657         for (;;) {
9658                 LOCK_OWNED(ump);
9659                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9660                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9661                     inodedep));
9662                 /*
9663                  * If nothing has yet been written simply remove us from
9664                  * the in memory list and return.  This is the most common
9665                  * case where handle_workitem_remove() loses the final
9666                  * reference.
9667                  */
9668                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9669                         break;
9670                 /*
9671                  * If we have a NEXT pointer and no PREV pointer we can simply
9672                  * clear NEXT's PREV and remove ourselves from the list.  Be
9673                  * careful not to clear PREV if the superblock points at
9674                  * next as well.
9675                  */
9676                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9677                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9678                         if (idn && fs->fs_sujfree != idn->id_ino)
9679                                 idn->id_state &= ~UNLINKPREV;
9680                         break;
9681                 }
9682                 /*
9683                  * Here we have an inodedep which is actually linked into
9684                  * the list.  We must remove it by forcing a write to the
9685                  * link before us, whether it be the superblock or an inode.
9686                  * Unfortunately the list may change while we're waiting
9687                  * on the buf lock for either resource so we must loop until
9688                  * we lock the right one.  If both the superblock and an
9689                  * inode point to this inode we must clear the inode first
9690                  * followed by the superblock.
9691                  */
9692                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9693                 pino = 0;
9694                 if (idp && (idp->id_state & UNLINKNEXT))
9695                         pino = idp->id_ino;
9696                 FREE_LOCK(ump);
9697                 if (pino == 0) {
9698                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9699                             (int)fs->fs_sbsize, 0, 0, 0);
9700                 } else {
9701                         error = bread(ump->um_devvp,
9702                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9703                             (int)fs->fs_bsize, NOCRED, &bp);
9704                         if (error)
9705                                 brelse(bp);
9706                 }
9707                 ACQUIRE_LOCK(ump);
9708                 if (error)
9709                         break;
9710                 /* If the list has changed restart the loop. */
9711                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9712                 nino = 0;
9713                 if (idp && (idp->id_state & UNLINKNEXT))
9714                         nino = idp->id_ino;
9715                 if (nino != pino ||
9716                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9717                         FREE_LOCK(ump);
9718                         brelse(bp);
9719                         ACQUIRE_LOCK(ump);
9720                         continue;
9721                 }
9722                 nino = 0;
9723                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9724                 if (idn)
9725                         nino = idn->id_ino;
9726                 /*
9727                  * Remove us from the in memory list.  After this we cannot
9728                  * access the inodedep.
9729                  */
9730                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9731                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9732                     inodedep));
9733                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9734                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9735                 FREE_LOCK(ump);
9736                 /*
9737                  * The predecessor's next pointer is manually updated here
9738                  * so that the NEXT flag is never cleared for an element
9739                  * that is in the list.
9740                  */
9741                 if (pino == 0) {
9742                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9743                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9744                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9745                             bp);
9746                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9747                         ((struct ufs1_dinode *)bp->b_data +
9748                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9749                 else
9750                         ((struct ufs2_dinode *)bp->b_data +
9751                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9752                 /*
9753                  * If the bwrite fails we have no recourse to recover.  The
9754                  * filesystem is corrupted already.
9755                  */
9756                 bwrite(bp);
9757                 ACQUIRE_LOCK(ump);
9758                 /*
9759                  * If the superblock pointer still needs to be cleared force
9760                  * a write here.
9761                  */
9762                 if (fs->fs_sujfree == ino) {
9763                         FREE_LOCK(ump);
9764                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9765                             (int)fs->fs_sbsize, 0, 0, 0);
9766                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9767                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9768                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9769                             bp);
9770                         bwrite(bp);
9771                         ACQUIRE_LOCK(ump);
9772                 }
9773
9774                 if (fs->fs_sujfree != ino)
9775                         return;
9776                 panic("clear_unlinked_inodedep: Failed to clear free head");
9777         }
9778         if (inodedep->id_ino == fs->fs_sujfree)
9779                 panic("clear_unlinked_inodedep: Freeing head of free list");
9780         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9781         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9782         return;
9783 }
9784
9785 /*
9786  * This workitem decrements the inode's link count.
9787  * If the link count reaches zero, the file is removed.
9788  */
9789 static int
9790 handle_workitem_remove(dirrem, flags)
9791         struct dirrem *dirrem;
9792         int flags;
9793 {
9794         struct inodedep *inodedep;
9795         struct workhead dotdotwk;
9796         struct worklist *wk;
9797         struct ufsmount *ump;
9798         struct mount *mp;
9799         struct vnode *vp;
9800         struct inode *ip;
9801         ino_t oldinum;
9802
9803         if (dirrem->dm_state & ONWORKLIST)
9804                 panic("handle_workitem_remove: dirrem %p still on worklist",
9805                     dirrem);
9806         oldinum = dirrem->dm_oldinum;
9807         mp = dirrem->dm_list.wk_mp;
9808         ump = VFSTOUFS(mp);
9809         flags |= LK_EXCLUSIVE;
9810         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9811                 return (EBUSY);
9812         ip = VTOI(vp);
9813         ACQUIRE_LOCK(ump);
9814         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9815                 panic("handle_workitem_remove: lost inodedep");
9816         if (dirrem->dm_state & ONDEPLIST)
9817                 LIST_REMOVE(dirrem, dm_inonext);
9818         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9819             ("handle_workitem_remove:  Journal entries not written."));
9820
9821         /*
9822          * Move all dependencies waiting on the remove to complete
9823          * from the dirrem to the inode inowait list to be completed
9824          * after the inode has been updated and written to disk.  Any
9825          * marked MKDIR_PARENT are saved to be completed when the .. ref
9826          * is removed.
9827          */
9828         LIST_INIT(&dotdotwk);
9829         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9830                 WORKLIST_REMOVE(wk);
9831                 if (wk->wk_state & MKDIR_PARENT) {
9832                         wk->wk_state &= ~MKDIR_PARENT;
9833                         WORKLIST_INSERT(&dotdotwk, wk);
9834                         continue;
9835                 }
9836                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9837         }
9838         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9839         /*
9840          * Normal file deletion.
9841          */
9842         if ((dirrem->dm_state & RMDIR) == 0) {
9843                 ip->i_nlink--;
9844                 DIP_SET(ip, i_nlink, ip->i_nlink);
9845                 ip->i_flag |= IN_CHANGE;
9846                 if (ip->i_nlink < ip->i_effnlink)
9847                         panic("handle_workitem_remove: bad file delta");
9848                 if (ip->i_nlink == 0) 
9849                         unlinked_inodedep(mp, inodedep);
9850                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9851                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9852                     ("handle_workitem_remove: worklist not empty. %s",
9853                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9854                 WORKITEM_FREE(dirrem, D_DIRREM);
9855                 FREE_LOCK(ump);
9856                 goto out;
9857         }
9858         /*
9859          * Directory deletion. Decrement reference count for both the
9860          * just deleted parent directory entry and the reference for ".".
9861          * Arrange to have the reference count on the parent decremented
9862          * to account for the loss of "..".
9863          */
9864         ip->i_nlink -= 2;
9865         DIP_SET(ip, i_nlink, ip->i_nlink);
9866         ip->i_flag |= IN_CHANGE;
9867         if (ip->i_nlink < ip->i_effnlink)
9868                 panic("handle_workitem_remove: bad dir delta");
9869         if (ip->i_nlink == 0)
9870                 unlinked_inodedep(mp, inodedep);
9871         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9872         /*
9873          * Rename a directory to a new parent. Since, we are both deleting
9874          * and creating a new directory entry, the link count on the new
9875          * directory should not change. Thus we skip the followup dirrem.
9876          */
9877         if (dirrem->dm_state & DIRCHG) {
9878                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9879                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9880                 WORKITEM_FREE(dirrem, D_DIRREM);
9881                 FREE_LOCK(ump);
9882                 goto out;
9883         }
9884         dirrem->dm_state = ONDEPLIST;
9885         dirrem->dm_oldinum = dirrem->dm_dirinum;
9886         /*
9887          * Place the dirrem on the parent's diremhd list.
9888          */
9889         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9890                 panic("handle_workitem_remove: lost dir inodedep");
9891         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9892         /*
9893          * If the allocated inode has never been written to disk, then
9894          * the on-disk inode is zero'ed and we can remove the file
9895          * immediately.  When journaling if the inode has been marked
9896          * unlinked and not DEPCOMPLETE we know it can never be written.
9897          */
9898         inodedep_lookup(mp, oldinum, 0, &inodedep);
9899         if (inodedep == NULL ||
9900             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9901             check_inode_unwritten(inodedep)) {
9902                 FREE_LOCK(ump);
9903                 vput(vp);
9904                 return handle_workitem_remove(dirrem, flags);
9905         }
9906         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9907         FREE_LOCK(ump);
9908         ip->i_flag |= IN_CHANGE;
9909 out:
9910         ffs_update(vp, 0);
9911         vput(vp);
9912         return (0);
9913 }
9914
9915 /*
9916  * Inode de-allocation dependencies.
9917  * 
9918  * When an inode's link count is reduced to zero, it can be de-allocated. We
9919  * found it convenient to postpone de-allocation until after the inode is
9920  * written to disk with its new link count (zero).  At this point, all of the
9921  * on-disk inode's block pointers are nullified and, with careful dependency
9922  * list ordering, all dependencies related to the inode will be satisfied and
9923  * the corresponding dependency structures de-allocated.  So, if/when the
9924  * inode is reused, there will be no mixing of old dependencies with new
9925  * ones.  This artificial dependency is set up by the block de-allocation
9926  * procedure above (softdep_setup_freeblocks) and completed by the
9927  * following procedure.
9928  */
9929 static void 
9930 handle_workitem_freefile(freefile)
9931         struct freefile *freefile;
9932 {
9933         struct workhead wkhd;
9934         struct fs *fs;
9935         struct inodedep *idp;
9936         struct ufsmount *ump;
9937         int error;
9938
9939         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9940         fs = ump->um_fs;
9941 #ifdef DEBUG
9942         ACQUIRE_LOCK(ump);
9943         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9944         FREE_LOCK(ump);
9945         if (error)
9946                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9947 #endif
9948         UFS_LOCK(ump);
9949         fs->fs_pendinginodes -= 1;
9950         UFS_UNLOCK(ump);
9951         LIST_INIT(&wkhd);
9952         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9953         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9954             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9955                 softdep_error("handle_workitem_freefile", error);
9956         ACQUIRE_LOCK(ump);
9957         WORKITEM_FREE(freefile, D_FREEFILE);
9958         FREE_LOCK(ump);
9959 }
9960
9961
9962 /*
9963  * Helper function which unlinks marker element from work list and returns
9964  * the next element on the list.
9965  */
9966 static __inline struct worklist *
9967 markernext(struct worklist *marker)
9968 {
9969         struct worklist *next;
9970         
9971         next = LIST_NEXT(marker, wk_list);
9972         LIST_REMOVE(marker, wk_list);
9973         return next;
9974 }
9975
9976 /*
9977  * Disk writes.
9978  * 
9979  * The dependency structures constructed above are most actively used when file
9980  * system blocks are written to disk.  No constraints are placed on when a
9981  * block can be written, but unsatisfied update dependencies are made safe by
9982  * modifying (or replacing) the source memory for the duration of the disk
9983  * write.  When the disk write completes, the memory block is again brought
9984  * up-to-date.
9985  *
9986  * In-core inode structure reclamation.
9987  * 
9988  * Because there are a finite number of "in-core" inode structures, they are
9989  * reused regularly.  By transferring all inode-related dependencies to the
9990  * in-memory inode block and indexing them separately (via "inodedep"s), we
9991  * can allow "in-core" inode structures to be reused at any time and avoid
9992  * any increase in contention.
9993  *
9994  * Called just before entering the device driver to initiate a new disk I/O.
9995  * The buffer must be locked, thus, no I/O completion operations can occur
9996  * while we are manipulating its associated dependencies.
9997  */
9998 static void 
9999 softdep_disk_io_initiation(bp)
10000         struct buf *bp;         /* structure describing disk write to occur */
10001 {
10002         struct worklist *wk;
10003         struct worklist marker;
10004         struct inodedep *inodedep;
10005         struct freeblks *freeblks;
10006         struct jblkdep *jblkdep;
10007         struct newblk *newblk;
10008         struct ufsmount *ump;
10009
10010         /*
10011          * We only care about write operations. There should never
10012          * be dependencies for reads.
10013          */
10014         if (bp->b_iocmd != BIO_WRITE)
10015                 panic("softdep_disk_io_initiation: not write");
10016
10017         if (bp->b_vflags & BV_BKGRDINPROG)
10018                 panic("softdep_disk_io_initiation: Writing buffer with "
10019                     "background write in progress: %p", bp);
10020
10021         ump = softdep_bp_to_mp(bp);
10022         if (ump == NULL)
10023                 return;
10024
10025         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
10026         PHOLD(curproc);                 /* Don't swap out kernel stack */
10027         ACQUIRE_LOCK(ump);
10028         /*
10029          * Do any necessary pre-I/O processing.
10030          */
10031         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10032              wk = markernext(&marker)) {
10033                 LIST_INSERT_AFTER(wk, &marker, wk_list);
10034                 switch (wk->wk_type) {
10035
10036                 case D_PAGEDEP:
10037                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10038                         continue;
10039
10040                 case D_INODEDEP:
10041                         inodedep = WK_INODEDEP(wk);
10042                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10043                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10044                         else
10045                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10046                         continue;
10047
10048                 case D_INDIRDEP:
10049                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10050                         continue;
10051
10052                 case D_BMSAFEMAP:
10053                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10054                         continue;
10055
10056                 case D_JSEG:
10057                         WK_JSEG(wk)->js_buf = NULL;
10058                         continue;
10059
10060                 case D_FREEBLKS:
10061                         freeblks = WK_FREEBLKS(wk);
10062                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10063                         /*
10064                          * We have to wait for the freeblks to be journaled
10065                          * before we can write an inodeblock with updated
10066                          * pointers.  Be careful to arrange the marker so
10067                          * we revisit the freeblks if it's not removed by
10068                          * the first jwait().
10069                          */
10070                         if (jblkdep != NULL) {
10071                                 LIST_REMOVE(&marker, wk_list);
10072                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10073                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10074                         }
10075                         continue;
10076                 case D_ALLOCDIRECT:
10077                 case D_ALLOCINDIR:
10078                         /*
10079                          * We have to wait for the jnewblk to be journaled
10080                          * before we can write to a block if the contents
10081                          * may be confused with an earlier file's indirect
10082                          * at recovery time.  Handle the marker as described
10083                          * above.
10084                          */
10085                         newblk = WK_NEWBLK(wk);
10086                         if (newblk->nb_jnewblk != NULL &&
10087                             indirblk_lookup(newblk->nb_list.wk_mp,
10088                             newblk->nb_newblkno)) {
10089                                 LIST_REMOVE(&marker, wk_list);
10090                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10091                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10092                         }
10093                         continue;
10094
10095                 case D_SBDEP:
10096                         initiate_write_sbdep(WK_SBDEP(wk));
10097                         continue;
10098
10099                 case D_MKDIR:
10100                 case D_FREEWORK:
10101                 case D_FREEDEP:
10102                 case D_JSEGDEP:
10103                         continue;
10104
10105                 default:
10106                         panic("handle_disk_io_initiation: Unexpected type %s",
10107                             TYPENAME(wk->wk_type));
10108                         /* NOTREACHED */
10109                 }
10110         }
10111         FREE_LOCK(ump);
10112         PRELE(curproc);                 /* Allow swapout of kernel stack */
10113 }
10114
10115 /*
10116  * Called from within the procedure above to deal with unsatisfied
10117  * allocation dependencies in a directory. The buffer must be locked,
10118  * thus, no I/O completion operations can occur while we are
10119  * manipulating its associated dependencies.
10120  */
10121 static void
10122 initiate_write_filepage(pagedep, bp)
10123         struct pagedep *pagedep;
10124         struct buf *bp;
10125 {
10126         struct jremref *jremref;
10127         struct jmvref *jmvref;
10128         struct dirrem *dirrem;
10129         struct diradd *dap;
10130         struct direct *ep;
10131         int i;
10132
10133         if (pagedep->pd_state & IOSTARTED) {
10134                 /*
10135                  * This can only happen if there is a driver that does not
10136                  * understand chaining. Here biodone will reissue the call
10137                  * to strategy for the incomplete buffers.
10138                  */
10139                 printf("initiate_write_filepage: already started\n");
10140                 return;
10141         }
10142         pagedep->pd_state |= IOSTARTED;
10143         /*
10144          * Wait for all journal remove dependencies to hit the disk.
10145          * We can not allow any potentially conflicting directory adds
10146          * to be visible before removes and rollback is too difficult.
10147          * The per-filesystem lock may be dropped and re-acquired, however 
10148          * we hold the buf locked so the dependency can not go away.
10149          */
10150         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10151                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10152                         jwait(&jremref->jr_list, MNT_WAIT);
10153         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10154                 jwait(&jmvref->jm_list, MNT_WAIT);
10155         for (i = 0; i < DAHASHSZ; i++) {
10156                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10157                         ep = (struct direct *)
10158                             ((char *)bp->b_data + dap->da_offset);
10159                         if (ep->d_ino != dap->da_newinum)
10160                                 panic("%s: dir inum %ju != new %ju",
10161                                     "initiate_write_filepage",
10162                                     (uintmax_t)ep->d_ino,
10163                                     (uintmax_t)dap->da_newinum);
10164                         if (dap->da_state & DIRCHG)
10165                                 ep->d_ino = dap->da_previous->dm_oldinum;
10166                         else
10167                                 ep->d_ino = 0;
10168                         dap->da_state &= ~ATTACHED;
10169                         dap->da_state |= UNDONE;
10170                 }
10171         }
10172 }
10173
10174 /*
10175  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10176  * Note that any bug fixes made to this routine must be done in the
10177  * version found below.
10178  *
10179  * Called from within the procedure above to deal with unsatisfied
10180  * allocation dependencies in an inodeblock. The buffer must be
10181  * locked, thus, no I/O completion operations can occur while we
10182  * are manipulating its associated dependencies.
10183  */
10184 static void 
10185 initiate_write_inodeblock_ufs1(inodedep, bp)
10186         struct inodedep *inodedep;
10187         struct buf *bp;                 /* The inode block */
10188 {
10189         struct allocdirect *adp, *lastadp;
10190         struct ufs1_dinode *dp;
10191         struct ufs1_dinode *sip;
10192         struct inoref *inoref;
10193         struct ufsmount *ump;
10194         struct fs *fs;
10195         ufs_lbn_t i;
10196 #ifdef INVARIANTS
10197         ufs_lbn_t prevlbn = 0;
10198 #endif
10199         int deplist;
10200
10201         if (inodedep->id_state & IOSTARTED)
10202                 panic("initiate_write_inodeblock_ufs1: already started");
10203         inodedep->id_state |= IOSTARTED;
10204         fs = inodedep->id_fs;
10205         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10206         LOCK_OWNED(ump);
10207         dp = (struct ufs1_dinode *)bp->b_data +
10208             ino_to_fsbo(fs, inodedep->id_ino);
10209
10210         /*
10211          * If we're on the unlinked list but have not yet written our
10212          * next pointer initialize it here.
10213          */
10214         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10215                 struct inodedep *inon;
10216
10217                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10218                 dp->di_freelink = inon ? inon->id_ino : 0;
10219         }
10220         /*
10221          * If the bitmap is not yet written, then the allocated
10222          * inode cannot be written to disk.
10223          */
10224         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10225                 if (inodedep->id_savedino1 != NULL)
10226                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10227                 FREE_LOCK(ump);
10228                 sip = malloc(sizeof(struct ufs1_dinode),
10229                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10230                 ACQUIRE_LOCK(ump);
10231                 inodedep->id_savedino1 = sip;
10232                 *inodedep->id_savedino1 = *dp;
10233                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10234                 dp->di_gen = inodedep->id_savedino1->di_gen;
10235                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10236                 return;
10237         }
10238         /*
10239          * If no dependencies, then there is nothing to roll back.
10240          */
10241         inodedep->id_savedsize = dp->di_size;
10242         inodedep->id_savedextsize = 0;
10243         inodedep->id_savednlink = dp->di_nlink;
10244         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10245             TAILQ_EMPTY(&inodedep->id_inoreflst))
10246                 return;
10247         /*
10248          * Revert the link count to that of the first unwritten journal entry.
10249          */
10250         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10251         if (inoref)
10252                 dp->di_nlink = inoref->if_nlink;
10253         /*
10254          * Set the dependencies to busy.
10255          */
10256         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10257              adp = TAILQ_NEXT(adp, ad_next)) {
10258 #ifdef INVARIANTS
10259                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10260                         panic("softdep_write_inodeblock: lbn order");
10261                 prevlbn = adp->ad_offset;
10262                 if (adp->ad_offset < UFS_NDADDR &&
10263                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10264                         panic("%s: direct pointer #%jd mismatch %d != %jd",
10265                             "softdep_write_inodeblock",
10266                             (intmax_t)adp->ad_offset,
10267                             dp->di_db[adp->ad_offset],
10268                             (intmax_t)adp->ad_newblkno);
10269                 if (adp->ad_offset >= UFS_NDADDR &&
10270                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10271                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
10272                             "softdep_write_inodeblock",
10273                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10274                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10275                             (intmax_t)adp->ad_newblkno);
10276                 deplist |= 1 << adp->ad_offset;
10277                 if ((adp->ad_state & ATTACHED) == 0)
10278                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10279                             adp->ad_state);
10280 #endif /* INVARIANTS */
10281                 adp->ad_state &= ~ATTACHED;
10282                 adp->ad_state |= UNDONE;
10283         }
10284         /*
10285          * The on-disk inode cannot claim to be any larger than the last
10286          * fragment that has been written. Otherwise, the on-disk inode
10287          * might have fragments that were not the last block in the file
10288          * which would corrupt the filesystem.
10289          */
10290         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10291              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10292                 if (adp->ad_offset >= UFS_NDADDR)
10293                         break;
10294                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10295                 /* keep going until hitting a rollback to a frag */
10296                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10297                         continue;
10298                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10299                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10300 #ifdef INVARIANTS
10301                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10302                                 panic("softdep_write_inodeblock: 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("softdep_write_inodeblock: lost dep2");
10311 #endif /* INVARIANTS */
10312                         dp->di_ib[i] = 0;
10313                 }
10314                 return;
10315         }
10316         /*
10317          * If we have zero'ed out the last allocated block of the file,
10318          * roll back the size to the last currently allocated block.
10319          * We know that this last allocated block is a full-sized as
10320          * we already checked for fragments in the loop above.
10321          */
10322         if (lastadp != NULL &&
10323             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10324                 for (i = lastadp->ad_offset; i >= 0; i--)
10325                         if (dp->di_db[i] != 0)
10326                                 break;
10327                 dp->di_size = (i + 1) * fs->fs_bsize;
10328         }
10329         /*
10330          * The only dependencies are for indirect blocks.
10331          *
10332          * The file size for indirect block additions is not guaranteed.
10333          * Such a guarantee would be non-trivial to achieve. The conventional
10334          * synchronous write implementation also does not make this guarantee.
10335          * Fsck should catch and fix discrepancies. Arguably, the file size
10336          * can be over-estimated without destroying integrity when the file
10337          * moves into the indirect blocks (i.e., is large). If we want to
10338          * postpone fsck, we are stuck with this argument.
10339          */
10340         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10341                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10342 }
10343                 
10344 /*
10345  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10346  * Note that any bug fixes made to this routine must be done in the
10347  * version found above.
10348  *
10349  * Called from within the procedure above to deal with unsatisfied
10350  * allocation dependencies in an inodeblock. The buffer must be
10351  * locked, thus, no I/O completion operations can occur while we
10352  * are manipulating its associated dependencies.
10353  */
10354 static void 
10355 initiate_write_inodeblock_ufs2(inodedep, bp)
10356         struct inodedep *inodedep;
10357         struct buf *bp;                 /* The inode block */
10358 {
10359         struct allocdirect *adp, *lastadp;
10360         struct ufs2_dinode *dp;
10361         struct ufs2_dinode *sip;
10362         struct inoref *inoref;
10363         struct ufsmount *ump;
10364         struct fs *fs;
10365         ufs_lbn_t i;
10366 #ifdef INVARIANTS
10367         ufs_lbn_t prevlbn = 0;
10368 #endif
10369         int deplist;
10370
10371         if (inodedep->id_state & IOSTARTED)
10372                 panic("initiate_write_inodeblock_ufs2: already started");
10373         inodedep->id_state |= IOSTARTED;
10374         fs = inodedep->id_fs;
10375         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10376         LOCK_OWNED(ump);
10377         dp = (struct ufs2_dinode *)bp->b_data +
10378             ino_to_fsbo(fs, inodedep->id_ino);
10379
10380         /*
10381          * If we're on the unlinked list but have not yet written our
10382          * next pointer initialize it here.
10383          */
10384         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10385                 struct inodedep *inon;
10386
10387                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10388                 dp->di_freelink = inon ? inon->id_ino : 0;
10389         }
10390         /*
10391          * If the bitmap is not yet written, then the allocated
10392          * inode cannot be written to disk.
10393          */
10394         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10395                 if (inodedep->id_savedino2 != NULL)
10396                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10397                 FREE_LOCK(ump);
10398                 sip = malloc(sizeof(struct ufs2_dinode),
10399                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10400                 ACQUIRE_LOCK(ump);
10401                 inodedep->id_savedino2 = sip;
10402                 *inodedep->id_savedino2 = *dp;
10403                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10404                 dp->di_gen = inodedep->id_savedino2->di_gen;
10405                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10406                 return;
10407         }
10408         /*
10409          * If no dependencies, then there is nothing to roll back.
10410          */
10411         inodedep->id_savedsize = dp->di_size;
10412         inodedep->id_savedextsize = dp->di_extsize;
10413         inodedep->id_savednlink = dp->di_nlink;
10414         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10415             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10416             TAILQ_EMPTY(&inodedep->id_inoreflst))
10417                 return;
10418         /*
10419          * Revert the link count to that of the first unwritten journal entry.
10420          */
10421         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10422         if (inoref)
10423                 dp->di_nlink = inoref->if_nlink;
10424
10425         /*
10426          * Set the ext data dependencies to busy.
10427          */
10428         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10429              adp = TAILQ_NEXT(adp, ad_next)) {
10430 #ifdef INVARIANTS
10431                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10432                         panic("softdep_write_inodeblock: lbn order");
10433                 prevlbn = adp->ad_offset;
10434                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10435                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10436                             "softdep_write_inodeblock",
10437                             (intmax_t)adp->ad_offset,
10438                             (intmax_t)dp->di_extb[adp->ad_offset],
10439                             (intmax_t)adp->ad_newblkno);
10440                 deplist |= 1 << adp->ad_offset;
10441                 if ((adp->ad_state & ATTACHED) == 0)
10442                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10443                             adp->ad_state);
10444 #endif /* INVARIANTS */
10445                 adp->ad_state &= ~ATTACHED;
10446                 adp->ad_state |= UNDONE;
10447         }
10448         /*
10449          * The on-disk inode cannot claim to be any larger than the last
10450          * fragment that has been written. Otherwise, the on-disk inode
10451          * might have fragments that were not the last block in the ext
10452          * data which would corrupt the filesystem.
10453          */
10454         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10455              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10456                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10457                 /* keep going until hitting a rollback to a frag */
10458                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10459                         continue;
10460                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10461                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10462 #ifdef INVARIANTS
10463                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10464                                 panic("softdep_write_inodeblock: lost dep1");
10465 #endif /* INVARIANTS */
10466                         dp->di_extb[i] = 0;
10467                 }
10468                 lastadp = NULL;
10469                 break;
10470         }
10471         /*
10472          * If we have zero'ed out the last allocated block of the ext
10473          * data, roll back the size to the last currently allocated block.
10474          * We know that this last allocated block is a full-sized as
10475          * we already checked for fragments in the loop above.
10476          */
10477         if (lastadp != NULL &&
10478             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10479                 for (i = lastadp->ad_offset; i >= 0; i--)
10480                         if (dp->di_extb[i] != 0)
10481                                 break;
10482                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10483         }
10484         /*
10485          * Set the file data dependencies to busy.
10486          */
10487         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10488              adp = TAILQ_NEXT(adp, ad_next)) {
10489 #ifdef INVARIANTS
10490                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10491                         panic("softdep_write_inodeblock: lbn order");
10492                 if ((adp->ad_state & ATTACHED) == 0)
10493                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10494                 prevlbn = adp->ad_offset;
10495                 if (adp->ad_offset < UFS_NDADDR &&
10496                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10497                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10498                             "softdep_write_inodeblock",
10499                             (intmax_t)adp->ad_offset,
10500                             (intmax_t)dp->di_db[adp->ad_offset],
10501                             (intmax_t)adp->ad_newblkno);
10502                 if (adp->ad_offset >= UFS_NDADDR &&
10503                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10504                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
10505                             "softdep_write_inodeblock:",
10506                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10507                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10508                             (intmax_t)adp->ad_newblkno);
10509                 deplist |= 1 << adp->ad_offset;
10510                 if ((adp->ad_state & ATTACHED) == 0)
10511                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10512                             adp->ad_state);
10513 #endif /* INVARIANTS */
10514                 adp->ad_state &= ~ATTACHED;
10515                 adp->ad_state |= UNDONE;
10516         }
10517         /*
10518          * The on-disk inode cannot claim to be any larger than the last
10519          * fragment that has been written. Otherwise, the on-disk inode
10520          * might have fragments that were not the last block in the file
10521          * which would corrupt the filesystem.
10522          */
10523         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10524              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10525                 if (adp->ad_offset >= UFS_NDADDR)
10526                         break;
10527                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10528                 /* keep going until hitting a rollback to a frag */
10529                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10530                         continue;
10531                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10532                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10533 #ifdef INVARIANTS
10534                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10535                                 panic("softdep_write_inodeblock: lost dep2");
10536 #endif /* INVARIANTS */
10537                         dp->di_db[i] = 0;
10538                 }
10539                 for (i = 0; i < UFS_NIADDR; i++) {
10540 #ifdef INVARIANTS
10541                         if (dp->di_ib[i] != 0 &&
10542                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10543                                 panic("softdep_write_inodeblock: lost dep3");
10544 #endif /* INVARIANTS */
10545                         dp->di_ib[i] = 0;
10546                 }
10547                 return;
10548         }
10549         /*
10550          * If we have zero'ed out the last allocated block of the file,
10551          * roll back the size to the last currently allocated block.
10552          * We know that this last allocated block is a full-sized as
10553          * we already checked for fragments in the loop above.
10554          */
10555         if (lastadp != NULL &&
10556             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10557                 for (i = lastadp->ad_offset; i >= 0; i--)
10558                         if (dp->di_db[i] != 0)
10559                                 break;
10560                 dp->di_size = (i + 1) * fs->fs_bsize;
10561         }
10562         /*
10563          * The only dependencies are for indirect blocks.
10564          *
10565          * The file size for indirect block additions is not guaranteed.
10566          * Such a guarantee would be non-trivial to achieve. The conventional
10567          * synchronous write implementation also does not make this guarantee.
10568          * Fsck should catch and fix discrepancies. Arguably, the file size
10569          * can be over-estimated without destroying integrity when the file
10570          * moves into the indirect blocks (i.e., is large). If we want to
10571          * postpone fsck, we are stuck with this argument.
10572          */
10573         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10574                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10575 }
10576
10577 /*
10578  * Cancel an indirdep as a result of truncation.  Release all of the
10579  * children allocindirs and place their journal work on the appropriate
10580  * list.
10581  */
10582 static void
10583 cancel_indirdep(indirdep, bp, freeblks)
10584         struct indirdep *indirdep;
10585         struct buf *bp;
10586         struct freeblks *freeblks;
10587 {
10588         struct allocindir *aip;
10589
10590         /*
10591          * None of the indirect pointers will ever be visible,
10592          * so they can simply be tossed. GOINGAWAY ensures
10593          * that allocated pointers will be saved in the buffer
10594          * cache until they are freed. Note that they will
10595          * only be able to be found by their physical address
10596          * since the inode mapping the logical address will
10597          * be gone. The save buffer used for the safe copy
10598          * was allocated in setup_allocindir_phase2 using
10599          * the physical address so it could be used for this
10600          * purpose. Hence we swap the safe copy with the real
10601          * copy, allowing the safe copy to be freed and holding
10602          * on to the real copy for later use in indir_trunc.
10603          */
10604         if (indirdep->ir_state & GOINGAWAY)
10605                 panic("cancel_indirdep: already gone");
10606         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10607                 indirdep->ir_state |= DEPCOMPLETE;
10608                 LIST_REMOVE(indirdep, ir_next);
10609         }
10610         indirdep->ir_state |= GOINGAWAY;
10611         /*
10612          * Pass in bp for blocks still have journal writes
10613          * pending so we can cancel them on their own.
10614          */
10615         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10616                 cancel_allocindir(aip, bp, freeblks, 0);
10617         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10618                 cancel_allocindir(aip, NULL, freeblks, 0);
10619         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10620                 cancel_allocindir(aip, NULL, freeblks, 0);
10621         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10622                 cancel_allocindir(aip, NULL, freeblks, 0);
10623         /*
10624          * If there are pending partial truncations we need to keep the
10625          * old block copy around until they complete.  This is because
10626          * the current b_data is not a perfect superset of the available
10627          * blocks.
10628          */
10629         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10630                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10631         else
10632                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10633         WORKLIST_REMOVE(&indirdep->ir_list);
10634         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10635         indirdep->ir_bp = NULL;
10636         indirdep->ir_freeblks = freeblks;
10637 }
10638
10639 /*
10640  * Free an indirdep once it no longer has new pointers to track.
10641  */
10642 static void
10643 free_indirdep(indirdep)
10644         struct indirdep *indirdep;
10645 {
10646
10647         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10648             ("free_indirdep: Indir trunc list not empty."));
10649         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10650             ("free_indirdep: Complete head not empty."));
10651         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10652             ("free_indirdep: write head not empty."));
10653         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10654             ("free_indirdep: done head not empty."));
10655         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10656             ("free_indirdep: deplist head not empty."));
10657         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10658             ("free_indirdep: %p still on newblk list.", indirdep));
10659         KASSERT(indirdep->ir_saveddata == NULL,
10660             ("free_indirdep: %p still has saved data.", indirdep));
10661         if (indirdep->ir_state & ONWORKLIST)
10662                 WORKLIST_REMOVE(&indirdep->ir_list);
10663         WORKITEM_FREE(indirdep, D_INDIRDEP);
10664 }
10665
10666 /*
10667  * Called before a write to an indirdep.  This routine is responsible for
10668  * rolling back pointers to a safe state which includes only those
10669  * allocindirs which have been completed.
10670  */
10671 static void
10672 initiate_write_indirdep(indirdep, bp)
10673         struct indirdep *indirdep;
10674         struct buf *bp;
10675 {
10676         struct ufsmount *ump;
10677
10678         indirdep->ir_state |= IOSTARTED;
10679         if (indirdep->ir_state & GOINGAWAY)
10680                 panic("disk_io_initiation: indirdep gone");
10681         /*
10682          * If there are no remaining dependencies, this will be writing
10683          * the real pointers.
10684          */
10685         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10686             TAILQ_EMPTY(&indirdep->ir_trunc))
10687                 return;
10688         /*
10689          * Replace up-to-date version with safe version.
10690          */
10691         if (indirdep->ir_saveddata == NULL) {
10692                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10693                 LOCK_OWNED(ump);
10694                 FREE_LOCK(ump);
10695                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10696                     M_SOFTDEP_FLAGS);
10697                 ACQUIRE_LOCK(ump);
10698         }
10699         indirdep->ir_state &= ~ATTACHED;
10700         indirdep->ir_state |= UNDONE;
10701         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10702         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10703             bp->b_bcount);
10704 }
10705
10706 /*
10707  * Called when an inode has been cleared in a cg bitmap.  This finally
10708  * eliminates any canceled jaddrefs
10709  */
10710 void
10711 softdep_setup_inofree(mp, bp, ino, wkhd)
10712         struct mount *mp;
10713         struct buf *bp;
10714         ino_t ino;
10715         struct workhead *wkhd;
10716 {
10717         struct worklist *wk, *wkn;
10718         struct inodedep *inodedep;
10719         struct ufsmount *ump;
10720         uint8_t *inosused;
10721         struct cg *cgp;
10722         struct fs *fs;
10723
10724         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10725             ("softdep_setup_inofree called on non-softdep filesystem"));
10726         ump = VFSTOUFS(mp);
10727         ACQUIRE_LOCK(ump);
10728         fs = ump->um_fs;
10729         cgp = (struct cg *)bp->b_data;
10730         inosused = cg_inosused(cgp);
10731         if (isset(inosused, ino % fs->fs_ipg))
10732                 panic("softdep_setup_inofree: inode %ju not freed.",
10733                     (uintmax_t)ino);
10734         if (inodedep_lookup(mp, ino, 0, &inodedep))
10735                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10736                     (uintmax_t)ino, inodedep);
10737         if (wkhd) {
10738                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10739                         if (wk->wk_type != D_JADDREF)
10740                                 continue;
10741                         WORKLIST_REMOVE(wk);
10742                         /*
10743                          * We can free immediately even if the jaddref
10744                          * isn't attached in a background write as now
10745                          * the bitmaps are reconciled.
10746                          */
10747                         wk->wk_state |= COMPLETE | ATTACHED;
10748                         free_jaddref(WK_JADDREF(wk));
10749                 }
10750                 jwork_move(&bp->b_dep, wkhd);
10751         }
10752         FREE_LOCK(ump);
10753 }
10754
10755
10756 /*
10757  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10758  * map.  Any dependencies waiting for the write to clear are added to the
10759  * buf's list and any jnewblks that are being canceled are discarded
10760  * immediately.
10761  */
10762 void
10763 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10764         struct mount *mp;
10765         struct buf *bp;
10766         ufs2_daddr_t blkno;
10767         int frags;
10768         struct workhead *wkhd;
10769 {
10770         struct bmsafemap *bmsafemap;
10771         struct jnewblk *jnewblk;
10772         struct ufsmount *ump;
10773         struct worklist *wk;
10774         struct fs *fs;
10775 #ifdef SUJ_DEBUG
10776         uint8_t *blksfree;
10777         struct cg *cgp;
10778         ufs2_daddr_t jstart;
10779         ufs2_daddr_t jend;
10780         ufs2_daddr_t end;
10781         long bno;
10782         int i;
10783 #endif
10784
10785         CTR3(KTR_SUJ,
10786             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10787             blkno, frags, wkhd);
10788
10789         ump = VFSTOUFS(mp);
10790         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10791             ("softdep_setup_blkfree called on non-softdep filesystem"));
10792         ACQUIRE_LOCK(ump);
10793         /* Lookup the bmsafemap so we track when it is dirty. */
10794         fs = ump->um_fs;
10795         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10796         /*
10797          * Detach any jnewblks which have been canceled.  They must linger
10798          * until the bitmap is cleared again by ffs_blkfree() to prevent
10799          * an unjournaled allocation from hitting the disk.
10800          */
10801         if (wkhd) {
10802                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10803                         CTR2(KTR_SUJ,
10804                             "softdep_setup_blkfree: blkno %jd wk type %d",
10805                             blkno, wk->wk_type);
10806                         WORKLIST_REMOVE(wk);
10807                         if (wk->wk_type != D_JNEWBLK) {
10808                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10809                                 continue;
10810                         }
10811                         jnewblk = WK_JNEWBLK(wk);
10812                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10813                             ("softdep_setup_blkfree: jnewblk not canceled."));
10814 #ifdef SUJ_DEBUG
10815                         /*
10816                          * Assert that this block is free in the bitmap
10817                          * before we discard the jnewblk.
10818                          */
10819                         cgp = (struct cg *)bp->b_data;
10820                         blksfree = cg_blksfree(cgp);
10821                         bno = dtogd(fs, jnewblk->jn_blkno);
10822                         for (i = jnewblk->jn_oldfrags;
10823                             i < jnewblk->jn_frags; i++) {
10824                                 if (isset(blksfree, bno + i))
10825                                         continue;
10826                                 panic("softdep_setup_blkfree: not free");
10827                         }
10828 #endif
10829                         /*
10830                          * Even if it's not attached we can free immediately
10831                          * as the new bitmap is correct.
10832                          */
10833                         wk->wk_state |= COMPLETE | ATTACHED;
10834                         free_jnewblk(jnewblk);
10835                 }
10836         }
10837
10838 #ifdef SUJ_DEBUG
10839         /*
10840          * Assert that we are not freeing a block which has an outstanding
10841          * allocation dependency.
10842          */
10843         fs = VFSTOUFS(mp)->um_fs;
10844         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10845         end = blkno + frags;
10846         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10847                 /*
10848                  * Don't match against blocks that will be freed when the
10849                  * background write is done.
10850                  */
10851                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10852                     (COMPLETE | DEPCOMPLETE))
10853                         continue;
10854                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10855                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10856                 if ((blkno >= jstart && blkno < jend) ||
10857                     (end > jstart && end <= jend)) {
10858                         printf("state 0x%X %jd - %d %d dep %p\n",
10859                             jnewblk->jn_state, jnewblk->jn_blkno,
10860                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10861                             jnewblk->jn_dep);
10862                         panic("softdep_setup_blkfree: "
10863                             "%jd-%jd(%d) overlaps with %jd-%jd",
10864                             blkno, end, frags, jstart, jend);
10865                 }
10866         }
10867 #endif
10868         FREE_LOCK(ump);
10869 }
10870
10871 /*
10872  * Revert a block allocation when the journal record that describes it
10873  * is not yet written.
10874  */
10875 static int
10876 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10877         struct jnewblk *jnewblk;
10878         struct fs *fs;
10879         struct cg *cgp;
10880         uint8_t *blksfree;
10881 {
10882         ufs1_daddr_t fragno;
10883         long cgbno, bbase;
10884         int frags, blk;
10885         int i;
10886
10887         frags = 0;
10888         cgbno = dtogd(fs, jnewblk->jn_blkno);
10889         /*
10890          * We have to test which frags need to be rolled back.  We may
10891          * be operating on a stale copy when doing background writes.
10892          */
10893         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10894                 if (isclr(blksfree, cgbno + i))
10895                         frags++;
10896         if (frags == 0)
10897                 return (0);
10898         /*
10899          * This is mostly ffs_blkfree() sans some validation and
10900          * superblock updates.
10901          */
10902         if (frags == fs->fs_frag) {
10903                 fragno = fragstoblks(fs, cgbno);
10904                 ffs_setblock(fs, blksfree, fragno);
10905                 ffs_clusteracct(fs, cgp, fragno, 1);
10906                 cgp->cg_cs.cs_nbfree++;
10907         } else {
10908                 cgbno += jnewblk->jn_oldfrags;
10909                 bbase = cgbno - fragnum(fs, cgbno);
10910                 /* Decrement the old frags.  */
10911                 blk = blkmap(fs, blksfree, bbase);
10912                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10913                 /* Deallocate the fragment */
10914                 for (i = 0; i < frags; i++)
10915                         setbit(blksfree, cgbno + i);
10916                 cgp->cg_cs.cs_nffree += frags;
10917                 /* Add back in counts associated with the new frags */
10918                 blk = blkmap(fs, blksfree, bbase);
10919                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10920                 /* If a complete block has been reassembled, account for it. */
10921                 fragno = fragstoblks(fs, bbase);
10922                 if (ffs_isblock(fs, blksfree, fragno)) {
10923                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10924                         ffs_clusteracct(fs, cgp, fragno, 1);
10925                         cgp->cg_cs.cs_nbfree++;
10926                 }
10927         }
10928         stat_jnewblk++;
10929         jnewblk->jn_state &= ~ATTACHED;
10930         jnewblk->jn_state |= UNDONE;
10931
10932         return (frags);
10933 }
10934
10935 static void
10936 initiate_write_bmsafemap(bmsafemap, bp)
10937         struct bmsafemap *bmsafemap;
10938         struct buf *bp;                 /* The cg block. */
10939 {
10940         struct jaddref *jaddref;
10941         struct jnewblk *jnewblk;
10942         uint8_t *inosused;
10943         uint8_t *blksfree;
10944         struct cg *cgp;
10945         struct fs *fs;
10946         ino_t ino;
10947
10948         /*
10949          * If this is a background write, we did this at the time that
10950          * the copy was made, so do not need to do it again.
10951          */
10952         if (bmsafemap->sm_state & IOSTARTED)
10953                 return;
10954         bmsafemap->sm_state |= IOSTARTED;
10955         /*
10956          * Clear any inode allocations which are pending journal writes.
10957          */
10958         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10959                 cgp = (struct cg *)bp->b_data;
10960                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10961                 inosused = cg_inosused(cgp);
10962                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10963                         ino = jaddref->ja_ino % fs->fs_ipg;
10964                         if (isset(inosused, ino)) {
10965                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10966                                         cgp->cg_cs.cs_ndir--;
10967                                 cgp->cg_cs.cs_nifree++;
10968                                 clrbit(inosused, ino);
10969                                 jaddref->ja_state &= ~ATTACHED;
10970                                 jaddref->ja_state |= UNDONE;
10971                                 stat_jaddref++;
10972                         } else
10973                                 panic("initiate_write_bmsafemap: inode %ju "
10974                                     "marked free", (uintmax_t)jaddref->ja_ino);
10975                 }
10976         }
10977         /*
10978          * Clear any block allocations which are pending journal writes.
10979          */
10980         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10981                 cgp = (struct cg *)bp->b_data;
10982                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10983                 blksfree = cg_blksfree(cgp);
10984                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10985                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10986                                 continue;
10987                         panic("initiate_write_bmsafemap: block %jd "
10988                             "marked free", jnewblk->jn_blkno);
10989                 }
10990         }
10991         /*
10992          * Move allocation lists to the written lists so they can be
10993          * cleared once the block write is complete.
10994          */
10995         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10996             inodedep, id_deps);
10997         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10998             newblk, nb_deps);
10999         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11000             wk_list);
11001 }
11002
11003 /*
11004  * This routine is called during the completion interrupt
11005  * service routine for a disk write (from the procedure called
11006  * by the device driver to inform the filesystem caches of
11007  * a request completion).  It should be called early in this
11008  * procedure, before the block is made available to other
11009  * processes or other routines are called.
11010  *
11011  */
11012 static void 
11013 softdep_disk_write_complete(bp)
11014         struct buf *bp;         /* describes the completed disk write */
11015 {
11016         struct worklist *wk;
11017         struct worklist *owk;
11018         struct ufsmount *ump;
11019         struct workhead reattach;
11020         struct freeblks *freeblks;
11021         struct buf *sbp;
11022
11023         ump = softdep_bp_to_mp(bp);
11024         if (ump == NULL)
11025                 return;
11026
11027         sbp = NULL;
11028
11029         /*
11030          * If an error occurred while doing the write, then the data
11031          * has not hit the disk and the dependencies cannot be processed.
11032          * But we do have to go through and roll forward any dependencies
11033          * that were rolled back before the disk write.
11034          */
11035         ACQUIRE_LOCK(ump);
11036         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11037                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11038                         switch (wk->wk_type) {
11039
11040                         case D_PAGEDEP:
11041                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11042                                 continue;
11043
11044                         case D_INODEDEP:
11045                                 handle_written_inodeblock(WK_INODEDEP(wk),
11046                                     bp, 0);
11047                                 continue;
11048
11049                         case D_BMSAFEMAP:
11050                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11051                                     bp, 0);
11052                                 continue;
11053
11054                         case D_INDIRDEP:
11055                                 handle_written_indirdep(WK_INDIRDEP(wk),
11056                                     bp, &sbp, 0);
11057                                 continue;
11058                         default:
11059                                 /* nothing to roll forward */
11060                                 continue;
11061                         }
11062                 }
11063                 FREE_LOCK(ump);
11064                 return;
11065         }
11066         LIST_INIT(&reattach);
11067
11068         /*
11069          * Ump SU lock must not be released anywhere in this code segment.
11070          */
11071         owk = NULL;
11072         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11073                 WORKLIST_REMOVE(wk);
11074                 atomic_add_long(&dep_write[wk->wk_type], 1);
11075                 if (wk == owk)
11076                         panic("duplicate worklist: %p\n", wk);
11077                 owk = wk;
11078                 switch (wk->wk_type) {
11079
11080                 case D_PAGEDEP:
11081                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11082                             WRITESUCCEEDED))
11083                                 WORKLIST_INSERT(&reattach, wk);
11084                         continue;
11085
11086                 case D_INODEDEP:
11087                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11088                             WRITESUCCEEDED))
11089                                 WORKLIST_INSERT(&reattach, wk);
11090                         continue;
11091
11092                 case D_BMSAFEMAP:
11093                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11094                             WRITESUCCEEDED))
11095                                 WORKLIST_INSERT(&reattach, wk);
11096                         continue;
11097
11098                 case D_MKDIR:
11099                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11100                         continue;
11101
11102                 case D_ALLOCDIRECT:
11103                         wk->wk_state |= COMPLETE;
11104                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11105                         continue;
11106
11107                 case D_ALLOCINDIR:
11108                         wk->wk_state |= COMPLETE;
11109                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11110                         continue;
11111
11112                 case D_INDIRDEP:
11113                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11114                             WRITESUCCEEDED))
11115                                 WORKLIST_INSERT(&reattach, wk);
11116                         continue;
11117
11118                 case D_FREEBLKS:
11119                         wk->wk_state |= COMPLETE;
11120                         freeblks = WK_FREEBLKS(wk);
11121                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11122                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11123                                 add_to_worklist(wk, WK_NODELAY);
11124                         continue;
11125
11126                 case D_FREEWORK:
11127                         handle_written_freework(WK_FREEWORK(wk));
11128                         break;
11129
11130                 case D_JSEGDEP:
11131                         free_jsegdep(WK_JSEGDEP(wk));
11132                         continue;
11133
11134                 case D_JSEG:
11135                         handle_written_jseg(WK_JSEG(wk), bp);
11136                         continue;
11137
11138                 case D_SBDEP:
11139                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11140                                 WORKLIST_INSERT(&reattach, wk);
11141                         continue;
11142
11143                 case D_FREEDEP:
11144                         free_freedep(WK_FREEDEP(wk));
11145                         continue;
11146
11147                 default:
11148                         panic("handle_disk_write_complete: Unknown type %s",
11149                             TYPENAME(wk->wk_type));
11150                         /* NOTREACHED */
11151                 }
11152         }
11153         /*
11154          * Reattach any requests that must be redone.
11155          */
11156         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11157                 WORKLIST_REMOVE(wk);
11158                 WORKLIST_INSERT(&bp->b_dep, wk);
11159         }
11160         FREE_LOCK(ump);
11161         if (sbp)
11162                 brelse(sbp);
11163 }
11164
11165 /*
11166  * Called from within softdep_disk_write_complete above. Note that
11167  * this routine is always called from interrupt level with further
11168  * splbio interrupts blocked.
11169  */
11170 static void 
11171 handle_allocdirect_partdone(adp, wkhd)
11172         struct allocdirect *adp;        /* the completed allocdirect */
11173         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11174 {
11175         struct allocdirectlst *listhead;
11176         struct allocdirect *listadp;
11177         struct inodedep *inodedep;
11178         long bsize;
11179
11180         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11181                 return;
11182         /*
11183          * The on-disk inode cannot claim to be any larger than the last
11184          * fragment that has been written. Otherwise, the on-disk inode
11185          * might have fragments that were not the last block in the file
11186          * which would corrupt the filesystem. Thus, we cannot free any
11187          * allocdirects after one whose ad_oldblkno claims a fragment as
11188          * these blocks must be rolled back to zero before writing the inode.
11189          * We check the currently active set of allocdirects in id_inoupdt
11190          * or id_extupdt as appropriate.
11191          */
11192         inodedep = adp->ad_inodedep;
11193         bsize = inodedep->id_fs->fs_bsize;
11194         if (adp->ad_state & EXTDATA)
11195                 listhead = &inodedep->id_extupdt;
11196         else
11197                 listhead = &inodedep->id_inoupdt;
11198         TAILQ_FOREACH(listadp, listhead, ad_next) {
11199                 /* found our block */
11200                 if (listadp == adp)
11201                         break;
11202                 /* continue if ad_oldlbn is not a fragment */
11203                 if (listadp->ad_oldsize == 0 ||
11204                     listadp->ad_oldsize == bsize)
11205                         continue;
11206                 /* hit a fragment */
11207                 return;
11208         }
11209         /*
11210          * If we have reached the end of the current list without
11211          * finding the just finished dependency, then it must be
11212          * on the future dependency list. Future dependencies cannot
11213          * be freed until they are moved to the current list.
11214          */
11215         if (listadp == NULL) {
11216 #ifdef DEBUG
11217                 if (adp->ad_state & EXTDATA)
11218                         listhead = &inodedep->id_newextupdt;
11219                 else
11220                         listhead = &inodedep->id_newinoupdt;
11221                 TAILQ_FOREACH(listadp, listhead, ad_next)
11222                         /* found our block */
11223                         if (listadp == adp)
11224                                 break;
11225                 if (listadp == NULL)
11226                         panic("handle_allocdirect_partdone: lost dep");
11227 #endif /* DEBUG */
11228                 return;
11229         }
11230         /*
11231          * If we have found the just finished dependency, then queue
11232          * it along with anything that follows it that is complete.
11233          * Since the pointer has not yet been written in the inode
11234          * as the dependency prevents it, place the allocdirect on the
11235          * bufwait list where it will be freed once the pointer is
11236          * valid.
11237          */
11238         if (wkhd == NULL)
11239                 wkhd = &inodedep->id_bufwait;
11240         for (; adp; adp = listadp) {
11241                 listadp = TAILQ_NEXT(adp, ad_next);
11242                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11243                         return;
11244                 TAILQ_REMOVE(listhead, adp, ad_next);
11245                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11246         }
11247 }
11248
11249 /*
11250  * Called from within softdep_disk_write_complete above.  This routine
11251  * completes successfully written allocindirs.
11252  */
11253 static void
11254 handle_allocindir_partdone(aip)
11255         struct allocindir *aip;         /* the completed allocindir */
11256 {
11257         struct indirdep *indirdep;
11258
11259         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11260                 return;
11261         indirdep = aip->ai_indirdep;
11262         LIST_REMOVE(aip, ai_next);
11263         /*
11264          * Don't set a pointer while the buffer is undergoing IO or while
11265          * we have active truncations.
11266          */
11267         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11268                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11269                 return;
11270         }
11271         if (indirdep->ir_state & UFS1FMT)
11272                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11273                     aip->ai_newblkno;
11274         else
11275                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11276                     aip->ai_newblkno;
11277         /*
11278          * Await the pointer write before freeing the allocindir.
11279          */
11280         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11281 }
11282
11283 /*
11284  * Release segments held on a jwork list.
11285  */
11286 static void
11287 handle_jwork(wkhd)
11288         struct workhead *wkhd;
11289 {
11290         struct worklist *wk;
11291
11292         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11293                 WORKLIST_REMOVE(wk);
11294                 switch (wk->wk_type) {
11295                 case D_JSEGDEP:
11296                         free_jsegdep(WK_JSEGDEP(wk));
11297                         continue;
11298                 case D_FREEDEP:
11299                         free_freedep(WK_FREEDEP(wk));
11300                         continue;
11301                 case D_FREEFRAG:
11302                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11303                         WORKITEM_FREE(wk, D_FREEFRAG);
11304                         continue;
11305                 case D_FREEWORK:
11306                         handle_written_freework(WK_FREEWORK(wk));
11307                         continue;
11308                 default:
11309                         panic("handle_jwork: Unknown type %s\n",
11310                             TYPENAME(wk->wk_type));
11311                 }
11312         }
11313 }
11314
11315 /*
11316  * Handle the bufwait list on an inode when it is safe to release items
11317  * held there.  This normally happens after an inode block is written but
11318  * may be delayed and handled later if there are pending journal items that
11319  * are not yet safe to be released.
11320  */
11321 static struct freefile *
11322 handle_bufwait(inodedep, refhd)
11323         struct inodedep *inodedep;
11324         struct workhead *refhd;
11325 {
11326         struct jaddref *jaddref;
11327         struct freefile *freefile;
11328         struct worklist *wk;
11329
11330         freefile = NULL;
11331         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11332                 WORKLIST_REMOVE(wk);
11333                 switch (wk->wk_type) {
11334                 case D_FREEFILE:
11335                         /*
11336                          * We defer adding freefile to the worklist
11337                          * until all other additions have been made to
11338                          * ensure that it will be done after all the
11339                          * old blocks have been freed.
11340                          */
11341                         if (freefile != NULL)
11342                                 panic("handle_bufwait: freefile");
11343                         freefile = WK_FREEFILE(wk);
11344                         continue;
11345
11346                 case D_MKDIR:
11347                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11348                         continue;
11349
11350                 case D_DIRADD:
11351                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11352                         continue;
11353
11354                 case D_FREEFRAG:
11355                         wk->wk_state |= COMPLETE;
11356                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11357                                 add_to_worklist(wk, 0);
11358                         continue;
11359
11360                 case D_DIRREM:
11361                         wk->wk_state |= COMPLETE;
11362                         add_to_worklist(wk, 0);
11363                         continue;
11364
11365                 case D_ALLOCDIRECT:
11366                 case D_ALLOCINDIR:
11367                         free_newblk(WK_NEWBLK(wk));
11368                         continue;
11369
11370                 case D_JNEWBLK:
11371                         wk->wk_state |= COMPLETE;
11372                         free_jnewblk(WK_JNEWBLK(wk));
11373                         continue;
11374
11375                 /*
11376                  * Save freed journal segments and add references on
11377                  * the supplied list which will delay their release
11378                  * until the cg bitmap is cleared on disk.
11379                  */
11380                 case D_JSEGDEP:
11381                         if (refhd == NULL)
11382                                 free_jsegdep(WK_JSEGDEP(wk));
11383                         else
11384                                 WORKLIST_INSERT(refhd, wk);
11385                         continue;
11386
11387                 case D_JADDREF:
11388                         jaddref = WK_JADDREF(wk);
11389                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11390                             if_deps);
11391                         /*
11392                          * Transfer any jaddrefs to the list to be freed with
11393                          * the bitmap if we're handling a removed file.
11394                          */
11395                         if (refhd == NULL) {
11396                                 wk->wk_state |= COMPLETE;
11397                                 free_jaddref(jaddref);
11398                         } else
11399                                 WORKLIST_INSERT(refhd, wk);
11400                         continue;
11401
11402                 default:
11403                         panic("handle_bufwait: Unknown type %p(%s)",
11404                             wk, TYPENAME(wk->wk_type));
11405                         /* NOTREACHED */
11406                 }
11407         }
11408         return (freefile);
11409 }
11410 /*
11411  * Called from within softdep_disk_write_complete above to restore
11412  * in-memory inode block contents to their most up-to-date state. Note
11413  * that this routine is always called from interrupt level with further
11414  * interrupts from this device blocked.
11415  *
11416  * If the write did not succeed, we will do all the roll-forward
11417  * operations, but we will not take the actions that will allow its
11418  * dependencies to be processed.
11419  */
11420 static int 
11421 handle_written_inodeblock(inodedep, bp, flags)
11422         struct inodedep *inodedep;
11423         struct buf *bp;         /* buffer containing the inode block */
11424         int flags;
11425 {
11426         struct freefile *freefile;
11427         struct allocdirect *adp, *nextadp;
11428         struct ufs1_dinode *dp1 = NULL;
11429         struct ufs2_dinode *dp2 = NULL;
11430         struct workhead wkhd;
11431         int hadchanges, fstype;
11432         ino_t freelink;
11433
11434         LIST_INIT(&wkhd);
11435         hadchanges = 0;
11436         freefile = NULL;
11437         if ((inodedep->id_state & IOSTARTED) == 0)
11438                 panic("handle_written_inodeblock: not started");
11439         inodedep->id_state &= ~IOSTARTED;
11440         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11441                 fstype = UFS1;
11442                 dp1 = (struct ufs1_dinode *)bp->b_data +
11443                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11444                 freelink = dp1->di_freelink;
11445         } else {
11446                 fstype = UFS2;
11447                 dp2 = (struct ufs2_dinode *)bp->b_data +
11448                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11449                 freelink = dp2->di_freelink;
11450         }
11451         /*
11452          * Leave this inodeblock dirty until it's in the list.
11453          */
11454         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11455             (flags & WRITESUCCEEDED)) {
11456                 struct inodedep *inon;
11457
11458                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11459                 if ((inon == NULL && freelink == 0) ||
11460                     (inon && inon->id_ino == freelink)) {
11461                         if (inon)
11462                                 inon->id_state |= UNLINKPREV;
11463                         inodedep->id_state |= UNLINKNEXT;
11464                 }
11465                 hadchanges = 1;
11466         }
11467         /*
11468          * If we had to rollback the inode allocation because of
11469          * bitmaps being incomplete, then simply restore it.
11470          * Keep the block dirty so that it will not be reclaimed until
11471          * all associated dependencies have been cleared and the
11472          * corresponding updates written to disk.
11473          */
11474         if (inodedep->id_savedino1 != NULL) {
11475                 hadchanges = 1;
11476                 if (fstype == UFS1)
11477                         *dp1 = *inodedep->id_savedino1;
11478                 else
11479                         *dp2 = *inodedep->id_savedino2;
11480                 free(inodedep->id_savedino1, M_SAVEDINO);
11481                 inodedep->id_savedino1 = NULL;
11482                 if ((bp->b_flags & B_DELWRI) == 0)
11483                         stat_inode_bitmap++;
11484                 bdirty(bp);
11485                 /*
11486                  * If the inode is clear here and GOINGAWAY it will never
11487                  * be written.  Process the bufwait and clear any pending
11488                  * work which may include the freefile.
11489                  */
11490                 if (inodedep->id_state & GOINGAWAY)
11491                         goto bufwait;
11492                 return (1);
11493         }
11494         if (flags & WRITESUCCEEDED)
11495                 inodedep->id_state |= COMPLETE;
11496         /*
11497          * Roll forward anything that had to be rolled back before 
11498          * the inode could be updated.
11499          */
11500         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11501                 nextadp = TAILQ_NEXT(adp, ad_next);
11502                 if (adp->ad_state & ATTACHED)
11503                         panic("handle_written_inodeblock: new entry");
11504                 if (fstype == UFS1) {
11505                         if (adp->ad_offset < UFS_NDADDR) {
11506                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11507                                         panic("%s %s #%jd mismatch %d != %jd",
11508                                             "handle_written_inodeblock:",
11509                                             "direct pointer",
11510                                             (intmax_t)adp->ad_offset,
11511                                             dp1->di_db[adp->ad_offset],
11512                                             (intmax_t)adp->ad_oldblkno);
11513                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11514                         } else {
11515                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11516                                     0)
11517                                         panic("%s: %s #%jd allocated as %d",
11518                                             "handle_written_inodeblock",
11519                                             "indirect pointer",
11520                                             (intmax_t)adp->ad_offset -
11521                                             UFS_NDADDR,
11522                                             dp1->di_ib[adp->ad_offset -
11523                                             UFS_NDADDR]);
11524                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11525                                     adp->ad_newblkno;
11526                         }
11527                 } else {
11528                         if (adp->ad_offset < UFS_NDADDR) {
11529                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11530                                         panic("%s: %s #%jd %s %jd != %jd",
11531                                             "handle_written_inodeblock",
11532                                             "direct pointer",
11533                                             (intmax_t)adp->ad_offset, "mismatch",
11534                                             (intmax_t)dp2->di_db[adp->ad_offset],
11535                                             (intmax_t)adp->ad_oldblkno);
11536                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11537                         } else {
11538                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11539                                     0)
11540                                         panic("%s: %s #%jd allocated as %jd",
11541                                             "handle_written_inodeblock",
11542                                             "indirect pointer",
11543                                             (intmax_t)adp->ad_offset -
11544                                             UFS_NDADDR,
11545                                             (intmax_t)
11546                                             dp2->di_ib[adp->ad_offset -
11547                                             UFS_NDADDR]);
11548                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11549                                     adp->ad_newblkno;
11550                         }
11551                 }
11552                 adp->ad_state &= ~UNDONE;
11553                 adp->ad_state |= ATTACHED;
11554                 hadchanges = 1;
11555         }
11556         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11557                 nextadp = TAILQ_NEXT(adp, ad_next);
11558                 if (adp->ad_state & ATTACHED)
11559                         panic("handle_written_inodeblock: new entry");
11560                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11561                         panic("%s: direct pointers #%jd %s %jd != %jd",
11562                             "handle_written_inodeblock",
11563                             (intmax_t)adp->ad_offset, "mismatch",
11564                             (intmax_t)dp2->di_extb[adp->ad_offset],
11565                             (intmax_t)adp->ad_oldblkno);
11566                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11567                 adp->ad_state &= ~UNDONE;
11568                 adp->ad_state |= ATTACHED;
11569                 hadchanges = 1;
11570         }
11571         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11572                 stat_direct_blk_ptrs++;
11573         /*
11574          * Reset the file size to its most up-to-date value.
11575          */
11576         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11577                 panic("handle_written_inodeblock: bad size");
11578         if (inodedep->id_savednlink > UFS_LINK_MAX)
11579                 panic("handle_written_inodeblock: Invalid link count "
11580                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11581                     inodedep);
11582         if (fstype == UFS1) {
11583                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11584                         dp1->di_nlink = inodedep->id_savednlink;
11585                         hadchanges = 1;
11586                 }
11587                 if (dp1->di_size != inodedep->id_savedsize) {
11588                         dp1->di_size = inodedep->id_savedsize;
11589                         hadchanges = 1;
11590                 }
11591         } else {
11592                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11593                         dp2->di_nlink = inodedep->id_savednlink;
11594                         hadchanges = 1;
11595                 }
11596                 if (dp2->di_size != inodedep->id_savedsize) {
11597                         dp2->di_size = inodedep->id_savedsize;
11598                         hadchanges = 1;
11599                 }
11600                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11601                         dp2->di_extsize = inodedep->id_savedextsize;
11602                         hadchanges = 1;
11603                 }
11604         }
11605         inodedep->id_savedsize = -1;
11606         inodedep->id_savedextsize = -1;
11607         inodedep->id_savednlink = -1;
11608         /*
11609          * If there were any rollbacks in the inode block, then it must be
11610          * marked dirty so that its will eventually get written back in
11611          * its correct form.
11612          */
11613         if (hadchanges)
11614                 bdirty(bp);
11615 bufwait:
11616         /*
11617          * If the write did not succeed, we have done all the roll-forward
11618          * operations, but we cannot take the actions that will allow its
11619          * dependencies to be processed.
11620          */
11621         if ((flags & WRITESUCCEEDED) == 0)
11622                 return (hadchanges);
11623         /*
11624          * Process any allocdirects that completed during the update.
11625          */
11626         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11627                 handle_allocdirect_partdone(adp, &wkhd);
11628         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11629                 handle_allocdirect_partdone(adp, &wkhd);
11630         /*
11631          * Process deallocations that were held pending until the
11632          * inode had been written to disk. Freeing of the inode
11633          * is delayed until after all blocks have been freed to
11634          * avoid creation of new <vfsid, inum, lbn> triples
11635          * before the old ones have been deleted.  Completely
11636          * unlinked inodes are not processed until the unlinked
11637          * inode list is written or the last reference is removed.
11638          */
11639         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11640                 freefile = handle_bufwait(inodedep, NULL);
11641                 if (freefile && !LIST_EMPTY(&wkhd)) {
11642                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11643                         freefile = NULL;
11644                 }
11645         }
11646         /*
11647          * Move rolled forward dependency completions to the bufwait list
11648          * now that those that were already written have been processed.
11649          */
11650         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11651                 panic("handle_written_inodeblock: bufwait but no changes");
11652         jwork_move(&inodedep->id_bufwait, &wkhd);
11653
11654         if (freefile != NULL) {
11655                 /*
11656                  * If the inode is goingaway it was never written.  Fake up
11657                  * the state here so free_inodedep() can succeed.
11658                  */
11659                 if (inodedep->id_state & GOINGAWAY)
11660                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11661                 if (free_inodedep(inodedep) == 0)
11662                         panic("handle_written_inodeblock: live inodedep %p",
11663                             inodedep);
11664                 add_to_worklist(&freefile->fx_list, 0);
11665                 return (0);
11666         }
11667
11668         /*
11669          * If no outstanding dependencies, free it.
11670          */
11671         if (free_inodedep(inodedep) ||
11672             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11673              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11674              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11675              LIST_FIRST(&inodedep->id_bufwait) == 0))
11676                 return (0);
11677         return (hadchanges);
11678 }
11679
11680 /*
11681  * Perform needed roll-forwards and kick off any dependencies that
11682  * can now be processed.
11683  *
11684  * If the write did not succeed, we will do all the roll-forward
11685  * operations, but we will not take the actions that will allow its
11686  * dependencies to be processed.
11687  */
11688 static int
11689 handle_written_indirdep(indirdep, bp, bpp, flags)
11690         struct indirdep *indirdep;
11691         struct buf *bp;
11692         struct buf **bpp;
11693         int flags;
11694 {
11695         struct allocindir *aip;
11696         struct buf *sbp;
11697         int chgs;
11698
11699         if (indirdep->ir_state & GOINGAWAY)
11700                 panic("handle_written_indirdep: indirdep gone");
11701         if ((indirdep->ir_state & IOSTARTED) == 0)
11702                 panic("handle_written_indirdep: IO not started");
11703         chgs = 0;
11704         /*
11705          * If there were rollbacks revert them here.
11706          */
11707         if (indirdep->ir_saveddata) {
11708                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11709                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11710                         free(indirdep->ir_saveddata, M_INDIRDEP);
11711                         indirdep->ir_saveddata = NULL;
11712                 }
11713                 chgs = 1;
11714         }
11715         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11716         indirdep->ir_state |= ATTACHED;
11717         /*
11718          * If the write did not succeed, we have done all the roll-forward
11719          * operations, but we cannot take the actions that will allow its
11720          * dependencies to be processed.
11721          */
11722         if ((flags & WRITESUCCEEDED) == 0) {
11723                 stat_indir_blk_ptrs++;
11724                 bdirty(bp);
11725                 return (1);
11726         }
11727         /*
11728          * Move allocindirs with written pointers to the completehd if
11729          * the indirdep's pointer is not yet written.  Otherwise
11730          * free them here.
11731          */
11732         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11733                 LIST_REMOVE(aip, ai_next);
11734                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11735                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11736                             ai_next);
11737                         newblk_freefrag(&aip->ai_block);
11738                         continue;
11739                 }
11740                 free_newblk(&aip->ai_block);
11741         }
11742         /*
11743          * Move allocindirs that have finished dependency processing from
11744          * the done list to the write list after updating the pointers.
11745          */
11746         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11747                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11748                         handle_allocindir_partdone(aip);
11749                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11750                                 panic("disk_write_complete: not gone");
11751                         chgs = 1;
11752                 }
11753         }
11754         /*
11755          * Preserve the indirdep if there were any changes or if it is not
11756          * yet valid on disk.
11757          */
11758         if (chgs) {
11759                 stat_indir_blk_ptrs++;
11760                 bdirty(bp);
11761                 return (1);
11762         }
11763         /*
11764          * If there were no changes we can discard the savedbp and detach
11765          * ourselves from the buf.  We are only carrying completed pointers
11766          * in this case.
11767          */
11768         sbp = indirdep->ir_savebp;
11769         sbp->b_flags |= B_INVAL | B_NOCACHE;
11770         indirdep->ir_savebp = NULL;
11771         indirdep->ir_bp = NULL;
11772         if (*bpp != NULL)
11773                 panic("handle_written_indirdep: bp already exists.");
11774         *bpp = sbp;
11775         /*
11776          * The indirdep may not be freed until its parent points at it.
11777          */
11778         if (indirdep->ir_state & DEPCOMPLETE)
11779                 free_indirdep(indirdep);
11780
11781         return (0);
11782 }
11783
11784 /*
11785  * Process a diradd entry after its dependent inode has been written.
11786  * This routine must be called with splbio interrupts blocked.
11787  */
11788 static void
11789 diradd_inode_written(dap, inodedep)
11790         struct diradd *dap;
11791         struct inodedep *inodedep;
11792 {
11793
11794         dap->da_state |= COMPLETE;
11795         complete_diradd(dap);
11796         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11797 }
11798
11799 /*
11800  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11801  * be called with the per-filesystem lock and the buf lock on the cg held.
11802  */
11803 static int
11804 bmsafemap_backgroundwrite(bmsafemap, bp)
11805         struct bmsafemap *bmsafemap;
11806         struct buf *bp;
11807 {
11808         int dirty;
11809
11810         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11811         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11812             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11813         /*
11814          * If we're initiating a background write we need to process the
11815          * rollbacks as they exist now, not as they exist when IO starts.
11816          * No other consumers will look at the contents of the shadowed
11817          * buf so this is safe to do here.
11818          */
11819         if (bp->b_xflags & BX_BKGRDMARKER)
11820                 initiate_write_bmsafemap(bmsafemap, bp);
11821
11822         return (dirty);
11823 }
11824
11825 /*
11826  * Re-apply an allocation when a cg write is complete.
11827  */
11828 static int
11829 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11830         struct jnewblk *jnewblk;
11831         struct fs *fs;
11832         struct cg *cgp;
11833         uint8_t *blksfree;
11834 {
11835         ufs1_daddr_t fragno;
11836         ufs2_daddr_t blkno;
11837         long cgbno, bbase;
11838         int frags, blk;
11839         int i;
11840
11841         frags = 0;
11842         cgbno = dtogd(fs, jnewblk->jn_blkno);
11843         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11844                 if (isclr(blksfree, cgbno + i))
11845                         panic("jnewblk_rollforward: re-allocated fragment");
11846                 frags++;
11847         }
11848         if (frags == fs->fs_frag) {
11849                 blkno = fragstoblks(fs, cgbno);
11850                 ffs_clrblock(fs, blksfree, (long)blkno);
11851                 ffs_clusteracct(fs, cgp, blkno, -1);
11852                 cgp->cg_cs.cs_nbfree--;
11853         } else {
11854                 bbase = cgbno - fragnum(fs, cgbno);
11855                 cgbno += jnewblk->jn_oldfrags;
11856                 /* If a complete block had been reassembled, account for it. */
11857                 fragno = fragstoblks(fs, bbase);
11858                 if (ffs_isblock(fs, blksfree, fragno)) {
11859                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11860                         ffs_clusteracct(fs, cgp, fragno, -1);
11861                         cgp->cg_cs.cs_nbfree--;
11862                 }
11863                 /* Decrement the old frags.  */
11864                 blk = blkmap(fs, blksfree, bbase);
11865                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11866                 /* Allocate the fragment */
11867                 for (i = 0; i < frags; i++)
11868                         clrbit(blksfree, cgbno + i);
11869                 cgp->cg_cs.cs_nffree -= frags;
11870                 /* Add back in counts associated with the new frags */
11871                 blk = blkmap(fs, blksfree, bbase);
11872                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11873         }
11874         return (frags);
11875 }
11876
11877 /*
11878  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11879  * changes if it's not a background write.  Set all written dependencies 
11880  * to DEPCOMPLETE and free the structure if possible.
11881  *
11882  * If the write did not succeed, we will do all the roll-forward
11883  * operations, but we will not take the actions that will allow its
11884  * dependencies to be processed.
11885  */
11886 static int
11887 handle_written_bmsafemap(bmsafemap, bp, flags)
11888         struct bmsafemap *bmsafemap;
11889         struct buf *bp;
11890         int flags;
11891 {
11892         struct newblk *newblk;
11893         struct inodedep *inodedep;
11894         struct jaddref *jaddref, *jatmp;
11895         struct jnewblk *jnewblk, *jntmp;
11896         struct ufsmount *ump;
11897         uint8_t *inosused;
11898         uint8_t *blksfree;
11899         struct cg *cgp;
11900         struct fs *fs;
11901         ino_t ino;
11902         int foreground;
11903         int chgs;
11904
11905         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11906                 panic("handle_written_bmsafemap: Not started\n");
11907         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11908         chgs = 0;
11909         bmsafemap->sm_state &= ~IOSTARTED;
11910         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11911         /*
11912          * If write was successful, release journal work that was waiting
11913          * on the write. Otherwise move the work back.
11914          */
11915         if (flags & WRITESUCCEEDED)
11916                 handle_jwork(&bmsafemap->sm_freewr);
11917         else
11918                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11919                     worklist, wk_list);
11920
11921         /*
11922          * Restore unwritten inode allocation pending jaddref writes.
11923          */
11924         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11925                 cgp = (struct cg *)bp->b_data;
11926                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11927                 inosused = cg_inosused(cgp);
11928                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11929                     ja_bmdeps, jatmp) {
11930                         if ((jaddref->ja_state & UNDONE) == 0)
11931                                 continue;
11932                         ino = jaddref->ja_ino % fs->fs_ipg;
11933                         if (isset(inosused, ino))
11934                                 panic("handle_written_bmsafemap: "
11935                                     "re-allocated inode");
11936                         /* Do the roll-forward only if it's a real copy. */
11937                         if (foreground) {
11938                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11939                                         cgp->cg_cs.cs_ndir++;
11940                                 cgp->cg_cs.cs_nifree--;
11941                                 setbit(inosused, ino);
11942                                 chgs = 1;
11943                         }
11944                         jaddref->ja_state &= ~UNDONE;
11945                         jaddref->ja_state |= ATTACHED;
11946                         free_jaddref(jaddref);
11947                 }
11948         }
11949         /*
11950          * Restore any block allocations which are pending journal writes.
11951          */
11952         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11953                 cgp = (struct cg *)bp->b_data;
11954                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11955                 blksfree = cg_blksfree(cgp);
11956                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11957                     jntmp) {
11958                         if ((jnewblk->jn_state & UNDONE) == 0)
11959                                 continue;
11960                         /* Do the roll-forward only if it's a real copy. */
11961                         if (foreground &&
11962                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11963                                 chgs = 1;
11964                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11965                         jnewblk->jn_state |= ATTACHED;
11966                         free_jnewblk(jnewblk);
11967                 }
11968         }
11969         /*
11970          * If the write did not succeed, we have done all the roll-forward
11971          * operations, but we cannot take the actions that will allow its
11972          * dependencies to be processed.
11973          */
11974         if ((flags & WRITESUCCEEDED) == 0) {
11975                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11976                     newblk, nb_deps);
11977                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11978                     worklist, wk_list);
11979                 if (foreground)
11980                         bdirty(bp);
11981                 return (1);
11982         }
11983         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11984                 newblk->nb_state |= DEPCOMPLETE;
11985                 newblk->nb_state &= ~ONDEPLIST;
11986                 newblk->nb_bmsafemap = NULL;
11987                 LIST_REMOVE(newblk, nb_deps);
11988                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11989                         handle_allocdirect_partdone(
11990                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11991                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11992                         handle_allocindir_partdone(
11993                             WK_ALLOCINDIR(&newblk->nb_list));
11994                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11995                         panic("handle_written_bmsafemap: Unexpected type: %s",
11996                             TYPENAME(newblk->nb_list.wk_type));
11997         }
11998         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11999                 inodedep->id_state |= DEPCOMPLETE;
12000                 inodedep->id_state &= ~ONDEPLIST;
12001                 LIST_REMOVE(inodedep, id_deps);
12002                 inodedep->id_bmsafemap = NULL;
12003         }
12004         LIST_REMOVE(bmsafemap, sm_next);
12005         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12006             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12007             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12008             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12009             LIST_EMPTY(&bmsafemap->sm_freehd)) {
12010                 LIST_REMOVE(bmsafemap, sm_hash);
12011                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12012                 return (0);
12013         }
12014         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12015         if (foreground)
12016                 bdirty(bp);
12017         return (1);
12018 }
12019
12020 /*
12021  * Try to free a mkdir dependency.
12022  */
12023 static void
12024 complete_mkdir(mkdir)
12025         struct mkdir *mkdir;
12026 {
12027         struct diradd *dap;
12028
12029         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12030                 return;
12031         LIST_REMOVE(mkdir, md_mkdirs);
12032         dap = mkdir->md_diradd;
12033         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12034         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12035                 dap->da_state |= DEPCOMPLETE;
12036                 complete_diradd(dap);
12037         }
12038         WORKITEM_FREE(mkdir, D_MKDIR);
12039 }
12040
12041 /*
12042  * Handle the completion of a mkdir dependency.
12043  */
12044 static void
12045 handle_written_mkdir(mkdir, type)
12046         struct mkdir *mkdir;
12047         int type;
12048 {
12049
12050         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12051                 panic("handle_written_mkdir: bad type");
12052         mkdir->md_state |= COMPLETE;
12053         complete_mkdir(mkdir);
12054 }
12055
12056 static int
12057 free_pagedep(pagedep)
12058         struct pagedep *pagedep;
12059 {
12060         int i;
12061
12062         if (pagedep->pd_state & NEWBLOCK)
12063                 return (0);
12064         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12065                 return (0);
12066         for (i = 0; i < DAHASHSZ; i++)
12067                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12068                         return (0);
12069         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12070                 return (0);
12071         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12072                 return (0);
12073         if (pagedep->pd_state & ONWORKLIST)
12074                 WORKLIST_REMOVE(&pagedep->pd_list);
12075         LIST_REMOVE(pagedep, pd_hash);
12076         WORKITEM_FREE(pagedep, D_PAGEDEP);
12077
12078         return (1);
12079 }
12080
12081 /*
12082  * Called from within softdep_disk_write_complete above.
12083  * A write operation was just completed. Removed inodes can
12084  * now be freed and associated block pointers may be committed.
12085  * Note that this routine is always called from interrupt level
12086  * with further interrupts from this device blocked.
12087  *
12088  * If the write did not succeed, we will do all the roll-forward
12089  * operations, but we will not take the actions that will allow its
12090  * dependencies to be processed.
12091  */
12092 static int 
12093 handle_written_filepage(pagedep, bp, flags)
12094         struct pagedep *pagedep;
12095         struct buf *bp;         /* buffer containing the written page */
12096         int flags;
12097 {
12098         struct dirrem *dirrem;
12099         struct diradd *dap, *nextdap;
12100         struct direct *ep;
12101         int i, chgs;
12102
12103         if ((pagedep->pd_state & IOSTARTED) == 0)
12104                 panic("handle_written_filepage: not started");
12105         pagedep->pd_state &= ~IOSTARTED;
12106         if ((flags & WRITESUCCEEDED) == 0)
12107                 goto rollforward;
12108         /*
12109          * Process any directory removals that have been committed.
12110          */
12111         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12112                 LIST_REMOVE(dirrem, dm_next);
12113                 dirrem->dm_state |= COMPLETE;
12114                 dirrem->dm_dirinum = pagedep->pd_ino;
12115                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12116                     ("handle_written_filepage: Journal entries not written."));
12117                 add_to_worklist(&dirrem->dm_list, 0);
12118         }
12119         /*
12120          * Free any directory additions that have been committed.
12121          * If it is a newly allocated block, we have to wait until
12122          * the on-disk directory inode claims the new block.
12123          */
12124         if ((pagedep->pd_state & NEWBLOCK) == 0)
12125                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12126                         free_diradd(dap, NULL);
12127 rollforward:
12128         /*
12129          * Uncommitted directory entries must be restored.
12130          */
12131         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12132                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12133                      dap = nextdap) {
12134                         nextdap = LIST_NEXT(dap, da_pdlist);
12135                         if (dap->da_state & ATTACHED)
12136                                 panic("handle_written_filepage: attached");
12137                         ep = (struct direct *)
12138                             ((char *)bp->b_data + dap->da_offset);
12139                         ep->d_ino = dap->da_newinum;
12140                         dap->da_state &= ~UNDONE;
12141                         dap->da_state |= ATTACHED;
12142                         chgs = 1;
12143                         /*
12144                          * If the inode referenced by the directory has
12145                          * been written out, then the dependency can be
12146                          * moved to the pending list.
12147                          */
12148                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12149                                 LIST_REMOVE(dap, da_pdlist);
12150                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12151                                     da_pdlist);
12152                         }
12153                 }
12154         }
12155         /*
12156          * If there were any rollbacks in the directory, then it must be
12157          * marked dirty so that its will eventually get written back in
12158          * its correct form.
12159          */
12160         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12161                 if ((bp->b_flags & B_DELWRI) == 0)
12162                         stat_dir_entry++;
12163                 bdirty(bp);
12164                 return (1);
12165         }
12166         /*
12167          * If we are not waiting for a new directory block to be
12168          * claimed by its inode, then the pagedep will be freed.
12169          * Otherwise it will remain to track any new entries on
12170          * the page in case they are fsync'ed.
12171          */
12172         free_pagedep(pagedep);
12173         return (0);
12174 }
12175
12176 /*
12177  * Writing back in-core inode structures.
12178  * 
12179  * The filesystem only accesses an inode's contents when it occupies an
12180  * "in-core" inode structure.  These "in-core" structures are separate from
12181  * the page frames used to cache inode blocks.  Only the latter are
12182  * transferred to/from the disk.  So, when the updated contents of the
12183  * "in-core" inode structure are copied to the corresponding in-memory inode
12184  * block, the dependencies are also transferred.  The following procedure is
12185  * called when copying a dirty "in-core" inode to a cached inode block.
12186  */
12187
12188 /*
12189  * Called when an inode is loaded from disk. If the effective link count
12190  * differed from the actual link count when it was last flushed, then we
12191  * need to ensure that the correct effective link count is put back.
12192  */
12193 void 
12194 softdep_load_inodeblock(ip)
12195         struct inode *ip;       /* the "in_core" copy of the inode */
12196 {
12197         struct inodedep *inodedep;
12198         struct ufsmount *ump;
12199
12200         ump = ITOUMP(ip);
12201         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12202             ("softdep_load_inodeblock called on non-softdep filesystem"));
12203         /*
12204          * Check for alternate nlink count.
12205          */
12206         ip->i_effnlink = ip->i_nlink;
12207         ACQUIRE_LOCK(ump);
12208         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12209                 FREE_LOCK(ump);
12210                 return;
12211         }
12212         ip->i_effnlink -= inodedep->id_nlinkdelta;
12213         FREE_LOCK(ump);
12214 }
12215
12216 /*
12217  * This routine is called just before the "in-core" inode
12218  * information is to be copied to the in-memory inode block.
12219  * Recall that an inode block contains several inodes. If
12220  * the force flag is set, then the dependencies will be
12221  * cleared so that the update can always be made. Note that
12222  * the buffer is locked when this routine is called, so we
12223  * will never be in the middle of writing the inode block 
12224  * to disk.
12225  */
12226 void 
12227 softdep_update_inodeblock(ip, bp, waitfor)
12228         struct inode *ip;       /* the "in_core" copy of the inode */
12229         struct buf *bp;         /* the buffer containing the inode block */
12230         int waitfor;            /* nonzero => update must be allowed */
12231 {
12232         struct inodedep *inodedep;
12233         struct inoref *inoref;
12234         struct ufsmount *ump;
12235         struct worklist *wk;
12236         struct mount *mp;
12237         struct buf *ibp;
12238         struct fs *fs;
12239         int error;
12240
12241         ump = ITOUMP(ip);
12242         mp = UFSTOVFS(ump);
12243         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12244             ("softdep_update_inodeblock called on non-softdep filesystem"));
12245         fs = ump->um_fs;
12246         /*
12247          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12248          * does not have access to the in-core ip so must write directly into
12249          * the inode block buffer when setting freelink.
12250          */
12251         if (fs->fs_magic == FS_UFS1_MAGIC)
12252                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12253                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12254         else
12255                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12256                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12257         /*
12258          * If the effective link count is not equal to the actual link
12259          * count, then we must track the difference in an inodedep while
12260          * the inode is (potentially) tossed out of the cache. Otherwise,
12261          * if there is no existing inodedep, then there are no dependencies
12262          * to track.
12263          */
12264         ACQUIRE_LOCK(ump);
12265 again:
12266         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12267                 FREE_LOCK(ump);
12268                 if (ip->i_effnlink != ip->i_nlink)
12269                         panic("softdep_update_inodeblock: bad link count");
12270                 return;
12271         }
12272         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12273                 panic("softdep_update_inodeblock: bad delta");
12274         /*
12275          * If we're flushing all dependencies we must also move any waiting
12276          * for journal writes onto the bufwait list prior to I/O.
12277          */
12278         if (waitfor) {
12279                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12280                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12281                             == DEPCOMPLETE) {
12282                                 jwait(&inoref->if_list, MNT_WAIT);
12283                                 goto again;
12284                         }
12285                 }
12286         }
12287         /*
12288          * Changes have been initiated. Anything depending on these
12289          * changes cannot occur until this inode has been written.
12290          */
12291         inodedep->id_state &= ~COMPLETE;
12292         if ((inodedep->id_state & ONWORKLIST) == 0)
12293                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12294         /*
12295          * Any new dependencies associated with the incore inode must 
12296          * now be moved to the list associated with the buffer holding
12297          * the in-memory copy of the inode. Once merged process any
12298          * allocdirects that are completed by the merger.
12299          */
12300         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12301         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12302                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12303                     NULL);
12304         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12305         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12306                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12307                     NULL);
12308         /*
12309          * Now that the inode has been pushed into the buffer, the
12310          * operations dependent on the inode being written to disk
12311          * can be moved to the id_bufwait so that they will be
12312          * processed when the buffer I/O completes.
12313          */
12314         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12315                 WORKLIST_REMOVE(wk);
12316                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12317         }
12318         /*
12319          * Newly allocated inodes cannot be written until the bitmap
12320          * that allocates them have been written (indicated by
12321          * DEPCOMPLETE being set in id_state). If we are doing a
12322          * forced sync (e.g., an fsync on a file), we force the bitmap
12323          * to be written so that the update can be done.
12324          */
12325         if (waitfor == 0) {
12326                 FREE_LOCK(ump);
12327                 return;
12328         }
12329 retry:
12330         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12331                 FREE_LOCK(ump);
12332                 return;
12333         }
12334         ibp = inodedep->id_bmsafemap->sm_buf;
12335         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12336         if (ibp == NULL) {
12337                 /*
12338                  * If ibp came back as NULL, the dependency could have been
12339                  * freed while we slept.  Look it up again, and check to see
12340                  * that it has completed.
12341                  */
12342                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12343                         goto retry;
12344                 FREE_LOCK(ump);
12345                 return;
12346         }
12347         FREE_LOCK(ump);
12348         if ((error = bwrite(ibp)) != 0)
12349                 softdep_error("softdep_update_inodeblock: bwrite", error);
12350 }
12351
12352 /*
12353  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12354  * old inode dependency list (such as id_inoupdt). This routine must be
12355  * called with splbio interrupts blocked.
12356  */
12357 static void
12358 merge_inode_lists(newlisthead, oldlisthead)
12359         struct allocdirectlst *newlisthead;
12360         struct allocdirectlst *oldlisthead;
12361 {
12362         struct allocdirect *listadp, *newadp;
12363
12364         newadp = TAILQ_FIRST(newlisthead);
12365         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12366                 if (listadp->ad_offset < newadp->ad_offset) {
12367                         listadp = TAILQ_NEXT(listadp, ad_next);
12368                         continue;
12369                 }
12370                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12371                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12372                 if (listadp->ad_offset == newadp->ad_offset) {
12373                         allocdirect_merge(oldlisthead, newadp,
12374                             listadp);
12375                         listadp = newadp;
12376                 }
12377                 newadp = TAILQ_FIRST(newlisthead);
12378         }
12379         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12380                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12381                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12382         }
12383 }
12384
12385 /*
12386  * If we are doing an fsync, then we must ensure that any directory
12387  * entries for the inode have been written after the inode gets to disk.
12388  */
12389 int
12390 softdep_fsync(vp)
12391         struct vnode *vp;       /* the "in_core" copy of the inode */
12392 {
12393         struct inodedep *inodedep;
12394         struct pagedep *pagedep;
12395         struct inoref *inoref;
12396         struct ufsmount *ump;
12397         struct worklist *wk;
12398         struct diradd *dap;
12399         struct mount *mp;
12400         struct vnode *pvp;
12401         struct inode *ip;
12402         struct buf *bp;
12403         struct fs *fs;
12404         struct thread *td = curthread;
12405         int error, flushparent, pagedep_new_block;
12406         ino_t parentino;
12407         ufs_lbn_t lbn;
12408
12409         ip = VTOI(vp);
12410         mp = vp->v_mount;
12411         ump = VFSTOUFS(mp);
12412         fs = ump->um_fs;
12413         if (MOUNTEDSOFTDEP(mp) == 0)
12414                 return (0);
12415         ACQUIRE_LOCK(ump);
12416 restart:
12417         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12418                 FREE_LOCK(ump);
12419                 return (0);
12420         }
12421         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12422                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12423                     == DEPCOMPLETE) {
12424                         jwait(&inoref->if_list, MNT_WAIT);
12425                         goto restart;
12426                 }
12427         }
12428         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12429             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12430             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12431             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12432             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12433                 panic("softdep_fsync: pending ops %p", inodedep);
12434         for (error = 0, flushparent = 0; ; ) {
12435                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12436                         break;
12437                 if (wk->wk_type != D_DIRADD)
12438                         panic("softdep_fsync: Unexpected type %s",
12439                             TYPENAME(wk->wk_type));
12440                 dap = WK_DIRADD(wk);
12441                 /*
12442                  * Flush our parent if this directory entry has a MKDIR_PARENT
12443                  * dependency or is contained in a newly allocated block.
12444                  */
12445                 if (dap->da_state & DIRCHG)
12446                         pagedep = dap->da_previous->dm_pagedep;
12447                 else
12448                         pagedep = dap->da_pagedep;
12449                 parentino = pagedep->pd_ino;
12450                 lbn = pagedep->pd_lbn;
12451                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12452                         panic("softdep_fsync: dirty");
12453                 if ((dap->da_state & MKDIR_PARENT) ||
12454                     (pagedep->pd_state & NEWBLOCK))
12455                         flushparent = 1;
12456                 else
12457                         flushparent = 0;
12458                 /*
12459                  * If we are being fsync'ed as part of vgone'ing this vnode,
12460                  * then we will not be able to release and recover the
12461                  * vnode below, so we just have to give up on writing its
12462                  * directory entry out. It will eventually be written, just
12463                  * not now, but then the user was not asking to have it
12464                  * written, so we are not breaking any promises.
12465                  */
12466                 if (vp->v_iflag & VI_DOOMED)
12467                         break;
12468                 /*
12469                  * We prevent deadlock by always fetching inodes from the
12470                  * root, moving down the directory tree. Thus, when fetching
12471                  * our parent directory, we first try to get the lock. If
12472                  * that fails, we must unlock ourselves before requesting
12473                  * the lock on our parent. See the comment in ufs_lookup
12474                  * for details on possible races.
12475                  */
12476                 FREE_LOCK(ump);
12477                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12478                     FFSV_FORCEINSMQ)) {
12479                         error = vfs_busy(mp, MBF_NOWAIT);
12480                         if (error != 0) {
12481                                 vfs_ref(mp);
12482                                 VOP_UNLOCK(vp, 0);
12483                                 error = vfs_busy(mp, 0);
12484                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12485                                 vfs_rel(mp);
12486                                 if (error != 0)
12487                                         return (ENOENT);
12488                                 if (vp->v_iflag & VI_DOOMED) {
12489                                         vfs_unbusy(mp);
12490                                         return (ENOENT);
12491                                 }
12492                         }
12493                         VOP_UNLOCK(vp, 0);
12494                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12495                             &pvp, FFSV_FORCEINSMQ);
12496                         vfs_unbusy(mp);
12497                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12498                         if (vp->v_iflag & VI_DOOMED) {
12499                                 if (error == 0)
12500                                         vput(pvp);
12501                                 error = ENOENT;
12502                         }
12503                         if (error != 0)
12504                                 return (error);
12505                 }
12506                 /*
12507                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12508                  * that are contained in direct blocks will be resolved by 
12509                  * doing a ffs_update. Pagedeps contained in indirect blocks
12510                  * may require a complete sync'ing of the directory. So, we
12511                  * try the cheap and fast ffs_update first, and if that fails,
12512                  * then we do the slower ffs_syncvnode of the directory.
12513                  */
12514                 if (flushparent) {
12515                         int locked;
12516
12517                         if ((error = ffs_update(pvp, 1)) != 0) {
12518                                 vput(pvp);
12519                                 return (error);
12520                         }
12521                         ACQUIRE_LOCK(ump);
12522                         locked = 1;
12523                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12524                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12525                                         if (wk->wk_type != D_DIRADD)
12526                                                 panic("softdep_fsync: Unexpected type %s",
12527                                                       TYPENAME(wk->wk_type));
12528                                         dap = WK_DIRADD(wk);
12529                                         if (dap->da_state & DIRCHG)
12530                                                 pagedep = dap->da_previous->dm_pagedep;
12531                                         else
12532                                                 pagedep = dap->da_pagedep;
12533                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12534                                         FREE_LOCK(ump);
12535                                         locked = 0;
12536                                         if (pagedep_new_block && (error =
12537                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12538                                                 vput(pvp);
12539                                                 return (error);
12540                                         }
12541                                 }
12542                         }
12543                         if (locked)
12544                                 FREE_LOCK(ump);
12545                 }
12546                 /*
12547                  * Flush directory page containing the inode's name.
12548                  */
12549                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12550                     &bp);
12551                 if (error == 0)
12552                         error = bwrite(bp);
12553                 else
12554                         brelse(bp);
12555                 vput(pvp);
12556                 if (error != 0)
12557                         return (error);
12558                 ACQUIRE_LOCK(ump);
12559                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12560                         break;
12561         }
12562         FREE_LOCK(ump);
12563         return (0);
12564 }
12565
12566 /*
12567  * Flush all the dirty bitmaps associated with the block device
12568  * before flushing the rest of the dirty blocks so as to reduce
12569  * the number of dependencies that will have to be rolled back.
12570  *
12571  * XXX Unused?
12572  */
12573 void
12574 softdep_fsync_mountdev(vp)
12575         struct vnode *vp;
12576 {
12577         struct buf *bp, *nbp;
12578         struct worklist *wk;
12579         struct bufobj *bo;
12580
12581         if (!vn_isdisk(vp, NULL))
12582                 panic("softdep_fsync_mountdev: vnode not a disk");
12583         bo = &vp->v_bufobj;
12584 restart:
12585         BO_LOCK(bo);
12586         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12587                 /* 
12588                  * If it is already scheduled, skip to the next buffer.
12589                  */
12590                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12591                         continue;
12592
12593                 if ((bp->b_flags & B_DELWRI) == 0)
12594                         panic("softdep_fsync_mountdev: not dirty");
12595                 /*
12596                  * We are only interested in bitmaps with outstanding
12597                  * dependencies.
12598                  */
12599                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12600                     wk->wk_type != D_BMSAFEMAP ||
12601                     (bp->b_vflags & BV_BKGRDINPROG)) {
12602                         BUF_UNLOCK(bp);
12603                         continue;
12604                 }
12605                 BO_UNLOCK(bo);
12606                 bremfree(bp);
12607                 (void) bawrite(bp);
12608                 goto restart;
12609         }
12610         drain_output(vp);
12611         BO_UNLOCK(bo);
12612 }
12613
12614 /*
12615  * Sync all cylinder groups that were dirty at the time this function is
12616  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12617  * is used to flush freedep activity that may be holding up writes to a
12618  * indirect block.
12619  */
12620 static int
12621 sync_cgs(mp, waitfor)
12622         struct mount *mp;
12623         int waitfor;
12624 {
12625         struct bmsafemap *bmsafemap;
12626         struct bmsafemap *sentinel;
12627         struct ufsmount *ump;
12628         struct buf *bp;
12629         int error;
12630
12631         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12632         sentinel->sm_cg = -1;
12633         ump = VFSTOUFS(mp);
12634         error = 0;
12635         ACQUIRE_LOCK(ump);
12636         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12637         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12638             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12639                 /* Skip sentinels and cgs with no work to release. */
12640                 if (bmsafemap->sm_cg == -1 ||
12641                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12642                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12643                         LIST_REMOVE(sentinel, sm_next);
12644                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12645                         continue;
12646                 }
12647                 /*
12648                  * If we don't get the lock and we're waiting try again, if
12649                  * not move on to the next buf and try to sync it.
12650                  */
12651                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12652                 if (bp == NULL && waitfor == MNT_WAIT)
12653                         continue;
12654                 LIST_REMOVE(sentinel, sm_next);
12655                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12656                 if (bp == NULL)
12657                         continue;
12658                 FREE_LOCK(ump);
12659                 if (waitfor == MNT_NOWAIT)
12660                         bawrite(bp);
12661                 else
12662                         error = bwrite(bp);
12663                 ACQUIRE_LOCK(ump);
12664                 if (error)
12665                         break;
12666         }
12667         LIST_REMOVE(sentinel, sm_next);
12668         FREE_LOCK(ump);
12669         free(sentinel, M_BMSAFEMAP);
12670         return (error);
12671 }
12672
12673 /*
12674  * This routine is called when we are trying to synchronously flush a
12675  * file. This routine must eliminate any filesystem metadata dependencies
12676  * so that the syncing routine can succeed.
12677  */
12678 int
12679 softdep_sync_metadata(struct vnode *vp)
12680 {
12681         struct inode *ip;
12682         int error;
12683
12684         ip = VTOI(vp);
12685         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12686             ("softdep_sync_metadata called on non-softdep filesystem"));
12687         /*
12688          * Ensure that any direct block dependencies have been cleared,
12689          * truncations are started, and inode references are journaled.
12690          */
12691         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12692         /*
12693          * Write all journal records to prevent rollbacks on devvp.
12694          */
12695         if (vp->v_type == VCHR)
12696                 softdep_flushjournal(vp->v_mount);
12697         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12698         /*
12699          * Ensure that all truncates are written so we won't find deps on
12700          * indirect blocks.
12701          */
12702         process_truncates(vp);
12703         FREE_LOCK(VFSTOUFS(vp->v_mount));
12704
12705         return (error);
12706 }
12707
12708 /*
12709  * This routine is called when we are attempting to sync a buf with
12710  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12711  * other IO it can but returns EBUSY if the buffer is not yet able to
12712  * be written.  Dependencies which will not cause rollbacks will always
12713  * return 0.
12714  */
12715 int
12716 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12717 {
12718         struct indirdep *indirdep;
12719         struct pagedep *pagedep;
12720         struct allocindir *aip;
12721         struct newblk *newblk;
12722         struct ufsmount *ump;
12723         struct buf *nbp;
12724         struct worklist *wk;
12725         int i, error;
12726
12727         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12728             ("softdep_sync_buf called on non-softdep filesystem"));
12729         /*
12730          * For VCHR we just don't want to force flush any dependencies that
12731          * will cause rollbacks.
12732          */
12733         if (vp->v_type == VCHR) {
12734                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12735                         return (EBUSY);
12736                 return (0);
12737         }
12738         ump = VFSTOUFS(vp->v_mount);
12739         ACQUIRE_LOCK(ump);
12740         /*
12741          * As we hold the buffer locked, none of its dependencies
12742          * will disappear.
12743          */
12744         error = 0;
12745 top:
12746         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12747                 switch (wk->wk_type) {
12748
12749                 case D_ALLOCDIRECT:
12750                 case D_ALLOCINDIR:
12751                         newblk = WK_NEWBLK(wk);
12752                         if (newblk->nb_jnewblk != NULL) {
12753                                 if (waitfor == MNT_NOWAIT) {
12754                                         error = EBUSY;
12755                                         goto out_unlock;
12756                                 }
12757                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12758                                 goto top;
12759                         }
12760                         if (newblk->nb_state & DEPCOMPLETE ||
12761                             waitfor == MNT_NOWAIT)
12762                                 continue;
12763                         nbp = newblk->nb_bmsafemap->sm_buf;
12764                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12765                         if (nbp == NULL)
12766                                 goto top;
12767                         FREE_LOCK(ump);
12768                         if ((error = bwrite(nbp)) != 0)
12769                                 goto out;
12770                         ACQUIRE_LOCK(ump);
12771                         continue;
12772
12773                 case D_INDIRDEP:
12774                         indirdep = WK_INDIRDEP(wk);
12775                         if (waitfor == MNT_NOWAIT) {
12776                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12777                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12778                                         error = EBUSY;
12779                                         goto out_unlock;
12780                                 }
12781                         }
12782                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12783                                 panic("softdep_sync_buf: truncation pending.");
12784                 restart:
12785                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12786                                 newblk = (struct newblk *)aip;
12787                                 if (newblk->nb_jnewblk != NULL) {
12788                                         jwait(&newblk->nb_jnewblk->jn_list,
12789                                             waitfor);
12790                                         goto restart;
12791                                 }
12792                                 if (newblk->nb_state & DEPCOMPLETE)
12793                                         continue;
12794                                 nbp = newblk->nb_bmsafemap->sm_buf;
12795                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12796                                 if (nbp == NULL)
12797                                         goto restart;
12798                                 FREE_LOCK(ump);
12799                                 if ((error = bwrite(nbp)) != 0)
12800                                         goto out;
12801                                 ACQUIRE_LOCK(ump);
12802                                 goto restart;
12803                         }
12804                         continue;
12805
12806                 case D_PAGEDEP:
12807                         /*
12808                          * Only flush directory entries in synchronous passes.
12809                          */
12810                         if (waitfor != MNT_WAIT) {
12811                                 error = EBUSY;
12812                                 goto out_unlock;
12813                         }
12814                         /*
12815                          * While syncing snapshots, we must allow recursive
12816                          * lookups.
12817                          */
12818                         BUF_AREC(bp);
12819                         /*
12820                          * We are trying to sync a directory that may
12821                          * have dependencies on both its own metadata
12822                          * and/or dependencies on the inodes of any
12823                          * recently allocated files. We walk its diradd
12824                          * lists pushing out the associated inode.
12825                          */
12826                         pagedep = WK_PAGEDEP(wk);
12827                         for (i = 0; i < DAHASHSZ; i++) {
12828                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12829                                         continue;
12830                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12831                                     &pagedep->pd_diraddhd[i]))) {
12832                                         BUF_NOREC(bp);
12833                                         goto out_unlock;
12834                                 }
12835                         }
12836                         BUF_NOREC(bp);
12837                         continue;
12838
12839                 case D_FREEWORK:
12840                 case D_FREEDEP:
12841                 case D_JSEGDEP:
12842                 case D_JNEWBLK:
12843                         continue;
12844
12845                 default:
12846                         panic("softdep_sync_buf: Unknown type %s",
12847                             TYPENAME(wk->wk_type));
12848                         /* NOTREACHED */
12849                 }
12850         }
12851 out_unlock:
12852         FREE_LOCK(ump);
12853 out:
12854         return (error);
12855 }
12856
12857 /*
12858  * Flush the dependencies associated with an inodedep.
12859  * Called with splbio blocked.
12860  */
12861 static int
12862 flush_inodedep_deps(vp, mp, ino)
12863         struct vnode *vp;
12864         struct mount *mp;
12865         ino_t ino;
12866 {
12867         struct inodedep *inodedep;
12868         struct inoref *inoref;
12869         struct ufsmount *ump;
12870         int error, waitfor;
12871
12872         /*
12873          * This work is done in two passes. The first pass grabs most
12874          * of the buffers and begins asynchronously writing them. The
12875          * only way to wait for these asynchronous writes is to sleep
12876          * on the filesystem vnode which may stay busy for a long time
12877          * if the filesystem is active. So, instead, we make a second
12878          * pass over the dependencies blocking on each write. In the
12879          * usual case we will be blocking against a write that we
12880          * initiated, so when it is done the dependency will have been
12881          * resolved. Thus the second pass is expected to end quickly.
12882          * We give a brief window at the top of the loop to allow
12883          * any pending I/O to complete.
12884          */
12885         ump = VFSTOUFS(mp);
12886         LOCK_OWNED(ump);
12887         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12888                 if (error)
12889                         return (error);
12890                 FREE_LOCK(ump);
12891                 ACQUIRE_LOCK(ump);
12892 restart:
12893                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12894                         return (0);
12895                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12896                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12897                             == DEPCOMPLETE) {
12898                                 jwait(&inoref->if_list, MNT_WAIT);
12899                                 goto restart;
12900                         }
12901                 }
12902                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12903                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12904                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12905                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12906                         continue;
12907                 /*
12908                  * If pass2, we are done, otherwise do pass 2.
12909                  */
12910                 if (waitfor == MNT_WAIT)
12911                         break;
12912                 waitfor = MNT_WAIT;
12913         }
12914         /*
12915          * Try freeing inodedep in case all dependencies have been removed.
12916          */
12917         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12918                 (void) free_inodedep(inodedep);
12919         return (0);
12920 }
12921
12922 /*
12923  * Flush an inode dependency list.
12924  * Called with splbio blocked.
12925  */
12926 static int
12927 flush_deplist(listhead, waitfor, errorp)
12928         struct allocdirectlst *listhead;
12929         int waitfor;
12930         int *errorp;
12931 {
12932         struct allocdirect *adp;
12933         struct newblk *newblk;
12934         struct ufsmount *ump;
12935         struct buf *bp;
12936
12937         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12938                 return (0);
12939         ump = VFSTOUFS(adp->ad_list.wk_mp);
12940         LOCK_OWNED(ump);
12941         TAILQ_FOREACH(adp, listhead, ad_next) {
12942                 newblk = (struct newblk *)adp;
12943                 if (newblk->nb_jnewblk != NULL) {
12944                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12945                         return (1);
12946                 }
12947                 if (newblk->nb_state & DEPCOMPLETE)
12948                         continue;
12949                 bp = newblk->nb_bmsafemap->sm_buf;
12950                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12951                 if (bp == NULL) {
12952                         if (waitfor == MNT_NOWAIT)
12953                                 continue;
12954                         return (1);
12955                 }
12956                 FREE_LOCK(ump);
12957                 if (waitfor == MNT_NOWAIT)
12958                         bawrite(bp);
12959                 else 
12960                         *errorp = bwrite(bp);
12961                 ACQUIRE_LOCK(ump);
12962                 return (1);
12963         }
12964         return (0);
12965 }
12966
12967 /*
12968  * Flush dependencies associated with an allocdirect block.
12969  */
12970 static int
12971 flush_newblk_dep(vp, mp, lbn)
12972         struct vnode *vp;
12973         struct mount *mp;
12974         ufs_lbn_t lbn;
12975 {
12976         struct newblk *newblk;
12977         struct ufsmount *ump;
12978         struct bufobj *bo;
12979         struct inode *ip;
12980         struct buf *bp;
12981         ufs2_daddr_t blkno;
12982         int error;
12983
12984         error = 0;
12985         bo = &vp->v_bufobj;
12986         ip = VTOI(vp);
12987         blkno = DIP(ip, i_db[lbn]);
12988         if (blkno == 0)
12989                 panic("flush_newblk_dep: Missing block");
12990         ump = VFSTOUFS(mp);
12991         ACQUIRE_LOCK(ump);
12992         /*
12993          * Loop until all dependencies related to this block are satisfied.
12994          * We must be careful to restart after each sleep in case a write
12995          * completes some part of this process for us.
12996          */
12997         for (;;) {
12998                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12999                         FREE_LOCK(ump);
13000                         break;
13001                 }
13002                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13003                         panic("flush_newblk_dep: Bad newblk %p", newblk);
13004                 /*
13005                  * Flush the journal.
13006                  */
13007                 if (newblk->nb_jnewblk != NULL) {
13008                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13009                         continue;
13010                 }
13011                 /*
13012                  * Write the bitmap dependency.
13013                  */
13014                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13015                         bp = newblk->nb_bmsafemap->sm_buf;
13016                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13017                         if (bp == NULL)
13018                                 continue;
13019                         FREE_LOCK(ump);
13020                         error = bwrite(bp);
13021                         if (error)
13022                                 break;
13023                         ACQUIRE_LOCK(ump);
13024                         continue;
13025                 }
13026                 /*
13027                  * Write the buffer.
13028                  */
13029                 FREE_LOCK(ump);
13030                 BO_LOCK(bo);
13031                 bp = gbincore(bo, lbn);
13032                 if (bp != NULL) {
13033                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13034                             LK_INTERLOCK, BO_LOCKPTR(bo));
13035                         if (error == ENOLCK) {
13036                                 ACQUIRE_LOCK(ump);
13037                                 error = 0;
13038                                 continue; /* Slept, retry */
13039                         }
13040                         if (error != 0)
13041                                 break;  /* Failed */
13042                         if (bp->b_flags & B_DELWRI) {
13043                                 bremfree(bp);
13044                                 error = bwrite(bp);
13045                                 if (error)
13046                                         break;
13047                         } else
13048                                 BUF_UNLOCK(bp);
13049                 } else
13050                         BO_UNLOCK(bo);
13051                 /*
13052                  * We have to wait for the direct pointers to
13053                  * point at the newdirblk before the dependency
13054                  * will go away.
13055                  */
13056                 error = ffs_update(vp, 1);
13057                 if (error)
13058                         break;
13059                 ACQUIRE_LOCK(ump);
13060         }
13061         return (error);
13062 }
13063
13064 /*
13065  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13066  * Called with splbio blocked.
13067  */
13068 static int
13069 flush_pagedep_deps(pvp, mp, diraddhdp)
13070         struct vnode *pvp;
13071         struct mount *mp;
13072         struct diraddhd *diraddhdp;
13073 {
13074         struct inodedep *inodedep;
13075         struct inoref *inoref;
13076         struct ufsmount *ump;
13077         struct diradd *dap;
13078         struct vnode *vp;
13079         int error = 0;
13080         struct buf *bp;
13081         ino_t inum;
13082         struct diraddhd unfinished;
13083
13084         LIST_INIT(&unfinished);
13085         ump = VFSTOUFS(mp);
13086         LOCK_OWNED(ump);
13087 restart:
13088         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13089                 /*
13090                  * Flush ourselves if this directory entry
13091                  * has a MKDIR_PARENT dependency.
13092                  */
13093                 if (dap->da_state & MKDIR_PARENT) {
13094                         FREE_LOCK(ump);
13095                         if ((error = ffs_update(pvp, 1)) != 0)
13096                                 break;
13097                         ACQUIRE_LOCK(ump);
13098                         /*
13099                          * If that cleared dependencies, go on to next.
13100                          */
13101                         if (dap != LIST_FIRST(diraddhdp))
13102                                 continue;
13103                         /*
13104                          * All MKDIR_PARENT dependencies and all the
13105                          * NEWBLOCK pagedeps that are contained in direct
13106                          * blocks were resolved by doing above ffs_update.
13107                          * Pagedeps contained in indirect blocks may
13108                          * require a complete sync'ing of the directory.
13109                          * We are in the midst of doing a complete sync,
13110                          * so if they are not resolved in this pass we
13111                          * defer them for now as they will be sync'ed by
13112                          * our caller shortly.
13113                          */
13114                         LIST_REMOVE(dap, da_pdlist);
13115                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13116                         continue;
13117                 }
13118                 /*
13119                  * A newly allocated directory must have its "." and
13120                  * ".." entries written out before its name can be
13121                  * committed in its parent. 
13122                  */
13123                 inum = dap->da_newinum;
13124                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13125                         panic("flush_pagedep_deps: lost inode1");
13126                 /*
13127                  * Wait for any pending journal adds to complete so we don't
13128                  * cause rollbacks while syncing.
13129                  */
13130                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13131                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13132                             == DEPCOMPLETE) {
13133                                 jwait(&inoref->if_list, MNT_WAIT);
13134                                 goto restart;
13135                         }
13136                 }
13137                 if (dap->da_state & MKDIR_BODY) {
13138                         FREE_LOCK(ump);
13139                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13140                             FFSV_FORCEINSMQ)))
13141                                 break;
13142                         error = flush_newblk_dep(vp, mp, 0);
13143                         /*
13144                          * If we still have the dependency we might need to
13145                          * update the vnode to sync the new link count to
13146                          * disk.
13147                          */
13148                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13149                                 error = ffs_update(vp, 1);
13150                         vput(vp);
13151                         if (error != 0)
13152                                 break;
13153                         ACQUIRE_LOCK(ump);
13154                         /*
13155                          * If that cleared dependencies, go on to next.
13156                          */
13157                         if (dap != LIST_FIRST(diraddhdp))
13158                                 continue;
13159                         if (dap->da_state & MKDIR_BODY) {
13160                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13161                                     &inodedep);
13162                                 panic("flush_pagedep_deps: MKDIR_BODY "
13163                                     "inodedep %p dap %p vp %p",
13164                                     inodedep, dap, vp);
13165                         }
13166                 }
13167                 /*
13168                  * Flush the inode on which the directory entry depends.
13169                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13170                  * the only remaining dependency is that the updated inode
13171                  * count must get pushed to disk. The inode has already
13172                  * been pushed into its inode buffer (via VOP_UPDATE) at
13173                  * the time of the reference count change. So we need only
13174                  * locate that buffer, ensure that there will be no rollback
13175                  * caused by a bitmap dependency, then write the inode buffer.
13176                  */
13177 retry:
13178                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13179                         panic("flush_pagedep_deps: lost inode");
13180                 /*
13181                  * If the inode still has bitmap dependencies,
13182                  * push them to disk.
13183                  */
13184                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13185                         bp = inodedep->id_bmsafemap->sm_buf;
13186                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13187                         if (bp == NULL)
13188                                 goto retry;
13189                         FREE_LOCK(ump);
13190                         if ((error = bwrite(bp)) != 0)
13191                                 break;
13192                         ACQUIRE_LOCK(ump);
13193                         if (dap != LIST_FIRST(diraddhdp))
13194                                 continue;
13195                 }
13196                 /*
13197                  * If the inode is still sitting in a buffer waiting
13198                  * to be written or waiting for the link count to be
13199                  * adjusted update it here to flush it to disk.
13200                  */
13201                 if (dap == LIST_FIRST(diraddhdp)) {
13202                         FREE_LOCK(ump);
13203                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13204                             FFSV_FORCEINSMQ)))
13205                                 break;
13206                         error = ffs_update(vp, 1);
13207                         vput(vp);
13208                         if (error)
13209                                 break;
13210                         ACQUIRE_LOCK(ump);
13211                 }
13212                 /*
13213                  * If we have failed to get rid of all the dependencies
13214                  * then something is seriously wrong.
13215                  */
13216                 if (dap == LIST_FIRST(diraddhdp)) {
13217                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13218                         panic("flush_pagedep_deps: failed to flush " 
13219                             "inodedep %p ino %ju dap %p",
13220                             inodedep, (uintmax_t)inum, dap);
13221                 }
13222         }
13223         if (error)
13224                 ACQUIRE_LOCK(ump);
13225         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13226                 LIST_REMOVE(dap, da_pdlist);
13227                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13228         }
13229         return (error);
13230 }
13231
13232 /*
13233  * A large burst of file addition or deletion activity can drive the
13234  * memory load excessively high. First attempt to slow things down
13235  * using the techniques below. If that fails, this routine requests
13236  * the offending operations to fall back to running synchronously
13237  * until the memory load returns to a reasonable level.
13238  */
13239 int
13240 softdep_slowdown(vp)
13241         struct vnode *vp;
13242 {
13243         struct ufsmount *ump;
13244         int jlow;
13245         int max_softdeps_hard;
13246
13247         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13248             ("softdep_slowdown called on non-softdep filesystem"));
13249         ump = VFSTOUFS(vp->v_mount);
13250         ACQUIRE_LOCK(ump);
13251         jlow = 0;
13252         /*
13253          * Check for journal space if needed.
13254          */
13255         if (DOINGSUJ(vp)) {
13256                 if (journal_space(ump, 0) == 0)
13257                         jlow = 1;
13258         }
13259         /*
13260          * If the system is under its limits and our filesystem is
13261          * not responsible for more than our share of the usage and
13262          * we are not low on journal space, then no need to slow down.
13263          */
13264         max_softdeps_hard = max_softdeps * 11 / 10;
13265         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13266             dep_current[D_INODEDEP] < max_softdeps_hard &&
13267             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13268             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13269             ump->softdep_curdeps[D_DIRREM] <
13270             (max_softdeps_hard / 2) / stat_flush_threads &&
13271             ump->softdep_curdeps[D_INODEDEP] <
13272             max_softdeps_hard / stat_flush_threads &&
13273             ump->softdep_curdeps[D_INDIRDEP] <
13274             (max_softdeps_hard / 1000) / stat_flush_threads &&
13275             ump->softdep_curdeps[D_FREEBLKS] <
13276             max_softdeps_hard / stat_flush_threads) {
13277                 FREE_LOCK(ump);
13278                 return (0);
13279         }
13280         /*
13281          * If the journal is low or our filesystem is over its limit
13282          * then speedup the cleanup.
13283          */
13284         if (ump->softdep_curdeps[D_INDIRDEP] <
13285             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13286                 softdep_speedup(ump);
13287         stat_sync_limit_hit += 1;
13288         FREE_LOCK(ump);
13289         /*
13290          * We only slow down the rate at which new dependencies are
13291          * generated if we are not using journaling. With journaling,
13292          * the cleanup should always be sufficient to keep things
13293          * under control.
13294          */
13295         if (DOINGSUJ(vp))
13296                 return (0);
13297         return (1);
13298 }
13299
13300 /*
13301  * Called by the allocation routines when they are about to fail
13302  * in the hope that we can free up the requested resource (inodes
13303  * or disk space).
13304  * 
13305  * First check to see if the work list has anything on it. If it has,
13306  * clean up entries until we successfully free the requested resource.
13307  * Because this process holds inodes locked, we cannot handle any remove
13308  * requests that might block on a locked inode as that could lead to
13309  * deadlock. If the worklist yields none of the requested resource,
13310  * start syncing out vnodes to free up the needed space.
13311  */
13312 int
13313 softdep_request_cleanup(fs, vp, cred, resource)
13314         struct fs *fs;
13315         struct vnode *vp;
13316         struct ucred *cred;
13317         int resource;
13318 {
13319         struct ufsmount *ump;
13320         struct mount *mp;
13321         long starttime;
13322         ufs2_daddr_t needed;
13323         int error, failed_vnode;
13324
13325         /*
13326          * If we are being called because of a process doing a
13327          * copy-on-write, then it is not safe to process any
13328          * worklist items as we will recurse into the copyonwrite
13329          * routine.  This will result in an incoherent snapshot.
13330          * If the vnode that we hold is a snapshot, we must avoid
13331          * handling other resources that could cause deadlock.
13332          */
13333         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13334                 return (0);
13335
13336         if (resource == FLUSH_BLOCKS_WAIT)
13337                 stat_cleanup_blkrequests += 1;
13338         else
13339                 stat_cleanup_inorequests += 1;
13340
13341         mp = vp->v_mount;
13342         ump = VFSTOUFS(mp);
13343         mtx_assert(UFS_MTX(ump), MA_OWNED);
13344         UFS_UNLOCK(ump);
13345         error = ffs_update(vp, 1);
13346         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13347                 UFS_LOCK(ump);
13348                 return (0);
13349         }
13350         /*
13351          * If we are in need of resources, start by cleaning up
13352          * any block removals associated with our inode.
13353          */
13354         ACQUIRE_LOCK(ump);
13355         process_removes(vp);
13356         process_truncates(vp);
13357         FREE_LOCK(ump);
13358         /*
13359          * Now clean up at least as many resources as we will need.
13360          *
13361          * When requested to clean up inodes, the number that are needed
13362          * is set by the number of simultaneous writers (mnt_writeopcount)
13363          * plus a bit of slop (2) in case some more writers show up while
13364          * we are cleaning.
13365          *
13366          * When requested to free up space, the amount of space that
13367          * we need is enough blocks to allocate a full-sized segment
13368          * (fs_contigsumsize). The number of such segments that will
13369          * be needed is set by the number of simultaneous writers
13370          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13371          * writers show up while we are cleaning.
13372          *
13373          * Additionally, if we are unpriviledged and allocating space,
13374          * we need to ensure that we clean up enough blocks to get the
13375          * needed number of blocks over the threshold of the minimum
13376          * number of blocks required to be kept free by the filesystem
13377          * (fs_minfree).
13378          */
13379         if (resource == FLUSH_INODES_WAIT) {
13380                 needed = vp->v_mount->mnt_writeopcount + 2;
13381         } else if (resource == FLUSH_BLOCKS_WAIT) {
13382                 needed = (vp->v_mount->mnt_writeopcount + 2) *
13383                     fs->fs_contigsumsize;
13384                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13385                         needed += fragstoblks(fs,
13386                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13387                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13388         } else {
13389                 UFS_LOCK(ump);
13390                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13391                     resource);
13392                 return (0);
13393         }
13394         starttime = time_second;
13395 retry:
13396         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13397             fs->fs_cstotal.cs_nbfree <= needed) ||
13398             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13399             fs->fs_cstotal.cs_nifree <= needed)) {
13400                 ACQUIRE_LOCK(ump);
13401                 if (ump->softdep_on_worklist > 0 &&
13402                     process_worklist_item(UFSTOVFS(ump),
13403                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13404                         stat_worklist_push += 1;
13405                 FREE_LOCK(ump);
13406         }
13407         /*
13408          * If we still need resources and there are no more worklist
13409          * entries to process to obtain them, we have to start flushing
13410          * the dirty vnodes to force the release of additional requests
13411          * to the worklist that we can then process to reap addition
13412          * resources. We walk the vnodes associated with the mount point
13413          * until we get the needed worklist requests that we can reap.
13414          *
13415          * If there are several threads all needing to clean the same
13416          * mount point, only one is allowed to walk the mount list.
13417          * When several threads all try to walk the same mount list,
13418          * they end up competing with each other and often end up in
13419          * livelock. This approach ensures that forward progress is
13420          * made at the cost of occational ENOSPC errors being returned
13421          * that might otherwise have been avoided.
13422          */
13423         error = 1;
13424         if ((resource == FLUSH_BLOCKS_WAIT && 
13425              fs->fs_cstotal.cs_nbfree <= needed) ||
13426             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13427              fs->fs_cstotal.cs_nifree <= needed)) {
13428                 ACQUIRE_LOCK(ump);
13429                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13430                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13431                         FREE_LOCK(ump);
13432                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13433                         ACQUIRE_LOCK(ump);
13434                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13435                         FREE_LOCK(ump);
13436                         if (ump->softdep_on_worklist > 0) {
13437                                 stat_cleanup_retries += 1;
13438                                 if (!failed_vnode)
13439                                         goto retry;
13440                         }
13441                 } else {
13442                         FREE_LOCK(ump);
13443                         error = 0;
13444                 }
13445                 stat_cleanup_failures += 1;
13446         }
13447         if (time_second - starttime > stat_cleanup_high_delay)
13448                 stat_cleanup_high_delay = time_second - starttime;
13449         UFS_LOCK(ump);
13450         return (error);
13451 }
13452
13453 /*
13454  * Scan the vnodes for the specified mount point flushing out any
13455  * vnodes that can be locked without waiting. Finally, try to flush
13456  * the device associated with the mount point if it can be locked
13457  * without waiting.
13458  *
13459  * We return 0 if we were able to lock every vnode in our scan.
13460  * If we had to skip one or more vnodes, we return 1.
13461  */
13462 static int
13463 softdep_request_cleanup_flush(mp, ump)
13464         struct mount *mp;
13465         struct ufsmount *ump;
13466 {
13467         struct thread *td;
13468         struct vnode *lvp, *mvp;
13469         int failed_vnode;
13470
13471         failed_vnode = 0;
13472         td = curthread;
13473         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13474                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13475                         VI_UNLOCK(lvp);
13476                         continue;
13477                 }
13478                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13479                     td) != 0) {
13480                         failed_vnode = 1;
13481                         continue;
13482                 }
13483                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13484                         vput(lvp);
13485                         continue;
13486                 }
13487                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13488                 vput(lvp);
13489         }
13490         lvp = ump->um_devvp;
13491         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13492                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13493                 VOP_UNLOCK(lvp, 0);
13494         }
13495         return (failed_vnode);
13496 }
13497
13498 static bool
13499 softdep_excess_items(struct ufsmount *ump, int item)
13500 {
13501
13502         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13503         return (dep_current[item] > max_softdeps &&
13504             ump->softdep_curdeps[item] > max_softdeps /
13505             stat_flush_threads);
13506 }
13507
13508 static void
13509 schedule_cleanup(struct mount *mp)
13510 {
13511         struct ufsmount *ump;
13512         struct thread *td;
13513
13514         ump = VFSTOUFS(mp);
13515         LOCK_OWNED(ump);
13516         FREE_LOCK(ump);
13517         td = curthread;
13518         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13519             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13520                 /*
13521                  * No ast is delivered to kernel threads, so nobody
13522                  * would deref the mp.  Some kernel threads
13523                  * explicitely check for AST, e.g. NFS daemon does
13524                  * this in the serving loop.
13525                  */
13526                 return;
13527         }
13528         if (td->td_su != NULL)
13529                 vfs_rel(td->td_su);
13530         vfs_ref(mp);
13531         td->td_su = mp;
13532         thread_lock(td);
13533         td->td_flags |= TDF_ASTPENDING;
13534         thread_unlock(td);
13535 }
13536
13537 static void
13538 softdep_ast_cleanup_proc(struct thread *td)
13539 {
13540         struct mount *mp;
13541         struct ufsmount *ump;
13542         int error;
13543         bool req;
13544
13545         while ((mp = td->td_su) != NULL) {
13546                 td->td_su = NULL;
13547                 error = vfs_busy(mp, MBF_NOWAIT);
13548                 vfs_rel(mp);
13549                 if (error != 0)
13550                         return;
13551                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13552                         ump = VFSTOUFS(mp);
13553                         for (;;) {
13554                                 req = false;
13555                                 ACQUIRE_LOCK(ump);
13556                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13557                                         req = true;
13558                                         request_cleanup(mp, FLUSH_INODES);
13559                                 }
13560                                 if (softdep_excess_items(ump, D_DIRREM)) {
13561                                         req = true;
13562                                         request_cleanup(mp, FLUSH_BLOCKS);
13563                                 }
13564                                 FREE_LOCK(ump);
13565                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13566                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13567                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13568                                         error = vn_start_write(NULL, &mp,
13569                                             V_WAIT);
13570                                         if (error == 0) {
13571                                                 req = true;
13572                                                 VFS_SYNC(mp, MNT_WAIT);
13573                                                 vn_finished_write(mp);
13574                                         }
13575                                 }
13576                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13577                                         break;
13578                         }
13579                 }
13580                 vfs_unbusy(mp);
13581         }
13582         if ((mp = td->td_su) != NULL) {
13583                 td->td_su = NULL;
13584                 vfs_rel(mp);
13585         }
13586 }
13587
13588 /*
13589  * If memory utilization has gotten too high, deliberately slow things
13590  * down and speed up the I/O processing.
13591  */
13592 static int
13593 request_cleanup(mp, resource)
13594         struct mount *mp;
13595         int resource;
13596 {
13597         struct thread *td = curthread;
13598         struct ufsmount *ump;
13599
13600         ump = VFSTOUFS(mp);
13601         LOCK_OWNED(ump);
13602         /*
13603          * We never hold up the filesystem syncer or buf daemon.
13604          */
13605         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13606                 return (0);
13607         /*
13608          * First check to see if the work list has gotten backlogged.
13609          * If it has, co-opt this process to help clean up two entries.
13610          * Because this process may hold inodes locked, we cannot
13611          * handle any remove requests that might block on a locked
13612          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13613          * to avoid recursively processing the worklist.
13614          */
13615         if (ump->softdep_on_worklist > max_softdeps / 10) {
13616                 td->td_pflags |= TDP_SOFTDEP;
13617                 process_worklist_item(mp, 2, LK_NOWAIT);
13618                 td->td_pflags &= ~TDP_SOFTDEP;
13619                 stat_worklist_push += 2;
13620                 return(1);
13621         }
13622         /*
13623          * Next, we attempt to speed up the syncer process. If that
13624          * is successful, then we allow the process to continue.
13625          */
13626         if (softdep_speedup(ump) &&
13627             resource != FLUSH_BLOCKS_WAIT &&
13628             resource != FLUSH_INODES_WAIT)
13629                 return(0);
13630         /*
13631          * If we are resource constrained on inode dependencies, try
13632          * flushing some dirty inodes. Otherwise, we are constrained
13633          * by file deletions, so try accelerating flushes of directories
13634          * with removal dependencies. We would like to do the cleanup
13635          * here, but we probably hold an inode locked at this point and 
13636          * that might deadlock against one that we try to clean. So,
13637          * the best that we can do is request the syncer daemon to do
13638          * the cleanup for us.
13639          */
13640         switch (resource) {
13641
13642         case FLUSH_INODES:
13643         case FLUSH_INODES_WAIT:
13644                 ACQUIRE_GBLLOCK(&lk);
13645                 stat_ino_limit_push += 1;
13646                 req_clear_inodedeps += 1;
13647                 FREE_GBLLOCK(&lk);
13648                 stat_countp = &stat_ino_limit_hit;
13649                 break;
13650
13651         case FLUSH_BLOCKS:
13652         case FLUSH_BLOCKS_WAIT:
13653                 ACQUIRE_GBLLOCK(&lk);
13654                 stat_blk_limit_push += 1;
13655                 req_clear_remove += 1;
13656                 FREE_GBLLOCK(&lk);
13657                 stat_countp = &stat_blk_limit_hit;
13658                 break;
13659
13660         default:
13661                 panic("request_cleanup: unknown type");
13662         }
13663         /*
13664          * Hopefully the syncer daemon will catch up and awaken us.
13665          * We wait at most tickdelay before proceeding in any case.
13666          */
13667         ACQUIRE_GBLLOCK(&lk);
13668         FREE_LOCK(ump);
13669         proc_waiting += 1;
13670         if (callout_pending(&softdep_callout) == FALSE)
13671                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13672                     pause_timer, 0);
13673
13674         if ((td->td_pflags & TDP_KTHREAD) == 0)
13675                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13676         proc_waiting -= 1;
13677         FREE_GBLLOCK(&lk);
13678         ACQUIRE_LOCK(ump);
13679         return (1);
13680 }
13681
13682 /*
13683  * Awaken processes pausing in request_cleanup and clear proc_waiting
13684  * to indicate that there is no longer a timer running. Pause_timer
13685  * will be called with the global softdep mutex (&lk) locked.
13686  */
13687 static void
13688 pause_timer(arg)
13689         void *arg;
13690 {
13691
13692         GBLLOCK_OWNED(&lk);
13693         /*
13694          * The callout_ API has acquired mtx and will hold it around this
13695          * function call.
13696          */
13697         *stat_countp += proc_waiting;
13698         wakeup(&proc_waiting);
13699 }
13700
13701 /*
13702  * If requested, try removing inode or removal dependencies.
13703  */
13704 static void
13705 check_clear_deps(mp)
13706         struct mount *mp;
13707 {
13708
13709         /*
13710          * If we are suspended, it may be because of our using
13711          * too many inodedeps, so help clear them out.
13712          */
13713         if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13714                 clear_inodedeps(mp);
13715         /*
13716          * General requests for cleanup of backed up dependencies
13717          */
13718         ACQUIRE_GBLLOCK(&lk);
13719         if (req_clear_inodedeps) {
13720                 req_clear_inodedeps -= 1;
13721                 FREE_GBLLOCK(&lk);
13722                 clear_inodedeps(mp);
13723                 ACQUIRE_GBLLOCK(&lk);
13724                 wakeup(&proc_waiting);
13725         }
13726         if (req_clear_remove) {
13727                 req_clear_remove -= 1;
13728                 FREE_GBLLOCK(&lk);
13729                 clear_remove(mp);
13730                 ACQUIRE_GBLLOCK(&lk);
13731                 wakeup(&proc_waiting);
13732         }
13733         FREE_GBLLOCK(&lk);
13734 }
13735
13736 /*
13737  * Flush out a directory with at least one removal dependency in an effort to
13738  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13739  */
13740 static void
13741 clear_remove(mp)
13742         struct mount *mp;
13743 {
13744         struct pagedep_hashhead *pagedephd;
13745         struct pagedep *pagedep;
13746         struct ufsmount *ump;
13747         struct vnode *vp;
13748         struct bufobj *bo;
13749         int error, cnt;
13750         ino_t ino;
13751
13752         ump = VFSTOUFS(mp);
13753         LOCK_OWNED(ump);
13754
13755         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13756                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13757                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13758                         ump->pagedep_nextclean = 0;
13759                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13760                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13761                                 continue;
13762                         ino = pagedep->pd_ino;
13763                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13764                                 continue;
13765                         FREE_LOCK(ump);
13766
13767                         /*
13768                          * Let unmount clear deps
13769                          */
13770                         error = vfs_busy(mp, MBF_NOWAIT);
13771                         if (error != 0)
13772                                 goto finish_write;
13773                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13774                              FFSV_FORCEINSMQ);
13775                         vfs_unbusy(mp);
13776                         if (error != 0) {
13777                                 softdep_error("clear_remove: vget", error);
13778                                 goto finish_write;
13779                         }
13780                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13781                                 softdep_error("clear_remove: fsync", error);
13782                         bo = &vp->v_bufobj;
13783                         BO_LOCK(bo);
13784                         drain_output(vp);
13785                         BO_UNLOCK(bo);
13786                         vput(vp);
13787                 finish_write:
13788                         vn_finished_write(mp);
13789                         ACQUIRE_LOCK(ump);
13790                         return;
13791                 }
13792         }
13793 }
13794
13795 /*
13796  * Clear out a block of dirty inodes in an effort to reduce
13797  * the number of inodedep dependency structures.
13798  */
13799 static void
13800 clear_inodedeps(mp)
13801         struct mount *mp;
13802 {
13803         struct inodedep_hashhead *inodedephd;
13804         struct inodedep *inodedep;
13805         struct ufsmount *ump;
13806         struct vnode *vp;
13807         struct fs *fs;
13808         int error, cnt;
13809         ino_t firstino, lastino, ino;
13810
13811         ump = VFSTOUFS(mp);
13812         fs = ump->um_fs;
13813         LOCK_OWNED(ump);
13814         /*
13815          * Pick a random inode dependency to be cleared.
13816          * We will then gather up all the inodes in its block 
13817          * that have dependencies and flush them out.
13818          */
13819         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13820                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13821                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13822                         ump->inodedep_nextclean = 0;
13823                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13824                         break;
13825         }
13826         if (inodedep == NULL)
13827                 return;
13828         /*
13829          * Find the last inode in the block with dependencies.
13830          */
13831         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13832         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13833                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13834                         break;
13835         /*
13836          * Asynchronously push all but the last inode with dependencies.
13837          * Synchronously push the last inode with dependencies to ensure
13838          * that the inode block gets written to free up the inodedeps.
13839          */
13840         for (ino = firstino; ino <= lastino; ino++) {
13841                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13842                         continue;
13843                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13844                         continue;
13845                 FREE_LOCK(ump);
13846                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13847                 if (error != 0) {
13848                         vn_finished_write(mp);
13849                         ACQUIRE_LOCK(ump);
13850                         return;
13851                 }
13852                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13853                     FFSV_FORCEINSMQ)) != 0) {
13854                         softdep_error("clear_inodedeps: vget", error);
13855                         vfs_unbusy(mp);
13856                         vn_finished_write(mp);
13857                         ACQUIRE_LOCK(ump);
13858                         return;
13859                 }
13860                 vfs_unbusy(mp);
13861                 if (ino == lastino) {
13862                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13863                                 softdep_error("clear_inodedeps: fsync1", error);
13864                 } else {
13865                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13866                                 softdep_error("clear_inodedeps: fsync2", error);
13867                         BO_LOCK(&vp->v_bufobj);
13868                         drain_output(vp);
13869                         BO_UNLOCK(&vp->v_bufobj);
13870                 }
13871                 vput(vp);
13872                 vn_finished_write(mp);
13873                 ACQUIRE_LOCK(ump);
13874         }
13875 }
13876
13877 void
13878 softdep_buf_append(bp, wkhd)
13879         struct buf *bp;
13880         struct workhead *wkhd;
13881 {
13882         struct worklist *wk;
13883         struct ufsmount *ump;
13884
13885         if ((wk = LIST_FIRST(wkhd)) == NULL)
13886                 return;
13887         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13888             ("softdep_buf_append called on non-softdep filesystem"));
13889         ump = VFSTOUFS(wk->wk_mp);
13890         ACQUIRE_LOCK(ump);
13891         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13892                 WORKLIST_REMOVE(wk);
13893                 WORKLIST_INSERT(&bp->b_dep, wk);
13894         }
13895         FREE_LOCK(ump);
13896
13897 }
13898
13899 void
13900 softdep_inode_append(ip, cred, wkhd)
13901         struct inode *ip;
13902         struct ucred *cred;
13903         struct workhead *wkhd;
13904 {
13905         struct buf *bp;
13906         struct fs *fs;
13907         struct ufsmount *ump;
13908         int error;
13909
13910         ump = ITOUMP(ip);
13911         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13912             ("softdep_inode_append called on non-softdep filesystem"));
13913         fs = ump->um_fs;
13914         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13915             (int)fs->fs_bsize, cred, &bp);
13916         if (error) {
13917                 bqrelse(bp);
13918                 softdep_freework(wkhd);
13919                 return;
13920         }
13921         softdep_buf_append(bp, wkhd);
13922         bqrelse(bp);
13923 }
13924
13925 void
13926 softdep_freework(wkhd)
13927         struct workhead *wkhd;
13928 {
13929         struct worklist *wk;
13930         struct ufsmount *ump;
13931
13932         if ((wk = LIST_FIRST(wkhd)) == NULL)
13933                 return;
13934         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13935             ("softdep_freework called on non-softdep filesystem"));
13936         ump = VFSTOUFS(wk->wk_mp);
13937         ACQUIRE_LOCK(ump);
13938         handle_jwork(wkhd);
13939         FREE_LOCK(ump);
13940 }
13941
13942 static struct ufsmount *
13943 softdep_bp_to_mp(bp)
13944         struct buf *bp;
13945 {
13946         struct mount *mp;
13947         struct vnode *vp;
13948
13949         if (LIST_EMPTY(&bp->b_dep))
13950                 return (NULL);
13951         vp = bp->b_vp;
13952
13953         /*
13954          * The ump mount point is stable after we get a correct
13955          * pointer, since bp is locked and this prevents unmount from
13956          * proceeding.  But to get to it, we cannot dereference bp->b_dep
13957          * head wk_mp, because we do not yet own SU ump lock and
13958          * workitem might be freed while dereferenced.
13959          */
13960 retry:
13961         if (vp->v_type == VCHR) {
13962                 VI_LOCK(vp);
13963                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13964                 VI_UNLOCK(vp);
13965                 if (mp == NULL)
13966                         goto retry;
13967         } else if (vp->v_type == VREG || vp->v_type == VDIR ||
13968             vp->v_type == VLNK) {
13969                 mp = vp->v_mount;
13970         } else {
13971                 return (NULL);
13972         }
13973         return (VFSTOUFS(mp));
13974 }
13975
13976 /*
13977  * Function to determine if the buffer has outstanding dependencies
13978  * that will cause a roll-back if the buffer is written. If wantcount
13979  * is set, return number of dependencies, otherwise just yes or no.
13980  */
13981 static int
13982 softdep_count_dependencies(bp, wantcount)
13983         struct buf *bp;
13984         int wantcount;
13985 {
13986         struct worklist *wk;
13987         struct ufsmount *ump;
13988         struct bmsafemap *bmsafemap;
13989         struct freework *freework;
13990         struct inodedep *inodedep;
13991         struct indirdep *indirdep;
13992         struct freeblks *freeblks;
13993         struct allocindir *aip;
13994         struct pagedep *pagedep;
13995         struct dirrem *dirrem;
13996         struct newblk *newblk;
13997         struct mkdir *mkdir;
13998         struct diradd *dap;
13999         int i, retval;
14000
14001         ump = softdep_bp_to_mp(bp);
14002         if (ump == NULL)
14003                 return (0);
14004         retval = 0;
14005         ACQUIRE_LOCK(ump);
14006         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14007                 switch (wk->wk_type) {
14008
14009                 case D_INODEDEP:
14010                         inodedep = WK_INODEDEP(wk);
14011                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14012                                 /* bitmap allocation dependency */
14013                                 retval += 1;
14014                                 if (!wantcount)
14015                                         goto out;
14016                         }
14017                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14018                                 /* direct block pointer dependency */
14019                                 retval += 1;
14020                                 if (!wantcount)
14021                                         goto out;
14022                         }
14023                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14024                                 /* direct block pointer dependency */
14025                                 retval += 1;
14026                                 if (!wantcount)
14027                                         goto out;
14028                         }
14029                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14030                                 /* Add reference dependency. */
14031                                 retval += 1;
14032                                 if (!wantcount)
14033                                         goto out;
14034                         }
14035                         continue;
14036
14037                 case D_INDIRDEP:
14038                         indirdep = WK_INDIRDEP(wk);
14039
14040                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14041                                 /* indirect truncation dependency */
14042                                 retval += 1;
14043                                 if (!wantcount)
14044                                         goto out;
14045                         }
14046
14047                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14048                                 /* indirect block pointer dependency */
14049                                 retval += 1;
14050                                 if (!wantcount)
14051                                         goto out;
14052                         }
14053                         continue;
14054
14055                 case D_PAGEDEP:
14056                         pagedep = WK_PAGEDEP(wk);
14057                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14058                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14059                                         /* Journal remove ref dependency. */
14060                                         retval += 1;
14061                                         if (!wantcount)
14062                                                 goto out;
14063                                 }
14064                         }
14065                         for (i = 0; i < DAHASHSZ; i++) {
14066
14067                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14068                                         /* directory entry dependency */
14069                                         retval += 1;
14070                                         if (!wantcount)
14071                                                 goto out;
14072                                 }
14073                         }
14074                         continue;
14075
14076                 case D_BMSAFEMAP:
14077                         bmsafemap = WK_BMSAFEMAP(wk);
14078                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14079                                 /* Add reference dependency. */
14080                                 retval += 1;
14081                                 if (!wantcount)
14082                                         goto out;
14083                         }
14084                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14085                                 /* Allocate block dependency. */
14086                                 retval += 1;
14087                                 if (!wantcount)
14088                                         goto out;
14089                         }
14090                         continue;
14091
14092                 case D_FREEBLKS:
14093                         freeblks = WK_FREEBLKS(wk);
14094                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14095                                 /* Freeblk journal dependency. */
14096                                 retval += 1;
14097                                 if (!wantcount)
14098                                         goto out;
14099                         }
14100                         continue;
14101
14102                 case D_ALLOCDIRECT:
14103                 case D_ALLOCINDIR:
14104                         newblk = WK_NEWBLK(wk);
14105                         if (newblk->nb_jnewblk) {
14106                                 /* Journal allocate dependency. */
14107                                 retval += 1;
14108                                 if (!wantcount)
14109                                         goto out;
14110                         }
14111                         continue;
14112
14113                 case D_MKDIR:
14114                         mkdir = WK_MKDIR(wk);
14115                         if (mkdir->md_jaddref) {
14116                                 /* Journal reference dependency. */
14117                                 retval += 1;
14118                                 if (!wantcount)
14119                                         goto out;
14120                         }
14121                         continue;
14122
14123                 case D_FREEWORK:
14124                 case D_FREEDEP:
14125                 case D_JSEGDEP:
14126                 case D_JSEG:
14127                 case D_SBDEP:
14128                         /* never a dependency on these blocks */
14129                         continue;
14130
14131                 default:
14132                         panic("softdep_count_dependencies: Unexpected type %s",
14133                             TYPENAME(wk->wk_type));
14134                         /* NOTREACHED */
14135                 }
14136         }
14137 out:
14138         FREE_LOCK(ump);
14139         return (retval);
14140 }
14141
14142 /*
14143  * Acquire exclusive access to a buffer.
14144  * Must be called with a locked mtx parameter.
14145  * Return acquired buffer or NULL on failure.
14146  */
14147 static struct buf *
14148 getdirtybuf(bp, lock, waitfor)
14149         struct buf *bp;
14150         struct rwlock *lock;
14151         int waitfor;
14152 {
14153         int error;
14154
14155         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14156                 if (waitfor != MNT_WAIT)
14157                         return (NULL);
14158                 error = BUF_LOCK(bp,
14159                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14160                 /*
14161                  * Even if we successfully acquire bp here, we have dropped
14162                  * lock, which may violates our guarantee.
14163                  */
14164                 if (error == 0)
14165                         BUF_UNLOCK(bp);
14166                 else if (error != ENOLCK)
14167                         panic("getdirtybuf: inconsistent lock: %d", error);
14168                 rw_wlock(lock);
14169                 return (NULL);
14170         }
14171         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14172                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14173                         rw_wunlock(lock);
14174                         BO_LOCK(bp->b_bufobj);
14175                         BUF_UNLOCK(bp);
14176                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14177                                 bp->b_vflags |= BV_BKGRDWAIT;
14178                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14179                                        PRIBIO | PDROP, "getbuf", 0);
14180                         } else
14181                                 BO_UNLOCK(bp->b_bufobj);
14182                         rw_wlock(lock);
14183                         return (NULL);
14184                 }
14185                 BUF_UNLOCK(bp);
14186                 if (waitfor != MNT_WAIT)
14187                         return (NULL);
14188 #ifdef DEBUG_VFS_LOCKS
14189                 if (bp->b_vp->v_type != VCHR)
14190                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14191 #endif
14192                 bp->b_vflags |= BV_BKGRDWAIT;
14193                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14194                 return (NULL);
14195         }
14196         if ((bp->b_flags & B_DELWRI) == 0) {
14197                 BUF_UNLOCK(bp);
14198                 return (NULL);
14199         }
14200         bremfree(bp);
14201         return (bp);
14202 }
14203
14204
14205 /*
14206  * Check if it is safe to suspend the file system now.  On entry,
14207  * the vnode interlock for devvp should be held.  Return 0 with
14208  * the mount interlock held if the file system can be suspended now,
14209  * otherwise return EAGAIN with the mount interlock held.
14210  */
14211 int
14212 softdep_check_suspend(struct mount *mp,
14213                       struct vnode *devvp,
14214                       int softdep_depcnt,
14215                       int softdep_accdepcnt,
14216                       int secondary_writes,
14217                       int secondary_accwrites)
14218 {
14219         struct bufobj *bo;
14220         struct ufsmount *ump;
14221         struct inodedep *inodedep;
14222         int error, unlinked;
14223
14224         bo = &devvp->v_bufobj;
14225         ASSERT_BO_WLOCKED(bo);
14226
14227         /*
14228          * If we are not running with soft updates, then we need only
14229          * deal with secondary writes as we try to suspend.
14230          */
14231         if (MOUNTEDSOFTDEP(mp) == 0) {
14232                 MNT_ILOCK(mp);
14233                 while (mp->mnt_secondary_writes != 0) {
14234                         BO_UNLOCK(bo);
14235                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14236                             (PUSER - 1) | PDROP, "secwr", 0);
14237                         BO_LOCK(bo);
14238                         MNT_ILOCK(mp);
14239                 }
14240
14241                 /*
14242                  * Reasons for needing more work before suspend:
14243                  * - Dirty buffers on devvp.
14244                  * - Secondary writes occurred after start of vnode sync loop
14245                  */
14246                 error = 0;
14247                 if (bo->bo_numoutput > 0 ||
14248                     bo->bo_dirty.bv_cnt > 0 ||
14249                     secondary_writes != 0 ||
14250                     mp->mnt_secondary_writes != 0 ||
14251                     secondary_accwrites != mp->mnt_secondary_accwrites)
14252                         error = EAGAIN;
14253                 BO_UNLOCK(bo);
14254                 return (error);
14255         }
14256
14257         /*
14258          * If we are running with soft updates, then we need to coordinate
14259          * with them as we try to suspend.
14260          */
14261         ump = VFSTOUFS(mp);
14262         for (;;) {
14263                 if (!TRY_ACQUIRE_LOCK(ump)) {
14264                         BO_UNLOCK(bo);
14265                         ACQUIRE_LOCK(ump);
14266                         FREE_LOCK(ump);
14267                         BO_LOCK(bo);
14268                         continue;
14269                 }
14270                 MNT_ILOCK(mp);
14271                 if (mp->mnt_secondary_writes != 0) {
14272                         FREE_LOCK(ump);
14273                         BO_UNLOCK(bo);
14274                         msleep(&mp->mnt_secondary_writes,
14275                                MNT_MTX(mp),
14276                                (PUSER - 1) | PDROP, "secwr", 0);
14277                         BO_LOCK(bo);
14278                         continue;
14279                 }
14280                 break;
14281         }
14282
14283         unlinked = 0;
14284         if (MOUNTEDSUJ(mp)) {
14285                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14286                     inodedep != NULL;
14287                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14288                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14289                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14290                             UNLINKONLIST) ||
14291                             !check_inodedep_free(inodedep))
14292                                 continue;
14293                         unlinked++;
14294                 }
14295         }
14296
14297         /*
14298          * Reasons for needing more work before suspend:
14299          * - Dirty buffers on devvp.
14300          * - Softdep activity occurred after start of vnode sync loop
14301          * - Secondary writes occurred after start of vnode sync loop
14302          */
14303         error = 0;
14304         if (bo->bo_numoutput > 0 ||
14305             bo->bo_dirty.bv_cnt > 0 ||
14306             softdep_depcnt != unlinked ||
14307             ump->softdep_deps != unlinked ||
14308             softdep_accdepcnt != ump->softdep_accdeps ||
14309             secondary_writes != 0 ||
14310             mp->mnt_secondary_writes != 0 ||
14311             secondary_accwrites != mp->mnt_secondary_accwrites)
14312                 error = EAGAIN;
14313         FREE_LOCK(ump);
14314         BO_UNLOCK(bo);
14315         return (error);
14316 }
14317
14318
14319 /*
14320  * Get the number of dependency structures for the file system, both
14321  * the current number and the total number allocated.  These will
14322  * later be used to detect that softdep processing has occurred.
14323  */
14324 void
14325 softdep_get_depcounts(struct mount *mp,
14326                       int *softdep_depsp,
14327                       int *softdep_accdepsp)
14328 {
14329         struct ufsmount *ump;
14330
14331         if (MOUNTEDSOFTDEP(mp) == 0) {
14332                 *softdep_depsp = 0;
14333                 *softdep_accdepsp = 0;
14334                 return;
14335         }
14336         ump = VFSTOUFS(mp);
14337         ACQUIRE_LOCK(ump);
14338         *softdep_depsp = ump->softdep_deps;
14339         *softdep_accdepsp = ump->softdep_accdeps;
14340         FREE_LOCK(ump);
14341 }
14342
14343 /*
14344  * Wait for pending output on a vnode to complete.
14345  */
14346 static void
14347 drain_output(vp)
14348         struct vnode *vp;
14349 {
14350
14351         ASSERT_VOP_LOCKED(vp, "drain_output");
14352         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14353 }
14354
14355 /*
14356  * Called whenever a buffer that is being invalidated or reallocated
14357  * contains dependencies. This should only happen if an I/O error has
14358  * occurred. The routine is called with the buffer locked.
14359  */ 
14360 static void
14361 softdep_deallocate_dependencies(bp)
14362         struct buf *bp;
14363 {
14364
14365         if ((bp->b_ioflags & BIO_ERROR) == 0)
14366                 panic("softdep_deallocate_dependencies: dangling deps");
14367         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14368                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14369         else
14370                 printf("softdep_deallocate_dependencies: "
14371                     "got error %d while accessing filesystem\n", bp->b_error);
14372         if (bp->b_error != ENXIO)
14373                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14374 }
14375
14376 /*
14377  * Function to handle asynchronous write errors in the filesystem.
14378  */
14379 static void
14380 softdep_error(func, error)
14381         char *func;
14382         int error;
14383 {
14384
14385         /* XXX should do something better! */
14386         printf("%s: got error %d while accessing filesystem\n", func, error);
14387 }
14388
14389 #ifdef DDB
14390
14391 static void
14392 inodedep_print(struct inodedep *inodedep, int verbose)
14393 {
14394         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14395             " saveino %p\n",
14396             inodedep, inodedep->id_fs, inodedep->id_state,
14397             (intmax_t)inodedep->id_ino,
14398             (intmax_t)fsbtodb(inodedep->id_fs,
14399             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14400             (intmax_t)inodedep->id_nlinkdelta,
14401             (intmax_t)inodedep->id_savednlink,
14402             inodedep->id_savedino1);
14403
14404         if (verbose == 0)
14405                 return;
14406
14407         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14408             "mkdiradd %p\n",
14409             LIST_FIRST(&inodedep->id_pendinghd),
14410             LIST_FIRST(&inodedep->id_bufwait),
14411             LIST_FIRST(&inodedep->id_inowait),
14412             TAILQ_FIRST(&inodedep->id_inoreflst),
14413             inodedep->id_mkdiradd);
14414         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14415             TAILQ_FIRST(&inodedep->id_inoupdt),
14416             TAILQ_FIRST(&inodedep->id_newinoupdt),
14417             TAILQ_FIRST(&inodedep->id_extupdt),
14418             TAILQ_FIRST(&inodedep->id_newextupdt));
14419 }
14420
14421 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14422 {
14423
14424         if (have_addr == 0) {
14425                 db_printf("Address required\n");
14426                 return;
14427         }
14428         inodedep_print((struct inodedep*)addr, 1);
14429 }
14430
14431 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14432 {
14433         struct inodedep_hashhead *inodedephd;
14434         struct inodedep *inodedep;
14435         struct ufsmount *ump;
14436         int cnt;
14437
14438         if (have_addr == 0) {
14439                 db_printf("Address required\n");
14440                 return;
14441         }
14442         ump = (struct ufsmount *)addr;
14443         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14444                 inodedephd = &ump->inodedep_hashtbl[cnt];
14445                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14446                         inodedep_print(inodedep, 0);
14447                 }
14448         }
14449 }
14450
14451 DB_SHOW_COMMAND(worklist, db_show_worklist)
14452 {
14453         struct worklist *wk;
14454
14455         if (have_addr == 0) {
14456                 db_printf("Address required\n");
14457                 return;
14458         }
14459         wk = (struct worklist *)addr;
14460         printf("worklist: %p type %s state 0x%X\n",
14461             wk, TYPENAME(wk->wk_type), wk->wk_state);
14462 }
14463
14464 DB_SHOW_COMMAND(workhead, db_show_workhead)
14465 {
14466         struct workhead *wkhd;
14467         struct worklist *wk;
14468         int i;
14469
14470         if (have_addr == 0) {
14471                 db_printf("Address required\n");
14472                 return;
14473         }
14474         wkhd = (struct workhead *)addr;
14475         wk = LIST_FIRST(wkhd);
14476         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14477                 db_printf("worklist: %p type %s state 0x%X",
14478                     wk, TYPENAME(wk->wk_type), wk->wk_state);
14479         if (i == 100)
14480                 db_printf("workhead overflow");
14481         printf("\n");
14482 }
14483
14484
14485 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14486 {
14487         struct mkdirlist *mkdirlisthd;
14488         struct jaddref *jaddref;
14489         struct diradd *diradd;
14490         struct mkdir *mkdir;
14491
14492         if (have_addr == 0) {
14493                 db_printf("Address required\n");
14494                 return;
14495         }
14496         mkdirlisthd = (struct mkdirlist *)addr;
14497         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14498                 diradd = mkdir->md_diradd;
14499                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14500                     mkdir, mkdir->md_state, diradd, diradd->da_state);
14501                 if ((jaddref = mkdir->md_jaddref) != NULL)
14502                         db_printf(" jaddref %p jaddref state 0x%X",
14503                             jaddref, jaddref->ja_state);
14504                 db_printf("\n");
14505         }
14506 }
14507
14508 /* exported to ffs_vfsops.c */
14509 extern void db_print_ffs(struct ufsmount *ump);
14510 void
14511 db_print_ffs(struct ufsmount *ump)
14512 {
14513         db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14514             ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14515             ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14516             ump->softdep_deps, ump->softdep_req);
14517 }
14518
14519 #endif /* DDB */
14520
14521 #endif /* SOFTUPDATES */