]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
MFV: r333378
[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 *);
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);
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                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5293         else
5294                 freefrag = NULL;
5295
5296         CTR6(KTR_SUJ,
5297             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5298             "off %jd newsize %ld oldsize %d",
5299             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5300         ACQUIRE_LOCK(ITOUMP(ip));
5301         if (off >= UFS_NDADDR) {
5302                 if (lbn > 0)
5303                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5304                             lbn, off);
5305                 /* allocating an indirect block */
5306                 if (oldblkno != 0)
5307                         panic("softdep_setup_allocdirect: non-zero indir");
5308         } else {
5309                 if (off != lbn)
5310                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5311                             lbn, off);
5312                 /*
5313                  * Allocating a direct block.
5314                  *
5315                  * If we are allocating a directory block, then we must
5316                  * allocate an associated pagedep to track additions and
5317                  * deletions.
5318                  */
5319                 if ((ip->i_mode & IFMT) == IFDIR)
5320                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5321                             &pagedep);
5322         }
5323         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5324                 panic("softdep_setup_allocdirect: lost block");
5325         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5326             ("softdep_setup_allocdirect: newblk already initialized"));
5327         /*
5328          * Convert the newblk to an allocdirect.
5329          */
5330         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5331         adp = (struct allocdirect *)newblk;
5332         newblk->nb_freefrag = freefrag;
5333         adp->ad_offset = off;
5334         adp->ad_oldblkno = oldblkno;
5335         adp->ad_newsize = newsize;
5336         adp->ad_oldsize = oldsize;
5337
5338         /*
5339          * Finish initializing the journal.
5340          */
5341         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5342                 jnewblk->jn_ino = ip->i_number;
5343                 jnewblk->jn_lbn = lbn;
5344                 add_to_journal(&jnewblk->jn_list);
5345         }
5346         if (freefrag && freefrag->ff_jdep != NULL &&
5347             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5348                 add_to_journal(freefrag->ff_jdep);
5349         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5350         adp->ad_inodedep = inodedep;
5351
5352         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5353         /*
5354          * The list of allocdirects must be kept in sorted and ascending
5355          * order so that the rollback routines can quickly determine the
5356          * first uncommitted block (the size of the file stored on disk
5357          * ends at the end of the lowest committed fragment, or if there
5358          * are no fragments, at the end of the highest committed block).
5359          * Since files generally grow, the typical case is that the new
5360          * block is to be added at the end of the list. We speed this
5361          * special case by checking against the last allocdirect in the
5362          * list before laboriously traversing the list looking for the
5363          * insertion point.
5364          */
5365         adphead = &inodedep->id_newinoupdt;
5366         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5367         if (oldadp == NULL || oldadp->ad_offset <= off) {
5368                 /* insert at end of list */
5369                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5370                 if (oldadp != NULL && oldadp->ad_offset == off)
5371                         allocdirect_merge(adphead, adp, oldadp);
5372                 FREE_LOCK(ITOUMP(ip));
5373                 return;
5374         }
5375         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5376                 if (oldadp->ad_offset >= off)
5377                         break;
5378         }
5379         if (oldadp == NULL)
5380                 panic("softdep_setup_allocdirect: lost entry");
5381         /* insert in middle of list */
5382         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5383         if (oldadp->ad_offset == off)
5384                 allocdirect_merge(adphead, adp, oldadp);
5385
5386         FREE_LOCK(ITOUMP(ip));
5387 }
5388
5389 /*
5390  * Merge a newer and older journal record to be stored either in a
5391  * newblock or freefrag.  This handles aggregating journal records for
5392  * fragment allocation into a second record as well as replacing a
5393  * journal free with an aborted journal allocation.  A segment for the
5394  * oldest record will be placed on wkhd if it has been written.  If not
5395  * the segment for the newer record will suffice.
5396  */
5397 static struct worklist *
5398 jnewblk_merge(new, old, wkhd)
5399         struct worklist *new;
5400         struct worklist *old;
5401         struct workhead *wkhd;
5402 {
5403         struct jnewblk *njnewblk;
5404         struct jnewblk *jnewblk;
5405
5406         /* Handle NULLs to simplify callers. */
5407         if (new == NULL)
5408                 return (old);
5409         if (old == NULL)
5410                 return (new);
5411         /* Replace a jfreefrag with a jnewblk. */
5412         if (new->wk_type == D_JFREEFRAG) {
5413                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5414                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5415                             old, new);
5416                 cancel_jfreefrag(WK_JFREEFRAG(new));
5417                 return (old);
5418         }
5419         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5420                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5421                     old->wk_type, new->wk_type);
5422         /*
5423          * Handle merging of two jnewblk records that describe
5424          * different sets of fragments in the same block.
5425          */
5426         jnewblk = WK_JNEWBLK(old);
5427         njnewblk = WK_JNEWBLK(new);
5428         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5429                 panic("jnewblk_merge: Merging disparate blocks.");
5430         /*
5431          * The record may be rolled back in the cg.
5432          */
5433         if (jnewblk->jn_state & UNDONE) {
5434                 jnewblk->jn_state &= ~UNDONE;
5435                 njnewblk->jn_state |= UNDONE;
5436                 njnewblk->jn_state &= ~ATTACHED;
5437         }
5438         /*
5439          * We modify the newer addref and free the older so that if neither
5440          * has been written the most up-to-date copy will be on disk.  If
5441          * both have been written but rolled back we only temporarily need
5442          * one of them to fix the bits when the cg write completes.
5443          */
5444         jnewblk->jn_state |= ATTACHED | COMPLETE;
5445         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5446         cancel_jnewblk(jnewblk, wkhd);
5447         WORKLIST_REMOVE(&jnewblk->jn_list);
5448         free_jnewblk(jnewblk);
5449         return (new);
5450 }
5451
5452 /*
5453  * Replace an old allocdirect dependency with a newer one.
5454  * This routine must be called with splbio interrupts blocked.
5455  */
5456 static void
5457 allocdirect_merge(adphead, newadp, oldadp)
5458         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5459         struct allocdirect *newadp;     /* allocdirect being added */
5460         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5461 {
5462         struct worklist *wk;
5463         struct freefrag *freefrag;
5464
5465         freefrag = NULL;
5466         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5467         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5468             newadp->ad_oldsize != oldadp->ad_newsize ||
5469             newadp->ad_offset >= UFS_NDADDR)
5470                 panic("%s %jd != new %jd || old size %ld != new %ld",
5471                     "allocdirect_merge: old blkno",
5472                     (intmax_t)newadp->ad_oldblkno,
5473                     (intmax_t)oldadp->ad_newblkno,
5474                     newadp->ad_oldsize, oldadp->ad_newsize);
5475         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5476         newadp->ad_oldsize = oldadp->ad_oldsize;
5477         /*
5478          * If the old dependency had a fragment to free or had never
5479          * previously had a block allocated, then the new dependency
5480          * can immediately post its freefrag and adopt the old freefrag.
5481          * This action is done by swapping the freefrag dependencies.
5482          * The new dependency gains the old one's freefrag, and the
5483          * old one gets the new one and then immediately puts it on
5484          * the worklist when it is freed by free_newblk. It is
5485          * not possible to do this swap when the old dependency had a
5486          * non-zero size but no previous fragment to free. This condition
5487          * arises when the new block is an extension of the old block.
5488          * Here, the first part of the fragment allocated to the new
5489          * dependency is part of the block currently claimed on disk by
5490          * the old dependency, so cannot legitimately be freed until the
5491          * conditions for the new dependency are fulfilled.
5492          */
5493         freefrag = newadp->ad_freefrag;
5494         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5495                 newadp->ad_freefrag = oldadp->ad_freefrag;
5496                 oldadp->ad_freefrag = freefrag;
5497         }
5498         /*
5499          * If we are tracking a new directory-block allocation,
5500          * move it from the old allocdirect to the new allocdirect.
5501          */
5502         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5503                 WORKLIST_REMOVE(wk);
5504                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5505                         panic("allocdirect_merge: extra newdirblk");
5506                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5507         }
5508         TAILQ_REMOVE(adphead, oldadp, ad_next);
5509         /*
5510          * We need to move any journal dependencies over to the freefrag
5511          * that releases this block if it exists.  Otherwise we are
5512          * extending an existing block and we'll wait until that is
5513          * complete to release the journal space and extend the
5514          * new journal to cover this old space as well.
5515          */
5516         if (freefrag == NULL) {
5517                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5518                         panic("allocdirect_merge: %jd != %jd",
5519                             oldadp->ad_newblkno, newadp->ad_newblkno);
5520                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5521                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5522                     &oldadp->ad_block.nb_jnewblk->jn_list,
5523                     &newadp->ad_block.nb_jwork);
5524                 oldadp->ad_block.nb_jnewblk = NULL;
5525                 cancel_newblk(&oldadp->ad_block, NULL,
5526                     &newadp->ad_block.nb_jwork);
5527         } else {
5528                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5529                     &freefrag->ff_list, &freefrag->ff_jwork);
5530                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5531                     &freefrag->ff_jwork);
5532         }
5533         free_newblk(&oldadp->ad_block);
5534 }
5535
5536 /*
5537  * Allocate a jfreefrag structure to journal a single block free.
5538  */
5539 static struct jfreefrag *
5540 newjfreefrag(freefrag, ip, blkno, size, lbn)
5541         struct freefrag *freefrag;
5542         struct inode *ip;
5543         ufs2_daddr_t blkno;
5544         long size;
5545         ufs_lbn_t lbn;
5546 {
5547         struct jfreefrag *jfreefrag;
5548         struct fs *fs;
5549
5550         fs = ITOFS(ip);
5551         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5552             M_SOFTDEP_FLAGS);
5553         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5554         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5555         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5556         jfreefrag->fr_ino = ip->i_number;
5557         jfreefrag->fr_lbn = lbn;
5558         jfreefrag->fr_blkno = blkno;
5559         jfreefrag->fr_frags = numfrags(fs, size);
5560         jfreefrag->fr_freefrag = freefrag;
5561
5562         return (jfreefrag);
5563 }
5564
5565 /*
5566  * Allocate a new freefrag structure.
5567  */
5568 static struct freefrag *
5569 newfreefrag(ip, blkno, size, lbn)
5570         struct inode *ip;
5571         ufs2_daddr_t blkno;
5572         long size;
5573         ufs_lbn_t lbn;
5574 {
5575         struct freefrag *freefrag;
5576         struct ufsmount *ump;
5577         struct fs *fs;
5578
5579         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5580             ip->i_number, blkno, size, lbn);
5581         ump = ITOUMP(ip);
5582         fs = ump->um_fs;
5583         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5584                 panic("newfreefrag: frag size");
5585         freefrag = malloc(sizeof(struct freefrag),
5586             M_FREEFRAG, M_SOFTDEP_FLAGS);
5587         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5588         freefrag->ff_state = ATTACHED;
5589         LIST_INIT(&freefrag->ff_jwork);
5590         freefrag->ff_inum = ip->i_number;
5591         freefrag->ff_vtype = ITOV(ip)->v_type;
5592         freefrag->ff_blkno = blkno;
5593         freefrag->ff_fragsize = size;
5594
5595         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5596                 freefrag->ff_jdep = (struct worklist *)
5597                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5598         } else {
5599                 freefrag->ff_state |= DEPCOMPLETE;
5600                 freefrag->ff_jdep = NULL;
5601         }
5602
5603         return (freefrag);
5604 }
5605
5606 /*
5607  * This workitem de-allocates fragments that were replaced during
5608  * file block allocation.
5609  */
5610 static void 
5611 handle_workitem_freefrag(freefrag)
5612         struct freefrag *freefrag;
5613 {
5614         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5615         struct workhead wkhd;
5616
5617         CTR3(KTR_SUJ,
5618             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5619             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5620         /*
5621          * It would be illegal to add new completion items to the
5622          * freefrag after it was schedule to be done so it must be
5623          * safe to modify the list head here.
5624          */
5625         LIST_INIT(&wkhd);
5626         ACQUIRE_LOCK(ump);
5627         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5628         /*
5629          * If the journal has not been written we must cancel it here.
5630          */
5631         if (freefrag->ff_jdep) {
5632                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5633                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5634                             freefrag->ff_jdep->wk_type);
5635                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5636         }
5637         FREE_LOCK(ump);
5638         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5639            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5640         ACQUIRE_LOCK(ump);
5641         WORKITEM_FREE(freefrag, D_FREEFRAG);
5642         FREE_LOCK(ump);
5643 }
5644
5645 /*
5646  * Set up a dependency structure for an external attributes data block.
5647  * This routine follows much of the structure of softdep_setup_allocdirect.
5648  * See the description of softdep_setup_allocdirect above for details.
5649  */
5650 void 
5651 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5652         struct inode *ip;
5653         ufs_lbn_t off;
5654         ufs2_daddr_t newblkno;
5655         ufs2_daddr_t oldblkno;
5656         long newsize;
5657         long oldsize;
5658         struct buf *bp;
5659 {
5660         struct allocdirect *adp, *oldadp;
5661         struct allocdirectlst *adphead;
5662         struct freefrag *freefrag;
5663         struct inodedep *inodedep;
5664         struct jnewblk *jnewblk;
5665         struct newblk *newblk;
5666         struct mount *mp;
5667         struct ufsmount *ump;
5668         ufs_lbn_t lbn;
5669
5670         mp = ITOVFS(ip);
5671         ump = VFSTOUFS(mp);
5672         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5673             ("softdep_setup_allocext called on non-softdep filesystem"));
5674         KASSERT(off < UFS_NXADDR,
5675             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5676
5677         lbn = bp->b_lblkno;
5678         if (oldblkno && oldblkno != newblkno)
5679                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5680         else
5681                 freefrag = NULL;
5682
5683         ACQUIRE_LOCK(ump);
5684         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5685                 panic("softdep_setup_allocext: lost block");
5686         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5687             ("softdep_setup_allocext: newblk already initialized"));
5688         /*
5689          * Convert the newblk to an allocdirect.
5690          */
5691         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5692         adp = (struct allocdirect *)newblk;
5693         newblk->nb_freefrag = freefrag;
5694         adp->ad_offset = off;
5695         adp->ad_oldblkno = oldblkno;
5696         adp->ad_newsize = newsize;
5697         adp->ad_oldsize = oldsize;
5698         adp->ad_state |=  EXTDATA;
5699
5700         /*
5701          * Finish initializing the journal.
5702          */
5703         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5704                 jnewblk->jn_ino = ip->i_number;
5705                 jnewblk->jn_lbn = lbn;
5706                 add_to_journal(&jnewblk->jn_list);
5707         }
5708         if (freefrag && freefrag->ff_jdep != NULL &&
5709             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5710                 add_to_journal(freefrag->ff_jdep);
5711         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5712         adp->ad_inodedep = inodedep;
5713
5714         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5715         /*
5716          * The list of allocdirects must be kept in sorted and ascending
5717          * order so that the rollback routines can quickly determine the
5718          * first uncommitted block (the size of the file stored on disk
5719          * ends at the end of the lowest committed fragment, or if there
5720          * are no fragments, at the end of the highest committed block).
5721          * Since files generally grow, the typical case is that the new
5722          * block is to be added at the end of the list. We speed this
5723          * special case by checking against the last allocdirect in the
5724          * list before laboriously traversing the list looking for the
5725          * insertion point.
5726          */
5727         adphead = &inodedep->id_newextupdt;
5728         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5729         if (oldadp == NULL || oldadp->ad_offset <= off) {
5730                 /* insert at end of list */
5731                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5732                 if (oldadp != NULL && oldadp->ad_offset == off)
5733                         allocdirect_merge(adphead, adp, oldadp);
5734                 FREE_LOCK(ump);
5735                 return;
5736         }
5737         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5738                 if (oldadp->ad_offset >= off)
5739                         break;
5740         }
5741         if (oldadp == NULL)
5742                 panic("softdep_setup_allocext: lost entry");
5743         /* insert in middle of list */
5744         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5745         if (oldadp->ad_offset == off)
5746                 allocdirect_merge(adphead, adp, oldadp);
5747         FREE_LOCK(ump);
5748 }
5749
5750 /*
5751  * Indirect block allocation dependencies.
5752  * 
5753  * The same dependencies that exist for a direct block also exist when
5754  * a new block is allocated and pointed to by an entry in a block of
5755  * indirect pointers. The undo/redo states described above are also
5756  * used here. Because an indirect block contains many pointers that
5757  * may have dependencies, a second copy of the entire in-memory indirect
5758  * block is kept. The buffer cache copy is always completely up-to-date.
5759  * The second copy, which is used only as a source for disk writes,
5760  * contains only the safe pointers (i.e., those that have no remaining
5761  * update dependencies). The second copy is freed when all pointers
5762  * are safe. The cache is not allowed to replace indirect blocks with
5763  * pending update dependencies. If a buffer containing an indirect
5764  * block with dependencies is written, these routines will mark it
5765  * dirty again. It can only be successfully written once all the
5766  * dependencies are removed. The ffs_fsync routine in conjunction with
5767  * softdep_sync_metadata work together to get all the dependencies
5768  * removed so that a file can be successfully written to disk. Three
5769  * procedures are used when setting up indirect block pointer
5770  * dependencies. The division is necessary because of the organization
5771  * of the "balloc" routine and because of the distinction between file
5772  * pages and file metadata blocks.
5773  */
5774
5775 /*
5776  * Allocate a new allocindir structure.
5777  */
5778 static struct allocindir *
5779 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5780         struct inode *ip;       /* inode for file being extended */
5781         int ptrno;              /* offset of pointer in indirect block */
5782         ufs2_daddr_t newblkno;  /* disk block number being added */
5783         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5784         ufs_lbn_t lbn;
5785 {
5786         struct newblk *newblk;
5787         struct allocindir *aip;
5788         struct freefrag *freefrag;
5789         struct jnewblk *jnewblk;
5790
5791         if (oldblkno)
5792                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn);
5793         else
5794                 freefrag = NULL;
5795         ACQUIRE_LOCK(ITOUMP(ip));
5796         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5797                 panic("new_allocindir: lost block");
5798         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5799             ("newallocindir: newblk already initialized"));
5800         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5801         newblk->nb_freefrag = freefrag;
5802         aip = (struct allocindir *)newblk;
5803         aip->ai_offset = ptrno;
5804         aip->ai_oldblkno = oldblkno;
5805         aip->ai_lbn = lbn;
5806         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5807                 jnewblk->jn_ino = ip->i_number;
5808                 jnewblk->jn_lbn = lbn;
5809                 add_to_journal(&jnewblk->jn_list);
5810         }
5811         if (freefrag && freefrag->ff_jdep != NULL &&
5812             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5813                 add_to_journal(freefrag->ff_jdep);
5814         return (aip);
5815 }
5816
5817 /*
5818  * Called just before setting an indirect block pointer
5819  * to a newly allocated file page.
5820  */
5821 void
5822 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5823         struct inode *ip;       /* inode for file being extended */
5824         ufs_lbn_t lbn;          /* allocated block number within file */
5825         struct buf *bp;         /* buffer with indirect blk referencing page */
5826         int ptrno;              /* offset of pointer in indirect block */
5827         ufs2_daddr_t newblkno;  /* disk block number being added */
5828         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5829         struct buf *nbp;        /* buffer holding allocated page */
5830 {
5831         struct inodedep *inodedep;
5832         struct freefrag *freefrag;
5833         struct allocindir *aip;
5834         struct pagedep *pagedep;
5835         struct mount *mp;
5836         struct ufsmount *ump;
5837
5838         mp = ITOVFS(ip);
5839         ump = VFSTOUFS(mp);
5840         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5841             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5842         KASSERT(lbn == nbp->b_lblkno,
5843             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5844             lbn, bp->b_lblkno));
5845         CTR4(KTR_SUJ,
5846             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5847             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5848         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5849         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5850         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5851         /*
5852          * If we are allocating a directory page, then we must
5853          * allocate an associated pagedep to track additions and
5854          * deletions.
5855          */
5856         if ((ip->i_mode & IFMT) == IFDIR)
5857                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5858         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5859         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5860         FREE_LOCK(ump);
5861         if (freefrag)
5862                 handle_workitem_freefrag(freefrag);
5863 }
5864
5865 /*
5866  * Called just before setting an indirect block pointer to a
5867  * newly allocated indirect block.
5868  */
5869 void
5870 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5871         struct buf *nbp;        /* newly allocated indirect block */
5872         struct inode *ip;       /* inode for file being extended */
5873         struct buf *bp;         /* indirect block referencing allocated block */
5874         int ptrno;              /* offset of pointer in indirect block */
5875         ufs2_daddr_t newblkno;  /* disk block number being added */
5876 {
5877         struct inodedep *inodedep;
5878         struct allocindir *aip;
5879         struct ufsmount *ump;
5880         ufs_lbn_t lbn;
5881
5882         ump = ITOUMP(ip);
5883         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5884             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5885         CTR3(KTR_SUJ,
5886             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5887             ip->i_number, newblkno, ptrno);
5888         lbn = nbp->b_lblkno;
5889         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5890         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5891         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5892         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5893         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5894                 panic("softdep_setup_allocindir_meta: Block already existed");
5895         FREE_LOCK(ump);
5896 }
5897
5898 static void
5899 indirdep_complete(indirdep)
5900         struct indirdep *indirdep;
5901 {
5902         struct allocindir *aip;
5903
5904         LIST_REMOVE(indirdep, ir_next);
5905         indirdep->ir_state |= DEPCOMPLETE;
5906
5907         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5908                 LIST_REMOVE(aip, ai_next);
5909                 free_newblk(&aip->ai_block);
5910         }
5911         /*
5912          * If this indirdep is not attached to a buf it was simply waiting
5913          * on completion to clear completehd.  free_indirdep() asserts
5914          * that nothing is dangling.
5915          */
5916         if ((indirdep->ir_state & ONWORKLIST) == 0)
5917                 free_indirdep(indirdep);
5918 }
5919
5920 static struct indirdep *
5921 indirdep_lookup(mp, ip, bp)
5922         struct mount *mp;
5923         struct inode *ip;
5924         struct buf *bp;
5925 {
5926         struct indirdep *indirdep, *newindirdep;
5927         struct newblk *newblk;
5928         struct ufsmount *ump;
5929         struct worklist *wk;
5930         struct fs *fs;
5931         ufs2_daddr_t blkno;
5932
5933         ump = VFSTOUFS(mp);
5934         LOCK_OWNED(ump);
5935         indirdep = NULL;
5936         newindirdep = NULL;
5937         fs = ump->um_fs;
5938         for (;;) {
5939                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5940                         if (wk->wk_type != D_INDIRDEP)
5941                                 continue;
5942                         indirdep = WK_INDIRDEP(wk);
5943                         break;
5944                 }
5945                 /* Found on the buffer worklist, no new structure to free. */
5946                 if (indirdep != NULL && newindirdep == NULL)
5947                         return (indirdep);
5948                 if (indirdep != NULL && newindirdep != NULL)
5949                         panic("indirdep_lookup: simultaneous create");
5950                 /* None found on the buffer and a new structure is ready. */
5951                 if (indirdep == NULL && newindirdep != NULL)
5952                         break;
5953                 /* None found and no new structure available. */
5954                 FREE_LOCK(ump);
5955                 newindirdep = malloc(sizeof(struct indirdep),
5956                     M_INDIRDEP, M_SOFTDEP_FLAGS);
5957                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5958                 newindirdep->ir_state = ATTACHED;
5959                 if (I_IS_UFS1(ip))
5960                         newindirdep->ir_state |= UFS1FMT;
5961                 TAILQ_INIT(&newindirdep->ir_trunc);
5962                 newindirdep->ir_saveddata = NULL;
5963                 LIST_INIT(&newindirdep->ir_deplisthd);
5964                 LIST_INIT(&newindirdep->ir_donehd);
5965                 LIST_INIT(&newindirdep->ir_writehd);
5966                 LIST_INIT(&newindirdep->ir_completehd);
5967                 if (bp->b_blkno == bp->b_lblkno) {
5968                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5969                             NULL, NULL);
5970                         bp->b_blkno = blkno;
5971                 }
5972                 newindirdep->ir_freeblks = NULL;
5973                 newindirdep->ir_savebp =
5974                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5975                 newindirdep->ir_bp = bp;
5976                 BUF_KERNPROC(newindirdep->ir_savebp);
5977                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5978                 ACQUIRE_LOCK(ump);
5979         }
5980         indirdep = newindirdep;
5981         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5982         /*
5983          * If the block is not yet allocated we don't set DEPCOMPLETE so
5984          * that we don't free dependencies until the pointers are valid.
5985          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5986          * than using the hash.
5987          */
5988         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5989                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5990         else
5991                 indirdep->ir_state |= DEPCOMPLETE;
5992         return (indirdep);
5993 }
5994
5995 /*
5996  * Called to finish the allocation of the "aip" allocated
5997  * by one of the two routines above.
5998  */
5999 static struct freefrag *
6000 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6001         struct buf *bp;         /* in-memory copy of the indirect block */
6002         struct inode *ip;       /* inode for file being extended */
6003         struct inodedep *inodedep; /* Inodedep for ip */
6004         struct allocindir *aip; /* allocindir allocated by the above routines */
6005         ufs_lbn_t lbn;          /* Logical block number for this block. */
6006 {
6007         struct fs *fs;
6008         struct indirdep *indirdep;
6009         struct allocindir *oldaip;
6010         struct freefrag *freefrag;
6011         struct mount *mp;
6012         struct ufsmount *ump;
6013
6014         mp = ITOVFS(ip);
6015         ump = VFSTOUFS(mp);
6016         LOCK_OWNED(ump);
6017         fs = ump->um_fs;
6018         if (bp->b_lblkno >= 0)
6019                 panic("setup_allocindir_phase2: not indir blk");
6020         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6021             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6022         indirdep = indirdep_lookup(mp, ip, bp);
6023         KASSERT(indirdep->ir_savebp != NULL,
6024             ("setup_allocindir_phase2 NULL ir_savebp"));
6025         aip->ai_indirdep = indirdep;
6026         /*
6027          * Check for an unwritten dependency for this indirect offset.  If
6028          * there is, merge the old dependency into the new one.  This happens
6029          * as a result of reallocblk only.
6030          */
6031         freefrag = NULL;
6032         if (aip->ai_oldblkno != 0) {
6033                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6034                         if (oldaip->ai_offset == aip->ai_offset) {
6035                                 freefrag = allocindir_merge(aip, oldaip);
6036                                 goto done;
6037                         }
6038                 }
6039                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6040                         if (oldaip->ai_offset == aip->ai_offset) {
6041                                 freefrag = allocindir_merge(aip, oldaip);
6042                                 goto done;
6043                         }
6044                 }
6045         }
6046 done:
6047         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6048         return (freefrag);
6049 }
6050
6051 /*
6052  * Merge two allocindirs which refer to the same block.  Move newblock
6053  * dependencies and setup the freefrags appropriately.
6054  */
6055 static struct freefrag *
6056 allocindir_merge(aip, oldaip)
6057         struct allocindir *aip;
6058         struct allocindir *oldaip;
6059 {
6060         struct freefrag *freefrag;
6061         struct worklist *wk;
6062
6063         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6064                 panic("allocindir_merge: blkno");
6065         aip->ai_oldblkno = oldaip->ai_oldblkno;
6066         freefrag = aip->ai_freefrag;
6067         aip->ai_freefrag = oldaip->ai_freefrag;
6068         oldaip->ai_freefrag = NULL;
6069         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6070         /*
6071          * If we are tracking a new directory-block allocation,
6072          * move it from the old allocindir to the new allocindir.
6073          */
6074         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6075                 WORKLIST_REMOVE(wk);
6076                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6077                         panic("allocindir_merge: extra newdirblk");
6078                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6079         }
6080         /*
6081          * We can skip journaling for this freefrag and just complete
6082          * any pending journal work for the allocindir that is being
6083          * removed after the freefrag completes.
6084          */
6085         if (freefrag->ff_jdep)
6086                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6087         LIST_REMOVE(oldaip, ai_next);
6088         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6089             &freefrag->ff_list, &freefrag->ff_jwork);
6090         free_newblk(&oldaip->ai_block);
6091
6092         return (freefrag);
6093 }
6094
6095 static inline void
6096 setup_freedirect(freeblks, ip, i, needj)
6097         struct freeblks *freeblks;
6098         struct inode *ip;
6099         int i;
6100         int needj;
6101 {
6102         struct ufsmount *ump;
6103         ufs2_daddr_t blkno;
6104         int frags;
6105
6106         blkno = DIP(ip, i_db[i]);
6107         if (blkno == 0)
6108                 return;
6109         DIP_SET(ip, i_db[i], 0);
6110         ump = ITOUMP(ip);
6111         frags = sblksize(ump->um_fs, ip->i_size, i);
6112         frags = numfrags(ump->um_fs, frags);
6113         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6114 }
6115
6116 static inline void
6117 setup_freeext(freeblks, ip, i, needj)
6118         struct freeblks *freeblks;
6119         struct inode *ip;
6120         int i;
6121         int needj;
6122 {
6123         struct ufsmount *ump;
6124         ufs2_daddr_t blkno;
6125         int frags;
6126
6127         blkno = ip->i_din2->di_extb[i];
6128         if (blkno == 0)
6129                 return;
6130         ip->i_din2->di_extb[i] = 0;
6131         ump = ITOUMP(ip);
6132         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6133         frags = numfrags(ump->um_fs, frags);
6134         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6135 }
6136
6137 static inline void
6138 setup_freeindir(freeblks, ip, i, lbn, needj)
6139         struct freeblks *freeblks;
6140         struct inode *ip;
6141         int i;
6142         ufs_lbn_t lbn;
6143         int needj;
6144 {
6145         struct ufsmount *ump;
6146         ufs2_daddr_t blkno;
6147
6148         blkno = DIP(ip, i_ib[i]);
6149         if (blkno == 0)
6150                 return;
6151         DIP_SET(ip, i_ib[i], 0);
6152         ump = ITOUMP(ip);
6153         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6154             0, needj);
6155 }
6156
6157 static inline struct freeblks *
6158 newfreeblks(mp, ip)
6159         struct mount *mp;
6160         struct inode *ip;
6161 {
6162         struct freeblks *freeblks;
6163
6164         freeblks = malloc(sizeof(struct freeblks),
6165                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6166         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6167         LIST_INIT(&freeblks->fb_jblkdephd);
6168         LIST_INIT(&freeblks->fb_jwork);
6169         freeblks->fb_ref = 0;
6170         freeblks->fb_cgwait = 0;
6171         freeblks->fb_state = ATTACHED;
6172         freeblks->fb_uid = ip->i_uid;
6173         freeblks->fb_inum = ip->i_number;
6174         freeblks->fb_vtype = ITOV(ip)->v_type;
6175         freeblks->fb_modrev = DIP(ip, i_modrev);
6176         freeblks->fb_devvp = ITODEVVP(ip);
6177         freeblks->fb_chkcnt = 0;
6178         freeblks->fb_len = 0;
6179
6180         return (freeblks);
6181 }
6182
6183 static void
6184 trunc_indirdep(indirdep, freeblks, bp, off)
6185         struct indirdep *indirdep;
6186         struct freeblks *freeblks;
6187         struct buf *bp;
6188         int off;
6189 {
6190         struct allocindir *aip, *aipn;
6191
6192         /*
6193          * The first set of allocindirs won't be in savedbp.
6194          */
6195         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6196                 if (aip->ai_offset > off)
6197                         cancel_allocindir(aip, bp, freeblks, 1);
6198         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6199                 if (aip->ai_offset > off)
6200                         cancel_allocindir(aip, bp, freeblks, 1);
6201         /*
6202          * These will exist in savedbp.
6203          */
6204         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6205                 if (aip->ai_offset > off)
6206                         cancel_allocindir(aip, NULL, freeblks, 0);
6207         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6208                 if (aip->ai_offset > off)
6209                         cancel_allocindir(aip, NULL, freeblks, 0);
6210 }
6211
6212 /*
6213  * Follow the chain of indirects down to lastlbn creating a freework
6214  * structure for each.  This will be used to start indir_trunc() at
6215  * the right offset and create the journal records for the parrtial
6216  * truncation.  A second step will handle the truncated dependencies.
6217  */
6218 static int
6219 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6220         struct freeblks *freeblks;
6221         struct inode *ip;
6222         ufs_lbn_t lbn;
6223         ufs_lbn_t lastlbn;
6224         ufs2_daddr_t blkno;
6225 {
6226         struct indirdep *indirdep;
6227         struct indirdep *indirn;
6228         struct freework *freework;
6229         struct newblk *newblk;
6230         struct mount *mp;
6231         struct ufsmount *ump;
6232         struct buf *bp;
6233         uint8_t *start;
6234         uint8_t *end;
6235         ufs_lbn_t lbnadd;
6236         int level;
6237         int error;
6238         int off;
6239
6240
6241         freework = NULL;
6242         if (blkno == 0)
6243                 return (0);
6244         mp = freeblks->fb_list.wk_mp;
6245         ump = VFSTOUFS(mp);
6246         bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6247         if ((bp->b_flags & B_CACHE) == 0) {
6248                 bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6249                 bp->b_iocmd = BIO_READ;
6250                 bp->b_flags &= ~B_INVAL;
6251                 bp->b_ioflags &= ~BIO_ERROR;
6252                 vfs_busy_pages(bp, 0);
6253                 bp->b_iooffset = dbtob(bp->b_blkno);
6254                 bstrategy(bp);
6255 #ifdef RACCT
6256                 if (racct_enable) {
6257                         PROC_LOCK(curproc);
6258                         racct_add_buf(curproc, bp, 0);
6259                         PROC_UNLOCK(curproc);
6260                 }
6261 #endif /* RACCT */
6262                 curthread->td_ru.ru_inblock++;
6263                 error = bufwait(bp);
6264                 if (error) {
6265                         brelse(bp);
6266                         return (error);
6267                 }
6268         }
6269         level = lbn_level(lbn);
6270         lbnadd = lbn_offset(ump->um_fs, level);
6271         /*
6272          * Compute the offset of the last block we want to keep.  Store
6273          * in the freework the first block we want to completely free.
6274          */
6275         off = (lastlbn - -(lbn + level)) / lbnadd;
6276         if (off + 1 == NINDIR(ump->um_fs))
6277                 goto nowork;
6278         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6279         /*
6280          * Link the freework into the indirdep.  This will prevent any new
6281          * allocations from proceeding until we are finished with the
6282          * truncate and the block is written.
6283          */
6284         ACQUIRE_LOCK(ump);
6285         indirdep = indirdep_lookup(mp, ip, bp);
6286         if (indirdep->ir_freeblks)
6287                 panic("setup_trunc_indir: indirdep already truncated.");
6288         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6289         freework->fw_indir = indirdep;
6290         /*
6291          * Cancel any allocindirs that will not make it to disk.
6292          * We have to do this for all copies of the indirdep that
6293          * live on this newblk.
6294          */
6295         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6296                 newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0, &newblk);
6297                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6298                         trunc_indirdep(indirn, freeblks, bp, off);
6299         } else
6300                 trunc_indirdep(indirdep, freeblks, bp, off);
6301         FREE_LOCK(ump);
6302         /*
6303          * Creation is protected by the buf lock. The saveddata is only
6304          * needed if a full truncation follows a partial truncation but it
6305          * is difficult to allocate in that case so we fetch it anyway.
6306          */
6307         if (indirdep->ir_saveddata == NULL)
6308                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6309                     M_SOFTDEP_FLAGS);
6310 nowork:
6311         /* Fetch the blkno of the child and the zero start offset. */
6312         if (I_IS_UFS1(ip)) {
6313                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6314                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6315         } else {
6316                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6317                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6318         }
6319         if (freework) {
6320                 /* Zero the truncated pointers. */
6321                 end = bp->b_data + bp->b_bcount;
6322                 bzero(start, end - start);
6323                 bdwrite(bp);
6324         } else
6325                 bqrelse(bp);
6326         if (level == 0)
6327                 return (0);
6328         lbn++; /* adjust level */
6329         lbn -= (off * lbnadd);
6330         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6331 }
6332
6333 /*
6334  * Complete the partial truncation of an indirect block setup by
6335  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6336  * copy and writes them to disk before the freeblks is allowed to complete.
6337  */
6338 static void
6339 complete_trunc_indir(freework)
6340         struct freework *freework;
6341 {
6342         struct freework *fwn;
6343         struct indirdep *indirdep;
6344         struct ufsmount *ump;
6345         struct buf *bp;
6346         uintptr_t start;
6347         int count;
6348
6349         ump = VFSTOUFS(freework->fw_list.wk_mp);
6350         LOCK_OWNED(ump);
6351         indirdep = freework->fw_indir;
6352         for (;;) {
6353                 bp = indirdep->ir_bp;
6354                 /* See if the block was discarded. */
6355                 if (bp == NULL)
6356                         break;
6357                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6358                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6359                         break;
6360                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6361                     LOCK_PTR(ump)) == 0)
6362                         BUF_UNLOCK(bp);
6363                 ACQUIRE_LOCK(ump);
6364         }
6365         freework->fw_state |= DEPCOMPLETE;
6366         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6367         /*
6368          * Zero the pointers in the saved copy.
6369          */
6370         if (indirdep->ir_state & UFS1FMT)
6371                 start = sizeof(ufs1_daddr_t);
6372         else
6373                 start = sizeof(ufs2_daddr_t);
6374         start *= freework->fw_start;
6375         count = indirdep->ir_savebp->b_bcount - start;
6376         start += (uintptr_t)indirdep->ir_savebp->b_data;
6377         bzero((char *)start, count);
6378         /*
6379          * We need to start the next truncation in the list if it has not
6380          * been started yet.
6381          */
6382         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6383         if (fwn != NULL) {
6384                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6385                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6386                 if ((fwn->fw_state & ONWORKLIST) == 0)
6387                         freework_enqueue(fwn);
6388         }
6389         /*
6390          * If bp is NULL the block was fully truncated, restore
6391          * the saved block list otherwise free it if it is no
6392          * longer needed.
6393          */
6394         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6395                 if (bp == NULL)
6396                         bcopy(indirdep->ir_saveddata,
6397                             indirdep->ir_savebp->b_data,
6398                             indirdep->ir_savebp->b_bcount);
6399                 free(indirdep->ir_saveddata, M_INDIRDEP);
6400                 indirdep->ir_saveddata = NULL;
6401         }
6402         /*
6403          * When bp is NULL there is a full truncation pending.  We
6404          * must wait for this full truncation to be journaled before
6405          * we can release this freework because the disk pointers will
6406          * never be written as zero.
6407          */
6408         if (bp == NULL)  {
6409                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6410                         handle_written_freework(freework);
6411                 else
6412                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6413                            &freework->fw_list);
6414         } else {
6415                 /* Complete when the real copy is written. */
6416                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6417                 BUF_UNLOCK(bp);
6418         }
6419 }
6420
6421 /*
6422  * Calculate the number of blocks we are going to release where datablocks
6423  * is the current total and length is the new file size.
6424  */
6425 static ufs2_daddr_t
6426 blkcount(fs, datablocks, length)
6427         struct fs *fs;
6428         ufs2_daddr_t datablocks;
6429         off_t length;
6430 {
6431         off_t totblks, numblks;
6432
6433         totblks = 0;
6434         numblks = howmany(length, fs->fs_bsize);
6435         if (numblks <= UFS_NDADDR) {
6436                 totblks = howmany(length, fs->fs_fsize);
6437                 goto out;
6438         }
6439         totblks = blkstofrags(fs, numblks);
6440         numblks -= UFS_NDADDR;
6441         /*
6442          * Count all single, then double, then triple indirects required.
6443          * Subtracting one indirects worth of blocks for each pass
6444          * acknowledges one of each pointed to by the inode.
6445          */
6446         for (;;) {
6447                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6448                 numblks -= NINDIR(fs);
6449                 if (numblks <= 0)
6450                         break;
6451                 numblks = howmany(numblks, NINDIR(fs));
6452         }
6453 out:
6454         totblks = fsbtodb(fs, totblks);
6455         /*
6456          * Handle sparse files.  We can't reclaim more blocks than the inode
6457          * references.  We will correct it later in handle_complete_freeblks()
6458          * when we know the real count.
6459          */
6460         if (totblks > datablocks)
6461                 return (0);
6462         return (datablocks - totblks);
6463 }
6464
6465 /*
6466  * Handle freeblocks for journaled softupdate filesystems.
6467  *
6468  * Contrary to normal softupdates, we must preserve the block pointers in
6469  * indirects until their subordinates are free.  This is to avoid journaling
6470  * every block that is freed which may consume more space than the journal
6471  * itself.  The recovery program will see the free block journals at the
6472  * base of the truncated area and traverse them to reclaim space.  The
6473  * pointers in the inode may be cleared immediately after the journal
6474  * records are written because each direct and indirect pointer in the
6475  * inode is recorded in a journal.  This permits full truncation to proceed
6476  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6477  *
6478  * The algorithm is as follows:
6479  * 1) Traverse the in-memory state and create journal entries to release
6480  *    the relevant blocks and full indirect trees.
6481  * 2) Traverse the indirect block chain adding partial truncation freework
6482  *    records to indirects in the path to lastlbn.  The freework will
6483  *    prevent new allocation dependencies from being satisfied in this
6484  *    indirect until the truncation completes.
6485  * 3) Read and lock the inode block, performing an update with the new size
6486  *    and pointers.  This prevents truncated data from becoming valid on
6487  *    disk through step 4.
6488  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6489  *    eliminate journal work for those records that do not require it.
6490  * 5) Schedule the journal records to be written followed by the inode block.
6491  * 6) Allocate any necessary frags for the end of file.
6492  * 7) Zero any partially truncated blocks.
6493  *
6494  * From this truncation proceeds asynchronously using the freework and
6495  * indir_trunc machinery.  The file will not be extended again into a
6496  * partially truncated indirect block until all work is completed but
6497  * the normal dependency mechanism ensures that it is rolled back/forward
6498  * as appropriate.  Further truncation may occur without delay and is
6499  * serialized in indir_trunc().
6500  */
6501 void
6502 softdep_journal_freeblocks(ip, cred, length, flags)
6503         struct inode *ip;       /* The inode whose length is to be reduced */
6504         struct ucred *cred;
6505         off_t length;           /* The new length for the file */
6506         int flags;              /* IO_EXT and/or IO_NORMAL */
6507 {
6508         struct freeblks *freeblks, *fbn;
6509         struct worklist *wk, *wkn;
6510         struct inodedep *inodedep;
6511         struct jblkdep *jblkdep;
6512         struct allocdirect *adp, *adpn;
6513         struct ufsmount *ump;
6514         struct fs *fs;
6515         struct buf *bp;
6516         struct vnode *vp;
6517         struct mount *mp;
6518         ufs2_daddr_t extblocks, datablocks;
6519         ufs_lbn_t tmpval, lbn, lastlbn;
6520         int frags, lastoff, iboff, allocblock, needj, error, i;
6521
6522         ump = ITOUMP(ip);
6523         mp = UFSTOVFS(ump);
6524         fs = ump->um_fs;
6525         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6526             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6527         vp = ITOV(ip);
6528         needj = 1;
6529         iboff = -1;
6530         allocblock = 0;
6531         extblocks = 0;
6532         datablocks = 0;
6533         frags = 0;
6534         freeblks = newfreeblks(mp, ip);
6535         ACQUIRE_LOCK(ump);
6536         /*
6537          * If we're truncating a removed file that will never be written
6538          * we don't need to journal the block frees.  The canceled journals
6539          * for the allocations will suffice.
6540          */
6541         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6542         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6543             length == 0)
6544                 needj = 0;
6545         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6546             ip->i_number, length, needj);
6547         FREE_LOCK(ump);
6548         /*
6549          * Calculate the lbn that we are truncating to.  This results in -1
6550          * if we're truncating the 0 bytes.  So it is the last lbn we want
6551          * to keep, not the first lbn we want to truncate.
6552          */
6553         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6554         lastoff = blkoff(fs, length);
6555         /*
6556          * Compute frags we are keeping in lastlbn.  0 means all.
6557          */
6558         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6559                 frags = fragroundup(fs, lastoff);
6560                 /* adp offset of last valid allocdirect. */
6561                 iboff = lastlbn;
6562         } else if (lastlbn > 0)
6563                 iboff = UFS_NDADDR;
6564         if (fs->fs_magic == FS_UFS2_MAGIC)
6565                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6566         /*
6567          * Handle normal data blocks and indirects.  This section saves
6568          * values used after the inode update to complete frag and indirect
6569          * truncation.
6570          */
6571         if ((flags & IO_NORMAL) != 0) {
6572                 /*
6573                  * Handle truncation of whole direct and indirect blocks.
6574                  */
6575                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6576                         setup_freedirect(freeblks, ip, i, needj);
6577                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6578                     i < UFS_NIADDR;
6579                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6580                         /* Release a whole indirect tree. */
6581                         if (lbn > lastlbn) {
6582                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6583                                     needj);
6584                                 continue;
6585                         }
6586                         iboff = i + UFS_NDADDR;
6587                         /*
6588                          * Traverse partially truncated indirect tree.
6589                          */
6590                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6591                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6592                                     lastlbn, DIP(ip, i_ib[i]));
6593                 }
6594                 /*
6595                  * Handle partial truncation to a frag boundary.
6596                  */
6597                 if (frags) {
6598                         ufs2_daddr_t blkno;
6599                         long oldfrags;
6600
6601                         oldfrags = blksize(fs, ip, lastlbn);
6602                         blkno = DIP(ip, i_db[lastlbn]);
6603                         if (blkno && oldfrags != frags) {
6604                                 oldfrags -= frags;
6605                                 oldfrags = numfrags(fs, oldfrags);
6606                                 blkno += numfrags(fs, frags);
6607                                 newfreework(ump, freeblks, NULL, lastlbn,
6608                                     blkno, oldfrags, 0, needj);
6609                                 if (needj)
6610                                         adjust_newfreework(freeblks,
6611                                             numfrags(fs, frags));
6612                         } else if (blkno == 0)
6613                                 allocblock = 1;
6614                 }
6615                 /*
6616                  * Add a journal record for partial truncate if we are
6617                  * handling indirect blocks.  Non-indirects need no extra
6618                  * journaling.
6619                  */
6620                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6621                         ip->i_flag |= IN_TRUNCATED;
6622                         newjtrunc(freeblks, length, 0);
6623                 }
6624                 ip->i_size = length;
6625                 DIP_SET(ip, i_size, ip->i_size);
6626                 datablocks = DIP(ip, i_blocks) - extblocks;
6627                 if (length != 0)
6628                         datablocks = blkcount(fs, datablocks, length);
6629                 freeblks->fb_len = length;
6630         }
6631         if ((flags & IO_EXT) != 0) {
6632                 for (i = 0; i < UFS_NXADDR; i++)
6633                         setup_freeext(freeblks, ip, i, needj);
6634                 ip->i_din2->di_extsize = 0;
6635                 datablocks += extblocks;
6636         }
6637 #ifdef QUOTA
6638         /* Reference the quotas in case the block count is wrong in the end. */
6639         quotaref(vp, freeblks->fb_quota);
6640         (void) chkdq(ip, -datablocks, NOCRED, 0);
6641 #endif
6642         freeblks->fb_chkcnt = -datablocks;
6643         UFS_LOCK(ump);
6644         fs->fs_pendingblocks += datablocks;
6645         UFS_UNLOCK(ump);
6646         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6647         /*
6648          * Handle truncation of incomplete alloc direct dependencies.  We
6649          * hold the inode block locked to prevent incomplete dependencies
6650          * from reaching the disk while we are eliminating those that
6651          * have been truncated.  This is a partially inlined ffs_update().
6652          */
6653         ufs_itimes(vp);
6654         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6655         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6656             (int)fs->fs_bsize, cred, &bp);
6657         if (error) {
6658                 brelse(bp);
6659                 softdep_error("softdep_journal_freeblocks", error);
6660                 return;
6661         }
6662         if (bp->b_bufsize == fs->fs_bsize)
6663                 bp->b_flags |= B_CLUSTEROK;
6664         softdep_update_inodeblock(ip, bp, 0);
6665         if (ump->um_fstype == UFS1)
6666                 *((struct ufs1_dinode *)bp->b_data +
6667                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6668         else
6669                 *((struct ufs2_dinode *)bp->b_data +
6670                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6671         ACQUIRE_LOCK(ump);
6672         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6673         if ((inodedep->id_state & IOSTARTED) != 0)
6674                 panic("softdep_setup_freeblocks: inode busy");
6675         /*
6676          * Add the freeblks structure to the list of operations that
6677          * must await the zero'ed inode being written to disk. If we
6678          * still have a bitmap dependency (needj), then the inode
6679          * has never been written to disk, so we can process the
6680          * freeblks below once we have deleted the dependencies.
6681          */
6682         if (needj)
6683                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6684         else
6685                 freeblks->fb_state |= COMPLETE;
6686         if ((flags & IO_NORMAL) != 0) {
6687                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6688                         if (adp->ad_offset > iboff)
6689                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6690                                     freeblks);
6691                         /*
6692                          * Truncate the allocdirect.  We could eliminate
6693                          * or modify journal records as well.
6694                          */
6695                         else if (adp->ad_offset == iboff && frags)
6696                                 adp->ad_newsize = frags;
6697                 }
6698         }
6699         if ((flags & IO_EXT) != 0)
6700                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6701                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6702                             freeblks);
6703         /*
6704          * Scan the bufwait list for newblock dependencies that will never
6705          * make it to disk.
6706          */
6707         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6708                 if (wk->wk_type != D_ALLOCDIRECT)
6709                         continue;
6710                 adp = WK_ALLOCDIRECT(wk);
6711                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6712                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6713                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6714                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6715                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6716                 }
6717         }
6718         /*
6719          * Add journal work.
6720          */
6721         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6722                 add_to_journal(&jblkdep->jb_list);
6723         FREE_LOCK(ump);
6724         bdwrite(bp);
6725         /*
6726          * Truncate dependency structures beyond length.
6727          */
6728         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6729         /*
6730          * This is only set when we need to allocate a fragment because
6731          * none existed at the end of a frag-sized file.  It handles only
6732          * allocating a new, zero filled block.
6733          */
6734         if (allocblock) {
6735                 ip->i_size = length - lastoff;
6736                 DIP_SET(ip, i_size, ip->i_size);
6737                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6738                 if (error != 0) {
6739                         softdep_error("softdep_journal_freeblks", error);
6740                         return;
6741                 }
6742                 ip->i_size = length;
6743                 DIP_SET(ip, i_size, length);
6744                 ip->i_flag |= IN_CHANGE | IN_UPDATE;
6745                 allocbuf(bp, frags);
6746                 ffs_update(vp, 0);
6747                 bawrite(bp);
6748         } else if (lastoff != 0 && vp->v_type != VDIR) {
6749                 int size;
6750
6751                 /*
6752                  * Zero the end of a truncated frag or block.
6753                  */
6754                 size = sblksize(fs, length, lastlbn);
6755                 error = bread(vp, lastlbn, size, cred, &bp);
6756                 if (error) {
6757                         softdep_error("softdep_journal_freeblks", error);
6758                         return;
6759                 }
6760                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6761                 bawrite(bp);
6762
6763         }
6764         ACQUIRE_LOCK(ump);
6765         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6766         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6767         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6768         /*
6769          * We zero earlier truncations so they don't erroneously
6770          * update i_blocks.
6771          */
6772         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6773                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6774                         fbn->fb_len = 0;
6775         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6776             LIST_EMPTY(&freeblks->fb_jblkdephd))
6777                 freeblks->fb_state |= INPROGRESS;
6778         else
6779                 freeblks = NULL;
6780         FREE_LOCK(ump);
6781         if (freeblks)
6782                 handle_workitem_freeblocks(freeblks, 0);
6783         trunc_pages(ip, length, extblocks, flags);
6784
6785 }
6786
6787 /*
6788  * Flush a JOP_SYNC to the journal.
6789  */
6790 void
6791 softdep_journal_fsync(ip)
6792         struct inode *ip;
6793 {
6794         struct jfsync *jfsync;
6795         struct ufsmount *ump;
6796
6797         ump = ITOUMP(ip);
6798         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6799             ("softdep_journal_fsync called on non-softdep filesystem"));
6800         if ((ip->i_flag & IN_TRUNCATED) == 0)
6801                 return;
6802         ip->i_flag &= ~IN_TRUNCATED;
6803         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6804         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6805         jfsync->jfs_size = ip->i_size;
6806         jfsync->jfs_ino = ip->i_number;
6807         ACQUIRE_LOCK(ump);
6808         add_to_journal(&jfsync->jfs_list);
6809         jwait(&jfsync->jfs_list, MNT_WAIT);
6810         FREE_LOCK(ump);
6811 }
6812
6813 /*
6814  * Block de-allocation dependencies.
6815  * 
6816  * When blocks are de-allocated, the on-disk pointers must be nullified before
6817  * the blocks are made available for use by other files.  (The true
6818  * requirement is that old pointers must be nullified before new on-disk
6819  * pointers are set.  We chose this slightly more stringent requirement to
6820  * reduce complexity.) Our implementation handles this dependency by updating
6821  * the inode (or indirect block) appropriately but delaying the actual block
6822  * de-allocation (i.e., freemap and free space count manipulation) until
6823  * after the updated versions reach stable storage.  After the disk is
6824  * updated, the blocks can be safely de-allocated whenever it is convenient.
6825  * This implementation handles only the common case of reducing a file's
6826  * length to zero. Other cases are handled by the conventional synchronous
6827  * write approach.
6828  *
6829  * The ffs implementation with which we worked double-checks
6830  * the state of the block pointers and file size as it reduces
6831  * a file's length.  Some of this code is replicated here in our
6832  * soft updates implementation.  The freeblks->fb_chkcnt field is
6833  * used to transfer a part of this information to the procedure
6834  * that eventually de-allocates the blocks.
6835  *
6836  * This routine should be called from the routine that shortens
6837  * a file's length, before the inode's size or block pointers
6838  * are modified. It will save the block pointer information for
6839  * later release and zero the inode so that the calling routine
6840  * can release it.
6841  */
6842 void
6843 softdep_setup_freeblocks(ip, length, flags)
6844         struct inode *ip;       /* The inode whose length is to be reduced */
6845         off_t length;           /* The new length for the file */
6846         int flags;              /* IO_EXT and/or IO_NORMAL */
6847 {
6848         struct ufs1_dinode *dp1;
6849         struct ufs2_dinode *dp2;
6850         struct freeblks *freeblks;
6851         struct inodedep *inodedep;
6852         struct allocdirect *adp;
6853         struct ufsmount *ump;
6854         struct buf *bp;
6855         struct fs *fs;
6856         ufs2_daddr_t extblocks, datablocks;
6857         struct mount *mp;
6858         int i, delay, error;
6859         ufs_lbn_t tmpval;
6860         ufs_lbn_t lbn;
6861
6862         ump = ITOUMP(ip);
6863         mp = UFSTOVFS(ump);
6864         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6865             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6866         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6867             ip->i_number, length);
6868         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6869         fs = ump->um_fs;
6870         if ((error = bread(ump->um_devvp,
6871             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6872             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6873                 brelse(bp);
6874                 softdep_error("softdep_setup_freeblocks", error);
6875                 return;
6876         }
6877         freeblks = newfreeblks(mp, ip);
6878         extblocks = 0;
6879         datablocks = 0;
6880         if (fs->fs_magic == FS_UFS2_MAGIC)
6881                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6882         if ((flags & IO_NORMAL) != 0) {
6883                 for (i = 0; i < UFS_NDADDR; i++)
6884                         setup_freedirect(freeblks, ip, i, 0);
6885                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6886                     i < UFS_NIADDR;
6887                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6888                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6889                 ip->i_size = 0;
6890                 DIP_SET(ip, i_size, 0);
6891                 datablocks = DIP(ip, i_blocks) - extblocks;
6892         }
6893         if ((flags & IO_EXT) != 0) {
6894                 for (i = 0; i < UFS_NXADDR; i++)
6895                         setup_freeext(freeblks, ip, i, 0);
6896                 ip->i_din2->di_extsize = 0;
6897                 datablocks += extblocks;
6898         }
6899 #ifdef QUOTA
6900         /* Reference the quotas in case the block count is wrong in the end. */
6901         quotaref(ITOV(ip), freeblks->fb_quota);
6902         (void) chkdq(ip, -datablocks, NOCRED, 0);
6903 #endif
6904         freeblks->fb_chkcnt = -datablocks;
6905         UFS_LOCK(ump);
6906         fs->fs_pendingblocks += datablocks;
6907         UFS_UNLOCK(ump);
6908         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6909         /*
6910          * Push the zero'ed inode to its disk buffer so that we are free
6911          * to delete its dependencies below. Once the dependencies are gone
6912          * the buffer can be safely released.
6913          */
6914         if (ump->um_fstype == UFS1) {
6915                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6916                     ino_to_fsbo(fs, ip->i_number));
6917                 ip->i_din1->di_freelink = dp1->di_freelink;
6918                 *dp1 = *ip->i_din1;
6919         } else {
6920                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6921                     ino_to_fsbo(fs, ip->i_number));
6922                 ip->i_din2->di_freelink = dp2->di_freelink;
6923                 *dp2 = *ip->i_din2;
6924         }
6925         /*
6926          * Find and eliminate any inode dependencies.
6927          */
6928         ACQUIRE_LOCK(ump);
6929         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6930         if ((inodedep->id_state & IOSTARTED) != 0)
6931                 panic("softdep_setup_freeblocks: inode busy");
6932         /*
6933          * Add the freeblks structure to the list of operations that
6934          * must await the zero'ed inode being written to disk. If we
6935          * still have a bitmap dependency (delay == 0), then the inode
6936          * has never been written to disk, so we can process the
6937          * freeblks below once we have deleted the dependencies.
6938          */
6939         delay = (inodedep->id_state & DEPCOMPLETE);
6940         if (delay)
6941                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6942         else
6943                 freeblks->fb_state |= COMPLETE;
6944         /*
6945          * Because the file length has been truncated to zero, any
6946          * pending block allocation dependency structures associated
6947          * with this inode are obsolete and can simply be de-allocated.
6948          * We must first merge the two dependency lists to get rid of
6949          * any duplicate freefrag structures, then purge the merged list.
6950          * If we still have a bitmap dependency, then the inode has never
6951          * been written to disk, so we can free any fragments without delay.
6952          */
6953         if (flags & IO_NORMAL) {
6954                 merge_inode_lists(&inodedep->id_newinoupdt,
6955                     &inodedep->id_inoupdt);
6956                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
6957                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
6958                             freeblks);
6959         }
6960         if (flags & IO_EXT) {
6961                 merge_inode_lists(&inodedep->id_newextupdt,
6962                     &inodedep->id_extupdt);
6963                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6964                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6965                             freeblks);
6966         }
6967         FREE_LOCK(ump);
6968         bdwrite(bp);
6969         trunc_dependencies(ip, freeblks, -1, 0, flags);
6970         ACQUIRE_LOCK(ump);
6971         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6972                 (void) free_inodedep(inodedep);
6973         freeblks->fb_state |= DEPCOMPLETE;
6974         /*
6975          * If the inode with zeroed block pointers is now on disk
6976          * we can start freeing blocks.
6977          */  
6978         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6979                 freeblks->fb_state |= INPROGRESS;
6980         else
6981                 freeblks = NULL;
6982         FREE_LOCK(ump);
6983         if (freeblks)
6984                 handle_workitem_freeblocks(freeblks, 0);
6985         trunc_pages(ip, length, extblocks, flags);
6986 }
6987
6988 /*
6989  * Eliminate pages from the page cache that back parts of this inode and
6990  * adjust the vnode pager's idea of our size.  This prevents stale data
6991  * from hanging around in the page cache.
6992  */
6993 static void
6994 trunc_pages(ip, length, extblocks, flags)
6995         struct inode *ip;
6996         off_t length;
6997         ufs2_daddr_t extblocks;
6998         int flags;
6999 {
7000         struct vnode *vp;
7001         struct fs *fs;
7002         ufs_lbn_t lbn;
7003         off_t end, extend;
7004
7005         vp = ITOV(ip);
7006         fs = ITOFS(ip);
7007         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7008         if ((flags & IO_EXT) != 0)
7009                 vn_pages_remove(vp, extend, 0);
7010         if ((flags & IO_NORMAL) == 0)
7011                 return;
7012         BO_LOCK(&vp->v_bufobj);
7013         drain_output(vp);
7014         BO_UNLOCK(&vp->v_bufobj);
7015         /*
7016          * The vnode pager eliminates file pages we eliminate indirects
7017          * below.
7018          */
7019         vnode_pager_setsize(vp, length);
7020         /*
7021          * Calculate the end based on the last indirect we want to keep.  If
7022          * the block extends into indirects we can just use the negative of
7023          * its lbn.  Doubles and triples exist at lower numbers so we must
7024          * be careful not to remove those, if they exist.  double and triple
7025          * indirect lbns do not overlap with others so it is not important
7026          * to verify how many levels are required.
7027          */
7028         lbn = lblkno(fs, length);
7029         if (lbn >= UFS_NDADDR) {
7030                 /* Calculate the virtual lbn of the triple indirect. */
7031                 lbn = -lbn - (UFS_NIADDR - 1);
7032                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7033         } else
7034                 end = extend;
7035         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7036 }
7037
7038 /*
7039  * See if the buf bp is in the range eliminated by truncation.
7040  */
7041 static int
7042 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7043         struct buf *bp;
7044         int *blkoffp;
7045         ufs_lbn_t lastlbn;
7046         int lastoff;
7047         int flags;
7048 {
7049         ufs_lbn_t lbn;
7050
7051         *blkoffp = 0;
7052         /* Only match ext/normal blocks as appropriate. */
7053         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7054             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7055                 return (0);
7056         /* ALTDATA is always a full truncation. */
7057         if ((bp->b_xflags & BX_ALTDATA) != 0)
7058                 return (1);
7059         /* -1 is full truncation. */
7060         if (lastlbn == -1)
7061                 return (1);
7062         /*
7063          * If this is a partial truncate we only want those
7064          * blocks and indirect blocks that cover the range
7065          * we're after.
7066          */
7067         lbn = bp->b_lblkno;
7068         if (lbn < 0)
7069                 lbn = -(lbn + lbn_level(lbn));
7070         if (lbn < lastlbn)
7071                 return (0);
7072         /* Here we only truncate lblkno if it's partial. */
7073         if (lbn == lastlbn) {
7074                 if (lastoff == 0)
7075                         return (0);
7076                 *blkoffp = lastoff;
7077         }
7078         return (1);
7079 }
7080
7081 /*
7082  * Eliminate any dependencies that exist in memory beyond lblkno:off
7083  */
7084 static void
7085 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7086         struct inode *ip;
7087         struct freeblks *freeblks;
7088         ufs_lbn_t lastlbn;
7089         int lastoff;
7090         int flags;
7091 {
7092         struct bufobj *bo;
7093         struct vnode *vp;
7094         struct buf *bp;
7095         int blkoff;
7096
7097         /*
7098          * We must wait for any I/O in progress to finish so that
7099          * all potential buffers on the dirty list will be visible.
7100          * Once they are all there, walk the list and get rid of
7101          * any dependencies.
7102          */
7103         vp = ITOV(ip);
7104         bo = &vp->v_bufobj;
7105         BO_LOCK(bo);
7106         drain_output(vp);
7107         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7108                 bp->b_vflags &= ~BV_SCANNED;
7109 restart:
7110         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7111                 if (bp->b_vflags & BV_SCANNED)
7112                         continue;
7113                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7114                         bp->b_vflags |= BV_SCANNED;
7115                         continue;
7116                 }
7117                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7118                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7119                         goto restart;
7120                 BO_UNLOCK(bo);
7121                 if (deallocate_dependencies(bp, freeblks, blkoff))
7122                         bqrelse(bp);
7123                 else
7124                         brelse(bp);
7125                 BO_LOCK(bo);
7126                 goto restart;
7127         }
7128         /*
7129          * Now do the work of vtruncbuf while also matching indirect blocks.
7130          */
7131         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7132                 bp->b_vflags &= ~BV_SCANNED;
7133 cleanrestart:
7134         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7135                 if (bp->b_vflags & BV_SCANNED)
7136                         continue;
7137                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7138                         bp->b_vflags |= BV_SCANNED;
7139                         continue;
7140                 }
7141                 if (BUF_LOCK(bp,
7142                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7143                     BO_LOCKPTR(bo)) == ENOLCK) {
7144                         BO_LOCK(bo);
7145                         goto cleanrestart;
7146                 }
7147                 bp->b_vflags |= BV_SCANNED;
7148                 bremfree(bp);
7149                 if (blkoff != 0) {
7150                         allocbuf(bp, blkoff);
7151                         bqrelse(bp);
7152                 } else {
7153                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7154                         brelse(bp);
7155                 }
7156                 BO_LOCK(bo);
7157                 goto cleanrestart;
7158         }
7159         drain_output(vp);
7160         BO_UNLOCK(bo);
7161 }
7162
7163 static int
7164 cancel_pagedep(pagedep, freeblks, blkoff)
7165         struct pagedep *pagedep;
7166         struct freeblks *freeblks;
7167         int blkoff;
7168 {
7169         struct jremref *jremref;
7170         struct jmvref *jmvref;
7171         struct dirrem *dirrem, *tmp;
7172         int i;
7173
7174         /*
7175          * Copy any directory remove dependencies to the list
7176          * to be processed after the freeblks proceeds.  If
7177          * directory entry never made it to disk they
7178          * can be dumped directly onto the work list.
7179          */
7180         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7181                 /* Skip this directory removal if it is intended to remain. */
7182                 if (dirrem->dm_offset < blkoff)
7183                         continue;
7184                 /*
7185                  * If there are any dirrems we wait for the journal write
7186                  * to complete and then restart the buf scan as the lock
7187                  * has been dropped.
7188                  */
7189                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7190                         jwait(&jremref->jr_list, MNT_WAIT);
7191                         return (ERESTART);
7192                 }
7193                 LIST_REMOVE(dirrem, dm_next);
7194                 dirrem->dm_dirinum = pagedep->pd_ino;
7195                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7196         }
7197         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7198                 jwait(&jmvref->jm_list, MNT_WAIT);
7199                 return (ERESTART);
7200         }
7201         /*
7202          * When we're partially truncating a pagedep we just want to flush
7203          * journal entries and return.  There can not be any adds in the
7204          * truncated portion of the directory and newblk must remain if
7205          * part of the block remains.
7206          */
7207         if (blkoff != 0) {
7208                 struct diradd *dap;
7209
7210                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7211                         if (dap->da_offset > blkoff)
7212                                 panic("cancel_pagedep: diradd %p off %d > %d",
7213                                     dap, dap->da_offset, blkoff);
7214                 for (i = 0; i < DAHASHSZ; i++)
7215                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7216                                 if (dap->da_offset > blkoff)
7217                                         panic("cancel_pagedep: diradd %p off %d > %d",
7218                                             dap, dap->da_offset, blkoff);
7219                 return (0);
7220         }
7221         /*
7222          * There should be no directory add dependencies present
7223          * as the directory could not be truncated until all
7224          * children were removed.
7225          */
7226         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7227             ("deallocate_dependencies: pendinghd != NULL"));
7228         for (i = 0; i < DAHASHSZ; i++)
7229                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7230                     ("deallocate_dependencies: diraddhd != NULL"));
7231         if ((pagedep->pd_state & NEWBLOCK) != 0)
7232                 free_newdirblk(pagedep->pd_newdirblk);
7233         if (free_pagedep(pagedep) == 0)
7234                 panic("Failed to free pagedep %p", pagedep);
7235         return (0);
7236 }
7237
7238 /*
7239  * Reclaim any dependency structures from a buffer that is about to
7240  * be reallocated to a new vnode. The buffer must be locked, thus,
7241  * no I/O completion operations can occur while we are manipulating
7242  * its associated dependencies. The mutex is held so that other I/O's
7243  * associated with related dependencies do not occur.
7244  */
7245 static int
7246 deallocate_dependencies(bp, freeblks, off)
7247         struct buf *bp;
7248         struct freeblks *freeblks;
7249         int off;
7250 {
7251         struct indirdep *indirdep;
7252         struct pagedep *pagedep;
7253         struct worklist *wk, *wkn;
7254         struct ufsmount *ump;
7255
7256         ump = softdep_bp_to_mp(bp);
7257         if (ump == NULL)
7258                 goto done;
7259         ACQUIRE_LOCK(ump);
7260         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7261                 switch (wk->wk_type) {
7262                 case D_INDIRDEP:
7263                         indirdep = WK_INDIRDEP(wk);
7264                         if (bp->b_lblkno >= 0 ||
7265                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7266                                 panic("deallocate_dependencies: not indir");
7267                         cancel_indirdep(indirdep, bp, freeblks);
7268                         continue;
7269
7270                 case D_PAGEDEP:
7271                         pagedep = WK_PAGEDEP(wk);
7272                         if (cancel_pagedep(pagedep, freeblks, off)) {
7273                                 FREE_LOCK(ump);
7274                                 return (ERESTART);
7275                         }
7276                         continue;
7277
7278                 case D_ALLOCINDIR:
7279                         /*
7280                          * Simply remove the allocindir, we'll find it via
7281                          * the indirdep where we can clear pointers if
7282                          * needed.
7283                          */
7284                         WORKLIST_REMOVE(wk);
7285                         continue;
7286
7287                 case D_FREEWORK:
7288                         /*
7289                          * A truncation is waiting for the zero'd pointers
7290                          * to be written.  It can be freed when the freeblks
7291                          * is journaled.
7292                          */
7293                         WORKLIST_REMOVE(wk);
7294                         wk->wk_state |= ONDEPLIST;
7295                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7296                         break;
7297
7298                 case D_ALLOCDIRECT:
7299                         if (off != 0)
7300                                 continue;
7301                         /* FALLTHROUGH */
7302                 default:
7303                         panic("deallocate_dependencies: Unexpected type %s",
7304                             TYPENAME(wk->wk_type));
7305                         /* NOTREACHED */
7306                 }
7307         }
7308         FREE_LOCK(ump);
7309 done:
7310         /*
7311          * Don't throw away this buf, we were partially truncating and
7312          * some deps may always remain.
7313          */
7314         if (off) {
7315                 allocbuf(bp, off);
7316                 bp->b_vflags |= BV_SCANNED;
7317                 return (EBUSY);
7318         }
7319         bp->b_flags |= B_INVAL | B_NOCACHE;
7320
7321         return (0);
7322 }
7323
7324 /*
7325  * An allocdirect is being canceled due to a truncate.  We must make sure
7326  * the journal entry is released in concert with the blkfree that releases
7327  * the storage.  Completed journal entries must not be released until the
7328  * space is no longer pointed to by the inode or in the bitmap.
7329  */
7330 static void
7331 cancel_allocdirect(adphead, adp, freeblks)
7332         struct allocdirectlst *adphead;
7333         struct allocdirect *adp;
7334         struct freeblks *freeblks;
7335 {
7336         struct freework *freework;
7337         struct newblk *newblk;
7338         struct worklist *wk;
7339
7340         TAILQ_REMOVE(adphead, adp, ad_next);
7341         newblk = (struct newblk *)adp;
7342         freework = NULL;
7343         /*
7344          * Find the correct freework structure.
7345          */
7346         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7347                 if (wk->wk_type != D_FREEWORK)
7348                         continue;
7349                 freework = WK_FREEWORK(wk);
7350                 if (freework->fw_blkno == newblk->nb_newblkno)
7351                         break;
7352         }
7353         if (freework == NULL)
7354                 panic("cancel_allocdirect: Freework not found");
7355         /*
7356          * If a newblk exists at all we still have the journal entry that
7357          * initiated the allocation so we do not need to journal the free.
7358          */
7359         cancel_jfreeblk(freeblks, freework->fw_blkno);
7360         /*
7361          * If the journal hasn't been written the jnewblk must be passed
7362          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7363          * this by linking the journal dependency into the freework to be
7364          * freed when freework_freeblock() is called.  If the journal has
7365          * been written we can simply reclaim the journal space when the
7366          * freeblks work is complete.
7367          */
7368         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7369             &freeblks->fb_jwork);
7370         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7371 }
7372
7373
7374 /*
7375  * Cancel a new block allocation.  May be an indirect or direct block.  We
7376  * remove it from various lists and return any journal record that needs to
7377  * be resolved by the caller.
7378  *
7379  * A special consideration is made for indirects which were never pointed
7380  * at on disk and will never be found once this block is released.
7381  */
7382 static struct jnewblk *
7383 cancel_newblk(newblk, wk, wkhd)
7384         struct newblk *newblk;
7385         struct worklist *wk;
7386         struct workhead *wkhd;
7387 {
7388         struct jnewblk *jnewblk;
7389
7390         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7391             
7392         newblk->nb_state |= GOINGAWAY;
7393         /*
7394          * Previously we traversed the completedhd on each indirdep
7395          * attached to this newblk to cancel them and gather journal
7396          * work.  Since we need only the oldest journal segment and
7397          * the lowest point on the tree will always have the oldest
7398          * journal segment we are free to release the segments
7399          * of any subordinates and may leave the indirdep list to
7400          * indirdep_complete() when this newblk is freed.
7401          */
7402         if (newblk->nb_state & ONDEPLIST) {
7403                 newblk->nb_state &= ~ONDEPLIST;
7404                 LIST_REMOVE(newblk, nb_deps);
7405         }
7406         if (newblk->nb_state & ONWORKLIST)
7407                 WORKLIST_REMOVE(&newblk->nb_list);
7408         /*
7409          * If the journal entry hasn't been written we save a pointer to
7410          * the dependency that frees it until it is written or the
7411          * superseding operation completes.
7412          */
7413         jnewblk = newblk->nb_jnewblk;
7414         if (jnewblk != NULL && wk != NULL) {
7415                 newblk->nb_jnewblk = NULL;
7416                 jnewblk->jn_dep = wk;
7417         }
7418         if (!LIST_EMPTY(&newblk->nb_jwork))
7419                 jwork_move(wkhd, &newblk->nb_jwork);
7420         /*
7421          * When truncating we must free the newdirblk early to remove
7422          * the pagedep from the hash before returning.
7423          */
7424         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7425                 free_newdirblk(WK_NEWDIRBLK(wk));
7426         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7427                 panic("cancel_newblk: extra newdirblk");
7428
7429         return (jnewblk);
7430 }
7431
7432 /*
7433  * Schedule the freefrag associated with a newblk to be released once
7434  * the pointers are written and the previous block is no longer needed.
7435  */
7436 static void
7437 newblk_freefrag(newblk)
7438         struct newblk *newblk;
7439 {
7440         struct freefrag *freefrag;
7441
7442         if (newblk->nb_freefrag == NULL)
7443                 return;
7444         freefrag = newblk->nb_freefrag;
7445         newblk->nb_freefrag = NULL;
7446         freefrag->ff_state |= COMPLETE;
7447         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7448                 add_to_worklist(&freefrag->ff_list, 0);
7449 }
7450
7451 /*
7452  * Free a newblk. Generate a new freefrag work request if appropriate.
7453  * This must be called after the inode pointer and any direct block pointers
7454  * are valid or fully removed via truncate or frag extension.
7455  */
7456 static void
7457 free_newblk(newblk)
7458         struct newblk *newblk;
7459 {
7460         struct indirdep *indirdep;
7461         struct worklist *wk;
7462
7463         KASSERT(newblk->nb_jnewblk == NULL,
7464             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7465         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7466             ("free_newblk: unclaimed newblk"));
7467         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7468         newblk_freefrag(newblk);
7469         if (newblk->nb_state & ONDEPLIST)
7470                 LIST_REMOVE(newblk, nb_deps);
7471         if (newblk->nb_state & ONWORKLIST)
7472                 WORKLIST_REMOVE(&newblk->nb_list);
7473         LIST_REMOVE(newblk, nb_hash);
7474         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7475                 free_newdirblk(WK_NEWDIRBLK(wk));
7476         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7477                 panic("free_newblk: extra newdirblk");
7478         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7479                 indirdep_complete(indirdep);
7480         handle_jwork(&newblk->nb_jwork);
7481         WORKITEM_FREE(newblk, D_NEWBLK);
7482 }
7483
7484 /*
7485  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7486  * This routine must be called with splbio interrupts blocked.
7487  */
7488 static void
7489 free_newdirblk(newdirblk)
7490         struct newdirblk *newdirblk;
7491 {
7492         struct pagedep *pagedep;
7493         struct diradd *dap;
7494         struct worklist *wk;
7495
7496         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7497         WORKLIST_REMOVE(&newdirblk->db_list);
7498         /*
7499          * If the pagedep is still linked onto the directory buffer
7500          * dependency chain, then some of the entries on the
7501          * pd_pendinghd list may not be committed to disk yet. In
7502          * this case, we will simply clear the NEWBLOCK flag and
7503          * let the pd_pendinghd list be processed when the pagedep
7504          * is next written. If the pagedep is no longer on the buffer
7505          * dependency chain, then all the entries on the pd_pending
7506          * list are committed to disk and we can free them here.
7507          */
7508         pagedep = newdirblk->db_pagedep;
7509         pagedep->pd_state &= ~NEWBLOCK;
7510         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7511                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7512                         free_diradd(dap, NULL);
7513                 /*
7514                  * If no dependencies remain, the pagedep will be freed.
7515                  */
7516                 free_pagedep(pagedep);
7517         }
7518         /* Should only ever be one item in the list. */
7519         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7520                 WORKLIST_REMOVE(wk);
7521                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7522         }
7523         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7524 }
7525
7526 /*
7527  * Prepare an inode to be freed. The actual free operation is not
7528  * done until the zero'ed inode has been written to disk.
7529  */
7530 void
7531 softdep_freefile(pvp, ino, mode)
7532         struct vnode *pvp;
7533         ino_t ino;
7534         int mode;
7535 {
7536         struct inode *ip = VTOI(pvp);
7537         struct inodedep *inodedep;
7538         struct freefile *freefile;
7539         struct freeblks *freeblks;
7540         struct ufsmount *ump;
7541
7542         ump = ITOUMP(ip);
7543         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7544             ("softdep_freefile called on non-softdep filesystem"));
7545         /*
7546          * This sets up the inode de-allocation dependency.
7547          */
7548         freefile = malloc(sizeof(struct freefile),
7549                 M_FREEFILE, M_SOFTDEP_FLAGS);
7550         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7551         freefile->fx_mode = mode;
7552         freefile->fx_oldinum = ino;
7553         freefile->fx_devvp = ump->um_devvp;
7554         LIST_INIT(&freefile->fx_jwork);
7555         UFS_LOCK(ump);
7556         ump->um_fs->fs_pendinginodes += 1;
7557         UFS_UNLOCK(ump);
7558
7559         /*
7560          * If the inodedep does not exist, then the zero'ed inode has
7561          * been written to disk. If the allocated inode has never been
7562          * written to disk, then the on-disk inode is zero'ed. In either
7563          * case we can free the file immediately.  If the journal was
7564          * canceled before being written the inode will never make it to
7565          * disk and we must send the canceled journal entrys to
7566          * ffs_freefile() to be cleared in conjunction with the bitmap.
7567          * Any blocks waiting on the inode to write can be safely freed
7568          * here as it will never been written.
7569          */
7570         ACQUIRE_LOCK(ump);
7571         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7572         if (inodedep) {
7573                 /*
7574                  * Clear out freeblks that no longer need to reference
7575                  * this inode.
7576                  */
7577                 while ((freeblks =
7578                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7579                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7580                             fb_next);
7581                         freeblks->fb_state &= ~ONDEPLIST;
7582                 }
7583                 /*
7584                  * Remove this inode from the unlinked list.
7585                  */
7586                 if (inodedep->id_state & UNLINKED) {
7587                         /*
7588                          * Save the journal work to be freed with the bitmap
7589                          * before we clear UNLINKED.  Otherwise it can be lost
7590                          * if the inode block is written.
7591                          */
7592                         handle_bufwait(inodedep, &freefile->fx_jwork);
7593                         clear_unlinked_inodedep(inodedep);
7594                         /*
7595                          * Re-acquire inodedep as we've dropped the
7596                          * per-filesystem lock in clear_unlinked_inodedep().
7597                          */
7598                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7599                 }
7600         }
7601         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7602                 FREE_LOCK(ump);
7603                 handle_workitem_freefile(freefile);
7604                 return;
7605         }
7606         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7607                 inodedep->id_state |= GOINGAWAY;
7608         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7609         FREE_LOCK(ump);
7610         if (ip->i_number == ino)
7611                 ip->i_flag |= IN_MODIFIED;
7612 }
7613
7614 /*
7615  * Check to see if an inode has never been written to disk. If
7616  * so free the inodedep and return success, otherwise return failure.
7617  * This routine must be called with splbio interrupts blocked.
7618  *
7619  * If we still have a bitmap dependency, then the inode has never
7620  * been written to disk. Drop the dependency as it is no longer
7621  * necessary since the inode is being deallocated. We set the
7622  * ALLCOMPLETE flags since the bitmap now properly shows that the
7623  * inode is not allocated. Even if the inode is actively being
7624  * written, it has been rolled back to its zero'ed state, so we
7625  * are ensured that a zero inode is what is on the disk. For short
7626  * lived files, this change will usually result in removing all the
7627  * dependencies from the inode so that it can be freed immediately.
7628  */
7629 static int
7630 check_inode_unwritten(inodedep)
7631         struct inodedep *inodedep;
7632 {
7633
7634         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7635
7636         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7637             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7638             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7639             !LIST_EMPTY(&inodedep->id_bufwait) ||
7640             !LIST_EMPTY(&inodedep->id_inowait) ||
7641             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7642             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7643             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7644             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7645             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7646             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7647             inodedep->id_mkdiradd != NULL || 
7648             inodedep->id_nlinkdelta != 0)
7649                 return (0);
7650         /*
7651          * Another process might be in initiate_write_inodeblock_ufs[12]
7652          * trying to allocate memory without holding "Softdep Lock".
7653          */
7654         if ((inodedep->id_state & IOSTARTED) != 0 &&
7655             inodedep->id_savedino1 == NULL)
7656                 return (0);
7657
7658         if (inodedep->id_state & ONDEPLIST)
7659                 LIST_REMOVE(inodedep, id_deps);
7660         inodedep->id_state &= ~ONDEPLIST;
7661         inodedep->id_state |= ALLCOMPLETE;
7662         inodedep->id_bmsafemap = NULL;
7663         if (inodedep->id_state & ONWORKLIST)
7664                 WORKLIST_REMOVE(&inodedep->id_list);
7665         if (inodedep->id_savedino1 != NULL) {
7666                 free(inodedep->id_savedino1, M_SAVEDINO);
7667                 inodedep->id_savedino1 = NULL;
7668         }
7669         if (free_inodedep(inodedep) == 0)
7670                 panic("check_inode_unwritten: busy inode");
7671         return (1);
7672 }
7673
7674 static int
7675 check_inodedep_free(inodedep)
7676         struct inodedep *inodedep;
7677 {
7678
7679         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7680         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7681             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7682             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7683             !LIST_EMPTY(&inodedep->id_bufwait) ||
7684             !LIST_EMPTY(&inodedep->id_inowait) ||
7685             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7686             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7687             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7688             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7689             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7690             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7691             inodedep->id_mkdiradd != NULL ||
7692             inodedep->id_nlinkdelta != 0 ||
7693             inodedep->id_savedino1 != NULL)
7694                 return (0);
7695         return (1);
7696 }
7697
7698 /*
7699  * Try to free an inodedep structure. Return 1 if it could be freed.
7700  */
7701 static int
7702 free_inodedep(inodedep)
7703         struct inodedep *inodedep;
7704 {
7705
7706         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7707         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7708             !check_inodedep_free(inodedep))
7709                 return (0);
7710         if (inodedep->id_state & ONDEPLIST)
7711                 LIST_REMOVE(inodedep, id_deps);
7712         LIST_REMOVE(inodedep, id_hash);
7713         WORKITEM_FREE(inodedep, D_INODEDEP);
7714         return (1);
7715 }
7716
7717 /*
7718  * Free the block referenced by a freework structure.  The parent freeblks
7719  * structure is released and completed when the final cg bitmap reaches
7720  * the disk.  This routine may be freeing a jnewblk which never made it to
7721  * disk in which case we do not have to wait as the operation is undone
7722  * in memory immediately.
7723  */
7724 static void
7725 freework_freeblock(freework)
7726         struct freework *freework;
7727 {
7728         struct freeblks *freeblks;
7729         struct jnewblk *jnewblk;
7730         struct ufsmount *ump;
7731         struct workhead wkhd;
7732         struct fs *fs;
7733         int bsize;
7734         int needj;
7735
7736         ump = VFSTOUFS(freework->fw_list.wk_mp);
7737         LOCK_OWNED(ump);
7738         /*
7739          * Handle partial truncate separately.
7740          */
7741         if (freework->fw_indir) {
7742                 complete_trunc_indir(freework);
7743                 return;
7744         }
7745         freeblks = freework->fw_freeblks;
7746         fs = ump->um_fs;
7747         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7748         bsize = lfragtosize(fs, freework->fw_frags);
7749         LIST_INIT(&wkhd);
7750         /*
7751          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7752          * on the indirblk hashtable and prevents premature freeing.
7753          */
7754         freework->fw_state |= DEPCOMPLETE;
7755         /*
7756          * SUJ needs to wait for the segment referencing freed indirect
7757          * blocks to expire so that we know the checker will not confuse
7758          * a re-allocated indirect block with its old contents.
7759          */
7760         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7761                 indirblk_insert(freework);
7762         /*
7763          * If we are canceling an existing jnewblk pass it to the free
7764          * routine, otherwise pass the freeblk which will ultimately
7765          * release the freeblks.  If we're not journaling, we can just
7766          * free the freeblks immediately.
7767          */
7768         jnewblk = freework->fw_jnewblk;
7769         if (jnewblk != NULL) {
7770                 cancel_jnewblk(jnewblk, &wkhd);
7771                 needj = 0;
7772         } else if (needj) {
7773                 freework->fw_state |= DELAYEDFREE;
7774                 freeblks->fb_cgwait++;
7775                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7776         }
7777         FREE_LOCK(ump);
7778         freeblks_free(ump, freeblks, btodb(bsize));
7779         CTR4(KTR_SUJ,
7780             "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7781             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7782         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7783             freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7784         ACQUIRE_LOCK(ump);
7785         /*
7786          * The jnewblk will be discarded and the bits in the map never
7787          * made it to disk.  We can immediately free the freeblk.
7788          */
7789         if (needj == 0)
7790                 handle_written_freework(freework);
7791 }
7792
7793 /*
7794  * We enqueue freework items that need processing back on the freeblks and
7795  * add the freeblks to the worklist.  This makes it easier to find all work
7796  * required to flush a truncation in process_truncates().
7797  */
7798 static void
7799 freework_enqueue(freework)
7800         struct freework *freework;
7801 {
7802         struct freeblks *freeblks;
7803
7804         freeblks = freework->fw_freeblks;
7805         if ((freework->fw_state & INPROGRESS) == 0)
7806                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7807         if ((freeblks->fb_state &
7808             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7809             LIST_EMPTY(&freeblks->fb_jblkdephd))
7810                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7811 }
7812
7813 /*
7814  * Start, continue, or finish the process of freeing an indirect block tree.
7815  * The free operation may be paused at any point with fw_off containing the
7816  * offset to restart from.  This enables us to implement some flow control
7817  * for large truncates which may fan out and generate a huge number of
7818  * dependencies.
7819  */
7820 static void
7821 handle_workitem_indirblk(freework)
7822         struct freework *freework;
7823 {
7824         struct freeblks *freeblks;
7825         struct ufsmount *ump;
7826         struct fs *fs;
7827
7828         freeblks = freework->fw_freeblks;
7829         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7830         fs = ump->um_fs;
7831         if (freework->fw_state & DEPCOMPLETE) {
7832                 handle_written_freework(freework);
7833                 return;
7834         }
7835         if (freework->fw_off == NINDIR(fs)) {
7836                 freework_freeblock(freework);
7837                 return;
7838         }
7839         freework->fw_state |= INPROGRESS;
7840         FREE_LOCK(ump);
7841         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7842             freework->fw_lbn);
7843         ACQUIRE_LOCK(ump);
7844 }
7845
7846 /*
7847  * Called when a freework structure attached to a cg buf is written.  The
7848  * ref on either the parent or the freeblks structure is released and
7849  * the freeblks is added back to the worklist if there is more work to do.
7850  */
7851 static void
7852 handle_written_freework(freework)
7853         struct freework *freework;
7854 {
7855         struct freeblks *freeblks;
7856         struct freework *parent;
7857
7858         freeblks = freework->fw_freeblks;
7859         parent = freework->fw_parent;
7860         if (freework->fw_state & DELAYEDFREE)
7861                 freeblks->fb_cgwait--;
7862         freework->fw_state |= COMPLETE;
7863         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7864                 WORKITEM_FREE(freework, D_FREEWORK);
7865         if (parent) {
7866                 if (--parent->fw_ref == 0)
7867                         freework_enqueue(parent);
7868                 return;
7869         }
7870         if (--freeblks->fb_ref != 0)
7871                 return;
7872         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7873             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7874                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7875 }
7876
7877 /*
7878  * This workitem routine performs the block de-allocation.
7879  * The workitem is added to the pending list after the updated
7880  * inode block has been written to disk.  As mentioned above,
7881  * checks regarding the number of blocks de-allocated (compared
7882  * to the number of blocks allocated for the file) are also
7883  * performed in this function.
7884  */
7885 static int
7886 handle_workitem_freeblocks(freeblks, flags)
7887         struct freeblks *freeblks;
7888         int flags;
7889 {
7890         struct freework *freework;
7891         struct newblk *newblk;
7892         struct allocindir *aip;
7893         struct ufsmount *ump;
7894         struct worklist *wk;
7895
7896         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7897             ("handle_workitem_freeblocks: Journal entries not written."));
7898         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7899         ACQUIRE_LOCK(ump);
7900         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7901                 WORKLIST_REMOVE(wk);
7902                 switch (wk->wk_type) {
7903                 case D_DIRREM:
7904                         wk->wk_state |= COMPLETE;
7905                         add_to_worklist(wk, 0);
7906                         continue;
7907
7908                 case D_ALLOCDIRECT:
7909                         free_newblk(WK_NEWBLK(wk));
7910                         continue;
7911
7912                 case D_ALLOCINDIR:
7913                         aip = WK_ALLOCINDIR(wk);
7914                         freework = NULL;
7915                         if (aip->ai_state & DELAYEDFREE) {
7916                                 FREE_LOCK(ump);
7917                                 freework = newfreework(ump, freeblks, NULL,
7918                                     aip->ai_lbn, aip->ai_newblkno,
7919                                     ump->um_fs->fs_frag, 0, 0);
7920                                 ACQUIRE_LOCK(ump);
7921                         }
7922                         newblk = WK_NEWBLK(wk);
7923                         if (newblk->nb_jnewblk) {
7924                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7925                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7926                                 newblk->nb_jnewblk = NULL;
7927                         }
7928                         free_newblk(newblk);
7929                         continue;
7930
7931                 case D_FREEWORK:
7932                         freework = WK_FREEWORK(wk);
7933                         if (freework->fw_lbn <= -UFS_NDADDR)
7934                                 handle_workitem_indirblk(freework);
7935                         else
7936                                 freework_freeblock(freework);
7937                         continue;
7938                 default:
7939                         panic("handle_workitem_freeblocks: Unknown type %s",
7940                             TYPENAME(wk->wk_type));
7941                 }
7942         }
7943         if (freeblks->fb_ref != 0) {
7944                 freeblks->fb_state &= ~INPROGRESS;
7945                 wake_worklist(&freeblks->fb_list);
7946                 freeblks = NULL;
7947         }
7948         FREE_LOCK(ump);
7949         if (freeblks)
7950                 return handle_complete_freeblocks(freeblks, flags);
7951         return (0);
7952 }
7953
7954 /*
7955  * Handle completion of block free via truncate.  This allows fs_pending
7956  * to track the actual free block count more closely than if we only updated
7957  * it at the end.  We must be careful to handle cases where the block count
7958  * on free was incorrect.
7959  */
7960 static void
7961 freeblks_free(ump, freeblks, blocks)
7962         struct ufsmount *ump;
7963         struct freeblks *freeblks;
7964         int blocks;
7965 {
7966         struct fs *fs;
7967         ufs2_daddr_t remain;
7968
7969         UFS_LOCK(ump);
7970         remain = -freeblks->fb_chkcnt;
7971         freeblks->fb_chkcnt += blocks;
7972         if (remain > 0) {
7973                 if (remain < blocks)
7974                         blocks = remain;
7975                 fs = ump->um_fs;
7976                 fs->fs_pendingblocks -= blocks;
7977         }
7978         UFS_UNLOCK(ump);
7979 }
7980
7981 /*
7982  * Once all of the freework workitems are complete we can retire the
7983  * freeblocks dependency and any journal work awaiting completion.  This
7984  * can not be called until all other dependencies are stable on disk.
7985  */
7986 static int
7987 handle_complete_freeblocks(freeblks, flags)
7988         struct freeblks *freeblks;
7989         int flags;
7990 {
7991         struct inodedep *inodedep;
7992         struct inode *ip;
7993         struct vnode *vp;
7994         struct fs *fs;
7995         struct ufsmount *ump;
7996         ufs2_daddr_t spare;
7997
7998         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7999         fs = ump->um_fs;
8000         flags = LK_EXCLUSIVE | flags;
8001         spare = freeblks->fb_chkcnt;
8002
8003         /*
8004          * If we did not release the expected number of blocks we may have
8005          * to adjust the inode block count here.  Only do so if it wasn't
8006          * a truncation to zero and the modrev still matches.
8007          */
8008         if (spare && freeblks->fb_len != 0) {
8009                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8010                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8011                         return (EBUSY);
8012                 ip = VTOI(vp);
8013                 if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8014                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8015                         ip->i_flag |= IN_CHANGE;
8016                         /*
8017                          * We must wait so this happens before the
8018                          * journal is reclaimed.
8019                          */
8020                         ffs_update(vp, 1);
8021                 }
8022                 vput(vp);
8023         }
8024         if (spare < 0) {
8025                 UFS_LOCK(ump);
8026                 fs->fs_pendingblocks += spare;
8027                 UFS_UNLOCK(ump);
8028         }
8029 #ifdef QUOTA
8030         /* Handle spare. */
8031         if (spare)
8032                 quotaadj(freeblks->fb_quota, ump, -spare);
8033         quotarele(freeblks->fb_quota);
8034 #endif
8035         ACQUIRE_LOCK(ump);
8036         if (freeblks->fb_state & ONDEPLIST) {
8037                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8038                     0, &inodedep);
8039                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8040                 freeblks->fb_state &= ~ONDEPLIST;
8041                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8042                         free_inodedep(inodedep);
8043         }
8044         /*
8045          * All of the freeblock deps must be complete prior to this call
8046          * so it's now safe to complete earlier outstanding journal entries.
8047          */
8048         handle_jwork(&freeblks->fb_jwork);
8049         WORKITEM_FREE(freeblks, D_FREEBLKS);
8050         FREE_LOCK(ump);
8051         return (0);
8052 }
8053
8054 /*
8055  * Release blocks associated with the freeblks and stored in the indirect
8056  * block dbn. If level is greater than SINGLE, the block is an indirect block
8057  * and recursive calls to indirtrunc must be used to cleanse other indirect
8058  * blocks.
8059  *
8060  * This handles partial and complete truncation of blocks.  Partial is noted
8061  * with goingaway == 0.  In this case the freework is completed after the
8062  * zero'd indirects are written to disk.  For full truncation the freework
8063  * is completed after the block is freed.
8064  */
8065 static void
8066 indir_trunc(freework, dbn, lbn)
8067         struct freework *freework;
8068         ufs2_daddr_t dbn;
8069         ufs_lbn_t lbn;
8070 {
8071         struct freework *nfreework;
8072         struct workhead wkhd;
8073         struct freeblks *freeblks;
8074         struct buf *bp;
8075         struct fs *fs;
8076         struct indirdep *indirdep;
8077         struct ufsmount *ump;
8078         ufs1_daddr_t *bap1;
8079         ufs2_daddr_t nb, nnb, *bap2;
8080         ufs_lbn_t lbnadd, nlbn;
8081         int i, nblocks, ufs1fmt;
8082         int freedblocks;
8083         int goingaway;
8084         int freedeps;
8085         int needj;
8086         int level;
8087         int cnt;
8088
8089         freeblks = freework->fw_freeblks;
8090         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8091         fs = ump->um_fs;
8092         /*
8093          * Get buffer of block pointers to be freed.  There are three cases:
8094          * 
8095          * 1) Partial truncate caches the indirdep pointer in the freework
8096          *    which provides us a back copy to the save bp which holds the
8097          *    pointers we want to clear.  When this completes the zero
8098          *    pointers are written to the real copy.
8099          * 2) The indirect is being completely truncated, cancel_indirdep()
8100          *    eliminated the real copy and placed the indirdep on the saved
8101          *    copy.  The indirdep and buf are discarded when this completes.
8102          * 3) The indirect was not in memory, we read a copy off of the disk
8103          *    using the devvp and drop and invalidate the buffer when we're
8104          *    done.
8105          */
8106         goingaway = 1;
8107         indirdep = NULL;
8108         if (freework->fw_indir != NULL) {
8109                 goingaway = 0;
8110                 indirdep = freework->fw_indir;
8111                 bp = indirdep->ir_savebp;
8112                 if (bp == NULL || bp->b_blkno != dbn)
8113                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8114                             bp, (intmax_t)dbn);
8115         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8116                 /*
8117                  * The lock prevents the buf dep list from changing and
8118                  * indirects on devvp should only ever have one dependency.
8119                  */
8120                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8121                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8122                         panic("indir_trunc: Bad indirdep %p from buf %p",
8123                             indirdep, bp);
8124         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8125             NOCRED, &bp) != 0) {
8126                 brelse(bp);
8127                 return;
8128         }
8129         ACQUIRE_LOCK(ump);
8130         /* Protects against a race with complete_trunc_indir(). */
8131         freework->fw_state &= ~INPROGRESS;
8132         /*
8133          * If we have an indirdep we need to enforce the truncation order
8134          * and discard it when it is complete.
8135          */
8136         if (indirdep) {
8137                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8138                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8139                         /*
8140                          * Add the complete truncate to the list on the
8141                          * indirdep to enforce in-order processing.
8142                          */
8143                         if (freework->fw_indir == NULL)
8144                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8145                                     freework, fw_next);
8146                         FREE_LOCK(ump);
8147                         return;
8148                 }
8149                 /*
8150                  * If we're goingaway, free the indirdep.  Otherwise it will
8151                  * linger until the write completes.
8152                  */
8153                 if (goingaway)
8154                         free_indirdep(indirdep);
8155         }
8156         FREE_LOCK(ump);
8157         /* Initialize pointers depending on block size. */
8158         if (ump->um_fstype == UFS1) {
8159                 bap1 = (ufs1_daddr_t *)bp->b_data;
8160                 nb = bap1[freework->fw_off];
8161                 ufs1fmt = 1;
8162                 bap2 = NULL;
8163         } else {
8164                 bap2 = (ufs2_daddr_t *)bp->b_data;
8165                 nb = bap2[freework->fw_off];
8166                 ufs1fmt = 0;
8167                 bap1 = NULL;
8168         }
8169         level = lbn_level(lbn);
8170         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8171         lbnadd = lbn_offset(fs, level);
8172         nblocks = btodb(fs->fs_bsize);
8173         nfreework = freework;
8174         freedeps = 0;
8175         cnt = 0;
8176         /*
8177          * Reclaim blocks.  Traverses into nested indirect levels and
8178          * arranges for the current level to be freed when subordinates
8179          * are free when journaling.
8180          */
8181         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8182                 if (i != NINDIR(fs) - 1) {
8183                         if (ufs1fmt)
8184                                 nnb = bap1[i+1];
8185                         else
8186                                 nnb = bap2[i+1];
8187                 } else
8188                         nnb = 0;
8189                 if (nb == 0)
8190                         continue;
8191                 cnt++;
8192                 if (level != 0) {
8193                         nlbn = (lbn + 1) - (i * lbnadd);
8194                         if (needj != 0) {
8195                                 nfreework = newfreework(ump, freeblks, freework,
8196                                     nlbn, nb, fs->fs_frag, 0, 0);
8197                                 freedeps++;
8198                         }
8199                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8200                 } else {
8201                         struct freedep *freedep;
8202
8203                         /*
8204                          * Attempt to aggregate freedep dependencies for
8205                          * all blocks being released to the same CG.
8206                          */
8207                         LIST_INIT(&wkhd);
8208                         if (needj != 0 &&
8209                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8210                                 freedep = newfreedep(freework);
8211                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8212                                     &freedep->fd_list);
8213                                 freedeps++;
8214                         }
8215                         CTR3(KTR_SUJ,
8216                             "indir_trunc: ino %d blkno %jd size %ld",
8217                             freeblks->fb_inum, nb, fs->fs_bsize);
8218                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8219                             fs->fs_bsize, freeblks->fb_inum,
8220                             freeblks->fb_vtype, &wkhd);
8221                 }
8222         }
8223         if (goingaway) {
8224                 bp->b_flags |= B_INVAL | B_NOCACHE;
8225                 brelse(bp);
8226         }
8227         freedblocks = 0;
8228         if (level == 0)
8229                 freedblocks = (nblocks * cnt);
8230         if (needj == 0)
8231                 freedblocks += nblocks;
8232         freeblks_free(ump, freeblks, freedblocks);
8233         /*
8234          * If we are journaling set up the ref counts and offset so this
8235          * indirect can be completed when its children are free.
8236          */
8237         if (needj) {
8238                 ACQUIRE_LOCK(ump);
8239                 freework->fw_off = i;
8240                 freework->fw_ref += freedeps;
8241                 freework->fw_ref -= NINDIR(fs) + 1;
8242                 if (level == 0)
8243                         freeblks->fb_cgwait += freedeps;
8244                 if (freework->fw_ref == 0)
8245                         freework_freeblock(freework);
8246                 FREE_LOCK(ump);
8247                 return;
8248         }
8249         /*
8250          * If we're not journaling we can free the indirect now.
8251          */
8252         dbn = dbtofsb(fs, dbn);
8253         CTR3(KTR_SUJ,
8254             "indir_trunc 2: ino %d blkno %jd size %ld",
8255             freeblks->fb_inum, dbn, fs->fs_bsize);
8256         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8257             freeblks->fb_inum, freeblks->fb_vtype, NULL);
8258         /* Non SUJ softdep does single-threaded truncations. */
8259         if (freework->fw_blkno == dbn) {
8260                 freework->fw_state |= ALLCOMPLETE;
8261                 ACQUIRE_LOCK(ump);
8262                 handle_written_freework(freework);
8263                 FREE_LOCK(ump);
8264         }
8265         return;
8266 }
8267
8268 /*
8269  * Cancel an allocindir when it is removed via truncation.  When bp is not
8270  * NULL the indirect never appeared on disk and is scheduled to be freed
8271  * independently of the indir so we can more easily track journal work.
8272  */
8273 static void
8274 cancel_allocindir(aip, bp, freeblks, trunc)
8275         struct allocindir *aip;
8276         struct buf *bp;
8277         struct freeblks *freeblks;
8278         int trunc;
8279 {
8280         struct indirdep *indirdep;
8281         struct freefrag *freefrag;
8282         struct newblk *newblk;
8283
8284         newblk = (struct newblk *)aip;
8285         LIST_REMOVE(aip, ai_next);
8286         /*
8287          * We must eliminate the pointer in bp if it must be freed on its
8288          * own due to partial truncate or pending journal work.
8289          */
8290         if (bp && (trunc || newblk->nb_jnewblk)) {
8291                 /*
8292                  * Clear the pointer and mark the aip to be freed
8293                  * directly if it never existed on disk.
8294                  */
8295                 aip->ai_state |= DELAYEDFREE;
8296                 indirdep = aip->ai_indirdep;
8297                 if (indirdep->ir_state & UFS1FMT)
8298                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8299                 else
8300                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8301         }
8302         /*
8303          * When truncating the previous pointer will be freed via
8304          * savedbp.  Eliminate the freefrag which would dup free.
8305          */
8306         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8307                 newblk->nb_freefrag = NULL;
8308                 if (freefrag->ff_jdep)
8309                         cancel_jfreefrag(
8310                             WK_JFREEFRAG(freefrag->ff_jdep));
8311                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8312                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8313         }
8314         /*
8315          * If the journal hasn't been written the jnewblk must be passed
8316          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8317          * this by leaving the journal dependency on the newblk to be freed
8318          * when a freework is created in handle_workitem_freeblocks().
8319          */
8320         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8321         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8322 }
8323
8324 /*
8325  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8326  * in to a newdirblk so any subsequent additions are tracked properly.  The
8327  * caller is responsible for adding the mkdir1 dependency to the journal
8328  * and updating id_mkdiradd.  This function returns with the per-filesystem
8329  * lock held.
8330  */
8331 static struct mkdir *
8332 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8333         struct diradd *dap;
8334         ino_t newinum;
8335         ino_t dinum;
8336         struct buf *newdirbp;
8337         struct mkdir **mkdirp;
8338 {
8339         struct newblk *newblk;
8340         struct pagedep *pagedep;
8341         struct inodedep *inodedep;
8342         struct newdirblk *newdirblk;
8343         struct mkdir *mkdir1, *mkdir2;
8344         struct worklist *wk;
8345         struct jaddref *jaddref;
8346         struct ufsmount *ump;
8347         struct mount *mp;
8348
8349         mp = dap->da_list.wk_mp;
8350         ump = VFSTOUFS(mp);
8351         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8352             M_SOFTDEP_FLAGS);
8353         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8354         LIST_INIT(&newdirblk->db_mkdir);
8355         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8356         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8357         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8358         mkdir1->md_diradd = dap;
8359         mkdir1->md_jaddref = NULL;
8360         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8361         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8362         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8363         mkdir2->md_diradd = dap;
8364         mkdir2->md_jaddref = NULL;
8365         if (MOUNTEDSUJ(mp) == 0) {
8366                 mkdir1->md_state |= DEPCOMPLETE;
8367                 mkdir2->md_state |= DEPCOMPLETE;
8368         }
8369         /*
8370          * Dependency on "." and ".." being written to disk.
8371          */
8372         mkdir1->md_buf = newdirbp;
8373         ACQUIRE_LOCK(VFSTOUFS(mp));
8374         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8375         /*
8376          * We must link the pagedep, allocdirect, and newdirblk for
8377          * the initial file page so the pointer to the new directory
8378          * is not written until the directory contents are live and
8379          * any subsequent additions are not marked live until the
8380          * block is reachable via the inode.
8381          */
8382         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8383                 panic("setup_newdir: lost pagedep");
8384         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8385                 if (wk->wk_type == D_ALLOCDIRECT)
8386                         break;
8387         if (wk == NULL)
8388                 panic("setup_newdir: lost allocdirect");
8389         if (pagedep->pd_state & NEWBLOCK)
8390                 panic("setup_newdir: NEWBLOCK already set");
8391         newblk = WK_NEWBLK(wk);
8392         pagedep->pd_state |= NEWBLOCK;
8393         pagedep->pd_newdirblk = newdirblk;
8394         newdirblk->db_pagedep = pagedep;
8395         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8396         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8397         /*
8398          * Look up the inodedep for the parent directory so that we
8399          * can link mkdir2 into the pending dotdot jaddref or
8400          * the inode write if there is none.  If the inode is
8401          * ALLCOMPLETE and no jaddref is present all dependencies have
8402          * been satisfied and mkdir2 can be freed.
8403          */
8404         inodedep_lookup(mp, dinum, 0, &inodedep);
8405         if (MOUNTEDSUJ(mp)) {
8406                 if (inodedep == NULL)
8407                         panic("setup_newdir: Lost parent.");
8408                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8409                     inoreflst);
8410                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8411                     (jaddref->ja_state & MKDIR_PARENT),
8412                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8413                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8414                 mkdir2->md_jaddref = jaddref;
8415                 jaddref->ja_mkdir = mkdir2;
8416         } else if (inodedep == NULL ||
8417             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8418                 dap->da_state &= ~MKDIR_PARENT;
8419                 WORKITEM_FREE(mkdir2, D_MKDIR);
8420                 mkdir2 = NULL;
8421         } else {
8422                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8423                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8424         }
8425         *mkdirp = mkdir2;
8426
8427         return (mkdir1);
8428 }
8429
8430 /*
8431  * Directory entry addition dependencies.
8432  * 
8433  * When adding a new directory entry, the inode (with its incremented link
8434  * count) must be written to disk before the directory entry's pointer to it.
8435  * Also, if the inode is newly allocated, the corresponding freemap must be
8436  * updated (on disk) before the directory entry's pointer. These requirements
8437  * are met via undo/redo on the directory entry's pointer, which consists
8438  * simply of the inode number.
8439  * 
8440  * As directory entries are added and deleted, the free space within a
8441  * directory block can become fragmented.  The ufs filesystem will compact
8442  * a fragmented directory block to make space for a new entry. When this
8443  * occurs, the offsets of previously added entries change. Any "diradd"
8444  * dependency structures corresponding to these entries must be updated with
8445  * the new offsets.
8446  */
8447
8448 /*
8449  * This routine is called after the in-memory inode's link
8450  * count has been incremented, but before the directory entry's
8451  * pointer to the inode has been set.
8452  */
8453 int
8454 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8455         struct buf *bp;         /* buffer containing directory block */
8456         struct inode *dp;       /* inode for directory */
8457         off_t diroffset;        /* offset of new entry in directory */
8458         ino_t newinum;          /* inode referenced by new directory entry */
8459         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8460         int isnewblk;           /* entry is in a newly allocated block */
8461 {
8462         int offset;             /* offset of new entry within directory block */
8463         ufs_lbn_t lbn;          /* block in directory containing new entry */
8464         struct fs *fs;
8465         struct diradd *dap;
8466         struct newblk *newblk;
8467         struct pagedep *pagedep;
8468         struct inodedep *inodedep;
8469         struct newdirblk *newdirblk;
8470         struct mkdir *mkdir1, *mkdir2;
8471         struct jaddref *jaddref;
8472         struct ufsmount *ump;
8473         struct mount *mp;
8474         int isindir;
8475
8476         mp = ITOVFS(dp);
8477         ump = VFSTOUFS(mp);
8478         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8479             ("softdep_setup_directory_add called on non-softdep filesystem"));
8480         /*
8481          * Whiteouts have no dependencies.
8482          */
8483         if (newinum == UFS_WINO) {
8484                 if (newdirbp != NULL)
8485                         bdwrite(newdirbp);
8486                 return (0);
8487         }
8488         jaddref = NULL;
8489         mkdir1 = mkdir2 = NULL;
8490         fs = ump->um_fs;
8491         lbn = lblkno(fs, diroffset);
8492         offset = blkoff(fs, diroffset);
8493         dap = malloc(sizeof(struct diradd), M_DIRADD,
8494                 M_SOFTDEP_FLAGS|M_ZERO);
8495         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8496         dap->da_offset = offset;
8497         dap->da_newinum = newinum;
8498         dap->da_state = ATTACHED;
8499         LIST_INIT(&dap->da_jwork);
8500         isindir = bp->b_lblkno >= UFS_NDADDR;
8501         newdirblk = NULL;
8502         if (isnewblk &&
8503             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8504                 newdirblk = malloc(sizeof(struct newdirblk),
8505                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8506                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8507                 LIST_INIT(&newdirblk->db_mkdir);
8508         }
8509         /*
8510          * If we're creating a new directory setup the dependencies and set
8511          * the dap state to wait for them.  Otherwise it's COMPLETE and
8512          * we can move on.
8513          */
8514         if (newdirbp == NULL) {
8515                 dap->da_state |= DEPCOMPLETE;
8516                 ACQUIRE_LOCK(ump);
8517         } else {
8518                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8519                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8520                     &mkdir2);
8521         }
8522         /*
8523          * Link into parent directory pagedep to await its being written.
8524          */
8525         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8526 #ifdef DEBUG
8527         if (diradd_lookup(pagedep, offset) != NULL)
8528                 panic("softdep_setup_directory_add: %p already at off %d\n",
8529                     diradd_lookup(pagedep, offset), offset);
8530 #endif
8531         dap->da_pagedep = pagedep;
8532         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8533             da_pdlist);
8534         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8535         /*
8536          * If we're journaling, link the diradd into the jaddref so it
8537          * may be completed after the journal entry is written.  Otherwise,
8538          * link the diradd into its inodedep.  If the inode is not yet
8539          * written place it on the bufwait list, otherwise do the post-inode
8540          * write processing to put it on the id_pendinghd list.
8541          */
8542         if (MOUNTEDSUJ(mp)) {
8543                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8544                     inoreflst);
8545                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8546                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8547                 jaddref->ja_diroff = diroffset;
8548                 jaddref->ja_diradd = dap;
8549                 add_to_journal(&jaddref->ja_list);
8550         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8551                 diradd_inode_written(dap, inodedep);
8552         else
8553                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8554         /*
8555          * Add the journal entries for . and .. links now that the primary
8556          * link is written.
8557          */
8558         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8559                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8560                     inoreflst, if_deps);
8561                 KASSERT(jaddref != NULL &&
8562                     jaddref->ja_ino == jaddref->ja_parent &&
8563                     (jaddref->ja_state & MKDIR_BODY),
8564                     ("softdep_setup_directory_add: bad dot jaddref %p",
8565                     jaddref));
8566                 mkdir1->md_jaddref = jaddref;
8567                 jaddref->ja_mkdir = mkdir1;
8568                 /*
8569                  * It is important that the dotdot journal entry
8570                  * is added prior to the dot entry since dot writes
8571                  * both the dot and dotdot links.  These both must
8572                  * be added after the primary link for the journal
8573                  * to remain consistent.
8574                  */
8575                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8576                 add_to_journal(&jaddref->ja_list);
8577         }
8578         /*
8579          * If we are adding a new directory remember this diradd so that if
8580          * we rename it we can keep the dot and dotdot dependencies.  If
8581          * we are adding a new name for an inode that has a mkdiradd we
8582          * must be in rename and we have to move the dot and dotdot
8583          * dependencies to this new name.  The old name is being orphaned
8584          * soon.
8585          */
8586         if (mkdir1 != NULL) {
8587                 if (inodedep->id_mkdiradd != NULL)
8588                         panic("softdep_setup_directory_add: Existing mkdir");
8589                 inodedep->id_mkdiradd = dap;
8590         } else if (inodedep->id_mkdiradd)
8591                 merge_diradd(inodedep, dap);
8592         if (newdirblk != NULL) {
8593                 /*
8594                  * There is nothing to do if we are already tracking
8595                  * this block.
8596                  */
8597                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8598                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8599                         FREE_LOCK(ump);
8600                         return (0);
8601                 }
8602                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8603                     == 0)
8604                         panic("softdep_setup_directory_add: lost entry");
8605                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8606                 pagedep->pd_state |= NEWBLOCK;
8607                 pagedep->pd_newdirblk = newdirblk;
8608                 newdirblk->db_pagedep = pagedep;
8609                 FREE_LOCK(ump);
8610                 /*
8611                  * If we extended into an indirect signal direnter to sync.
8612                  */
8613                 if (isindir)
8614                         return (1);
8615                 return (0);
8616         }
8617         FREE_LOCK(ump);
8618         return (0);
8619 }
8620
8621 /*
8622  * This procedure is called to change the offset of a directory
8623  * entry when compacting a directory block which must be owned
8624  * exclusively by the caller. Note that the actual entry movement
8625  * must be done in this procedure to ensure that no I/O completions
8626  * occur while the move is in progress.
8627  */
8628 void 
8629 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8630         struct buf *bp;         /* Buffer holding directory block. */
8631         struct inode *dp;       /* inode for directory */
8632         caddr_t base;           /* address of dp->i_offset */
8633         caddr_t oldloc;         /* address of old directory location */
8634         caddr_t newloc;         /* address of new directory location */
8635         int entrysize;          /* size of directory entry */
8636 {
8637         int offset, oldoffset, newoffset;
8638         struct pagedep *pagedep;
8639         struct jmvref *jmvref;
8640         struct diradd *dap;
8641         struct direct *de;
8642         struct mount *mp;
8643         struct ufsmount *ump;
8644         ufs_lbn_t lbn;
8645         int flags;
8646
8647         mp = ITOVFS(dp);
8648         ump = VFSTOUFS(mp);
8649         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8650             ("softdep_change_directoryentry_offset called on "
8651              "non-softdep filesystem"));
8652         de = (struct direct *)oldloc;
8653         jmvref = NULL;
8654         flags = 0;
8655         /*
8656          * Moves are always journaled as it would be too complex to
8657          * determine if any affected adds or removes are present in the
8658          * journal.
8659          */
8660         if (MOUNTEDSUJ(mp)) {
8661                 flags = DEPALLOC;
8662                 jmvref = newjmvref(dp, de->d_ino,
8663                     dp->i_offset + (oldloc - base),
8664                     dp->i_offset + (newloc - base));
8665         }
8666         lbn = lblkno(ump->um_fs, dp->i_offset);
8667         offset = blkoff(ump->um_fs, dp->i_offset);
8668         oldoffset = offset + (oldloc - base);
8669         newoffset = offset + (newloc - base);
8670         ACQUIRE_LOCK(ump);
8671         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8672                 goto done;
8673         dap = diradd_lookup(pagedep, oldoffset);
8674         if (dap) {
8675                 dap->da_offset = newoffset;
8676                 newoffset = DIRADDHASH(newoffset);
8677                 oldoffset = DIRADDHASH(oldoffset);
8678                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8679                     newoffset != oldoffset) {
8680                         LIST_REMOVE(dap, da_pdlist);
8681                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8682                             dap, da_pdlist);
8683                 }
8684         }
8685 done:
8686         if (jmvref) {
8687                 jmvref->jm_pagedep = pagedep;
8688                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8689                 add_to_journal(&jmvref->jm_list);
8690         }
8691         bcopy(oldloc, newloc, entrysize);
8692         FREE_LOCK(ump);
8693 }
8694
8695 /*
8696  * Move the mkdir dependencies and journal work from one diradd to another
8697  * when renaming a directory.  The new name must depend on the mkdir deps
8698  * completing as the old name did.  Directories can only have one valid link
8699  * at a time so one must be canonical.
8700  */
8701 static void
8702 merge_diradd(inodedep, newdap)
8703         struct inodedep *inodedep;
8704         struct diradd *newdap;
8705 {
8706         struct diradd *olddap;
8707         struct mkdir *mkdir, *nextmd;
8708         struct ufsmount *ump;
8709         short state;
8710
8711         olddap = inodedep->id_mkdiradd;
8712         inodedep->id_mkdiradd = newdap;
8713         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8714                 newdap->da_state &= ~DEPCOMPLETE;
8715                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8716                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8717                      mkdir = nextmd) {
8718                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8719                         if (mkdir->md_diradd != olddap)
8720                                 continue;
8721                         mkdir->md_diradd = newdap;
8722                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8723                         newdap->da_state |= state;
8724                         olddap->da_state &= ~state;
8725                         if ((olddap->da_state &
8726                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8727                                 break;
8728                 }
8729                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8730                         panic("merge_diradd: unfound ref");
8731         }
8732         /*
8733          * Any mkdir related journal items are not safe to be freed until
8734          * the new name is stable.
8735          */
8736         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8737         olddap->da_state |= DEPCOMPLETE;
8738         complete_diradd(olddap);
8739 }
8740
8741 /*
8742  * Move the diradd to the pending list when all diradd dependencies are
8743  * complete.
8744  */
8745 static void
8746 complete_diradd(dap)
8747         struct diradd *dap;
8748 {
8749         struct pagedep *pagedep;
8750
8751         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8752                 if (dap->da_state & DIRCHG)
8753                         pagedep = dap->da_previous->dm_pagedep;
8754                 else
8755                         pagedep = dap->da_pagedep;
8756                 LIST_REMOVE(dap, da_pdlist);
8757                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8758         }
8759 }
8760
8761 /*
8762  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8763  * add entries and conditonally journal the remove.
8764  */
8765 static void
8766 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8767         struct diradd *dap;
8768         struct dirrem *dirrem;
8769         struct jremref *jremref;
8770         struct jremref *dotremref;
8771         struct jremref *dotdotremref;
8772 {
8773         struct inodedep *inodedep;
8774         struct jaddref *jaddref;
8775         struct inoref *inoref;
8776         struct ufsmount *ump;
8777         struct mkdir *mkdir;
8778
8779         /*
8780          * If no remove references were allocated we're on a non-journaled
8781          * filesystem and can skip the cancel step.
8782          */
8783         if (jremref == NULL) {
8784                 free_diradd(dap, NULL);
8785                 return;
8786         }
8787         /*
8788          * Cancel the primary name an free it if it does not require
8789          * journaling.
8790          */
8791         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8792             0, &inodedep) != 0) {
8793                 /* Abort the addref that reference this diradd.  */
8794                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8795                         if (inoref->if_list.wk_type != D_JADDREF)
8796                                 continue;
8797                         jaddref = (struct jaddref *)inoref;
8798                         if (jaddref->ja_diradd != dap)
8799                                 continue;
8800                         if (cancel_jaddref(jaddref, inodedep,
8801                             &dirrem->dm_jwork) == 0) {
8802                                 free_jremref(jremref);
8803                                 jremref = NULL;
8804                         }
8805                         break;
8806                 }
8807         }
8808         /*
8809          * Cancel subordinate names and free them if they do not require
8810          * journaling.
8811          */
8812         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8813                 ump = VFSTOUFS(dap->da_list.wk_mp);
8814                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8815                         if (mkdir->md_diradd != dap)
8816                                 continue;
8817                         if ((jaddref = mkdir->md_jaddref) == NULL)
8818                                 continue;
8819                         mkdir->md_jaddref = NULL;
8820                         if (mkdir->md_state & MKDIR_PARENT) {
8821                                 if (cancel_jaddref(jaddref, NULL,
8822                                     &dirrem->dm_jwork) == 0) {
8823                                         free_jremref(dotdotremref);
8824                                         dotdotremref = NULL;
8825                                 }
8826                         } else {
8827                                 if (cancel_jaddref(jaddref, inodedep,
8828                                     &dirrem->dm_jwork) == 0) {
8829                                         free_jremref(dotremref);
8830                                         dotremref = NULL;
8831                                 }
8832                         }
8833                 }
8834         }
8835
8836         if (jremref)
8837                 journal_jremref(dirrem, jremref, inodedep);
8838         if (dotremref)
8839                 journal_jremref(dirrem, dotremref, inodedep);
8840         if (dotdotremref)
8841                 journal_jremref(dirrem, dotdotremref, NULL);
8842         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8843         free_diradd(dap, &dirrem->dm_jwork);
8844 }
8845
8846 /*
8847  * Free a diradd dependency structure. This routine must be called
8848  * with splbio interrupts blocked.
8849  */
8850 static void
8851 free_diradd(dap, wkhd)
8852         struct diradd *dap;
8853         struct workhead *wkhd;
8854 {
8855         struct dirrem *dirrem;
8856         struct pagedep *pagedep;
8857         struct inodedep *inodedep;
8858         struct mkdir *mkdir, *nextmd;
8859         struct ufsmount *ump;
8860
8861         ump = VFSTOUFS(dap->da_list.wk_mp);
8862         LOCK_OWNED(ump);
8863         LIST_REMOVE(dap, da_pdlist);
8864         if (dap->da_state & ONWORKLIST)
8865                 WORKLIST_REMOVE(&dap->da_list);
8866         if ((dap->da_state & DIRCHG) == 0) {
8867                 pagedep = dap->da_pagedep;
8868         } else {
8869                 dirrem = dap->da_previous;
8870                 pagedep = dirrem->dm_pagedep;
8871                 dirrem->dm_dirinum = pagedep->pd_ino;
8872                 dirrem->dm_state |= COMPLETE;
8873                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8874                         add_to_worklist(&dirrem->dm_list, 0);
8875         }
8876         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8877             0, &inodedep) != 0)
8878                 if (inodedep->id_mkdiradd == dap)
8879                         inodedep->id_mkdiradd = NULL;
8880         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8881                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8882                      mkdir = nextmd) {
8883                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8884                         if (mkdir->md_diradd != dap)
8885                                 continue;
8886                         dap->da_state &=
8887                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8888                         LIST_REMOVE(mkdir, md_mkdirs);
8889                         if (mkdir->md_state & ONWORKLIST)
8890                                 WORKLIST_REMOVE(&mkdir->md_list);
8891                         if (mkdir->md_jaddref != NULL)
8892                                 panic("free_diradd: Unexpected jaddref");
8893                         WORKITEM_FREE(mkdir, D_MKDIR);
8894                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8895                                 break;
8896                 }
8897                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8898                         panic("free_diradd: unfound ref");
8899         }
8900         if (inodedep)
8901                 free_inodedep(inodedep);
8902         /*
8903          * Free any journal segments waiting for the directory write.
8904          */
8905         handle_jwork(&dap->da_jwork);
8906         WORKITEM_FREE(dap, D_DIRADD);
8907 }
8908
8909 /*
8910  * Directory entry removal dependencies.
8911  * 
8912  * When removing a directory entry, the entry's inode pointer must be
8913  * zero'ed on disk before the corresponding inode's link count is decremented
8914  * (possibly freeing the inode for re-use). This dependency is handled by
8915  * updating the directory entry but delaying the inode count reduction until
8916  * after the directory block has been written to disk. After this point, the
8917  * inode count can be decremented whenever it is convenient.
8918  */
8919
8920 /*
8921  * This routine should be called immediately after removing
8922  * a directory entry.  The inode's link count should not be
8923  * decremented by the calling procedure -- the soft updates
8924  * code will do this task when it is safe.
8925  */
8926 void 
8927 softdep_setup_remove(bp, dp, ip, isrmdir)
8928         struct buf *bp;         /* buffer containing directory block */
8929         struct inode *dp;       /* inode for the directory being modified */
8930         struct inode *ip;       /* inode for directory entry being removed */
8931         int isrmdir;            /* indicates if doing RMDIR */
8932 {
8933         struct dirrem *dirrem, *prevdirrem;
8934         struct inodedep *inodedep;
8935         struct ufsmount *ump;
8936         int direct;
8937
8938         ump = ITOUMP(ip);
8939         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
8940             ("softdep_setup_remove called on non-softdep filesystem"));
8941         /*
8942          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8943          * newdirrem() to setup the full directory remove which requires
8944          * isrmdir > 1.
8945          */
8946         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8947         /*
8948          * Add the dirrem to the inodedep's pending remove list for quick
8949          * discovery later.
8950          */
8951         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
8952                 panic("softdep_setup_remove: Lost inodedep.");
8953         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8954         dirrem->dm_state |= ONDEPLIST;
8955         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8956
8957         /*
8958          * If the COMPLETE flag is clear, then there were no active
8959          * entries and we want to roll back to a zeroed entry until
8960          * the new inode is committed to disk. If the COMPLETE flag is
8961          * set then we have deleted an entry that never made it to
8962          * disk. If the entry we deleted resulted from a name change,
8963          * then the old name still resides on disk. We cannot delete
8964          * its inode (returned to us in prevdirrem) until the zeroed
8965          * directory entry gets to disk. The new inode has never been
8966          * referenced on the disk, so can be deleted immediately.
8967          */
8968         if ((dirrem->dm_state & COMPLETE) == 0) {
8969                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8970                     dm_next);
8971                 FREE_LOCK(ump);
8972         } else {
8973                 if (prevdirrem != NULL)
8974                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8975                             prevdirrem, dm_next);
8976                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8977                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8978                 FREE_LOCK(ump);
8979                 if (direct)
8980                         handle_workitem_remove(dirrem, 0);
8981         }
8982 }
8983
8984 /*
8985  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8986  * pd_pendinghd list of a pagedep.
8987  */
8988 static struct diradd *
8989 diradd_lookup(pagedep, offset)
8990         struct pagedep *pagedep;
8991         int offset;
8992 {
8993         struct diradd *dap;
8994
8995         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8996                 if (dap->da_offset == offset)
8997                         return (dap);
8998         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8999                 if (dap->da_offset == offset)
9000                         return (dap);
9001         return (NULL);
9002 }
9003
9004 /*
9005  * Search for a .. diradd dependency in a directory that is being removed.
9006  * If the directory was renamed to a new parent we have a diradd rather
9007  * than a mkdir for the .. entry.  We need to cancel it now before
9008  * it is found in truncate().
9009  */
9010 static struct jremref *
9011 cancel_diradd_dotdot(ip, dirrem, jremref)
9012         struct inode *ip;
9013         struct dirrem *dirrem;
9014         struct jremref *jremref;
9015 {
9016         struct pagedep *pagedep;
9017         struct diradd *dap;
9018         struct worklist *wk;
9019
9020         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9021                 return (jremref);
9022         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9023         if (dap == NULL)
9024                 return (jremref);
9025         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9026         /*
9027          * Mark any journal work as belonging to the parent so it is freed
9028          * with the .. reference.
9029          */
9030         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9031                 wk->wk_state |= MKDIR_PARENT;
9032         return (NULL);
9033 }
9034
9035 /*
9036  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9037  * replace it with a dirrem/diradd pair as a result of re-parenting a
9038  * directory.  This ensures that we don't simultaneously have a mkdir and
9039  * a diradd for the same .. entry.
9040  */
9041 static struct jremref *
9042 cancel_mkdir_dotdot(ip, dirrem, jremref)
9043         struct inode *ip;
9044         struct dirrem *dirrem;
9045         struct jremref *jremref;
9046 {
9047         struct inodedep *inodedep;
9048         struct jaddref *jaddref;
9049         struct ufsmount *ump;
9050         struct mkdir *mkdir;
9051         struct diradd *dap;
9052         struct mount *mp;
9053
9054         mp = ITOVFS(ip);
9055         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9056                 return (jremref);
9057         dap = inodedep->id_mkdiradd;
9058         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9059                 return (jremref);
9060         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9061         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9062             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9063                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9064                         break;
9065         if (mkdir == NULL)
9066                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9067         if ((jaddref = mkdir->md_jaddref) != NULL) {
9068                 mkdir->md_jaddref = NULL;
9069                 jaddref->ja_state &= ~MKDIR_PARENT;
9070                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9071                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9072                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9073                         journal_jremref(dirrem, jremref, inodedep);
9074                         jremref = NULL;
9075                 }
9076         }
9077         if (mkdir->md_state & ONWORKLIST)
9078                 WORKLIST_REMOVE(&mkdir->md_list);
9079         mkdir->md_state |= ALLCOMPLETE;
9080         complete_mkdir(mkdir);
9081         return (jremref);
9082 }
9083
9084 static void
9085 journal_jremref(dirrem, jremref, inodedep)
9086         struct dirrem *dirrem;
9087         struct jremref *jremref;
9088         struct inodedep *inodedep;
9089 {
9090
9091         if (inodedep == NULL)
9092                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9093                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9094                         panic("journal_jremref: Lost inodedep");
9095         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9096         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9097         add_to_journal(&jremref->jr_list);
9098 }
9099
9100 static void
9101 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9102         struct dirrem *dirrem;
9103         struct jremref *jremref;
9104         struct jremref *dotremref;
9105         struct jremref *dotdotremref;
9106 {
9107         struct inodedep *inodedep;
9108
9109
9110         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9111             &inodedep) == 0)
9112                 panic("dirrem_journal: Lost inodedep");
9113         journal_jremref(dirrem, jremref, inodedep);
9114         if (dotremref)
9115                 journal_jremref(dirrem, dotremref, inodedep);
9116         if (dotdotremref)
9117                 journal_jremref(dirrem, dotdotremref, NULL);
9118 }
9119
9120 /*
9121  * Allocate a new dirrem if appropriate and return it along with
9122  * its associated pagedep. Called without a lock, returns with lock.
9123  */
9124 static struct dirrem *
9125 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9126         struct buf *bp;         /* buffer containing directory block */
9127         struct inode *dp;       /* inode for the directory being modified */
9128         struct inode *ip;       /* inode for directory entry being removed */
9129         int isrmdir;            /* indicates if doing RMDIR */
9130         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9131 {
9132         int offset;
9133         ufs_lbn_t lbn;
9134         struct diradd *dap;
9135         struct dirrem *dirrem;
9136         struct pagedep *pagedep;
9137         struct jremref *jremref;
9138         struct jremref *dotremref;
9139         struct jremref *dotdotremref;
9140         struct vnode *dvp;
9141         struct ufsmount *ump;
9142
9143         /*
9144          * Whiteouts have no deletion dependencies.
9145          */
9146         if (ip == NULL)
9147                 panic("newdirrem: whiteout");
9148         dvp = ITOV(dp);
9149         ump = ITOUMP(dp);
9150
9151         /*
9152          * If the system is over its limit and our filesystem is
9153          * responsible for more than our share of that usage and
9154          * we are not a snapshot, request some inodedep cleanup.
9155          * Limiting the number of dirrem structures will also limit
9156          * the number of freefile and freeblks structures.
9157          */
9158         ACQUIRE_LOCK(ump);
9159         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9160                 schedule_cleanup(UFSTOVFS(ump));
9161         else
9162                 FREE_LOCK(ump);
9163         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9164             M_ZERO);
9165         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9166         LIST_INIT(&dirrem->dm_jremrefhd);
9167         LIST_INIT(&dirrem->dm_jwork);
9168         dirrem->dm_state = isrmdir ? RMDIR : 0;
9169         dirrem->dm_oldinum = ip->i_number;
9170         *prevdirremp = NULL;
9171         /*
9172          * Allocate remove reference structures to track journal write
9173          * dependencies.  We will always have one for the link and
9174          * when doing directories we will always have one more for dot.
9175          * When renaming a directory we skip the dotdot link change so
9176          * this is not needed.
9177          */
9178         jremref = dotremref = dotdotremref = NULL;
9179         if (DOINGSUJ(dvp)) {
9180                 if (isrmdir) {
9181                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9182                             ip->i_effnlink + 2);
9183                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9184                             ip->i_effnlink + 1);
9185                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9186                             dp->i_effnlink + 1);
9187                         dotdotremref->jr_state |= MKDIR_PARENT;
9188                 } else
9189                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9190                             ip->i_effnlink + 1);
9191         }
9192         ACQUIRE_LOCK(ump);
9193         lbn = lblkno(ump->um_fs, dp->i_offset);
9194         offset = blkoff(ump->um_fs, dp->i_offset);
9195         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9196             &pagedep);
9197         dirrem->dm_pagedep = pagedep;
9198         dirrem->dm_offset = offset;
9199         /*
9200          * If we're renaming a .. link to a new directory, cancel any
9201          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9202          * the jremref is preserved for any potential diradd in this
9203          * location.  This can not coincide with a rmdir.
9204          */
9205         if (dp->i_offset == DOTDOT_OFFSET) {
9206                 if (isrmdir)
9207                         panic("newdirrem: .. directory change during remove?");
9208                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9209         }
9210         /*
9211          * If we're removing a directory search for the .. dependency now and
9212          * cancel it.  Any pending journal work will be added to the dirrem
9213          * to be completed when the workitem remove completes.
9214          */
9215         if (isrmdir)
9216                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9217         /*
9218          * Check for a diradd dependency for the same directory entry.
9219          * If present, then both dependencies become obsolete and can
9220          * be de-allocated.
9221          */
9222         dap = diradd_lookup(pagedep, offset);
9223         if (dap == NULL) {
9224                 /*
9225                  * Link the jremref structures into the dirrem so they are
9226                  * written prior to the pagedep.
9227                  */
9228                 if (jremref)
9229                         dirrem_journal(dirrem, jremref, dotremref,
9230                             dotdotremref);
9231                 return (dirrem);
9232         }
9233         /*
9234          * Must be ATTACHED at this point.
9235          */
9236         if ((dap->da_state & ATTACHED) == 0)
9237                 panic("newdirrem: not ATTACHED");
9238         if (dap->da_newinum != ip->i_number)
9239                 panic("newdirrem: inum %ju should be %ju",
9240                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9241         /*
9242          * If we are deleting a changed name that never made it to disk,
9243          * then return the dirrem describing the previous inode (which
9244          * represents the inode currently referenced from this entry on disk).
9245          */
9246         if ((dap->da_state & DIRCHG) != 0) {
9247                 *prevdirremp = dap->da_previous;
9248                 dap->da_state &= ~DIRCHG;
9249                 dap->da_pagedep = pagedep;
9250         }
9251         /*
9252          * We are deleting an entry that never made it to disk.
9253          * Mark it COMPLETE so we can delete its inode immediately.
9254          */
9255         dirrem->dm_state |= COMPLETE;
9256         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9257 #ifdef SUJ_DEBUG
9258         if (isrmdir == 0) {
9259                 struct worklist *wk;
9260
9261                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9262                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9263                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9264         }
9265 #endif
9266
9267         return (dirrem);
9268 }
9269
9270 /*
9271  * Directory entry change dependencies.
9272  * 
9273  * Changing an existing directory entry requires that an add operation
9274  * be completed first followed by a deletion. The semantics for the addition
9275  * are identical to the description of adding a new entry above except
9276  * that the rollback is to the old inode number rather than zero. Once
9277  * the addition dependency is completed, the removal is done as described
9278  * in the removal routine above.
9279  */
9280
9281 /*
9282  * This routine should be called immediately after changing
9283  * a directory entry.  The inode's link count should not be
9284  * decremented by the calling procedure -- the soft updates
9285  * code will perform this task when it is safe.
9286  */
9287 void 
9288 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9289         struct buf *bp;         /* buffer containing directory block */
9290         struct inode *dp;       /* inode for the directory being modified */
9291         struct inode *ip;       /* inode for directory entry being removed */
9292         ino_t newinum;          /* new inode number for changed entry */
9293         int isrmdir;            /* indicates if doing RMDIR */
9294 {
9295         int offset;
9296         struct diradd *dap = NULL;
9297         struct dirrem *dirrem, *prevdirrem;
9298         struct pagedep *pagedep;
9299         struct inodedep *inodedep;
9300         struct jaddref *jaddref;
9301         struct mount *mp;
9302         struct ufsmount *ump;
9303
9304         mp = ITOVFS(dp);
9305         ump = VFSTOUFS(mp);
9306         offset = blkoff(ump->um_fs, dp->i_offset);
9307         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9308            ("softdep_setup_directory_change called on non-softdep filesystem"));
9309
9310         /*
9311          * Whiteouts do not need diradd dependencies.
9312          */
9313         if (newinum != UFS_WINO) {
9314                 dap = malloc(sizeof(struct diradd),
9315                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9316                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9317                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9318                 dap->da_offset = offset;
9319                 dap->da_newinum = newinum;
9320                 LIST_INIT(&dap->da_jwork);
9321         }
9322
9323         /*
9324          * Allocate a new dirrem and ACQUIRE_LOCK.
9325          */
9326         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9327         pagedep = dirrem->dm_pagedep;
9328         /*
9329          * The possible values for isrmdir:
9330          *      0 - non-directory file rename
9331          *      1 - directory rename within same directory
9332          *   inum - directory rename to new directory of given inode number
9333          * When renaming to a new directory, we are both deleting and
9334          * creating a new directory entry, so the link count on the new
9335          * directory should not change. Thus we do not need the followup
9336          * dirrem which is usually done in handle_workitem_remove. We set
9337          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9338          * followup dirrem.
9339          */
9340         if (isrmdir > 1)
9341                 dirrem->dm_state |= DIRCHG;
9342
9343         /*
9344          * Whiteouts have no additional dependencies,
9345          * so just put the dirrem on the correct list.
9346          */
9347         if (newinum == UFS_WINO) {
9348                 if ((dirrem->dm_state & COMPLETE) == 0) {
9349                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9350                             dm_next);
9351                 } else {
9352                         dirrem->dm_dirinum = pagedep->pd_ino;
9353                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9354                                 add_to_worklist(&dirrem->dm_list, 0);
9355                 }
9356                 FREE_LOCK(ump);
9357                 return;
9358         }
9359         /*
9360          * Add the dirrem to the inodedep's pending remove list for quick
9361          * discovery later.  A valid nlinkdelta ensures that this lookup
9362          * will not fail.
9363          */
9364         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9365                 panic("softdep_setup_directory_change: Lost inodedep.");
9366         dirrem->dm_state |= ONDEPLIST;
9367         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9368
9369         /*
9370          * If the COMPLETE flag is clear, then there were no active
9371          * entries and we want to roll back to the previous inode until
9372          * the new inode is committed to disk. If the COMPLETE flag is
9373          * set, then we have deleted an entry that never made it to disk.
9374          * If the entry we deleted resulted from a name change, then the old
9375          * inode reference still resides on disk. Any rollback that we do
9376          * needs to be to that old inode (returned to us in prevdirrem). If
9377          * the entry we deleted resulted from a create, then there is
9378          * no entry on the disk, so we want to roll back to zero rather
9379          * than the uncommitted inode. In either of the COMPLETE cases we
9380          * want to immediately free the unwritten and unreferenced inode.
9381          */
9382         if ((dirrem->dm_state & COMPLETE) == 0) {
9383                 dap->da_previous = dirrem;
9384         } else {
9385                 if (prevdirrem != NULL) {
9386                         dap->da_previous = prevdirrem;
9387                 } else {
9388                         dap->da_state &= ~DIRCHG;
9389                         dap->da_pagedep = pagedep;
9390                 }
9391                 dirrem->dm_dirinum = pagedep->pd_ino;
9392                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9393                         add_to_worklist(&dirrem->dm_list, 0);
9394         }
9395         /*
9396          * Lookup the jaddref for this journal entry.  We must finish
9397          * initializing it and make the diradd write dependent on it.
9398          * If we're not journaling, put it on the id_bufwait list if the
9399          * inode is not yet written. If it is written, do the post-inode
9400          * write processing to put it on the id_pendinghd list.
9401          */
9402         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9403         if (MOUNTEDSUJ(mp)) {
9404                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9405                     inoreflst);
9406                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9407                     ("softdep_setup_directory_change: bad jaddref %p",
9408                     jaddref));
9409                 jaddref->ja_diroff = dp->i_offset;
9410                 jaddref->ja_diradd = dap;
9411                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9412                     dap, da_pdlist);
9413                 add_to_journal(&jaddref->ja_list);
9414         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9415                 dap->da_state |= COMPLETE;
9416                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9417                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9418         } else {
9419                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9420                     dap, da_pdlist);
9421                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9422         }
9423         /*
9424          * If we're making a new name for a directory that has not been
9425          * committed when need to move the dot and dotdot references to
9426          * this new name.
9427          */
9428         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9429                 merge_diradd(inodedep, dap);
9430         FREE_LOCK(ump);
9431 }
9432
9433 /*
9434  * Called whenever the link count on an inode is changed.
9435  * It creates an inode dependency so that the new reference(s)
9436  * to the inode cannot be committed to disk until the updated
9437  * inode has been written.
9438  */
9439 void
9440 softdep_change_linkcnt(ip)
9441         struct inode *ip;       /* the inode with the increased link count */
9442 {
9443         struct inodedep *inodedep;
9444         struct ufsmount *ump;
9445
9446         ump = ITOUMP(ip);
9447         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9448             ("softdep_change_linkcnt called on non-softdep filesystem"));
9449         ACQUIRE_LOCK(ump);
9450         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9451         if (ip->i_nlink < ip->i_effnlink)
9452                 panic("softdep_change_linkcnt: bad delta");
9453         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9454         FREE_LOCK(ump);
9455 }
9456
9457 /*
9458  * Attach a sbdep dependency to the superblock buf so that we can keep
9459  * track of the head of the linked list of referenced but unlinked inodes.
9460  */
9461 void
9462 softdep_setup_sbupdate(ump, fs, bp)
9463         struct ufsmount *ump;
9464         struct fs *fs;
9465         struct buf *bp;
9466 {
9467         struct sbdep *sbdep;
9468         struct worklist *wk;
9469
9470         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9471             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9472         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9473                 if (wk->wk_type == D_SBDEP)
9474                         break;
9475         if (wk != NULL)
9476                 return;
9477         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9478         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9479         sbdep->sb_fs = fs;
9480         sbdep->sb_ump = ump;
9481         ACQUIRE_LOCK(ump);
9482         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9483         FREE_LOCK(ump);
9484 }
9485
9486 /*
9487  * Return the first unlinked inodedep which is ready to be the head of the
9488  * list.  The inodedep and all those after it must have valid next pointers.
9489  */
9490 static struct inodedep *
9491 first_unlinked_inodedep(ump)
9492         struct ufsmount *ump;
9493 {
9494         struct inodedep *inodedep;
9495         struct inodedep *idp;
9496
9497         LOCK_OWNED(ump);
9498         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9499             inodedep; inodedep = idp) {
9500                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9501                         return (NULL);
9502                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9503                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9504                         break;
9505                 if ((inodedep->id_state & UNLINKPREV) == 0)
9506                         break;
9507         }
9508         return (inodedep);
9509 }
9510
9511 /*
9512  * Set the sujfree unlinked head pointer prior to writing a superblock.
9513  */
9514 static void
9515 initiate_write_sbdep(sbdep)
9516         struct sbdep *sbdep;
9517 {
9518         struct inodedep *inodedep;
9519         struct fs *bpfs;
9520         struct fs *fs;
9521
9522         bpfs = sbdep->sb_fs;
9523         fs = sbdep->sb_ump->um_fs;
9524         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9525         if (inodedep) {
9526                 fs->fs_sujfree = inodedep->id_ino;
9527                 inodedep->id_state |= UNLINKPREV;
9528         } else
9529                 fs->fs_sujfree = 0;
9530         bpfs->fs_sujfree = fs->fs_sujfree;
9531 }
9532
9533 /*
9534  * After a superblock is written determine whether it must be written again
9535  * due to a changing unlinked list head.
9536  */
9537 static int
9538 handle_written_sbdep(sbdep, bp)
9539         struct sbdep *sbdep;
9540         struct buf *bp;
9541 {
9542         struct inodedep *inodedep;
9543         struct fs *fs;
9544
9545         LOCK_OWNED(sbdep->sb_ump);
9546         fs = sbdep->sb_fs;
9547         /*
9548          * If the superblock doesn't match the in-memory list start over.
9549          */
9550         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9551         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9552             (inodedep == NULL && fs->fs_sujfree != 0)) {
9553                 bdirty(bp);
9554                 return (1);
9555         }
9556         WORKITEM_FREE(sbdep, D_SBDEP);
9557         if (fs->fs_sujfree == 0)
9558                 return (0);
9559         /*
9560          * Now that we have a record of this inode in stable store allow it
9561          * to be written to free up pending work.  Inodes may see a lot of
9562          * write activity after they are unlinked which we must not hold up.
9563          */
9564         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9565                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9566                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9567                             inodedep, inodedep->id_state);
9568                 if (inodedep->id_state & UNLINKONLIST)
9569                         break;
9570                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9571         }
9572
9573         return (0);
9574 }
9575
9576 /*
9577  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9578  */
9579 static void
9580 unlinked_inodedep(mp, inodedep)
9581         struct mount *mp;
9582         struct inodedep *inodedep;
9583 {
9584         struct ufsmount *ump;
9585
9586         ump = VFSTOUFS(mp);
9587         LOCK_OWNED(ump);
9588         if (MOUNTEDSUJ(mp) == 0)
9589                 return;
9590         ump->um_fs->fs_fmod = 1;
9591         if (inodedep->id_state & UNLINKED)
9592                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9593         inodedep->id_state |= UNLINKED;
9594         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9595 }
9596
9597 /*
9598  * Remove an inodedep from the unlinked inodedep list.  This may require
9599  * disk writes if the inode has made it that far.
9600  */
9601 static void
9602 clear_unlinked_inodedep(inodedep)
9603         struct inodedep *inodedep;
9604 {
9605         struct ufsmount *ump;
9606         struct inodedep *idp;
9607         struct inodedep *idn;
9608         struct fs *fs;
9609         struct buf *bp;
9610         ino_t ino;
9611         ino_t nino;
9612         ino_t pino;
9613         int error;
9614
9615         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9616         fs = ump->um_fs;
9617         ino = inodedep->id_ino;
9618         error = 0;
9619         for (;;) {
9620                 LOCK_OWNED(ump);
9621                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9622                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9623                     inodedep));
9624                 /*
9625                  * If nothing has yet been written simply remove us from
9626                  * the in memory list and return.  This is the most common
9627                  * case where handle_workitem_remove() loses the final
9628                  * reference.
9629                  */
9630                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9631                         break;
9632                 /*
9633                  * If we have a NEXT pointer and no PREV pointer we can simply
9634                  * clear NEXT's PREV and remove ourselves from the list.  Be
9635                  * careful not to clear PREV if the superblock points at
9636                  * next as well.
9637                  */
9638                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9639                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9640                         if (idn && fs->fs_sujfree != idn->id_ino)
9641                                 idn->id_state &= ~UNLINKPREV;
9642                         break;
9643                 }
9644                 /*
9645                  * Here we have an inodedep which is actually linked into
9646                  * the list.  We must remove it by forcing a write to the
9647                  * link before us, whether it be the superblock or an inode.
9648                  * Unfortunately the list may change while we're waiting
9649                  * on the buf lock for either resource so we must loop until
9650                  * we lock the right one.  If both the superblock and an
9651                  * inode point to this inode we must clear the inode first
9652                  * followed by the superblock.
9653                  */
9654                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9655                 pino = 0;
9656                 if (idp && (idp->id_state & UNLINKNEXT))
9657                         pino = idp->id_ino;
9658                 FREE_LOCK(ump);
9659                 if (pino == 0) {
9660                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9661                             (int)fs->fs_sbsize, 0, 0, 0);
9662                 } else {
9663                         error = bread(ump->um_devvp,
9664                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9665                             (int)fs->fs_bsize, NOCRED, &bp);
9666                         if (error)
9667                                 brelse(bp);
9668                 }
9669                 ACQUIRE_LOCK(ump);
9670                 if (error)
9671                         break;
9672                 /* If the list has changed restart the loop. */
9673                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9674                 nino = 0;
9675                 if (idp && (idp->id_state & UNLINKNEXT))
9676                         nino = idp->id_ino;
9677                 if (nino != pino ||
9678                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9679                         FREE_LOCK(ump);
9680                         brelse(bp);
9681                         ACQUIRE_LOCK(ump);
9682                         continue;
9683                 }
9684                 nino = 0;
9685                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9686                 if (idn)
9687                         nino = idn->id_ino;
9688                 /*
9689                  * Remove us from the in memory list.  After this we cannot
9690                  * access the inodedep.
9691                  */
9692                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9693                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9694                     inodedep));
9695                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9696                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9697                 FREE_LOCK(ump);
9698                 /*
9699                  * The predecessor's next pointer is manually updated here
9700                  * so that the NEXT flag is never cleared for an element
9701                  * that is in the list.
9702                  */
9703                 if (pino == 0) {
9704                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9705                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9706                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9707                             bp);
9708                 } else if (fs->fs_magic == FS_UFS1_MAGIC)
9709                         ((struct ufs1_dinode *)bp->b_data +
9710                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9711                 else
9712                         ((struct ufs2_dinode *)bp->b_data +
9713                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9714                 /*
9715                  * If the bwrite fails we have no recourse to recover.  The
9716                  * filesystem is corrupted already.
9717                  */
9718                 bwrite(bp);
9719                 ACQUIRE_LOCK(ump);
9720                 /*
9721                  * If the superblock pointer still needs to be cleared force
9722                  * a write here.
9723                  */
9724                 if (fs->fs_sujfree == ino) {
9725                         FREE_LOCK(ump);
9726                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9727                             (int)fs->fs_sbsize, 0, 0, 0);
9728                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9729                         ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9730                         softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9731                             bp);
9732                         bwrite(bp);
9733                         ACQUIRE_LOCK(ump);
9734                 }
9735
9736                 if (fs->fs_sujfree != ino)
9737                         return;
9738                 panic("clear_unlinked_inodedep: Failed to clear free head");
9739         }
9740         if (inodedep->id_ino == fs->fs_sujfree)
9741                 panic("clear_unlinked_inodedep: Freeing head of free list");
9742         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9743         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9744         return;
9745 }
9746
9747 /*
9748  * This workitem decrements the inode's link count.
9749  * If the link count reaches zero, the file is removed.
9750  */
9751 static int
9752 handle_workitem_remove(dirrem, flags)
9753         struct dirrem *dirrem;
9754         int flags;
9755 {
9756         struct inodedep *inodedep;
9757         struct workhead dotdotwk;
9758         struct worklist *wk;
9759         struct ufsmount *ump;
9760         struct mount *mp;
9761         struct vnode *vp;
9762         struct inode *ip;
9763         ino_t oldinum;
9764
9765         if (dirrem->dm_state & ONWORKLIST)
9766                 panic("handle_workitem_remove: dirrem %p still on worklist",
9767                     dirrem);
9768         oldinum = dirrem->dm_oldinum;
9769         mp = dirrem->dm_list.wk_mp;
9770         ump = VFSTOUFS(mp);
9771         flags |= LK_EXCLUSIVE;
9772         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9773                 return (EBUSY);
9774         ip = VTOI(vp);
9775         ACQUIRE_LOCK(ump);
9776         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9777                 panic("handle_workitem_remove: lost inodedep");
9778         if (dirrem->dm_state & ONDEPLIST)
9779                 LIST_REMOVE(dirrem, dm_inonext);
9780         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9781             ("handle_workitem_remove:  Journal entries not written."));
9782
9783         /*
9784          * Move all dependencies waiting on the remove to complete
9785          * from the dirrem to the inode inowait list to be completed
9786          * after the inode has been updated and written to disk.  Any
9787          * marked MKDIR_PARENT are saved to be completed when the .. ref
9788          * is removed.
9789          */
9790         LIST_INIT(&dotdotwk);
9791         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9792                 WORKLIST_REMOVE(wk);
9793                 if (wk->wk_state & MKDIR_PARENT) {
9794                         wk->wk_state &= ~MKDIR_PARENT;
9795                         WORKLIST_INSERT(&dotdotwk, wk);
9796                         continue;
9797                 }
9798                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9799         }
9800         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9801         /*
9802          * Normal file deletion.
9803          */
9804         if ((dirrem->dm_state & RMDIR) == 0) {
9805                 ip->i_nlink--;
9806                 DIP_SET(ip, i_nlink, ip->i_nlink);
9807                 ip->i_flag |= IN_CHANGE;
9808                 if (ip->i_nlink < ip->i_effnlink)
9809                         panic("handle_workitem_remove: bad file delta");
9810                 if (ip->i_nlink == 0) 
9811                         unlinked_inodedep(mp, inodedep);
9812                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9813                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9814                     ("handle_workitem_remove: worklist not empty. %s",
9815                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9816                 WORKITEM_FREE(dirrem, D_DIRREM);
9817                 FREE_LOCK(ump);
9818                 goto out;
9819         }
9820         /*
9821          * Directory deletion. Decrement reference count for both the
9822          * just deleted parent directory entry and the reference for ".".
9823          * Arrange to have the reference count on the parent decremented
9824          * to account for the loss of "..".
9825          */
9826         ip->i_nlink -= 2;
9827         DIP_SET(ip, i_nlink, ip->i_nlink);
9828         ip->i_flag |= IN_CHANGE;
9829         if (ip->i_nlink < ip->i_effnlink)
9830                 panic("handle_workitem_remove: bad dir delta");
9831         if (ip->i_nlink == 0)
9832                 unlinked_inodedep(mp, inodedep);
9833         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9834         /*
9835          * Rename a directory to a new parent. Since, we are both deleting
9836          * and creating a new directory entry, the link count on the new
9837          * directory should not change. Thus we skip the followup dirrem.
9838          */
9839         if (dirrem->dm_state & DIRCHG) {
9840                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9841                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9842                 WORKITEM_FREE(dirrem, D_DIRREM);
9843                 FREE_LOCK(ump);
9844                 goto out;
9845         }
9846         dirrem->dm_state = ONDEPLIST;
9847         dirrem->dm_oldinum = dirrem->dm_dirinum;
9848         /*
9849          * Place the dirrem on the parent's diremhd list.
9850          */
9851         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9852                 panic("handle_workitem_remove: lost dir inodedep");
9853         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9854         /*
9855          * If the allocated inode has never been written to disk, then
9856          * the on-disk inode is zero'ed and we can remove the file
9857          * immediately.  When journaling if the inode has been marked
9858          * unlinked and not DEPCOMPLETE we know it can never be written.
9859          */
9860         inodedep_lookup(mp, oldinum, 0, &inodedep);
9861         if (inodedep == NULL ||
9862             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9863             check_inode_unwritten(inodedep)) {
9864                 FREE_LOCK(ump);
9865                 vput(vp);
9866                 return handle_workitem_remove(dirrem, flags);
9867         }
9868         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9869         FREE_LOCK(ump);
9870         ip->i_flag |= IN_CHANGE;
9871 out:
9872         ffs_update(vp, 0);
9873         vput(vp);
9874         return (0);
9875 }
9876
9877 /*
9878  * Inode de-allocation dependencies.
9879  * 
9880  * When an inode's link count is reduced to zero, it can be de-allocated. We
9881  * found it convenient to postpone de-allocation until after the inode is
9882  * written to disk with its new link count (zero).  At this point, all of the
9883  * on-disk inode's block pointers are nullified and, with careful dependency
9884  * list ordering, all dependencies related to the inode will be satisfied and
9885  * the corresponding dependency structures de-allocated.  So, if/when the
9886  * inode is reused, there will be no mixing of old dependencies with new
9887  * ones.  This artificial dependency is set up by the block de-allocation
9888  * procedure above (softdep_setup_freeblocks) and completed by the
9889  * following procedure.
9890  */
9891 static void 
9892 handle_workitem_freefile(freefile)
9893         struct freefile *freefile;
9894 {
9895         struct workhead wkhd;
9896         struct fs *fs;
9897         struct inodedep *idp;
9898         struct ufsmount *ump;
9899         int error;
9900
9901         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9902         fs = ump->um_fs;
9903 #ifdef DEBUG
9904         ACQUIRE_LOCK(ump);
9905         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9906         FREE_LOCK(ump);
9907         if (error)
9908                 panic("handle_workitem_freefile: inodedep %p survived", idp);
9909 #endif
9910         UFS_LOCK(ump);
9911         fs->fs_pendinginodes -= 1;
9912         UFS_UNLOCK(ump);
9913         LIST_INIT(&wkhd);
9914         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9915         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9916             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9917                 softdep_error("handle_workitem_freefile", error);
9918         ACQUIRE_LOCK(ump);
9919         WORKITEM_FREE(freefile, D_FREEFILE);
9920         FREE_LOCK(ump);
9921 }
9922
9923
9924 /*
9925  * Helper function which unlinks marker element from work list and returns
9926  * the next element on the list.
9927  */
9928 static __inline struct worklist *
9929 markernext(struct worklist *marker)
9930 {
9931         struct worklist *next;
9932         
9933         next = LIST_NEXT(marker, wk_list);
9934         LIST_REMOVE(marker, wk_list);
9935         return next;
9936 }
9937
9938 /*
9939  * Disk writes.
9940  * 
9941  * The dependency structures constructed above are most actively used when file
9942  * system blocks are written to disk.  No constraints are placed on when a
9943  * block can be written, but unsatisfied update dependencies are made safe by
9944  * modifying (or replacing) the source memory for the duration of the disk
9945  * write.  When the disk write completes, the memory block is again brought
9946  * up-to-date.
9947  *
9948  * In-core inode structure reclamation.
9949  * 
9950  * Because there are a finite number of "in-core" inode structures, they are
9951  * reused regularly.  By transferring all inode-related dependencies to the
9952  * in-memory inode block and indexing them separately (via "inodedep"s), we
9953  * can allow "in-core" inode structures to be reused at any time and avoid
9954  * any increase in contention.
9955  *
9956  * Called just before entering the device driver to initiate a new disk I/O.
9957  * The buffer must be locked, thus, no I/O completion operations can occur
9958  * while we are manipulating its associated dependencies.
9959  */
9960 static void 
9961 softdep_disk_io_initiation(bp)
9962         struct buf *bp;         /* structure describing disk write to occur */
9963 {
9964         struct worklist *wk;
9965         struct worklist marker;
9966         struct inodedep *inodedep;
9967         struct freeblks *freeblks;
9968         struct jblkdep *jblkdep;
9969         struct newblk *newblk;
9970         struct ufsmount *ump;
9971
9972         /*
9973          * We only care about write operations. There should never
9974          * be dependencies for reads.
9975          */
9976         if (bp->b_iocmd != BIO_WRITE)
9977                 panic("softdep_disk_io_initiation: not write");
9978
9979         if (bp->b_vflags & BV_BKGRDINPROG)
9980                 panic("softdep_disk_io_initiation: Writing buffer with "
9981                     "background write in progress: %p", bp);
9982
9983         ump = softdep_bp_to_mp(bp);
9984         if (ump == NULL)
9985                 return;
9986
9987         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
9988         PHOLD(curproc);                 /* Don't swap out kernel stack */
9989         ACQUIRE_LOCK(ump);
9990         /*
9991          * Do any necessary pre-I/O processing.
9992          */
9993         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9994              wk = markernext(&marker)) {
9995                 LIST_INSERT_AFTER(wk, &marker, wk_list);
9996                 switch (wk->wk_type) {
9997
9998                 case D_PAGEDEP:
9999                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10000                         continue;
10001
10002                 case D_INODEDEP:
10003                         inodedep = WK_INODEDEP(wk);
10004                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10005                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10006                         else
10007                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10008                         continue;
10009
10010                 case D_INDIRDEP:
10011                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10012                         continue;
10013
10014                 case D_BMSAFEMAP:
10015                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10016                         continue;
10017
10018                 case D_JSEG:
10019                         WK_JSEG(wk)->js_buf = NULL;
10020                         continue;
10021
10022                 case D_FREEBLKS:
10023                         freeblks = WK_FREEBLKS(wk);
10024                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10025                         /*
10026                          * We have to wait for the freeblks to be journaled
10027                          * before we can write an inodeblock with updated
10028                          * pointers.  Be careful to arrange the marker so
10029                          * we revisit the freeblks if it's not removed by
10030                          * the first jwait().
10031                          */
10032                         if (jblkdep != NULL) {
10033                                 LIST_REMOVE(&marker, wk_list);
10034                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10035                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10036                         }
10037                         continue;
10038                 case D_ALLOCDIRECT:
10039                 case D_ALLOCINDIR:
10040                         /*
10041                          * We have to wait for the jnewblk to be journaled
10042                          * before we can write to a block if the contents
10043                          * may be confused with an earlier file's indirect
10044                          * at recovery time.  Handle the marker as described
10045                          * above.
10046                          */
10047                         newblk = WK_NEWBLK(wk);
10048                         if (newblk->nb_jnewblk != NULL &&
10049                             indirblk_lookup(newblk->nb_list.wk_mp,
10050                             newblk->nb_newblkno)) {
10051                                 LIST_REMOVE(&marker, wk_list);
10052                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10053                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10054                         }
10055                         continue;
10056
10057                 case D_SBDEP:
10058                         initiate_write_sbdep(WK_SBDEP(wk));
10059                         continue;
10060
10061                 case D_MKDIR:
10062                 case D_FREEWORK:
10063                 case D_FREEDEP:
10064                 case D_JSEGDEP:
10065                         continue;
10066
10067                 default:
10068                         panic("handle_disk_io_initiation: Unexpected type %s",
10069                             TYPENAME(wk->wk_type));
10070                         /* NOTREACHED */
10071                 }
10072         }
10073         FREE_LOCK(ump);
10074         PRELE(curproc);                 /* Allow swapout of kernel stack */
10075 }
10076
10077 /*
10078  * Called from within the procedure above to deal with unsatisfied
10079  * allocation dependencies in a directory. The buffer must be locked,
10080  * thus, no I/O completion operations can occur while we are
10081  * manipulating its associated dependencies.
10082  */
10083 static void
10084 initiate_write_filepage(pagedep, bp)
10085         struct pagedep *pagedep;
10086         struct buf *bp;
10087 {
10088         struct jremref *jremref;
10089         struct jmvref *jmvref;
10090         struct dirrem *dirrem;
10091         struct diradd *dap;
10092         struct direct *ep;
10093         int i;
10094
10095         if (pagedep->pd_state & IOSTARTED) {
10096                 /*
10097                  * This can only happen if there is a driver that does not
10098                  * understand chaining. Here biodone will reissue the call
10099                  * to strategy for the incomplete buffers.
10100                  */
10101                 printf("initiate_write_filepage: already started\n");
10102                 return;
10103         }
10104         pagedep->pd_state |= IOSTARTED;
10105         /*
10106          * Wait for all journal remove dependencies to hit the disk.
10107          * We can not allow any potentially conflicting directory adds
10108          * to be visible before removes and rollback is too difficult.
10109          * The per-filesystem lock may be dropped and re-acquired, however 
10110          * we hold the buf locked so the dependency can not go away.
10111          */
10112         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10113                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10114                         jwait(&jremref->jr_list, MNT_WAIT);
10115         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10116                 jwait(&jmvref->jm_list, MNT_WAIT);
10117         for (i = 0; i < DAHASHSZ; i++) {
10118                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10119                         ep = (struct direct *)
10120                             ((char *)bp->b_data + dap->da_offset);
10121                         if (ep->d_ino != dap->da_newinum)
10122                                 panic("%s: dir inum %ju != new %ju",
10123                                     "initiate_write_filepage",
10124                                     (uintmax_t)ep->d_ino,
10125                                     (uintmax_t)dap->da_newinum);
10126                         if (dap->da_state & DIRCHG)
10127                                 ep->d_ino = dap->da_previous->dm_oldinum;
10128                         else
10129                                 ep->d_ino = 0;
10130                         dap->da_state &= ~ATTACHED;
10131                         dap->da_state |= UNDONE;
10132                 }
10133         }
10134 }
10135
10136 /*
10137  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10138  * Note that any bug fixes made to this routine must be done in the
10139  * version found below.
10140  *
10141  * Called from within the procedure above to deal with unsatisfied
10142  * allocation dependencies in an inodeblock. The buffer must be
10143  * locked, thus, no I/O completion operations can occur while we
10144  * are manipulating its associated dependencies.
10145  */
10146 static void 
10147 initiate_write_inodeblock_ufs1(inodedep, bp)
10148         struct inodedep *inodedep;
10149         struct buf *bp;                 /* The inode block */
10150 {
10151         struct allocdirect *adp, *lastadp;
10152         struct ufs1_dinode *dp;
10153         struct ufs1_dinode *sip;
10154         struct inoref *inoref;
10155         struct ufsmount *ump;
10156         struct fs *fs;
10157         ufs_lbn_t i;
10158 #ifdef INVARIANTS
10159         ufs_lbn_t prevlbn = 0;
10160 #endif
10161         int deplist;
10162
10163         if (inodedep->id_state & IOSTARTED)
10164                 panic("initiate_write_inodeblock_ufs1: already started");
10165         inodedep->id_state |= IOSTARTED;
10166         fs = inodedep->id_fs;
10167         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10168         LOCK_OWNED(ump);
10169         dp = (struct ufs1_dinode *)bp->b_data +
10170             ino_to_fsbo(fs, inodedep->id_ino);
10171
10172         /*
10173          * If we're on the unlinked list but have not yet written our
10174          * next pointer initialize it here.
10175          */
10176         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10177                 struct inodedep *inon;
10178
10179                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10180                 dp->di_freelink = inon ? inon->id_ino : 0;
10181         }
10182         /*
10183          * If the bitmap is not yet written, then the allocated
10184          * inode cannot be written to disk.
10185          */
10186         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10187                 if (inodedep->id_savedino1 != NULL)
10188                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10189                 FREE_LOCK(ump);
10190                 sip = malloc(sizeof(struct ufs1_dinode),
10191                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10192                 ACQUIRE_LOCK(ump);
10193                 inodedep->id_savedino1 = sip;
10194                 *inodedep->id_savedino1 = *dp;
10195                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10196                 dp->di_gen = inodedep->id_savedino1->di_gen;
10197                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10198                 return;
10199         }
10200         /*
10201          * If no dependencies, then there is nothing to roll back.
10202          */
10203         inodedep->id_savedsize = dp->di_size;
10204         inodedep->id_savedextsize = 0;
10205         inodedep->id_savednlink = dp->di_nlink;
10206         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10207             TAILQ_EMPTY(&inodedep->id_inoreflst))
10208                 return;
10209         /*
10210          * Revert the link count to that of the first unwritten journal entry.
10211          */
10212         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10213         if (inoref)
10214                 dp->di_nlink = inoref->if_nlink;
10215         /*
10216          * Set the dependencies to busy.
10217          */
10218         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10219              adp = TAILQ_NEXT(adp, ad_next)) {
10220 #ifdef INVARIANTS
10221                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10222                         panic("softdep_write_inodeblock: lbn order");
10223                 prevlbn = adp->ad_offset;
10224                 if (adp->ad_offset < UFS_NDADDR &&
10225                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10226                         panic("%s: direct pointer #%jd mismatch %d != %jd",
10227                             "softdep_write_inodeblock",
10228                             (intmax_t)adp->ad_offset,
10229                             dp->di_db[adp->ad_offset],
10230                             (intmax_t)adp->ad_newblkno);
10231                 if (adp->ad_offset >= UFS_NDADDR &&
10232                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10233                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
10234                             "softdep_write_inodeblock",
10235                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10236                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10237                             (intmax_t)adp->ad_newblkno);
10238                 deplist |= 1 << adp->ad_offset;
10239                 if ((adp->ad_state & ATTACHED) == 0)
10240                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10241                             adp->ad_state);
10242 #endif /* INVARIANTS */
10243                 adp->ad_state &= ~ATTACHED;
10244                 adp->ad_state |= UNDONE;
10245         }
10246         /*
10247          * The on-disk inode cannot claim to be any larger than the last
10248          * fragment that has been written. Otherwise, the on-disk inode
10249          * might have fragments that were not the last block in the file
10250          * which would corrupt the filesystem.
10251          */
10252         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10253              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10254                 if (adp->ad_offset >= UFS_NDADDR)
10255                         break;
10256                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10257                 /* keep going until hitting a rollback to a frag */
10258                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10259                         continue;
10260                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10261                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10262 #ifdef INVARIANTS
10263                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10264                                 panic("softdep_write_inodeblock: lost dep1");
10265 #endif /* INVARIANTS */
10266                         dp->di_db[i] = 0;
10267                 }
10268                 for (i = 0; i < UFS_NIADDR; i++) {
10269 #ifdef INVARIANTS
10270                         if (dp->di_ib[i] != 0 &&
10271                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10272                                 panic("softdep_write_inodeblock: lost dep2");
10273 #endif /* INVARIANTS */
10274                         dp->di_ib[i] = 0;
10275                 }
10276                 return;
10277         }
10278         /*
10279          * If we have zero'ed out the last allocated block of the file,
10280          * roll back the size to the last currently allocated block.
10281          * We know that this last allocated block is a full-sized as
10282          * we already checked for fragments in the loop above.
10283          */
10284         if (lastadp != NULL &&
10285             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10286                 for (i = lastadp->ad_offset; i >= 0; i--)
10287                         if (dp->di_db[i] != 0)
10288                                 break;
10289                 dp->di_size = (i + 1) * fs->fs_bsize;
10290         }
10291         /*
10292          * The only dependencies are for indirect blocks.
10293          *
10294          * The file size for indirect block additions is not guaranteed.
10295          * Such a guarantee would be non-trivial to achieve. The conventional
10296          * synchronous write implementation also does not make this guarantee.
10297          * Fsck should catch and fix discrepancies. Arguably, the file size
10298          * can be over-estimated without destroying integrity when the file
10299          * moves into the indirect blocks (i.e., is large). If we want to
10300          * postpone fsck, we are stuck with this argument.
10301          */
10302         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10303                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10304 }
10305                 
10306 /*
10307  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10308  * Note that any bug fixes made to this routine must be done in the
10309  * version found above.
10310  *
10311  * Called from within the procedure above to deal with unsatisfied
10312  * allocation dependencies in an inodeblock. The buffer must be
10313  * locked, thus, no I/O completion operations can occur while we
10314  * are manipulating its associated dependencies.
10315  */
10316 static void 
10317 initiate_write_inodeblock_ufs2(inodedep, bp)
10318         struct inodedep *inodedep;
10319         struct buf *bp;                 /* The inode block */
10320 {
10321         struct allocdirect *adp, *lastadp;
10322         struct ufs2_dinode *dp;
10323         struct ufs2_dinode *sip;
10324         struct inoref *inoref;
10325         struct ufsmount *ump;
10326         struct fs *fs;
10327         ufs_lbn_t i;
10328 #ifdef INVARIANTS
10329         ufs_lbn_t prevlbn = 0;
10330 #endif
10331         int deplist;
10332
10333         if (inodedep->id_state & IOSTARTED)
10334                 panic("initiate_write_inodeblock_ufs2: already started");
10335         inodedep->id_state |= IOSTARTED;
10336         fs = inodedep->id_fs;
10337         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10338         LOCK_OWNED(ump);
10339         dp = (struct ufs2_dinode *)bp->b_data +
10340             ino_to_fsbo(fs, inodedep->id_ino);
10341
10342         /*
10343          * If we're on the unlinked list but have not yet written our
10344          * next pointer initialize it here.
10345          */
10346         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10347                 struct inodedep *inon;
10348
10349                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10350                 dp->di_freelink = inon ? inon->id_ino : 0;
10351         }
10352         /*
10353          * If the bitmap is not yet written, then the allocated
10354          * inode cannot be written to disk.
10355          */
10356         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10357                 if (inodedep->id_savedino2 != NULL)
10358                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10359                 FREE_LOCK(ump);
10360                 sip = malloc(sizeof(struct ufs2_dinode),
10361                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10362                 ACQUIRE_LOCK(ump);
10363                 inodedep->id_savedino2 = sip;
10364                 *inodedep->id_savedino2 = *dp;
10365                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10366                 dp->di_gen = inodedep->id_savedino2->di_gen;
10367                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10368                 return;
10369         }
10370         /*
10371          * If no dependencies, then there is nothing to roll back.
10372          */
10373         inodedep->id_savedsize = dp->di_size;
10374         inodedep->id_savedextsize = dp->di_extsize;
10375         inodedep->id_savednlink = dp->di_nlink;
10376         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10377             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10378             TAILQ_EMPTY(&inodedep->id_inoreflst))
10379                 return;
10380         /*
10381          * Revert the link count to that of the first unwritten journal entry.
10382          */
10383         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10384         if (inoref)
10385                 dp->di_nlink = inoref->if_nlink;
10386
10387         /*
10388          * Set the ext data dependencies to busy.
10389          */
10390         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10391              adp = TAILQ_NEXT(adp, ad_next)) {
10392 #ifdef INVARIANTS
10393                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10394                         panic("softdep_write_inodeblock: lbn order");
10395                 prevlbn = adp->ad_offset;
10396                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10397                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10398                             "softdep_write_inodeblock",
10399                             (intmax_t)adp->ad_offset,
10400                             (intmax_t)dp->di_extb[adp->ad_offset],
10401                             (intmax_t)adp->ad_newblkno);
10402                 deplist |= 1 << adp->ad_offset;
10403                 if ((adp->ad_state & ATTACHED) == 0)
10404                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10405                             adp->ad_state);
10406 #endif /* INVARIANTS */
10407                 adp->ad_state &= ~ATTACHED;
10408                 adp->ad_state |= UNDONE;
10409         }
10410         /*
10411          * The on-disk inode cannot claim to be any larger than the last
10412          * fragment that has been written. Otherwise, the on-disk inode
10413          * might have fragments that were not the last block in the ext
10414          * data which would corrupt the filesystem.
10415          */
10416         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10417              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10418                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10419                 /* keep going until hitting a rollback to a frag */
10420                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10421                         continue;
10422                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10423                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10424 #ifdef INVARIANTS
10425                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10426                                 panic("softdep_write_inodeblock: lost dep1");
10427 #endif /* INVARIANTS */
10428                         dp->di_extb[i] = 0;
10429                 }
10430                 lastadp = NULL;
10431                 break;
10432         }
10433         /*
10434          * If we have zero'ed out the last allocated block of the ext
10435          * data, roll back the size to the last currently allocated block.
10436          * We know that this last allocated block is a full-sized as
10437          * we already checked for fragments in the loop above.
10438          */
10439         if (lastadp != NULL &&
10440             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10441                 for (i = lastadp->ad_offset; i >= 0; i--)
10442                         if (dp->di_extb[i] != 0)
10443                                 break;
10444                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10445         }
10446         /*
10447          * Set the file data dependencies to busy.
10448          */
10449         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10450              adp = TAILQ_NEXT(adp, ad_next)) {
10451 #ifdef INVARIANTS
10452                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10453                         panic("softdep_write_inodeblock: lbn order");
10454                 if ((adp->ad_state & ATTACHED) == 0)
10455                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10456                 prevlbn = adp->ad_offset;
10457                 if (adp->ad_offset < UFS_NDADDR &&
10458                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10459                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
10460                             "softdep_write_inodeblock",
10461                             (intmax_t)adp->ad_offset,
10462                             (intmax_t)dp->di_db[adp->ad_offset],
10463                             (intmax_t)adp->ad_newblkno);
10464                 if (adp->ad_offset >= UFS_NDADDR &&
10465                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10466                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
10467                             "softdep_write_inodeblock:",
10468                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10469                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10470                             (intmax_t)adp->ad_newblkno);
10471                 deplist |= 1 << adp->ad_offset;
10472                 if ((adp->ad_state & ATTACHED) == 0)
10473                         panic("softdep_write_inodeblock: Unknown state 0x%x",
10474                             adp->ad_state);
10475 #endif /* INVARIANTS */
10476                 adp->ad_state &= ~ATTACHED;
10477                 adp->ad_state |= UNDONE;
10478         }
10479         /*
10480          * The on-disk inode cannot claim to be any larger than the last
10481          * fragment that has been written. Otherwise, the on-disk inode
10482          * might have fragments that were not the last block in the file
10483          * which would corrupt the filesystem.
10484          */
10485         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10486              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10487                 if (adp->ad_offset >= UFS_NDADDR)
10488                         break;
10489                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10490                 /* keep going until hitting a rollback to a frag */
10491                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10492                         continue;
10493                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10494                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10495 #ifdef INVARIANTS
10496                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10497                                 panic("softdep_write_inodeblock: lost dep2");
10498 #endif /* INVARIANTS */
10499                         dp->di_db[i] = 0;
10500                 }
10501                 for (i = 0; i < UFS_NIADDR; i++) {
10502 #ifdef INVARIANTS
10503                         if (dp->di_ib[i] != 0 &&
10504                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10505                                 panic("softdep_write_inodeblock: lost dep3");
10506 #endif /* INVARIANTS */
10507                         dp->di_ib[i] = 0;
10508                 }
10509                 return;
10510         }
10511         /*
10512          * If we have zero'ed out the last allocated block of the file,
10513          * roll back the size to the last currently allocated block.
10514          * We know that this last allocated block is a full-sized as
10515          * we already checked for fragments in the loop above.
10516          */
10517         if (lastadp != NULL &&
10518             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10519                 for (i = lastadp->ad_offset; i >= 0; i--)
10520                         if (dp->di_db[i] != 0)
10521                                 break;
10522                 dp->di_size = (i + 1) * fs->fs_bsize;
10523         }
10524         /*
10525          * The only dependencies are for indirect blocks.
10526          *
10527          * The file size for indirect block additions is not guaranteed.
10528          * Such a guarantee would be non-trivial to achieve. The conventional
10529          * synchronous write implementation also does not make this guarantee.
10530          * Fsck should catch and fix discrepancies. Arguably, the file size
10531          * can be over-estimated without destroying integrity when the file
10532          * moves into the indirect blocks (i.e., is large). If we want to
10533          * postpone fsck, we are stuck with this argument.
10534          */
10535         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10536                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10537 }
10538
10539 /*
10540  * Cancel an indirdep as a result of truncation.  Release all of the
10541  * children allocindirs and place their journal work on the appropriate
10542  * list.
10543  */
10544 static void
10545 cancel_indirdep(indirdep, bp, freeblks)
10546         struct indirdep *indirdep;
10547         struct buf *bp;
10548         struct freeblks *freeblks;
10549 {
10550         struct allocindir *aip;
10551
10552         /*
10553          * None of the indirect pointers will ever be visible,
10554          * so they can simply be tossed. GOINGAWAY ensures
10555          * that allocated pointers will be saved in the buffer
10556          * cache until they are freed. Note that they will
10557          * only be able to be found by their physical address
10558          * since the inode mapping the logical address will
10559          * be gone. The save buffer used for the safe copy
10560          * was allocated in setup_allocindir_phase2 using
10561          * the physical address so it could be used for this
10562          * purpose. Hence we swap the safe copy with the real
10563          * copy, allowing the safe copy to be freed and holding
10564          * on to the real copy for later use in indir_trunc.
10565          */
10566         if (indirdep->ir_state & GOINGAWAY)
10567                 panic("cancel_indirdep: already gone");
10568         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10569                 indirdep->ir_state |= DEPCOMPLETE;
10570                 LIST_REMOVE(indirdep, ir_next);
10571         }
10572         indirdep->ir_state |= GOINGAWAY;
10573         /*
10574          * Pass in bp for blocks still have journal writes
10575          * pending so we can cancel them on their own.
10576          */
10577         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10578                 cancel_allocindir(aip, bp, freeblks, 0);
10579         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10580                 cancel_allocindir(aip, NULL, freeblks, 0);
10581         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10582                 cancel_allocindir(aip, NULL, freeblks, 0);
10583         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10584                 cancel_allocindir(aip, NULL, freeblks, 0);
10585         /*
10586          * If there are pending partial truncations we need to keep the
10587          * old block copy around until they complete.  This is because
10588          * the current b_data is not a perfect superset of the available
10589          * blocks.
10590          */
10591         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10592                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10593         else
10594                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10595         WORKLIST_REMOVE(&indirdep->ir_list);
10596         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10597         indirdep->ir_bp = NULL;
10598         indirdep->ir_freeblks = freeblks;
10599 }
10600
10601 /*
10602  * Free an indirdep once it no longer has new pointers to track.
10603  */
10604 static void
10605 free_indirdep(indirdep)
10606         struct indirdep *indirdep;
10607 {
10608
10609         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10610             ("free_indirdep: Indir trunc list not empty."));
10611         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10612             ("free_indirdep: Complete head not empty."));
10613         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10614             ("free_indirdep: write head not empty."));
10615         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10616             ("free_indirdep: done head not empty."));
10617         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10618             ("free_indirdep: deplist head not empty."));
10619         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10620             ("free_indirdep: %p still on newblk list.", indirdep));
10621         KASSERT(indirdep->ir_saveddata == NULL,
10622             ("free_indirdep: %p still has saved data.", indirdep));
10623         if (indirdep->ir_state & ONWORKLIST)
10624                 WORKLIST_REMOVE(&indirdep->ir_list);
10625         WORKITEM_FREE(indirdep, D_INDIRDEP);
10626 }
10627
10628 /*
10629  * Called before a write to an indirdep.  This routine is responsible for
10630  * rolling back pointers to a safe state which includes only those
10631  * allocindirs which have been completed.
10632  */
10633 static void
10634 initiate_write_indirdep(indirdep, bp)
10635         struct indirdep *indirdep;
10636         struct buf *bp;
10637 {
10638         struct ufsmount *ump;
10639
10640         indirdep->ir_state |= IOSTARTED;
10641         if (indirdep->ir_state & GOINGAWAY)
10642                 panic("disk_io_initiation: indirdep gone");
10643         /*
10644          * If there are no remaining dependencies, this will be writing
10645          * the real pointers.
10646          */
10647         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10648             TAILQ_EMPTY(&indirdep->ir_trunc))
10649                 return;
10650         /*
10651          * Replace up-to-date version with safe version.
10652          */
10653         if (indirdep->ir_saveddata == NULL) {
10654                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10655                 LOCK_OWNED(ump);
10656                 FREE_LOCK(ump);
10657                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10658                     M_SOFTDEP_FLAGS);
10659                 ACQUIRE_LOCK(ump);
10660         }
10661         indirdep->ir_state &= ~ATTACHED;
10662         indirdep->ir_state |= UNDONE;
10663         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10664         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10665             bp->b_bcount);
10666 }
10667
10668 /*
10669  * Called when an inode has been cleared in a cg bitmap.  This finally
10670  * eliminates any canceled jaddrefs
10671  */
10672 void
10673 softdep_setup_inofree(mp, bp, ino, wkhd)
10674         struct mount *mp;
10675         struct buf *bp;
10676         ino_t ino;
10677         struct workhead *wkhd;
10678 {
10679         struct worklist *wk, *wkn;
10680         struct inodedep *inodedep;
10681         struct ufsmount *ump;
10682         uint8_t *inosused;
10683         struct cg *cgp;
10684         struct fs *fs;
10685
10686         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10687             ("softdep_setup_inofree called on non-softdep filesystem"));
10688         ump = VFSTOUFS(mp);
10689         ACQUIRE_LOCK(ump);
10690         fs = ump->um_fs;
10691         cgp = (struct cg *)bp->b_data;
10692         inosused = cg_inosused(cgp);
10693         if (isset(inosused, ino % fs->fs_ipg))
10694                 panic("softdep_setup_inofree: inode %ju not freed.",
10695                     (uintmax_t)ino);
10696         if (inodedep_lookup(mp, ino, 0, &inodedep))
10697                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10698                     (uintmax_t)ino, inodedep);
10699         if (wkhd) {
10700                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10701                         if (wk->wk_type != D_JADDREF)
10702                                 continue;
10703                         WORKLIST_REMOVE(wk);
10704                         /*
10705                          * We can free immediately even if the jaddref
10706                          * isn't attached in a background write as now
10707                          * the bitmaps are reconciled.
10708                          */
10709                         wk->wk_state |= COMPLETE | ATTACHED;
10710                         free_jaddref(WK_JADDREF(wk));
10711                 }
10712                 jwork_move(&bp->b_dep, wkhd);
10713         }
10714         FREE_LOCK(ump);
10715 }
10716
10717
10718 /*
10719  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10720  * map.  Any dependencies waiting for the write to clear are added to the
10721  * buf's list and any jnewblks that are being canceled are discarded
10722  * immediately.
10723  */
10724 void
10725 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10726         struct mount *mp;
10727         struct buf *bp;
10728         ufs2_daddr_t blkno;
10729         int frags;
10730         struct workhead *wkhd;
10731 {
10732         struct bmsafemap *bmsafemap;
10733         struct jnewblk *jnewblk;
10734         struct ufsmount *ump;
10735         struct worklist *wk;
10736         struct fs *fs;
10737 #ifdef SUJ_DEBUG
10738         uint8_t *blksfree;
10739         struct cg *cgp;
10740         ufs2_daddr_t jstart;
10741         ufs2_daddr_t jend;
10742         ufs2_daddr_t end;
10743         long bno;
10744         int i;
10745 #endif
10746
10747         CTR3(KTR_SUJ,
10748             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10749             blkno, frags, wkhd);
10750
10751         ump = VFSTOUFS(mp);
10752         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10753             ("softdep_setup_blkfree called on non-softdep filesystem"));
10754         ACQUIRE_LOCK(ump);
10755         /* Lookup the bmsafemap so we track when it is dirty. */
10756         fs = ump->um_fs;
10757         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10758         /*
10759          * Detach any jnewblks which have been canceled.  They must linger
10760          * until the bitmap is cleared again by ffs_blkfree() to prevent
10761          * an unjournaled allocation from hitting the disk.
10762          */
10763         if (wkhd) {
10764                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10765                         CTR2(KTR_SUJ,
10766                             "softdep_setup_blkfree: blkno %jd wk type %d",
10767                             blkno, wk->wk_type);
10768                         WORKLIST_REMOVE(wk);
10769                         if (wk->wk_type != D_JNEWBLK) {
10770                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10771                                 continue;
10772                         }
10773                         jnewblk = WK_JNEWBLK(wk);
10774                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10775                             ("softdep_setup_blkfree: jnewblk not canceled."));
10776 #ifdef SUJ_DEBUG
10777                         /*
10778                          * Assert that this block is free in the bitmap
10779                          * before we discard the jnewblk.
10780                          */
10781                         cgp = (struct cg *)bp->b_data;
10782                         blksfree = cg_blksfree(cgp);
10783                         bno = dtogd(fs, jnewblk->jn_blkno);
10784                         for (i = jnewblk->jn_oldfrags;
10785                             i < jnewblk->jn_frags; i++) {
10786                                 if (isset(blksfree, bno + i))
10787                                         continue;
10788                                 panic("softdep_setup_blkfree: not free");
10789                         }
10790 #endif
10791                         /*
10792                          * Even if it's not attached we can free immediately
10793                          * as the new bitmap is correct.
10794                          */
10795                         wk->wk_state |= COMPLETE | ATTACHED;
10796                         free_jnewblk(jnewblk);
10797                 }
10798         }
10799
10800 #ifdef SUJ_DEBUG
10801         /*
10802          * Assert that we are not freeing a block which has an outstanding
10803          * allocation dependency.
10804          */
10805         fs = VFSTOUFS(mp)->um_fs;
10806         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10807         end = blkno + frags;
10808         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10809                 /*
10810                  * Don't match against blocks that will be freed when the
10811                  * background write is done.
10812                  */
10813                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10814                     (COMPLETE | DEPCOMPLETE))
10815                         continue;
10816                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10817                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10818                 if ((blkno >= jstart && blkno < jend) ||
10819                     (end > jstart && end <= jend)) {
10820                         printf("state 0x%X %jd - %d %d dep %p\n",
10821                             jnewblk->jn_state, jnewblk->jn_blkno,
10822                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10823                             jnewblk->jn_dep);
10824                         panic("softdep_setup_blkfree: "
10825                             "%jd-%jd(%d) overlaps with %jd-%jd",
10826                             blkno, end, frags, jstart, jend);
10827                 }
10828         }
10829 #endif
10830         FREE_LOCK(ump);
10831 }
10832
10833 /*
10834  * Revert a block allocation when the journal record that describes it
10835  * is not yet written.
10836  */
10837 static int
10838 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10839         struct jnewblk *jnewblk;
10840         struct fs *fs;
10841         struct cg *cgp;
10842         uint8_t *blksfree;
10843 {
10844         ufs1_daddr_t fragno;
10845         long cgbno, bbase;
10846         int frags, blk;
10847         int i;
10848
10849         frags = 0;
10850         cgbno = dtogd(fs, jnewblk->jn_blkno);
10851         /*
10852          * We have to test which frags need to be rolled back.  We may
10853          * be operating on a stale copy when doing background writes.
10854          */
10855         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10856                 if (isclr(blksfree, cgbno + i))
10857                         frags++;
10858         if (frags == 0)
10859                 return (0);
10860         /*
10861          * This is mostly ffs_blkfree() sans some validation and
10862          * superblock updates.
10863          */
10864         if (frags == fs->fs_frag) {
10865                 fragno = fragstoblks(fs, cgbno);
10866                 ffs_setblock(fs, blksfree, fragno);
10867                 ffs_clusteracct(fs, cgp, fragno, 1);
10868                 cgp->cg_cs.cs_nbfree++;
10869         } else {
10870                 cgbno += jnewblk->jn_oldfrags;
10871                 bbase = cgbno - fragnum(fs, cgbno);
10872                 /* Decrement the old frags.  */
10873                 blk = blkmap(fs, blksfree, bbase);
10874                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10875                 /* Deallocate the fragment */
10876                 for (i = 0; i < frags; i++)
10877                         setbit(blksfree, cgbno + i);
10878                 cgp->cg_cs.cs_nffree += frags;
10879                 /* Add back in counts associated with the new frags */
10880                 blk = blkmap(fs, blksfree, bbase);
10881                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10882                 /* If a complete block has been reassembled, account for it. */
10883                 fragno = fragstoblks(fs, bbase);
10884                 if (ffs_isblock(fs, blksfree, fragno)) {
10885                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10886                         ffs_clusteracct(fs, cgp, fragno, 1);
10887                         cgp->cg_cs.cs_nbfree++;
10888                 }
10889         }
10890         stat_jnewblk++;
10891         jnewblk->jn_state &= ~ATTACHED;
10892         jnewblk->jn_state |= UNDONE;
10893
10894         return (frags);
10895 }
10896
10897 static void
10898 initiate_write_bmsafemap(bmsafemap, bp)
10899         struct bmsafemap *bmsafemap;
10900         struct buf *bp;                 /* The cg block. */
10901 {
10902         struct jaddref *jaddref;
10903         struct jnewblk *jnewblk;
10904         uint8_t *inosused;
10905         uint8_t *blksfree;
10906         struct cg *cgp;
10907         struct fs *fs;
10908         ino_t ino;
10909
10910         /*
10911          * If this is a background write, we did this at the time that
10912          * the copy was made, so do not need to do it again.
10913          */
10914         if (bmsafemap->sm_state & IOSTARTED)
10915                 return;
10916         bmsafemap->sm_state |= IOSTARTED;
10917         /*
10918          * Clear any inode allocations which are pending journal writes.
10919          */
10920         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10921                 cgp = (struct cg *)bp->b_data;
10922                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10923                 inosused = cg_inosused(cgp);
10924                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10925                         ino = jaddref->ja_ino % fs->fs_ipg;
10926                         if (isset(inosused, ino)) {
10927                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
10928                                         cgp->cg_cs.cs_ndir--;
10929                                 cgp->cg_cs.cs_nifree++;
10930                                 clrbit(inosused, ino);
10931                                 jaddref->ja_state &= ~ATTACHED;
10932                                 jaddref->ja_state |= UNDONE;
10933                                 stat_jaddref++;
10934                         } else
10935                                 panic("initiate_write_bmsafemap: inode %ju "
10936                                     "marked free", (uintmax_t)jaddref->ja_ino);
10937                 }
10938         }
10939         /*
10940          * Clear any block allocations which are pending journal writes.
10941          */
10942         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10943                 cgp = (struct cg *)bp->b_data;
10944                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10945                 blksfree = cg_blksfree(cgp);
10946                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10947                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10948                                 continue;
10949                         panic("initiate_write_bmsafemap: block %jd "
10950                             "marked free", jnewblk->jn_blkno);
10951                 }
10952         }
10953         /*
10954          * Move allocation lists to the written lists so they can be
10955          * cleared once the block write is complete.
10956          */
10957         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10958             inodedep, id_deps);
10959         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10960             newblk, nb_deps);
10961         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10962             wk_list);
10963 }
10964
10965 /*
10966  * This routine is called during the completion interrupt
10967  * service routine for a disk write (from the procedure called
10968  * by the device driver to inform the filesystem caches of
10969  * a request completion).  It should be called early in this
10970  * procedure, before the block is made available to other
10971  * processes or other routines are called.
10972  *
10973  */
10974 static void 
10975 softdep_disk_write_complete(bp)
10976         struct buf *bp;         /* describes the completed disk write */
10977 {
10978         struct worklist *wk;
10979         struct worklist *owk;
10980         struct ufsmount *ump;
10981         struct workhead reattach;
10982         struct freeblks *freeblks;
10983         struct buf *sbp;
10984
10985         ump = softdep_bp_to_mp(bp);
10986         if (ump == NULL)
10987                 return;
10988
10989         sbp = NULL;
10990
10991         /*
10992          * If an error occurred while doing the write, then the data
10993          * has not hit the disk and the dependencies cannot be processed.
10994          * But we do have to go through and roll forward any dependencies
10995          * that were rolled back before the disk write.
10996          */
10997         ACQUIRE_LOCK(ump);
10998         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
10999                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11000                         switch (wk->wk_type) {
11001
11002                         case D_PAGEDEP:
11003                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11004                                 continue;
11005
11006                         case D_INODEDEP:
11007                                 handle_written_inodeblock(WK_INODEDEP(wk),
11008                                     bp, 0);
11009                                 continue;
11010
11011                         case D_BMSAFEMAP:
11012                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11013                                     bp, 0);
11014                                 continue;
11015
11016                         case D_INDIRDEP:
11017                                 handle_written_indirdep(WK_INDIRDEP(wk),
11018                                     bp, &sbp, 0);
11019                                 continue;
11020                         default:
11021                                 /* nothing to roll forward */
11022                                 continue;
11023                         }
11024                 }
11025                 FREE_LOCK(ump);
11026                 return;
11027         }
11028         LIST_INIT(&reattach);
11029
11030         /*
11031          * Ump SU lock must not be released anywhere in this code segment.
11032          */
11033         owk = NULL;
11034         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11035                 WORKLIST_REMOVE(wk);
11036                 atomic_add_long(&dep_write[wk->wk_type], 1);
11037                 if (wk == owk)
11038                         panic("duplicate worklist: %p\n", wk);
11039                 owk = wk;
11040                 switch (wk->wk_type) {
11041
11042                 case D_PAGEDEP:
11043                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11044                             WRITESUCCEEDED))
11045                                 WORKLIST_INSERT(&reattach, wk);
11046                         continue;
11047
11048                 case D_INODEDEP:
11049                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11050                             WRITESUCCEEDED))
11051                                 WORKLIST_INSERT(&reattach, wk);
11052                         continue;
11053
11054                 case D_BMSAFEMAP:
11055                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11056                             WRITESUCCEEDED))
11057                                 WORKLIST_INSERT(&reattach, wk);
11058                         continue;
11059
11060                 case D_MKDIR:
11061                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11062                         continue;
11063
11064                 case D_ALLOCDIRECT:
11065                         wk->wk_state |= COMPLETE;
11066                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11067                         continue;
11068
11069                 case D_ALLOCINDIR:
11070                         wk->wk_state |= COMPLETE;
11071                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11072                         continue;
11073
11074                 case D_INDIRDEP:
11075                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11076                             WRITESUCCEEDED))
11077                                 WORKLIST_INSERT(&reattach, wk);
11078                         continue;
11079
11080                 case D_FREEBLKS:
11081                         wk->wk_state |= COMPLETE;
11082                         freeblks = WK_FREEBLKS(wk);
11083                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11084                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11085                                 add_to_worklist(wk, WK_NODELAY);
11086                         continue;
11087
11088                 case D_FREEWORK:
11089                         handle_written_freework(WK_FREEWORK(wk));
11090                         break;
11091
11092                 case D_JSEGDEP:
11093                         free_jsegdep(WK_JSEGDEP(wk));
11094                         continue;
11095
11096                 case D_JSEG:
11097                         handle_written_jseg(WK_JSEG(wk), bp);
11098                         continue;
11099
11100                 case D_SBDEP:
11101                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11102                                 WORKLIST_INSERT(&reattach, wk);
11103                         continue;
11104
11105                 case D_FREEDEP:
11106                         free_freedep(WK_FREEDEP(wk));
11107                         continue;
11108
11109                 default:
11110                         panic("handle_disk_write_complete: Unknown type %s",
11111                             TYPENAME(wk->wk_type));
11112                         /* NOTREACHED */
11113                 }
11114         }
11115         /*
11116          * Reattach any requests that must be redone.
11117          */
11118         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11119                 WORKLIST_REMOVE(wk);
11120                 WORKLIST_INSERT(&bp->b_dep, wk);
11121         }
11122         FREE_LOCK(ump);
11123         if (sbp)
11124                 brelse(sbp);
11125 }
11126
11127 /*
11128  * Called from within softdep_disk_write_complete above. Note that
11129  * this routine is always called from interrupt level with further
11130  * splbio interrupts blocked.
11131  */
11132 static void 
11133 handle_allocdirect_partdone(adp, wkhd)
11134         struct allocdirect *adp;        /* the completed allocdirect */
11135         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11136 {
11137         struct allocdirectlst *listhead;
11138         struct allocdirect *listadp;
11139         struct inodedep *inodedep;
11140         long bsize;
11141
11142         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11143                 return;
11144         /*
11145          * The on-disk inode cannot claim to be any larger than the last
11146          * fragment that has been written. Otherwise, the on-disk inode
11147          * might have fragments that were not the last block in the file
11148          * which would corrupt the filesystem. Thus, we cannot free any
11149          * allocdirects after one whose ad_oldblkno claims a fragment as
11150          * these blocks must be rolled back to zero before writing the inode.
11151          * We check the currently active set of allocdirects in id_inoupdt
11152          * or id_extupdt as appropriate.
11153          */
11154         inodedep = adp->ad_inodedep;
11155         bsize = inodedep->id_fs->fs_bsize;
11156         if (adp->ad_state & EXTDATA)
11157                 listhead = &inodedep->id_extupdt;
11158         else
11159                 listhead = &inodedep->id_inoupdt;
11160         TAILQ_FOREACH(listadp, listhead, ad_next) {
11161                 /* found our block */
11162                 if (listadp == adp)
11163                         break;
11164                 /* continue if ad_oldlbn is not a fragment */
11165                 if (listadp->ad_oldsize == 0 ||
11166                     listadp->ad_oldsize == bsize)
11167                         continue;
11168                 /* hit a fragment */
11169                 return;
11170         }
11171         /*
11172          * If we have reached the end of the current list without
11173          * finding the just finished dependency, then it must be
11174          * on the future dependency list. Future dependencies cannot
11175          * be freed until they are moved to the current list.
11176          */
11177         if (listadp == NULL) {
11178 #ifdef DEBUG
11179                 if (adp->ad_state & EXTDATA)
11180                         listhead = &inodedep->id_newextupdt;
11181                 else
11182                         listhead = &inodedep->id_newinoupdt;
11183                 TAILQ_FOREACH(listadp, listhead, ad_next)
11184                         /* found our block */
11185                         if (listadp == adp)
11186                                 break;
11187                 if (listadp == NULL)
11188                         panic("handle_allocdirect_partdone: lost dep");
11189 #endif /* DEBUG */
11190                 return;
11191         }
11192         /*
11193          * If we have found the just finished dependency, then queue
11194          * it along with anything that follows it that is complete.
11195          * Since the pointer has not yet been written in the inode
11196          * as the dependency prevents it, place the allocdirect on the
11197          * bufwait list where it will be freed once the pointer is
11198          * valid.
11199          */
11200         if (wkhd == NULL)
11201                 wkhd = &inodedep->id_bufwait;
11202         for (; adp; adp = listadp) {
11203                 listadp = TAILQ_NEXT(adp, ad_next);
11204                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11205                         return;
11206                 TAILQ_REMOVE(listhead, adp, ad_next);
11207                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11208         }
11209 }
11210
11211 /*
11212  * Called from within softdep_disk_write_complete above.  This routine
11213  * completes successfully written allocindirs.
11214  */
11215 static void
11216 handle_allocindir_partdone(aip)
11217         struct allocindir *aip;         /* the completed allocindir */
11218 {
11219         struct indirdep *indirdep;
11220
11221         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11222                 return;
11223         indirdep = aip->ai_indirdep;
11224         LIST_REMOVE(aip, ai_next);
11225         /*
11226          * Don't set a pointer while the buffer is undergoing IO or while
11227          * we have active truncations.
11228          */
11229         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11230                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11231                 return;
11232         }
11233         if (indirdep->ir_state & UFS1FMT)
11234                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11235                     aip->ai_newblkno;
11236         else
11237                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11238                     aip->ai_newblkno;
11239         /*
11240          * Await the pointer write before freeing the allocindir.
11241          */
11242         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11243 }
11244
11245 /*
11246  * Release segments held on a jwork list.
11247  */
11248 static void
11249 handle_jwork(wkhd)
11250         struct workhead *wkhd;
11251 {
11252         struct worklist *wk;
11253
11254         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11255                 WORKLIST_REMOVE(wk);
11256                 switch (wk->wk_type) {
11257                 case D_JSEGDEP:
11258                         free_jsegdep(WK_JSEGDEP(wk));
11259                         continue;
11260                 case D_FREEDEP:
11261                         free_freedep(WK_FREEDEP(wk));
11262                         continue;
11263                 case D_FREEFRAG:
11264                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11265                         WORKITEM_FREE(wk, D_FREEFRAG);
11266                         continue;
11267                 case D_FREEWORK:
11268                         handle_written_freework(WK_FREEWORK(wk));
11269                         continue;
11270                 default:
11271                         panic("handle_jwork: Unknown type %s\n",
11272                             TYPENAME(wk->wk_type));
11273                 }
11274         }
11275 }
11276
11277 /*
11278  * Handle the bufwait list on an inode when it is safe to release items
11279  * held there.  This normally happens after an inode block is written but
11280  * may be delayed and handled later if there are pending journal items that
11281  * are not yet safe to be released.
11282  */
11283 static struct freefile *
11284 handle_bufwait(inodedep, refhd)
11285         struct inodedep *inodedep;
11286         struct workhead *refhd;
11287 {
11288         struct jaddref *jaddref;
11289         struct freefile *freefile;
11290         struct worklist *wk;
11291
11292         freefile = NULL;
11293         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11294                 WORKLIST_REMOVE(wk);
11295                 switch (wk->wk_type) {
11296                 case D_FREEFILE:
11297                         /*
11298                          * We defer adding freefile to the worklist
11299                          * until all other additions have been made to
11300                          * ensure that it will be done after all the
11301                          * old blocks have been freed.
11302                          */
11303                         if (freefile != NULL)
11304                                 panic("handle_bufwait: freefile");
11305                         freefile = WK_FREEFILE(wk);
11306                         continue;
11307
11308                 case D_MKDIR:
11309                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11310                         continue;
11311
11312                 case D_DIRADD:
11313                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11314                         continue;
11315
11316                 case D_FREEFRAG:
11317                         wk->wk_state |= COMPLETE;
11318                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11319                                 add_to_worklist(wk, 0);
11320                         continue;
11321
11322                 case D_DIRREM:
11323                         wk->wk_state |= COMPLETE;
11324                         add_to_worklist(wk, 0);
11325                         continue;
11326
11327                 case D_ALLOCDIRECT:
11328                 case D_ALLOCINDIR:
11329                         free_newblk(WK_NEWBLK(wk));
11330                         continue;
11331
11332                 case D_JNEWBLK:
11333                         wk->wk_state |= COMPLETE;
11334                         free_jnewblk(WK_JNEWBLK(wk));
11335                         continue;
11336
11337                 /*
11338                  * Save freed journal segments and add references on
11339                  * the supplied list which will delay their release
11340                  * until the cg bitmap is cleared on disk.
11341                  */
11342                 case D_JSEGDEP:
11343                         if (refhd == NULL)
11344                                 free_jsegdep(WK_JSEGDEP(wk));
11345                         else
11346                                 WORKLIST_INSERT(refhd, wk);
11347                         continue;
11348
11349                 case D_JADDREF:
11350                         jaddref = WK_JADDREF(wk);
11351                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11352                             if_deps);
11353                         /*
11354                          * Transfer any jaddrefs to the list to be freed with
11355                          * the bitmap if we're handling a removed file.
11356                          */
11357                         if (refhd == NULL) {
11358                                 wk->wk_state |= COMPLETE;
11359                                 free_jaddref(jaddref);
11360                         } else
11361                                 WORKLIST_INSERT(refhd, wk);
11362                         continue;
11363
11364                 default:
11365                         panic("handle_bufwait: Unknown type %p(%s)",
11366                             wk, TYPENAME(wk->wk_type));
11367                         /* NOTREACHED */
11368                 }
11369         }
11370         return (freefile);
11371 }
11372 /*
11373  * Called from within softdep_disk_write_complete above to restore
11374  * in-memory inode block contents to their most up-to-date state. Note
11375  * that this routine is always called from interrupt level with further
11376  * interrupts from this device blocked.
11377  *
11378  * If the write did not succeed, we will do all the roll-forward
11379  * operations, but we will not take the actions that will allow its
11380  * dependencies to be processed.
11381  */
11382 static int 
11383 handle_written_inodeblock(inodedep, bp, flags)
11384         struct inodedep *inodedep;
11385         struct buf *bp;         /* buffer containing the inode block */
11386         int flags;
11387 {
11388         struct freefile *freefile;
11389         struct allocdirect *adp, *nextadp;
11390         struct ufs1_dinode *dp1 = NULL;
11391         struct ufs2_dinode *dp2 = NULL;
11392         struct workhead wkhd;
11393         int hadchanges, fstype;
11394         ino_t freelink;
11395
11396         LIST_INIT(&wkhd);
11397         hadchanges = 0;
11398         freefile = NULL;
11399         if ((inodedep->id_state & IOSTARTED) == 0)
11400                 panic("handle_written_inodeblock: not started");
11401         inodedep->id_state &= ~IOSTARTED;
11402         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11403                 fstype = UFS1;
11404                 dp1 = (struct ufs1_dinode *)bp->b_data +
11405                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11406                 freelink = dp1->di_freelink;
11407         } else {
11408                 fstype = UFS2;
11409                 dp2 = (struct ufs2_dinode *)bp->b_data +
11410                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11411                 freelink = dp2->di_freelink;
11412         }
11413         /*
11414          * Leave this inodeblock dirty until it's in the list.
11415          */
11416         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11417             (flags & WRITESUCCEEDED)) {
11418                 struct inodedep *inon;
11419
11420                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11421                 if ((inon == NULL && freelink == 0) ||
11422                     (inon && inon->id_ino == freelink)) {
11423                         if (inon)
11424                                 inon->id_state |= UNLINKPREV;
11425                         inodedep->id_state |= UNLINKNEXT;
11426                 }
11427                 hadchanges = 1;
11428         }
11429         /*
11430          * If we had to rollback the inode allocation because of
11431          * bitmaps being incomplete, then simply restore it.
11432          * Keep the block dirty so that it will not be reclaimed until
11433          * all associated dependencies have been cleared and the
11434          * corresponding updates written to disk.
11435          */
11436         if (inodedep->id_savedino1 != NULL) {
11437                 hadchanges = 1;
11438                 if (fstype == UFS1)
11439                         *dp1 = *inodedep->id_savedino1;
11440                 else
11441                         *dp2 = *inodedep->id_savedino2;
11442                 free(inodedep->id_savedino1, M_SAVEDINO);
11443                 inodedep->id_savedino1 = NULL;
11444                 if ((bp->b_flags & B_DELWRI) == 0)
11445                         stat_inode_bitmap++;
11446                 bdirty(bp);
11447                 /*
11448                  * If the inode is clear here and GOINGAWAY it will never
11449                  * be written.  Process the bufwait and clear any pending
11450                  * work which may include the freefile.
11451                  */
11452                 if (inodedep->id_state & GOINGAWAY)
11453                         goto bufwait;
11454                 return (1);
11455         }
11456         if (flags & WRITESUCCEEDED)
11457                 inodedep->id_state |= COMPLETE;
11458         /*
11459          * Roll forward anything that had to be rolled back before 
11460          * the inode could be updated.
11461          */
11462         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11463                 nextadp = TAILQ_NEXT(adp, ad_next);
11464                 if (adp->ad_state & ATTACHED)
11465                         panic("handle_written_inodeblock: new entry");
11466                 if (fstype == UFS1) {
11467                         if (adp->ad_offset < UFS_NDADDR) {
11468                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11469                                         panic("%s %s #%jd mismatch %d != %jd",
11470                                             "handle_written_inodeblock:",
11471                                             "direct pointer",
11472                                             (intmax_t)adp->ad_offset,
11473                                             dp1->di_db[adp->ad_offset],
11474                                             (intmax_t)adp->ad_oldblkno);
11475                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11476                         } else {
11477                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11478                                     0)
11479                                         panic("%s: %s #%jd allocated as %d",
11480                                             "handle_written_inodeblock",
11481                                             "indirect pointer",
11482                                             (intmax_t)adp->ad_offset -
11483                                             UFS_NDADDR,
11484                                             dp1->di_ib[adp->ad_offset -
11485                                             UFS_NDADDR]);
11486                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11487                                     adp->ad_newblkno;
11488                         }
11489                 } else {
11490                         if (adp->ad_offset < UFS_NDADDR) {
11491                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11492                                         panic("%s: %s #%jd %s %jd != %jd",
11493                                             "handle_written_inodeblock",
11494                                             "direct pointer",
11495                                             (intmax_t)adp->ad_offset, "mismatch",
11496                                             (intmax_t)dp2->di_db[adp->ad_offset],
11497                                             (intmax_t)adp->ad_oldblkno);
11498                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11499                         } else {
11500                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11501                                     0)
11502                                         panic("%s: %s #%jd allocated as %jd",
11503                                             "handle_written_inodeblock",
11504                                             "indirect pointer",
11505                                             (intmax_t)adp->ad_offset -
11506                                             UFS_NDADDR,
11507                                             (intmax_t)
11508                                             dp2->di_ib[adp->ad_offset -
11509                                             UFS_NDADDR]);
11510                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11511                                     adp->ad_newblkno;
11512                         }
11513                 }
11514                 adp->ad_state &= ~UNDONE;
11515                 adp->ad_state |= ATTACHED;
11516                 hadchanges = 1;
11517         }
11518         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11519                 nextadp = TAILQ_NEXT(adp, ad_next);
11520                 if (adp->ad_state & ATTACHED)
11521                         panic("handle_written_inodeblock: new entry");
11522                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11523                         panic("%s: direct pointers #%jd %s %jd != %jd",
11524                             "handle_written_inodeblock",
11525                             (intmax_t)adp->ad_offset, "mismatch",
11526                             (intmax_t)dp2->di_extb[adp->ad_offset],
11527                             (intmax_t)adp->ad_oldblkno);
11528                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11529                 adp->ad_state &= ~UNDONE;
11530                 adp->ad_state |= ATTACHED;
11531                 hadchanges = 1;
11532         }
11533         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11534                 stat_direct_blk_ptrs++;
11535         /*
11536          * Reset the file size to its most up-to-date value.
11537          */
11538         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11539                 panic("handle_written_inodeblock: bad size");
11540         if (inodedep->id_savednlink > UFS_LINK_MAX)
11541                 panic("handle_written_inodeblock: Invalid link count "
11542                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11543                     inodedep);
11544         if (fstype == UFS1) {
11545                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11546                         dp1->di_nlink = inodedep->id_savednlink;
11547                         hadchanges = 1;
11548                 }
11549                 if (dp1->di_size != inodedep->id_savedsize) {
11550                         dp1->di_size = inodedep->id_savedsize;
11551                         hadchanges = 1;
11552                 }
11553         } else {
11554                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11555                         dp2->di_nlink = inodedep->id_savednlink;
11556                         hadchanges = 1;
11557                 }
11558                 if (dp2->di_size != inodedep->id_savedsize) {
11559                         dp2->di_size = inodedep->id_savedsize;
11560                         hadchanges = 1;
11561                 }
11562                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11563                         dp2->di_extsize = inodedep->id_savedextsize;
11564                         hadchanges = 1;
11565                 }
11566         }
11567         inodedep->id_savedsize = -1;
11568         inodedep->id_savedextsize = -1;
11569         inodedep->id_savednlink = -1;
11570         /*
11571          * If there were any rollbacks in the inode block, then it must be
11572          * marked dirty so that its will eventually get written back in
11573          * its correct form.
11574          */
11575         if (hadchanges)
11576                 bdirty(bp);
11577 bufwait:
11578         /*
11579          * If the write did not succeed, we have done all the roll-forward
11580          * operations, but we cannot take the actions that will allow its
11581          * dependencies to be processed.
11582          */
11583         if ((flags & WRITESUCCEEDED) == 0)
11584                 return (hadchanges);
11585         /*
11586          * Process any allocdirects that completed during the update.
11587          */
11588         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11589                 handle_allocdirect_partdone(adp, &wkhd);
11590         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11591                 handle_allocdirect_partdone(adp, &wkhd);
11592         /*
11593          * Process deallocations that were held pending until the
11594          * inode had been written to disk. Freeing of the inode
11595          * is delayed until after all blocks have been freed to
11596          * avoid creation of new <vfsid, inum, lbn> triples
11597          * before the old ones have been deleted.  Completely
11598          * unlinked inodes are not processed until the unlinked
11599          * inode list is written or the last reference is removed.
11600          */
11601         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11602                 freefile = handle_bufwait(inodedep, NULL);
11603                 if (freefile && !LIST_EMPTY(&wkhd)) {
11604                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11605                         freefile = NULL;
11606                 }
11607         }
11608         /*
11609          * Move rolled forward dependency completions to the bufwait list
11610          * now that those that were already written have been processed.
11611          */
11612         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11613                 panic("handle_written_inodeblock: bufwait but no changes");
11614         jwork_move(&inodedep->id_bufwait, &wkhd);
11615
11616         if (freefile != NULL) {
11617                 /*
11618                  * If the inode is goingaway it was never written.  Fake up
11619                  * the state here so free_inodedep() can succeed.
11620                  */
11621                 if (inodedep->id_state & GOINGAWAY)
11622                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11623                 if (free_inodedep(inodedep) == 0)
11624                         panic("handle_written_inodeblock: live inodedep %p",
11625                             inodedep);
11626                 add_to_worklist(&freefile->fx_list, 0);
11627                 return (0);
11628         }
11629
11630         /*
11631          * If no outstanding dependencies, free it.
11632          */
11633         if (free_inodedep(inodedep) ||
11634             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11635              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11636              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11637              LIST_FIRST(&inodedep->id_bufwait) == 0))
11638                 return (0);
11639         return (hadchanges);
11640 }
11641
11642 /*
11643  * Perform needed roll-forwards and kick off any dependencies that
11644  * can now be processed.
11645  *
11646  * If the write did not succeed, we will do all the roll-forward
11647  * operations, but we will not take the actions that will allow its
11648  * dependencies to be processed.
11649  */
11650 static int
11651 handle_written_indirdep(indirdep, bp, bpp, flags)
11652         struct indirdep *indirdep;
11653         struct buf *bp;
11654         struct buf **bpp;
11655         int flags;
11656 {
11657         struct allocindir *aip;
11658         struct buf *sbp;
11659         int chgs;
11660
11661         if (indirdep->ir_state & GOINGAWAY)
11662                 panic("handle_written_indirdep: indirdep gone");
11663         if ((indirdep->ir_state & IOSTARTED) == 0)
11664                 panic("handle_written_indirdep: IO not started");
11665         chgs = 0;
11666         /*
11667          * If there were rollbacks revert them here.
11668          */
11669         if (indirdep->ir_saveddata) {
11670                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11671                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11672                         free(indirdep->ir_saveddata, M_INDIRDEP);
11673                         indirdep->ir_saveddata = NULL;
11674                 }
11675                 chgs = 1;
11676         }
11677         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11678         indirdep->ir_state |= ATTACHED;
11679         /*
11680          * If the write did not succeed, we have done all the roll-forward
11681          * operations, but we cannot take the actions that will allow its
11682          * dependencies to be processed.
11683          */
11684         if ((flags & WRITESUCCEEDED) == 0) {
11685                 stat_indir_blk_ptrs++;
11686                 bdirty(bp);
11687                 return (1);
11688         }
11689         /*
11690          * Move allocindirs with written pointers to the completehd if
11691          * the indirdep's pointer is not yet written.  Otherwise
11692          * free them here.
11693          */
11694         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11695                 LIST_REMOVE(aip, ai_next);
11696                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11697                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11698                             ai_next);
11699                         newblk_freefrag(&aip->ai_block);
11700                         continue;
11701                 }
11702                 free_newblk(&aip->ai_block);
11703         }
11704         /*
11705          * Move allocindirs that have finished dependency processing from
11706          * the done list to the write list after updating the pointers.
11707          */
11708         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11709                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11710                         handle_allocindir_partdone(aip);
11711                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11712                                 panic("disk_write_complete: not gone");
11713                         chgs = 1;
11714                 }
11715         }
11716         /*
11717          * Preserve the indirdep if there were any changes or if it is not
11718          * yet valid on disk.
11719          */
11720         if (chgs) {
11721                 stat_indir_blk_ptrs++;
11722                 bdirty(bp);
11723                 return (1);
11724         }
11725         /*
11726          * If there were no changes we can discard the savedbp and detach
11727          * ourselves from the buf.  We are only carrying completed pointers
11728          * in this case.
11729          */
11730         sbp = indirdep->ir_savebp;
11731         sbp->b_flags |= B_INVAL | B_NOCACHE;
11732         indirdep->ir_savebp = NULL;
11733         indirdep->ir_bp = NULL;
11734         if (*bpp != NULL)
11735                 panic("handle_written_indirdep: bp already exists.");
11736         *bpp = sbp;
11737         /*
11738          * The indirdep may not be freed until its parent points at it.
11739          */
11740         if (indirdep->ir_state & DEPCOMPLETE)
11741                 free_indirdep(indirdep);
11742
11743         return (0);
11744 }
11745
11746 /*
11747  * Process a diradd entry after its dependent inode has been written.
11748  * This routine must be called with splbio interrupts blocked.
11749  */
11750 static void
11751 diradd_inode_written(dap, inodedep)
11752         struct diradd *dap;
11753         struct inodedep *inodedep;
11754 {
11755
11756         dap->da_state |= COMPLETE;
11757         complete_diradd(dap);
11758         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11759 }
11760
11761 /*
11762  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11763  * be called with the per-filesystem lock and the buf lock on the cg held.
11764  */
11765 static int
11766 bmsafemap_backgroundwrite(bmsafemap, bp)
11767         struct bmsafemap *bmsafemap;
11768         struct buf *bp;
11769 {
11770         int dirty;
11771
11772         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11773         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11774             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11775         /*
11776          * If we're initiating a background write we need to process the
11777          * rollbacks as they exist now, not as they exist when IO starts.
11778          * No other consumers will look at the contents of the shadowed
11779          * buf so this is safe to do here.
11780          */
11781         if (bp->b_xflags & BX_BKGRDMARKER)
11782                 initiate_write_bmsafemap(bmsafemap, bp);
11783
11784         return (dirty);
11785 }
11786
11787 /*
11788  * Re-apply an allocation when a cg write is complete.
11789  */
11790 static int
11791 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11792         struct jnewblk *jnewblk;
11793         struct fs *fs;
11794         struct cg *cgp;
11795         uint8_t *blksfree;
11796 {
11797         ufs1_daddr_t fragno;
11798         ufs2_daddr_t blkno;
11799         long cgbno, bbase;
11800         int frags, blk;
11801         int i;
11802
11803         frags = 0;
11804         cgbno = dtogd(fs, jnewblk->jn_blkno);
11805         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11806                 if (isclr(blksfree, cgbno + i))
11807                         panic("jnewblk_rollforward: re-allocated fragment");
11808                 frags++;
11809         }
11810         if (frags == fs->fs_frag) {
11811                 blkno = fragstoblks(fs, cgbno);
11812                 ffs_clrblock(fs, blksfree, (long)blkno);
11813                 ffs_clusteracct(fs, cgp, blkno, -1);
11814                 cgp->cg_cs.cs_nbfree--;
11815         } else {
11816                 bbase = cgbno - fragnum(fs, cgbno);
11817                 cgbno += jnewblk->jn_oldfrags;
11818                 /* If a complete block had been reassembled, account for it. */
11819                 fragno = fragstoblks(fs, bbase);
11820                 if (ffs_isblock(fs, blksfree, fragno)) {
11821                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11822                         ffs_clusteracct(fs, cgp, fragno, -1);
11823                         cgp->cg_cs.cs_nbfree--;
11824                 }
11825                 /* Decrement the old frags.  */
11826                 blk = blkmap(fs, blksfree, bbase);
11827                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11828                 /* Allocate the fragment */
11829                 for (i = 0; i < frags; i++)
11830                         clrbit(blksfree, cgbno + i);
11831                 cgp->cg_cs.cs_nffree -= frags;
11832                 /* Add back in counts associated with the new frags */
11833                 blk = blkmap(fs, blksfree, bbase);
11834                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11835         }
11836         return (frags);
11837 }
11838
11839 /*
11840  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11841  * changes if it's not a background write.  Set all written dependencies 
11842  * to DEPCOMPLETE and free the structure if possible.
11843  *
11844  * If the write did not succeed, we will do all the roll-forward
11845  * operations, but we will not take the actions that will allow its
11846  * dependencies to be processed.
11847  */
11848 static int
11849 handle_written_bmsafemap(bmsafemap, bp, flags)
11850         struct bmsafemap *bmsafemap;
11851         struct buf *bp;
11852         int flags;
11853 {
11854         struct newblk *newblk;
11855         struct inodedep *inodedep;
11856         struct jaddref *jaddref, *jatmp;
11857         struct jnewblk *jnewblk, *jntmp;
11858         struct ufsmount *ump;
11859         uint8_t *inosused;
11860         uint8_t *blksfree;
11861         struct cg *cgp;
11862         struct fs *fs;
11863         ino_t ino;
11864         int foreground;
11865         int chgs;
11866
11867         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11868                 panic("handle_written_bmsafemap: Not started\n");
11869         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11870         chgs = 0;
11871         bmsafemap->sm_state &= ~IOSTARTED;
11872         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11873         /*
11874          * If write was successful, release journal work that was waiting
11875          * on the write. Otherwise move the work back.
11876          */
11877         if (flags & WRITESUCCEEDED)
11878                 handle_jwork(&bmsafemap->sm_freewr);
11879         else
11880                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11881                     worklist, wk_list);
11882
11883         /*
11884          * Restore unwritten inode allocation pending jaddref writes.
11885          */
11886         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11887                 cgp = (struct cg *)bp->b_data;
11888                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11889                 inosused = cg_inosused(cgp);
11890                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11891                     ja_bmdeps, jatmp) {
11892                         if ((jaddref->ja_state & UNDONE) == 0)
11893                                 continue;
11894                         ino = jaddref->ja_ino % fs->fs_ipg;
11895                         if (isset(inosused, ino))
11896                                 panic("handle_written_bmsafemap: "
11897                                     "re-allocated inode");
11898                         /* Do the roll-forward only if it's a real copy. */
11899                         if (foreground) {
11900                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11901                                         cgp->cg_cs.cs_ndir++;
11902                                 cgp->cg_cs.cs_nifree--;
11903                                 setbit(inosused, ino);
11904                                 chgs = 1;
11905                         }
11906                         jaddref->ja_state &= ~UNDONE;
11907                         jaddref->ja_state |= ATTACHED;
11908                         free_jaddref(jaddref);
11909                 }
11910         }
11911         /*
11912          * Restore any block allocations which are pending journal writes.
11913          */
11914         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11915                 cgp = (struct cg *)bp->b_data;
11916                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11917                 blksfree = cg_blksfree(cgp);
11918                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11919                     jntmp) {
11920                         if ((jnewblk->jn_state & UNDONE) == 0)
11921                                 continue;
11922                         /* Do the roll-forward only if it's a real copy. */
11923                         if (foreground &&
11924                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11925                                 chgs = 1;
11926                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11927                         jnewblk->jn_state |= ATTACHED;
11928                         free_jnewblk(jnewblk);
11929                 }
11930         }
11931         /*
11932          * If the write did not succeed, we have done all the roll-forward
11933          * operations, but we cannot take the actions that will allow its
11934          * dependencies to be processed.
11935          */
11936         if ((flags & WRITESUCCEEDED) == 0) {
11937                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11938                     newblk, nb_deps);
11939                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11940                     worklist, wk_list);
11941                 if (foreground)
11942                         bdirty(bp);
11943                 return (1);
11944         }
11945         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11946                 newblk->nb_state |= DEPCOMPLETE;
11947                 newblk->nb_state &= ~ONDEPLIST;
11948                 newblk->nb_bmsafemap = NULL;
11949                 LIST_REMOVE(newblk, nb_deps);
11950                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11951                         handle_allocdirect_partdone(
11952                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11953                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11954                         handle_allocindir_partdone(
11955                             WK_ALLOCINDIR(&newblk->nb_list));
11956                 else if (newblk->nb_list.wk_type != D_NEWBLK)
11957                         panic("handle_written_bmsafemap: Unexpected type: %s",
11958                             TYPENAME(newblk->nb_list.wk_type));
11959         }
11960         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11961                 inodedep->id_state |= DEPCOMPLETE;
11962                 inodedep->id_state &= ~ONDEPLIST;
11963                 LIST_REMOVE(inodedep, id_deps);
11964                 inodedep->id_bmsafemap = NULL;
11965         }
11966         LIST_REMOVE(bmsafemap, sm_next);
11967         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11968             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11969             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11970             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11971             LIST_EMPTY(&bmsafemap->sm_freehd)) {
11972                 LIST_REMOVE(bmsafemap, sm_hash);
11973                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11974                 return (0);
11975         }
11976         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11977         if (foreground)
11978                 bdirty(bp);
11979         return (1);
11980 }
11981
11982 /*
11983  * Try to free a mkdir dependency.
11984  */
11985 static void
11986 complete_mkdir(mkdir)
11987         struct mkdir *mkdir;
11988 {
11989         struct diradd *dap;
11990
11991         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11992                 return;
11993         LIST_REMOVE(mkdir, md_mkdirs);
11994         dap = mkdir->md_diradd;
11995         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11996         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11997                 dap->da_state |= DEPCOMPLETE;
11998                 complete_diradd(dap);
11999         }
12000         WORKITEM_FREE(mkdir, D_MKDIR);
12001 }
12002
12003 /*
12004  * Handle the completion of a mkdir dependency.
12005  */
12006 static void
12007 handle_written_mkdir(mkdir, type)
12008         struct mkdir *mkdir;
12009         int type;
12010 {
12011
12012         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12013                 panic("handle_written_mkdir: bad type");
12014         mkdir->md_state |= COMPLETE;
12015         complete_mkdir(mkdir);
12016 }
12017
12018 static int
12019 free_pagedep(pagedep)
12020         struct pagedep *pagedep;
12021 {
12022         int i;
12023
12024         if (pagedep->pd_state & NEWBLOCK)
12025                 return (0);
12026         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12027                 return (0);
12028         for (i = 0; i < DAHASHSZ; i++)
12029                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12030                         return (0);
12031         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12032                 return (0);
12033         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12034                 return (0);
12035         if (pagedep->pd_state & ONWORKLIST)
12036                 WORKLIST_REMOVE(&pagedep->pd_list);
12037         LIST_REMOVE(pagedep, pd_hash);
12038         WORKITEM_FREE(pagedep, D_PAGEDEP);
12039
12040         return (1);
12041 }
12042
12043 /*
12044  * Called from within softdep_disk_write_complete above.
12045  * A write operation was just completed. Removed inodes can
12046  * now be freed and associated block pointers may be committed.
12047  * Note that this routine is always called from interrupt level
12048  * with further interrupts from this device blocked.
12049  *
12050  * If the write did not succeed, we will do all the roll-forward
12051  * operations, but we will not take the actions that will allow its
12052  * dependencies to be processed.
12053  */
12054 static int 
12055 handle_written_filepage(pagedep, bp, flags)
12056         struct pagedep *pagedep;
12057         struct buf *bp;         /* buffer containing the written page */
12058         int flags;
12059 {
12060         struct dirrem *dirrem;
12061         struct diradd *dap, *nextdap;
12062         struct direct *ep;
12063         int i, chgs;
12064
12065         if ((pagedep->pd_state & IOSTARTED) == 0)
12066                 panic("handle_written_filepage: not started");
12067         pagedep->pd_state &= ~IOSTARTED;
12068         if ((flags & WRITESUCCEEDED) == 0)
12069                 goto rollforward;
12070         /*
12071          * Process any directory removals that have been committed.
12072          */
12073         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12074                 LIST_REMOVE(dirrem, dm_next);
12075                 dirrem->dm_state |= COMPLETE;
12076                 dirrem->dm_dirinum = pagedep->pd_ino;
12077                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12078                     ("handle_written_filepage: Journal entries not written."));
12079                 add_to_worklist(&dirrem->dm_list, 0);
12080         }
12081         /*
12082          * Free any directory additions that have been committed.
12083          * If it is a newly allocated block, we have to wait until
12084          * the on-disk directory inode claims the new block.
12085          */
12086         if ((pagedep->pd_state & NEWBLOCK) == 0)
12087                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12088                         free_diradd(dap, NULL);
12089 rollforward:
12090         /*
12091          * Uncommitted directory entries must be restored.
12092          */
12093         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12094                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12095                      dap = nextdap) {
12096                         nextdap = LIST_NEXT(dap, da_pdlist);
12097                         if (dap->da_state & ATTACHED)
12098                                 panic("handle_written_filepage: attached");
12099                         ep = (struct direct *)
12100                             ((char *)bp->b_data + dap->da_offset);
12101                         ep->d_ino = dap->da_newinum;
12102                         dap->da_state &= ~UNDONE;
12103                         dap->da_state |= ATTACHED;
12104                         chgs = 1;
12105                         /*
12106                          * If the inode referenced by the directory has
12107                          * been written out, then the dependency can be
12108                          * moved to the pending list.
12109                          */
12110                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12111                                 LIST_REMOVE(dap, da_pdlist);
12112                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12113                                     da_pdlist);
12114                         }
12115                 }
12116         }
12117         /*
12118          * If there were any rollbacks in the directory, then it must be
12119          * marked dirty so that its will eventually get written back in
12120          * its correct form.
12121          */
12122         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12123                 if ((bp->b_flags & B_DELWRI) == 0)
12124                         stat_dir_entry++;
12125                 bdirty(bp);
12126                 return (1);
12127         }
12128         /*
12129          * If we are not waiting for a new directory block to be
12130          * claimed by its inode, then the pagedep will be freed.
12131          * Otherwise it will remain to track any new entries on
12132          * the page in case they are fsync'ed.
12133          */
12134         free_pagedep(pagedep);
12135         return (0);
12136 }
12137
12138 /*
12139  * Writing back in-core inode structures.
12140  * 
12141  * The filesystem only accesses an inode's contents when it occupies an
12142  * "in-core" inode structure.  These "in-core" structures are separate from
12143  * the page frames used to cache inode blocks.  Only the latter are
12144  * transferred to/from the disk.  So, when the updated contents of the
12145  * "in-core" inode structure are copied to the corresponding in-memory inode
12146  * block, the dependencies are also transferred.  The following procedure is
12147  * called when copying a dirty "in-core" inode to a cached inode block.
12148  */
12149
12150 /*
12151  * Called when an inode is loaded from disk. If the effective link count
12152  * differed from the actual link count when it was last flushed, then we
12153  * need to ensure that the correct effective link count is put back.
12154  */
12155 void 
12156 softdep_load_inodeblock(ip)
12157         struct inode *ip;       /* the "in_core" copy of the inode */
12158 {
12159         struct inodedep *inodedep;
12160         struct ufsmount *ump;
12161
12162         ump = ITOUMP(ip);
12163         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12164             ("softdep_load_inodeblock called on non-softdep filesystem"));
12165         /*
12166          * Check for alternate nlink count.
12167          */
12168         ip->i_effnlink = ip->i_nlink;
12169         ACQUIRE_LOCK(ump);
12170         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12171                 FREE_LOCK(ump);
12172                 return;
12173         }
12174         ip->i_effnlink -= inodedep->id_nlinkdelta;
12175         FREE_LOCK(ump);
12176 }
12177
12178 /*
12179  * This routine is called just before the "in-core" inode
12180  * information is to be copied to the in-memory inode block.
12181  * Recall that an inode block contains several inodes. If
12182  * the force flag is set, then the dependencies will be
12183  * cleared so that the update can always be made. Note that
12184  * the buffer is locked when this routine is called, so we
12185  * will never be in the middle of writing the inode block 
12186  * to disk.
12187  */
12188 void 
12189 softdep_update_inodeblock(ip, bp, waitfor)
12190         struct inode *ip;       /* the "in_core" copy of the inode */
12191         struct buf *bp;         /* the buffer containing the inode block */
12192         int waitfor;            /* nonzero => update must be allowed */
12193 {
12194         struct inodedep *inodedep;
12195         struct inoref *inoref;
12196         struct ufsmount *ump;
12197         struct worklist *wk;
12198         struct mount *mp;
12199         struct buf *ibp;
12200         struct fs *fs;
12201         int error;
12202
12203         ump = ITOUMP(ip);
12204         mp = UFSTOVFS(ump);
12205         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12206             ("softdep_update_inodeblock called on non-softdep filesystem"));
12207         fs = ump->um_fs;
12208         /*
12209          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12210          * does not have access to the in-core ip so must write directly into
12211          * the inode block buffer when setting freelink.
12212          */
12213         if (fs->fs_magic == FS_UFS1_MAGIC)
12214                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12215                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12216         else
12217                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12218                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12219         /*
12220          * If the effective link count is not equal to the actual link
12221          * count, then we must track the difference in an inodedep while
12222          * the inode is (potentially) tossed out of the cache. Otherwise,
12223          * if there is no existing inodedep, then there are no dependencies
12224          * to track.
12225          */
12226         ACQUIRE_LOCK(ump);
12227 again:
12228         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12229                 FREE_LOCK(ump);
12230                 if (ip->i_effnlink != ip->i_nlink)
12231                         panic("softdep_update_inodeblock: bad link count");
12232                 return;
12233         }
12234         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12235                 panic("softdep_update_inodeblock: bad delta");
12236         /*
12237          * If we're flushing all dependencies we must also move any waiting
12238          * for journal writes onto the bufwait list prior to I/O.
12239          */
12240         if (waitfor) {
12241                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12242                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12243                             == DEPCOMPLETE) {
12244                                 jwait(&inoref->if_list, MNT_WAIT);
12245                                 goto again;
12246                         }
12247                 }
12248         }
12249         /*
12250          * Changes have been initiated. Anything depending on these
12251          * changes cannot occur until this inode has been written.
12252          */
12253         inodedep->id_state &= ~COMPLETE;
12254         if ((inodedep->id_state & ONWORKLIST) == 0)
12255                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12256         /*
12257          * Any new dependencies associated with the incore inode must 
12258          * now be moved to the list associated with the buffer holding
12259          * the in-memory copy of the inode. Once merged process any
12260          * allocdirects that are completed by the merger.
12261          */
12262         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12263         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12264                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12265                     NULL);
12266         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12267         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12268                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12269                     NULL);
12270         /*
12271          * Now that the inode has been pushed into the buffer, the
12272          * operations dependent on the inode being written to disk
12273          * can be moved to the id_bufwait so that they will be
12274          * processed when the buffer I/O completes.
12275          */
12276         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12277                 WORKLIST_REMOVE(wk);
12278                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12279         }
12280         /*
12281          * Newly allocated inodes cannot be written until the bitmap
12282          * that allocates them have been written (indicated by
12283          * DEPCOMPLETE being set in id_state). If we are doing a
12284          * forced sync (e.g., an fsync on a file), we force the bitmap
12285          * to be written so that the update can be done.
12286          */
12287         if (waitfor == 0) {
12288                 FREE_LOCK(ump);
12289                 return;
12290         }
12291 retry:
12292         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12293                 FREE_LOCK(ump);
12294                 return;
12295         }
12296         ibp = inodedep->id_bmsafemap->sm_buf;
12297         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12298         if (ibp == NULL) {
12299                 /*
12300                  * If ibp came back as NULL, the dependency could have been
12301                  * freed while we slept.  Look it up again, and check to see
12302                  * that it has completed.
12303                  */
12304                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12305                         goto retry;
12306                 FREE_LOCK(ump);
12307                 return;
12308         }
12309         FREE_LOCK(ump);
12310         if ((error = bwrite(ibp)) != 0)
12311                 softdep_error("softdep_update_inodeblock: bwrite", error);
12312 }
12313
12314 /*
12315  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12316  * old inode dependency list (such as id_inoupdt). This routine must be
12317  * called with splbio interrupts blocked.
12318  */
12319 static void
12320 merge_inode_lists(newlisthead, oldlisthead)
12321         struct allocdirectlst *newlisthead;
12322         struct allocdirectlst *oldlisthead;
12323 {
12324         struct allocdirect *listadp, *newadp;
12325
12326         newadp = TAILQ_FIRST(newlisthead);
12327         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12328                 if (listadp->ad_offset < newadp->ad_offset) {
12329                         listadp = TAILQ_NEXT(listadp, ad_next);
12330                         continue;
12331                 }
12332                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12333                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12334                 if (listadp->ad_offset == newadp->ad_offset) {
12335                         allocdirect_merge(oldlisthead, newadp,
12336                             listadp);
12337                         listadp = newadp;
12338                 }
12339                 newadp = TAILQ_FIRST(newlisthead);
12340         }
12341         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12342                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12343                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12344         }
12345 }
12346
12347 /*
12348  * If we are doing an fsync, then we must ensure that any directory
12349  * entries for the inode have been written after the inode gets to disk.
12350  */
12351 int
12352 softdep_fsync(vp)
12353         struct vnode *vp;       /* the "in_core" copy of the inode */
12354 {
12355         struct inodedep *inodedep;
12356         struct pagedep *pagedep;
12357         struct inoref *inoref;
12358         struct ufsmount *ump;
12359         struct worklist *wk;
12360         struct diradd *dap;
12361         struct mount *mp;
12362         struct vnode *pvp;
12363         struct inode *ip;
12364         struct buf *bp;
12365         struct fs *fs;
12366         struct thread *td = curthread;
12367         int error, flushparent, pagedep_new_block;
12368         ino_t parentino;
12369         ufs_lbn_t lbn;
12370
12371         ip = VTOI(vp);
12372         mp = vp->v_mount;
12373         ump = VFSTOUFS(mp);
12374         fs = ump->um_fs;
12375         if (MOUNTEDSOFTDEP(mp) == 0)
12376                 return (0);
12377         ACQUIRE_LOCK(ump);
12378 restart:
12379         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12380                 FREE_LOCK(ump);
12381                 return (0);
12382         }
12383         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12384                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12385                     == DEPCOMPLETE) {
12386                         jwait(&inoref->if_list, MNT_WAIT);
12387                         goto restart;
12388                 }
12389         }
12390         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12391             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12392             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12393             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12394             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12395                 panic("softdep_fsync: pending ops %p", inodedep);
12396         for (error = 0, flushparent = 0; ; ) {
12397                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12398                         break;
12399                 if (wk->wk_type != D_DIRADD)
12400                         panic("softdep_fsync: Unexpected type %s",
12401                             TYPENAME(wk->wk_type));
12402                 dap = WK_DIRADD(wk);
12403                 /*
12404                  * Flush our parent if this directory entry has a MKDIR_PARENT
12405                  * dependency or is contained in a newly allocated block.
12406                  */
12407                 if (dap->da_state & DIRCHG)
12408                         pagedep = dap->da_previous->dm_pagedep;
12409                 else
12410                         pagedep = dap->da_pagedep;
12411                 parentino = pagedep->pd_ino;
12412                 lbn = pagedep->pd_lbn;
12413                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12414                         panic("softdep_fsync: dirty");
12415                 if ((dap->da_state & MKDIR_PARENT) ||
12416                     (pagedep->pd_state & NEWBLOCK))
12417                         flushparent = 1;
12418                 else
12419                         flushparent = 0;
12420                 /*
12421                  * If we are being fsync'ed as part of vgone'ing this vnode,
12422                  * then we will not be able to release and recover the
12423                  * vnode below, so we just have to give up on writing its
12424                  * directory entry out. It will eventually be written, just
12425                  * not now, but then the user was not asking to have it
12426                  * written, so we are not breaking any promises.
12427                  */
12428                 if (vp->v_iflag & VI_DOOMED)
12429                         break;
12430                 /*
12431                  * We prevent deadlock by always fetching inodes from the
12432                  * root, moving down the directory tree. Thus, when fetching
12433                  * our parent directory, we first try to get the lock. If
12434                  * that fails, we must unlock ourselves before requesting
12435                  * the lock on our parent. See the comment in ufs_lookup
12436                  * for details on possible races.
12437                  */
12438                 FREE_LOCK(ump);
12439                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12440                     FFSV_FORCEINSMQ)) {
12441                         error = vfs_busy(mp, MBF_NOWAIT);
12442                         if (error != 0) {
12443                                 vfs_ref(mp);
12444                                 VOP_UNLOCK(vp, 0);
12445                                 error = vfs_busy(mp, 0);
12446                                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12447                                 vfs_rel(mp);
12448                                 if (error != 0)
12449                                         return (ENOENT);
12450                                 if (vp->v_iflag & VI_DOOMED) {
12451                                         vfs_unbusy(mp);
12452                                         return (ENOENT);
12453                                 }
12454                         }
12455                         VOP_UNLOCK(vp, 0);
12456                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12457                             &pvp, FFSV_FORCEINSMQ);
12458                         vfs_unbusy(mp);
12459                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12460                         if (vp->v_iflag & VI_DOOMED) {
12461                                 if (error == 0)
12462                                         vput(pvp);
12463                                 error = ENOENT;
12464                         }
12465                         if (error != 0)
12466                                 return (error);
12467                 }
12468                 /*
12469                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12470                  * that are contained in direct blocks will be resolved by 
12471                  * doing a ffs_update. Pagedeps contained in indirect blocks
12472                  * may require a complete sync'ing of the directory. So, we
12473                  * try the cheap and fast ffs_update first, and if that fails,
12474                  * then we do the slower ffs_syncvnode of the directory.
12475                  */
12476                 if (flushparent) {
12477                         int locked;
12478
12479                         if ((error = ffs_update(pvp, 1)) != 0) {
12480                                 vput(pvp);
12481                                 return (error);
12482                         }
12483                         ACQUIRE_LOCK(ump);
12484                         locked = 1;
12485                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12486                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12487                                         if (wk->wk_type != D_DIRADD)
12488                                                 panic("softdep_fsync: Unexpected type %s",
12489                                                       TYPENAME(wk->wk_type));
12490                                         dap = WK_DIRADD(wk);
12491                                         if (dap->da_state & DIRCHG)
12492                                                 pagedep = dap->da_previous->dm_pagedep;
12493                                         else
12494                                                 pagedep = dap->da_pagedep;
12495                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12496                                         FREE_LOCK(ump);
12497                                         locked = 0;
12498                                         if (pagedep_new_block && (error =
12499                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12500                                                 vput(pvp);
12501                                                 return (error);
12502                                         }
12503                                 }
12504                         }
12505                         if (locked)
12506                                 FREE_LOCK(ump);
12507                 }
12508                 /*
12509                  * Flush directory page containing the inode's name.
12510                  */
12511                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12512                     &bp);
12513                 if (error == 0)
12514                         error = bwrite(bp);
12515                 else
12516                         brelse(bp);
12517                 vput(pvp);
12518                 if (error != 0)
12519                         return (error);
12520                 ACQUIRE_LOCK(ump);
12521                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12522                         break;
12523         }
12524         FREE_LOCK(ump);
12525         return (0);
12526 }
12527
12528 /*
12529  * Flush all the dirty bitmaps associated with the block device
12530  * before flushing the rest of the dirty blocks so as to reduce
12531  * the number of dependencies that will have to be rolled back.
12532  *
12533  * XXX Unused?
12534  */
12535 void
12536 softdep_fsync_mountdev(vp)
12537         struct vnode *vp;
12538 {
12539         struct buf *bp, *nbp;
12540         struct worklist *wk;
12541         struct bufobj *bo;
12542
12543         if (!vn_isdisk(vp, NULL))
12544                 panic("softdep_fsync_mountdev: vnode not a disk");
12545         bo = &vp->v_bufobj;
12546 restart:
12547         BO_LOCK(bo);
12548         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12549                 /* 
12550                  * If it is already scheduled, skip to the next buffer.
12551                  */
12552                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12553                         continue;
12554
12555                 if ((bp->b_flags & B_DELWRI) == 0)
12556                         panic("softdep_fsync_mountdev: not dirty");
12557                 /*
12558                  * We are only interested in bitmaps with outstanding
12559                  * dependencies.
12560                  */
12561                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12562                     wk->wk_type != D_BMSAFEMAP ||
12563                     (bp->b_vflags & BV_BKGRDINPROG)) {
12564                         BUF_UNLOCK(bp);
12565                         continue;
12566                 }
12567                 BO_UNLOCK(bo);
12568                 bremfree(bp);
12569                 (void) bawrite(bp);
12570                 goto restart;
12571         }
12572         drain_output(vp);
12573         BO_UNLOCK(bo);
12574 }
12575
12576 /*
12577  * Sync all cylinder groups that were dirty at the time this function is
12578  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12579  * is used to flush freedep activity that may be holding up writes to a
12580  * indirect block.
12581  */
12582 static int
12583 sync_cgs(mp, waitfor)
12584         struct mount *mp;
12585         int waitfor;
12586 {
12587         struct bmsafemap *bmsafemap;
12588         struct bmsafemap *sentinel;
12589         struct ufsmount *ump;
12590         struct buf *bp;
12591         int error;
12592
12593         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12594         sentinel->sm_cg = -1;
12595         ump = VFSTOUFS(mp);
12596         error = 0;
12597         ACQUIRE_LOCK(ump);
12598         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12599         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12600             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12601                 /* Skip sentinels and cgs with no work to release. */
12602                 if (bmsafemap->sm_cg == -1 ||
12603                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12604                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12605                         LIST_REMOVE(sentinel, sm_next);
12606                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12607                         continue;
12608                 }
12609                 /*
12610                  * If we don't get the lock and we're waiting try again, if
12611                  * not move on to the next buf and try to sync it.
12612                  */
12613                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12614                 if (bp == NULL && waitfor == MNT_WAIT)
12615                         continue;
12616                 LIST_REMOVE(sentinel, sm_next);
12617                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12618                 if (bp == NULL)
12619                         continue;
12620                 FREE_LOCK(ump);
12621                 if (waitfor == MNT_NOWAIT)
12622                         bawrite(bp);
12623                 else
12624                         error = bwrite(bp);
12625                 ACQUIRE_LOCK(ump);
12626                 if (error)
12627                         break;
12628         }
12629         LIST_REMOVE(sentinel, sm_next);
12630         FREE_LOCK(ump);
12631         free(sentinel, M_BMSAFEMAP);
12632         return (error);
12633 }
12634
12635 /*
12636  * This routine is called when we are trying to synchronously flush a
12637  * file. This routine must eliminate any filesystem metadata dependencies
12638  * so that the syncing routine can succeed.
12639  */
12640 int
12641 softdep_sync_metadata(struct vnode *vp)
12642 {
12643         struct inode *ip;
12644         int error;
12645
12646         ip = VTOI(vp);
12647         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12648             ("softdep_sync_metadata called on non-softdep filesystem"));
12649         /*
12650          * Ensure that any direct block dependencies have been cleared,
12651          * truncations are started, and inode references are journaled.
12652          */
12653         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12654         /*
12655          * Write all journal records to prevent rollbacks on devvp.
12656          */
12657         if (vp->v_type == VCHR)
12658                 softdep_flushjournal(vp->v_mount);
12659         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12660         /*
12661          * Ensure that all truncates are written so we won't find deps on
12662          * indirect blocks.
12663          */
12664         process_truncates(vp);
12665         FREE_LOCK(VFSTOUFS(vp->v_mount));
12666
12667         return (error);
12668 }
12669
12670 /*
12671  * This routine is called when we are attempting to sync a buf with
12672  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12673  * other IO it can but returns EBUSY if the buffer is not yet able to
12674  * be written.  Dependencies which will not cause rollbacks will always
12675  * return 0.
12676  */
12677 int
12678 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12679 {
12680         struct indirdep *indirdep;
12681         struct pagedep *pagedep;
12682         struct allocindir *aip;
12683         struct newblk *newblk;
12684         struct ufsmount *ump;
12685         struct buf *nbp;
12686         struct worklist *wk;
12687         int i, error;
12688
12689         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12690             ("softdep_sync_buf called on non-softdep filesystem"));
12691         /*
12692          * For VCHR we just don't want to force flush any dependencies that
12693          * will cause rollbacks.
12694          */
12695         if (vp->v_type == VCHR) {
12696                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12697                         return (EBUSY);
12698                 return (0);
12699         }
12700         ump = VFSTOUFS(vp->v_mount);
12701         ACQUIRE_LOCK(ump);
12702         /*
12703          * As we hold the buffer locked, none of its dependencies
12704          * will disappear.
12705          */
12706         error = 0;
12707 top:
12708         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12709                 switch (wk->wk_type) {
12710
12711                 case D_ALLOCDIRECT:
12712                 case D_ALLOCINDIR:
12713                         newblk = WK_NEWBLK(wk);
12714                         if (newblk->nb_jnewblk != NULL) {
12715                                 if (waitfor == MNT_NOWAIT) {
12716                                         error = EBUSY;
12717                                         goto out_unlock;
12718                                 }
12719                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12720                                 goto top;
12721                         }
12722                         if (newblk->nb_state & DEPCOMPLETE ||
12723                             waitfor == MNT_NOWAIT)
12724                                 continue;
12725                         nbp = newblk->nb_bmsafemap->sm_buf;
12726                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12727                         if (nbp == NULL)
12728                                 goto top;
12729                         FREE_LOCK(ump);
12730                         if ((error = bwrite(nbp)) != 0)
12731                                 goto out;
12732                         ACQUIRE_LOCK(ump);
12733                         continue;
12734
12735                 case D_INDIRDEP:
12736                         indirdep = WK_INDIRDEP(wk);
12737                         if (waitfor == MNT_NOWAIT) {
12738                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12739                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12740                                         error = EBUSY;
12741                                         goto out_unlock;
12742                                 }
12743                         }
12744                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12745                                 panic("softdep_sync_buf: truncation pending.");
12746                 restart:
12747                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12748                                 newblk = (struct newblk *)aip;
12749                                 if (newblk->nb_jnewblk != NULL) {
12750                                         jwait(&newblk->nb_jnewblk->jn_list,
12751                                             waitfor);
12752                                         goto restart;
12753                                 }
12754                                 if (newblk->nb_state & DEPCOMPLETE)
12755                                         continue;
12756                                 nbp = newblk->nb_bmsafemap->sm_buf;
12757                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12758                                 if (nbp == NULL)
12759                                         goto restart;
12760                                 FREE_LOCK(ump);
12761                                 if ((error = bwrite(nbp)) != 0)
12762                                         goto out;
12763                                 ACQUIRE_LOCK(ump);
12764                                 goto restart;
12765                         }
12766                         continue;
12767
12768                 case D_PAGEDEP:
12769                         /*
12770                          * Only flush directory entries in synchronous passes.
12771                          */
12772                         if (waitfor != MNT_WAIT) {
12773                                 error = EBUSY;
12774                                 goto out_unlock;
12775                         }
12776                         /*
12777                          * While syncing snapshots, we must allow recursive
12778                          * lookups.
12779                          */
12780                         BUF_AREC(bp);
12781                         /*
12782                          * We are trying to sync a directory that may
12783                          * have dependencies on both its own metadata
12784                          * and/or dependencies on the inodes of any
12785                          * recently allocated files. We walk its diradd
12786                          * lists pushing out the associated inode.
12787                          */
12788                         pagedep = WK_PAGEDEP(wk);
12789                         for (i = 0; i < DAHASHSZ; i++) {
12790                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12791                                         continue;
12792                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12793                                     &pagedep->pd_diraddhd[i]))) {
12794                                         BUF_NOREC(bp);
12795                                         goto out_unlock;
12796                                 }
12797                         }
12798                         BUF_NOREC(bp);
12799                         continue;
12800
12801                 case D_FREEWORK:
12802                 case D_FREEDEP:
12803                 case D_JSEGDEP:
12804                 case D_JNEWBLK:
12805                         continue;
12806
12807                 default:
12808                         panic("softdep_sync_buf: Unknown type %s",
12809                             TYPENAME(wk->wk_type));
12810                         /* NOTREACHED */
12811                 }
12812         }
12813 out_unlock:
12814         FREE_LOCK(ump);
12815 out:
12816         return (error);
12817 }
12818
12819 /*
12820  * Flush the dependencies associated with an inodedep.
12821  * Called with splbio blocked.
12822  */
12823 static int
12824 flush_inodedep_deps(vp, mp, ino)
12825         struct vnode *vp;
12826         struct mount *mp;
12827         ino_t ino;
12828 {
12829         struct inodedep *inodedep;
12830         struct inoref *inoref;
12831         struct ufsmount *ump;
12832         int error, waitfor;
12833
12834         /*
12835          * This work is done in two passes. The first pass grabs most
12836          * of the buffers and begins asynchronously writing them. The
12837          * only way to wait for these asynchronous writes is to sleep
12838          * on the filesystem vnode which may stay busy for a long time
12839          * if the filesystem is active. So, instead, we make a second
12840          * pass over the dependencies blocking on each write. In the
12841          * usual case we will be blocking against a write that we
12842          * initiated, so when it is done the dependency will have been
12843          * resolved. Thus the second pass is expected to end quickly.
12844          * We give a brief window at the top of the loop to allow
12845          * any pending I/O to complete.
12846          */
12847         ump = VFSTOUFS(mp);
12848         LOCK_OWNED(ump);
12849         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12850                 if (error)
12851                         return (error);
12852                 FREE_LOCK(ump);
12853                 ACQUIRE_LOCK(ump);
12854 restart:
12855                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12856                         return (0);
12857                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12858                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12859                             == DEPCOMPLETE) {
12860                                 jwait(&inoref->if_list, MNT_WAIT);
12861                                 goto restart;
12862                         }
12863                 }
12864                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12865                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12866                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12867                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12868                         continue;
12869                 /*
12870                  * If pass2, we are done, otherwise do pass 2.
12871                  */
12872                 if (waitfor == MNT_WAIT)
12873                         break;
12874                 waitfor = MNT_WAIT;
12875         }
12876         /*
12877          * Try freeing inodedep in case all dependencies have been removed.
12878          */
12879         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12880                 (void) free_inodedep(inodedep);
12881         return (0);
12882 }
12883
12884 /*
12885  * Flush an inode dependency list.
12886  * Called with splbio blocked.
12887  */
12888 static int
12889 flush_deplist(listhead, waitfor, errorp)
12890         struct allocdirectlst *listhead;
12891         int waitfor;
12892         int *errorp;
12893 {
12894         struct allocdirect *adp;
12895         struct newblk *newblk;
12896         struct ufsmount *ump;
12897         struct buf *bp;
12898
12899         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12900                 return (0);
12901         ump = VFSTOUFS(adp->ad_list.wk_mp);
12902         LOCK_OWNED(ump);
12903         TAILQ_FOREACH(adp, listhead, ad_next) {
12904                 newblk = (struct newblk *)adp;
12905                 if (newblk->nb_jnewblk != NULL) {
12906                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12907                         return (1);
12908                 }
12909                 if (newblk->nb_state & DEPCOMPLETE)
12910                         continue;
12911                 bp = newblk->nb_bmsafemap->sm_buf;
12912                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12913                 if (bp == NULL) {
12914                         if (waitfor == MNT_NOWAIT)
12915                                 continue;
12916                         return (1);
12917                 }
12918                 FREE_LOCK(ump);
12919                 if (waitfor == MNT_NOWAIT)
12920                         bawrite(bp);
12921                 else 
12922                         *errorp = bwrite(bp);
12923                 ACQUIRE_LOCK(ump);
12924                 return (1);
12925         }
12926         return (0);
12927 }
12928
12929 /*
12930  * Flush dependencies associated with an allocdirect block.
12931  */
12932 static int
12933 flush_newblk_dep(vp, mp, lbn)
12934         struct vnode *vp;
12935         struct mount *mp;
12936         ufs_lbn_t lbn;
12937 {
12938         struct newblk *newblk;
12939         struct ufsmount *ump;
12940         struct bufobj *bo;
12941         struct inode *ip;
12942         struct buf *bp;
12943         ufs2_daddr_t blkno;
12944         int error;
12945
12946         error = 0;
12947         bo = &vp->v_bufobj;
12948         ip = VTOI(vp);
12949         blkno = DIP(ip, i_db[lbn]);
12950         if (blkno == 0)
12951                 panic("flush_newblk_dep: Missing block");
12952         ump = VFSTOUFS(mp);
12953         ACQUIRE_LOCK(ump);
12954         /*
12955          * Loop until all dependencies related to this block are satisfied.
12956          * We must be careful to restart after each sleep in case a write
12957          * completes some part of this process for us.
12958          */
12959         for (;;) {
12960                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12961                         FREE_LOCK(ump);
12962                         break;
12963                 }
12964                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12965                         panic("flush_newblk_dep: Bad newblk %p", newblk);
12966                 /*
12967                  * Flush the journal.
12968                  */
12969                 if (newblk->nb_jnewblk != NULL) {
12970                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12971                         continue;
12972                 }
12973                 /*
12974                  * Write the bitmap dependency.
12975                  */
12976                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12977                         bp = newblk->nb_bmsafemap->sm_buf;
12978                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12979                         if (bp == NULL)
12980                                 continue;
12981                         FREE_LOCK(ump);
12982                         error = bwrite(bp);
12983                         if (error)
12984                                 break;
12985                         ACQUIRE_LOCK(ump);
12986                         continue;
12987                 }
12988                 /*
12989                  * Write the buffer.
12990                  */
12991                 FREE_LOCK(ump);
12992                 BO_LOCK(bo);
12993                 bp = gbincore(bo, lbn);
12994                 if (bp != NULL) {
12995                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12996                             LK_INTERLOCK, BO_LOCKPTR(bo));
12997                         if (error == ENOLCK) {
12998                                 ACQUIRE_LOCK(ump);
12999                                 error = 0;
13000                                 continue; /* Slept, retry */
13001                         }
13002                         if (error != 0)
13003                                 break;  /* Failed */
13004                         if (bp->b_flags & B_DELWRI) {
13005                                 bremfree(bp);
13006                                 error = bwrite(bp);
13007                                 if (error)
13008                                         break;
13009                         } else
13010                                 BUF_UNLOCK(bp);
13011                 } else
13012                         BO_UNLOCK(bo);
13013                 /*
13014                  * We have to wait for the direct pointers to
13015                  * point at the newdirblk before the dependency
13016                  * will go away.
13017                  */
13018                 error = ffs_update(vp, 1);
13019                 if (error)
13020                         break;
13021                 ACQUIRE_LOCK(ump);
13022         }
13023         return (error);
13024 }
13025
13026 /*
13027  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13028  * Called with splbio blocked.
13029  */
13030 static int
13031 flush_pagedep_deps(pvp, mp, diraddhdp)
13032         struct vnode *pvp;
13033         struct mount *mp;
13034         struct diraddhd *diraddhdp;
13035 {
13036         struct inodedep *inodedep;
13037         struct inoref *inoref;
13038         struct ufsmount *ump;
13039         struct diradd *dap;
13040         struct vnode *vp;
13041         int error = 0;
13042         struct buf *bp;
13043         ino_t inum;
13044         struct diraddhd unfinished;
13045
13046         LIST_INIT(&unfinished);
13047         ump = VFSTOUFS(mp);
13048         LOCK_OWNED(ump);
13049 restart:
13050         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13051                 /*
13052                  * Flush ourselves if this directory entry
13053                  * has a MKDIR_PARENT dependency.
13054                  */
13055                 if (dap->da_state & MKDIR_PARENT) {
13056                         FREE_LOCK(ump);
13057                         if ((error = ffs_update(pvp, 1)) != 0)
13058                                 break;
13059                         ACQUIRE_LOCK(ump);
13060                         /*
13061                          * If that cleared dependencies, go on to next.
13062                          */
13063                         if (dap != LIST_FIRST(diraddhdp))
13064                                 continue;
13065                         /*
13066                          * All MKDIR_PARENT dependencies and all the
13067                          * NEWBLOCK pagedeps that are contained in direct
13068                          * blocks were resolved by doing above ffs_update.
13069                          * Pagedeps contained in indirect blocks may
13070                          * require a complete sync'ing of the directory.
13071                          * We are in the midst of doing a complete sync,
13072                          * so if they are not resolved in this pass we
13073                          * defer them for now as they will be sync'ed by
13074                          * our caller shortly.
13075                          */
13076                         LIST_REMOVE(dap, da_pdlist);
13077                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13078                         continue;
13079                 }
13080                 /*
13081                  * A newly allocated directory must have its "." and
13082                  * ".." entries written out before its name can be
13083                  * committed in its parent. 
13084                  */
13085                 inum = dap->da_newinum;
13086                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13087                         panic("flush_pagedep_deps: lost inode1");
13088                 /*
13089                  * Wait for any pending journal adds to complete so we don't
13090                  * cause rollbacks while syncing.
13091                  */
13092                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13093                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13094                             == DEPCOMPLETE) {
13095                                 jwait(&inoref->if_list, MNT_WAIT);
13096                                 goto restart;
13097                         }
13098                 }
13099                 if (dap->da_state & MKDIR_BODY) {
13100                         FREE_LOCK(ump);
13101                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13102                             FFSV_FORCEINSMQ)))
13103                                 break;
13104                         error = flush_newblk_dep(vp, mp, 0);
13105                         /*
13106                          * If we still have the dependency we might need to
13107                          * update the vnode to sync the new link count to
13108                          * disk.
13109                          */
13110                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13111                                 error = ffs_update(vp, 1);
13112                         vput(vp);
13113                         if (error != 0)
13114                                 break;
13115                         ACQUIRE_LOCK(ump);
13116                         /*
13117                          * If that cleared dependencies, go on to next.
13118                          */
13119                         if (dap != LIST_FIRST(diraddhdp))
13120                                 continue;
13121                         if (dap->da_state & MKDIR_BODY) {
13122                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13123                                     &inodedep);
13124                                 panic("flush_pagedep_deps: MKDIR_BODY "
13125                                     "inodedep %p dap %p vp %p",
13126                                     inodedep, dap, vp);
13127                         }
13128                 }
13129                 /*
13130                  * Flush the inode on which the directory entry depends.
13131                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13132                  * the only remaining dependency is that the updated inode
13133                  * count must get pushed to disk. The inode has already
13134                  * been pushed into its inode buffer (via VOP_UPDATE) at
13135                  * the time of the reference count change. So we need only
13136                  * locate that buffer, ensure that there will be no rollback
13137                  * caused by a bitmap dependency, then write the inode buffer.
13138                  */
13139 retry:
13140                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13141                         panic("flush_pagedep_deps: lost inode");
13142                 /*
13143                  * If the inode still has bitmap dependencies,
13144                  * push them to disk.
13145                  */
13146                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13147                         bp = inodedep->id_bmsafemap->sm_buf;
13148                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13149                         if (bp == NULL)
13150                                 goto retry;
13151                         FREE_LOCK(ump);
13152                         if ((error = bwrite(bp)) != 0)
13153                                 break;
13154                         ACQUIRE_LOCK(ump);
13155                         if (dap != LIST_FIRST(diraddhdp))
13156                                 continue;
13157                 }
13158                 /*
13159                  * If the inode is still sitting in a buffer waiting
13160                  * to be written or waiting for the link count to be
13161                  * adjusted update it here to flush it to disk.
13162                  */
13163                 if (dap == LIST_FIRST(diraddhdp)) {
13164                         FREE_LOCK(ump);
13165                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13166                             FFSV_FORCEINSMQ)))
13167                                 break;
13168                         error = ffs_update(vp, 1);
13169                         vput(vp);
13170                         if (error)
13171                                 break;
13172                         ACQUIRE_LOCK(ump);
13173                 }
13174                 /*
13175                  * If we have failed to get rid of all the dependencies
13176                  * then something is seriously wrong.
13177                  */
13178                 if (dap == LIST_FIRST(diraddhdp)) {
13179                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13180                         panic("flush_pagedep_deps: failed to flush " 
13181                             "inodedep %p ino %ju dap %p",
13182                             inodedep, (uintmax_t)inum, dap);
13183                 }
13184         }
13185         if (error)
13186                 ACQUIRE_LOCK(ump);
13187         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13188                 LIST_REMOVE(dap, da_pdlist);
13189                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13190         }
13191         return (error);
13192 }
13193
13194 /*
13195  * A large burst of file addition or deletion activity can drive the
13196  * memory load excessively high. First attempt to slow things down
13197  * using the techniques below. If that fails, this routine requests
13198  * the offending operations to fall back to running synchronously
13199  * until the memory load returns to a reasonable level.
13200  */
13201 int
13202 softdep_slowdown(vp)
13203         struct vnode *vp;
13204 {
13205         struct ufsmount *ump;
13206         int jlow;
13207         int max_softdeps_hard;
13208
13209         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13210             ("softdep_slowdown called on non-softdep filesystem"));
13211         ump = VFSTOUFS(vp->v_mount);
13212         ACQUIRE_LOCK(ump);
13213         jlow = 0;
13214         /*
13215          * Check for journal space if needed.
13216          */
13217         if (DOINGSUJ(vp)) {
13218                 if (journal_space(ump, 0) == 0)
13219                         jlow = 1;
13220         }
13221         /*
13222          * If the system is under its limits and our filesystem is
13223          * not responsible for more than our share of the usage and
13224          * we are not low on journal space, then no need to slow down.
13225          */
13226         max_softdeps_hard = max_softdeps * 11 / 10;
13227         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13228             dep_current[D_INODEDEP] < max_softdeps_hard &&
13229             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13230             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13231             ump->softdep_curdeps[D_DIRREM] <
13232             (max_softdeps_hard / 2) / stat_flush_threads &&
13233             ump->softdep_curdeps[D_INODEDEP] <
13234             max_softdeps_hard / stat_flush_threads &&
13235             ump->softdep_curdeps[D_INDIRDEP] <
13236             (max_softdeps_hard / 1000) / stat_flush_threads &&
13237             ump->softdep_curdeps[D_FREEBLKS] <
13238             max_softdeps_hard / stat_flush_threads) {
13239                 FREE_LOCK(ump);
13240                 return (0);
13241         }
13242         /*
13243          * If the journal is low or our filesystem is over its limit
13244          * then speedup the cleanup.
13245          */
13246         if (ump->softdep_curdeps[D_INDIRDEP] <
13247             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13248                 softdep_speedup(ump);
13249         stat_sync_limit_hit += 1;
13250         FREE_LOCK(ump);
13251         /*
13252          * We only slow down the rate at which new dependencies are
13253          * generated if we are not using journaling. With journaling,
13254          * the cleanup should always be sufficient to keep things
13255          * under control.
13256          */
13257         if (DOINGSUJ(vp))
13258                 return (0);
13259         return (1);
13260 }
13261
13262 /*
13263  * Called by the allocation routines when they are about to fail
13264  * in the hope that we can free up the requested resource (inodes
13265  * or disk space).
13266  * 
13267  * First check to see if the work list has anything on it. If it has,
13268  * clean up entries until we successfully free the requested resource.
13269  * Because this process holds inodes locked, we cannot handle any remove
13270  * requests that might block on a locked inode as that could lead to
13271  * deadlock. If the worklist yields none of the requested resource,
13272  * start syncing out vnodes to free up the needed space.
13273  */
13274 int
13275 softdep_request_cleanup(fs, vp, cred, resource)
13276         struct fs *fs;
13277         struct vnode *vp;
13278         struct ucred *cred;
13279         int resource;
13280 {
13281         struct ufsmount *ump;
13282         struct mount *mp;
13283         long starttime;
13284         ufs2_daddr_t needed;
13285         int error, failed_vnode;
13286
13287         /*
13288          * If we are being called because of a process doing a
13289          * copy-on-write, then it is not safe to process any
13290          * worklist items as we will recurse into the copyonwrite
13291          * routine.  This will result in an incoherent snapshot.
13292          * If the vnode that we hold is a snapshot, we must avoid
13293          * handling other resources that could cause deadlock.
13294          */
13295         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13296                 return (0);
13297
13298         if (resource == FLUSH_BLOCKS_WAIT)
13299                 stat_cleanup_blkrequests += 1;
13300         else
13301                 stat_cleanup_inorequests += 1;
13302
13303         mp = vp->v_mount;
13304         ump = VFSTOUFS(mp);
13305         mtx_assert(UFS_MTX(ump), MA_OWNED);
13306         UFS_UNLOCK(ump);
13307         error = ffs_update(vp, 1);
13308         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13309                 UFS_LOCK(ump);
13310                 return (0);
13311         }
13312         /*
13313          * If we are in need of resources, start by cleaning up
13314          * any block removals associated with our inode.
13315          */
13316         ACQUIRE_LOCK(ump);
13317         process_removes(vp);
13318         process_truncates(vp);
13319         FREE_LOCK(ump);
13320         /*
13321          * Now clean up at least as many resources as we will need.
13322          *
13323          * When requested to clean up inodes, the number that are needed
13324          * is set by the number of simultaneous writers (mnt_writeopcount)
13325          * plus a bit of slop (2) in case some more writers show up while
13326          * we are cleaning.
13327          *
13328          * When requested to free up space, the amount of space that
13329          * we need is enough blocks to allocate a full-sized segment
13330          * (fs_contigsumsize). The number of such segments that will
13331          * be needed is set by the number of simultaneous writers
13332          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13333          * writers show up while we are cleaning.
13334          *
13335          * Additionally, if we are unpriviledged and allocating space,
13336          * we need to ensure that we clean up enough blocks to get the
13337          * needed number of blocks over the threshold of the minimum
13338          * number of blocks required to be kept free by the filesystem
13339          * (fs_minfree).
13340          */
13341         if (resource == FLUSH_INODES_WAIT) {
13342                 needed = vp->v_mount->mnt_writeopcount + 2;
13343         } else if (resource == FLUSH_BLOCKS_WAIT) {
13344                 needed = (vp->v_mount->mnt_writeopcount + 2) *
13345                     fs->fs_contigsumsize;
13346                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13347                         needed += fragstoblks(fs,
13348                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13349                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13350         } else {
13351                 UFS_LOCK(ump);
13352                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13353                     resource);
13354                 return (0);
13355         }
13356         starttime = time_second;
13357 retry:
13358         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13359             fs->fs_cstotal.cs_nbfree <= needed) ||
13360             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13361             fs->fs_cstotal.cs_nifree <= needed)) {
13362                 ACQUIRE_LOCK(ump);
13363                 if (ump->softdep_on_worklist > 0 &&
13364                     process_worklist_item(UFSTOVFS(ump),
13365                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13366                         stat_worklist_push += 1;
13367                 FREE_LOCK(ump);
13368         }
13369         /*
13370          * If we still need resources and there are no more worklist
13371          * entries to process to obtain them, we have to start flushing
13372          * the dirty vnodes to force the release of additional requests
13373          * to the worklist that we can then process to reap addition
13374          * resources. We walk the vnodes associated with the mount point
13375          * until we get the needed worklist requests that we can reap.
13376          *
13377          * If there are several threads all needing to clean the same
13378          * mount point, only one is allowed to walk the mount list.
13379          * When several threads all try to walk the same mount list,
13380          * they end up competing with each other and often end up in
13381          * livelock. This approach ensures that forward progress is
13382          * made at the cost of occational ENOSPC errors being returned
13383          * that might otherwise have been avoided.
13384          */
13385         error = 1;
13386         if ((resource == FLUSH_BLOCKS_WAIT && 
13387              fs->fs_cstotal.cs_nbfree <= needed) ||
13388             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13389              fs->fs_cstotal.cs_nifree <= needed)) {
13390                 ACQUIRE_LOCK(ump);
13391                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13392                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13393                         FREE_LOCK(ump);
13394                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13395                         ACQUIRE_LOCK(ump);
13396                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13397                         FREE_LOCK(ump);
13398                         if (ump->softdep_on_worklist > 0) {
13399                                 stat_cleanup_retries += 1;
13400                                 if (!failed_vnode)
13401                                         goto retry;
13402                         }
13403                 } else {
13404                         FREE_LOCK(ump);
13405                         error = 0;
13406                 }
13407                 stat_cleanup_failures += 1;
13408         }
13409         if (time_second - starttime > stat_cleanup_high_delay)
13410                 stat_cleanup_high_delay = time_second - starttime;
13411         UFS_LOCK(ump);
13412         return (error);
13413 }
13414
13415 /*
13416  * Scan the vnodes for the specified mount point flushing out any
13417  * vnodes that can be locked without waiting. Finally, try to flush
13418  * the device associated with the mount point if it can be locked
13419  * without waiting.
13420  *
13421  * We return 0 if we were able to lock every vnode in our scan.
13422  * If we had to skip one or more vnodes, we return 1.
13423  */
13424 static int
13425 softdep_request_cleanup_flush(mp, ump)
13426         struct mount *mp;
13427         struct ufsmount *ump;
13428 {
13429         struct thread *td;
13430         struct vnode *lvp, *mvp;
13431         int failed_vnode;
13432
13433         failed_vnode = 0;
13434         td = curthread;
13435         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13436                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13437                         VI_UNLOCK(lvp);
13438                         continue;
13439                 }
13440                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13441                     td) != 0) {
13442                         failed_vnode = 1;
13443                         continue;
13444                 }
13445                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13446                         vput(lvp);
13447                         continue;
13448                 }
13449                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13450                 vput(lvp);
13451         }
13452         lvp = ump->um_devvp;
13453         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13454                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13455                 VOP_UNLOCK(lvp, 0);
13456         }
13457         return (failed_vnode);
13458 }
13459
13460 static bool
13461 softdep_excess_items(struct ufsmount *ump, int item)
13462 {
13463
13464         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13465         return (dep_current[item] > max_softdeps &&
13466             ump->softdep_curdeps[item] > max_softdeps /
13467             stat_flush_threads);
13468 }
13469
13470 static void
13471 schedule_cleanup(struct mount *mp)
13472 {
13473         struct ufsmount *ump;
13474         struct thread *td;
13475
13476         ump = VFSTOUFS(mp);
13477         LOCK_OWNED(ump);
13478         FREE_LOCK(ump);
13479         td = curthread;
13480         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13481             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13482                 /*
13483                  * No ast is delivered to kernel threads, so nobody
13484                  * would deref the mp.  Some kernel threads
13485                  * explicitely check for AST, e.g. NFS daemon does
13486                  * this in the serving loop.
13487                  */
13488                 return;
13489         }
13490         if (td->td_su != NULL)
13491                 vfs_rel(td->td_su);
13492         vfs_ref(mp);
13493         td->td_su = mp;
13494         thread_lock(td);
13495         td->td_flags |= TDF_ASTPENDING;
13496         thread_unlock(td);
13497 }
13498
13499 static void
13500 softdep_ast_cleanup_proc(struct thread *td)
13501 {
13502         struct mount *mp;
13503         struct ufsmount *ump;
13504         int error;
13505         bool req;
13506
13507         while ((mp = td->td_su) != NULL) {
13508                 td->td_su = NULL;
13509                 error = vfs_busy(mp, MBF_NOWAIT);
13510                 vfs_rel(mp);
13511                 if (error != 0)
13512                         return;
13513                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13514                         ump = VFSTOUFS(mp);
13515                         for (;;) {
13516                                 req = false;
13517                                 ACQUIRE_LOCK(ump);
13518                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13519                                         req = true;
13520                                         request_cleanup(mp, FLUSH_INODES);
13521                                 }
13522                                 if (softdep_excess_items(ump, D_DIRREM)) {
13523                                         req = true;
13524                                         request_cleanup(mp, FLUSH_BLOCKS);
13525                                 }
13526                                 FREE_LOCK(ump);
13527                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13528                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13529                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13530                                         error = vn_start_write(NULL, &mp,
13531                                             V_WAIT);
13532                                         if (error == 0) {
13533                                                 req = true;
13534                                                 VFS_SYNC(mp, MNT_WAIT);
13535                                                 vn_finished_write(mp);
13536                                         }
13537                                 }
13538                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13539                                         break;
13540                         }
13541                 }
13542                 vfs_unbusy(mp);
13543         }
13544         if ((mp = td->td_su) != NULL) {
13545                 td->td_su = NULL;
13546                 vfs_rel(mp);
13547         }
13548 }
13549
13550 /*
13551  * If memory utilization has gotten too high, deliberately slow things
13552  * down and speed up the I/O processing.
13553  */
13554 static int
13555 request_cleanup(mp, resource)
13556         struct mount *mp;
13557         int resource;
13558 {
13559         struct thread *td = curthread;
13560         struct ufsmount *ump;
13561
13562         ump = VFSTOUFS(mp);
13563         LOCK_OWNED(ump);
13564         /*
13565          * We never hold up the filesystem syncer or buf daemon.
13566          */
13567         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13568                 return (0);
13569         /*
13570          * First check to see if the work list has gotten backlogged.
13571          * If it has, co-opt this process to help clean up two entries.
13572          * Because this process may hold inodes locked, we cannot
13573          * handle any remove requests that might block on a locked
13574          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13575          * to avoid recursively processing the worklist.
13576          */
13577         if (ump->softdep_on_worklist > max_softdeps / 10) {
13578                 td->td_pflags |= TDP_SOFTDEP;
13579                 process_worklist_item(mp, 2, LK_NOWAIT);
13580                 td->td_pflags &= ~TDP_SOFTDEP;
13581                 stat_worklist_push += 2;
13582                 return(1);
13583         }
13584         /*
13585          * Next, we attempt to speed up the syncer process. If that
13586          * is successful, then we allow the process to continue.
13587          */
13588         if (softdep_speedup(ump) &&
13589             resource != FLUSH_BLOCKS_WAIT &&
13590             resource != FLUSH_INODES_WAIT)
13591                 return(0);
13592         /*
13593          * If we are resource constrained on inode dependencies, try
13594          * flushing some dirty inodes. Otherwise, we are constrained
13595          * by file deletions, so try accelerating flushes of directories
13596          * with removal dependencies. We would like to do the cleanup
13597          * here, but we probably hold an inode locked at this point and 
13598          * that might deadlock against one that we try to clean. So,
13599          * the best that we can do is request the syncer daemon to do
13600          * the cleanup for us.
13601          */
13602         switch (resource) {
13603
13604         case FLUSH_INODES:
13605         case FLUSH_INODES_WAIT:
13606                 ACQUIRE_GBLLOCK(&lk);
13607                 stat_ino_limit_push += 1;
13608                 req_clear_inodedeps += 1;
13609                 FREE_GBLLOCK(&lk);
13610                 stat_countp = &stat_ino_limit_hit;
13611                 break;
13612
13613         case FLUSH_BLOCKS:
13614         case FLUSH_BLOCKS_WAIT:
13615                 ACQUIRE_GBLLOCK(&lk);
13616                 stat_blk_limit_push += 1;
13617                 req_clear_remove += 1;
13618                 FREE_GBLLOCK(&lk);
13619                 stat_countp = &stat_blk_limit_hit;
13620                 break;
13621
13622         default:
13623                 panic("request_cleanup: unknown type");
13624         }
13625         /*
13626          * Hopefully the syncer daemon will catch up and awaken us.
13627          * We wait at most tickdelay before proceeding in any case.
13628          */
13629         ACQUIRE_GBLLOCK(&lk);
13630         FREE_LOCK(ump);
13631         proc_waiting += 1;
13632         if (callout_pending(&softdep_callout) == FALSE)
13633                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13634                     pause_timer, 0);
13635
13636         if ((td->td_pflags & TDP_KTHREAD) == 0)
13637                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13638         proc_waiting -= 1;
13639         FREE_GBLLOCK(&lk);
13640         ACQUIRE_LOCK(ump);
13641         return (1);
13642 }
13643
13644 /*
13645  * Awaken processes pausing in request_cleanup and clear proc_waiting
13646  * to indicate that there is no longer a timer running. Pause_timer
13647  * will be called with the global softdep mutex (&lk) locked.
13648  */
13649 static void
13650 pause_timer(arg)
13651         void *arg;
13652 {
13653
13654         GBLLOCK_OWNED(&lk);
13655         /*
13656          * The callout_ API has acquired mtx and will hold it around this
13657          * function call.
13658          */
13659         *stat_countp += proc_waiting;
13660         wakeup(&proc_waiting);
13661 }
13662
13663 /*
13664  * If requested, try removing inode or removal dependencies.
13665  */
13666 static void
13667 check_clear_deps(mp)
13668         struct mount *mp;
13669 {
13670
13671         /*
13672          * If we are suspended, it may be because of our using
13673          * too many inodedeps, so help clear them out.
13674          */
13675         if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13676                 clear_inodedeps(mp);
13677         /*
13678          * General requests for cleanup of backed up dependencies
13679          */
13680         ACQUIRE_GBLLOCK(&lk);
13681         if (req_clear_inodedeps) {
13682                 req_clear_inodedeps -= 1;
13683                 FREE_GBLLOCK(&lk);
13684                 clear_inodedeps(mp);
13685                 ACQUIRE_GBLLOCK(&lk);
13686                 wakeup(&proc_waiting);
13687         }
13688         if (req_clear_remove) {
13689                 req_clear_remove -= 1;
13690                 FREE_GBLLOCK(&lk);
13691                 clear_remove(mp);
13692                 ACQUIRE_GBLLOCK(&lk);
13693                 wakeup(&proc_waiting);
13694         }
13695         FREE_GBLLOCK(&lk);
13696 }
13697
13698 /*
13699  * Flush out a directory with at least one removal dependency in an effort to
13700  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13701  */
13702 static void
13703 clear_remove(mp)
13704         struct mount *mp;
13705 {
13706         struct pagedep_hashhead *pagedephd;
13707         struct pagedep *pagedep;
13708         struct ufsmount *ump;
13709         struct vnode *vp;
13710         struct bufobj *bo;
13711         int error, cnt;
13712         ino_t ino;
13713
13714         ump = VFSTOUFS(mp);
13715         LOCK_OWNED(ump);
13716
13717         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13718                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13719                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13720                         ump->pagedep_nextclean = 0;
13721                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13722                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13723                                 continue;
13724                         ino = pagedep->pd_ino;
13725                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13726                                 continue;
13727                         FREE_LOCK(ump);
13728
13729                         /*
13730                          * Let unmount clear deps
13731                          */
13732                         error = vfs_busy(mp, MBF_NOWAIT);
13733                         if (error != 0)
13734                                 goto finish_write;
13735                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13736                              FFSV_FORCEINSMQ);
13737                         vfs_unbusy(mp);
13738                         if (error != 0) {
13739                                 softdep_error("clear_remove: vget", error);
13740                                 goto finish_write;
13741                         }
13742                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13743                                 softdep_error("clear_remove: fsync", error);
13744                         bo = &vp->v_bufobj;
13745                         BO_LOCK(bo);
13746                         drain_output(vp);
13747                         BO_UNLOCK(bo);
13748                         vput(vp);
13749                 finish_write:
13750                         vn_finished_write(mp);
13751                         ACQUIRE_LOCK(ump);
13752                         return;
13753                 }
13754         }
13755 }
13756
13757 /*
13758  * Clear out a block of dirty inodes in an effort to reduce
13759  * the number of inodedep dependency structures.
13760  */
13761 static void
13762 clear_inodedeps(mp)
13763         struct mount *mp;
13764 {
13765         struct inodedep_hashhead *inodedephd;
13766         struct inodedep *inodedep;
13767         struct ufsmount *ump;
13768         struct vnode *vp;
13769         struct fs *fs;
13770         int error, cnt;
13771         ino_t firstino, lastino, ino;
13772
13773         ump = VFSTOUFS(mp);
13774         fs = ump->um_fs;
13775         LOCK_OWNED(ump);
13776         /*
13777          * Pick a random inode dependency to be cleared.
13778          * We will then gather up all the inodes in its block 
13779          * that have dependencies and flush them out.
13780          */
13781         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13782                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13783                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13784                         ump->inodedep_nextclean = 0;
13785                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13786                         break;
13787         }
13788         if (inodedep == NULL)
13789                 return;
13790         /*
13791          * Find the last inode in the block with dependencies.
13792          */
13793         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13794         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13795                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13796                         break;
13797         /*
13798          * Asynchronously push all but the last inode with dependencies.
13799          * Synchronously push the last inode with dependencies to ensure
13800          * that the inode block gets written to free up the inodedeps.
13801          */
13802         for (ino = firstino; ino <= lastino; ino++) {
13803                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13804                         continue;
13805                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13806                         continue;
13807                 FREE_LOCK(ump);
13808                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13809                 if (error != 0) {
13810                         vn_finished_write(mp);
13811                         ACQUIRE_LOCK(ump);
13812                         return;
13813                 }
13814                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13815                     FFSV_FORCEINSMQ)) != 0) {
13816                         softdep_error("clear_inodedeps: vget", error);
13817                         vfs_unbusy(mp);
13818                         vn_finished_write(mp);
13819                         ACQUIRE_LOCK(ump);
13820                         return;
13821                 }
13822                 vfs_unbusy(mp);
13823                 if (ino == lastino) {
13824                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13825                                 softdep_error("clear_inodedeps: fsync1", error);
13826                 } else {
13827                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13828                                 softdep_error("clear_inodedeps: fsync2", error);
13829                         BO_LOCK(&vp->v_bufobj);
13830                         drain_output(vp);
13831                         BO_UNLOCK(&vp->v_bufobj);
13832                 }
13833                 vput(vp);
13834                 vn_finished_write(mp);
13835                 ACQUIRE_LOCK(ump);
13836         }
13837 }
13838
13839 void
13840 softdep_buf_append(bp, wkhd)
13841         struct buf *bp;
13842         struct workhead *wkhd;
13843 {
13844         struct worklist *wk;
13845         struct ufsmount *ump;
13846
13847         if ((wk = LIST_FIRST(wkhd)) == NULL)
13848                 return;
13849         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13850             ("softdep_buf_append called on non-softdep filesystem"));
13851         ump = VFSTOUFS(wk->wk_mp);
13852         ACQUIRE_LOCK(ump);
13853         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13854                 WORKLIST_REMOVE(wk);
13855                 WORKLIST_INSERT(&bp->b_dep, wk);
13856         }
13857         FREE_LOCK(ump);
13858
13859 }
13860
13861 void
13862 softdep_inode_append(ip, cred, wkhd)
13863         struct inode *ip;
13864         struct ucred *cred;
13865         struct workhead *wkhd;
13866 {
13867         struct buf *bp;
13868         struct fs *fs;
13869         struct ufsmount *ump;
13870         int error;
13871
13872         ump = ITOUMP(ip);
13873         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13874             ("softdep_inode_append called on non-softdep filesystem"));
13875         fs = ump->um_fs;
13876         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13877             (int)fs->fs_bsize, cred, &bp);
13878         if (error) {
13879                 bqrelse(bp);
13880                 softdep_freework(wkhd);
13881                 return;
13882         }
13883         softdep_buf_append(bp, wkhd);
13884         bqrelse(bp);
13885 }
13886
13887 void
13888 softdep_freework(wkhd)
13889         struct workhead *wkhd;
13890 {
13891         struct worklist *wk;
13892         struct ufsmount *ump;
13893
13894         if ((wk = LIST_FIRST(wkhd)) == NULL)
13895                 return;
13896         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13897             ("softdep_freework called on non-softdep filesystem"));
13898         ump = VFSTOUFS(wk->wk_mp);
13899         ACQUIRE_LOCK(ump);
13900         handle_jwork(wkhd);
13901         FREE_LOCK(ump);
13902 }
13903
13904 static struct ufsmount *
13905 softdep_bp_to_mp(bp)
13906         struct buf *bp;
13907 {
13908         struct mount *mp;
13909         struct vnode *vp;
13910
13911         if (LIST_EMPTY(&bp->b_dep))
13912                 return (NULL);
13913         vp = bp->b_vp;
13914
13915         /*
13916          * The ump mount point is stable after we get a correct
13917          * pointer, since bp is locked and this prevents unmount from
13918          * proceeding.  But to get to it, we cannot dereference bp->b_dep
13919          * head wk_mp, because we do not yet own SU ump lock and
13920          * workitem might be freed while dereferenced.
13921          */
13922 retry:
13923         if (vp->v_type == VCHR) {
13924                 VI_LOCK(vp);
13925                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
13926                 VI_UNLOCK(vp);
13927                 if (mp == NULL)
13928                         goto retry;
13929         } else if (vp->v_type == VREG || vp->v_type == VDIR ||
13930             vp->v_type == VLNK) {
13931                 mp = vp->v_mount;
13932         } else {
13933                 return (NULL);
13934         }
13935         return (VFSTOUFS(mp));
13936 }
13937
13938 /*
13939  * Function to determine if the buffer has outstanding dependencies
13940  * that will cause a roll-back if the buffer is written. If wantcount
13941  * is set, return number of dependencies, otherwise just yes or no.
13942  */
13943 static int
13944 softdep_count_dependencies(bp, wantcount)
13945         struct buf *bp;
13946         int wantcount;
13947 {
13948         struct worklist *wk;
13949         struct ufsmount *ump;
13950         struct bmsafemap *bmsafemap;
13951         struct freework *freework;
13952         struct inodedep *inodedep;
13953         struct indirdep *indirdep;
13954         struct freeblks *freeblks;
13955         struct allocindir *aip;
13956         struct pagedep *pagedep;
13957         struct dirrem *dirrem;
13958         struct newblk *newblk;
13959         struct mkdir *mkdir;
13960         struct diradd *dap;
13961         int i, retval;
13962
13963         ump = softdep_bp_to_mp(bp);
13964         if (ump == NULL)
13965                 return (0);
13966         retval = 0;
13967         ACQUIRE_LOCK(ump);
13968         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13969                 switch (wk->wk_type) {
13970
13971                 case D_INODEDEP:
13972                         inodedep = WK_INODEDEP(wk);
13973                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13974                                 /* bitmap allocation dependency */
13975                                 retval += 1;
13976                                 if (!wantcount)
13977                                         goto out;
13978                         }
13979                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13980                                 /* direct block pointer dependency */
13981                                 retval += 1;
13982                                 if (!wantcount)
13983                                         goto out;
13984                         }
13985                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13986                                 /* direct block pointer dependency */
13987                                 retval += 1;
13988                                 if (!wantcount)
13989                                         goto out;
13990                         }
13991                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13992                                 /* Add reference dependency. */
13993                                 retval += 1;
13994                                 if (!wantcount)
13995                                         goto out;
13996                         }
13997                         continue;
13998
13999                 case D_INDIRDEP:
14000                         indirdep = WK_INDIRDEP(wk);
14001
14002                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14003                                 /* indirect truncation dependency */
14004                                 retval += 1;
14005                                 if (!wantcount)
14006                                         goto out;
14007                         }
14008
14009                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14010                                 /* indirect block pointer dependency */
14011                                 retval += 1;
14012                                 if (!wantcount)
14013                                         goto out;
14014                         }
14015                         continue;
14016
14017                 case D_PAGEDEP:
14018                         pagedep = WK_PAGEDEP(wk);
14019                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14020                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14021                                         /* Journal remove ref dependency. */
14022                                         retval += 1;
14023                                         if (!wantcount)
14024                                                 goto out;
14025                                 }
14026                         }
14027                         for (i = 0; i < DAHASHSZ; i++) {
14028
14029                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14030                                         /* directory entry dependency */
14031                                         retval += 1;
14032                                         if (!wantcount)
14033                                                 goto out;
14034                                 }
14035                         }
14036                         continue;
14037
14038                 case D_BMSAFEMAP:
14039                         bmsafemap = WK_BMSAFEMAP(wk);
14040                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14041                                 /* Add reference dependency. */
14042                                 retval += 1;
14043                                 if (!wantcount)
14044                                         goto out;
14045                         }
14046                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14047                                 /* Allocate block dependency. */
14048                                 retval += 1;
14049                                 if (!wantcount)
14050                                         goto out;
14051                         }
14052                         continue;
14053
14054                 case D_FREEBLKS:
14055                         freeblks = WK_FREEBLKS(wk);
14056                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14057                                 /* Freeblk journal dependency. */
14058                                 retval += 1;
14059                                 if (!wantcount)
14060                                         goto out;
14061                         }
14062                         continue;
14063
14064                 case D_ALLOCDIRECT:
14065                 case D_ALLOCINDIR:
14066                         newblk = WK_NEWBLK(wk);
14067                         if (newblk->nb_jnewblk) {
14068                                 /* Journal allocate dependency. */
14069                                 retval += 1;
14070                                 if (!wantcount)
14071                                         goto out;
14072                         }
14073                         continue;
14074
14075                 case D_MKDIR:
14076                         mkdir = WK_MKDIR(wk);
14077                         if (mkdir->md_jaddref) {
14078                                 /* Journal reference dependency. */
14079                                 retval += 1;
14080                                 if (!wantcount)
14081                                         goto out;
14082                         }
14083                         continue;
14084
14085                 case D_FREEWORK:
14086                 case D_FREEDEP:
14087                 case D_JSEGDEP:
14088                 case D_JSEG:
14089                 case D_SBDEP:
14090                         /* never a dependency on these blocks */
14091                         continue;
14092
14093                 default:
14094                         panic("softdep_count_dependencies: Unexpected type %s",
14095                             TYPENAME(wk->wk_type));
14096                         /* NOTREACHED */
14097                 }
14098         }
14099 out:
14100         FREE_LOCK(ump);
14101         return (retval);
14102 }
14103
14104 /*
14105  * Acquire exclusive access to a buffer.
14106  * Must be called with a locked mtx parameter.
14107  * Return acquired buffer or NULL on failure.
14108  */
14109 static struct buf *
14110 getdirtybuf(bp, lock, waitfor)
14111         struct buf *bp;
14112         struct rwlock *lock;
14113         int waitfor;
14114 {
14115         int error;
14116
14117         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14118                 if (waitfor != MNT_WAIT)
14119                         return (NULL);
14120                 error = BUF_LOCK(bp,
14121                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14122                 /*
14123                  * Even if we successfully acquire bp here, we have dropped
14124                  * lock, which may violates our guarantee.
14125                  */
14126                 if (error == 0)
14127                         BUF_UNLOCK(bp);
14128                 else if (error != ENOLCK)
14129                         panic("getdirtybuf: inconsistent lock: %d", error);
14130                 rw_wlock(lock);
14131                 return (NULL);
14132         }
14133         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14134                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14135                         rw_wunlock(lock);
14136                         BO_LOCK(bp->b_bufobj);
14137                         BUF_UNLOCK(bp);
14138                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14139                                 bp->b_vflags |= BV_BKGRDWAIT;
14140                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14141                                        PRIBIO | PDROP, "getbuf", 0);
14142                         } else
14143                                 BO_UNLOCK(bp->b_bufobj);
14144                         rw_wlock(lock);
14145                         return (NULL);
14146                 }
14147                 BUF_UNLOCK(bp);
14148                 if (waitfor != MNT_WAIT)
14149                         return (NULL);
14150 #ifdef DEBUG_VFS_LOCKS
14151                 if (bp->b_vp->v_type != VCHR)
14152                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14153 #endif
14154                 bp->b_vflags |= BV_BKGRDWAIT;
14155                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14156                 return (NULL);
14157         }
14158         if ((bp->b_flags & B_DELWRI) == 0) {
14159                 BUF_UNLOCK(bp);
14160                 return (NULL);
14161         }
14162         bremfree(bp);
14163         return (bp);
14164 }
14165
14166
14167 /*
14168  * Check if it is safe to suspend the file system now.  On entry,
14169  * the vnode interlock for devvp should be held.  Return 0 with
14170  * the mount interlock held if the file system can be suspended now,
14171  * otherwise return EAGAIN with the mount interlock held.
14172  */
14173 int
14174 softdep_check_suspend(struct mount *mp,
14175                       struct vnode *devvp,
14176                       int softdep_depcnt,
14177                       int softdep_accdepcnt,
14178                       int secondary_writes,
14179                       int secondary_accwrites)
14180 {
14181         struct bufobj *bo;
14182         struct ufsmount *ump;
14183         struct inodedep *inodedep;
14184         int error, unlinked;
14185
14186         bo = &devvp->v_bufobj;
14187         ASSERT_BO_WLOCKED(bo);
14188
14189         /*
14190          * If we are not running with soft updates, then we need only
14191          * deal with secondary writes as we try to suspend.
14192          */
14193         if (MOUNTEDSOFTDEP(mp) == 0) {
14194                 MNT_ILOCK(mp);
14195                 while (mp->mnt_secondary_writes != 0) {
14196                         BO_UNLOCK(bo);
14197                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14198                             (PUSER - 1) | PDROP, "secwr", 0);
14199                         BO_LOCK(bo);
14200                         MNT_ILOCK(mp);
14201                 }
14202
14203                 /*
14204                  * Reasons for needing more work before suspend:
14205                  * - Dirty buffers on devvp.
14206                  * - Secondary writes occurred after start of vnode sync loop
14207                  */
14208                 error = 0;
14209                 if (bo->bo_numoutput > 0 ||
14210                     bo->bo_dirty.bv_cnt > 0 ||
14211                     secondary_writes != 0 ||
14212                     mp->mnt_secondary_writes != 0 ||
14213                     secondary_accwrites != mp->mnt_secondary_accwrites)
14214                         error = EAGAIN;
14215                 BO_UNLOCK(bo);
14216                 return (error);
14217         }
14218
14219         /*
14220          * If we are running with soft updates, then we need to coordinate
14221          * with them as we try to suspend.
14222          */
14223         ump = VFSTOUFS(mp);
14224         for (;;) {
14225                 if (!TRY_ACQUIRE_LOCK(ump)) {
14226                         BO_UNLOCK(bo);
14227                         ACQUIRE_LOCK(ump);
14228                         FREE_LOCK(ump);
14229                         BO_LOCK(bo);
14230                         continue;
14231                 }
14232                 MNT_ILOCK(mp);
14233                 if (mp->mnt_secondary_writes != 0) {
14234                         FREE_LOCK(ump);
14235                         BO_UNLOCK(bo);
14236                         msleep(&mp->mnt_secondary_writes,
14237                                MNT_MTX(mp),
14238                                (PUSER - 1) | PDROP, "secwr", 0);
14239                         BO_LOCK(bo);
14240                         continue;
14241                 }
14242                 break;
14243         }
14244
14245         unlinked = 0;
14246         if (MOUNTEDSUJ(mp)) {
14247                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14248                     inodedep != NULL;
14249                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14250                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14251                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14252                             UNLINKONLIST) ||
14253                             !check_inodedep_free(inodedep))
14254                                 continue;
14255                         unlinked++;
14256                 }
14257         }
14258
14259         /*
14260          * Reasons for needing more work before suspend:
14261          * - Dirty buffers on devvp.
14262          * - Softdep activity occurred after start of vnode sync loop
14263          * - Secondary writes occurred after start of vnode sync loop
14264          */
14265         error = 0;
14266         if (bo->bo_numoutput > 0 ||
14267             bo->bo_dirty.bv_cnt > 0 ||
14268             softdep_depcnt != unlinked ||
14269             ump->softdep_deps != unlinked ||
14270             softdep_accdepcnt != ump->softdep_accdeps ||
14271             secondary_writes != 0 ||
14272             mp->mnt_secondary_writes != 0 ||
14273             secondary_accwrites != mp->mnt_secondary_accwrites)
14274                 error = EAGAIN;
14275         FREE_LOCK(ump);
14276         BO_UNLOCK(bo);
14277         return (error);
14278 }
14279
14280
14281 /*
14282  * Get the number of dependency structures for the file system, both
14283  * the current number and the total number allocated.  These will
14284  * later be used to detect that softdep processing has occurred.
14285  */
14286 void
14287 softdep_get_depcounts(struct mount *mp,
14288                       int *softdep_depsp,
14289                       int *softdep_accdepsp)
14290 {
14291         struct ufsmount *ump;
14292
14293         if (MOUNTEDSOFTDEP(mp) == 0) {
14294                 *softdep_depsp = 0;
14295                 *softdep_accdepsp = 0;
14296                 return;
14297         }
14298         ump = VFSTOUFS(mp);
14299         ACQUIRE_LOCK(ump);
14300         *softdep_depsp = ump->softdep_deps;
14301         *softdep_accdepsp = ump->softdep_accdeps;
14302         FREE_LOCK(ump);
14303 }
14304
14305 /*
14306  * Wait for pending output on a vnode to complete.
14307  */
14308 static void
14309 drain_output(vp)
14310         struct vnode *vp;
14311 {
14312
14313         ASSERT_VOP_LOCKED(vp, "drain_output");
14314         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14315 }
14316
14317 /*
14318  * Called whenever a buffer that is being invalidated or reallocated
14319  * contains dependencies. This should only happen if an I/O error has
14320  * occurred. The routine is called with the buffer locked.
14321  */ 
14322 static void
14323 softdep_deallocate_dependencies(bp)
14324         struct buf *bp;
14325 {
14326
14327         if ((bp->b_ioflags & BIO_ERROR) == 0)
14328                 panic("softdep_deallocate_dependencies: dangling deps");
14329         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14330                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14331         else
14332                 printf("softdep_deallocate_dependencies: "
14333                     "got error %d while accessing filesystem\n", bp->b_error);
14334         if (bp->b_error != ENXIO)
14335                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14336 }
14337
14338 /*
14339  * Function to handle asynchronous write errors in the filesystem.
14340  */
14341 static void
14342 softdep_error(func, error)
14343         char *func;
14344         int error;
14345 {
14346
14347         /* XXX should do something better! */
14348         printf("%s: got error %d while accessing filesystem\n", func, error);
14349 }
14350
14351 #ifdef DDB
14352
14353 static void
14354 inodedep_print(struct inodedep *inodedep, int verbose)
14355 {
14356         db_printf("%p fs %p st %x ino %jd inoblk %jd delta %jd nlink %jd"
14357             " saveino %p\n",
14358             inodedep, inodedep->id_fs, inodedep->id_state,
14359             (intmax_t)inodedep->id_ino,
14360             (intmax_t)fsbtodb(inodedep->id_fs,
14361             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14362             (intmax_t)inodedep->id_nlinkdelta,
14363             (intmax_t)inodedep->id_savednlink,
14364             inodedep->id_savedino1);
14365
14366         if (verbose == 0)
14367                 return;
14368
14369         db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14370             "mkdiradd %p\n",
14371             LIST_FIRST(&inodedep->id_pendinghd),
14372             LIST_FIRST(&inodedep->id_bufwait),
14373             LIST_FIRST(&inodedep->id_inowait),
14374             TAILQ_FIRST(&inodedep->id_inoreflst),
14375             inodedep->id_mkdiradd);
14376         db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14377             TAILQ_FIRST(&inodedep->id_inoupdt),
14378             TAILQ_FIRST(&inodedep->id_newinoupdt),
14379             TAILQ_FIRST(&inodedep->id_extupdt),
14380             TAILQ_FIRST(&inodedep->id_newextupdt));
14381 }
14382
14383 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14384 {
14385
14386         if (have_addr == 0) {
14387                 db_printf("Address required\n");
14388                 return;
14389         }
14390         inodedep_print((struct inodedep*)addr, 1);
14391 }
14392
14393 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14394 {
14395         struct inodedep_hashhead *inodedephd;
14396         struct inodedep *inodedep;
14397         struct ufsmount *ump;
14398         int cnt;
14399
14400         if (have_addr == 0) {
14401                 db_printf("Address required\n");
14402                 return;
14403         }
14404         ump = (struct ufsmount *)addr;
14405         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14406                 inodedephd = &ump->inodedep_hashtbl[cnt];
14407                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14408                         inodedep_print(inodedep, 0);
14409                 }
14410         }
14411 }
14412
14413 DB_SHOW_COMMAND(worklist, db_show_worklist)
14414 {
14415         struct worklist *wk;
14416
14417         if (have_addr == 0) {
14418                 db_printf("Address required\n");
14419                 return;
14420         }
14421         wk = (struct worklist *)addr;
14422         printf("worklist: %p type %s state 0x%X\n",
14423             wk, TYPENAME(wk->wk_type), wk->wk_state);
14424 }
14425
14426 DB_SHOW_COMMAND(workhead, db_show_workhead)
14427 {
14428         struct workhead *wkhd;
14429         struct worklist *wk;
14430         int i;
14431
14432         if (have_addr == 0) {
14433                 db_printf("Address required\n");
14434                 return;
14435         }
14436         wkhd = (struct workhead *)addr;
14437         wk = LIST_FIRST(wkhd);
14438         for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14439                 db_printf("worklist: %p type %s state 0x%X",
14440                     wk, TYPENAME(wk->wk_type), wk->wk_state);
14441         if (i == 100)
14442                 db_printf("workhead overflow");
14443         printf("\n");
14444 }
14445
14446
14447 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14448 {
14449         struct mkdirlist *mkdirlisthd;
14450         struct jaddref *jaddref;
14451         struct diradd *diradd;
14452         struct mkdir *mkdir;
14453
14454         if (have_addr == 0) {
14455                 db_printf("Address required\n");
14456                 return;
14457         }
14458         mkdirlisthd = (struct mkdirlist *)addr;
14459         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14460                 diradd = mkdir->md_diradd;
14461                 db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14462                     mkdir, mkdir->md_state, diradd, diradd->da_state);
14463                 if ((jaddref = mkdir->md_jaddref) != NULL)
14464                         db_printf(" jaddref %p jaddref state 0x%X",
14465                             jaddref, jaddref->ja_state);
14466                 db_printf("\n");
14467         }
14468 }
14469
14470 /* exported to ffs_vfsops.c */
14471 extern void db_print_ffs(struct ufsmount *ump);
14472 void
14473 db_print_ffs(struct ufsmount *ump)
14474 {
14475         db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14476             ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14477             ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14478             ump->softdep_deps, ump->softdep_req);
14479 }
14480
14481 #endif /* DDB */
14482
14483 #endif /* SOFTUPDATES */