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