]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/ufs/ffs/ffs_softdep.c
Merge ^/vendor/llvm/dist up to its last change, and resolve conflicts.
[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 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88
89 #include <geom/geom.h>
90 #include <geom/geom_vfs.h>
91
92 #include <ddb/ddb.h>
93
94 #define KTR_SUJ 0       /* Define to KTR_SPARE. */
95
96 #ifndef SOFTUPDATES
97
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100         struct mount *oldmnt;
101         int flags;
102         struct thread *td;
103 {
104
105         panic("softdep_flushfiles called");
106 }
107
108 int
109 softdep_mount(devvp, mp, fs, cred)
110         struct vnode *devvp;
111         struct mount *mp;
112         struct fs *fs;
113         struct ucred *cred;
114 {
115
116         return (0);
117 }
118
119 void
120 softdep_initialize()
121 {
122
123         return;
124 }
125
126 void
127 softdep_uninitialize()
128 {
129
130         return;
131 }
132
133 void
134 softdep_unmount(mp)
135         struct mount *mp;
136 {
137
138         panic("softdep_unmount called");
139 }
140
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143         struct ufsmount *ump;
144         struct fs *fs;
145         struct buf *bp;
146 {
147
148         panic("softdep_setup_sbupdate called");
149 }
150
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153         struct buf *bp;
154         struct inode *ip;
155         ino_t newinum;
156         int mode;
157 {
158
159         panic("softdep_setup_inomapdep called");
160 }
161
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164         struct buf *bp;
165         struct mount *mp;
166         ufs2_daddr_t newblkno;
167         int frags;
168         int oldfrags;
169 {
170
171         panic("softdep_setup_blkmapdep called");
172 }
173
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176         struct inode *ip;
177         ufs_lbn_t lbn;
178         ufs2_daddr_t newblkno;
179         ufs2_daddr_t oldblkno;
180         long newsize;
181         long oldsize;
182         struct buf *bp;
183 {
184         
185         panic("softdep_setup_allocdirect called");
186 }
187
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190         struct inode *ip;
191         ufs_lbn_t lbn;
192         ufs2_daddr_t newblkno;
193         ufs2_daddr_t oldblkno;
194         long newsize;
195         long oldsize;
196         struct buf *bp;
197 {
198         
199         panic("softdep_setup_allocext called");
200 }
201
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204         struct inode *ip;
205         ufs_lbn_t lbn;
206         struct buf *bp;
207         int ptrno;
208         ufs2_daddr_t newblkno;
209         ufs2_daddr_t oldblkno;
210         struct buf *nbp;
211 {
212
213         panic("softdep_setup_allocindir_page called");
214 }
215
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218         struct buf *nbp;
219         struct inode *ip;
220         struct buf *bp;
221         int ptrno;
222         ufs2_daddr_t newblkno;
223 {
224
225         panic("softdep_setup_allocindir_meta called");
226 }
227
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230         struct inode *ip;
231         struct ucred *cred;
232         off_t length;
233         int flags;
234 {
235         
236         panic("softdep_journal_freeblocks called");
237 }
238
239 void
240 softdep_journal_fsync(ip)
241         struct inode *ip;
242 {
243
244         panic("softdep_journal_fsync called");
245 }
246
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249         struct inode *ip;
250         off_t length;
251         int flags;
252 {
253         
254         panic("softdep_setup_freeblocks called");
255 }
256
257 void
258 softdep_freefile(pvp, ino, mode)
259                 struct vnode *pvp;
260                 ino_t ino;
261                 int mode;
262 {
263
264         panic("softdep_freefile called");
265 }
266
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269         struct buf *bp;
270         struct inode *dp;
271         off_t diroffset;
272         ino_t newinum;
273         struct buf *newdirbp;
274         int isnewblk;
275 {
276
277         panic("softdep_setup_directory_add called");
278 }
279
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282         struct buf *bp;
283         struct inode *dp;
284         caddr_t base;
285         caddr_t oldloc;
286         caddr_t newloc;
287         int entrysize;
288 {
289
290         panic("softdep_change_directoryentry_offset called");
291 }
292
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295         struct buf *bp;
296         struct inode *dp;
297         struct inode *ip;
298         int isrmdir;
299 {
300         
301         panic("softdep_setup_remove called");
302 }
303
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306         struct buf *bp;
307         struct inode *dp;
308         struct inode *ip;
309         ino_t newinum;
310         int isrmdir;
311 {
312
313         panic("softdep_setup_directory_change called");
314 }
315
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318         struct mount *mp;
319         struct buf *bp;
320         ufs2_daddr_t blkno;
321         int frags;
322         struct workhead *wkhd;
323 {
324
325         panic("%s called", __FUNCTION__);
326 }
327
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330         struct mount *mp;
331         struct buf *bp;
332         ino_t ino;
333         struct workhead *wkhd;
334 {
335
336         panic("%s called", __FUNCTION__);
337 }
338
339 void
340 softdep_setup_unlink(dp, ip)
341         struct inode *dp;
342         struct inode *ip;
343 {
344
345         panic("%s called", __FUNCTION__);
346 }
347
348 void
349 softdep_setup_link(dp, ip)
350         struct inode *dp;
351         struct inode *ip;
352 {
353
354         panic("%s called", __FUNCTION__);
355 }
356
357 void
358 softdep_revert_link(dp, ip)
359         struct inode *dp;
360         struct inode *ip;
361 {
362
363         panic("%s called", __FUNCTION__);
364 }
365
366 void
367 softdep_setup_rmdir(dp, ip)
368         struct inode *dp;
369         struct inode *ip;
370 {
371
372         panic("%s called", __FUNCTION__);
373 }
374
375 void
376 softdep_revert_rmdir(dp, ip)
377         struct inode *dp;
378         struct inode *ip;
379 {
380
381         panic("%s called", __FUNCTION__);
382 }
383
384 void
385 softdep_setup_create(dp, ip)
386         struct inode *dp;
387         struct inode *ip;
388 {
389
390         panic("%s called", __FUNCTION__);
391 }
392
393 void
394 softdep_revert_create(dp, ip)
395         struct inode *dp;
396         struct inode *ip;
397 {
398
399         panic("%s called", __FUNCTION__);
400 }
401
402 void
403 softdep_setup_mkdir(dp, ip)
404         struct inode *dp;
405         struct inode *ip;
406 {
407
408         panic("%s called", __FUNCTION__);
409 }
410
411 void
412 softdep_revert_mkdir(dp, ip)
413         struct inode *dp;
414         struct inode *ip;
415 {
416
417         panic("%s called", __FUNCTION__);
418 }
419
420 void
421 softdep_setup_dotdot_link(dp, ip)
422         struct inode *dp;
423         struct inode *ip;
424 {
425
426         panic("%s called", __FUNCTION__);
427 }
428
429 int
430 softdep_prealloc(vp, waitok)
431         struct vnode *vp;
432         int waitok;
433 {
434
435         panic("%s called", __FUNCTION__);
436 }
437
438 int
439 softdep_journal_lookup(mp, vpp)
440         struct mount *mp;
441         struct vnode **vpp;
442 {
443
444         return (ENOENT);
445 }
446
447 void
448 softdep_change_linkcnt(ip)
449         struct inode *ip;
450 {
451
452         panic("softdep_change_linkcnt called");
453 }
454
455 void 
456 softdep_load_inodeblock(ip)
457         struct inode *ip;
458 {
459
460         panic("softdep_load_inodeblock called");
461 }
462
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465         struct inode *ip;
466         struct buf *bp;
467         int waitfor;
468 {
469
470         panic("softdep_update_inodeblock called");
471 }
472
473 int
474 softdep_fsync(vp)
475         struct vnode *vp;       /* the "in_core" copy of the inode */
476 {
477
478         return (0);
479 }
480
481 void
482 softdep_fsync_mountdev(vp)
483         struct vnode *vp;
484 {
485
486         return;
487 }
488
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491         struct mount *oldmnt;
492         int *countp;
493         struct thread *td;
494 {
495
496         *countp = 0;
497         return (0);
498 }
499
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503
504         panic("softdep_sync_metadata called");
505 }
506
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510
511         panic("softdep_sync_buf called");
512 }
513
514 int
515 softdep_slowdown(vp)
516         struct vnode *vp;
517 {
518
519         panic("softdep_slowdown called");
520 }
521
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524         struct fs *fs;
525         struct vnode *vp;
526         struct ucred *cred;
527         int resource;
528 {
529
530         return (0);
531 }
532
533 int
534 softdep_check_suspend(struct mount *mp,
535                       struct vnode *devvp,
536                       int softdep_depcnt,
537                       int softdep_accdepcnt,
538                       int secondary_writes,
539                       int secondary_accwrites)
540 {
541         struct bufobj *bo;
542         int error;
543         
544         (void) softdep_depcnt,
545         (void) softdep_accdepcnt;
546
547         bo = &devvp->v_bufobj;
548         ASSERT_BO_WLOCKED(bo);
549
550         MNT_ILOCK(mp);
551         while (mp->mnt_secondary_writes != 0) {
552                 BO_UNLOCK(bo);
553                 msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554                     (PUSER - 1) | PDROP, "secwr", 0);
555                 BO_LOCK(bo);
556                 MNT_ILOCK(mp);
557         }
558
559         /*
560          * Reasons for needing more work before suspend:
561          * - Dirty buffers on devvp.
562          * - Secondary writes occurred after start of vnode sync loop
563          */
564         error = 0;
565         if (bo->bo_numoutput > 0 ||
566             bo->bo_dirty.bv_cnt > 0 ||
567             secondary_writes != 0 ||
568             mp->mnt_secondary_writes != 0 ||
569             secondary_accwrites != mp->mnt_secondary_accwrites)
570                 error = EAGAIN;
571         BO_UNLOCK(bo);
572         return (error);
573 }
574
575 void
576 softdep_get_depcounts(struct mount *mp,
577                       int *softdepactivep,
578                       int *softdepactiveaccp)
579 {
580         (void) mp;
581         *softdepactivep = 0;
582         *softdepactiveaccp = 0;
583 }
584
585 void
586 softdep_buf_append(bp, wkhd)
587         struct buf *bp;
588         struct workhead *wkhd;
589 {
590
591         panic("softdep_buf_appendwork called");
592 }
593
594 void
595 softdep_inode_append(ip, cred, wkhd)
596         struct inode *ip;
597         struct ucred *cred;
598         struct workhead *wkhd;
599 {
600
601         panic("softdep_inode_appendwork called");
602 }
603
604 void
605 softdep_freework(wkhd)
606         struct workhead *wkhd;
607 {
608
609         panic("softdep_freework called");
610 }
611
612 #else
613
614 FEATURE(softupdates, "FFS soft-updates support");
615
616 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
617     "soft updates stats");
618 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
619     "total dependencies allocated");
620 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
621     "high use dependencies allocated");
622 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
623     "current dependencies allocated");
624 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
625     "current dependencies written");
626
627 unsigned long dep_current[D_LAST + 1];
628 unsigned long dep_highuse[D_LAST + 1];
629 unsigned long dep_total[D_LAST + 1];
630 unsigned long dep_write[D_LAST + 1];
631
632 #define SOFTDEP_TYPE(type, str, long)                                   \
633     static MALLOC_DEFINE(M_ ## type, #str, long);                       \
634     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,       \
635         &dep_total[D_ ## type], 0, "");                                 \
636     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD,     \
637         &dep_current[D_ ## type], 0, "");                               \
638     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD,     \
639         &dep_highuse[D_ ## type], 0, "");                               \
640     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD,       \
641         &dep_write[D_ ## type], 0, "");
642
643 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies"); 
644 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
645 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
646     "Block or frag allocated from cyl group map");
647 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
648 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
649 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
650 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
651 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
652 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
653 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
654 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
655 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
656 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
657 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
658 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
659 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
660 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
661 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
662 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
663 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
664 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
665 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
666 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
667 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
668 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
669 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
670 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
671
672 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
673
674 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
675 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
676 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
677
678 #define M_SOFTDEP_FLAGS (M_WAITOK)
679
680 /* 
681  * translate from workitem type to memory type
682  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
683  */
684 static struct malloc_type *memtype[] = {
685         NULL,
686         M_PAGEDEP,
687         M_INODEDEP,
688         M_BMSAFEMAP,
689         M_NEWBLK,
690         M_ALLOCDIRECT,
691         M_INDIRDEP,
692         M_ALLOCINDIR,
693         M_FREEFRAG,
694         M_FREEBLKS,
695         M_FREEFILE,
696         M_DIRADD,
697         M_MKDIR,
698         M_DIRREM,
699         M_NEWDIRBLK,
700         M_FREEWORK,
701         M_FREEDEP,
702         M_JADDREF,
703         M_JREMREF,
704         M_JMVREF,
705         M_JNEWBLK,
706         M_JFREEBLK,
707         M_JFREEFRAG,
708         M_JSEG,
709         M_JSEGDEP,
710         M_SBDEP,
711         M_JTRUNC,
712         M_JFSYNC,
713         M_SENTINEL
714 };
715
716 #define DtoM(type) (memtype[type])
717
718 /*
719  * Names of malloc types.
720  */
721 #define TYPENAME(type)  \
722         ((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
723         memtype[type]->ks_shortdesc : "???")
724 /*
725  * End system adaptation definitions.
726  */
727
728 #define DOTDOT_OFFSET   offsetof(struct dirtemplate, dotdot_ino)
729 #define DOT_OFFSET      offsetof(struct dirtemplate, dot_ino)
730
731 /*
732  * Internal function prototypes.
733  */
734 static  void check_clear_deps(struct mount *);
735 static  void softdep_error(char *, int);
736 static  int softdep_process_worklist(struct mount *, int);
737 static  int softdep_waitidle(struct mount *, int);
738 static  void drain_output(struct vnode *);
739 static  struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
740 static  int check_inodedep_free(struct inodedep *);
741 static  void clear_remove(struct mount *);
742 static  void clear_inodedeps(struct mount *);
743 static  void unlinked_inodedep(struct mount *, struct inodedep *);
744 static  void clear_unlinked_inodedep(struct inodedep *);
745 static  struct inodedep *first_unlinked_inodedep(struct ufsmount *);
746 static  int flush_pagedep_deps(struct vnode *, struct mount *,
747             struct diraddhd *);
748 static  int free_pagedep(struct pagedep *);
749 static  int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
750 static  int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
751 static  int flush_deplist(struct allocdirectlst *, int, int *);
752 static  int sync_cgs(struct mount *, int);
753 static  int handle_written_filepage(struct pagedep *, struct buf *, int);
754 static  int handle_written_sbdep(struct sbdep *, struct buf *);
755 static  void initiate_write_sbdep(struct sbdep *);
756 static  void diradd_inode_written(struct diradd *, struct inodedep *);
757 static  int handle_written_indirdep(struct indirdep *, struct buf *,
758             struct buf**, int);
759 static  int handle_written_inodeblock(struct inodedep *, struct buf *, int);
760 static  int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
761             uint8_t *);
762 static  int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
763 static  void handle_written_jaddref(struct jaddref *);
764 static  void handle_written_jremref(struct jremref *);
765 static  void handle_written_jseg(struct jseg *, struct buf *);
766 static  void handle_written_jnewblk(struct jnewblk *);
767 static  void handle_written_jblkdep(struct jblkdep *);
768 static  void handle_written_jfreefrag(struct jfreefrag *);
769 static  void complete_jseg(struct jseg *);
770 static  void complete_jsegs(struct jseg *);
771 static  void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
772 static  void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
773 static  void jremref_write(struct jremref *, struct jseg *, uint8_t *);
774 static  void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
775 static  void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
776 static  void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
777 static  void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
778 static  void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
779 static  void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
780 static  inline void inoref_write(struct inoref *, struct jseg *,
781             struct jrefrec *);
782 static  void handle_allocdirect_partdone(struct allocdirect *,
783             struct workhead *);
784 static  struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
785             struct workhead *);
786 static  void indirdep_complete(struct indirdep *);
787 static  int indirblk_lookup(struct mount *, ufs2_daddr_t);
788 static  void indirblk_insert(struct freework *);
789 static  void indirblk_remove(struct freework *);
790 static  void handle_allocindir_partdone(struct allocindir *);
791 static  void initiate_write_filepage(struct pagedep *, struct buf *);
792 static  void initiate_write_indirdep(struct indirdep*, struct buf *);
793 static  void handle_written_mkdir(struct mkdir *, int);
794 static  int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
795             uint8_t *);
796 static  void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
797 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
798 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
799 static  void handle_workitem_freefile(struct freefile *);
800 static  int handle_workitem_remove(struct dirrem *, int);
801 static  struct dirrem *newdirrem(struct buf *, struct inode *,
802             struct inode *, int, struct dirrem **);
803 static  struct indirdep *indirdep_lookup(struct mount *, struct inode *,
804             struct buf *);
805 static  void cancel_indirdep(struct indirdep *, struct buf *,
806             struct freeblks *);
807 static  void free_indirdep(struct indirdep *);
808 static  void free_diradd(struct diradd *, struct workhead *);
809 static  void merge_diradd(struct inodedep *, struct diradd *);
810 static  void complete_diradd(struct diradd *);
811 static  struct diradd *diradd_lookup(struct pagedep *, int);
812 static  struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
813             struct jremref *);
814 static  struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
815             struct jremref *);
816 static  void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
817             struct jremref *, struct jremref *);
818 static  void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
819             struct jremref *);
820 static  void cancel_allocindir(struct allocindir *, struct buf *bp,
821             struct freeblks *, int);
822 static  int setup_trunc_indir(struct freeblks *, struct inode *,
823             ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
824 static  void complete_trunc_indir(struct freework *);
825 static  void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
826             int);
827 static  void complete_mkdir(struct mkdir *);
828 static  void free_newdirblk(struct newdirblk *);
829 static  void free_jremref(struct jremref *);
830 static  void free_jaddref(struct jaddref *);
831 static  void free_jsegdep(struct jsegdep *);
832 static  void free_jsegs(struct jblocks *);
833 static  void rele_jseg(struct jseg *);
834 static  void free_jseg(struct jseg *, struct jblocks *);
835 static  void free_jnewblk(struct jnewblk *);
836 static  void free_jblkdep(struct jblkdep *);
837 static  void free_jfreefrag(struct jfreefrag *);
838 static  void free_freedep(struct freedep *);
839 static  void journal_jremref(struct dirrem *, struct jremref *,
840             struct inodedep *);
841 static  void cancel_jnewblk(struct jnewblk *, struct workhead *);
842 static  int cancel_jaddref(struct jaddref *, struct inodedep *,
843             struct workhead *);
844 static  void cancel_jfreefrag(struct jfreefrag *);
845 static  inline void setup_freedirect(struct freeblks *, struct inode *,
846             int, int);
847 static  inline void setup_freeext(struct freeblks *, struct inode *, int, int);
848 static  inline void setup_freeindir(struct freeblks *, struct inode *, int,
849             ufs_lbn_t, int);
850 static  inline struct freeblks *newfreeblks(struct mount *, struct inode *);
851 static  void freeblks_free(struct ufsmount *, struct freeblks *, int);
852 static  void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
853 static  ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
854 static  int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
855 static  void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
856             int, int);
857 static  void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
858 static  int cancel_pagedep(struct pagedep *, struct freeblks *, int);
859 static  int deallocate_dependencies(struct buf *, struct freeblks *, int);
860 static  void newblk_freefrag(struct newblk*);
861 static  void free_newblk(struct newblk *);
862 static  void cancel_allocdirect(struct allocdirectlst *,
863             struct allocdirect *, struct freeblks *);
864 static  int check_inode_unwritten(struct inodedep *);
865 static  int free_inodedep(struct inodedep *);
866 static  void freework_freeblock(struct freework *, u_long);
867 static  void freework_enqueue(struct freework *);
868 static  int handle_workitem_freeblocks(struct freeblks *, int);
869 static  int handle_complete_freeblocks(struct freeblks *, int);
870 static  void handle_workitem_indirblk(struct freework *);
871 static  void handle_written_freework(struct freework *);
872 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
873 static  struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
874             struct workhead *);
875 static  struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
876             struct inodedep *, struct allocindir *, ufs_lbn_t);
877 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
878             ufs2_daddr_t, ufs_lbn_t);
879 static  void handle_workitem_freefrag(struct freefrag *);
880 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
881             ufs_lbn_t, u_long);
882 static  void allocdirect_merge(struct allocdirectlst *,
883             struct allocdirect *, struct allocdirect *);
884 static  struct freefrag *allocindir_merge(struct allocindir *,
885             struct allocindir *);
886 static  int bmsafemap_find(struct bmsafemap_hashhead *, int,
887             struct bmsafemap **);
888 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
889             int cg, struct bmsafemap *);
890 static  int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
891             struct newblk **);
892 static  int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
893 static  int inodedep_find(struct inodedep_hashhead *, ino_t,
894             struct inodedep **);
895 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
896 static  int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
897             int, struct pagedep **);
898 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
899             struct pagedep **);
900 static  void pause_timer(void *);
901 static  int request_cleanup(struct mount *, int);
902 static  int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
903 static  void schedule_cleanup(struct mount *);
904 static void softdep_ast_cleanup_proc(struct thread *);
905 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
906 static  int process_worklist_item(struct mount *, int, int);
907 static  void process_removes(struct vnode *);
908 static  void process_truncates(struct vnode *);
909 static  void jwork_move(struct workhead *, struct workhead *);
910 static  void jwork_insert(struct workhead *, struct jsegdep *);
911 static  void add_to_worklist(struct worklist *, int);
912 static  void wake_worklist(struct worklist *);
913 static  void wait_worklist(struct worklist *, char *);
914 static  void remove_from_worklist(struct worklist *);
915 static  void softdep_flush(void *);
916 static  void softdep_flushjournal(struct mount *);
917 static  int softdep_speedup(struct ufsmount *);
918 static  void worklist_speedup(struct mount *);
919 static  int journal_mount(struct mount *, struct fs *, struct ucred *);
920 static  void journal_unmount(struct ufsmount *);
921 static  int journal_space(struct ufsmount *, int);
922 static  void journal_suspend(struct ufsmount *);
923 static  int journal_unsuspend(struct ufsmount *ump);
924 static  void softdep_prelink(struct vnode *, struct vnode *);
925 static  void add_to_journal(struct worklist *);
926 static  void remove_from_journal(struct worklist *);
927 static  bool softdep_excess_items(struct ufsmount *, int);
928 static  void softdep_process_journal(struct mount *, struct worklist *, int);
929 static  struct jremref *newjremref(struct dirrem *, struct inode *,
930             struct inode *ip, off_t, nlink_t);
931 static  struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
932             uint16_t);
933 static  inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
934             uint16_t);
935 static  inline struct jsegdep *inoref_jseg(struct inoref *);
936 static  struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
937 static  struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
938             ufs2_daddr_t, int);
939 static  void adjust_newfreework(struct freeblks *, int);
940 static  struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
941 static  void move_newblock_dep(struct jaddref *, struct inodedep *);
942 static  void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
943 static  struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
944             ufs2_daddr_t, long, ufs_lbn_t);
945 static  struct freework *newfreework(struct ufsmount *, struct freeblks *,
946             struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
947 static  int jwait(struct worklist *, int);
948 static  struct inodedep *inodedep_lookup_ip(struct inode *);
949 static  int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
950 static  struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
951 static  void handle_jwork(struct workhead *);
952 static  struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
953             struct mkdir **);
954 static  struct jblocks *jblocks_create(void);
955 static  ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
956 static  void jblocks_free(struct jblocks *, struct mount *, int);
957 static  void jblocks_destroy(struct jblocks *);
958 static  void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
959
960 /*
961  * Exported softdep operations.
962  */
963 static  void softdep_disk_io_initiation(struct buf *);
964 static  void softdep_disk_write_complete(struct buf *);
965 static  void softdep_deallocate_dependencies(struct buf *);
966 static  int softdep_count_dependencies(struct buf *bp, int);
967
968 /*
969  * Global lock over all of soft updates.
970  */
971 static struct mtx lk;
972 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
973
974 #define ACQUIRE_GBLLOCK(lk)     mtx_lock(lk)
975 #define FREE_GBLLOCK(lk)        mtx_unlock(lk)
976 #define GBLLOCK_OWNED(lk)       mtx_assert((lk), MA_OWNED)
977
978 /*
979  * Per-filesystem soft-updates locking.
980  */
981 #define LOCK_PTR(ump)           (&(ump)->um_softdep->sd_fslock)
982 #define TRY_ACQUIRE_LOCK(ump)   rw_try_wlock(&(ump)->um_softdep->sd_fslock)
983 #define ACQUIRE_LOCK(ump)       rw_wlock(&(ump)->um_softdep->sd_fslock)
984 #define FREE_LOCK(ump)          rw_wunlock(&(ump)->um_softdep->sd_fslock)
985 #define LOCK_OWNED(ump)         rw_assert(&(ump)->um_softdep->sd_fslock, \
986                                     RA_WLOCKED)
987
988 #define BUF_AREC(bp)            lockallowrecurse(&(bp)->b_lock)
989 #define BUF_NOREC(bp)           lockdisablerecurse(&(bp)->b_lock)
990
991 /*
992  * Worklist queue management.
993  * These routines require that the lock be held.
994  */
995 #ifndef /* NOT */ INVARIANTS
996 #define WORKLIST_INSERT(head, item) do {        \
997         (item)->wk_state |= ONWORKLIST;         \
998         LIST_INSERT_HEAD(head, item, wk_list);  \
999 } while (0)
1000 #define WORKLIST_REMOVE(item) do {              \
1001         (item)->wk_state &= ~ONWORKLIST;        \
1002         LIST_REMOVE(item, wk_list);             \
1003 } while (0)
1004 #define WORKLIST_INSERT_UNLOCKED        WORKLIST_INSERT
1005 #define WORKLIST_REMOVE_UNLOCKED        WORKLIST_REMOVE
1006
1007 #else /* INVARIANTS */
1008 static  void worklist_insert(struct workhead *, struct worklist *, int,
1009         const char *, int);
1010 static  void worklist_remove(struct worklist *, int, const char *, int);
1011
1012 #define WORKLIST_INSERT(head, item) \
1013         worklist_insert(head, item, 1, __func__, __LINE__)
1014 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1015         worklist_insert(head, item, 0, __func__, __LINE__)
1016 #define WORKLIST_REMOVE(item)\
1017         worklist_remove(item, 1, __func__, __LINE__)
1018 #define WORKLIST_REMOVE_UNLOCKED(item)\
1019         worklist_remove(item, 0, __func__, __LINE__)
1020
1021 static void
1022 worklist_insert(head, item, locked, func, line)
1023         struct workhead *head;
1024         struct worklist *item;
1025         int locked;
1026         const char *func;
1027         int line;
1028 {
1029
1030         if (locked)
1031                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1032         if (item->wk_state & ONWORKLIST)
1033                 panic("worklist_insert: %p %s(0x%X) already on list, "
1034                     "added in function %s at line %d",
1035                     item, TYPENAME(item->wk_type), item->wk_state,
1036                     item->wk_func, item->wk_line);
1037         item->wk_state |= ONWORKLIST;
1038         item->wk_func = func;
1039         item->wk_line = line;
1040         LIST_INSERT_HEAD(head, item, wk_list);
1041 }
1042
1043 static void
1044 worklist_remove(item, locked, func, line)
1045         struct worklist *item;
1046         int locked;
1047         const char *func;
1048         int line;
1049 {
1050
1051         if (locked)
1052                 LOCK_OWNED(VFSTOUFS(item->wk_mp));
1053         if ((item->wk_state & ONWORKLIST) == 0)
1054                 panic("worklist_remove: %p %s(0x%X) not on list, "
1055                     "removed in function %s at line %d",
1056                     item, TYPENAME(item->wk_type), item->wk_state,
1057                     item->wk_func, item->wk_line);
1058         item->wk_state &= ~ONWORKLIST;
1059         item->wk_func = func;
1060         item->wk_line = line;
1061         LIST_REMOVE(item, wk_list);
1062 }
1063 #endif /* INVARIANTS */
1064
1065 /*
1066  * Merge two jsegdeps keeping only the oldest one as newer references
1067  * can't be discarded until after older references.
1068  */
1069 static inline struct jsegdep *
1070 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1071 {
1072         struct jsegdep *swp;
1073
1074         if (two == NULL)
1075                 return (one);
1076
1077         if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1078                 swp = one;
1079                 one = two;
1080                 two = swp;
1081         }
1082         WORKLIST_REMOVE(&two->jd_list);
1083         free_jsegdep(two);
1084
1085         return (one);
1086 }
1087
1088 /*
1089  * If two freedeps are compatible free one to reduce list size.
1090  */
1091 static inline struct freedep *
1092 freedep_merge(struct freedep *one, struct freedep *two)
1093 {
1094         if (two == NULL)
1095                 return (one);
1096
1097         if (one->fd_freework == two->fd_freework) {
1098                 WORKLIST_REMOVE(&two->fd_list);
1099                 free_freedep(two);
1100         }
1101         return (one);
1102 }
1103
1104 /*
1105  * Move journal work from one list to another.  Duplicate freedeps and
1106  * jsegdeps are coalesced to keep the lists as small as possible.
1107  */
1108 static void
1109 jwork_move(dst, src)
1110         struct workhead *dst;
1111         struct workhead *src;
1112 {
1113         struct freedep *freedep;
1114         struct jsegdep *jsegdep;
1115         struct worklist *wkn;
1116         struct worklist *wk;
1117
1118         KASSERT(dst != src,
1119             ("jwork_move: dst == src"));
1120         freedep = NULL;
1121         jsegdep = NULL;
1122         LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1123                 if (wk->wk_type == D_JSEGDEP)
1124                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1125                 else if (wk->wk_type == D_FREEDEP)
1126                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1127         }
1128
1129         while ((wk = LIST_FIRST(src)) != NULL) {
1130                 WORKLIST_REMOVE(wk);
1131                 WORKLIST_INSERT(dst, wk);
1132                 if (wk->wk_type == D_JSEGDEP) {
1133                         jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1134                         continue;
1135                 }
1136                 if (wk->wk_type == D_FREEDEP)
1137                         freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1138         }
1139 }
1140
1141 static void
1142 jwork_insert(dst, jsegdep)
1143         struct workhead *dst;
1144         struct jsegdep *jsegdep;
1145 {
1146         struct jsegdep *jsegdepn;
1147         struct worklist *wk;
1148
1149         LIST_FOREACH(wk, dst, wk_list)
1150                 if (wk->wk_type == D_JSEGDEP)
1151                         break;
1152         if (wk == NULL) {
1153                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1154                 return;
1155         }
1156         jsegdepn = WK_JSEGDEP(wk);
1157         if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1158                 WORKLIST_REMOVE(wk);
1159                 free_jsegdep(jsegdepn);
1160                 WORKLIST_INSERT(dst, &jsegdep->jd_list);
1161         } else
1162                 free_jsegdep(jsegdep);
1163 }
1164
1165 /*
1166  * Routines for tracking and managing workitems.
1167  */
1168 static  void workitem_free(struct worklist *, int);
1169 static  void workitem_alloc(struct worklist *, int, struct mount *);
1170 static  void workitem_reassign(struct worklist *, int);
1171
1172 #define WORKITEM_FREE(item, type) \
1173         workitem_free((struct worklist *)(item), (type))
1174 #define WORKITEM_REASSIGN(item, type) \
1175         workitem_reassign((struct worklist *)(item), (type))
1176
1177 static void
1178 workitem_free(item, type)
1179         struct worklist *item;
1180         int type;
1181 {
1182         struct ufsmount *ump;
1183
1184 #ifdef INVARIANTS
1185         if (item->wk_state & ONWORKLIST)
1186                 panic("workitem_free: %s(0x%X) still on list, "
1187                     "added in function %s at line %d",
1188                     TYPENAME(item->wk_type), item->wk_state,
1189                     item->wk_func, item->wk_line);
1190         if (item->wk_type != type && type != D_NEWBLK)
1191                 panic("workitem_free: type mismatch %s != %s",
1192                     TYPENAME(item->wk_type), TYPENAME(type));
1193 #endif
1194         if (item->wk_state & IOWAITING)
1195                 wakeup(item);
1196         ump = VFSTOUFS(item->wk_mp);
1197         LOCK_OWNED(ump);
1198         KASSERT(ump->softdep_deps > 0,
1199             ("workitem_free: %s: softdep_deps going negative",
1200             ump->um_fs->fs_fsmnt));
1201         if (--ump->softdep_deps == 0 && ump->softdep_req)
1202                 wakeup(&ump->softdep_deps);
1203         KASSERT(dep_current[item->wk_type] > 0,
1204             ("workitem_free: %s: dep_current[%s] going negative",
1205             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1206         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1207             ("workitem_free: %s: softdep_curdeps[%s] going negative",
1208             ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1209         atomic_subtract_long(&dep_current[item->wk_type], 1);
1210         ump->softdep_curdeps[item->wk_type] -= 1;
1211         free(item, DtoM(type));
1212 }
1213
1214 static void
1215 workitem_alloc(item, type, mp)
1216         struct worklist *item;
1217         int type;
1218         struct mount *mp;
1219 {
1220         struct ufsmount *ump;
1221
1222         item->wk_type = type;
1223         item->wk_mp = mp;
1224         item->wk_state = 0;
1225
1226         ump = VFSTOUFS(mp);
1227         ACQUIRE_GBLLOCK(&lk);
1228         dep_current[type]++;
1229         if (dep_current[type] > dep_highuse[type])
1230                 dep_highuse[type] = dep_current[type];
1231         dep_total[type]++;
1232         FREE_GBLLOCK(&lk);
1233         ACQUIRE_LOCK(ump);
1234         ump->softdep_curdeps[type] += 1;
1235         ump->softdep_deps++;
1236         ump->softdep_accdeps++;
1237         FREE_LOCK(ump);
1238 }
1239
1240 static void
1241 workitem_reassign(item, newtype)
1242         struct worklist *item;
1243         int newtype;
1244 {
1245         struct ufsmount *ump;
1246
1247         ump = VFSTOUFS(item->wk_mp);
1248         LOCK_OWNED(ump);
1249         KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1250             ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1251             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1252         ump->softdep_curdeps[item->wk_type] -= 1;
1253         ump->softdep_curdeps[newtype] += 1;
1254         KASSERT(dep_current[item->wk_type] > 0,
1255             ("workitem_reassign: %s: dep_current[%s] going negative",
1256             VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1257         ACQUIRE_GBLLOCK(&lk);
1258         dep_current[newtype]++;
1259         dep_current[item->wk_type]--;
1260         if (dep_current[newtype] > dep_highuse[newtype])
1261                 dep_highuse[newtype] = dep_current[newtype];
1262         dep_total[newtype]++;
1263         FREE_GBLLOCK(&lk);
1264         item->wk_type = newtype;
1265 }
1266
1267 /*
1268  * Workitem queue management
1269  */
1270 static int max_softdeps;        /* maximum number of structs before slowdown */
1271 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
1272 static int proc_waiting;        /* tracks whether we have a timeout posted */
1273 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
1274 static struct callout softdep_callout;
1275 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
1276 static int req_clear_remove;    /* syncer process flush some freeblks */
1277 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1278
1279 /*
1280  * runtime statistics
1281  */
1282 static int stat_flush_threads;  /* number of softdep flushing threads */
1283 static int stat_worklist_push;  /* number of worklist cleanups */
1284 static int stat_blk_limit_push; /* number of times block limit neared */
1285 static int stat_ino_limit_push; /* number of times inode limit neared */
1286 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
1287 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
1288 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
1289 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
1290 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
1291 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1292 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
1293 static int stat_jaddref;        /* bufs redirtied as ino bitmap can not write */
1294 static int stat_jnewblk;        /* bufs redirtied as blk bitmap can not write */
1295 static int stat_journal_min;    /* Times hit journal min threshold */
1296 static int stat_journal_low;    /* Times hit journal low threshold */
1297 static int stat_journal_wait;   /* Times blocked in jwait(). */
1298 static int stat_jwait_filepage; /* Times blocked in jwait() for filepage. */
1299 static int stat_jwait_freeblks; /* Times blocked in jwait() for freeblks. */
1300 static int stat_jwait_inode;    /* Times blocked in jwait() for inodes. */
1301 static int stat_jwait_newblk;   /* Times blocked in jwait() for newblks. */
1302 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1303 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1304 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1305 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1306 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1307 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1308
1309 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1310     &max_softdeps, 0, "");
1311 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1312     &tickdelay, 0, "");
1313 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1314     &stat_flush_threads, 0, "");
1315 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1316     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1317 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1318     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1319 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1320     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1321 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1322     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1323 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1324     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1325 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1326     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1327 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1328     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1329 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1330     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1331 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1332     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1333 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1334     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1335 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1336     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1337 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1338     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1339 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1340     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1341 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1342     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1343 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1344     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1345 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1346     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1347 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1348     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1349 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1350     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1351 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1352     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1353 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1354     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1355 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1356     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1357 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1358     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1359 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1360     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1361 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1362     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1363
1364 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1365     &softdep_flushcache, 0, "");
1366 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1367     &stat_emptyjblocks, 0, "");
1368
1369 SYSCTL_DECL(_vfs_ffs);
1370
1371 /* Whether to recompute the summary at mount time */
1372 static int compute_summary_at_mount = 0;
1373 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1374            &compute_summary_at_mount, 0, "Recompute summary at mount");
1375 static int print_threads = 0;
1376 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1377     &print_threads, 0, "Notify flusher thread start/stop");
1378
1379 /* List of all filesystems mounted with soft updates */
1380 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1381
1382 /*
1383  * This function cleans the worklist for a filesystem.
1384  * Each filesystem running with soft dependencies gets its own
1385  * thread to run in this function. The thread is started up in
1386  * softdep_mount and shutdown in softdep_unmount. They show up
1387  * as part of the kernel "bufdaemon" process whose process
1388  * entry is available in bufdaemonproc.
1389  */
1390 static int searchfailed;
1391 extern struct proc *bufdaemonproc;
1392 static void
1393 softdep_flush(addr)
1394         void *addr;
1395 {
1396         struct mount *mp;
1397         struct thread *td;
1398         struct ufsmount *ump;
1399
1400         td = curthread;
1401         td->td_pflags |= TDP_NORUNNINGBUF;
1402         mp = (struct mount *)addr;
1403         ump = VFSTOUFS(mp);
1404         atomic_add_int(&stat_flush_threads, 1);
1405         ACQUIRE_LOCK(ump);
1406         ump->softdep_flags &= ~FLUSH_STARTING;
1407         wakeup(&ump->softdep_flushtd);
1408         FREE_LOCK(ump);
1409         if (print_threads) {
1410                 if (stat_flush_threads == 1)
1411                         printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1412                             bufdaemonproc->p_pid);
1413                 printf("Start thread %s\n", td->td_name);
1414         }
1415         for (;;) {      
1416                 while (softdep_process_worklist(mp, 0) > 0 ||
1417                     (MOUNTEDSUJ(mp) &&
1418                     VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1419                         kthread_suspend_check();
1420                 ACQUIRE_LOCK(ump);
1421                 if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1422                         msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1423                             "sdflush", hz / 2);
1424                 ump->softdep_flags &= ~FLUSH_CLEANUP;
1425                 /*
1426                  * Check to see if we are done and need to exit.
1427                  */
1428                 if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1429                         FREE_LOCK(ump);
1430                         continue;
1431                 }
1432                 ump->softdep_flags &= ~FLUSH_EXIT;
1433                 FREE_LOCK(ump);
1434                 wakeup(&ump->softdep_flags);
1435                 if (print_threads)
1436                         printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1437                 atomic_subtract_int(&stat_flush_threads, 1);
1438                 kthread_exit();
1439                 panic("kthread_exit failed\n");
1440         }
1441 }
1442
1443 static void
1444 worklist_speedup(mp)
1445         struct mount *mp;
1446 {
1447         struct ufsmount *ump;
1448
1449         ump = VFSTOUFS(mp);
1450         LOCK_OWNED(ump);
1451         if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1452                 ump->softdep_flags |= FLUSH_CLEANUP;
1453         wakeup(&ump->softdep_flushtd);
1454 }
1455
1456 static void
1457 softdep_send_speedup(struct ufsmount *ump, size_t shortage, u_int flags)
1458 {
1459         struct buf *bp;
1460
1461         bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1462         bp->b_iocmd = BIO_SPEEDUP;
1463         bp->b_ioflags = flags;
1464         bp->b_bcount = shortage;
1465         g_vfs_strategy(ump->um_bo, bp);
1466         bufwait(bp);
1467         free(bp, M_TRIM);
1468 }
1469
1470 static int
1471 softdep_speedup(ump)
1472         struct ufsmount *ump;
1473 {
1474         struct ufsmount *altump;
1475         struct mount_softdeps *sdp;
1476
1477         LOCK_OWNED(ump);
1478         worklist_speedup(ump->um_mountp);
1479         bd_speedup();
1480         /*
1481          * If we have global shortages, then we need other
1482          * filesystems to help with the cleanup. Here we wakeup a
1483          * flusher thread for a filesystem that is over its fair
1484          * share of resources.
1485          */
1486         if (req_clear_inodedeps || req_clear_remove) {
1487                 ACQUIRE_GBLLOCK(&lk);
1488                 TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1489                         if ((altump = sdp->sd_ump) == ump)
1490                                 continue;
1491                         if (((req_clear_inodedeps &&
1492                             altump->softdep_curdeps[D_INODEDEP] >
1493                             max_softdeps / stat_flush_threads) ||
1494                             (req_clear_remove &&
1495                             altump->softdep_curdeps[D_DIRREM] >
1496                             (max_softdeps / 2) / stat_flush_threads)) &&
1497                             TRY_ACQUIRE_LOCK(altump))
1498                                 break;
1499                 }
1500                 if (sdp == NULL) {
1501                         searchfailed++;
1502                         FREE_GBLLOCK(&lk);
1503                 } else {
1504                         /*
1505                          * Move to the end of the list so we pick a
1506                          * different one on out next try.
1507                          */
1508                         TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1509                         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1510                         FREE_GBLLOCK(&lk);
1511                         if ((altump->softdep_flags &
1512                             (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1513                                 altump->softdep_flags |= FLUSH_CLEANUP;
1514                         altump->um_softdep->sd_cleanups++;
1515                         wakeup(&altump->softdep_flushtd);
1516                         FREE_LOCK(altump);
1517                 }
1518         }
1519         return (speedup_syncer());
1520 }
1521
1522 /*
1523  * Add an item to the end of the work queue.
1524  * This routine requires that the lock be held.
1525  * This is the only routine that adds items to the list.
1526  * The following routine is the only one that removes items
1527  * and does so in order from first to last.
1528  */
1529
1530 #define WK_HEAD         0x0001  /* Add to HEAD. */
1531 #define WK_NODELAY      0x0002  /* Process immediately. */
1532
1533 static void
1534 add_to_worklist(wk, flags)
1535         struct worklist *wk;
1536         int flags;
1537 {
1538         struct ufsmount *ump;
1539
1540         ump = VFSTOUFS(wk->wk_mp);
1541         LOCK_OWNED(ump);
1542         if (wk->wk_state & ONWORKLIST)
1543                 panic("add_to_worklist: %s(0x%X) already on list",
1544                     TYPENAME(wk->wk_type), wk->wk_state);
1545         wk->wk_state |= ONWORKLIST;
1546         if (ump->softdep_on_worklist == 0) {
1547                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1548                 ump->softdep_worklist_tail = wk;
1549         } else if (flags & WK_HEAD) {
1550                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1551         } else {
1552                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1553                 ump->softdep_worklist_tail = wk;
1554         }
1555         ump->softdep_on_worklist += 1;
1556         if (flags & WK_NODELAY)
1557                 worklist_speedup(wk->wk_mp);
1558 }
1559
1560 /*
1561  * Remove the item to be processed. If we are removing the last
1562  * item on the list, we need to recalculate the tail pointer.
1563  */
1564 static void
1565 remove_from_worklist(wk)
1566         struct worklist *wk;
1567 {
1568         struct ufsmount *ump;
1569
1570         ump = VFSTOUFS(wk->wk_mp);
1571         if (ump->softdep_worklist_tail == wk)
1572                 ump->softdep_worklist_tail =
1573                     (struct worklist *)wk->wk_list.le_prev;
1574         WORKLIST_REMOVE(wk);
1575         ump->softdep_on_worklist -= 1;
1576 }
1577
1578 static void
1579 wake_worklist(wk)
1580         struct worklist *wk;
1581 {
1582         if (wk->wk_state & IOWAITING) {
1583                 wk->wk_state &= ~IOWAITING;
1584                 wakeup(wk);
1585         }
1586 }
1587
1588 static void
1589 wait_worklist(wk, wmesg)
1590         struct worklist *wk;
1591         char *wmesg;
1592 {
1593         struct ufsmount *ump;
1594
1595         ump = VFSTOUFS(wk->wk_mp);
1596         wk->wk_state |= IOWAITING;
1597         msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1598 }
1599
1600 /*
1601  * Process that runs once per second to handle items in the background queue.
1602  *
1603  * Note that we ensure that everything is done in the order in which they
1604  * appear in the queue. The code below depends on this property to ensure
1605  * that blocks of a file are freed before the inode itself is freed. This
1606  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1607  * until all the old ones have been purged from the dependency lists.
1608  */
1609 static int 
1610 softdep_process_worklist(mp, full)
1611         struct mount *mp;
1612         int full;
1613 {
1614         int cnt, matchcnt;
1615         struct ufsmount *ump;
1616         long starttime;
1617
1618         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1619         if (MOUNTEDSOFTDEP(mp) == 0)
1620                 return (0);
1621         matchcnt = 0;
1622         ump = VFSTOUFS(mp);
1623         ACQUIRE_LOCK(ump);
1624         starttime = time_second;
1625         softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1626         check_clear_deps(mp);
1627         while (ump->softdep_on_worklist > 0) {
1628                 if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1629                         break;
1630                 else
1631                         matchcnt += cnt;
1632                 check_clear_deps(mp);
1633                 /*
1634                  * We do not generally want to stop for buffer space, but if
1635                  * we are really being a buffer hog, we will stop and wait.
1636                  */
1637                 if (should_yield()) {
1638                         FREE_LOCK(ump);
1639                         kern_yield(PRI_USER);
1640                         bwillwrite();
1641                         ACQUIRE_LOCK(ump);
1642                 }
1643                 /*
1644                  * Never allow processing to run for more than one
1645                  * second. This gives the syncer thread the opportunity
1646                  * to pause if appropriate.
1647                  */
1648                 if (!full && starttime != time_second)
1649                         break;
1650         }
1651         if (full == 0)
1652                 journal_unsuspend(ump);
1653         FREE_LOCK(ump);
1654         return (matchcnt);
1655 }
1656
1657 /*
1658  * Process all removes associated with a vnode if we are running out of
1659  * journal space.  Any other process which attempts to flush these will
1660  * be unable as we have the vnodes locked.
1661  */
1662 static void
1663 process_removes(vp)
1664         struct vnode *vp;
1665 {
1666         struct inodedep *inodedep;
1667         struct dirrem *dirrem;
1668         struct ufsmount *ump;
1669         struct mount *mp;
1670         ino_t inum;
1671
1672         mp = vp->v_mount;
1673         ump = VFSTOUFS(mp);
1674         LOCK_OWNED(ump);
1675         inum = VTOI(vp)->i_number;
1676         for (;;) {
1677 top:
1678                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1679                         return;
1680                 LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1681                         /*
1682                          * If another thread is trying to lock this vnode
1683                          * it will fail but we must wait for it to do so
1684                          * before we can proceed.
1685                          */
1686                         if (dirrem->dm_state & INPROGRESS) {
1687                                 wait_worklist(&dirrem->dm_list, "pwrwait");
1688                                 goto top;
1689                         }
1690                         if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) == 
1691                             (COMPLETE | ONWORKLIST))
1692                                 break;
1693                 }
1694                 if (dirrem == NULL)
1695                         return;
1696                 remove_from_worklist(&dirrem->dm_list);
1697                 FREE_LOCK(ump);
1698                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1699                         panic("process_removes: suspended filesystem");
1700                 handle_workitem_remove(dirrem, 0);
1701                 vn_finished_secondary_write(mp);
1702                 ACQUIRE_LOCK(ump);
1703         }
1704 }
1705
1706 /*
1707  * Process all truncations associated with a vnode if we are running out
1708  * of journal space.  This is called when the vnode lock is already held
1709  * and no other process can clear the truncation.  This function returns
1710  * a value greater than zero if it did any work.
1711  */
1712 static void
1713 process_truncates(vp)
1714         struct vnode *vp;
1715 {
1716         struct inodedep *inodedep;
1717         struct freeblks *freeblks;
1718         struct ufsmount *ump;
1719         struct mount *mp;
1720         ino_t inum;
1721         int cgwait;
1722
1723         mp = vp->v_mount;
1724         ump = VFSTOUFS(mp);
1725         LOCK_OWNED(ump);
1726         inum = VTOI(vp)->i_number;
1727         for (;;) {
1728                 if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1729                         return;
1730                 cgwait = 0;
1731                 TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1732                         /* Journal entries not yet written.  */
1733                         if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1734                                 jwait(&LIST_FIRST(
1735                                     &freeblks->fb_jblkdephd)->jb_list,
1736                                     MNT_WAIT);
1737                                 break;
1738                         }
1739                         /* Another thread is executing this item. */
1740                         if (freeblks->fb_state & INPROGRESS) {
1741                                 wait_worklist(&freeblks->fb_list, "ptrwait");
1742                                 break;
1743                         }
1744                         /* Freeblks is waiting on a inode write. */
1745                         if ((freeblks->fb_state & COMPLETE) == 0) {
1746                                 FREE_LOCK(ump);
1747                                 ffs_update(vp, 1);
1748                                 ACQUIRE_LOCK(ump);
1749                                 break;
1750                         }
1751                         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1752                             (ALLCOMPLETE | ONWORKLIST)) {
1753                                 remove_from_worklist(&freeblks->fb_list);
1754                                 freeblks->fb_state |= INPROGRESS;
1755                                 FREE_LOCK(ump);
1756                                 if (vn_start_secondary_write(NULL, &mp,
1757                                     V_NOWAIT))
1758                                         panic("process_truncates: "
1759                                             "suspended filesystem");
1760                                 handle_workitem_freeblocks(freeblks, 0);
1761                                 vn_finished_secondary_write(mp);
1762                                 ACQUIRE_LOCK(ump);
1763                                 break;
1764                         }
1765                         if (freeblks->fb_cgwait)
1766                                 cgwait++;
1767                 }
1768                 if (cgwait) {
1769                         FREE_LOCK(ump);
1770                         sync_cgs(mp, MNT_WAIT);
1771                         ffs_sync_snap(mp, MNT_WAIT);
1772                         ACQUIRE_LOCK(ump);
1773                         continue;
1774                 }
1775                 if (freeblks == NULL)
1776                         break;
1777         }
1778         return;
1779 }
1780
1781 /*
1782  * Process one item on the worklist.
1783  */
1784 static int
1785 process_worklist_item(mp, target, flags)
1786         struct mount *mp;
1787         int target;
1788         int flags;
1789 {
1790         struct worklist sentinel;
1791         struct worklist *wk;
1792         struct ufsmount *ump;
1793         int matchcnt;
1794         int error;
1795
1796         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1797         /*
1798          * If we are being called because of a process doing a
1799          * copy-on-write, then it is not safe to write as we may
1800          * recurse into the copy-on-write routine.
1801          */
1802         if (curthread->td_pflags & TDP_COWINPROGRESS)
1803                 return (-1);
1804         PHOLD(curproc); /* Don't let the stack go away. */
1805         ump = VFSTOUFS(mp);
1806         LOCK_OWNED(ump);
1807         matchcnt = 0;
1808         sentinel.wk_mp = NULL;
1809         sentinel.wk_type = D_SENTINEL;
1810         LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1811         for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1812             wk = LIST_NEXT(&sentinel, wk_list)) {
1813                 if (wk->wk_type == D_SENTINEL) {
1814                         LIST_REMOVE(&sentinel, wk_list);
1815                         LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1816                         continue;
1817                 }
1818                 if (wk->wk_state & INPROGRESS)
1819                         panic("process_worklist_item: %p already in progress.",
1820                             wk);
1821                 wk->wk_state |= INPROGRESS;
1822                 remove_from_worklist(wk);
1823                 FREE_LOCK(ump);
1824                 if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1825                         panic("process_worklist_item: suspended filesystem");
1826                 switch (wk->wk_type) {
1827                 case D_DIRREM:
1828                         /* removal of a directory entry */
1829                         error = handle_workitem_remove(WK_DIRREM(wk), flags);
1830                         break;
1831
1832                 case D_FREEBLKS:
1833                         /* releasing blocks and/or fragments from a file */
1834                         error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1835                             flags);
1836                         break;
1837
1838                 case D_FREEFRAG:
1839                         /* releasing a fragment when replaced as a file grows */
1840                         handle_workitem_freefrag(WK_FREEFRAG(wk));
1841                         error = 0;
1842                         break;
1843
1844                 case D_FREEFILE:
1845                         /* releasing an inode when its link count drops to 0 */
1846                         handle_workitem_freefile(WK_FREEFILE(wk));
1847                         error = 0;
1848                         break;
1849
1850                 default:
1851                         panic("%s_process_worklist: Unknown type %s",
1852                             "softdep", TYPENAME(wk->wk_type));
1853                         /* NOTREACHED */
1854                 }
1855                 vn_finished_secondary_write(mp);
1856                 ACQUIRE_LOCK(ump);
1857                 if (error == 0) {
1858                         if (++matchcnt == target)
1859                                 break;
1860                         continue;
1861                 }
1862                 /*
1863                  * We have to retry the worklist item later.  Wake up any
1864                  * waiters who may be able to complete it immediately and
1865                  * add the item back to the head so we don't try to execute
1866                  * it again.
1867                  */
1868                 wk->wk_state &= ~INPROGRESS;
1869                 wake_worklist(wk);
1870                 add_to_worklist(wk, WK_HEAD);
1871         }
1872         /* Sentinal could've become the tail from remove_from_worklist. */
1873         if (ump->softdep_worklist_tail == &sentinel)
1874                 ump->softdep_worklist_tail =
1875                     (struct worklist *)sentinel.wk_list.le_prev;
1876         LIST_REMOVE(&sentinel, wk_list);
1877         PRELE(curproc);
1878         return (matchcnt);
1879 }
1880
1881 /*
1882  * Move dependencies from one buffer to another.
1883  */
1884 int
1885 softdep_move_dependencies(oldbp, newbp)
1886         struct buf *oldbp;
1887         struct buf *newbp;
1888 {
1889         struct worklist *wk, *wktail;
1890         struct ufsmount *ump;
1891         int dirty;
1892
1893         if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1894                 return (0);
1895         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1896             ("softdep_move_dependencies called on non-softdep filesystem"));
1897         dirty = 0;
1898         wktail = NULL;
1899         ump = VFSTOUFS(wk->wk_mp);
1900         ACQUIRE_LOCK(ump);
1901         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1902                 LIST_REMOVE(wk, wk_list);
1903                 if (wk->wk_type == D_BMSAFEMAP &&
1904                     bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1905                         dirty = 1;
1906                 if (wktail == NULL)
1907                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1908                 else
1909                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1910                 wktail = wk;
1911         }
1912         FREE_LOCK(ump);
1913
1914         return (dirty);
1915 }
1916
1917 /*
1918  * Purge the work list of all items associated with a particular mount point.
1919  */
1920 int
1921 softdep_flushworklist(oldmnt, countp, td)
1922         struct mount *oldmnt;
1923         int *countp;
1924         struct thread *td;
1925 {
1926         struct vnode *devvp;
1927         struct ufsmount *ump;
1928         int count, error;
1929
1930         /*
1931          * Alternately flush the block device associated with the mount
1932          * point and process any dependencies that the flushing
1933          * creates. We continue until no more worklist dependencies
1934          * are found.
1935          */
1936         *countp = 0;
1937         error = 0;
1938         ump = VFSTOUFS(oldmnt);
1939         devvp = ump->um_devvp;
1940         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1941                 *countp += count;
1942                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1943                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1944                 VOP_UNLOCK(devvp);
1945                 if (error != 0)
1946                         break;
1947         }
1948         return (error);
1949 }
1950
1951 #define SU_WAITIDLE_RETRIES     20
1952 static int
1953 softdep_waitidle(struct mount *mp, int flags __unused)
1954 {
1955         struct ufsmount *ump;
1956         struct vnode *devvp;
1957         struct thread *td;
1958         int error, i;
1959
1960         ump = VFSTOUFS(mp);
1961         devvp = ump->um_devvp;
1962         td = curthread;
1963         error = 0;
1964         ACQUIRE_LOCK(ump);
1965         for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1966                 ump->softdep_req = 1;
1967                 KASSERT((flags & FORCECLOSE) == 0 ||
1968                     ump->softdep_on_worklist == 0,
1969                     ("softdep_waitidle: work added after flush"));
1970                 msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1971                     "softdeps", 10 * hz);
1972                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1973                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1974                 VOP_UNLOCK(devvp);
1975                 ACQUIRE_LOCK(ump);
1976                 if (error != 0)
1977                         break;
1978         }
1979         ump->softdep_req = 0;
1980         if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1981                 error = EBUSY;
1982                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1983                     mp);
1984         }
1985         FREE_LOCK(ump);
1986         return (error);
1987 }
1988
1989 /*
1990  * Flush all vnodes and worklist items associated with a specified mount point.
1991  */
1992 int
1993 softdep_flushfiles(oldmnt, flags, td)
1994         struct mount *oldmnt;
1995         int flags;
1996         struct thread *td;
1997 {
1998 #ifdef QUOTA
1999         struct ufsmount *ump;
2000         int i;
2001 #endif
2002         int error, early, depcount, loopcnt, retry_flush_count, retry;
2003         int morework;
2004
2005         KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2006             ("softdep_flushfiles called on non-softdep filesystem"));
2007         loopcnt = 10;
2008         retry_flush_count = 3;
2009 retry_flush:
2010         error = 0;
2011
2012         /*
2013          * Alternately flush the vnodes associated with the mount
2014          * point and process any dependencies that the flushing
2015          * creates. In theory, this loop can happen at most twice,
2016          * but we give it a few extra just to be sure.
2017          */
2018         for (; loopcnt > 0; loopcnt--) {
2019                 /*
2020                  * Do another flush in case any vnodes were brought in
2021                  * as part of the cleanup operations.
2022                  */
2023                 early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2024                     MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2025                 if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2026                         break;
2027                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2028                     depcount == 0)
2029                         break;
2030         }
2031         /*
2032          * If we are unmounting then it is an error to fail. If we
2033          * are simply trying to downgrade to read-only, then filesystem
2034          * activity can keep us busy forever, so we just fail with EBUSY.
2035          */
2036         if (loopcnt == 0) {
2037                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2038                         panic("softdep_flushfiles: looping");
2039                 error = EBUSY;
2040         }
2041         if (!error)
2042                 error = softdep_waitidle(oldmnt, flags);
2043         if (!error) {
2044                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2045                         retry = 0;
2046                         MNT_ILOCK(oldmnt);
2047                         morework = oldmnt->mnt_nvnodelistsize > 0;
2048 #ifdef QUOTA
2049                         ump = VFSTOUFS(oldmnt);
2050                         UFS_LOCK(ump);
2051                         for (i = 0; i < MAXQUOTAS; i++) {
2052                                 if (ump->um_quotas[i] != NULLVP)
2053                                         morework = 1;
2054                         }
2055                         UFS_UNLOCK(ump);
2056 #endif
2057                         if (morework) {
2058                                 if (--retry_flush_count > 0) {
2059                                         retry = 1;
2060                                         loopcnt = 3;
2061                                 } else
2062                                         error = EBUSY;
2063                         }
2064                         MNT_IUNLOCK(oldmnt);
2065                         if (retry)
2066                                 goto retry_flush;
2067                 }
2068         }
2069         return (error);
2070 }
2071
2072 /*
2073  * Structure hashing.
2074  * 
2075  * There are four types of structures that can be looked up:
2076  *      1) pagedep structures identified by mount point, inode number,
2077  *         and logical block.
2078  *      2) inodedep structures identified by mount point and inode number.
2079  *      3) newblk structures identified by mount point and
2080  *         physical block number.
2081  *      4) bmsafemap structures identified by mount point and
2082  *         cylinder group number.
2083  *
2084  * The "pagedep" and "inodedep" dependency structures are hashed
2085  * separately from the file blocks and inodes to which they correspond.
2086  * This separation helps when the in-memory copy of an inode or
2087  * file block must be replaced. It also obviates the need to access
2088  * an inode or file page when simply updating (or de-allocating)
2089  * dependency structures. Lookup of newblk structures is needed to
2090  * find newly allocated blocks when trying to associate them with
2091  * their allocdirect or allocindir structure.
2092  *
2093  * The lookup routines optionally create and hash a new instance when
2094  * an existing entry is not found. The bmsafemap lookup routine always
2095  * allocates a new structure if an existing one is not found.
2096  */
2097 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
2098
2099 /*
2100  * Structures and routines associated with pagedep caching.
2101  */
2102 #define PAGEDEP_HASH(ump, inum, lbn) \
2103         (&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2104
2105 static int
2106 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2107         struct pagedep_hashhead *pagedephd;
2108         ino_t ino;
2109         ufs_lbn_t lbn;
2110         struct pagedep **pagedeppp;
2111 {
2112         struct pagedep *pagedep;
2113
2114         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2115                 if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2116                         *pagedeppp = pagedep;
2117                         return (1);
2118                 }
2119         }
2120         *pagedeppp = NULL;
2121         return (0);
2122 }
2123 /*
2124  * Look up a pagedep. Return 1 if found, 0 otherwise.
2125  * If not found, allocate if DEPALLOC flag is passed.
2126  * Found or allocated entry is returned in pagedeppp.
2127  */
2128 static int
2129 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2130         struct mount *mp;
2131         struct buf *bp;
2132         ino_t ino;
2133         ufs_lbn_t lbn;
2134         int flags;
2135         struct pagedep **pagedeppp;
2136 {
2137         struct pagedep *pagedep;
2138         struct pagedep_hashhead *pagedephd;
2139         struct worklist *wk;
2140         struct ufsmount *ump;
2141         int ret;
2142         int i;
2143
2144         ump = VFSTOUFS(mp);
2145         LOCK_OWNED(ump);
2146         if (bp) {
2147                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2148                         if (wk->wk_type == D_PAGEDEP) {
2149                                 *pagedeppp = WK_PAGEDEP(wk);
2150                                 return (1);
2151                         }
2152                 }
2153         }
2154         pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2155         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2156         if (ret) {
2157                 if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2158                         WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2159                 return (1);
2160         }
2161         if ((flags & DEPALLOC) == 0)
2162                 return (0);
2163         FREE_LOCK(ump);
2164         pagedep = malloc(sizeof(struct pagedep),
2165             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2166         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2167         ACQUIRE_LOCK(ump);
2168         ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2169         if (*pagedeppp) {
2170                 /*
2171                  * This should never happen since we only create pagedeps
2172                  * with the vnode lock held.  Could be an assert.
2173                  */
2174                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2175                 return (ret);
2176         }
2177         pagedep->pd_ino = ino;
2178         pagedep->pd_lbn = lbn;
2179         LIST_INIT(&pagedep->pd_dirremhd);
2180         LIST_INIT(&pagedep->pd_pendinghd);
2181         for (i = 0; i < DAHASHSZ; i++)
2182                 LIST_INIT(&pagedep->pd_diraddhd[i]);
2183         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2184         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2185         *pagedeppp = pagedep;
2186         return (0);
2187 }
2188
2189 /*
2190  * Structures and routines associated with inodedep caching.
2191  */
2192 #define INODEDEP_HASH(ump, inum) \
2193       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2194
2195 static int
2196 inodedep_find(inodedephd, inum, inodedeppp)
2197         struct inodedep_hashhead *inodedephd;
2198         ino_t inum;
2199         struct inodedep **inodedeppp;
2200 {
2201         struct inodedep *inodedep;
2202
2203         LIST_FOREACH(inodedep, inodedephd, id_hash)
2204                 if (inum == inodedep->id_ino)
2205                         break;
2206         if (inodedep) {
2207                 *inodedeppp = inodedep;
2208                 return (1);
2209         }
2210         *inodedeppp = NULL;
2211
2212         return (0);
2213 }
2214 /*
2215  * Look up an inodedep. Return 1 if found, 0 if not found.
2216  * If not found, allocate if DEPALLOC flag is passed.
2217  * Found or allocated entry is returned in inodedeppp.
2218  */
2219 static int
2220 inodedep_lookup(mp, inum, flags, inodedeppp)
2221         struct mount *mp;
2222         ino_t inum;
2223         int flags;
2224         struct inodedep **inodedeppp;
2225 {
2226         struct inodedep *inodedep;
2227         struct inodedep_hashhead *inodedephd;
2228         struct ufsmount *ump;
2229         struct fs *fs;
2230
2231         ump = VFSTOUFS(mp);
2232         LOCK_OWNED(ump);
2233         fs = ump->um_fs;
2234         inodedephd = INODEDEP_HASH(ump, inum);
2235
2236         if (inodedep_find(inodedephd, inum, inodedeppp))
2237                 return (1);
2238         if ((flags & DEPALLOC) == 0)
2239                 return (0);
2240         /*
2241          * If the system is over its limit and our filesystem is
2242          * responsible for more than our share of that usage and
2243          * we are not in a rush, request some inodedep cleanup.
2244          */
2245         if (softdep_excess_items(ump, D_INODEDEP))
2246                 schedule_cleanup(mp);
2247         else
2248                 FREE_LOCK(ump);
2249         inodedep = malloc(sizeof(struct inodedep),
2250                 M_INODEDEP, M_SOFTDEP_FLAGS);
2251         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2252         ACQUIRE_LOCK(ump);
2253         if (inodedep_find(inodedephd, inum, inodedeppp)) {
2254                 WORKITEM_FREE(inodedep, D_INODEDEP);
2255                 return (1);
2256         }
2257         inodedep->id_fs = fs;
2258         inodedep->id_ino = inum;
2259         inodedep->id_state = ALLCOMPLETE;
2260         inodedep->id_nlinkdelta = 0;
2261         inodedep->id_savedino1 = NULL;
2262         inodedep->id_savedsize = -1;
2263         inodedep->id_savedextsize = -1;
2264         inodedep->id_savednlink = -1;
2265         inodedep->id_bmsafemap = NULL;
2266         inodedep->id_mkdiradd = NULL;
2267         LIST_INIT(&inodedep->id_dirremhd);
2268         LIST_INIT(&inodedep->id_pendinghd);
2269         LIST_INIT(&inodedep->id_inowait);
2270         LIST_INIT(&inodedep->id_bufwait);
2271         TAILQ_INIT(&inodedep->id_inoreflst);
2272         TAILQ_INIT(&inodedep->id_inoupdt);
2273         TAILQ_INIT(&inodedep->id_newinoupdt);
2274         TAILQ_INIT(&inodedep->id_extupdt);
2275         TAILQ_INIT(&inodedep->id_newextupdt);
2276         TAILQ_INIT(&inodedep->id_freeblklst);
2277         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2278         *inodedeppp = inodedep;
2279         return (0);
2280 }
2281
2282 /*
2283  * Structures and routines associated with newblk caching.
2284  */
2285 #define NEWBLK_HASH(ump, inum) \
2286         (&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2287
2288 static int
2289 newblk_find(newblkhd, newblkno, flags, newblkpp)
2290         struct newblk_hashhead *newblkhd;
2291         ufs2_daddr_t newblkno;
2292         int flags;
2293         struct newblk **newblkpp;
2294 {
2295         struct newblk *newblk;
2296
2297         LIST_FOREACH(newblk, newblkhd, nb_hash) {
2298                 if (newblkno != newblk->nb_newblkno)
2299                         continue;
2300                 /*
2301                  * If we're creating a new dependency don't match those that
2302                  * have already been converted to allocdirects.  This is for
2303                  * a frag extend.
2304                  */
2305                 if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2306                         continue;
2307                 break;
2308         }
2309         if (newblk) {
2310                 *newblkpp = newblk;
2311                 return (1);
2312         }
2313         *newblkpp = NULL;
2314         return (0);
2315 }
2316
2317 /*
2318  * Look up a newblk. Return 1 if found, 0 if not found.
2319  * If not found, allocate if DEPALLOC flag is passed.
2320  * Found or allocated entry is returned in newblkpp.
2321  */
2322 static int
2323 newblk_lookup(mp, newblkno, flags, newblkpp)
2324         struct mount *mp;
2325         ufs2_daddr_t newblkno;
2326         int flags;
2327         struct newblk **newblkpp;
2328 {
2329         struct newblk *newblk;
2330         struct newblk_hashhead *newblkhd;
2331         struct ufsmount *ump;
2332
2333         ump = VFSTOUFS(mp);
2334         LOCK_OWNED(ump);
2335         newblkhd = NEWBLK_HASH(ump, newblkno);
2336         if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2337                 return (1);
2338         if ((flags & DEPALLOC) == 0)
2339                 return (0);
2340         if (softdep_excess_items(ump, D_NEWBLK) ||
2341             softdep_excess_items(ump, D_ALLOCDIRECT) ||
2342             softdep_excess_items(ump, D_ALLOCINDIR))
2343                 schedule_cleanup(mp);
2344         else
2345                 FREE_LOCK(ump);
2346         newblk = malloc(sizeof(union allblk), M_NEWBLK,
2347             M_SOFTDEP_FLAGS | M_ZERO);
2348         workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2349         ACQUIRE_LOCK(ump);
2350         if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2351                 WORKITEM_FREE(newblk, D_NEWBLK);
2352                 return (1);
2353         }
2354         newblk->nb_freefrag = NULL;
2355         LIST_INIT(&newblk->nb_indirdeps);
2356         LIST_INIT(&newblk->nb_newdirblk);
2357         LIST_INIT(&newblk->nb_jwork);
2358         newblk->nb_state = ATTACHED;
2359         newblk->nb_newblkno = newblkno;
2360         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2361         *newblkpp = newblk;
2362         return (0);
2363 }
2364
2365 /*
2366  * Structures and routines associated with freed indirect block caching.
2367  */
2368 #define INDIR_HASH(ump, blkno) \
2369         (&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2370
2371 /*
2372  * Lookup an indirect block in the indir hash table.  The freework is
2373  * removed and potentially freed.  The caller must do a blocking journal
2374  * write before writing to the blkno.
2375  */
2376 static int
2377 indirblk_lookup(mp, blkno)
2378         struct mount *mp;
2379         ufs2_daddr_t blkno;
2380 {
2381         struct freework *freework;
2382         struct indir_hashhead *wkhd;
2383         struct ufsmount *ump;
2384
2385         ump = VFSTOUFS(mp);
2386         wkhd = INDIR_HASH(ump, blkno);
2387         TAILQ_FOREACH(freework, wkhd, fw_next) {
2388                 if (freework->fw_blkno != blkno)
2389                         continue;
2390                 indirblk_remove(freework);
2391                 return (1);
2392         }
2393         return (0);
2394 }
2395
2396 /*
2397  * Insert an indirect block represented by freework into the indirblk
2398  * hash table so that it may prevent the block from being re-used prior
2399  * to the journal being written.
2400  */
2401 static void
2402 indirblk_insert(freework)
2403         struct freework *freework;
2404 {
2405         struct jblocks *jblocks;
2406         struct jseg *jseg;
2407         struct ufsmount *ump;
2408
2409         ump = VFSTOUFS(freework->fw_list.wk_mp);
2410         jblocks = ump->softdep_jblocks;
2411         jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2412         if (jseg == NULL)
2413                 return;
2414         
2415         LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2416         TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2417             fw_next);
2418         freework->fw_state &= ~DEPCOMPLETE;
2419 }
2420
2421 static void
2422 indirblk_remove(freework)
2423         struct freework *freework;
2424 {
2425         struct ufsmount *ump;
2426
2427         ump = VFSTOUFS(freework->fw_list.wk_mp);
2428         LIST_REMOVE(freework, fw_segs);
2429         TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2430         freework->fw_state |= DEPCOMPLETE;
2431         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2432                 WORKITEM_FREE(freework, D_FREEWORK);
2433 }
2434
2435 /*
2436  * Executed during filesystem system initialization before
2437  * mounting any filesystems.
2438  */
2439 void 
2440 softdep_initialize()
2441 {
2442
2443         TAILQ_INIT(&softdepmounts);
2444 #ifdef __LP64__
2445         max_softdeps = desiredvnodes * 4;
2446 #else
2447         max_softdeps = desiredvnodes * 2;
2448 #endif
2449
2450         /* initialise bioops hack */
2451         bioops.io_start = softdep_disk_io_initiation;
2452         bioops.io_complete = softdep_disk_write_complete;
2453         bioops.io_deallocate = softdep_deallocate_dependencies;
2454         bioops.io_countdeps = softdep_count_dependencies;
2455         softdep_ast_cleanup = softdep_ast_cleanup_proc;
2456
2457         /* Initialize the callout with an mtx. */
2458         callout_init_mtx(&softdep_callout, &lk, 0);
2459 }
2460
2461 /*
2462  * Executed after all filesystems have been unmounted during
2463  * filesystem module unload.
2464  */
2465 void
2466 softdep_uninitialize()
2467 {
2468
2469         /* clear bioops hack */
2470         bioops.io_start = NULL;
2471         bioops.io_complete = NULL;
2472         bioops.io_deallocate = NULL;
2473         bioops.io_countdeps = NULL;
2474         softdep_ast_cleanup = NULL;
2475
2476         callout_drain(&softdep_callout);
2477 }
2478
2479 /*
2480  * Called at mount time to notify the dependency code that a
2481  * filesystem wishes to use it.
2482  */
2483 int
2484 softdep_mount(devvp, mp, fs, cred)
2485         struct vnode *devvp;
2486         struct mount *mp;
2487         struct fs *fs;
2488         struct ucred *cred;
2489 {
2490         struct csum_total cstotal;
2491         struct mount_softdeps *sdp;
2492         struct ufsmount *ump;
2493         struct cg *cgp;
2494         struct buf *bp;
2495         u_int cyl, i;
2496         int error;
2497
2498         sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2499             M_WAITOK | M_ZERO);
2500         MNT_ILOCK(mp);
2501         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2502         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2503                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
2504                         MNTK_SOFTDEP | MNTK_NOASYNC;
2505         }
2506         ump = VFSTOUFS(mp);
2507         ump->um_softdep = sdp;
2508         MNT_IUNLOCK(mp);
2509         rw_init(LOCK_PTR(ump), "per-fs softdep");
2510         sdp->sd_ump = ump;
2511         LIST_INIT(&ump->softdep_workitem_pending);
2512         LIST_INIT(&ump->softdep_journal_pending);
2513         TAILQ_INIT(&ump->softdep_unlinked);
2514         LIST_INIT(&ump->softdep_dirtycg);
2515         ump->softdep_worklist_tail = NULL;
2516         ump->softdep_on_worklist = 0;
2517         ump->softdep_deps = 0;
2518         LIST_INIT(&ump->softdep_mkdirlisthd);
2519         ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2520             &ump->pagedep_hash_size);
2521         ump->pagedep_nextclean = 0;
2522         ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2523             &ump->inodedep_hash_size);
2524         ump->inodedep_nextclean = 0;
2525         ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2526             &ump->newblk_hash_size);
2527         ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2528             &ump->bmsafemap_hash_size);
2529         i = 1 << (ffs(desiredvnodes / 10) - 1);
2530         ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2531             M_FREEWORK, M_WAITOK);
2532         ump->indir_hash_size = i - 1;
2533         for (i = 0; i <= ump->indir_hash_size; i++)
2534                 TAILQ_INIT(&ump->indir_hashtbl[i]);
2535         ACQUIRE_GBLLOCK(&lk);
2536         TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2537         FREE_GBLLOCK(&lk);
2538         if ((fs->fs_flags & FS_SUJ) &&
2539             (error = journal_mount(mp, fs, cred)) != 0) {
2540                 printf("Failed to start journal: %d\n", error);
2541                 softdep_unmount(mp);
2542                 return (error);
2543         }
2544         /*
2545          * Start our flushing thread in the bufdaemon process.
2546          */
2547         ACQUIRE_LOCK(ump);
2548         ump->softdep_flags |= FLUSH_STARTING;
2549         FREE_LOCK(ump);
2550         kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2551             &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2552             mp->mnt_stat.f_mntonname);
2553         ACQUIRE_LOCK(ump);
2554         while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2555                 msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2556                     hz / 2);
2557         }
2558         FREE_LOCK(ump);
2559         /*
2560          * When doing soft updates, the counters in the
2561          * superblock may have gotten out of sync. Recomputation
2562          * can take a long time and can be deferred for background
2563          * fsck.  However, the old behavior of scanning the cylinder
2564          * groups and recalculating them at mount time is available
2565          * by setting vfs.ffs.compute_summary_at_mount to one.
2566          */
2567         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2568                 return (0);
2569         bzero(&cstotal, sizeof cstotal);
2570         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2571                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2572                     fs->fs_cgsize, cred, &bp)) != 0) {
2573                         brelse(bp);
2574                         softdep_unmount(mp);
2575                         return (error);
2576                 }
2577                 cgp = (struct cg *)bp->b_data;
2578                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2579                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2580                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2581                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2582                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
2583                 brelse(bp);
2584         }
2585 #ifdef INVARIANTS
2586         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2587                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2588 #endif
2589         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2590         return (0);
2591 }
2592
2593 void
2594 softdep_unmount(mp)
2595         struct mount *mp;
2596 {
2597         struct ufsmount *ump;
2598 #ifdef INVARIANTS
2599         int i;
2600 #endif
2601
2602         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2603             ("softdep_unmount called on non-softdep filesystem"));
2604         ump = VFSTOUFS(mp);
2605         MNT_ILOCK(mp);
2606         mp->mnt_flag &= ~MNT_SOFTDEP;
2607         if (MOUNTEDSUJ(mp) == 0) {
2608                 MNT_IUNLOCK(mp);
2609         } else {
2610                 mp->mnt_flag &= ~MNT_SUJ;
2611                 MNT_IUNLOCK(mp);
2612                 journal_unmount(ump);
2613         }
2614         /*
2615          * Shut down our flushing thread. Check for NULL is if
2616          * softdep_mount errors out before the thread has been created.
2617          */
2618         if (ump->softdep_flushtd != NULL) {
2619                 ACQUIRE_LOCK(ump);
2620                 ump->softdep_flags |= FLUSH_EXIT;
2621                 wakeup(&ump->softdep_flushtd);
2622                 msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2623                     "sdwait", 0);
2624                 KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2625                     ("Thread shutdown failed"));
2626         }
2627         /*
2628          * Free up our resources.
2629          */
2630         ACQUIRE_GBLLOCK(&lk);
2631         TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2632         FREE_GBLLOCK(&lk);
2633         rw_destroy(LOCK_PTR(ump));
2634         hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2635         hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2636         hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2637         hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2638             ump->bmsafemap_hash_size);
2639         free(ump->indir_hashtbl, M_FREEWORK);
2640 #ifdef INVARIANTS
2641         for (i = 0; i <= D_LAST; i++)
2642                 KASSERT(ump->softdep_curdeps[i] == 0,
2643                     ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2644                     TYPENAME(i), ump->softdep_curdeps[i]));
2645 #endif
2646         free(ump->um_softdep, M_MOUNTDATA);
2647 }
2648
2649 static struct jblocks *
2650 jblocks_create(void)
2651 {
2652         struct jblocks *jblocks;
2653
2654         jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2655         TAILQ_INIT(&jblocks->jb_segs);
2656         jblocks->jb_avail = 10;
2657         jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2658             M_JBLOCKS, M_WAITOK | M_ZERO);
2659
2660         return (jblocks);
2661 }
2662
2663 static ufs2_daddr_t
2664 jblocks_alloc(jblocks, bytes, actual)
2665         struct jblocks *jblocks;
2666         int bytes;
2667         int *actual;
2668 {
2669         ufs2_daddr_t daddr;
2670         struct jextent *jext;
2671         int freecnt;
2672         int blocks;
2673
2674         blocks = bytes / DEV_BSIZE;
2675         jext = &jblocks->jb_extent[jblocks->jb_head];
2676         freecnt = jext->je_blocks - jblocks->jb_off;
2677         if (freecnt == 0) {
2678                 jblocks->jb_off = 0;
2679                 if (++jblocks->jb_head > jblocks->jb_used)
2680                         jblocks->jb_head = 0;
2681                 jext = &jblocks->jb_extent[jblocks->jb_head];
2682                 freecnt = jext->je_blocks;
2683         }
2684         if (freecnt > blocks)
2685                 freecnt = blocks;
2686         *actual = freecnt * DEV_BSIZE;
2687         daddr = jext->je_daddr + jblocks->jb_off;
2688         jblocks->jb_off += freecnt;
2689         jblocks->jb_free -= freecnt;
2690
2691         return (daddr);
2692 }
2693
2694 static void
2695 jblocks_free(jblocks, mp, bytes)
2696         struct jblocks *jblocks;
2697         struct mount *mp;
2698         int bytes;
2699 {
2700
2701         LOCK_OWNED(VFSTOUFS(mp));
2702         jblocks->jb_free += bytes / DEV_BSIZE;
2703         if (jblocks->jb_suspended)
2704                 worklist_speedup(mp);
2705         wakeup(jblocks);
2706 }
2707
2708 static void
2709 jblocks_destroy(jblocks)
2710         struct jblocks *jblocks;
2711 {
2712
2713         if (jblocks->jb_extent)
2714                 free(jblocks->jb_extent, M_JBLOCKS);
2715         free(jblocks, M_JBLOCKS);
2716 }
2717
2718 static void
2719 jblocks_add(jblocks, daddr, blocks)
2720         struct jblocks *jblocks;
2721         ufs2_daddr_t daddr;
2722         int blocks;
2723 {
2724         struct jextent *jext;
2725
2726         jblocks->jb_blocks += blocks;
2727         jblocks->jb_free += blocks;
2728         jext = &jblocks->jb_extent[jblocks->jb_used];
2729         /* Adding the first block. */
2730         if (jext->je_daddr == 0) {
2731                 jext->je_daddr = daddr;
2732                 jext->je_blocks = blocks;
2733                 return;
2734         }
2735         /* Extending the last extent. */
2736         if (jext->je_daddr + jext->je_blocks == daddr) {
2737                 jext->je_blocks += blocks;
2738                 return;
2739         }
2740         /* Adding a new extent. */
2741         if (++jblocks->jb_used == jblocks->jb_avail) {
2742                 jblocks->jb_avail *= 2;
2743                 jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2744                     M_JBLOCKS, M_WAITOK | M_ZERO);
2745                 memcpy(jext, jblocks->jb_extent,
2746                     sizeof(struct jextent) * jblocks->jb_used);
2747                 free(jblocks->jb_extent, M_JBLOCKS);
2748                 jblocks->jb_extent = jext;
2749         }
2750         jext = &jblocks->jb_extent[jblocks->jb_used];
2751         jext->je_daddr = daddr;
2752         jext->je_blocks = blocks;
2753         return;
2754 }
2755
2756 int
2757 softdep_journal_lookup(mp, vpp)
2758         struct mount *mp;
2759         struct vnode **vpp;
2760 {
2761         struct componentname cnp;
2762         struct vnode *dvp;
2763         ino_t sujournal;
2764         int error;
2765
2766         error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2767         if (error)
2768                 return (error);
2769         bzero(&cnp, sizeof(cnp));
2770         cnp.cn_nameiop = LOOKUP;
2771         cnp.cn_flags = ISLASTCN;
2772         cnp.cn_thread = curthread;
2773         cnp.cn_cred = curthread->td_ucred;
2774         cnp.cn_pnbuf = SUJ_FILE;
2775         cnp.cn_nameptr = SUJ_FILE;
2776         cnp.cn_namelen = strlen(SUJ_FILE);
2777         error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2778         vput(dvp);
2779         if (error != 0)
2780                 return (error);
2781         error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2782         return (error);
2783 }
2784
2785 /*
2786  * Open and verify the journal file.
2787  */
2788 static int
2789 journal_mount(mp, fs, cred)
2790         struct mount *mp;
2791         struct fs *fs;
2792         struct ucred *cred;
2793 {
2794         struct jblocks *jblocks;
2795         struct ufsmount *ump;
2796         struct vnode *vp;
2797         struct inode *ip;
2798         ufs2_daddr_t blkno;
2799         int bcount;
2800         int error;
2801         int i;
2802
2803         ump = VFSTOUFS(mp);
2804         ump->softdep_journal_tail = NULL;
2805         ump->softdep_on_journal = 0;
2806         ump->softdep_accdeps = 0;
2807         ump->softdep_req = 0;
2808         ump->softdep_jblocks = NULL;
2809         error = softdep_journal_lookup(mp, &vp);
2810         if (error != 0) {
2811                 printf("Failed to find journal.  Use tunefs to create one\n");
2812                 return (error);
2813         }
2814         ip = VTOI(vp);
2815         if (ip->i_size < SUJ_MIN) {
2816                 error = ENOSPC;
2817                 goto out;
2818         }
2819         bcount = lblkno(fs, ip->i_size);        /* Only use whole blocks. */
2820         jblocks = jblocks_create();
2821         for (i = 0; i < bcount; i++) {
2822                 error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2823                 if (error)
2824                         break;
2825                 jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2826         }
2827         if (error) {
2828                 jblocks_destroy(jblocks);
2829                 goto out;
2830         }
2831         jblocks->jb_low = jblocks->jb_free / 3; /* Reserve 33%. */
2832         jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2833         ump->softdep_jblocks = jblocks;
2834 out:
2835         if (error == 0) {
2836                 MNT_ILOCK(mp);
2837                 mp->mnt_flag |= MNT_SUJ;
2838                 mp->mnt_flag &= ~MNT_SOFTDEP;
2839                 MNT_IUNLOCK(mp);
2840                 /*
2841                  * Only validate the journal contents if the
2842                  * filesystem is clean, otherwise we write the logs
2843                  * but they'll never be used.  If the filesystem was
2844                  * still dirty when we mounted it the journal is
2845                  * invalid and a new journal can only be valid if it
2846                  * starts from a clean mount.
2847                  */
2848                 if (fs->fs_clean) {
2849                         DIP_SET(ip, i_modrev, fs->fs_mtime);
2850                         ip->i_flags |= IN_MODIFIED;
2851                         ffs_update(vp, 1);
2852                 }
2853         }
2854         vput(vp);
2855         return (error);
2856 }
2857
2858 static void
2859 journal_unmount(ump)
2860         struct ufsmount *ump;
2861 {
2862
2863         if (ump->softdep_jblocks)
2864                 jblocks_destroy(ump->softdep_jblocks);
2865         ump->softdep_jblocks = NULL;
2866 }
2867
2868 /*
2869  * Called when a journal record is ready to be written.  Space is allocated
2870  * and the journal entry is created when the journal is flushed to stable
2871  * store.
2872  */
2873 static void
2874 add_to_journal(wk)
2875         struct worklist *wk;
2876 {
2877         struct ufsmount *ump;
2878
2879         ump = VFSTOUFS(wk->wk_mp);
2880         LOCK_OWNED(ump);
2881         if (wk->wk_state & ONWORKLIST)
2882                 panic("add_to_journal: %s(0x%X) already on list",
2883                     TYPENAME(wk->wk_type), wk->wk_state);
2884         wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2885         if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2886                 ump->softdep_jblocks->jb_age = ticks;
2887                 LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2888         } else
2889                 LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2890         ump->softdep_journal_tail = wk;
2891         ump->softdep_on_journal += 1;
2892 }
2893
2894 /*
2895  * Remove an arbitrary item for the journal worklist maintain the tail
2896  * pointer.  This happens when a new operation obviates the need to
2897  * journal an old operation.
2898  */
2899 static void
2900 remove_from_journal(wk)
2901         struct worklist *wk;
2902 {
2903         struct ufsmount *ump;
2904
2905         ump = VFSTOUFS(wk->wk_mp);
2906         LOCK_OWNED(ump);
2907 #ifdef INVARIANTS
2908         {
2909                 struct worklist *wkn;
2910
2911                 LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2912                         if (wkn == wk)
2913                                 break;
2914                 if (wkn == NULL)
2915                         panic("remove_from_journal: %p is not in journal", wk);
2916         }
2917 #endif
2918         /*
2919          * We emulate a TAILQ to save space in most structures which do not
2920          * require TAILQ semantics.  Here we must update the tail position
2921          * when removing the tail which is not the final entry. This works
2922          * only if the worklist linkage are at the beginning of the structure.
2923          */
2924         if (ump->softdep_journal_tail == wk)
2925                 ump->softdep_journal_tail =
2926                     (struct worklist *)wk->wk_list.le_prev;
2927         WORKLIST_REMOVE(wk);
2928         ump->softdep_on_journal -= 1;
2929 }
2930
2931 /*
2932  * Check for journal space as well as dependency limits so the prelink
2933  * code can throttle both journaled and non-journaled filesystems.
2934  * Threshold is 0 for low and 1 for min.
2935  */
2936 static int
2937 journal_space(ump, thresh)
2938         struct ufsmount *ump;
2939         int thresh;
2940 {
2941         struct jblocks *jblocks;
2942         int limit, avail;
2943
2944         jblocks = ump->softdep_jblocks;
2945         if (jblocks == NULL)
2946                 return (1);
2947         /*
2948          * We use a tighter restriction here to prevent request_cleanup()
2949          * running in threads from running into locks we currently hold.
2950          * We have to be over the limit and our filesystem has to be
2951          * responsible for more than our share of that usage.
2952          */
2953         limit = (max_softdeps / 10) * 9;
2954         if (dep_current[D_INODEDEP] > limit &&
2955             ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2956                 return (0);
2957         if (thresh)
2958                 thresh = jblocks->jb_min;
2959         else
2960                 thresh = jblocks->jb_low;
2961         avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2962         avail = jblocks->jb_free - avail;
2963
2964         return (avail > thresh);
2965 }
2966
2967 static void
2968 journal_suspend(ump)
2969         struct ufsmount *ump;
2970 {
2971         struct jblocks *jblocks;
2972         struct mount *mp;
2973         bool set;
2974
2975         mp = UFSTOVFS(ump);
2976         if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
2977                 return;
2978
2979         jblocks = ump->softdep_jblocks;
2980         vfs_op_enter(mp);
2981         set = false;
2982         MNT_ILOCK(mp);
2983         if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2984                 stat_journal_min++;
2985                 mp->mnt_kern_flag |= MNTK_SUSPEND;
2986                 mp->mnt_susp_owner = ump->softdep_flushtd;
2987                 set = true;
2988         }
2989         jblocks->jb_suspended = 1;
2990         MNT_IUNLOCK(mp);
2991         if (!set)
2992                 vfs_op_exit(mp);
2993 }
2994
2995 static int
2996 journal_unsuspend(struct ufsmount *ump)
2997 {
2998         struct jblocks *jblocks;
2999         struct mount *mp;
3000
3001         mp = UFSTOVFS(ump);
3002         jblocks = ump->softdep_jblocks;
3003
3004         if (jblocks != NULL && jblocks->jb_suspended &&
3005             journal_space(ump, jblocks->jb_min)) {
3006                 jblocks->jb_suspended = 0;
3007                 FREE_LOCK(ump);
3008                 mp->mnt_susp_owner = curthread;
3009                 vfs_write_resume(mp, 0);
3010                 ACQUIRE_LOCK(ump);
3011                 return (1);
3012         }
3013         return (0);
3014 }
3015
3016 /*
3017  * Called before any allocation function to be certain that there is
3018  * sufficient space in the journal prior to creating any new records.
3019  * Since in the case of block allocation we may have multiple locked
3020  * buffers at the time of the actual allocation we can not block
3021  * when the journal records are created.  Doing so would create a deadlock
3022  * if any of these buffers needed to be flushed to reclaim space.  Instead
3023  * we require a sufficiently large amount of available space such that
3024  * each thread in the system could have passed this allocation check and
3025  * still have sufficient free space.  With 20% of a minimum journal size
3026  * of 1MB we have 6553 records available.
3027  */
3028 int
3029 softdep_prealloc(vp, waitok)
3030         struct vnode *vp;
3031         int waitok;
3032 {
3033         struct ufsmount *ump;
3034
3035         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3036             ("softdep_prealloc called on non-softdep filesystem"));
3037         /*
3038          * Nothing to do if we are not running journaled soft updates.
3039          * If we currently hold the snapshot lock, we must avoid
3040          * handling other resources that could cause deadlock.  Do not
3041          * touch quotas vnode since it is typically recursed with
3042          * other vnode locks held.
3043          */
3044         if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3045             (vp->v_vflag & VV_SYSTEM) != 0)
3046                 return (0);
3047         ump = VFSTOUFS(vp->v_mount);
3048         ACQUIRE_LOCK(ump);
3049         if (journal_space(ump, 0)) {
3050                 FREE_LOCK(ump);
3051                 return (0);
3052         }
3053         stat_journal_low++;
3054         FREE_LOCK(ump);
3055         if (waitok == MNT_NOWAIT)
3056                 return (ENOSPC);
3057         /*
3058          * Attempt to sync this vnode once to flush any journal
3059          * work attached to it.
3060          */
3061         if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3062                 ffs_syncvnode(vp, waitok, 0);
3063         ACQUIRE_LOCK(ump);
3064         process_removes(vp);
3065         process_truncates(vp);
3066         if (journal_space(ump, 0) == 0) {
3067                 softdep_speedup(ump);
3068                 if (journal_space(ump, 1) == 0)
3069                         journal_suspend(ump);
3070         }
3071         FREE_LOCK(ump);
3072
3073         return (0);
3074 }
3075
3076 /*
3077  * Before adjusting a link count on a vnode verify that we have sufficient
3078  * journal space.  If not, process operations that depend on the currently
3079  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3080  * and softdep flush threads can not acquire these locks to reclaim space.
3081  */
3082 static void
3083 softdep_prelink(dvp, vp)
3084         struct vnode *dvp;
3085         struct vnode *vp;
3086 {
3087         struct ufsmount *ump;
3088
3089         ump = VFSTOUFS(dvp->v_mount);
3090         LOCK_OWNED(ump);
3091         /*
3092          * Nothing to do if we have sufficient journal space.
3093          * If we currently hold the snapshot lock, we must avoid
3094          * handling other resources that could cause deadlock.
3095          */
3096         if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3097                 return;
3098         stat_journal_low++;
3099         FREE_LOCK(ump);
3100         if (vp)
3101                 ffs_syncvnode(vp, MNT_NOWAIT, 0);
3102         ffs_syncvnode(dvp, MNT_WAIT, 0);
3103         ACQUIRE_LOCK(ump);
3104         /* Process vp before dvp as it may create .. removes. */
3105         if (vp) {
3106                 process_removes(vp);
3107                 process_truncates(vp);
3108         }
3109         process_removes(dvp);
3110         process_truncates(dvp);
3111         softdep_speedup(ump);
3112         process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3113         if (journal_space(ump, 0) == 0) {
3114                 softdep_speedup(ump);
3115                 if (journal_space(ump, 1) == 0)
3116                         journal_suspend(ump);
3117         }
3118 }
3119
3120 static void
3121 jseg_write(ump, jseg, data)
3122         struct ufsmount *ump;
3123         struct jseg *jseg;
3124         uint8_t *data;
3125 {
3126         struct jsegrec *rec;
3127
3128         rec = (struct jsegrec *)data;
3129         rec->jsr_seq = jseg->js_seq;
3130         rec->jsr_oldest = jseg->js_oldseq;
3131         rec->jsr_cnt = jseg->js_cnt;
3132         rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3133         rec->jsr_crc = 0;
3134         rec->jsr_time = ump->um_fs->fs_mtime;
3135 }
3136
3137 static inline void
3138 inoref_write(inoref, jseg, rec)
3139         struct inoref *inoref;
3140         struct jseg *jseg;
3141         struct jrefrec *rec;
3142 {
3143
3144         inoref->if_jsegdep->jd_seg = jseg;
3145         rec->jr_ino = inoref->if_ino;
3146         rec->jr_parent = inoref->if_parent;
3147         rec->jr_nlink = inoref->if_nlink;
3148         rec->jr_mode = inoref->if_mode;
3149         rec->jr_diroff = inoref->if_diroff;
3150 }
3151
3152 static void
3153 jaddref_write(jaddref, jseg, data)
3154         struct jaddref *jaddref;
3155         struct jseg *jseg;
3156         uint8_t *data;
3157 {
3158         struct jrefrec *rec;
3159
3160         rec = (struct jrefrec *)data;
3161         rec->jr_op = JOP_ADDREF;
3162         inoref_write(&jaddref->ja_ref, jseg, rec);
3163 }
3164
3165 static void
3166 jremref_write(jremref, jseg, data)
3167         struct jremref *jremref;
3168         struct jseg *jseg;
3169         uint8_t *data;
3170 {
3171         struct jrefrec *rec;
3172
3173         rec = (struct jrefrec *)data;
3174         rec->jr_op = JOP_REMREF;
3175         inoref_write(&jremref->jr_ref, jseg, rec);
3176 }
3177
3178 static void
3179 jmvref_write(jmvref, jseg, data)
3180         struct jmvref *jmvref;
3181         struct jseg *jseg;
3182         uint8_t *data;
3183 {
3184         struct jmvrec *rec;
3185
3186         rec = (struct jmvrec *)data;
3187         rec->jm_op = JOP_MVREF;
3188         rec->jm_ino = jmvref->jm_ino;
3189         rec->jm_parent = jmvref->jm_parent;
3190         rec->jm_oldoff = jmvref->jm_oldoff;
3191         rec->jm_newoff = jmvref->jm_newoff;
3192 }
3193
3194 static void
3195 jnewblk_write(jnewblk, jseg, data)
3196         struct jnewblk *jnewblk;
3197         struct jseg *jseg;
3198         uint8_t *data;
3199 {
3200         struct jblkrec *rec;
3201
3202         jnewblk->jn_jsegdep->jd_seg = jseg;
3203         rec = (struct jblkrec *)data;
3204         rec->jb_op = JOP_NEWBLK;
3205         rec->jb_ino = jnewblk->jn_ino;
3206         rec->jb_blkno = jnewblk->jn_blkno;
3207         rec->jb_lbn = jnewblk->jn_lbn;
3208         rec->jb_frags = jnewblk->jn_frags;
3209         rec->jb_oldfrags = jnewblk->jn_oldfrags;
3210 }
3211
3212 static void
3213 jfreeblk_write(jfreeblk, jseg, data)
3214         struct jfreeblk *jfreeblk;
3215         struct jseg *jseg;
3216         uint8_t *data;
3217 {
3218         struct jblkrec *rec;
3219
3220         jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3221         rec = (struct jblkrec *)data;
3222         rec->jb_op = JOP_FREEBLK;
3223         rec->jb_ino = jfreeblk->jf_ino;
3224         rec->jb_blkno = jfreeblk->jf_blkno;
3225         rec->jb_lbn = jfreeblk->jf_lbn;
3226         rec->jb_frags = jfreeblk->jf_frags;
3227         rec->jb_oldfrags = 0;
3228 }
3229
3230 static void
3231 jfreefrag_write(jfreefrag, jseg, data)
3232         struct jfreefrag *jfreefrag;
3233         struct jseg *jseg;
3234         uint8_t *data;
3235 {
3236         struct jblkrec *rec;
3237
3238         jfreefrag->fr_jsegdep->jd_seg = jseg;
3239         rec = (struct jblkrec *)data;
3240         rec->jb_op = JOP_FREEBLK;
3241         rec->jb_ino = jfreefrag->fr_ino;
3242         rec->jb_blkno = jfreefrag->fr_blkno;
3243         rec->jb_lbn = jfreefrag->fr_lbn;
3244         rec->jb_frags = jfreefrag->fr_frags;
3245         rec->jb_oldfrags = 0;
3246 }
3247
3248 static void
3249 jtrunc_write(jtrunc, jseg, data)
3250         struct jtrunc *jtrunc;
3251         struct jseg *jseg;
3252         uint8_t *data;
3253 {
3254         struct jtrncrec *rec;
3255
3256         jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3257         rec = (struct jtrncrec *)data;
3258         rec->jt_op = JOP_TRUNC;
3259         rec->jt_ino = jtrunc->jt_ino;
3260         rec->jt_size = jtrunc->jt_size;
3261         rec->jt_extsize = jtrunc->jt_extsize;
3262 }
3263
3264 static void
3265 jfsync_write(jfsync, jseg, data)
3266         struct jfsync *jfsync;
3267         struct jseg *jseg;
3268         uint8_t *data;
3269 {
3270         struct jtrncrec *rec;
3271
3272         rec = (struct jtrncrec *)data;
3273         rec->jt_op = JOP_SYNC;
3274         rec->jt_ino = jfsync->jfs_ino;
3275         rec->jt_size = jfsync->jfs_size;
3276         rec->jt_extsize = jfsync->jfs_extsize;
3277 }
3278
3279 static void
3280 softdep_flushjournal(mp)
3281         struct mount *mp;
3282 {
3283         struct jblocks *jblocks;
3284         struct ufsmount *ump;
3285
3286         if (MOUNTEDSUJ(mp) == 0)
3287                 return;
3288         ump = VFSTOUFS(mp);
3289         jblocks = ump->softdep_jblocks;
3290         ACQUIRE_LOCK(ump);
3291         while (ump->softdep_on_journal) {
3292                 jblocks->jb_needseg = 1;
3293                 softdep_process_journal(mp, NULL, MNT_WAIT);
3294         }
3295         FREE_LOCK(ump);
3296 }
3297
3298 static void softdep_synchronize_completed(struct bio *);
3299 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3300
3301 static void
3302 softdep_synchronize_completed(bp)
3303         struct bio *bp;
3304 {
3305         struct jseg *oldest;
3306         struct jseg *jseg;
3307         struct ufsmount *ump;
3308
3309         /*
3310          * caller1 marks the last segment written before we issued the
3311          * synchronize cache.
3312          */
3313         jseg = bp->bio_caller1;
3314         if (jseg == NULL) {
3315                 g_destroy_bio(bp);
3316                 return;
3317         }
3318         ump = VFSTOUFS(jseg->js_list.wk_mp);
3319         ACQUIRE_LOCK(ump);
3320         oldest = NULL;
3321         /*
3322          * Mark all the journal entries waiting on the synchronize cache
3323          * as completed so they may continue on.
3324          */
3325         while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3326                 jseg->js_state |= COMPLETE;
3327                 oldest = jseg;
3328                 jseg = TAILQ_PREV(jseg, jseglst, js_next);
3329         }
3330         /*
3331          * Restart deferred journal entry processing from the oldest
3332          * completed jseg.
3333          */
3334         if (oldest)
3335                 complete_jsegs(oldest);
3336
3337         FREE_LOCK(ump);
3338         g_destroy_bio(bp);
3339 }
3340
3341 /*
3342  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3343  * barriers.  The journal must be written prior to any blocks that depend
3344  * on it and the journal can not be released until the blocks have be
3345  * written.  This code handles both barriers simultaneously.
3346  */
3347 static void
3348 softdep_synchronize(bp, ump, caller1)
3349         struct bio *bp;
3350         struct ufsmount *ump;
3351         void *caller1;
3352 {
3353
3354         bp->bio_cmd = BIO_FLUSH;
3355         bp->bio_flags |= BIO_ORDERED;
3356         bp->bio_data = NULL;
3357         bp->bio_offset = ump->um_cp->provider->mediasize;
3358         bp->bio_length = 0;
3359         bp->bio_done = softdep_synchronize_completed;
3360         bp->bio_caller1 = caller1;
3361         g_io_request(bp, ump->um_cp);
3362 }
3363
3364 /*
3365  * Flush some journal records to disk.
3366  */
3367 static void
3368 softdep_process_journal(mp, needwk, flags)
3369         struct mount *mp;
3370         struct worklist *needwk;
3371         int flags;
3372 {
3373         struct jblocks *jblocks;
3374         struct ufsmount *ump;
3375         struct worklist *wk;
3376         struct jseg *jseg;
3377         struct buf *bp;
3378         struct bio *bio;
3379         uint8_t *data;
3380         struct fs *fs;
3381         int shouldflush;
3382         int segwritten;
3383         int jrecmin;    /* Minimum records per block. */
3384         int jrecmax;    /* Maximum records per block. */
3385         int size;
3386         int cnt;
3387         int off;
3388         int devbsize;
3389
3390         if (MOUNTEDSUJ(mp) == 0)
3391                 return;
3392         shouldflush = softdep_flushcache;
3393         bio = NULL;
3394         jseg = NULL;
3395         ump = VFSTOUFS(mp);
3396         LOCK_OWNED(ump);
3397         fs = ump->um_fs;
3398         jblocks = ump->softdep_jblocks;
3399         devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3400         /*
3401          * We write anywhere between a disk block and fs block.  The upper
3402          * bound is picked to prevent buffer cache fragmentation and limit
3403          * processing time per I/O.
3404          */
3405         jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3406         jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3407         segwritten = 0;
3408         for (;;) {
3409                 cnt = ump->softdep_on_journal;
3410                 /*
3411                  * Criteria for writing a segment:
3412                  * 1) We have a full block.
3413                  * 2) We're called from jwait() and haven't found the
3414                  *    journal item yet.
3415                  * 3) Always write if needseg is set.
3416                  * 4) If we are called from process_worklist and have
3417                  *    not yet written anything we write a partial block
3418                  *    to enforce a 1 second maximum latency on journal
3419                  *    entries.
3420                  */
3421                 if (cnt < (jrecmax - 1) && needwk == NULL &&
3422                     jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3423                         break;
3424                 cnt++;
3425                 /*
3426                  * Verify some free journal space.  softdep_prealloc() should
3427                  * guarantee that we don't run out so this is indicative of
3428                  * a problem with the flow control.  Try to recover
3429                  * gracefully in any event.
3430                  */
3431                 while (jblocks->jb_free == 0) {
3432                         if (flags != MNT_WAIT)
3433                                 break;
3434                         printf("softdep: Out of journal space!\n");
3435                         softdep_speedup(ump);
3436                         msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3437                 }
3438                 FREE_LOCK(ump);
3439                 jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3440                 workitem_alloc(&jseg->js_list, D_JSEG, mp);
3441                 LIST_INIT(&jseg->js_entries);
3442                 LIST_INIT(&jseg->js_indirs);
3443                 jseg->js_state = ATTACHED;
3444                 if (shouldflush == 0)
3445                         jseg->js_state |= COMPLETE;
3446                 else if (bio == NULL)
3447                         bio = g_alloc_bio();
3448                 jseg->js_jblocks = jblocks;
3449                 bp = geteblk(fs->fs_bsize, 0);
3450                 ACQUIRE_LOCK(ump);
3451                 /*
3452                  * If there was a race while we were allocating the block
3453                  * and jseg the entry we care about was likely written.
3454                  * We bail out in both the WAIT and NOWAIT case and assume
3455                  * the caller will loop if the entry it cares about is
3456                  * not written.
3457                  */
3458                 cnt = ump->softdep_on_journal;
3459                 if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3460                         bp->b_flags |= B_INVAL | B_NOCACHE;
3461                         WORKITEM_FREE(jseg, D_JSEG);
3462                         FREE_LOCK(ump);
3463                         brelse(bp);
3464                         ACQUIRE_LOCK(ump);
3465                         break;
3466                 }
3467                 /*
3468                  * Calculate the disk block size required for the available
3469                  * records rounded to the min size.
3470                  */
3471                 if (cnt == 0)
3472                         size = devbsize;
3473                 else if (cnt < jrecmax)
3474                         size = howmany(cnt, jrecmin) * devbsize;
3475                 else
3476                         size = fs->fs_bsize;
3477                 /*
3478                  * Allocate a disk block for this journal data and account
3479                  * for truncation of the requested size if enough contiguous
3480                  * space was not available.
3481                  */
3482                 bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3483                 bp->b_lblkno = bp->b_blkno;
3484                 bp->b_offset = bp->b_blkno * DEV_BSIZE;
3485                 bp->b_bcount = size;
3486                 bp->b_flags &= ~B_INVAL;
3487                 bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3488                 /*
3489                  * Initialize our jseg with cnt records.  Assign the next
3490                  * sequence number to it and link it in-order.
3491                  */
3492                 cnt = MIN(cnt, (size / devbsize) * jrecmin);
3493                 jseg->js_buf = bp;
3494                 jseg->js_cnt = cnt;
3495                 jseg->js_refs = cnt + 1;        /* Self ref. */
3496                 jseg->js_size = size;
3497                 jseg->js_seq = jblocks->jb_nextseq++;
3498                 if (jblocks->jb_oldestseg == NULL)
3499                         jblocks->jb_oldestseg = jseg;
3500                 jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3501                 TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3502                 if (jblocks->jb_writeseg == NULL)
3503                         jblocks->jb_writeseg = jseg;
3504                 /*
3505                  * Start filling in records from the pending list.
3506                  */
3507                 data = bp->b_data;
3508                 off = 0;
3509
3510                 /*
3511                  * Always put a header on the first block.
3512                  * XXX As with below, there might not be a chance to get
3513                  * into the loop.  Ensure that something valid is written.
3514                  */
3515                 jseg_write(ump, jseg, data);
3516                 off += JREC_SIZE;
3517                 data = bp->b_data + off;
3518
3519                 /*
3520                  * XXX Something is wrong here.  There's no work to do,
3521                  * but we need to perform and I/O and allow it to complete
3522                  * anyways.
3523                  */
3524                 if (LIST_EMPTY(&ump->softdep_journal_pending))
3525                         stat_emptyjblocks++;
3526
3527                 while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3528                     != NULL) {
3529                         if (cnt == 0)
3530                                 break;
3531                         /* Place a segment header on every device block. */
3532                         if ((off % devbsize) == 0) {
3533                                 jseg_write(ump, jseg, data);
3534                                 off += JREC_SIZE;
3535                                 data = bp->b_data + off;
3536                         }
3537                         if (wk == needwk)
3538                                 needwk = NULL;
3539                         remove_from_journal(wk);
3540                         wk->wk_state |= INPROGRESS;
3541                         WORKLIST_INSERT(&jseg->js_entries, wk);
3542                         switch (wk->wk_type) {
3543                         case D_JADDREF:
3544                                 jaddref_write(WK_JADDREF(wk), jseg, data);
3545                                 break;
3546                         case D_JREMREF:
3547                                 jremref_write(WK_JREMREF(wk), jseg, data);
3548                                 break;
3549                         case D_JMVREF:
3550                                 jmvref_write(WK_JMVREF(wk), jseg, data);
3551                                 break;
3552                         case D_JNEWBLK:
3553                                 jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3554                                 break;
3555                         case D_JFREEBLK:
3556                                 jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3557                                 break;
3558                         case D_JFREEFRAG:
3559                                 jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3560                                 break;
3561                         case D_JTRUNC:
3562                                 jtrunc_write(WK_JTRUNC(wk), jseg, data);
3563                                 break;
3564                         case D_JFSYNC:
3565                                 jfsync_write(WK_JFSYNC(wk), jseg, data);
3566                                 break;
3567                         default:
3568                                 panic("process_journal: Unknown type %s",
3569                                     TYPENAME(wk->wk_type));
3570                                 /* NOTREACHED */
3571                         }
3572                         off += JREC_SIZE;
3573                         data = bp->b_data + off;
3574                         cnt--;
3575                 }
3576
3577                 /* Clear any remaining space so we don't leak kernel data */
3578                 if (size > off)
3579                         bzero(data, size - off);
3580
3581                 /*
3582                  * Write this one buffer and continue.
3583                  */
3584                 segwritten = 1;
3585                 jblocks->jb_needseg = 0;
3586                 WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3587                 FREE_LOCK(ump);
3588                 pbgetvp(ump->um_devvp, bp);
3589                 /*
3590                  * We only do the blocking wait once we find the journal
3591                  * entry we're looking for.
3592                  */
3593                 if (needwk == NULL && flags == MNT_WAIT)
3594                         bwrite(bp);
3595                 else
3596                         bawrite(bp);
3597                 ACQUIRE_LOCK(ump);
3598         }
3599         /*
3600          * If we wrote a segment issue a synchronize cache so the journal
3601          * is reflected on disk before the data is written.  Since reclaiming
3602          * journal space also requires writing a journal record this
3603          * process also enforces a barrier before reclamation.
3604          */
3605         if (segwritten && shouldflush) {
3606                 softdep_synchronize(bio, ump, 
3607                     TAILQ_LAST(&jblocks->jb_segs, jseglst));
3608         } else if (bio)
3609                 g_destroy_bio(bio);
3610         /*
3611          * If we've suspended the filesystem because we ran out of journal
3612          * space either try to sync it here to make some progress or
3613          * unsuspend it if we already have.
3614          */
3615         if (flags == 0 && jblocks->jb_suspended) {
3616                 if (journal_unsuspend(ump))
3617                         return;
3618                 FREE_LOCK(ump);
3619                 VFS_SYNC(mp, MNT_NOWAIT);
3620                 ffs_sbupdate(ump, MNT_WAIT, 0);
3621                 ACQUIRE_LOCK(ump);
3622         }
3623 }
3624
3625 /*
3626  * Complete a jseg, allowing all dependencies awaiting journal writes
3627  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3628  * structures so that the journal segment can be freed to reclaim space.
3629  */
3630 static void
3631 complete_jseg(jseg)
3632         struct jseg *jseg;
3633 {
3634         struct worklist *wk;
3635         struct jmvref *jmvref;
3636 #ifdef INVARIANTS
3637         int i = 0;
3638 #endif
3639
3640         while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3641                 WORKLIST_REMOVE(wk);
3642                 wk->wk_state &= ~INPROGRESS;
3643                 wk->wk_state |= COMPLETE;
3644                 KASSERT(i++ < jseg->js_cnt,
3645                     ("handle_written_jseg: overflow %d >= %d",
3646                     i - 1, jseg->js_cnt));
3647                 switch (wk->wk_type) {
3648                 case D_JADDREF:
3649                         handle_written_jaddref(WK_JADDREF(wk));
3650                         break;
3651                 case D_JREMREF:
3652                         handle_written_jremref(WK_JREMREF(wk));
3653                         break;
3654                 case D_JMVREF:
3655                         rele_jseg(jseg);        /* No jsegdep. */
3656                         jmvref = WK_JMVREF(wk);
3657                         LIST_REMOVE(jmvref, jm_deps);
3658                         if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3659                                 free_pagedep(jmvref->jm_pagedep);
3660                         WORKITEM_FREE(jmvref, D_JMVREF);
3661                         break;
3662                 case D_JNEWBLK:
3663                         handle_written_jnewblk(WK_JNEWBLK(wk));
3664                         break;
3665                 case D_JFREEBLK:
3666                         handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3667                         break;
3668                 case D_JTRUNC:
3669                         handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3670                         break;
3671                 case D_JFSYNC:
3672                         rele_jseg(jseg);        /* No jsegdep. */
3673                         WORKITEM_FREE(wk, D_JFSYNC);
3674                         break;
3675                 case D_JFREEFRAG:
3676                         handle_written_jfreefrag(WK_JFREEFRAG(wk));
3677                         break;
3678                 default:
3679                         panic("handle_written_jseg: Unknown type %s",
3680                             TYPENAME(wk->wk_type));
3681                         /* NOTREACHED */
3682                 }
3683         }
3684         /* Release the self reference so the structure may be freed. */
3685         rele_jseg(jseg);
3686 }
3687
3688 /*
3689  * Determine which jsegs are ready for completion processing.  Waits for
3690  * synchronize cache to complete as well as forcing in-order completion
3691  * of journal entries.
3692  */
3693 static void
3694 complete_jsegs(jseg)
3695         struct jseg *jseg;
3696 {
3697         struct jblocks *jblocks;
3698         struct jseg *jsegn;
3699
3700         jblocks = jseg->js_jblocks;
3701         /*
3702          * Don't allow out of order completions.  If this isn't the first
3703          * block wait for it to write before we're done.
3704          */
3705         if (jseg != jblocks->jb_writeseg)
3706                 return;
3707         /* Iterate through available jsegs processing their entries. */
3708         while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3709                 jblocks->jb_oldestwrseq = jseg->js_oldseq;
3710                 jsegn = TAILQ_NEXT(jseg, js_next);
3711                 complete_jseg(jseg);
3712                 jseg = jsegn;
3713         }
3714         jblocks->jb_writeseg = jseg;
3715         /*
3716          * Attempt to free jsegs now that oldestwrseq may have advanced. 
3717          */
3718         free_jsegs(jblocks);
3719 }
3720
3721 /*
3722  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3723  * the final completions.
3724  */
3725 static void
3726 handle_written_jseg(jseg, bp)
3727         struct jseg *jseg;
3728         struct buf *bp;
3729 {
3730
3731         if (jseg->js_refs == 0)
3732                 panic("handle_written_jseg: No self-reference on %p", jseg);
3733         jseg->js_state |= DEPCOMPLETE;
3734         /*
3735          * We'll never need this buffer again, set flags so it will be
3736          * discarded.
3737          */
3738         bp->b_flags |= B_INVAL | B_NOCACHE;
3739         pbrelvp(bp);
3740         complete_jsegs(jseg);
3741 }
3742
3743 static inline struct jsegdep *
3744 inoref_jseg(inoref)
3745         struct inoref *inoref;
3746 {
3747         struct jsegdep *jsegdep;
3748
3749         jsegdep = inoref->if_jsegdep;
3750         inoref->if_jsegdep = NULL;
3751
3752         return (jsegdep);
3753 }
3754
3755 /*
3756  * Called once a jremref has made it to stable store.  The jremref is marked
3757  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3758  * for the jremref to complete will be awoken by free_jremref.
3759  */
3760 static void
3761 handle_written_jremref(jremref)
3762         struct jremref *jremref;
3763 {
3764         struct inodedep *inodedep;
3765         struct jsegdep *jsegdep;
3766         struct dirrem *dirrem;
3767
3768         /* Grab the jsegdep. */
3769         jsegdep = inoref_jseg(&jremref->jr_ref);
3770         /*
3771          * Remove us from the inoref list.
3772          */
3773         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3774             0, &inodedep) == 0)
3775                 panic("handle_written_jremref: Lost inodedep");
3776         TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3777         /*
3778          * Complete the dirrem.
3779          */
3780         dirrem = jremref->jr_dirrem;
3781         jremref->jr_dirrem = NULL;
3782         LIST_REMOVE(jremref, jr_deps);
3783         jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3784         jwork_insert(&dirrem->dm_jwork, jsegdep);
3785         if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3786             (dirrem->dm_state & COMPLETE) != 0)
3787                 add_to_worklist(&dirrem->dm_list, 0);
3788         free_jremref(jremref);
3789 }
3790
3791 /*
3792  * Called once a jaddref has made it to stable store.  The dependency is
3793  * marked complete and any dependent structures are added to the inode
3794  * bufwait list to be completed as soon as it is written.  If a bitmap write
3795  * depends on this entry we move the inode into the inodedephd of the
3796  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3797  */
3798 static void
3799 handle_written_jaddref(jaddref)
3800         struct jaddref *jaddref;
3801 {
3802         struct jsegdep *jsegdep;
3803         struct inodedep *inodedep;
3804         struct diradd *diradd;
3805         struct mkdir *mkdir;
3806
3807         /* Grab the jsegdep. */
3808         jsegdep = inoref_jseg(&jaddref->ja_ref);
3809         mkdir = NULL;
3810         diradd = NULL;
3811         if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3812             0, &inodedep) == 0)
3813                 panic("handle_written_jaddref: Lost inodedep.");
3814         if (jaddref->ja_diradd == NULL)
3815                 panic("handle_written_jaddref: No dependency");
3816         if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3817                 diradd = jaddref->ja_diradd;
3818                 WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3819         } else if (jaddref->ja_state & MKDIR_PARENT) {
3820                 mkdir = jaddref->ja_mkdir;
3821                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3822         } else if (jaddref->ja_state & MKDIR_BODY)
3823                 mkdir = jaddref->ja_mkdir;
3824         else
3825                 panic("handle_written_jaddref: Unknown dependency %p",
3826                     jaddref->ja_diradd);
3827         jaddref->ja_diradd = NULL;      /* also clears ja_mkdir */
3828         /*
3829          * Remove us from the inode list.
3830          */
3831         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3832         /*
3833          * The mkdir may be waiting on the jaddref to clear before freeing.
3834          */
3835         if (mkdir) {
3836                 KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3837                     ("handle_written_jaddref: Incorrect type for mkdir %s",
3838                     TYPENAME(mkdir->md_list.wk_type)));
3839                 mkdir->md_jaddref = NULL;
3840                 diradd = mkdir->md_diradd;
3841                 mkdir->md_state |= DEPCOMPLETE;
3842                 complete_mkdir(mkdir);
3843         }
3844         jwork_insert(&diradd->da_jwork, jsegdep);
3845         if (jaddref->ja_state & NEWBLOCK) {
3846                 inodedep->id_state |= ONDEPLIST;
3847                 LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3848                     inodedep, id_deps);
3849         }
3850         free_jaddref(jaddref);
3851 }
3852
3853 /*
3854  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3855  * is placed in the bmsafemap to await notification of a written bitmap.  If
3856  * the operation was canceled we add the segdep to the appropriate
3857  * dependency to free the journal space once the canceling operation
3858  * completes.
3859  */
3860 static void
3861 handle_written_jnewblk(jnewblk)
3862         struct jnewblk *jnewblk;
3863 {
3864         struct bmsafemap *bmsafemap;
3865         struct freefrag *freefrag;
3866         struct freework *freework;
3867         struct jsegdep *jsegdep;
3868         struct newblk *newblk;
3869
3870         /* Grab the jsegdep. */
3871         jsegdep = jnewblk->jn_jsegdep;
3872         jnewblk->jn_jsegdep = NULL;
3873         if (jnewblk->jn_dep == NULL) 
3874                 panic("handle_written_jnewblk: No dependency for the segdep.");
3875         switch (jnewblk->jn_dep->wk_type) {
3876         case D_NEWBLK:
3877         case D_ALLOCDIRECT:
3878         case D_ALLOCINDIR:
3879                 /*
3880                  * Add the written block to the bmsafemap so it can
3881                  * be notified when the bitmap is on disk.
3882                  */
3883                 newblk = WK_NEWBLK(jnewblk->jn_dep);
3884                 newblk->nb_jnewblk = NULL;
3885                 if ((newblk->nb_state & GOINGAWAY) == 0) {
3886                         bmsafemap = newblk->nb_bmsafemap;
3887                         newblk->nb_state |= ONDEPLIST;
3888                         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3889                             nb_deps);
3890                 }
3891                 jwork_insert(&newblk->nb_jwork, jsegdep);
3892                 break;
3893         case D_FREEFRAG:
3894                 /*
3895                  * A newblock being removed by a freefrag when replaced by
3896                  * frag extension.
3897                  */
3898                 freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3899                 freefrag->ff_jdep = NULL;
3900                 jwork_insert(&freefrag->ff_jwork, jsegdep);
3901                 break;
3902         case D_FREEWORK:
3903                 /*
3904                  * A direct block was removed by truncate.
3905                  */
3906                 freework = WK_FREEWORK(jnewblk->jn_dep);
3907                 freework->fw_jnewblk = NULL;
3908                 jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3909                 break;
3910         default:
3911                 panic("handle_written_jnewblk: Unknown type %d.",
3912                     jnewblk->jn_dep->wk_type);
3913         }
3914         jnewblk->jn_dep = NULL;
3915         free_jnewblk(jnewblk);
3916 }
3917
3918 /*
3919  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3920  * an in-flight allocation that has not yet been committed.  Divorce us
3921  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3922  * to the worklist.
3923  */
3924 static void
3925 cancel_jfreefrag(jfreefrag)
3926         struct jfreefrag *jfreefrag;
3927 {
3928         struct freefrag *freefrag;
3929
3930         if (jfreefrag->fr_jsegdep) {
3931                 free_jsegdep(jfreefrag->fr_jsegdep);
3932                 jfreefrag->fr_jsegdep = NULL;
3933         }
3934         freefrag = jfreefrag->fr_freefrag;
3935         jfreefrag->fr_freefrag = NULL;
3936         free_jfreefrag(jfreefrag);
3937         freefrag->ff_state |= DEPCOMPLETE;
3938         CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3939 }
3940
3941 /*
3942  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3943  */
3944 static void
3945 free_jfreefrag(jfreefrag)
3946         struct jfreefrag *jfreefrag;
3947 {
3948
3949         if (jfreefrag->fr_state & INPROGRESS)
3950                 WORKLIST_REMOVE(&jfreefrag->fr_list);
3951         else if (jfreefrag->fr_state & ONWORKLIST)
3952                 remove_from_journal(&jfreefrag->fr_list);
3953         if (jfreefrag->fr_freefrag != NULL)
3954                 panic("free_jfreefrag:  Still attached to a freefrag.");
3955         WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3956 }
3957
3958 /*
3959  * Called when the journal write for a jfreefrag completes.  The parent
3960  * freefrag is added to the worklist if this completes its dependencies.
3961  */
3962 static void
3963 handle_written_jfreefrag(jfreefrag)
3964         struct jfreefrag *jfreefrag;
3965 {
3966         struct jsegdep *jsegdep;
3967         struct freefrag *freefrag;
3968
3969         /* Grab the jsegdep. */
3970         jsegdep = jfreefrag->fr_jsegdep;
3971         jfreefrag->fr_jsegdep = NULL;
3972         freefrag = jfreefrag->fr_freefrag;
3973         if (freefrag == NULL)
3974                 panic("handle_written_jfreefrag: No freefrag.");
3975         freefrag->ff_state |= DEPCOMPLETE;
3976         freefrag->ff_jdep = NULL;
3977         jwork_insert(&freefrag->ff_jwork, jsegdep);
3978         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3979                 add_to_worklist(&freefrag->ff_list, 0);
3980         jfreefrag->fr_freefrag = NULL;
3981         free_jfreefrag(jfreefrag);
3982 }
3983
3984 /*
3985  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3986  * is removed from the freeblks list of pending journal writes and the
3987  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3988  * have been reclaimed.
3989  */
3990 static void
3991 handle_written_jblkdep(jblkdep)
3992         struct jblkdep *jblkdep;
3993 {
3994         struct freeblks *freeblks;
3995         struct jsegdep *jsegdep;
3996
3997         /* Grab the jsegdep. */
3998         jsegdep = jblkdep->jb_jsegdep;
3999         jblkdep->jb_jsegdep = NULL;
4000         freeblks = jblkdep->jb_freeblks;
4001         LIST_REMOVE(jblkdep, jb_deps);
4002         jwork_insert(&freeblks->fb_jwork, jsegdep);
4003         /*
4004          * If the freeblks is all journaled, we can add it to the worklist.
4005          */
4006         if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4007             (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4008                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4009
4010         free_jblkdep(jblkdep);
4011 }
4012
4013 static struct jsegdep *
4014 newjsegdep(struct worklist *wk)
4015 {
4016         struct jsegdep *jsegdep;
4017
4018         jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4019         workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4020         jsegdep->jd_seg = NULL;
4021
4022         return (jsegdep);
4023 }
4024
4025 static struct jmvref *
4026 newjmvref(dp, ino, oldoff, newoff)
4027         struct inode *dp;
4028         ino_t ino;
4029         off_t oldoff;
4030         off_t newoff;
4031 {
4032         struct jmvref *jmvref;
4033
4034         jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4035         workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4036         jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4037         jmvref->jm_parent = dp->i_number;
4038         jmvref->jm_ino = ino;
4039         jmvref->jm_oldoff = oldoff;
4040         jmvref->jm_newoff = newoff;
4041
4042         return (jmvref);
4043 }
4044
4045 /*
4046  * Allocate a new jremref that tracks the removal of ip from dp with the
4047  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4048  * DEPCOMPLETE as we have all the information required for the journal write
4049  * and the directory has already been removed from the buffer.  The caller
4050  * is responsible for linking the jremref into the pagedep and adding it
4051  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4052  * a DOTDOT addition so handle_workitem_remove() can properly assign
4053  * the jsegdep when we're done.
4054  */
4055 static struct jremref *
4056 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4057     off_t diroff, nlink_t nlink)
4058 {
4059         struct jremref *jremref;
4060
4061         jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4062         workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4063         jremref->jr_state = ATTACHED;
4064         newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4065            nlink, ip->i_mode);
4066         jremref->jr_dirrem = dirrem;
4067
4068         return (jremref);
4069 }
4070
4071 static inline void
4072 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4073     nlink_t nlink, uint16_t mode)
4074 {
4075
4076         inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4077         inoref->if_diroff = diroff;
4078         inoref->if_ino = ino;
4079         inoref->if_parent = parent;
4080         inoref->if_nlink = nlink;
4081         inoref->if_mode = mode;
4082 }
4083
4084 /*
4085  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4086  * directory offset may not be known until later.  The caller is responsible
4087  * adding the entry to the journal when this information is available.  nlink
4088  * should be the link count prior to the addition and mode is only required
4089  * to have the correct FMT.
4090  */
4091 static struct jaddref *
4092 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4093     uint16_t mode)
4094 {
4095         struct jaddref *jaddref;
4096
4097         jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4098         workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4099         jaddref->ja_state = ATTACHED;
4100         jaddref->ja_mkdir = NULL;
4101         newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4102
4103         return (jaddref);
4104 }
4105
4106 /*
4107  * Create a new free dependency for a freework.  The caller is responsible
4108  * for adjusting the reference count when it has the lock held.  The freedep
4109  * will track an outstanding bitmap write that will ultimately clear the
4110  * freework to continue.
4111  */
4112 static struct freedep *
4113 newfreedep(struct freework *freework)
4114 {
4115         struct freedep *freedep;
4116
4117         freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4118         workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4119         freedep->fd_freework = freework;
4120
4121         return (freedep);
4122 }
4123
4124 /*
4125  * Free a freedep structure once the buffer it is linked to is written.  If
4126  * this is the last reference to the freework schedule it for completion.
4127  */
4128 static void
4129 free_freedep(freedep)
4130         struct freedep *freedep;
4131 {
4132         struct freework *freework;
4133
4134         freework = freedep->fd_freework;
4135         freework->fw_freeblks->fb_cgwait--;
4136         if (--freework->fw_ref == 0)
4137                 freework_enqueue(freework);
4138         WORKITEM_FREE(freedep, D_FREEDEP);
4139 }
4140
4141 /*
4142  * Allocate a new freework structure that may be a level in an indirect
4143  * when parent is not NULL or a top level block when it is.  The top level
4144  * freework structures are allocated without the per-filesystem lock held
4145  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4146  */
4147 static struct freework *
4148 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4149         struct ufsmount *ump;
4150         struct freeblks *freeblks;
4151         struct freework *parent;
4152         ufs_lbn_t lbn;
4153         ufs2_daddr_t nb;
4154         int frags;
4155         int off;
4156         int journal;
4157 {
4158         struct freework *freework;
4159
4160         freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4161         workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4162         freework->fw_state = ATTACHED;
4163         freework->fw_jnewblk = NULL;
4164         freework->fw_freeblks = freeblks;
4165         freework->fw_parent = parent;
4166         freework->fw_lbn = lbn;
4167         freework->fw_blkno = nb;
4168         freework->fw_frags = frags;
4169         freework->fw_indir = NULL;
4170         freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4171             lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4172         freework->fw_start = freework->fw_off = off;
4173         if (journal)
4174                 newjfreeblk(freeblks, lbn, nb, frags);
4175         if (parent == NULL) {
4176                 ACQUIRE_LOCK(ump);
4177                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4178                 freeblks->fb_ref++;
4179                 FREE_LOCK(ump);
4180         }
4181
4182         return (freework);
4183 }
4184
4185 /*
4186  * Eliminate a jfreeblk for a block that does not need journaling.
4187  */
4188 static void
4189 cancel_jfreeblk(freeblks, blkno)
4190         struct freeblks *freeblks;
4191         ufs2_daddr_t blkno;
4192 {
4193         struct jfreeblk *jfreeblk;
4194         struct jblkdep *jblkdep;
4195
4196         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4197                 if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4198                         continue;
4199                 jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4200                 if (jfreeblk->jf_blkno == blkno)
4201                         break;
4202         }
4203         if (jblkdep == NULL)
4204                 return;
4205         CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4206         free_jsegdep(jblkdep->jb_jsegdep);
4207         LIST_REMOVE(jblkdep, jb_deps);
4208         WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4209 }
4210
4211 /*
4212  * Allocate a new jfreeblk to journal top level block pointer when truncating
4213  * a file.  The caller must add this to the worklist when the per-filesystem
4214  * lock is held.
4215  */
4216 static struct jfreeblk *
4217 newjfreeblk(freeblks, lbn, blkno, frags)
4218         struct freeblks *freeblks;
4219         ufs_lbn_t lbn;
4220         ufs2_daddr_t blkno;
4221         int frags;
4222 {
4223         struct jfreeblk *jfreeblk;
4224
4225         jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4226         workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4227             freeblks->fb_list.wk_mp);
4228         jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4229         jfreeblk->jf_dep.jb_freeblks = freeblks;
4230         jfreeblk->jf_ino = freeblks->fb_inum;
4231         jfreeblk->jf_lbn = lbn;
4232         jfreeblk->jf_blkno = blkno;
4233         jfreeblk->jf_frags = frags;
4234         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4235
4236         return (jfreeblk);
4237 }
4238
4239 /*
4240  * The journal is only prepared to handle full-size block numbers, so we
4241  * have to adjust the record to reflect the change to a full-size block.
4242  * For example, suppose we have a block made up of fragments 8-15 and
4243  * want to free its last two fragments. We are given a request that says:
4244  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4245  * where frags are the number of fragments to free and oldfrags are the
4246  * number of fragments to keep. To block align it, we have to change it to
4247  * have a valid full-size blkno, so it becomes:
4248  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4249  */
4250 static void
4251 adjust_newfreework(freeblks, frag_offset)
4252         struct freeblks *freeblks;
4253         int frag_offset;
4254 {
4255         struct jfreeblk *jfreeblk;
4256
4257         KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4258             LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4259             ("adjust_newfreework: Missing freeblks dependency"));
4260
4261         jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4262         jfreeblk->jf_blkno -= frag_offset;
4263         jfreeblk->jf_frags += frag_offset;
4264 }
4265
4266 /*
4267  * Allocate a new jtrunc to track a partial truncation.
4268  */
4269 static struct jtrunc *
4270 newjtrunc(freeblks, size, extsize)
4271         struct freeblks *freeblks;
4272         off_t size;
4273         int extsize;
4274 {
4275         struct jtrunc *jtrunc;
4276
4277         jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4278         workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4279             freeblks->fb_list.wk_mp);
4280         jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4281         jtrunc->jt_dep.jb_freeblks = freeblks;
4282         jtrunc->jt_ino = freeblks->fb_inum;
4283         jtrunc->jt_size = size;
4284         jtrunc->jt_extsize = extsize;
4285         LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4286
4287         return (jtrunc);
4288 }
4289
4290 /*
4291  * If we're canceling a new bitmap we have to search for another ref
4292  * to move into the bmsafemap dep.  This might be better expressed
4293  * with another structure.
4294  */
4295 static void
4296 move_newblock_dep(jaddref, inodedep)
4297         struct jaddref *jaddref;
4298         struct inodedep *inodedep;
4299 {
4300         struct inoref *inoref;
4301         struct jaddref *jaddrefn;
4302
4303         jaddrefn = NULL;
4304         for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4305             inoref = TAILQ_NEXT(inoref, if_deps)) {
4306                 if ((jaddref->ja_state & NEWBLOCK) &&
4307                     inoref->if_list.wk_type == D_JADDREF) {
4308                         jaddrefn = (struct jaddref *)inoref;
4309                         break;
4310                 }
4311         }
4312         if (jaddrefn == NULL)
4313                 return;
4314         jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4315         jaddrefn->ja_state |= jaddref->ja_state &
4316             (ATTACHED | UNDONE | NEWBLOCK);
4317         jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4318         jaddref->ja_state |= ATTACHED;
4319         LIST_REMOVE(jaddref, ja_bmdeps);
4320         LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4321             ja_bmdeps);
4322 }
4323
4324 /*
4325  * Cancel a jaddref either before it has been written or while it is being
4326  * written.  This happens when a link is removed before the add reaches
4327  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4328  * and inode to prevent the link count or bitmap from reaching the disk
4329  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4330  * required.
4331  *
4332  * Returns 1 if the canceled addref requires journaling of the remove and
4333  * 0 otherwise.
4334  */
4335 static int
4336 cancel_jaddref(jaddref, inodedep, wkhd)
4337         struct jaddref *jaddref;
4338         struct inodedep *inodedep;
4339         struct workhead *wkhd;
4340 {
4341         struct inoref *inoref;
4342         struct jsegdep *jsegdep;
4343         int needsj;
4344
4345         KASSERT((jaddref->ja_state & COMPLETE) == 0,
4346             ("cancel_jaddref: Canceling complete jaddref"));
4347         if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4348                 needsj = 1;
4349         else
4350                 needsj = 0;
4351         if (inodedep == NULL)
4352                 if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4353                     0, &inodedep) == 0)
4354                         panic("cancel_jaddref: Lost inodedep");
4355         /*
4356          * We must adjust the nlink of any reference operation that follows
4357          * us so that it is consistent with the in-memory reference.  This
4358          * ensures that inode nlink rollbacks always have the correct link.
4359          */
4360         if (needsj == 0) {
4361                 for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4362                     inoref = TAILQ_NEXT(inoref, if_deps)) {
4363                         if (inoref->if_state & GOINGAWAY)
4364                                 break;
4365                         inoref->if_nlink--;
4366                 }
4367         }
4368         jsegdep = inoref_jseg(&jaddref->ja_ref);
4369         if (jaddref->ja_state & NEWBLOCK)
4370                 move_newblock_dep(jaddref, inodedep);
4371         wake_worklist(&jaddref->ja_list);
4372         jaddref->ja_mkdir = NULL;
4373         if (jaddref->ja_state & INPROGRESS) {
4374                 jaddref->ja_state &= ~INPROGRESS;
4375                 WORKLIST_REMOVE(&jaddref->ja_list);
4376                 jwork_insert(wkhd, jsegdep);
4377         } else {
4378                 free_jsegdep(jsegdep);
4379                 if (jaddref->ja_state & DEPCOMPLETE)
4380                         remove_from_journal(&jaddref->ja_list);
4381         }
4382         jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4383         /*
4384          * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4385          * can arrange for them to be freed with the bitmap.  Otherwise we
4386          * no longer need this addref attached to the inoreflst and it
4387          * will incorrectly adjust nlink if we leave it.
4388          */
4389         if ((jaddref->ja_state & NEWBLOCK) == 0) {
4390                 TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4391                     if_deps);
4392                 jaddref->ja_state |= COMPLETE;
4393                 free_jaddref(jaddref);
4394                 return (needsj);
4395         }
4396         /*
4397          * Leave the head of the list for jsegdeps for fast merging.
4398          */
4399         if (LIST_FIRST(wkhd) != NULL) {
4400                 jaddref->ja_state |= ONWORKLIST;
4401                 LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4402         } else
4403                 WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4404
4405         return (needsj);
4406 }
4407
4408 /* 
4409  * Attempt to free a jaddref structure when some work completes.  This
4410  * should only succeed once the entry is written and all dependencies have
4411  * been notified.
4412  */
4413 static void
4414 free_jaddref(jaddref)
4415         struct jaddref *jaddref;
4416 {
4417
4418         if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4419                 return;
4420         if (jaddref->ja_ref.if_jsegdep)
4421                 panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4422                     jaddref, jaddref->ja_state);
4423         if (jaddref->ja_state & NEWBLOCK)
4424                 LIST_REMOVE(jaddref, ja_bmdeps);
4425         if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4426                 panic("free_jaddref: Bad state %p(0x%X)",
4427                     jaddref, jaddref->ja_state);
4428         if (jaddref->ja_mkdir != NULL)
4429                 panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4430         WORKITEM_FREE(jaddref, D_JADDREF);
4431 }
4432
4433 /*
4434  * Free a jremref structure once it has been written or discarded.
4435  */
4436 static void
4437 free_jremref(jremref)
4438         struct jremref *jremref;
4439 {
4440
4441         if (jremref->jr_ref.if_jsegdep)
4442                 free_jsegdep(jremref->jr_ref.if_jsegdep);
4443         if (jremref->jr_state & INPROGRESS)
4444                 panic("free_jremref: IO still pending");
4445         WORKITEM_FREE(jremref, D_JREMREF);
4446 }
4447
4448 /*
4449  * Free a jnewblk structure.
4450  */
4451 static void
4452 free_jnewblk(jnewblk)
4453         struct jnewblk *jnewblk;
4454 {
4455
4456         if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4457                 return;
4458         LIST_REMOVE(jnewblk, jn_deps);
4459         if (jnewblk->jn_dep != NULL)
4460                 panic("free_jnewblk: Dependency still attached.");
4461         WORKITEM_FREE(jnewblk, D_JNEWBLK);
4462 }
4463
4464 /*
4465  * Cancel a jnewblk which has been been made redundant by frag extension.
4466  */
4467 static void
4468 cancel_jnewblk(jnewblk, wkhd)
4469         struct jnewblk *jnewblk;
4470         struct workhead *wkhd;
4471 {
4472         struct jsegdep *jsegdep;
4473
4474         CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4475         jsegdep = jnewblk->jn_jsegdep;
4476         if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4477                 panic("cancel_jnewblk: Invalid state");
4478         jnewblk->jn_jsegdep  = NULL;
4479         jnewblk->jn_dep = NULL;
4480         jnewblk->jn_state |= GOINGAWAY;
4481         if (jnewblk->jn_state & INPROGRESS) {
4482                 jnewblk->jn_state &= ~INPROGRESS;
4483                 WORKLIST_REMOVE(&jnewblk->jn_list);
4484                 jwork_insert(wkhd, jsegdep);
4485         } else {
4486                 free_jsegdep(jsegdep);
4487                 remove_from_journal(&jnewblk->jn_list);
4488         }
4489         wake_worklist(&jnewblk->jn_list);
4490         WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4491 }
4492
4493 static void
4494 free_jblkdep(jblkdep)
4495         struct jblkdep *jblkdep;
4496 {
4497
4498         if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4499                 WORKITEM_FREE(jblkdep, D_JFREEBLK);
4500         else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4501                 WORKITEM_FREE(jblkdep, D_JTRUNC);
4502         else
4503                 panic("free_jblkdep: Unexpected type %s",
4504                     TYPENAME(jblkdep->jb_list.wk_type));
4505 }
4506
4507 /*
4508  * Free a single jseg once it is no longer referenced in memory or on
4509  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4510  * to disappear.
4511  */
4512 static void
4513 free_jseg(jseg, jblocks)
4514         struct jseg *jseg;
4515         struct jblocks *jblocks;
4516 {
4517         struct freework *freework;
4518
4519         /*
4520          * Free freework structures that were lingering to indicate freed
4521          * indirect blocks that forced journal write ordering on reallocate.
4522          */
4523         while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4524                 indirblk_remove(freework);
4525         if (jblocks->jb_oldestseg == jseg)
4526                 jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4527         TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4528         jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4529         KASSERT(LIST_EMPTY(&jseg->js_entries),
4530             ("free_jseg: Freed jseg has valid entries."));
4531         WORKITEM_FREE(jseg, D_JSEG);
4532 }
4533
4534 /*
4535  * Free all jsegs that meet the criteria for being reclaimed and update
4536  * oldestseg.
4537  */
4538 static void
4539 free_jsegs(jblocks)
4540         struct jblocks *jblocks;
4541 {
4542         struct jseg *jseg;
4543
4544         /*
4545          * Free only those jsegs which have none allocated before them to
4546          * preserve the journal space ordering.
4547          */
4548         while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4549                 /*
4550                  * Only reclaim space when nothing depends on this journal
4551                  * set and another set has written that it is no longer
4552                  * valid.
4553                  */
4554                 if (jseg->js_refs != 0) {
4555                         jblocks->jb_oldestseg = jseg;
4556                         return;
4557                 }
4558                 if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4559                         break;
4560                 if (jseg->js_seq > jblocks->jb_oldestwrseq)
4561                         break;
4562                 /*
4563                  * We can free jsegs that didn't write entries when
4564                  * oldestwrseq == js_seq.
4565                  */
4566                 if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4567                     jseg->js_cnt != 0)
4568                         break;
4569                 free_jseg(jseg, jblocks);
4570         }
4571         /*
4572          * If we exited the loop above we still must discover the
4573          * oldest valid segment.
4574          */
4575         if (jseg)
4576                 for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4577                      jseg = TAILQ_NEXT(jseg, js_next))
4578                         if (jseg->js_refs != 0)
4579                                 break;
4580         jblocks->jb_oldestseg = jseg;
4581         /*
4582          * The journal has no valid records but some jsegs may still be
4583          * waiting on oldestwrseq to advance.  We force a small record
4584          * out to permit these lingering records to be reclaimed.
4585          */
4586         if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4587                 jblocks->jb_needseg = 1;
4588 }
4589
4590 /*
4591  * Release one reference to a jseg and free it if the count reaches 0.  This
4592  * should eventually reclaim journal space as well.
4593  */
4594 static void
4595 rele_jseg(jseg)
4596         struct jseg *jseg;
4597 {
4598
4599         KASSERT(jseg->js_refs > 0,
4600             ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4601         if (--jseg->js_refs != 0)
4602                 return;
4603         free_jsegs(jseg->js_jblocks);
4604 }
4605
4606 /*
4607  * Release a jsegdep and decrement the jseg count.
4608  */
4609 static void
4610 free_jsegdep(jsegdep)
4611         struct jsegdep *jsegdep;
4612 {
4613
4614         if (jsegdep->jd_seg)
4615                 rele_jseg(jsegdep->jd_seg);
4616         WORKITEM_FREE(jsegdep, D_JSEGDEP);
4617 }
4618
4619 /*
4620  * Wait for a journal item to make it to disk.  Initiate journal processing
4621  * if required.
4622  */
4623 static int
4624 jwait(wk, waitfor)
4625         struct worklist *wk;
4626         int waitfor;
4627 {
4628
4629         LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4630         /*
4631          * Blocking journal waits cause slow synchronous behavior.  Record
4632          * stats on the frequency of these blocking operations.
4633          */
4634         if (waitfor == MNT_WAIT) {
4635                 stat_journal_wait++;
4636                 switch (wk->wk_type) {
4637                 case D_JREMREF:
4638                 case D_JMVREF:
4639                         stat_jwait_filepage++;
4640                         break;
4641                 case D_JTRUNC:
4642                 case D_JFREEBLK:
4643                         stat_jwait_freeblks++;
4644                         break;
4645                 case D_JNEWBLK:
4646                         stat_jwait_newblk++;
4647                         break;
4648                 case D_JADDREF:
4649                         stat_jwait_inode++;
4650                         break;
4651                 default:
4652                         break;
4653                 }
4654         }
4655         /*
4656          * If IO has not started we process the journal.  We can't mark the
4657          * worklist item as IOWAITING because we drop the lock while
4658          * processing the journal and the worklist entry may be freed after
4659          * this point.  The caller may call back in and re-issue the request.
4660          */
4661         if ((wk->wk_state & INPROGRESS) == 0) {
4662                 softdep_process_journal(wk->wk_mp, wk, waitfor);
4663                 if (waitfor != MNT_WAIT)
4664                         return (EBUSY);
4665                 return (0);
4666         }
4667         if (waitfor != MNT_WAIT)
4668                 return (EBUSY);
4669         wait_worklist(wk, "jwait");
4670         return (0);
4671 }
4672
4673 /*
4674  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4675  * appropriate.  This is a convenience function to reduce duplicate code
4676  * for the setup and revert functions below.
4677  */
4678 static struct inodedep *
4679 inodedep_lookup_ip(ip)
4680         struct inode *ip;
4681 {
4682         struct inodedep *inodedep;
4683
4684         KASSERT(ip->i_nlink >= ip->i_effnlink,
4685             ("inodedep_lookup_ip: bad delta"));
4686         (void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
4687             &inodedep);
4688         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4689         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4690
4691         return (inodedep);
4692 }
4693
4694 /*
4695  * Called prior to creating a new inode and linking it to a directory.  The
4696  * jaddref structure must already be allocated by softdep_setup_inomapdep
4697  * and it is discovered here so we can initialize the mode and update
4698  * nlinkdelta.
4699  */
4700 void
4701 softdep_setup_create(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_create called on non-softdep filesystem"));
4711         KASSERT(ip->i_nlink == 1,
4712             ("softdep_setup_create: Invalid link count."));
4713         dvp = ITOV(dp);
4714         ACQUIRE_LOCK(ITOUMP(dp));
4715         inodedep = inodedep_lookup_ip(ip);
4716         if (DOINGSUJ(dvp)) {
4717                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4718                     inoreflst);
4719                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4720                     ("softdep_setup_create: No addref structure present."));
4721         }
4722         softdep_prelink(dvp, NULL);
4723         FREE_LOCK(ITOUMP(dp));
4724 }
4725
4726 /*
4727  * Create a jaddref structure to track the addition of a DOTDOT link when
4728  * we are reparenting an inode as part of a rename.  This jaddref will be
4729  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4730  * non-journaling softdep.
4731  */
4732 void
4733 softdep_setup_dotdot_link(dp, ip)
4734         struct inode *dp;
4735         struct inode *ip;
4736 {
4737         struct inodedep *inodedep;
4738         struct jaddref *jaddref;
4739         struct vnode *dvp;
4740
4741         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4742             ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4743         dvp = ITOV(dp);
4744         jaddref = NULL;
4745         /*
4746          * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4747          * is used as a normal link would be.
4748          */
4749         if (DOINGSUJ(dvp))
4750                 jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4751                     dp->i_effnlink - 1, dp->i_mode);
4752         ACQUIRE_LOCK(ITOUMP(dp));
4753         inodedep = inodedep_lookup_ip(dp);
4754         if (jaddref)
4755                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4756                     if_deps);
4757         softdep_prelink(dvp, ITOV(ip));
4758         FREE_LOCK(ITOUMP(dp));
4759 }
4760
4761 /*
4762  * Create a jaddref structure to track a new link to an inode.  The directory
4763  * offset is not known until softdep_setup_directory_add or
4764  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4765  * softdep.
4766  */
4767 void
4768 softdep_setup_link(dp, ip)
4769         struct inode *dp;
4770         struct inode *ip;
4771 {
4772         struct inodedep *inodedep;
4773         struct jaddref *jaddref;
4774         struct vnode *dvp;
4775
4776         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4777             ("softdep_setup_link called on non-softdep filesystem"));
4778         dvp = ITOV(dp);
4779         jaddref = NULL;
4780         if (DOINGSUJ(dvp))
4781                 jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4782                     ip->i_mode);
4783         ACQUIRE_LOCK(ITOUMP(dp));
4784         inodedep = inodedep_lookup_ip(ip);
4785         if (jaddref)
4786                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4787                     if_deps);
4788         softdep_prelink(dvp, ITOV(ip));
4789         FREE_LOCK(ITOUMP(dp));
4790 }
4791
4792 /*
4793  * Called to create the jaddref structures to track . and .. references as
4794  * well as lookup and further initialize the incomplete jaddref created
4795  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4796  * nlinkdelta for non-journaling softdep.
4797  */
4798 void
4799 softdep_setup_mkdir(dp, ip)
4800         struct inode *dp;
4801         struct inode *ip;
4802 {
4803         struct inodedep *inodedep;
4804         struct jaddref *dotdotaddref;
4805         struct jaddref *dotaddref;
4806         struct jaddref *jaddref;
4807         struct vnode *dvp;
4808
4809         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4810             ("softdep_setup_mkdir called on non-softdep filesystem"));
4811         dvp = ITOV(dp);
4812         dotaddref = dotdotaddref = NULL;
4813         if (DOINGSUJ(dvp)) {
4814                 dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4815                     ip->i_mode);
4816                 dotaddref->ja_state |= MKDIR_BODY;
4817                 dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4818                     dp->i_effnlink - 1, dp->i_mode);
4819                 dotdotaddref->ja_state |= MKDIR_PARENT;
4820         }
4821         ACQUIRE_LOCK(ITOUMP(dp));
4822         inodedep = inodedep_lookup_ip(ip);
4823         if (DOINGSUJ(dvp)) {
4824                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4825                     inoreflst);
4826                 KASSERT(jaddref != NULL,
4827                     ("softdep_setup_mkdir: No addref structure present."));
4828                 KASSERT(jaddref->ja_parent == dp->i_number, 
4829                     ("softdep_setup_mkdir: bad parent %ju",
4830                     (uintmax_t)jaddref->ja_parent));
4831                 TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4832                     if_deps);
4833         }
4834         inodedep = inodedep_lookup_ip(dp);
4835         if (DOINGSUJ(dvp))
4836                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4837                     &dotdotaddref->ja_ref, if_deps);
4838         softdep_prelink(ITOV(dp), NULL);
4839         FREE_LOCK(ITOUMP(dp));
4840 }
4841
4842 /*
4843  * Called to track nlinkdelta of the inode and parent directories prior to
4844  * unlinking a directory.
4845  */
4846 void
4847 softdep_setup_rmdir(dp, ip)
4848         struct inode *dp;
4849         struct inode *ip;
4850 {
4851         struct vnode *dvp;
4852
4853         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4854             ("softdep_setup_rmdir called on non-softdep filesystem"));
4855         dvp = ITOV(dp);
4856         ACQUIRE_LOCK(ITOUMP(dp));
4857         (void) inodedep_lookup_ip(ip);
4858         (void) inodedep_lookup_ip(dp);
4859         softdep_prelink(dvp, ITOV(ip));
4860         FREE_LOCK(ITOUMP(dp));
4861 }
4862
4863 /*
4864  * Called to track nlinkdelta of the inode and parent directories prior to
4865  * unlink.
4866  */
4867 void
4868 softdep_setup_unlink(dp, ip)
4869         struct inode *dp;
4870         struct inode *ip;
4871 {
4872         struct vnode *dvp;
4873
4874         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4875             ("softdep_setup_unlink called on non-softdep filesystem"));
4876         dvp = ITOV(dp);
4877         ACQUIRE_LOCK(ITOUMP(dp));
4878         (void) inodedep_lookup_ip(ip);
4879         (void) inodedep_lookup_ip(dp);
4880         softdep_prelink(dvp, ITOV(ip));
4881         FREE_LOCK(ITOUMP(dp));
4882 }
4883
4884 /*
4885  * Called to release the journal structures created by a failed non-directory
4886  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4887  */
4888 void
4889 softdep_revert_create(dp, ip)
4890         struct inode *dp;
4891         struct inode *ip;
4892 {
4893         struct inodedep *inodedep;
4894         struct jaddref *jaddref;
4895         struct vnode *dvp;
4896
4897         KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
4898             ("softdep_revert_create called on non-softdep filesystem"));
4899         dvp = ITOV(dp);
4900         ACQUIRE_LOCK(ITOUMP(dp));
4901         inodedep = inodedep_lookup_ip(ip);
4902         if (DOINGSUJ(dvp)) {
4903                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4904                     inoreflst);
4905                 KASSERT(jaddref->ja_parent == dp->i_number,
4906                     ("softdep_revert_create: addref parent mismatch"));
4907                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4908         }
4909         FREE_LOCK(ITOUMP(dp));
4910 }
4911
4912 /*
4913  * Called to release the journal structures created by a failed link
4914  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4915  */
4916 void
4917 softdep_revert_link(dp, ip)
4918         struct inode *dp;
4919         struct inode *ip;
4920 {
4921         struct inodedep *inodedep;
4922         struct jaddref *jaddref;
4923         struct vnode *dvp;
4924
4925         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4926             ("softdep_revert_link called on non-softdep filesystem"));
4927         dvp = ITOV(dp);
4928         ACQUIRE_LOCK(ITOUMP(dp));
4929         inodedep = inodedep_lookup_ip(ip);
4930         if (DOINGSUJ(dvp)) {
4931                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4932                     inoreflst);
4933                 KASSERT(jaddref->ja_parent == dp->i_number,
4934                     ("softdep_revert_link: addref parent mismatch"));
4935                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4936         }
4937         FREE_LOCK(ITOUMP(dp));
4938 }
4939
4940 /*
4941  * Called to release the journal structures created by a failed mkdir
4942  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4943  */
4944 void
4945 softdep_revert_mkdir(dp, ip)
4946         struct inode *dp;
4947         struct inode *ip;
4948 {
4949         struct inodedep *inodedep;
4950         struct jaddref *jaddref;
4951         struct jaddref *dotaddref;
4952         struct vnode *dvp;
4953
4954         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4955             ("softdep_revert_mkdir called on non-softdep filesystem"));
4956         dvp = ITOV(dp);
4957
4958         ACQUIRE_LOCK(ITOUMP(dp));
4959         inodedep = inodedep_lookup_ip(dp);
4960         if (DOINGSUJ(dvp)) {
4961                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4962                     inoreflst);
4963                 KASSERT(jaddref->ja_parent == ip->i_number,
4964                     ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4965                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4966         }
4967         inodedep = inodedep_lookup_ip(ip);
4968         if (DOINGSUJ(dvp)) {
4969                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4970                     inoreflst);
4971                 KASSERT(jaddref->ja_parent == dp->i_number,
4972                     ("softdep_revert_mkdir: addref parent mismatch"));
4973                 dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4974                     inoreflst, if_deps);
4975                 cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4976                 KASSERT(dotaddref->ja_parent == ip->i_number,
4977                     ("softdep_revert_mkdir: dot addref parent mismatch"));
4978                 cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4979         }
4980         FREE_LOCK(ITOUMP(dp));
4981 }
4982
4983 /* 
4984  * Called to correct nlinkdelta after a failed rmdir.
4985  */
4986 void
4987 softdep_revert_rmdir(dp, ip)
4988         struct inode *dp;
4989         struct inode *ip;
4990 {
4991
4992         KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
4993             ("softdep_revert_rmdir called on non-softdep filesystem"));
4994         ACQUIRE_LOCK(ITOUMP(dp));
4995         (void) inodedep_lookup_ip(ip);
4996         (void) inodedep_lookup_ip(dp);
4997         FREE_LOCK(ITOUMP(dp));
4998 }
4999
5000 /*
5001  * Protecting the freemaps (or bitmaps).
5002  * 
5003  * To eliminate the need to execute fsck before mounting a filesystem
5004  * after a power failure, one must (conservatively) guarantee that the
5005  * on-disk copy of the bitmaps never indicate that a live inode or block is
5006  * free.  So, when a block or inode is allocated, the bitmap should be
5007  * updated (on disk) before any new pointers.  When a block or inode is
5008  * freed, the bitmap should not be updated until all pointers have been
5009  * reset.  The latter dependency is handled by the delayed de-allocation
5010  * approach described below for block and inode de-allocation.  The former
5011  * dependency is handled by calling the following procedure when a block or
5012  * inode is allocated. When an inode is allocated an "inodedep" is created
5013  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5014  * Each "inodedep" is also inserted into the hash indexing structure so
5015  * that any additional link additions can be made dependent on the inode
5016  * allocation.
5017  * 
5018  * The ufs filesystem maintains a number of free block counts (e.g., per
5019  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5020  * in addition to the bitmaps.  These counts are used to improve efficiency
5021  * during allocation and therefore must be consistent with the bitmaps.
5022  * There is no convenient way to guarantee post-crash consistency of these
5023  * counts with simple update ordering, for two main reasons: (1) The counts
5024  * and bitmaps for a single cylinder group block are not in the same disk
5025  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5026  * be written and the other not.  (2) Some of the counts are located in the
5027  * superblock rather than the cylinder group block. So, we focus our soft
5028  * updates implementation on protecting the bitmaps. When mounting a
5029  * filesystem, we recompute the auxiliary counts from the bitmaps.
5030  */
5031
5032 /*
5033  * Called just after updating the cylinder group block to allocate an inode.
5034  */
5035 void
5036 softdep_setup_inomapdep(bp, ip, newinum, mode)
5037         struct buf *bp;         /* buffer for cylgroup block with inode map */
5038         struct inode *ip;       /* inode related to allocation */
5039         ino_t newinum;          /* new inode number being allocated */
5040         int mode;
5041 {
5042         struct inodedep *inodedep;
5043         struct bmsafemap *bmsafemap;
5044         struct jaddref *jaddref;
5045         struct mount *mp;
5046         struct fs *fs;
5047
5048         mp = ITOVFS(ip);
5049         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5050             ("softdep_setup_inomapdep called on non-softdep filesystem"));
5051         fs = VFSTOUFS(mp)->um_fs;
5052         jaddref = NULL;
5053
5054         /*
5055          * Allocate the journal reference add structure so that the bitmap
5056          * can be dependent on it.
5057          */
5058         if (MOUNTEDSUJ(mp)) {
5059                 jaddref = newjaddref(ip, newinum, 0, 0, mode);
5060                 jaddref->ja_state |= NEWBLOCK;
5061         }
5062
5063         /*
5064          * Create a dependency for the newly allocated inode.
5065          * Panic if it already exists as something is seriously wrong.
5066          * Otherwise add it to the dependency list for the buffer holding
5067          * the cylinder group map from which it was allocated.
5068          *
5069          * We have to preallocate a bmsafemap entry in case it is needed
5070          * in bmsafemap_lookup since once we allocate the inodedep, we
5071          * have to finish initializing it before we can FREE_LOCK().
5072          * By preallocating, we avoid FREE_LOCK() while doing a malloc
5073          * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5074          * creating the inodedep as it can be freed during the time
5075          * that we FREE_LOCK() while allocating the inodedep. We must
5076          * call workitem_alloc() before entering the locked section as
5077          * it also acquires the lock and we must avoid trying doing so
5078          * recursively.
5079          */
5080         bmsafemap = malloc(sizeof(struct bmsafemap),
5081             M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5082         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5083         ACQUIRE_LOCK(ITOUMP(ip));
5084         if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5085                 panic("softdep_setup_inomapdep: dependency %p for new"
5086                     "inode already exists", inodedep);
5087         bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5088         if (jaddref) {
5089                 LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5090                 TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5091                     if_deps);
5092         } else {
5093                 inodedep->id_state |= ONDEPLIST;
5094                 LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5095         }
5096         inodedep->id_bmsafemap = bmsafemap;
5097         inodedep->id_state &= ~DEPCOMPLETE;
5098         FREE_LOCK(ITOUMP(ip));
5099 }
5100
5101 /*
5102  * Called just after updating the cylinder group block to
5103  * allocate block or fragment.
5104  */
5105 void
5106 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5107         struct buf *bp;         /* buffer for cylgroup block with block map */
5108         struct mount *mp;       /* filesystem doing allocation */
5109         ufs2_daddr_t newblkno;  /* number of newly allocated block */
5110         int frags;              /* Number of fragments. */
5111         int oldfrags;           /* Previous number of fragments for extend. */
5112 {
5113         struct newblk *newblk;
5114         struct bmsafemap *bmsafemap;
5115         struct jnewblk *jnewblk;
5116         struct ufsmount *ump;
5117         struct fs *fs;
5118
5119         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5120             ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5121         ump = VFSTOUFS(mp);
5122         fs = ump->um_fs;
5123         jnewblk = NULL;
5124         /*
5125          * Create a dependency for the newly allocated block.
5126          * Add it to the dependency list for the buffer holding
5127          * the cylinder group map from which it was allocated.
5128          */
5129         if (MOUNTEDSUJ(mp)) {
5130                 jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5131                 workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5132                 jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5133                 jnewblk->jn_state = ATTACHED;
5134                 jnewblk->jn_blkno = newblkno;
5135                 jnewblk->jn_frags = frags;
5136                 jnewblk->jn_oldfrags = oldfrags;
5137 #ifdef INVARIANTS
5138                 {
5139                         struct cg *cgp;
5140                         uint8_t *blksfree;
5141                         long bno;
5142                         int i;
5143         
5144                         cgp = (struct cg *)bp->b_data;
5145                         blksfree = cg_blksfree(cgp);
5146                         bno = dtogd(fs, jnewblk->jn_blkno);
5147                         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5148                             i++) {
5149                                 if (isset(blksfree, bno + i))
5150                                         panic("softdep_setup_blkmapdep: "
5151                                             "free fragment %d from %d-%d "
5152                                             "state 0x%X dep %p", i,
5153                                             jnewblk->jn_oldfrags,
5154                                             jnewblk->jn_frags,
5155                                             jnewblk->jn_state,
5156                                             jnewblk->jn_dep);
5157                         }
5158                 }
5159 #endif
5160         }
5161
5162         CTR3(KTR_SUJ,
5163             "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5164             newblkno, frags, oldfrags);
5165         ACQUIRE_LOCK(ump);
5166         if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5167                 panic("softdep_setup_blkmapdep: found block");
5168         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5169             dtog(fs, newblkno), NULL);
5170         if (jnewblk) {
5171                 jnewblk->jn_dep = (struct worklist *)newblk;
5172                 LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5173         } else {
5174                 newblk->nb_state |= ONDEPLIST;
5175                 LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5176         }
5177         newblk->nb_bmsafemap = bmsafemap;
5178         newblk->nb_jnewblk = jnewblk;
5179         FREE_LOCK(ump);
5180 }
5181
5182 #define BMSAFEMAP_HASH(ump, cg) \
5183       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5184
5185 static int
5186 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5187         struct bmsafemap_hashhead *bmsafemaphd;
5188         int cg;
5189         struct bmsafemap **bmsafemapp;
5190 {
5191         struct bmsafemap *bmsafemap;
5192
5193         LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5194                 if (bmsafemap->sm_cg == cg)
5195                         break;
5196         if (bmsafemap) {
5197                 *bmsafemapp = bmsafemap;
5198                 return (1);
5199         }
5200         *bmsafemapp = NULL;
5201
5202         return (0);
5203 }
5204
5205 /*
5206  * Find the bmsafemap associated with a cylinder group buffer.
5207  * If none exists, create one. The buffer must be locked when
5208  * this routine is called and this routine must be called with
5209  * the softdep lock held. To avoid giving up the lock while
5210  * allocating a new bmsafemap, a preallocated bmsafemap may be
5211  * provided. If it is provided but not needed, it is freed.
5212  */
5213 static struct bmsafemap *
5214 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5215         struct mount *mp;
5216         struct buf *bp;
5217         int cg;
5218         struct bmsafemap *newbmsafemap;
5219 {
5220         struct bmsafemap_hashhead *bmsafemaphd;
5221         struct bmsafemap *bmsafemap, *collision;
5222         struct worklist *wk;
5223         struct ufsmount *ump;
5224
5225         ump = VFSTOUFS(mp);
5226         LOCK_OWNED(ump);
5227         KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5228         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5229                 if (wk->wk_type == D_BMSAFEMAP) {
5230                         if (newbmsafemap)
5231                                 WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5232                         return (WK_BMSAFEMAP(wk));
5233                 }
5234         }
5235         bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5236         if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5237                 if (newbmsafemap)
5238                         WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5239                 return (bmsafemap);
5240         }
5241         if (newbmsafemap) {
5242                 bmsafemap = newbmsafemap;
5243         } else {
5244                 FREE_LOCK(ump);
5245                 bmsafemap = malloc(sizeof(struct bmsafemap),
5246                         M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5247                 workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5248                 ACQUIRE_LOCK(ump);
5249         }
5250         bmsafemap->sm_buf = bp;
5251         LIST_INIT(&bmsafemap->sm_inodedephd);
5252         LIST_INIT(&bmsafemap->sm_inodedepwr);
5253         LIST_INIT(&bmsafemap->sm_newblkhd);
5254         LIST_INIT(&bmsafemap->sm_newblkwr);
5255         LIST_INIT(&bmsafemap->sm_jaddrefhd);
5256         LIST_INIT(&bmsafemap->sm_jnewblkhd);
5257         LIST_INIT(&bmsafemap->sm_freehd);
5258         LIST_INIT(&bmsafemap->sm_freewr);
5259         if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5260                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5261                 return (collision);
5262         }
5263         bmsafemap->sm_cg = cg;
5264         LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5265         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5266         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5267         return (bmsafemap);
5268 }
5269
5270 /*
5271  * Direct block allocation dependencies.
5272  * 
5273  * When a new block is allocated, the corresponding disk locations must be
5274  * initialized (with zeros or new data) before the on-disk inode points to
5275  * them.  Also, the freemap from which the block was allocated must be
5276  * updated (on disk) before the inode's pointer. These two dependencies are
5277  * independent of each other and are needed for all file blocks and indirect
5278  * blocks that are pointed to directly by the inode.  Just before the
5279  * "in-core" version of the inode is updated with a newly allocated block
5280  * number, a procedure (below) is called to setup allocation dependency
5281  * structures.  These structures are removed when the corresponding
5282  * dependencies are satisfied or when the block allocation becomes obsolete
5283  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5284  * fragment that gets upgraded).  All of these cases are handled in
5285  * procedures described later.
5286  * 
5287  * When a file extension causes a fragment to be upgraded, either to a larger
5288  * fragment or to a full block, the on-disk location may change (if the
5289  * previous fragment could not simply be extended). In this case, the old
5290  * fragment must be de-allocated, but not until after the inode's pointer has
5291  * been updated. In most cases, this is handled by later procedures, which
5292  * will construct a "freefrag" structure to be added to the workitem queue
5293  * when the inode update is complete (or obsolete).  The main exception to
5294  * this is when an allocation occurs while a pending allocation dependency
5295  * (for the same block pointer) remains.  This case is handled in the main
5296  * allocation dependency setup procedure by immediately freeing the
5297  * unreferenced fragments.
5298  */ 
5299 void 
5300 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5301         struct inode *ip;       /* inode to which block is being added */
5302         ufs_lbn_t off;          /* block pointer within inode */
5303         ufs2_daddr_t newblkno;  /* disk block number being added */
5304         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
5305         long newsize;           /* size of new block */
5306         long oldsize;           /* size of new block */
5307         struct buf *bp;         /* bp for allocated block */
5308 {
5309         struct allocdirect *adp, *oldadp;
5310         struct allocdirectlst *adphead;
5311         struct freefrag *freefrag;
5312         struct inodedep *inodedep;
5313         struct pagedep *pagedep;
5314         struct jnewblk *jnewblk;
5315         struct newblk *newblk;
5316         struct mount *mp;
5317         ufs_lbn_t lbn;
5318
5319         lbn = bp->b_lblkno;
5320         mp = ITOVFS(ip);
5321         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5322             ("softdep_setup_allocdirect called on non-softdep filesystem"));
5323         if (oldblkno && oldblkno != newblkno)
5324                 /*
5325                  * The usual case is that a smaller fragment that
5326                  * was just allocated has been replaced with a bigger
5327                  * fragment or a full-size block. If it is marked as
5328                  * B_DELWRI, the current contents have not been written
5329                  * to disk. It is possible that the block was written
5330                  * earlier, but very uncommon. If the block has never
5331                  * been written, there is no need to send a BIO_DELETE
5332                  * for it when it is freed. The gain from avoiding the
5333                  * TRIMs for the common case of unwritten blocks far
5334                  * exceeds the cost of the write amplification for the
5335                  * uncommon case of failing to send a TRIM for a block
5336                  * that had been written.
5337                  */
5338                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5339                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5340         else
5341                 freefrag = NULL;
5342
5343         CTR6(KTR_SUJ,
5344             "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5345             "off %jd newsize %ld oldsize %d",
5346             ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5347         ACQUIRE_LOCK(ITOUMP(ip));
5348         if (off >= UFS_NDADDR) {
5349                 if (lbn > 0)
5350                         panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5351                             lbn, off);
5352                 /* allocating an indirect block */
5353                 if (oldblkno != 0)
5354                         panic("softdep_setup_allocdirect: non-zero indir");
5355         } else {
5356                 if (off != lbn)
5357                         panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5358                             lbn, off);
5359                 /*
5360                  * Allocating a direct block.
5361                  *
5362                  * If we are allocating a directory block, then we must
5363                  * allocate an associated pagedep to track additions and
5364                  * deletions.
5365                  */
5366                 if ((ip->i_mode & IFMT) == IFDIR)
5367                         pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5368                             &pagedep);
5369         }
5370         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5371                 panic("softdep_setup_allocdirect: lost block");
5372         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5373             ("softdep_setup_allocdirect: newblk already initialized"));
5374         /*
5375          * Convert the newblk to an allocdirect.
5376          */
5377         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5378         adp = (struct allocdirect *)newblk;
5379         newblk->nb_freefrag = freefrag;
5380         adp->ad_offset = off;
5381         adp->ad_oldblkno = oldblkno;
5382         adp->ad_newsize = newsize;
5383         adp->ad_oldsize = oldsize;
5384
5385         /*
5386          * Finish initializing the journal.
5387          */
5388         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5389                 jnewblk->jn_ino = ip->i_number;
5390                 jnewblk->jn_lbn = lbn;
5391                 add_to_journal(&jnewblk->jn_list);
5392         }
5393         if (freefrag && freefrag->ff_jdep != NULL &&
5394             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5395                 add_to_journal(freefrag->ff_jdep);
5396         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5397         adp->ad_inodedep = inodedep;
5398
5399         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5400         /*
5401          * The list of allocdirects must be kept in sorted and ascending
5402          * order so that the rollback routines can quickly determine the
5403          * first uncommitted block (the size of the file stored on disk
5404          * ends at the end of the lowest committed fragment, or if there
5405          * are no fragments, at the end of the highest committed block).
5406          * Since files generally grow, the typical case is that the new
5407          * block is to be added at the end of the list. We speed this
5408          * special case by checking against the last allocdirect in the
5409          * list before laboriously traversing the list looking for the
5410          * insertion point.
5411          */
5412         adphead = &inodedep->id_newinoupdt;
5413         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5414         if (oldadp == NULL || oldadp->ad_offset <= off) {
5415                 /* insert at end of list */
5416                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5417                 if (oldadp != NULL && oldadp->ad_offset == off)
5418                         allocdirect_merge(adphead, adp, oldadp);
5419                 FREE_LOCK(ITOUMP(ip));
5420                 return;
5421         }
5422         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5423                 if (oldadp->ad_offset >= off)
5424                         break;
5425         }
5426         if (oldadp == NULL)
5427                 panic("softdep_setup_allocdirect: lost entry");
5428         /* insert in middle of list */
5429         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5430         if (oldadp->ad_offset == off)
5431                 allocdirect_merge(adphead, adp, oldadp);
5432
5433         FREE_LOCK(ITOUMP(ip));
5434 }
5435
5436 /*
5437  * Merge a newer and older journal record to be stored either in a
5438  * newblock or freefrag.  This handles aggregating journal records for
5439  * fragment allocation into a second record as well as replacing a
5440  * journal free with an aborted journal allocation.  A segment for the
5441  * oldest record will be placed on wkhd if it has been written.  If not
5442  * the segment for the newer record will suffice.
5443  */
5444 static struct worklist *
5445 jnewblk_merge(new, old, wkhd)
5446         struct worklist *new;
5447         struct worklist *old;
5448         struct workhead *wkhd;
5449 {
5450         struct jnewblk *njnewblk;
5451         struct jnewblk *jnewblk;
5452
5453         /* Handle NULLs to simplify callers. */
5454         if (new == NULL)
5455                 return (old);
5456         if (old == NULL)
5457                 return (new);
5458         /* Replace a jfreefrag with a jnewblk. */
5459         if (new->wk_type == D_JFREEFRAG) {
5460                 if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5461                         panic("jnewblk_merge: blkno mismatch: %p, %p",
5462                             old, new);
5463                 cancel_jfreefrag(WK_JFREEFRAG(new));
5464                 return (old);
5465         }
5466         if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5467                 panic("jnewblk_merge: Bad type: old %d new %d\n",
5468                     old->wk_type, new->wk_type);
5469         /*
5470          * Handle merging of two jnewblk records that describe
5471          * different sets of fragments in the same block.
5472          */
5473         jnewblk = WK_JNEWBLK(old);
5474         njnewblk = WK_JNEWBLK(new);
5475         if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5476                 panic("jnewblk_merge: Merging disparate blocks.");
5477         /*
5478          * The record may be rolled back in the cg.
5479          */
5480         if (jnewblk->jn_state & UNDONE) {
5481                 jnewblk->jn_state &= ~UNDONE;
5482                 njnewblk->jn_state |= UNDONE;
5483                 njnewblk->jn_state &= ~ATTACHED;
5484         }
5485         /*
5486          * We modify the newer addref and free the older so that if neither
5487          * has been written the most up-to-date copy will be on disk.  If
5488          * both have been written but rolled back we only temporarily need
5489          * one of them to fix the bits when the cg write completes.
5490          */
5491         jnewblk->jn_state |= ATTACHED | COMPLETE;
5492         njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5493         cancel_jnewblk(jnewblk, wkhd);
5494         WORKLIST_REMOVE(&jnewblk->jn_list);
5495         free_jnewblk(jnewblk);
5496         return (new);
5497 }
5498
5499 /*
5500  * Replace an old allocdirect dependency with a newer one.
5501  */
5502 static void
5503 allocdirect_merge(adphead, newadp, oldadp)
5504         struct allocdirectlst *adphead; /* head of list holding allocdirects */
5505         struct allocdirect *newadp;     /* allocdirect being added */
5506         struct allocdirect *oldadp;     /* existing allocdirect being checked */
5507 {
5508         struct worklist *wk;
5509         struct freefrag *freefrag;
5510
5511         freefrag = NULL;
5512         LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5513         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5514             newadp->ad_oldsize != oldadp->ad_newsize ||
5515             newadp->ad_offset >= UFS_NDADDR)
5516                 panic("%s %jd != new %jd || old size %ld != new %ld",
5517                     "allocdirect_merge: old blkno",
5518                     (intmax_t)newadp->ad_oldblkno,
5519                     (intmax_t)oldadp->ad_newblkno,
5520                     newadp->ad_oldsize, oldadp->ad_newsize);
5521         newadp->ad_oldblkno = oldadp->ad_oldblkno;
5522         newadp->ad_oldsize = oldadp->ad_oldsize;
5523         /*
5524          * If the old dependency had a fragment to free or had never
5525          * previously had a block allocated, then the new dependency
5526          * can immediately post its freefrag and adopt the old freefrag.
5527          * This action is done by swapping the freefrag dependencies.
5528          * The new dependency gains the old one's freefrag, and the
5529          * old one gets the new one and then immediately puts it on
5530          * the worklist when it is freed by free_newblk. It is
5531          * not possible to do this swap when the old dependency had a
5532          * non-zero size but no previous fragment to free. This condition
5533          * arises when the new block is an extension of the old block.
5534          * Here, the first part of the fragment allocated to the new
5535          * dependency is part of the block currently claimed on disk by
5536          * the old dependency, so cannot legitimately be freed until the
5537          * conditions for the new dependency are fulfilled.
5538          */
5539         freefrag = newadp->ad_freefrag;
5540         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5541                 newadp->ad_freefrag = oldadp->ad_freefrag;
5542                 oldadp->ad_freefrag = freefrag;
5543         }
5544         /*
5545          * If we are tracking a new directory-block allocation,
5546          * move it from the old allocdirect to the new allocdirect.
5547          */
5548         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5549                 WORKLIST_REMOVE(wk);
5550                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5551                         panic("allocdirect_merge: extra newdirblk");
5552                 WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5553         }
5554         TAILQ_REMOVE(adphead, oldadp, ad_next);
5555         /*
5556          * We need to move any journal dependencies over to the freefrag
5557          * that releases this block if it exists.  Otherwise we are
5558          * extending an existing block and we'll wait until that is
5559          * complete to release the journal space and extend the
5560          * new journal to cover this old space as well.
5561          */
5562         if (freefrag == NULL) {
5563                 if (oldadp->ad_newblkno != newadp->ad_newblkno)
5564                         panic("allocdirect_merge: %jd != %jd",
5565                             oldadp->ad_newblkno, newadp->ad_newblkno);
5566                 newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5567                     jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list, 
5568                     &oldadp->ad_block.nb_jnewblk->jn_list,
5569                     &newadp->ad_block.nb_jwork);
5570                 oldadp->ad_block.nb_jnewblk = NULL;
5571                 cancel_newblk(&oldadp->ad_block, NULL,
5572                     &newadp->ad_block.nb_jwork);
5573         } else {
5574                 wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5575                     &freefrag->ff_list, &freefrag->ff_jwork);
5576                 freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5577                     &freefrag->ff_jwork);
5578         }
5579         free_newblk(&oldadp->ad_block);
5580 }
5581
5582 /*
5583  * Allocate a jfreefrag structure to journal a single block free.
5584  */
5585 static struct jfreefrag *
5586 newjfreefrag(freefrag, ip, blkno, size, lbn)
5587         struct freefrag *freefrag;
5588         struct inode *ip;
5589         ufs2_daddr_t blkno;
5590         long size;
5591         ufs_lbn_t lbn;
5592 {
5593         struct jfreefrag *jfreefrag;
5594         struct fs *fs;
5595
5596         fs = ITOFS(ip);
5597         jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5598             M_SOFTDEP_FLAGS);
5599         workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5600         jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5601         jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5602         jfreefrag->fr_ino = ip->i_number;
5603         jfreefrag->fr_lbn = lbn;
5604         jfreefrag->fr_blkno = blkno;
5605         jfreefrag->fr_frags = numfrags(fs, size);
5606         jfreefrag->fr_freefrag = freefrag;
5607
5608         return (jfreefrag);
5609 }
5610
5611 /*
5612  * Allocate a new freefrag structure.
5613  */
5614 static struct freefrag *
5615 newfreefrag(ip, blkno, size, lbn, key)
5616         struct inode *ip;
5617         ufs2_daddr_t blkno;
5618         long size;
5619         ufs_lbn_t lbn;
5620         u_long key;
5621 {
5622         struct freefrag *freefrag;
5623         struct ufsmount *ump;
5624         struct fs *fs;
5625
5626         CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5627             ip->i_number, blkno, size, lbn);
5628         ump = ITOUMP(ip);
5629         fs = ump->um_fs;
5630         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5631                 panic("newfreefrag: frag size");
5632         freefrag = malloc(sizeof(struct freefrag),
5633             M_FREEFRAG, M_SOFTDEP_FLAGS);
5634         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5635         freefrag->ff_state = ATTACHED;
5636         LIST_INIT(&freefrag->ff_jwork);
5637         freefrag->ff_inum = ip->i_number;
5638         freefrag->ff_vtype = ITOV(ip)->v_type;
5639         freefrag->ff_blkno = blkno;
5640         freefrag->ff_fragsize = size;
5641         freefrag->ff_key = key;
5642
5643         if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5644                 freefrag->ff_jdep = (struct worklist *)
5645                     newjfreefrag(freefrag, ip, blkno, size, lbn);
5646         } else {
5647                 freefrag->ff_state |= DEPCOMPLETE;
5648                 freefrag->ff_jdep = NULL;
5649         }
5650
5651         return (freefrag);
5652 }
5653
5654 /*
5655  * This workitem de-allocates fragments that were replaced during
5656  * file block allocation.
5657  */
5658 static void 
5659 handle_workitem_freefrag(freefrag)
5660         struct freefrag *freefrag;
5661 {
5662         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5663         struct workhead wkhd;
5664
5665         CTR3(KTR_SUJ,
5666             "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5667             freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5668         /*
5669          * It would be illegal to add new completion items to the
5670          * freefrag after it was schedule to be done so it must be
5671          * safe to modify the list head here.
5672          */
5673         LIST_INIT(&wkhd);
5674         ACQUIRE_LOCK(ump);
5675         LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5676         /*
5677          * If the journal has not been written we must cancel it here.
5678          */
5679         if (freefrag->ff_jdep) {
5680                 if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5681                         panic("handle_workitem_freefrag: Unexpected type %d\n",
5682                             freefrag->ff_jdep->wk_type);
5683                 cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5684         }
5685         FREE_LOCK(ump);
5686         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5687            freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
5688            &wkhd, freefrag->ff_key);
5689         ACQUIRE_LOCK(ump);
5690         WORKITEM_FREE(freefrag, D_FREEFRAG);
5691         FREE_LOCK(ump);
5692 }
5693
5694 /*
5695  * Set up a dependency structure for an external attributes data block.
5696  * This routine follows much of the structure of softdep_setup_allocdirect.
5697  * See the description of softdep_setup_allocdirect above for details.
5698  */
5699 void 
5700 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5701         struct inode *ip;
5702         ufs_lbn_t off;
5703         ufs2_daddr_t newblkno;
5704         ufs2_daddr_t oldblkno;
5705         long newsize;
5706         long oldsize;
5707         struct buf *bp;
5708 {
5709         struct allocdirect *adp, *oldadp;
5710         struct allocdirectlst *adphead;
5711         struct freefrag *freefrag;
5712         struct inodedep *inodedep;
5713         struct jnewblk *jnewblk;
5714         struct newblk *newblk;
5715         struct mount *mp;
5716         struct ufsmount *ump;
5717         ufs_lbn_t lbn;
5718
5719         mp = ITOVFS(ip);
5720         ump = VFSTOUFS(mp);
5721         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5722             ("softdep_setup_allocext called on non-softdep filesystem"));
5723         KASSERT(off < UFS_NXADDR,
5724             ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
5725
5726         lbn = bp->b_lblkno;
5727         if (oldblkno && oldblkno != newblkno)
5728                 /*
5729                  * The usual case is that a smaller fragment that
5730                  * was just allocated has been replaced with a bigger
5731                  * fragment or a full-size block. If it is marked as
5732                  * B_DELWRI, the current contents have not been written
5733                  * to disk. It is possible that the block was written
5734                  * earlier, but very uncommon. If the block has never
5735                  * been written, there is no need to send a BIO_DELETE
5736                  * for it when it is freed. The gain from avoiding the
5737                  * TRIMs for the common case of unwritten blocks far
5738                  * exceeds the cost of the write amplification for the
5739                  * uncommon case of failing to send a TRIM for a block
5740                  * that had been written.
5741                  */
5742                 freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5743                     (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5744         else
5745                 freefrag = NULL;
5746
5747         ACQUIRE_LOCK(ump);
5748         if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5749                 panic("softdep_setup_allocext: lost block");
5750         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5751             ("softdep_setup_allocext: newblk already initialized"));
5752         /*
5753          * Convert the newblk to an allocdirect.
5754          */
5755         WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5756         adp = (struct allocdirect *)newblk;
5757         newblk->nb_freefrag = freefrag;
5758         adp->ad_offset = off;
5759         adp->ad_oldblkno = oldblkno;
5760         adp->ad_newsize = newsize;
5761         adp->ad_oldsize = oldsize;
5762         adp->ad_state |=  EXTDATA;
5763
5764         /*
5765          * Finish initializing the journal.
5766          */
5767         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5768                 jnewblk->jn_ino = ip->i_number;
5769                 jnewblk->jn_lbn = lbn;
5770                 add_to_journal(&jnewblk->jn_list);
5771         }
5772         if (freefrag && freefrag->ff_jdep != NULL &&
5773             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5774                 add_to_journal(freefrag->ff_jdep);
5775         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5776         adp->ad_inodedep = inodedep;
5777
5778         WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5779         /*
5780          * The list of allocdirects must be kept in sorted and ascending
5781          * order so that the rollback routines can quickly determine the
5782          * first uncommitted block (the size of the file stored on disk
5783          * ends at the end of the lowest committed fragment, or if there
5784          * are no fragments, at the end of the highest committed block).
5785          * Since files generally grow, the typical case is that the new
5786          * block is to be added at the end of the list. We speed this
5787          * special case by checking against the last allocdirect in the
5788          * list before laboriously traversing the list looking for the
5789          * insertion point.
5790          */
5791         adphead = &inodedep->id_newextupdt;
5792         oldadp = TAILQ_LAST(adphead, allocdirectlst);
5793         if (oldadp == NULL || oldadp->ad_offset <= off) {
5794                 /* insert at end of list */
5795                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5796                 if (oldadp != NULL && oldadp->ad_offset == off)
5797                         allocdirect_merge(adphead, adp, oldadp);
5798                 FREE_LOCK(ump);
5799                 return;
5800         }
5801         TAILQ_FOREACH(oldadp, adphead, ad_next) {
5802                 if (oldadp->ad_offset >= off)
5803                         break;
5804         }
5805         if (oldadp == NULL)
5806                 panic("softdep_setup_allocext: lost entry");
5807         /* insert in middle of list */
5808         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5809         if (oldadp->ad_offset == off)
5810                 allocdirect_merge(adphead, adp, oldadp);
5811         FREE_LOCK(ump);
5812 }
5813
5814 /*
5815  * Indirect block allocation dependencies.
5816  * 
5817  * The same dependencies that exist for a direct block also exist when
5818  * a new block is allocated and pointed to by an entry in a block of
5819  * indirect pointers. The undo/redo states described above are also
5820  * used here. Because an indirect block contains many pointers that
5821  * may have dependencies, a second copy of the entire in-memory indirect
5822  * block is kept. The buffer cache copy is always completely up-to-date.
5823  * The second copy, which is used only as a source for disk writes,
5824  * contains only the safe pointers (i.e., those that have no remaining
5825  * update dependencies). The second copy is freed when all pointers
5826  * are safe. The cache is not allowed to replace indirect blocks with
5827  * pending update dependencies. If a buffer containing an indirect
5828  * block with dependencies is written, these routines will mark it
5829  * dirty again. It can only be successfully written once all the
5830  * dependencies are removed. The ffs_fsync routine in conjunction with
5831  * softdep_sync_metadata work together to get all the dependencies
5832  * removed so that a file can be successfully written to disk. Three
5833  * procedures are used when setting up indirect block pointer
5834  * dependencies. The division is necessary because of the organization
5835  * of the "balloc" routine and because of the distinction between file
5836  * pages and file metadata blocks.
5837  */
5838
5839 /*
5840  * Allocate a new allocindir structure.
5841  */
5842 static struct allocindir *
5843 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5844         struct inode *ip;       /* inode for file being extended */
5845         int ptrno;              /* offset of pointer in indirect block */
5846         ufs2_daddr_t newblkno;  /* disk block number being added */
5847         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5848         ufs_lbn_t lbn;
5849 {
5850         struct newblk *newblk;
5851         struct allocindir *aip;
5852         struct freefrag *freefrag;
5853         struct jnewblk *jnewblk;
5854
5855         if (oldblkno)
5856                 freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
5857                     SINGLETON_KEY);
5858         else
5859                 freefrag = NULL;
5860         ACQUIRE_LOCK(ITOUMP(ip));
5861         if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
5862                 panic("new_allocindir: lost block");
5863         KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5864             ("newallocindir: newblk already initialized"));
5865         WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5866         newblk->nb_freefrag = freefrag;
5867         aip = (struct allocindir *)newblk;
5868         aip->ai_offset = ptrno;
5869         aip->ai_oldblkno = oldblkno;
5870         aip->ai_lbn = lbn;
5871         if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5872                 jnewblk->jn_ino = ip->i_number;
5873                 jnewblk->jn_lbn = lbn;
5874                 add_to_journal(&jnewblk->jn_list);
5875         }
5876         if (freefrag && freefrag->ff_jdep != NULL &&
5877             freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5878                 add_to_journal(freefrag->ff_jdep);
5879         return (aip);
5880 }
5881
5882 /*
5883  * Called just before setting an indirect block pointer
5884  * to a newly allocated file page.
5885  */
5886 void
5887 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5888         struct inode *ip;       /* inode for file being extended */
5889         ufs_lbn_t lbn;          /* allocated block number within file */
5890         struct buf *bp;         /* buffer with indirect blk referencing page */
5891         int ptrno;              /* offset of pointer in indirect block */
5892         ufs2_daddr_t newblkno;  /* disk block number being added */
5893         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
5894         struct buf *nbp;        /* buffer holding allocated page */
5895 {
5896         struct inodedep *inodedep;
5897         struct freefrag *freefrag;
5898         struct allocindir *aip;
5899         struct pagedep *pagedep;
5900         struct mount *mp;
5901         struct ufsmount *ump;
5902
5903         mp = ITOVFS(ip);
5904         ump = VFSTOUFS(mp);
5905         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5906             ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5907         KASSERT(lbn == nbp->b_lblkno,
5908             ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5909             lbn, bp->b_lblkno));
5910         CTR4(KTR_SUJ,
5911             "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5912             "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5913         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5914         aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5915         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5916         /*
5917          * If we are allocating a directory page, then we must
5918          * allocate an associated pagedep to track additions and
5919          * deletions.
5920          */
5921         if ((ip->i_mode & IFMT) == IFDIR)
5922                 pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5923         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5924         freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5925         FREE_LOCK(ump);
5926         if (freefrag)
5927                 handle_workitem_freefrag(freefrag);
5928 }
5929
5930 /*
5931  * Called just before setting an indirect block pointer to a
5932  * newly allocated indirect block.
5933  */
5934 void
5935 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5936         struct buf *nbp;        /* newly allocated indirect block */
5937         struct inode *ip;       /* inode for file being extended */
5938         struct buf *bp;         /* indirect block referencing allocated block */
5939         int ptrno;              /* offset of pointer in indirect block */
5940         ufs2_daddr_t newblkno;  /* disk block number being added */
5941 {
5942         struct inodedep *inodedep;
5943         struct allocindir *aip;
5944         struct ufsmount *ump;
5945         ufs_lbn_t lbn;
5946
5947         ump = ITOUMP(ip);
5948         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
5949             ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5950         CTR3(KTR_SUJ,
5951             "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5952             ip->i_number, newblkno, ptrno);
5953         lbn = nbp->b_lblkno;
5954         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5955         aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5956         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
5957         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5958         if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5959                 panic("softdep_setup_allocindir_meta: Block already existed");
5960         FREE_LOCK(ump);
5961 }
5962
5963 static void
5964 indirdep_complete(indirdep)
5965         struct indirdep *indirdep;
5966 {
5967         struct allocindir *aip;
5968
5969         LIST_REMOVE(indirdep, ir_next);
5970         indirdep->ir_state |= DEPCOMPLETE;
5971
5972         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5973                 LIST_REMOVE(aip, ai_next);
5974                 free_newblk(&aip->ai_block);
5975         }
5976         /*
5977          * If this indirdep is not attached to a buf it was simply waiting
5978          * on completion to clear completehd.  free_indirdep() asserts
5979          * that nothing is dangling.
5980          */
5981         if ((indirdep->ir_state & ONWORKLIST) == 0)
5982                 free_indirdep(indirdep);
5983 }
5984
5985 static struct indirdep *
5986 indirdep_lookup(mp, ip, bp)
5987         struct mount *mp;
5988         struct inode *ip;
5989         struct buf *bp;
5990 {
5991         struct indirdep *indirdep, *newindirdep;
5992         struct newblk *newblk;
5993         struct ufsmount *ump;
5994         struct worklist *wk;
5995         struct fs *fs;
5996         ufs2_daddr_t blkno;
5997
5998         ump = VFSTOUFS(mp);
5999         LOCK_OWNED(ump);
6000         indirdep = NULL;
6001         newindirdep = NULL;
6002         fs = ump->um_fs;
6003         for (;;) {
6004                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6005                         if (wk->wk_type != D_INDIRDEP)
6006                                 continue;
6007                         indirdep = WK_INDIRDEP(wk);
6008                         break;
6009                 }
6010                 /* Found on the buffer worklist, no new structure to free. */
6011                 if (indirdep != NULL && newindirdep == NULL)
6012                         return (indirdep);
6013                 if (indirdep != NULL && newindirdep != NULL)
6014                         panic("indirdep_lookup: simultaneous create");
6015                 /* None found on the buffer and a new structure is ready. */
6016                 if (indirdep == NULL && newindirdep != NULL)
6017                         break;
6018                 /* None found and no new structure available. */
6019                 FREE_LOCK(ump);
6020                 newindirdep = malloc(sizeof(struct indirdep),
6021                     M_INDIRDEP, M_SOFTDEP_FLAGS);
6022                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6023                 newindirdep->ir_state = ATTACHED;
6024                 if (I_IS_UFS1(ip))
6025                         newindirdep->ir_state |= UFS1FMT;
6026                 TAILQ_INIT(&newindirdep->ir_trunc);
6027                 newindirdep->ir_saveddata = NULL;
6028                 LIST_INIT(&newindirdep->ir_deplisthd);
6029                 LIST_INIT(&newindirdep->ir_donehd);
6030                 LIST_INIT(&newindirdep->ir_writehd);
6031                 LIST_INIT(&newindirdep->ir_completehd);
6032                 if (bp->b_blkno == bp->b_lblkno) {
6033                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6034                             NULL, NULL);
6035                         bp->b_blkno = blkno;
6036                 }
6037                 newindirdep->ir_freeblks = NULL;
6038                 newindirdep->ir_savebp =
6039                     getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6040                 newindirdep->ir_bp = bp;
6041                 BUF_KERNPROC(newindirdep->ir_savebp);
6042                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6043                 ACQUIRE_LOCK(ump);
6044         }
6045         indirdep = newindirdep;
6046         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6047         /*
6048          * If the block is not yet allocated we don't set DEPCOMPLETE so
6049          * that we don't free dependencies until the pointers are valid.
6050          * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6051          * than using the hash.
6052          */
6053         if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6054                 LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6055         else
6056                 indirdep->ir_state |= DEPCOMPLETE;
6057         return (indirdep);
6058 }
6059
6060 /*
6061  * Called to finish the allocation of the "aip" allocated
6062  * by one of the two routines above.
6063  */
6064 static struct freefrag *
6065 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6066         struct buf *bp;         /* in-memory copy of the indirect block */
6067         struct inode *ip;       /* inode for file being extended */
6068         struct inodedep *inodedep; /* Inodedep for ip */
6069         struct allocindir *aip; /* allocindir allocated by the above routines */
6070         ufs_lbn_t lbn;          /* Logical block number for this block. */
6071 {
6072         struct fs *fs;
6073         struct indirdep *indirdep;
6074         struct allocindir *oldaip;
6075         struct freefrag *freefrag;
6076         struct mount *mp;
6077         struct ufsmount *ump;
6078
6079         mp = ITOVFS(ip);
6080         ump = VFSTOUFS(mp);
6081         LOCK_OWNED(ump);
6082         fs = ump->um_fs;
6083         if (bp->b_lblkno >= 0)
6084                 panic("setup_allocindir_phase2: not indir blk");
6085         KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6086             ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6087         indirdep = indirdep_lookup(mp, ip, bp);
6088         KASSERT(indirdep->ir_savebp != NULL,
6089             ("setup_allocindir_phase2 NULL ir_savebp"));
6090         aip->ai_indirdep = indirdep;
6091         /*
6092          * Check for an unwritten dependency for this indirect offset.  If
6093          * there is, merge the old dependency into the new one.  This happens
6094          * as a result of reallocblk only.
6095          */
6096         freefrag = NULL;
6097         if (aip->ai_oldblkno != 0) {
6098                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6099                         if (oldaip->ai_offset == aip->ai_offset) {
6100                                 freefrag = allocindir_merge(aip, oldaip);
6101                                 goto done;
6102                         }
6103                 }
6104                 LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6105                         if (oldaip->ai_offset == aip->ai_offset) {
6106                                 freefrag = allocindir_merge(aip, oldaip);
6107                                 goto done;
6108                         }
6109                 }
6110         }
6111 done:
6112         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6113         return (freefrag);
6114 }
6115
6116 /*
6117  * Merge two allocindirs which refer to the same block.  Move newblock
6118  * dependencies and setup the freefrags appropriately.
6119  */
6120 static struct freefrag *
6121 allocindir_merge(aip, oldaip)
6122         struct allocindir *aip;
6123         struct allocindir *oldaip;
6124 {
6125         struct freefrag *freefrag;
6126         struct worklist *wk;
6127
6128         if (oldaip->ai_newblkno != aip->ai_oldblkno)
6129                 panic("allocindir_merge: blkno");
6130         aip->ai_oldblkno = oldaip->ai_oldblkno;
6131         freefrag = aip->ai_freefrag;
6132         aip->ai_freefrag = oldaip->ai_freefrag;
6133         oldaip->ai_freefrag = NULL;
6134         KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6135         /*
6136          * If we are tracking a new directory-block allocation,
6137          * move it from the old allocindir to the new allocindir.
6138          */
6139         if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6140                 WORKLIST_REMOVE(wk);
6141                 if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6142                         panic("allocindir_merge: extra newdirblk");
6143                 WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6144         }
6145         /*
6146          * We can skip journaling for this freefrag and just complete
6147          * any pending journal work for the allocindir that is being
6148          * removed after the freefrag completes.
6149          */
6150         if (freefrag->ff_jdep)
6151                 cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6152         LIST_REMOVE(oldaip, ai_next);
6153         freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6154             &freefrag->ff_list, &freefrag->ff_jwork);
6155         free_newblk(&oldaip->ai_block);
6156
6157         return (freefrag);
6158 }
6159
6160 static inline void
6161 setup_freedirect(freeblks, ip, i, needj)
6162         struct freeblks *freeblks;
6163         struct inode *ip;
6164         int i;
6165         int needj;
6166 {
6167         struct ufsmount *ump;
6168         ufs2_daddr_t blkno;
6169         int frags;
6170
6171         blkno = DIP(ip, i_db[i]);
6172         if (blkno == 0)
6173                 return;
6174         DIP_SET(ip, i_db[i], 0);
6175         ump = ITOUMP(ip);
6176         frags = sblksize(ump->um_fs, ip->i_size, i);
6177         frags = numfrags(ump->um_fs, frags);
6178         newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6179 }
6180
6181 static inline void
6182 setup_freeext(freeblks, ip, i, needj)
6183         struct freeblks *freeblks;
6184         struct inode *ip;
6185         int i;
6186         int needj;
6187 {
6188         struct ufsmount *ump;
6189         ufs2_daddr_t blkno;
6190         int frags;
6191
6192         blkno = ip->i_din2->di_extb[i];
6193         if (blkno == 0)
6194                 return;
6195         ip->i_din2->di_extb[i] = 0;
6196         ump = ITOUMP(ip);
6197         frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6198         frags = numfrags(ump->um_fs, frags);
6199         newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6200 }
6201
6202 static inline void
6203 setup_freeindir(freeblks, ip, i, lbn, needj)
6204         struct freeblks *freeblks;
6205         struct inode *ip;
6206         int i;
6207         ufs_lbn_t lbn;
6208         int needj;
6209 {
6210         struct ufsmount *ump;
6211         ufs2_daddr_t blkno;
6212
6213         blkno = DIP(ip, i_ib[i]);
6214         if (blkno == 0)
6215                 return;
6216         DIP_SET(ip, i_ib[i], 0);
6217         ump = ITOUMP(ip);
6218         newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6219             0, needj);
6220 }
6221
6222 static inline struct freeblks *
6223 newfreeblks(mp, ip)
6224         struct mount *mp;
6225         struct inode *ip;
6226 {
6227         struct freeblks *freeblks;
6228
6229         freeblks = malloc(sizeof(struct freeblks),
6230                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6231         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6232         LIST_INIT(&freeblks->fb_jblkdephd);
6233         LIST_INIT(&freeblks->fb_jwork);
6234         freeblks->fb_ref = 0;
6235         freeblks->fb_cgwait = 0;
6236         freeblks->fb_state = ATTACHED;
6237         freeblks->fb_uid = ip->i_uid;
6238         freeblks->fb_inum = ip->i_number;
6239         freeblks->fb_vtype = ITOV(ip)->v_type;
6240         freeblks->fb_modrev = DIP(ip, i_modrev);
6241         freeblks->fb_devvp = ITODEVVP(ip);
6242         freeblks->fb_chkcnt = 0;
6243         freeblks->fb_len = 0;
6244
6245         return (freeblks);
6246 }
6247
6248 static void
6249 trunc_indirdep(indirdep, freeblks, bp, off)
6250         struct indirdep *indirdep;
6251         struct freeblks *freeblks;
6252         struct buf *bp;
6253         int off;
6254 {
6255         struct allocindir *aip, *aipn;
6256
6257         /*
6258          * The first set of allocindirs won't be in savedbp.
6259          */
6260         LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6261                 if (aip->ai_offset > off)
6262                         cancel_allocindir(aip, bp, freeblks, 1);
6263         LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6264                 if (aip->ai_offset > off)
6265                         cancel_allocindir(aip, bp, freeblks, 1);
6266         /*
6267          * These will exist in savedbp.
6268          */
6269         LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6270                 if (aip->ai_offset > off)
6271                         cancel_allocindir(aip, NULL, freeblks, 0);
6272         LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6273                 if (aip->ai_offset > off)
6274                         cancel_allocindir(aip, NULL, freeblks, 0);
6275 }
6276
6277 /*
6278  * Follow the chain of indirects down to lastlbn creating a freework
6279  * structure for each.  This will be used to start indir_trunc() at
6280  * the right offset and create the journal records for the parrtial
6281  * truncation.  A second step will handle the truncated dependencies.
6282  */
6283 static int
6284 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6285         struct freeblks *freeblks;
6286         struct inode *ip;
6287         ufs_lbn_t lbn;
6288         ufs_lbn_t lastlbn;
6289         ufs2_daddr_t blkno;
6290 {
6291         struct indirdep *indirdep;
6292         struct indirdep *indirn;
6293         struct freework *freework;
6294         struct newblk *newblk;
6295         struct mount *mp;
6296         struct ufsmount *ump;
6297         struct buf *bp;
6298         uint8_t *start;
6299         uint8_t *end;
6300         ufs_lbn_t lbnadd;
6301         int level;
6302         int error;
6303         int off;
6304
6305
6306         freework = NULL;
6307         if (blkno == 0)
6308                 return (0);
6309         mp = freeblks->fb_list.wk_mp;
6310         ump = VFSTOUFS(mp);
6311         /*
6312          * Here, calls to VOP_BMAP() will fail.  However, we already have
6313          * the on-disk address, so we just pass it to bread() instead of
6314          * having bread() attempt to calculate it using VOP_BMAP().
6315          */
6316         error = breadn_flags(ITOV(ip), lbn, blkptrtodb(ump, blkno),
6317             (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6318         if (error)
6319                 return (error);
6320         level = lbn_level(lbn);
6321         lbnadd = lbn_offset(ump->um_fs, level);
6322         /*
6323          * Compute the offset of the last block we want to keep.  Store
6324          * in the freework the first block we want to completely free.
6325          */
6326         off = (lastlbn - -(lbn + level)) / lbnadd;
6327         if (off + 1 == NINDIR(ump->um_fs))
6328                 goto nowork;
6329         freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6330         /*
6331          * Link the freework into the indirdep.  This will prevent any new
6332          * allocations from proceeding until we are finished with the
6333          * truncate and the block is written.
6334          */
6335         ACQUIRE_LOCK(ump);
6336         indirdep = indirdep_lookup(mp, ip, bp);
6337         if (indirdep->ir_freeblks)
6338                 panic("setup_trunc_indir: indirdep already truncated.");
6339         TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6340         freework->fw_indir = indirdep;
6341         /*
6342          * Cancel any allocindirs that will not make it to disk.
6343          * We have to do this for all copies of the indirdep that
6344          * live on this newblk.
6345          */
6346         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6347                 if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6348                     &newblk) == 0)
6349                         panic("setup_trunc_indir: lost block");
6350                 LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6351                         trunc_indirdep(indirn, freeblks, bp, off);
6352         } else
6353                 trunc_indirdep(indirdep, freeblks, bp, off);
6354         FREE_LOCK(ump);
6355         /*
6356          * Creation is protected by the buf lock. The saveddata is only
6357          * needed if a full truncation follows a partial truncation but it
6358          * is difficult to allocate in that case so we fetch it anyway.
6359          */
6360         if (indirdep->ir_saveddata == NULL)
6361                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6362                     M_SOFTDEP_FLAGS);
6363 nowork:
6364         /* Fetch the blkno of the child and the zero start offset. */
6365         if (I_IS_UFS1(ip)) {
6366                 blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6367                 start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6368         } else {
6369                 blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6370                 start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6371         }
6372         if (freework) {
6373                 /* Zero the truncated pointers. */
6374                 end = bp->b_data + bp->b_bcount;
6375                 bzero(start, end - start);
6376                 bdwrite(bp);
6377         } else
6378                 bqrelse(bp);
6379         if (level == 0)
6380                 return (0);
6381         lbn++; /* adjust level */
6382         lbn -= (off * lbnadd);
6383         return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6384 }
6385
6386 /*
6387  * Complete the partial truncation of an indirect block setup by
6388  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6389  * copy and writes them to disk before the freeblks is allowed to complete.
6390  */
6391 static void
6392 complete_trunc_indir(freework)
6393         struct freework *freework;
6394 {
6395         struct freework *fwn;
6396         struct indirdep *indirdep;
6397         struct ufsmount *ump;
6398         struct buf *bp;
6399         uintptr_t start;
6400         int count;
6401
6402         ump = VFSTOUFS(freework->fw_list.wk_mp);
6403         LOCK_OWNED(ump);
6404         indirdep = freework->fw_indir;
6405         for (;;) {
6406                 bp = indirdep->ir_bp;
6407                 /* See if the block was discarded. */
6408                 if (bp == NULL)
6409                         break;
6410                 /* Inline part of getdirtybuf().  We dont want bremfree. */
6411                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6412                         break;
6413                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6414                     LOCK_PTR(ump)) == 0)
6415                         BUF_UNLOCK(bp);
6416                 ACQUIRE_LOCK(ump);
6417         }
6418         freework->fw_state |= DEPCOMPLETE;
6419         TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6420         /*
6421          * Zero the pointers in the saved copy.
6422          */
6423         if (indirdep->ir_state & UFS1FMT)
6424                 start = sizeof(ufs1_daddr_t);
6425         else
6426                 start = sizeof(ufs2_daddr_t);
6427         start *= freework->fw_start;
6428         count = indirdep->ir_savebp->b_bcount - start;
6429         start += (uintptr_t)indirdep->ir_savebp->b_data;
6430         bzero((char *)start, count);
6431         /*
6432          * We need to start the next truncation in the list if it has not
6433          * been started yet.
6434          */
6435         fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6436         if (fwn != NULL) {
6437                 if (fwn->fw_freeblks == indirdep->ir_freeblks)
6438                         TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6439                 if ((fwn->fw_state & ONWORKLIST) == 0)
6440                         freework_enqueue(fwn);
6441         }
6442         /*
6443          * If bp is NULL the block was fully truncated, restore
6444          * the saved block list otherwise free it if it is no
6445          * longer needed.
6446          */
6447         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6448                 if (bp == NULL)
6449                         bcopy(indirdep->ir_saveddata,
6450                             indirdep->ir_savebp->b_data,
6451                             indirdep->ir_savebp->b_bcount);
6452                 free(indirdep->ir_saveddata, M_INDIRDEP);
6453                 indirdep->ir_saveddata = NULL;
6454         }
6455         /*
6456          * When bp is NULL there is a full truncation pending.  We
6457          * must wait for this full truncation to be journaled before
6458          * we can release this freework because the disk pointers will
6459          * never be written as zero.
6460          */
6461         if (bp == NULL)  {
6462                 if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6463                         handle_written_freework(freework);
6464                 else
6465                         WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6466                            &freework->fw_list);
6467         } else {
6468                 /* Complete when the real copy is written. */
6469                 WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6470                 BUF_UNLOCK(bp);
6471         }
6472 }
6473
6474 /*
6475  * Calculate the number of blocks we are going to release where datablocks
6476  * is the current total and length is the new file size.
6477  */
6478 static ufs2_daddr_t
6479 blkcount(fs, datablocks, length)
6480         struct fs *fs;
6481         ufs2_daddr_t datablocks;
6482         off_t length;
6483 {
6484         off_t totblks, numblks;
6485
6486         totblks = 0;
6487         numblks = howmany(length, fs->fs_bsize);
6488         if (numblks <= UFS_NDADDR) {
6489                 totblks = howmany(length, fs->fs_fsize);
6490                 goto out;
6491         }
6492         totblks = blkstofrags(fs, numblks);
6493         numblks -= UFS_NDADDR;
6494         /*
6495          * Count all single, then double, then triple indirects required.
6496          * Subtracting one indirects worth of blocks for each pass
6497          * acknowledges one of each pointed to by the inode.
6498          */
6499         for (;;) {
6500                 totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6501                 numblks -= NINDIR(fs);
6502                 if (numblks <= 0)
6503                         break;
6504                 numblks = howmany(numblks, NINDIR(fs));
6505         }
6506 out:
6507         totblks = fsbtodb(fs, totblks);
6508         /*
6509          * Handle sparse files.  We can't reclaim more blocks than the inode
6510          * references.  We will correct it later in handle_complete_freeblks()
6511          * when we know the real count.
6512          */
6513         if (totblks > datablocks)
6514                 return (0);
6515         return (datablocks - totblks);
6516 }
6517
6518 /*
6519  * Handle freeblocks for journaled softupdate filesystems.
6520  *
6521  * Contrary to normal softupdates, we must preserve the block pointers in
6522  * indirects until their subordinates are free.  This is to avoid journaling
6523  * every block that is freed which may consume more space than the journal
6524  * itself.  The recovery program will see the free block journals at the
6525  * base of the truncated area and traverse them to reclaim space.  The
6526  * pointers in the inode may be cleared immediately after the journal
6527  * records are written because each direct and indirect pointer in the
6528  * inode is recorded in a journal.  This permits full truncation to proceed
6529  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6530  *
6531  * The algorithm is as follows:
6532  * 1) Traverse the in-memory state and create journal entries to release
6533  *    the relevant blocks and full indirect trees.
6534  * 2) Traverse the indirect block chain adding partial truncation freework
6535  *    records to indirects in the path to lastlbn.  The freework will
6536  *    prevent new allocation dependencies from being satisfied in this
6537  *    indirect until the truncation completes.
6538  * 3) Read and lock the inode block, performing an update with the new size
6539  *    and pointers.  This prevents truncated data from becoming valid on
6540  *    disk through step 4.
6541  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6542  *    eliminate journal work for those records that do not require it.
6543  * 5) Schedule the journal records to be written followed by the inode block.
6544  * 6) Allocate any necessary frags for the end of file.
6545  * 7) Zero any partially truncated blocks.
6546  *
6547  * From this truncation proceeds asynchronously using the freework and
6548  * indir_trunc machinery.  The file will not be extended again into a
6549  * partially truncated indirect block until all work is completed but
6550  * the normal dependency mechanism ensures that it is rolled back/forward
6551  * as appropriate.  Further truncation may occur without delay and is
6552  * serialized in indir_trunc().
6553  */
6554 void
6555 softdep_journal_freeblocks(ip, cred, length, flags)
6556         struct inode *ip;       /* The inode whose length is to be reduced */
6557         struct ucred *cred;
6558         off_t length;           /* The new length for the file */
6559         int flags;              /* IO_EXT and/or IO_NORMAL */
6560 {
6561         struct freeblks *freeblks, *fbn;
6562         struct worklist *wk, *wkn;
6563         struct inodedep *inodedep;
6564         struct jblkdep *jblkdep;
6565         struct allocdirect *adp, *adpn;
6566         struct ufsmount *ump;
6567         struct fs *fs;
6568         struct buf *bp;
6569         struct vnode *vp;
6570         struct mount *mp;
6571         ufs2_daddr_t extblocks, datablocks;
6572         ufs_lbn_t tmpval, lbn, lastlbn;
6573         int frags, lastoff, iboff, allocblock, needj, error, i;
6574
6575         ump = ITOUMP(ip);
6576         mp = UFSTOVFS(ump);
6577         fs = ump->um_fs;
6578         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6579             ("softdep_journal_freeblocks called on non-softdep filesystem"));
6580         vp = ITOV(ip);
6581         needj = 1;
6582         iboff = -1;
6583         allocblock = 0;
6584         extblocks = 0;
6585         datablocks = 0;
6586         frags = 0;
6587         freeblks = newfreeblks(mp, ip);
6588         ACQUIRE_LOCK(ump);
6589         /*
6590          * If we're truncating a removed file that will never be written
6591          * we don't need to journal the block frees.  The canceled journals
6592          * for the allocations will suffice.
6593          */
6594         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6595         if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6596             length == 0)
6597                 needj = 0;
6598         CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6599             ip->i_number, length, needj);
6600         FREE_LOCK(ump);
6601         /*
6602          * Calculate the lbn that we are truncating to.  This results in -1
6603          * if we're truncating the 0 bytes.  So it is the last lbn we want
6604          * to keep, not the first lbn we want to truncate.
6605          */
6606         lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6607         lastoff = blkoff(fs, length);
6608         /*
6609          * Compute frags we are keeping in lastlbn.  0 means all.
6610          */
6611         if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6612                 frags = fragroundup(fs, lastoff);
6613                 /* adp offset of last valid allocdirect. */
6614                 iboff = lastlbn;
6615         } else if (lastlbn > 0)
6616                 iboff = UFS_NDADDR;
6617         if (fs->fs_magic == FS_UFS2_MAGIC)
6618                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6619         /*
6620          * Handle normal data blocks and indirects.  This section saves
6621          * values used after the inode update to complete frag and indirect
6622          * truncation.
6623          */
6624         if ((flags & IO_NORMAL) != 0) {
6625                 /*
6626                  * Handle truncation of whole direct and indirect blocks.
6627                  */
6628                 for (i = iboff + 1; i < UFS_NDADDR; i++)
6629                         setup_freedirect(freeblks, ip, i, needj);
6630                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6631                     i < UFS_NIADDR;
6632                     i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6633                         /* Release a whole indirect tree. */
6634                         if (lbn > lastlbn) {
6635                                 setup_freeindir(freeblks, ip, i, -lbn -i,
6636                                     needj);
6637                                 continue;
6638                         }
6639                         iboff = i + UFS_NDADDR;
6640                         /*
6641                          * Traverse partially truncated indirect tree.
6642                          */
6643                         if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6644                                 setup_trunc_indir(freeblks, ip, -lbn - i,
6645                                     lastlbn, DIP(ip, i_ib[i]));
6646                 }
6647                 /*
6648                  * Handle partial truncation to a frag boundary.
6649                  */
6650                 if (frags) {
6651                         ufs2_daddr_t blkno;
6652                         long oldfrags;
6653
6654                         oldfrags = blksize(fs, ip, lastlbn);
6655                         blkno = DIP(ip, i_db[lastlbn]);
6656                         if (blkno && oldfrags != frags) {
6657                                 oldfrags -= frags;
6658                                 oldfrags = numfrags(fs, oldfrags);
6659                                 blkno += numfrags(fs, frags);
6660                                 newfreework(ump, freeblks, NULL, lastlbn,
6661                                     blkno, oldfrags, 0, needj);
6662                                 if (needj)
6663                                         adjust_newfreework(freeblks,
6664                                             numfrags(fs, frags));
6665                         } else if (blkno == 0)
6666                                 allocblock = 1;
6667                 }
6668                 /*
6669                  * Add a journal record for partial truncate if we are
6670                  * handling indirect blocks.  Non-indirects need no extra
6671                  * journaling.
6672                  */
6673                 if (length != 0 && lastlbn >= UFS_NDADDR) {
6674                         UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
6675                         newjtrunc(freeblks, length, 0);
6676                 }
6677                 ip->i_size = length;
6678                 DIP_SET(ip, i_size, ip->i_size);
6679                 datablocks = DIP(ip, i_blocks) - extblocks;
6680                 if (length != 0)
6681                         datablocks = blkcount(fs, datablocks, length);
6682                 freeblks->fb_len = length;
6683         }
6684         if ((flags & IO_EXT) != 0) {
6685                 for (i = 0; i < UFS_NXADDR; i++)
6686                         setup_freeext(freeblks, ip, i, needj);
6687                 ip->i_din2->di_extsize = 0;
6688                 datablocks += extblocks;
6689         }
6690 #ifdef QUOTA
6691         /* Reference the quotas in case the block count is wrong in the end. */
6692         quotaref(vp, freeblks->fb_quota);
6693         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6694 #endif
6695         freeblks->fb_chkcnt = -datablocks;
6696         UFS_LOCK(ump);
6697         fs->fs_pendingblocks += datablocks;
6698         UFS_UNLOCK(ump);
6699         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6700         /*
6701          * Handle truncation of incomplete alloc direct dependencies.  We
6702          * hold the inode block locked to prevent incomplete dependencies
6703          * from reaching the disk while we are eliminating those that
6704          * have been truncated.  This is a partially inlined ffs_update().
6705          */
6706         ufs_itimes(vp);
6707         ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6708         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6709             (int)fs->fs_bsize, cred, &bp);
6710         if (error) {
6711                 softdep_error("softdep_journal_freeblocks", error);
6712                 return;
6713         }
6714         if (bp->b_bufsize == fs->fs_bsize)
6715                 bp->b_flags |= B_CLUSTEROK;
6716         softdep_update_inodeblock(ip, bp, 0);
6717         if (ump->um_fstype == UFS1) {
6718                 *((struct ufs1_dinode *)bp->b_data +
6719                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6720         } else {
6721                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6722                 *((struct ufs2_dinode *)bp->b_data +
6723                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6724         }
6725         ACQUIRE_LOCK(ump);
6726         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6727         if ((inodedep->id_state & IOSTARTED) != 0)
6728                 panic("softdep_setup_freeblocks: inode busy");
6729         /*
6730          * Add the freeblks structure to the list of operations that
6731          * must await the zero'ed inode being written to disk. If we
6732          * still have a bitmap dependency (needj), then the inode
6733          * has never been written to disk, so we can process the
6734          * freeblks below once we have deleted the dependencies.
6735          */
6736         if (needj)
6737                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6738         else
6739                 freeblks->fb_state |= COMPLETE;
6740         if ((flags & IO_NORMAL) != 0) {
6741                 TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6742                         if (adp->ad_offset > iboff)
6743                                 cancel_allocdirect(&inodedep->id_inoupdt, adp,
6744                                     freeblks);
6745                         /*
6746                          * Truncate the allocdirect.  We could eliminate
6747                          * or modify journal records as well.
6748                          */
6749                         else if (adp->ad_offset == iboff && frags)
6750                                 adp->ad_newsize = frags;
6751                 }
6752         }
6753         if ((flags & IO_EXT) != 0)
6754                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
6755                         cancel_allocdirect(&inodedep->id_extupdt, adp,
6756                             freeblks);
6757         /*
6758          * Scan the bufwait list for newblock dependencies that will never
6759          * make it to disk.
6760          */
6761         LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6762                 if (wk->wk_type != D_ALLOCDIRECT)
6763                         continue;
6764                 adp = WK_ALLOCDIRECT(wk);
6765                 if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6766                     ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6767                         cancel_jfreeblk(freeblks, adp->ad_newblkno);
6768                         cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6769                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6770                 }
6771         }
6772         /*
6773          * Add journal work.
6774          */
6775         LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6776                 add_to_journal(&jblkdep->jb_list);
6777         FREE_LOCK(ump);
6778         bdwrite(bp);
6779         /*
6780          * Truncate dependency structures beyond length.
6781          */
6782         trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6783         /*
6784          * This is only set when we need to allocate a fragment because
6785          * none existed at the end of a frag-sized file.  It handles only
6786          * allocating a new, zero filled block.
6787          */
6788         if (allocblock) {
6789                 ip->i_size = length - lastoff;
6790                 DIP_SET(ip, i_size, ip->i_size);
6791                 error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6792                 if (error != 0) {
6793                         softdep_error("softdep_journal_freeblks", error);
6794                         return;
6795                 }
6796                 ip->i_size = length;
6797                 DIP_SET(ip, i_size, length);
6798                 UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
6799                 allocbuf(bp, frags);
6800                 ffs_update(vp, 0);
6801                 bawrite(bp);
6802         } else if (lastoff != 0 && vp->v_type != VDIR) {
6803                 int size;
6804
6805                 /*
6806                  * Zero the end of a truncated frag or block.
6807                  */
6808                 size = sblksize(fs, length, lastlbn);
6809                 error = bread(vp, lastlbn, size, cred, &bp);
6810                 if (error) {
6811                         softdep_error("softdep_journal_freeblks", error);
6812                         return;
6813                 }
6814                 bzero((char *)bp->b_data + lastoff, size - lastoff);
6815                 bawrite(bp);
6816
6817         }
6818         ACQUIRE_LOCK(ump);
6819         inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6820         TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6821         freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6822         /*
6823          * We zero earlier truncations so they don't erroneously
6824          * update i_blocks.
6825          */
6826         if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6827                 TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6828                         fbn->fb_len = 0;
6829         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6830             LIST_EMPTY(&freeblks->fb_jblkdephd))
6831                 freeblks->fb_state |= INPROGRESS;
6832         else
6833                 freeblks = NULL;
6834         FREE_LOCK(ump);
6835         if (freeblks)
6836                 handle_workitem_freeblocks(freeblks, 0);
6837         trunc_pages(ip, length, extblocks, flags);
6838
6839 }
6840
6841 /*
6842  * Flush a JOP_SYNC to the journal.
6843  */
6844 void
6845 softdep_journal_fsync(ip)
6846         struct inode *ip;
6847 {
6848         struct jfsync *jfsync;
6849         struct ufsmount *ump;
6850
6851         ump = ITOUMP(ip);
6852         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6853             ("softdep_journal_fsync called on non-softdep filesystem"));
6854         if ((ip->i_flag & IN_TRUNCATED) == 0)
6855                 return;
6856         ip->i_flag &= ~IN_TRUNCATED;
6857         jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6858         workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
6859         jfsync->jfs_size = ip->i_size;
6860         jfsync->jfs_ino = ip->i_number;
6861         ACQUIRE_LOCK(ump);
6862         add_to_journal(&jfsync->jfs_list);
6863         jwait(&jfsync->jfs_list, MNT_WAIT);
6864         FREE_LOCK(ump);
6865 }
6866
6867 /*
6868  * Block de-allocation dependencies.
6869  * 
6870  * When blocks are de-allocated, the on-disk pointers must be nullified before
6871  * the blocks are made available for use by other files.  (The true
6872  * requirement is that old pointers must be nullified before new on-disk
6873  * pointers are set.  We chose this slightly more stringent requirement to
6874  * reduce complexity.) Our implementation handles this dependency by updating
6875  * the inode (or indirect block) appropriately but delaying the actual block
6876  * de-allocation (i.e., freemap and free space count manipulation) until
6877  * after the updated versions reach stable storage.  After the disk is
6878  * updated, the blocks can be safely de-allocated whenever it is convenient.
6879  * This implementation handles only the common case of reducing a file's
6880  * length to zero. Other cases are handled by the conventional synchronous
6881  * write approach.
6882  *
6883  * The ffs implementation with which we worked double-checks
6884  * the state of the block pointers and file size as it reduces
6885  * a file's length.  Some of this code is replicated here in our
6886  * soft updates implementation.  The freeblks->fb_chkcnt field is
6887  * used to transfer a part of this information to the procedure
6888  * that eventually de-allocates the blocks.
6889  *
6890  * This routine should be called from the routine that shortens
6891  * a file's length, before the inode's size or block pointers
6892  * are modified. It will save the block pointer information for
6893  * later release and zero the inode so that the calling routine
6894  * can release it.
6895  */
6896 void
6897 softdep_setup_freeblocks(ip, length, flags)
6898         struct inode *ip;       /* The inode whose length is to be reduced */
6899         off_t length;           /* The new length for the file */
6900         int flags;              /* IO_EXT and/or IO_NORMAL */
6901 {
6902         struct ufs1_dinode *dp1;
6903         struct ufs2_dinode *dp2;
6904         struct freeblks *freeblks;
6905         struct inodedep *inodedep;
6906         struct allocdirect *adp;
6907         struct ufsmount *ump;
6908         struct buf *bp;
6909         struct fs *fs;
6910         ufs2_daddr_t extblocks, datablocks;
6911         struct mount *mp;
6912         int i, delay, error;
6913         ufs_lbn_t tmpval;
6914         ufs_lbn_t lbn;
6915
6916         ump = ITOUMP(ip);
6917         mp = UFSTOVFS(ump);
6918         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6919             ("softdep_setup_freeblocks called on non-softdep filesystem"));
6920         CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6921             ip->i_number, length);
6922         KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6923         fs = ump->um_fs;
6924         if ((error = bread(ump->um_devvp,
6925             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6926             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6927                 brelse(bp);
6928                 softdep_error("softdep_setup_freeblocks", error);
6929                 return;
6930         }
6931         freeblks = newfreeblks(mp, ip);
6932         extblocks = 0;
6933         datablocks = 0;
6934         if (fs->fs_magic == FS_UFS2_MAGIC)
6935                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6936         if ((flags & IO_NORMAL) != 0) {
6937                 for (i = 0; i < UFS_NDADDR; i++)
6938                         setup_freedirect(freeblks, ip, i, 0);
6939                 for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6940                     i < UFS_NIADDR;
6941                     i++, lbn += tmpval, tmpval *= NINDIR(fs))
6942                         setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6943                 ip->i_size = 0;
6944                 DIP_SET(ip, i_size, 0);
6945                 datablocks = DIP(ip, i_blocks) - extblocks;
6946         }
6947         if ((flags & IO_EXT) != 0) {
6948                 for (i = 0; i < UFS_NXADDR; i++)
6949                         setup_freeext(freeblks, ip, i, 0);
6950                 ip->i_din2->di_extsize = 0;
6951                 datablocks += extblocks;
6952         }
6953 #ifdef QUOTA
6954         /* Reference the quotas in case the block count is wrong in the end. */
6955         quotaref(ITOV(ip), freeblks->fb_quota);
6956         (void) chkdq(ip, -datablocks, NOCRED, FORCE);
6957 #endif
6958         freeblks->fb_chkcnt = -datablocks;
6959         UFS_LOCK(ump);
6960         fs->fs_pendingblocks += datablocks;
6961         UFS_UNLOCK(ump);
6962         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6963         /*
6964          * Push the zero'ed inode to its disk buffer so that we are free
6965          * to delete its dependencies below. Once the dependencies are gone
6966          * the buffer can be safely released.
6967          */
6968         if (ump->um_fstype == UFS1) {
6969                 dp1 = ((struct ufs1_dinode *)bp->b_data +
6970                     ino_to_fsbo(fs, ip->i_number));
6971                 ip->i_din1->di_freelink = dp1->di_freelink;
6972                 *dp1 = *ip->i_din1;
6973         } else {
6974                 dp2 = ((struct ufs2_dinode *)bp->b_data +
6975                     ino_to_fsbo(fs, ip->i_number));
6976                 ip->i_din2->di_freelink = dp2->di_freelink;
6977                 ffs_update_dinode_ckhash(fs, ip->i_din2);
6978                 *dp2 = *ip->i_din2;
6979         }
6980         /*
6981          * Find and eliminate any inode dependencies.
6982          */
6983         ACQUIRE_LOCK(ump);
6984         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6985         if ((inodedep->id_state & IOSTARTED) != 0)
6986                 panic("softdep_setup_freeblocks: inode busy");
6987         /*
6988          * Add the freeblks structure to the list of operations that
6989          * must await the zero'ed inode being written to disk. If we
6990          * still have a bitmap dependency (delay == 0), then the inode
6991          * has never been written to disk, so we can process the
6992          * freeblks below once we have deleted the dependencies.
6993          */
6994         delay = (inodedep->id_state & DEPCOMPLETE);
6995         if (delay)
6996                 WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6997         else
6998                 freeblks->fb_state |= COMPLETE;
6999         /*
7000          * Because the file length has been truncated to zero, any
7001          * pending block allocation dependency structures associated
7002          * with this inode are obsolete and can simply be de-allocated.
7003          * We must first merge the two dependency lists to get rid of
7004          * any duplicate freefrag structures, then purge the merged list.
7005          * If we still have a bitmap dependency, then the inode has never
7006          * been written to disk, so we can free any fragments without delay.
7007          */
7008         if (flags & IO_NORMAL) {
7009                 merge_inode_lists(&inodedep->id_newinoupdt,
7010                     &inodedep->id_inoupdt);
7011                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7012                         cancel_allocdirect(&inodedep->id_inoupdt, adp,
7013                             freeblks);
7014         }
7015         if (flags & IO_EXT) {
7016                 merge_inode_lists(&inodedep->id_newextupdt,
7017                     &inodedep->id_extupdt);
7018                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7019                         cancel_allocdirect(&inodedep->id_extupdt, adp,
7020                             freeblks);
7021         }
7022         FREE_LOCK(ump);
7023         bdwrite(bp);
7024         trunc_dependencies(ip, freeblks, -1, 0, flags);
7025         ACQUIRE_LOCK(ump);
7026         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7027                 (void) free_inodedep(inodedep);
7028         freeblks->fb_state |= DEPCOMPLETE;
7029         /*
7030          * If the inode with zeroed block pointers is now on disk
7031          * we can start freeing blocks.
7032          */  
7033         if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7034                 freeblks->fb_state |= INPROGRESS;
7035         else
7036                 freeblks = NULL;
7037         FREE_LOCK(ump);
7038         if (freeblks)
7039                 handle_workitem_freeblocks(freeblks, 0);
7040         trunc_pages(ip, length, extblocks, flags);
7041 }
7042
7043 /*
7044  * Eliminate pages from the page cache that back parts of this inode and
7045  * adjust the vnode pager's idea of our size.  This prevents stale data
7046  * from hanging around in the page cache.
7047  */
7048 static void
7049 trunc_pages(ip, length, extblocks, flags)
7050         struct inode *ip;
7051         off_t length;
7052         ufs2_daddr_t extblocks;
7053         int flags;
7054 {
7055         struct vnode *vp;
7056         struct fs *fs;
7057         ufs_lbn_t lbn;
7058         off_t end, extend;
7059
7060         vp = ITOV(ip);
7061         fs = ITOFS(ip);
7062         extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7063         if ((flags & IO_EXT) != 0)
7064                 vn_pages_remove(vp, extend, 0);
7065         if ((flags & IO_NORMAL) == 0)
7066                 return;
7067         BO_LOCK(&vp->v_bufobj);
7068         drain_output(vp);
7069         BO_UNLOCK(&vp->v_bufobj);
7070         /*
7071          * The vnode pager eliminates file pages we eliminate indirects
7072          * below.
7073          */
7074         vnode_pager_setsize(vp, length);
7075         /*
7076          * Calculate the end based on the last indirect we want to keep.  If
7077          * the block extends into indirects we can just use the negative of
7078          * its lbn.  Doubles and triples exist at lower numbers so we must
7079          * be careful not to remove those, if they exist.  double and triple
7080          * indirect lbns do not overlap with others so it is not important
7081          * to verify how many levels are required.
7082          */
7083         lbn = lblkno(fs, length);
7084         if (lbn >= UFS_NDADDR) {
7085                 /* Calculate the virtual lbn of the triple indirect. */
7086                 lbn = -lbn - (UFS_NIADDR - 1);
7087                 end = OFF_TO_IDX(lblktosize(fs, lbn));
7088         } else
7089                 end = extend;
7090         vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7091 }
7092
7093 /*
7094  * See if the buf bp is in the range eliminated by truncation.
7095  */
7096 static int
7097 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7098         struct buf *bp;
7099         int *blkoffp;
7100         ufs_lbn_t lastlbn;
7101         int lastoff;
7102         int flags;
7103 {
7104         ufs_lbn_t lbn;
7105
7106         *blkoffp = 0;
7107         /* Only match ext/normal blocks as appropriate. */
7108         if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7109             ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7110                 return (0);
7111         /* ALTDATA is always a full truncation. */
7112         if ((bp->b_xflags & BX_ALTDATA) != 0)
7113                 return (1);
7114         /* -1 is full truncation. */
7115         if (lastlbn == -1)
7116                 return (1);
7117         /*
7118          * If this is a partial truncate we only want those
7119          * blocks and indirect blocks that cover the range
7120          * we're after.
7121          */
7122         lbn = bp->b_lblkno;
7123         if (lbn < 0)
7124                 lbn = -(lbn + lbn_level(lbn));
7125         if (lbn < lastlbn)
7126                 return (0);
7127         /* Here we only truncate lblkno if it's partial. */
7128         if (lbn == lastlbn) {
7129                 if (lastoff == 0)
7130                         return (0);
7131                 *blkoffp = lastoff;
7132         }
7133         return (1);
7134 }
7135
7136 /*
7137  * Eliminate any dependencies that exist in memory beyond lblkno:off
7138  */
7139 static void
7140 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7141         struct inode *ip;
7142         struct freeblks *freeblks;
7143         ufs_lbn_t lastlbn;
7144         int lastoff;
7145         int flags;
7146 {
7147         struct bufobj *bo;
7148         struct vnode *vp;
7149         struct buf *bp;
7150         int blkoff;
7151
7152         /*
7153          * We must wait for any I/O in progress to finish so that
7154          * all potential buffers on the dirty list will be visible.
7155          * Once they are all there, walk the list and get rid of
7156          * any dependencies.
7157          */
7158         vp = ITOV(ip);
7159         bo = &vp->v_bufobj;
7160         BO_LOCK(bo);
7161         drain_output(vp);
7162         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7163                 bp->b_vflags &= ~BV_SCANNED;
7164 restart:
7165         TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7166                 if (bp->b_vflags & BV_SCANNED)
7167                         continue;
7168                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7169                         bp->b_vflags |= BV_SCANNED;
7170                         continue;
7171                 }
7172                 KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7173                 if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7174                         goto restart;
7175                 BO_UNLOCK(bo);
7176                 if (deallocate_dependencies(bp, freeblks, blkoff))
7177                         bqrelse(bp);
7178                 else
7179                         brelse(bp);
7180                 BO_LOCK(bo);
7181                 goto restart;
7182         }
7183         /*
7184          * Now do the work of vtruncbuf while also matching indirect blocks.
7185          */
7186         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7187                 bp->b_vflags &= ~BV_SCANNED;
7188 cleanrestart:
7189         TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7190                 if (bp->b_vflags & BV_SCANNED)
7191                         continue;
7192                 if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7193                         bp->b_vflags |= BV_SCANNED;
7194                         continue;
7195                 }
7196                 if (BUF_LOCK(bp,
7197                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7198                     BO_LOCKPTR(bo)) == ENOLCK) {
7199                         BO_LOCK(bo);
7200                         goto cleanrestart;
7201                 }
7202                 bp->b_vflags |= BV_SCANNED;
7203                 bremfree(bp);
7204                 if (blkoff != 0) {
7205                         allocbuf(bp, blkoff);
7206                         bqrelse(bp);
7207                 } else {
7208                         bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7209                         brelse(bp);
7210                 }
7211                 BO_LOCK(bo);
7212                 goto cleanrestart;
7213         }
7214         drain_output(vp);
7215         BO_UNLOCK(bo);
7216 }
7217
7218 static int
7219 cancel_pagedep(pagedep, freeblks, blkoff)
7220         struct pagedep *pagedep;
7221         struct freeblks *freeblks;
7222         int blkoff;
7223 {
7224         struct jremref *jremref;
7225         struct jmvref *jmvref;
7226         struct dirrem *dirrem, *tmp;
7227         int i;
7228
7229         /*
7230          * Copy any directory remove dependencies to the list
7231          * to be processed after the freeblks proceeds.  If
7232          * directory entry never made it to disk they
7233          * can be dumped directly onto the work list.
7234          */
7235         LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7236                 /* Skip this directory removal if it is intended to remain. */
7237                 if (dirrem->dm_offset < blkoff)
7238                         continue;
7239                 /*
7240                  * If there are any dirrems we wait for the journal write
7241                  * to complete and then restart the buf scan as the lock
7242                  * has been dropped.
7243                  */
7244                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7245                         jwait(&jremref->jr_list, MNT_WAIT);
7246                         return (ERESTART);
7247                 }
7248                 LIST_REMOVE(dirrem, dm_next);
7249                 dirrem->dm_dirinum = pagedep->pd_ino;
7250                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7251         }
7252         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7253                 jwait(&jmvref->jm_list, MNT_WAIT);
7254                 return (ERESTART);
7255         }
7256         /*
7257          * When we're partially truncating a pagedep we just want to flush
7258          * journal entries and return.  There can not be any adds in the
7259          * truncated portion of the directory and newblk must remain if
7260          * part of the block remains.
7261          */
7262         if (blkoff != 0) {
7263                 struct diradd *dap;
7264
7265                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7266                         if (dap->da_offset > blkoff)
7267                                 panic("cancel_pagedep: diradd %p off %d > %d",
7268                                     dap, dap->da_offset, blkoff);
7269                 for (i = 0; i < DAHASHSZ; i++)
7270                         LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7271                                 if (dap->da_offset > blkoff)
7272                                         panic("cancel_pagedep: diradd %p off %d > %d",
7273                                             dap, dap->da_offset, blkoff);
7274                 return (0);
7275         }
7276         /*
7277          * There should be no directory add dependencies present
7278          * as the directory could not be truncated until all
7279          * children were removed.
7280          */
7281         KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7282             ("deallocate_dependencies: pendinghd != NULL"));
7283         for (i = 0; i < DAHASHSZ; i++)
7284                 KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7285                     ("deallocate_dependencies: diraddhd != NULL"));
7286         if ((pagedep->pd_state & NEWBLOCK) != 0)
7287                 free_newdirblk(pagedep->pd_newdirblk);
7288         if (free_pagedep(pagedep) == 0)
7289                 panic("Failed to free pagedep %p", pagedep);
7290         return (0);
7291 }
7292
7293 /*
7294  * Reclaim any dependency structures from a buffer that is about to
7295  * be reallocated to a new vnode. The buffer must be locked, thus,
7296  * no I/O completion operations can occur while we are manipulating
7297  * its associated dependencies. The mutex is held so that other I/O's
7298  * associated with related dependencies do not occur.
7299  */
7300 static int
7301 deallocate_dependencies(bp, freeblks, off)
7302         struct buf *bp;
7303         struct freeblks *freeblks;
7304         int off;
7305 {
7306         struct indirdep *indirdep;
7307         struct pagedep *pagedep;
7308         struct worklist *wk, *wkn;
7309         struct ufsmount *ump;
7310
7311         ump = softdep_bp_to_mp(bp);
7312         if (ump == NULL)
7313                 goto done;
7314         ACQUIRE_LOCK(ump);
7315         LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7316                 switch (wk->wk_type) {
7317                 case D_INDIRDEP:
7318                         indirdep = WK_INDIRDEP(wk);
7319                         if (bp->b_lblkno >= 0 ||
7320                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7321                                 panic("deallocate_dependencies: not indir");
7322                         cancel_indirdep(indirdep, bp, freeblks);
7323                         continue;
7324
7325                 case D_PAGEDEP:
7326                         pagedep = WK_PAGEDEP(wk);
7327                         if (cancel_pagedep(pagedep, freeblks, off)) {
7328                                 FREE_LOCK(ump);
7329                                 return (ERESTART);
7330                         }
7331                         continue;
7332
7333                 case D_ALLOCINDIR:
7334                         /*
7335                          * Simply remove the allocindir, we'll find it via
7336                          * the indirdep where we can clear pointers if
7337                          * needed.
7338                          */
7339                         WORKLIST_REMOVE(wk);
7340                         continue;
7341
7342                 case D_FREEWORK:
7343                         /*
7344                          * A truncation is waiting for the zero'd pointers
7345                          * to be written.  It can be freed when the freeblks
7346                          * is journaled.
7347                          */
7348                         WORKLIST_REMOVE(wk);
7349                         wk->wk_state |= ONDEPLIST;
7350                         WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7351                         break;
7352
7353                 case D_ALLOCDIRECT:
7354                         if (off != 0)
7355                                 continue;
7356                         /* FALLTHROUGH */
7357                 default:
7358                         panic("deallocate_dependencies: Unexpected type %s",
7359                             TYPENAME(wk->wk_type));
7360                         /* NOTREACHED */
7361                 }
7362         }
7363         FREE_LOCK(ump);
7364 done:
7365         /*
7366          * Don't throw away this buf, we were partially truncating and
7367          * some deps may always remain.
7368          */
7369         if (off) {
7370                 allocbuf(bp, off);
7371                 bp->b_vflags |= BV_SCANNED;
7372                 return (EBUSY);
7373         }
7374         bp->b_flags |= B_INVAL | B_NOCACHE;
7375
7376         return (0);
7377 }
7378
7379 /*
7380  * An allocdirect is being canceled due to a truncate.  We must make sure
7381  * the journal entry is released in concert with the blkfree that releases
7382  * the storage.  Completed journal entries must not be released until the
7383  * space is no longer pointed to by the inode or in the bitmap.
7384  */
7385 static void
7386 cancel_allocdirect(adphead, adp, freeblks)
7387         struct allocdirectlst *adphead;
7388         struct allocdirect *adp;
7389         struct freeblks *freeblks;
7390 {
7391         struct freework *freework;
7392         struct newblk *newblk;
7393         struct worklist *wk;
7394
7395         TAILQ_REMOVE(adphead, adp, ad_next);
7396         newblk = (struct newblk *)adp;
7397         freework = NULL;
7398         /*
7399          * Find the correct freework structure.
7400          */
7401         LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7402                 if (wk->wk_type != D_FREEWORK)
7403                         continue;
7404                 freework = WK_FREEWORK(wk);
7405                 if (freework->fw_blkno == newblk->nb_newblkno)
7406                         break;
7407         }
7408         if (freework == NULL)
7409                 panic("cancel_allocdirect: Freework not found");
7410         /*
7411          * If a newblk exists at all we still have the journal entry that
7412          * initiated the allocation so we do not need to journal the free.
7413          */
7414         cancel_jfreeblk(freeblks, freework->fw_blkno);
7415         /*
7416          * If the journal hasn't been written the jnewblk must be passed
7417          * to the call to ffs_blkfree that reclaims the space.  We accomplish
7418          * this by linking the journal dependency into the freework to be
7419          * freed when freework_freeblock() is called.  If the journal has
7420          * been written we can simply reclaim the journal space when the
7421          * freeblks work is complete.
7422          */
7423         freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7424             &freeblks->fb_jwork);
7425         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7426 }
7427
7428
7429 /*
7430  * Cancel a new block allocation.  May be an indirect or direct block.  We
7431  * remove it from various lists and return any journal record that needs to
7432  * be resolved by the caller.
7433  *
7434  * A special consideration is made for indirects which were never pointed
7435  * at on disk and will never be found once this block is released.
7436  */
7437 static struct jnewblk *
7438 cancel_newblk(newblk, wk, wkhd)
7439         struct newblk *newblk;
7440         struct worklist *wk;
7441         struct workhead *wkhd;
7442 {
7443         struct jnewblk *jnewblk;
7444
7445         CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7446             
7447         newblk->nb_state |= GOINGAWAY;
7448         /*
7449          * Previously we traversed the completedhd on each indirdep
7450          * attached to this newblk to cancel them and gather journal
7451          * work.  Since we need only the oldest journal segment and
7452          * the lowest point on the tree will always have the oldest
7453          * journal segment we are free to release the segments
7454          * of any subordinates and may leave the indirdep list to
7455          * indirdep_complete() when this newblk is freed.
7456          */
7457         if (newblk->nb_state & ONDEPLIST) {
7458                 newblk->nb_state &= ~ONDEPLIST;
7459                 LIST_REMOVE(newblk, nb_deps);
7460         }
7461         if (newblk->nb_state & ONWORKLIST)
7462                 WORKLIST_REMOVE(&newblk->nb_list);
7463         /*
7464          * If the journal entry hasn't been written we save a pointer to
7465          * the dependency that frees it until it is written or the
7466          * superseding operation completes.
7467          */
7468         jnewblk = newblk->nb_jnewblk;
7469         if (jnewblk != NULL && wk != NULL) {
7470                 newblk->nb_jnewblk = NULL;
7471                 jnewblk->jn_dep = wk;
7472         }
7473         if (!LIST_EMPTY(&newblk->nb_jwork))
7474                 jwork_move(wkhd, &newblk->nb_jwork);
7475         /*
7476          * When truncating we must free the newdirblk early to remove
7477          * the pagedep from the hash before returning.
7478          */
7479         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7480                 free_newdirblk(WK_NEWDIRBLK(wk));
7481         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7482                 panic("cancel_newblk: extra newdirblk");
7483
7484         return (jnewblk);
7485 }
7486
7487 /*
7488  * Schedule the freefrag associated with a newblk to be released once
7489  * the pointers are written and the previous block is no longer needed.
7490  */
7491 static void
7492 newblk_freefrag(newblk)
7493         struct newblk *newblk;
7494 {
7495         struct freefrag *freefrag;
7496
7497         if (newblk->nb_freefrag == NULL)
7498                 return;
7499         freefrag = newblk->nb_freefrag;
7500         newblk->nb_freefrag = NULL;
7501         freefrag->ff_state |= COMPLETE;
7502         if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7503                 add_to_worklist(&freefrag->ff_list, 0);
7504 }
7505
7506 /*
7507  * Free a newblk. Generate a new freefrag work request if appropriate.
7508  * This must be called after the inode pointer and any direct block pointers
7509  * are valid or fully removed via truncate or frag extension.
7510  */
7511 static void
7512 free_newblk(newblk)
7513         struct newblk *newblk;
7514 {
7515         struct indirdep *indirdep;
7516         struct worklist *wk;
7517
7518         KASSERT(newblk->nb_jnewblk == NULL,
7519             ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7520         KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7521             ("free_newblk: unclaimed newblk"));
7522         LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7523         newblk_freefrag(newblk);
7524         if (newblk->nb_state & ONDEPLIST)
7525                 LIST_REMOVE(newblk, nb_deps);
7526         if (newblk->nb_state & ONWORKLIST)
7527                 WORKLIST_REMOVE(&newblk->nb_list);
7528         LIST_REMOVE(newblk, nb_hash);
7529         if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7530                 free_newdirblk(WK_NEWDIRBLK(wk));
7531         if (!LIST_EMPTY(&newblk->nb_newdirblk))
7532                 panic("free_newblk: extra newdirblk");
7533         while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7534                 indirdep_complete(indirdep);
7535         handle_jwork(&newblk->nb_jwork);
7536         WORKITEM_FREE(newblk, D_NEWBLK);
7537 }
7538
7539 /*
7540  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7541  */
7542 static void
7543 free_newdirblk(newdirblk)
7544         struct newdirblk *newdirblk;
7545 {
7546         struct pagedep *pagedep;
7547         struct diradd *dap;
7548         struct worklist *wk;
7549
7550         LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7551         WORKLIST_REMOVE(&newdirblk->db_list);
7552         /*
7553          * If the pagedep is still linked onto the directory buffer
7554          * dependency chain, then some of the entries on the
7555          * pd_pendinghd list may not be committed to disk yet. In
7556          * this case, we will simply clear the NEWBLOCK flag and
7557          * let the pd_pendinghd list be processed when the pagedep
7558          * is next written. If the pagedep is no longer on the buffer
7559          * dependency chain, then all the entries on the pd_pending
7560          * list are committed to disk and we can free them here.
7561          */
7562         pagedep = newdirblk->db_pagedep;
7563         pagedep->pd_state &= ~NEWBLOCK;
7564         if ((pagedep->pd_state & ONWORKLIST) == 0) {
7565                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7566                         free_diradd(dap, NULL);
7567                 /*
7568                  * If no dependencies remain, the pagedep will be freed.
7569                  */
7570                 free_pagedep(pagedep);
7571         }
7572         /* Should only ever be one item in the list. */
7573         while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7574                 WORKLIST_REMOVE(wk);
7575                 handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7576         }
7577         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7578 }
7579
7580 /*
7581  * Prepare an inode to be freed. The actual free operation is not
7582  * done until the zero'ed inode has been written to disk.
7583  */
7584 void
7585 softdep_freefile(pvp, ino, mode)
7586         struct vnode *pvp;
7587         ino_t ino;
7588         int mode;
7589 {
7590         struct inode *ip = VTOI(pvp);
7591         struct inodedep *inodedep;
7592         struct freefile *freefile;
7593         struct freeblks *freeblks;
7594         struct ufsmount *ump;
7595
7596         ump = ITOUMP(ip);
7597         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7598             ("softdep_freefile called on non-softdep filesystem"));
7599         /*
7600          * This sets up the inode de-allocation dependency.
7601          */
7602         freefile = malloc(sizeof(struct freefile),
7603                 M_FREEFILE, M_SOFTDEP_FLAGS);
7604         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7605         freefile->fx_mode = mode;
7606         freefile->fx_oldinum = ino;
7607         freefile->fx_devvp = ump->um_devvp;
7608         LIST_INIT(&freefile->fx_jwork);
7609         UFS_LOCK(ump);
7610         ump->um_fs->fs_pendinginodes += 1;
7611         UFS_UNLOCK(ump);
7612
7613         /*
7614          * If the inodedep does not exist, then the zero'ed inode has
7615          * been written to disk. If the allocated inode has never been
7616          * written to disk, then the on-disk inode is zero'ed. In either
7617          * case we can free the file immediately.  If the journal was
7618          * canceled before being written the inode will never make it to
7619          * disk and we must send the canceled journal entrys to
7620          * ffs_freefile() to be cleared in conjunction with the bitmap.
7621          * Any blocks waiting on the inode to write can be safely freed
7622          * here as it will never been written.
7623          */
7624         ACQUIRE_LOCK(ump);
7625         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7626         if (inodedep) {
7627                 /*
7628                  * Clear out freeblks that no longer need to reference
7629                  * this inode.
7630                  */
7631                 while ((freeblks =
7632                     TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7633                         TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7634                             fb_next);
7635                         freeblks->fb_state &= ~ONDEPLIST;
7636                 }
7637                 /*
7638                  * Remove this inode from the unlinked list.
7639                  */
7640                 if (inodedep->id_state & UNLINKED) {
7641                         /*
7642                          * Save the journal work to be freed with the bitmap
7643                          * before we clear UNLINKED.  Otherwise it can be lost
7644                          * if the inode block is written.
7645                          */
7646                         handle_bufwait(inodedep, &freefile->fx_jwork);
7647                         clear_unlinked_inodedep(inodedep);
7648                         /*
7649                          * Re-acquire inodedep as we've dropped the
7650                          * per-filesystem lock in clear_unlinked_inodedep().
7651                          */
7652                         inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7653                 }
7654         }
7655         if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7656                 FREE_LOCK(ump);
7657                 handle_workitem_freefile(freefile);
7658                 return;
7659         }
7660         if ((inodedep->id_state & DEPCOMPLETE) == 0)
7661                 inodedep->id_state |= GOINGAWAY;
7662         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7663         FREE_LOCK(ump);
7664         if (ip->i_number == ino)
7665                 UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
7666 }
7667
7668 /*
7669  * Check to see if an inode has never been written to disk. If
7670  * so free the inodedep and return success, otherwise return failure.
7671  *
7672  * If we still have a bitmap dependency, then the inode has never
7673  * been written to disk. Drop the dependency as it is no longer
7674  * necessary since the inode is being deallocated. We set the
7675  * ALLCOMPLETE flags since the bitmap now properly shows that the
7676  * inode is not allocated. Even if the inode is actively being
7677  * written, it has been rolled back to its zero'ed state, so we
7678  * are ensured that a zero inode is what is on the disk. For short
7679  * lived files, this change will usually result in removing all the
7680  * dependencies from the inode so that it can be freed immediately.
7681  */
7682 static int
7683 check_inode_unwritten(inodedep)
7684         struct inodedep *inodedep;
7685 {
7686
7687         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7688
7689         if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7690             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7691             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7692             !LIST_EMPTY(&inodedep->id_bufwait) ||
7693             !LIST_EMPTY(&inodedep->id_inowait) ||
7694             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7695             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7696             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7697             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7698             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7699             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7700             inodedep->id_mkdiradd != NULL || 
7701             inodedep->id_nlinkdelta != 0)
7702                 return (0);
7703         /*
7704          * Another process might be in initiate_write_inodeblock_ufs[12]
7705          * trying to allocate memory without holding "Softdep Lock".
7706          */
7707         if ((inodedep->id_state & IOSTARTED) != 0 &&
7708             inodedep->id_savedino1 == NULL)
7709                 return (0);
7710
7711         if (inodedep->id_state & ONDEPLIST)
7712                 LIST_REMOVE(inodedep, id_deps);
7713         inodedep->id_state &= ~ONDEPLIST;
7714         inodedep->id_state |= ALLCOMPLETE;
7715         inodedep->id_bmsafemap = NULL;
7716         if (inodedep->id_state & ONWORKLIST)
7717                 WORKLIST_REMOVE(&inodedep->id_list);
7718         if (inodedep->id_savedino1 != NULL) {
7719                 free(inodedep->id_savedino1, M_SAVEDINO);
7720                 inodedep->id_savedino1 = NULL;
7721         }
7722         if (free_inodedep(inodedep) == 0)
7723                 panic("check_inode_unwritten: busy inode");
7724         return (1);
7725 }
7726
7727 static int
7728 check_inodedep_free(inodedep)
7729         struct inodedep *inodedep;
7730 {
7731
7732         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7733         if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7734             !LIST_EMPTY(&inodedep->id_dirremhd) ||
7735             !LIST_EMPTY(&inodedep->id_pendinghd) ||
7736             !LIST_EMPTY(&inodedep->id_bufwait) ||
7737             !LIST_EMPTY(&inodedep->id_inowait) ||
7738             !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7739             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7740             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7741             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7742             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7743             !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7744             inodedep->id_mkdiradd != NULL ||
7745             inodedep->id_nlinkdelta != 0 ||
7746             inodedep->id_savedino1 != NULL)
7747                 return (0);
7748         return (1);
7749 }
7750
7751 /*
7752  * Try to free an inodedep structure. Return 1 if it could be freed.
7753  */
7754 static int
7755 free_inodedep(inodedep)
7756         struct inodedep *inodedep;
7757 {
7758
7759         LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7760         if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7761             !check_inodedep_free(inodedep))
7762                 return (0);
7763         if (inodedep->id_state & ONDEPLIST)
7764                 LIST_REMOVE(inodedep, id_deps);
7765         LIST_REMOVE(inodedep, id_hash);
7766         WORKITEM_FREE(inodedep, D_INODEDEP);
7767         return (1);
7768 }
7769
7770 /*
7771  * Free the block referenced by a freework structure.  The parent freeblks
7772  * structure is released and completed when the final cg bitmap reaches
7773  * the disk.  This routine may be freeing a jnewblk which never made it to
7774  * disk in which case we do not have to wait as the operation is undone
7775  * in memory immediately.
7776  */
7777 static void
7778 freework_freeblock(freework, key)
7779         struct freework *freework;
7780         u_long key;
7781 {
7782         struct freeblks *freeblks;
7783         struct jnewblk *jnewblk;
7784         struct ufsmount *ump;
7785         struct workhead wkhd;
7786         struct fs *fs;
7787         int bsize;
7788         int needj;
7789
7790         ump = VFSTOUFS(freework->fw_list.wk_mp);
7791         LOCK_OWNED(ump);
7792         /*
7793          * Handle partial truncate separately.
7794          */
7795         if (freework->fw_indir) {
7796                 complete_trunc_indir(freework);
7797                 return;
7798         }
7799         freeblks = freework->fw_freeblks;
7800         fs = ump->um_fs;
7801         needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7802         bsize = lfragtosize(fs, freework->fw_frags);
7803         LIST_INIT(&wkhd);
7804         /*
7805          * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7806          * on the indirblk hashtable and prevents premature freeing.
7807          */
7808         freework->fw_state |= DEPCOMPLETE;
7809         /*
7810          * SUJ needs to wait for the segment referencing freed indirect
7811          * blocks to expire so that we know the checker will not confuse
7812          * a re-allocated indirect block with its old contents.
7813          */
7814         if (needj && freework->fw_lbn <= -UFS_NDADDR)
7815                 indirblk_insert(freework);
7816         /*
7817          * If we are canceling an existing jnewblk pass it to the free
7818          * routine, otherwise pass the freeblk which will ultimately
7819          * release the freeblks.  If we're not journaling, we can just
7820          * free the freeblks immediately.
7821          */
7822         jnewblk = freework->fw_jnewblk;
7823         if (jnewblk != NULL) {
7824                 cancel_jnewblk(jnewblk, &wkhd);
7825                 needj = 0;
7826         } else if (needj) {
7827                 freework->fw_state |= DELAYEDFREE;
7828                 freeblks->fb_cgwait++;
7829                 WORKLIST_INSERT(&wkhd, &freework->fw_list);
7830         }
7831         FREE_LOCK(ump);
7832         freeblks_free(ump, freeblks, btodb(bsize));
7833         CTR4(KTR_SUJ,
7834             "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
7835             freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7836         ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7837             freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
7838         ACQUIRE_LOCK(ump);
7839         /*
7840          * The jnewblk will be discarded and the bits in the map never
7841          * made it to disk.  We can immediately free the freeblk.
7842          */
7843         if (needj == 0)
7844                 handle_written_freework(freework);
7845 }
7846
7847 /*
7848  * We enqueue freework items that need processing back on the freeblks and
7849  * add the freeblks to the worklist.  This makes it easier to find all work
7850  * required to flush a truncation in process_truncates().
7851  */
7852 static void
7853 freework_enqueue(freework)
7854         struct freework *freework;
7855 {
7856         struct freeblks *freeblks;
7857
7858         freeblks = freework->fw_freeblks;
7859         if ((freework->fw_state & INPROGRESS) == 0)
7860                 WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7861         if ((freeblks->fb_state &
7862             (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7863             LIST_EMPTY(&freeblks->fb_jblkdephd))
7864                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7865 }
7866
7867 /*
7868  * Start, continue, or finish the process of freeing an indirect block tree.
7869  * The free operation may be paused at any point with fw_off containing the
7870  * offset to restart from.  This enables us to implement some flow control
7871  * for large truncates which may fan out and generate a huge number of
7872  * dependencies.
7873  */
7874 static void
7875 handle_workitem_indirblk(freework)
7876         struct freework *freework;
7877 {
7878         struct freeblks *freeblks;
7879         struct ufsmount *ump;
7880         struct fs *fs;
7881
7882         freeblks = freework->fw_freeblks;
7883         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7884         fs = ump->um_fs;
7885         if (freework->fw_state & DEPCOMPLETE) {
7886                 handle_written_freework(freework);
7887                 return;
7888         }
7889         if (freework->fw_off == NINDIR(fs)) {
7890                 freework_freeblock(freework, SINGLETON_KEY);
7891                 return;
7892         }
7893         freework->fw_state |= INPROGRESS;
7894         FREE_LOCK(ump);
7895         indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7896             freework->fw_lbn);
7897         ACQUIRE_LOCK(ump);
7898 }
7899
7900 /*
7901  * Called when a freework structure attached to a cg buf is written.  The
7902  * ref on either the parent or the freeblks structure is released and
7903  * the freeblks is added back to the worklist if there is more work to do.
7904  */
7905 static void
7906 handle_written_freework(freework)
7907         struct freework *freework;
7908 {
7909         struct freeblks *freeblks;
7910         struct freework *parent;
7911
7912         freeblks = freework->fw_freeblks;
7913         parent = freework->fw_parent;
7914         if (freework->fw_state & DELAYEDFREE)
7915                 freeblks->fb_cgwait--;
7916         freework->fw_state |= COMPLETE;
7917         if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7918                 WORKITEM_FREE(freework, D_FREEWORK);
7919         if (parent) {
7920                 if (--parent->fw_ref == 0)
7921                         freework_enqueue(parent);
7922                 return;
7923         }
7924         if (--freeblks->fb_ref != 0)
7925                 return;
7926         if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7927             ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd)) 
7928                 add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7929 }
7930
7931 /*
7932  * This workitem routine performs the block de-allocation.
7933  * The workitem is added to the pending list after the updated
7934  * inode block has been written to disk.  As mentioned above,
7935  * checks regarding the number of blocks de-allocated (compared
7936  * to the number of blocks allocated for the file) are also
7937  * performed in this function.
7938  */
7939 static int
7940 handle_workitem_freeblocks(freeblks, flags)
7941         struct freeblks *freeblks;
7942         int flags;
7943 {
7944         struct freework *freework;
7945         struct newblk *newblk;
7946         struct allocindir *aip;
7947         struct ufsmount *ump;
7948         struct worklist *wk;
7949         u_long key;
7950
7951         KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7952             ("handle_workitem_freeblocks: Journal entries not written."));
7953         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7954         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
7955         ACQUIRE_LOCK(ump);
7956         while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7957                 WORKLIST_REMOVE(wk);
7958                 switch (wk->wk_type) {
7959                 case D_DIRREM:
7960                         wk->wk_state |= COMPLETE;
7961                         add_to_worklist(wk, 0);
7962                         continue;
7963
7964                 case D_ALLOCDIRECT:
7965                         free_newblk(WK_NEWBLK(wk));
7966                         continue;
7967
7968                 case D_ALLOCINDIR:
7969                         aip = WK_ALLOCINDIR(wk);
7970                         freework = NULL;
7971                         if (aip->ai_state & DELAYEDFREE) {
7972                                 FREE_LOCK(ump);
7973                                 freework = newfreework(ump, freeblks, NULL,
7974                                     aip->ai_lbn, aip->ai_newblkno,
7975                                     ump->um_fs->fs_frag, 0, 0);
7976                                 ACQUIRE_LOCK(ump);
7977                         }
7978                         newblk = WK_NEWBLK(wk);
7979                         if (newblk->nb_jnewblk) {
7980                                 freework->fw_jnewblk = newblk->nb_jnewblk;
7981                                 newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7982                                 newblk->nb_jnewblk = NULL;
7983                         }
7984                         free_newblk(newblk);
7985                         continue;
7986
7987                 case D_FREEWORK:
7988                         freework = WK_FREEWORK(wk);
7989                         if (freework->fw_lbn <= -UFS_NDADDR)
7990                                 handle_workitem_indirblk(freework);
7991                         else
7992                                 freework_freeblock(freework, key);
7993                         continue;
7994                 default:
7995                         panic("handle_workitem_freeblocks: Unknown type %s",
7996                             TYPENAME(wk->wk_type));
7997                 }
7998         }
7999         if (freeblks->fb_ref != 0) {
8000                 freeblks->fb_state &= ~INPROGRESS;
8001                 wake_worklist(&freeblks->fb_list);
8002                 freeblks = NULL;
8003         }
8004         FREE_LOCK(ump);
8005         ffs_blkrelease_finish(ump, key);
8006         if (freeblks)
8007                 return handle_complete_freeblocks(freeblks, flags);
8008         return (0);
8009 }
8010
8011 /*
8012  * Handle completion of block free via truncate.  This allows fs_pending
8013  * to track the actual free block count more closely than if we only updated
8014  * it at the end.  We must be careful to handle cases where the block count
8015  * on free was incorrect.
8016  */
8017 static void
8018 freeblks_free(ump, freeblks, blocks)
8019         struct ufsmount *ump;
8020         struct freeblks *freeblks;
8021         int blocks;
8022 {
8023         struct fs *fs;
8024         ufs2_daddr_t remain;
8025
8026         UFS_LOCK(ump);
8027         remain = -freeblks->fb_chkcnt;
8028         freeblks->fb_chkcnt += blocks;
8029         if (remain > 0) {
8030                 if (remain < blocks)
8031                         blocks = remain;
8032                 fs = ump->um_fs;
8033                 fs->fs_pendingblocks -= blocks;
8034         }
8035         UFS_UNLOCK(ump);
8036 }
8037
8038 /*
8039  * Once all of the freework workitems are complete we can retire the
8040  * freeblocks dependency and any journal work awaiting completion.  This
8041  * can not be called until all other dependencies are stable on disk.
8042  */
8043 static int
8044 handle_complete_freeblocks(freeblks, flags)
8045         struct freeblks *freeblks;
8046         int flags;
8047 {
8048         struct inodedep *inodedep;
8049         struct inode *ip;
8050         struct vnode *vp;
8051         struct fs *fs;
8052         struct ufsmount *ump;
8053         ufs2_daddr_t spare;
8054
8055         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8056         fs = ump->um_fs;
8057         flags = LK_EXCLUSIVE | flags;
8058         spare = freeblks->fb_chkcnt;
8059
8060         /*
8061          * If we did not release the expected number of blocks we may have
8062          * to adjust the inode block count here.  Only do so if it wasn't
8063          * a truncation to zero and the modrev still matches.
8064          */
8065         if (spare && freeblks->fb_len != 0) {
8066                 if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8067                     flags, &vp, FFSV_FORCEINSMQ) != 0)
8068                         return (EBUSY);
8069                 ip = VTOI(vp);
8070                 if (ip->i_mode == 0) {
8071                         vgone(vp);
8072                 } else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8073                         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8074                         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8075                         /*
8076                          * We must wait so this happens before the
8077                          * journal is reclaimed.
8078                          */
8079                         ffs_update(vp, 1);
8080                 }
8081                 vput(vp);
8082         }
8083         if (spare < 0) {
8084                 UFS_LOCK(ump);
8085                 fs->fs_pendingblocks += spare;
8086                 UFS_UNLOCK(ump);
8087         }
8088 #ifdef QUOTA
8089         /* Handle spare. */
8090         if (spare)
8091                 quotaadj(freeblks->fb_quota, ump, -spare);
8092         quotarele(freeblks->fb_quota);
8093 #endif
8094         ACQUIRE_LOCK(ump);
8095         if (freeblks->fb_state & ONDEPLIST) {
8096                 inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8097                     0, &inodedep);
8098                 TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8099                 freeblks->fb_state &= ~ONDEPLIST;
8100                 if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8101                         free_inodedep(inodedep);
8102         }
8103         /*
8104          * All of the freeblock deps must be complete prior to this call
8105          * so it's now safe to complete earlier outstanding journal entries.
8106          */
8107         handle_jwork(&freeblks->fb_jwork);
8108         WORKITEM_FREE(freeblks, D_FREEBLKS);
8109         FREE_LOCK(ump);
8110         return (0);
8111 }
8112
8113 /*
8114  * Release blocks associated with the freeblks and stored in the indirect
8115  * block dbn. If level is greater than SINGLE, the block is an indirect block
8116  * and recursive calls to indirtrunc must be used to cleanse other indirect
8117  * blocks.
8118  *
8119  * This handles partial and complete truncation of blocks.  Partial is noted
8120  * with goingaway == 0.  In this case the freework is completed after the
8121  * zero'd indirects are written to disk.  For full truncation the freework
8122  * is completed after the block is freed.
8123  */
8124 static void
8125 indir_trunc(freework, dbn, lbn)
8126         struct freework *freework;
8127         ufs2_daddr_t dbn;
8128         ufs_lbn_t lbn;
8129 {
8130         struct freework *nfreework;
8131         struct workhead wkhd;
8132         struct freeblks *freeblks;
8133         struct buf *bp;
8134         struct fs *fs;
8135         struct indirdep *indirdep;
8136         struct mount *mp;
8137         struct ufsmount *ump;
8138         ufs1_daddr_t *bap1;
8139         ufs2_daddr_t nb, nnb, *bap2;
8140         ufs_lbn_t lbnadd, nlbn;
8141         u_long key;
8142         int nblocks, ufs1fmt, freedblocks;
8143         int goingaway, freedeps, needj, level, cnt, i;
8144
8145         freeblks = freework->fw_freeblks;
8146         mp = freeblks->fb_list.wk_mp;
8147         ump = VFSTOUFS(mp);
8148         fs = ump->um_fs;
8149         /*
8150          * Get buffer of block pointers to be freed.  There are three cases:
8151          * 
8152          * 1) Partial truncate caches the indirdep pointer in the freework
8153          *    which provides us a back copy to the save bp which holds the
8154          *    pointers we want to clear.  When this completes the zero
8155          *    pointers are written to the real copy.
8156          * 2) The indirect is being completely truncated, cancel_indirdep()
8157          *    eliminated the real copy and placed the indirdep on the saved
8158          *    copy.  The indirdep and buf are discarded when this completes.
8159          * 3) The indirect was not in memory, we read a copy off of the disk
8160          *    using the devvp and drop and invalidate the buffer when we're
8161          *    done.
8162          */
8163         goingaway = 1;
8164         indirdep = NULL;
8165         if (freework->fw_indir != NULL) {
8166                 goingaway = 0;
8167                 indirdep = freework->fw_indir;
8168                 bp = indirdep->ir_savebp;
8169                 if (bp == NULL || bp->b_blkno != dbn)
8170                         panic("indir_trunc: Bad saved buf %p blkno %jd",
8171                             bp, (intmax_t)dbn);
8172         } else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8173                 /*
8174                  * The lock prevents the buf dep list from changing and
8175                  * indirects on devvp should only ever have one dependency.
8176                  */
8177                 indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8178                 if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8179                         panic("indir_trunc: Bad indirdep %p from buf %p",
8180                             indirdep, bp);
8181         } else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8182             NOCRED, &bp) != 0) {
8183                 brelse(bp);
8184                 return;
8185         }
8186         ACQUIRE_LOCK(ump);
8187         /* Protects against a race with complete_trunc_indir(). */
8188         freework->fw_state &= ~INPROGRESS;
8189         /*
8190          * If we have an indirdep we need to enforce the truncation order
8191          * and discard it when it is complete.
8192          */
8193         if (indirdep) {
8194                 if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8195                     !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8196                         /*
8197                          * Add the complete truncate to the list on the
8198                          * indirdep to enforce in-order processing.
8199                          */
8200                         if (freework->fw_indir == NULL)
8201                                 TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8202                                     freework, fw_next);
8203                         FREE_LOCK(ump);
8204                         return;
8205                 }
8206                 /*
8207                  * If we're goingaway, free the indirdep.  Otherwise it will
8208                  * linger until the write completes.
8209                  */
8210                 if (goingaway)
8211                         free_indirdep(indirdep);
8212         }
8213         FREE_LOCK(ump);
8214         /* Initialize pointers depending on block size. */
8215         if (ump->um_fstype == UFS1) {
8216                 bap1 = (ufs1_daddr_t *)bp->b_data;
8217                 nb = bap1[freework->fw_off];
8218                 ufs1fmt = 1;
8219                 bap2 = NULL;
8220         } else {
8221                 bap2 = (ufs2_daddr_t *)bp->b_data;
8222                 nb = bap2[freework->fw_off];
8223                 ufs1fmt = 0;
8224                 bap1 = NULL;
8225         }
8226         level = lbn_level(lbn);
8227         needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8228         lbnadd = lbn_offset(fs, level);
8229         nblocks = btodb(fs->fs_bsize);
8230         nfreework = freework;
8231         freedeps = 0;
8232         cnt = 0;
8233         /*
8234          * Reclaim blocks.  Traverses into nested indirect levels and
8235          * arranges for the current level to be freed when subordinates
8236          * are free when journaling.
8237          */
8238         key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8239         for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8240                 if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8241                     fs->fs_bsize) != 0)
8242                         nb = 0;
8243                 if (i != NINDIR(fs) - 1) {
8244                         if (ufs1fmt)
8245                                 nnb = bap1[i+1];
8246                         else
8247                                 nnb = bap2[i+1];
8248                 } else
8249                         nnb = 0;
8250                 if (nb == 0)
8251                         continue;
8252                 cnt++;
8253                 if (level != 0) {
8254                         nlbn = (lbn + 1) - (i * lbnadd);
8255                         if (needj != 0) {
8256                                 nfreework = newfreework(ump, freeblks, freework,
8257                                     nlbn, nb, fs->fs_frag, 0, 0);
8258                                 freedeps++;
8259                         }
8260                         indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8261                 } else {
8262                         struct freedep *freedep;
8263
8264                         /*
8265                          * Attempt to aggregate freedep dependencies for
8266                          * all blocks being released to the same CG.
8267                          */
8268                         LIST_INIT(&wkhd);
8269                         if (needj != 0 &&
8270                             (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8271                                 freedep = newfreedep(freework);
8272                                 WORKLIST_INSERT_UNLOCKED(&wkhd,
8273                                     &freedep->fd_list);
8274                                 freedeps++;
8275                         }
8276                         CTR3(KTR_SUJ,
8277                             "indir_trunc: ino %jd blkno %jd size %d",
8278                             freeblks->fb_inum, nb, fs->fs_bsize);
8279                         ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8280                             fs->fs_bsize, freeblks->fb_inum,
8281                             freeblks->fb_vtype, &wkhd, key);
8282                 }
8283         }
8284         ffs_blkrelease_finish(ump, key);
8285         if (goingaway) {
8286                 bp->b_flags |= B_INVAL | B_NOCACHE;
8287                 brelse(bp);
8288         }
8289         freedblocks = 0;
8290         if (level == 0)
8291                 freedblocks = (nblocks * cnt);
8292         if (needj == 0)
8293                 freedblocks += nblocks;
8294         freeblks_free(ump, freeblks, freedblocks);
8295         /*
8296          * If we are journaling set up the ref counts and offset so this
8297          * indirect can be completed when its children are free.
8298          */
8299         if (needj) {
8300                 ACQUIRE_LOCK(ump);
8301                 freework->fw_off = i;
8302                 freework->fw_ref += freedeps;
8303                 freework->fw_ref -= NINDIR(fs) + 1;
8304                 if (level == 0)
8305                         freeblks->fb_cgwait += freedeps;
8306                 if (freework->fw_ref == 0)
8307                         freework_freeblock(freework, SINGLETON_KEY);
8308                 FREE_LOCK(ump);
8309                 return;
8310         }
8311         /*
8312          * If we're not journaling we can free the indirect now.
8313          */
8314         dbn = dbtofsb(fs, dbn);
8315         CTR3(KTR_SUJ,
8316             "indir_trunc 2: ino %jd blkno %jd size %d",
8317             freeblks->fb_inum, dbn, fs->fs_bsize);
8318         ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8319             freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8320         /* Non SUJ softdep does single-threaded truncations. */
8321         if (freework->fw_blkno == dbn) {
8322                 freework->fw_state |= ALLCOMPLETE;
8323                 ACQUIRE_LOCK(ump);
8324                 handle_written_freework(freework);
8325                 FREE_LOCK(ump);
8326         }
8327         return;
8328 }
8329
8330 /*
8331  * Cancel an allocindir when it is removed via truncation.  When bp is not
8332  * NULL the indirect never appeared on disk and is scheduled to be freed
8333  * independently of the indir so we can more easily track journal work.
8334  */
8335 static void
8336 cancel_allocindir(aip, bp, freeblks, trunc)
8337         struct allocindir *aip;
8338         struct buf *bp;
8339         struct freeblks *freeblks;
8340         int trunc;
8341 {
8342         struct indirdep *indirdep;
8343         struct freefrag *freefrag;
8344         struct newblk *newblk;
8345
8346         newblk = (struct newblk *)aip;
8347         LIST_REMOVE(aip, ai_next);
8348         /*
8349          * We must eliminate the pointer in bp if it must be freed on its
8350          * own due to partial truncate or pending journal work.
8351          */
8352         if (bp && (trunc || newblk->nb_jnewblk)) {
8353                 /*
8354                  * Clear the pointer and mark the aip to be freed
8355                  * directly if it never existed on disk.
8356                  */
8357                 aip->ai_state |= DELAYEDFREE;
8358                 indirdep = aip->ai_indirdep;
8359                 if (indirdep->ir_state & UFS1FMT)
8360                         ((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8361                 else
8362                         ((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8363         }
8364         /*
8365          * When truncating the previous pointer will be freed via
8366          * savedbp.  Eliminate the freefrag which would dup free.
8367          */
8368         if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8369                 newblk->nb_freefrag = NULL;
8370                 if (freefrag->ff_jdep)
8371                         cancel_jfreefrag(
8372                             WK_JFREEFRAG(freefrag->ff_jdep));
8373                 jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8374                 WORKITEM_FREE(freefrag, D_FREEFRAG);
8375         }
8376         /*
8377          * If the journal hasn't been written the jnewblk must be passed
8378          * to the call to ffs_blkfree that reclaims the space.  We accomplish
8379          * this by leaving the journal dependency on the newblk to be freed
8380          * when a freework is created in handle_workitem_freeblocks().
8381          */
8382         cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8383         WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8384 }
8385
8386 /*
8387  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8388  * in to a newdirblk so any subsequent additions are tracked properly.  The
8389  * caller is responsible for adding the mkdir1 dependency to the journal
8390  * and updating id_mkdiradd.  This function returns with the per-filesystem
8391  * lock held.
8392  */
8393 static struct mkdir *
8394 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8395         struct diradd *dap;
8396         ino_t newinum;
8397         ino_t dinum;
8398         struct buf *newdirbp;
8399         struct mkdir **mkdirp;
8400 {
8401         struct newblk *newblk;
8402         struct pagedep *pagedep;
8403         struct inodedep *inodedep;
8404         struct newdirblk *newdirblk;
8405         struct mkdir *mkdir1, *mkdir2;
8406         struct worklist *wk;
8407         struct jaddref *jaddref;
8408         struct ufsmount *ump;
8409         struct mount *mp;
8410
8411         mp = dap->da_list.wk_mp;
8412         ump = VFSTOUFS(mp);
8413         newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8414             M_SOFTDEP_FLAGS);
8415         workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8416         LIST_INIT(&newdirblk->db_mkdir);
8417         mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8418         workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8419         mkdir1->md_state = ATTACHED | MKDIR_BODY;
8420         mkdir1->md_diradd = dap;
8421         mkdir1->md_jaddref = NULL;
8422         mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8423         workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8424         mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8425         mkdir2->md_diradd = dap;
8426         mkdir2->md_jaddref = NULL;
8427         if (MOUNTEDSUJ(mp) == 0) {
8428                 mkdir1->md_state |= DEPCOMPLETE;
8429                 mkdir2->md_state |= DEPCOMPLETE;
8430         }
8431         /*
8432          * Dependency on "." and ".." being written to disk.
8433          */
8434         mkdir1->md_buf = newdirbp;
8435         ACQUIRE_LOCK(VFSTOUFS(mp));
8436         LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8437         /*
8438          * We must link the pagedep, allocdirect, and newdirblk for
8439          * the initial file page so the pointer to the new directory
8440          * is not written until the directory contents are live and
8441          * any subsequent additions are not marked live until the
8442          * block is reachable via the inode.
8443          */
8444         if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8445                 panic("setup_newdir: lost pagedep");
8446         LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8447                 if (wk->wk_type == D_ALLOCDIRECT)
8448                         break;
8449         if (wk == NULL)
8450                 panic("setup_newdir: lost allocdirect");
8451         if (pagedep->pd_state & NEWBLOCK)
8452                 panic("setup_newdir: NEWBLOCK already set");
8453         newblk = WK_NEWBLK(wk);
8454         pagedep->pd_state |= NEWBLOCK;
8455         pagedep->pd_newdirblk = newdirblk;
8456         newdirblk->db_pagedep = pagedep;
8457         WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8458         WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8459         /*
8460          * Look up the inodedep for the parent directory so that we
8461          * can link mkdir2 into the pending dotdot jaddref or
8462          * the inode write if there is none.  If the inode is
8463          * ALLCOMPLETE and no jaddref is present all dependencies have
8464          * been satisfied and mkdir2 can be freed.
8465          */
8466         inodedep_lookup(mp, dinum, 0, &inodedep);
8467         if (MOUNTEDSUJ(mp)) {
8468                 if (inodedep == NULL)
8469                         panic("setup_newdir: Lost parent.");
8470                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8471                     inoreflst);
8472                 KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8473                     (jaddref->ja_state & MKDIR_PARENT),
8474                     ("setup_newdir: bad dotdot jaddref %p", jaddref));
8475                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8476                 mkdir2->md_jaddref = jaddref;
8477                 jaddref->ja_mkdir = mkdir2;
8478         } else if (inodedep == NULL ||
8479             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8480                 dap->da_state &= ~MKDIR_PARENT;
8481                 WORKITEM_FREE(mkdir2, D_MKDIR);
8482                 mkdir2 = NULL;
8483         } else {
8484                 LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8485                 WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8486         }
8487         *mkdirp = mkdir2;
8488
8489         return (mkdir1);
8490 }
8491
8492 /*
8493  * Directory entry addition dependencies.
8494  * 
8495  * When adding a new directory entry, the inode (with its incremented link
8496  * count) must be written to disk before the directory entry's pointer to it.
8497  * Also, if the inode is newly allocated, the corresponding freemap must be
8498  * updated (on disk) before the directory entry's pointer. These requirements
8499  * are met via undo/redo on the directory entry's pointer, which consists
8500  * simply of the inode number.
8501  * 
8502  * As directory entries are added and deleted, the free space within a
8503  * directory block can become fragmented.  The ufs filesystem will compact
8504  * a fragmented directory block to make space for a new entry. When this
8505  * occurs, the offsets of previously added entries change. Any "diradd"
8506  * dependency structures corresponding to these entries must be updated with
8507  * the new offsets.
8508  */
8509
8510 /*
8511  * This routine is called after the in-memory inode's link
8512  * count has been incremented, but before the directory entry's
8513  * pointer to the inode has been set.
8514  */
8515 int
8516 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8517         struct buf *bp;         /* buffer containing directory block */
8518         struct inode *dp;       /* inode for directory */
8519         off_t diroffset;        /* offset of new entry in directory */
8520         ino_t newinum;          /* inode referenced by new directory entry */
8521         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
8522         int isnewblk;           /* entry is in a newly allocated block */
8523 {
8524         int offset;             /* offset of new entry within directory block */
8525         ufs_lbn_t lbn;          /* block in directory containing new entry */
8526         struct fs *fs;
8527         struct diradd *dap;
8528         struct newblk *newblk;
8529         struct pagedep *pagedep;
8530         struct inodedep *inodedep;
8531         struct newdirblk *newdirblk;
8532         struct mkdir *mkdir1, *mkdir2;
8533         struct jaddref *jaddref;
8534         struct ufsmount *ump;
8535         struct mount *mp;
8536         int isindir;
8537
8538         mp = ITOVFS(dp);
8539         ump = VFSTOUFS(mp);
8540         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8541             ("softdep_setup_directory_add called on non-softdep filesystem"));
8542         /*
8543          * Whiteouts have no dependencies.
8544          */
8545         if (newinum == UFS_WINO) {
8546                 if (newdirbp != NULL)
8547                         bdwrite(newdirbp);
8548                 return (0);
8549         }
8550         jaddref = NULL;
8551         mkdir1 = mkdir2 = NULL;
8552         fs = ump->um_fs;
8553         lbn = lblkno(fs, diroffset);
8554         offset = blkoff(fs, diroffset);
8555         dap = malloc(sizeof(struct diradd), M_DIRADD,
8556                 M_SOFTDEP_FLAGS|M_ZERO);
8557         workitem_alloc(&dap->da_list, D_DIRADD, mp);
8558         dap->da_offset = offset;
8559         dap->da_newinum = newinum;
8560         dap->da_state = ATTACHED;
8561         LIST_INIT(&dap->da_jwork);
8562         isindir = bp->b_lblkno >= UFS_NDADDR;
8563         newdirblk = NULL;
8564         if (isnewblk &&
8565             (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8566                 newdirblk = malloc(sizeof(struct newdirblk),
8567                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8568                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8569                 LIST_INIT(&newdirblk->db_mkdir);
8570         }
8571         /*
8572          * If we're creating a new directory setup the dependencies and set
8573          * the dap state to wait for them.  Otherwise it's COMPLETE and
8574          * we can move on.
8575          */
8576         if (newdirbp == NULL) {
8577                 dap->da_state |= DEPCOMPLETE;
8578                 ACQUIRE_LOCK(ump);
8579         } else {
8580                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8581                 mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8582                     &mkdir2);
8583         }
8584         /*
8585          * Link into parent directory pagedep to await its being written.
8586          */
8587         pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8588 #ifdef INVARIANTS
8589         if (diradd_lookup(pagedep, offset) != NULL)
8590                 panic("softdep_setup_directory_add: %p already at off %d\n",
8591                     diradd_lookup(pagedep, offset), offset);
8592 #endif
8593         dap->da_pagedep = pagedep;
8594         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8595             da_pdlist);
8596         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8597         /*
8598          * If we're journaling, link the diradd into the jaddref so it
8599          * may be completed after the journal entry is written.  Otherwise,
8600          * link the diradd into its inodedep.  If the inode is not yet
8601          * written place it on the bufwait list, otherwise do the post-inode
8602          * write processing to put it on the id_pendinghd list.
8603          */
8604         if (MOUNTEDSUJ(mp)) {
8605                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8606                     inoreflst);
8607                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8608                     ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8609                 jaddref->ja_diroff = diroffset;
8610                 jaddref->ja_diradd = dap;
8611                 add_to_journal(&jaddref->ja_list);
8612         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8613                 diradd_inode_written(dap, inodedep);
8614         else
8615                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8616         /*
8617          * Add the journal entries for . and .. links now that the primary
8618          * link is written.
8619          */
8620         if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8621                 jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8622                     inoreflst, if_deps);
8623                 KASSERT(jaddref != NULL &&
8624                     jaddref->ja_ino == jaddref->ja_parent &&
8625                     (jaddref->ja_state & MKDIR_BODY),
8626                     ("softdep_setup_directory_add: bad dot jaddref %p",
8627                     jaddref));
8628                 mkdir1->md_jaddref = jaddref;
8629                 jaddref->ja_mkdir = mkdir1;
8630                 /*
8631                  * It is important that the dotdot journal entry
8632                  * is added prior to the dot entry since dot writes
8633                  * both the dot and dotdot links.  These both must
8634                  * be added after the primary link for the journal
8635                  * to remain consistent.
8636                  */
8637                 add_to_journal(&mkdir2->md_jaddref->ja_list);
8638                 add_to_journal(&jaddref->ja_list);
8639         }
8640         /*
8641          * If we are adding a new directory remember this diradd so that if
8642          * we rename it we can keep the dot and dotdot dependencies.  If
8643          * we are adding a new name for an inode that has a mkdiradd we
8644          * must be in rename and we have to move the dot and dotdot
8645          * dependencies to this new name.  The old name is being orphaned
8646          * soon.
8647          */
8648         if (mkdir1 != NULL) {
8649                 if (inodedep->id_mkdiradd != NULL)
8650                         panic("softdep_setup_directory_add: Existing mkdir");
8651                 inodedep->id_mkdiradd = dap;
8652         } else if (inodedep->id_mkdiradd)
8653                 merge_diradd(inodedep, dap);
8654         if (newdirblk != NULL) {
8655                 /*
8656                  * There is nothing to do if we are already tracking
8657                  * this block.
8658                  */
8659                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
8660                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8661                         FREE_LOCK(ump);
8662                         return (0);
8663                 }
8664                 if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8665                     == 0)
8666                         panic("softdep_setup_directory_add: lost entry");
8667                 WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8668                 pagedep->pd_state |= NEWBLOCK;
8669                 pagedep->pd_newdirblk = newdirblk;
8670                 newdirblk->db_pagedep = pagedep;
8671                 FREE_LOCK(ump);
8672                 /*
8673                  * If we extended into an indirect signal direnter to sync.
8674                  */
8675                 if (isindir)
8676                         return (1);
8677                 return (0);
8678         }
8679         FREE_LOCK(ump);
8680         return (0);
8681 }
8682
8683 /*
8684  * This procedure is called to change the offset of a directory
8685  * entry when compacting a directory block which must be owned
8686  * exclusively by the caller. Note that the actual entry movement
8687  * must be done in this procedure to ensure that no I/O completions
8688  * occur while the move is in progress.
8689  */
8690 void 
8691 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8692         struct buf *bp;         /* Buffer holding directory block. */
8693         struct inode *dp;       /* inode for directory */
8694         caddr_t base;           /* address of dp->i_offset */
8695         caddr_t oldloc;         /* address of old directory location */
8696         caddr_t newloc;         /* address of new directory location */
8697         int entrysize;          /* size of directory entry */
8698 {
8699         int offset, oldoffset, newoffset;
8700         struct pagedep *pagedep;
8701         struct jmvref *jmvref;
8702         struct diradd *dap;
8703         struct direct *de;
8704         struct mount *mp;
8705         struct ufsmount *ump;
8706         ufs_lbn_t lbn;
8707         int flags;
8708
8709         mp = ITOVFS(dp);
8710         ump = VFSTOUFS(mp);
8711         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8712             ("softdep_change_directoryentry_offset called on "
8713              "non-softdep filesystem"));
8714         de = (struct direct *)oldloc;
8715         jmvref = NULL;
8716         flags = 0;
8717         /*
8718          * Moves are always journaled as it would be too complex to
8719          * determine if any affected adds or removes are present in the
8720          * journal.
8721          */
8722         if (MOUNTEDSUJ(mp)) {
8723                 flags = DEPALLOC;
8724                 jmvref = newjmvref(dp, de->d_ino,
8725                     dp->i_offset + (oldloc - base),
8726                     dp->i_offset + (newloc - base));
8727         }
8728         lbn = lblkno(ump->um_fs, dp->i_offset);
8729         offset = blkoff(ump->um_fs, dp->i_offset);
8730         oldoffset = offset + (oldloc - base);
8731         newoffset = offset + (newloc - base);
8732         ACQUIRE_LOCK(ump);
8733         if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8734                 goto done;
8735         dap = diradd_lookup(pagedep, oldoffset);
8736         if (dap) {
8737                 dap->da_offset = newoffset;
8738                 newoffset = DIRADDHASH(newoffset);
8739                 oldoffset = DIRADDHASH(oldoffset);
8740                 if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8741                     newoffset != oldoffset) {
8742                         LIST_REMOVE(dap, da_pdlist);
8743                         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8744                             dap, da_pdlist);
8745                 }
8746         }
8747 done:
8748         if (jmvref) {
8749                 jmvref->jm_pagedep = pagedep;
8750                 LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8751                 add_to_journal(&jmvref->jm_list);
8752         }
8753         bcopy(oldloc, newloc, entrysize);
8754         FREE_LOCK(ump);
8755 }
8756
8757 /*
8758  * Move the mkdir dependencies and journal work from one diradd to another
8759  * when renaming a directory.  The new name must depend on the mkdir deps
8760  * completing as the old name did.  Directories can only have one valid link
8761  * at a time so one must be canonical.
8762  */
8763 static void
8764 merge_diradd(inodedep, newdap)
8765         struct inodedep *inodedep;
8766         struct diradd *newdap;
8767 {
8768         struct diradd *olddap;
8769         struct mkdir *mkdir, *nextmd;
8770         struct ufsmount *ump;
8771         short state;
8772
8773         olddap = inodedep->id_mkdiradd;
8774         inodedep->id_mkdiradd = newdap;
8775         if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8776                 newdap->da_state &= ~DEPCOMPLETE;
8777                 ump = VFSTOUFS(inodedep->id_list.wk_mp);
8778                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8779                      mkdir = nextmd) {
8780                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8781                         if (mkdir->md_diradd != olddap)
8782                                 continue;
8783                         mkdir->md_diradd = newdap;
8784                         state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8785                         newdap->da_state |= state;
8786                         olddap->da_state &= ~state;
8787                         if ((olddap->da_state &
8788                             (MKDIR_PARENT | MKDIR_BODY)) == 0)
8789                                 break;
8790                 }
8791                 if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8792                         panic("merge_diradd: unfound ref");
8793         }
8794         /*
8795          * Any mkdir related journal items are not safe to be freed until
8796          * the new name is stable.
8797          */
8798         jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8799         olddap->da_state |= DEPCOMPLETE;
8800         complete_diradd(olddap);
8801 }
8802
8803 /*
8804  * Move the diradd to the pending list when all diradd dependencies are
8805  * complete.
8806  */
8807 static void
8808 complete_diradd(dap)
8809         struct diradd *dap;
8810 {
8811         struct pagedep *pagedep;
8812
8813         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8814                 if (dap->da_state & DIRCHG)
8815                         pagedep = dap->da_previous->dm_pagedep;
8816                 else
8817                         pagedep = dap->da_pagedep;
8818                 LIST_REMOVE(dap, da_pdlist);
8819                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8820         }
8821 }
8822
8823 /*
8824  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8825  * add entries and conditonally journal the remove.
8826  */
8827 static void
8828 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8829         struct diradd *dap;
8830         struct dirrem *dirrem;
8831         struct jremref *jremref;
8832         struct jremref *dotremref;
8833         struct jremref *dotdotremref;
8834 {
8835         struct inodedep *inodedep;
8836         struct jaddref *jaddref;
8837         struct inoref *inoref;
8838         struct ufsmount *ump;
8839         struct mkdir *mkdir;
8840
8841         /*
8842          * If no remove references were allocated we're on a non-journaled
8843          * filesystem and can skip the cancel step.
8844          */
8845         if (jremref == NULL) {
8846                 free_diradd(dap, NULL);
8847                 return;
8848         }
8849         /*
8850          * Cancel the primary name an free it if it does not require
8851          * journaling.
8852          */
8853         if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8854             0, &inodedep) != 0) {
8855                 /* Abort the addref that reference this diradd.  */
8856                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8857                         if (inoref->if_list.wk_type != D_JADDREF)
8858                                 continue;
8859                         jaddref = (struct jaddref *)inoref;
8860                         if (jaddref->ja_diradd != dap)
8861                                 continue;
8862                         if (cancel_jaddref(jaddref, inodedep,
8863                             &dirrem->dm_jwork) == 0) {
8864                                 free_jremref(jremref);
8865                                 jremref = NULL;
8866                         }
8867                         break;
8868                 }
8869         }
8870         /*
8871          * Cancel subordinate names and free them if they do not require
8872          * journaling.
8873          */
8874         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8875                 ump = VFSTOUFS(dap->da_list.wk_mp);
8876                 LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8877                         if (mkdir->md_diradd != dap)
8878                                 continue;
8879                         if ((jaddref = mkdir->md_jaddref) == NULL)
8880                                 continue;
8881                         mkdir->md_jaddref = NULL;
8882                         if (mkdir->md_state & MKDIR_PARENT) {
8883                                 if (cancel_jaddref(jaddref, NULL,
8884                                     &dirrem->dm_jwork) == 0) {
8885                                         free_jremref(dotdotremref);
8886                                         dotdotremref = NULL;
8887                                 }
8888                         } else {
8889                                 if (cancel_jaddref(jaddref, inodedep,
8890                                     &dirrem->dm_jwork) == 0) {
8891                                         free_jremref(dotremref);
8892                                         dotremref = NULL;
8893                                 }
8894                         }
8895                 }
8896         }
8897
8898         if (jremref)
8899                 journal_jremref(dirrem, jremref, inodedep);
8900         if (dotremref)
8901                 journal_jremref(dirrem, dotremref, inodedep);
8902         if (dotdotremref)
8903                 journal_jremref(dirrem, dotdotremref, NULL);
8904         jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8905         free_diradd(dap, &dirrem->dm_jwork);
8906 }
8907
8908 /*
8909  * Free a diradd dependency structure.
8910  */
8911 static void
8912 free_diradd(dap, wkhd)
8913         struct diradd *dap;
8914         struct workhead *wkhd;
8915 {
8916         struct dirrem *dirrem;
8917         struct pagedep *pagedep;
8918         struct inodedep *inodedep;
8919         struct mkdir *mkdir, *nextmd;
8920         struct ufsmount *ump;
8921
8922         ump = VFSTOUFS(dap->da_list.wk_mp);
8923         LOCK_OWNED(ump);
8924         LIST_REMOVE(dap, da_pdlist);
8925         if (dap->da_state & ONWORKLIST)
8926                 WORKLIST_REMOVE(&dap->da_list);
8927         if ((dap->da_state & DIRCHG) == 0) {
8928                 pagedep = dap->da_pagedep;
8929         } else {
8930                 dirrem = dap->da_previous;
8931                 pagedep = dirrem->dm_pagedep;
8932                 dirrem->dm_dirinum = pagedep->pd_ino;
8933                 dirrem->dm_state |= COMPLETE;
8934                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8935                         add_to_worklist(&dirrem->dm_list, 0);
8936         }
8937         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8938             0, &inodedep) != 0)
8939                 if (inodedep->id_mkdiradd == dap)
8940                         inodedep->id_mkdiradd = NULL;
8941         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8942                 for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8943                      mkdir = nextmd) {
8944                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
8945                         if (mkdir->md_diradd != dap)
8946                                 continue;
8947                         dap->da_state &=
8948                             ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8949                         LIST_REMOVE(mkdir, md_mkdirs);
8950                         if (mkdir->md_state & ONWORKLIST)
8951                                 WORKLIST_REMOVE(&mkdir->md_list);
8952                         if (mkdir->md_jaddref != NULL)
8953                                 panic("free_diradd: Unexpected jaddref");
8954                         WORKITEM_FREE(mkdir, D_MKDIR);
8955                         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8956                                 break;
8957                 }
8958                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8959                         panic("free_diradd: unfound ref");
8960         }
8961         if (inodedep)
8962                 free_inodedep(inodedep);
8963         /*
8964          * Free any journal segments waiting for the directory write.
8965          */
8966         handle_jwork(&dap->da_jwork);
8967         WORKITEM_FREE(dap, D_DIRADD);
8968 }
8969
8970 /*
8971  * Directory entry removal dependencies.
8972  * 
8973  * When removing a directory entry, the entry's inode pointer must be
8974  * zero'ed on disk before the corresponding inode's link count is decremented
8975  * (possibly freeing the inode for re-use). This dependency is handled by
8976  * updating the directory entry but delaying the inode count reduction until
8977  * after the directory block has been written to disk. After this point, the
8978  * inode count can be decremented whenever it is convenient.
8979  */
8980
8981 /*
8982  * This routine should be called immediately after removing
8983  * a directory entry.  The inode's link count should not be
8984  * decremented by the calling procedure -- the soft updates
8985  * code will do this task when it is safe.
8986  */
8987 void 
8988 softdep_setup_remove(bp, dp, ip, isrmdir)
8989         struct buf *bp;         /* buffer containing directory block */
8990         struct inode *dp;       /* inode for the directory being modified */
8991         struct inode *ip;       /* inode for directory entry being removed */
8992         int isrmdir;            /* indicates if doing RMDIR */
8993 {
8994         struct dirrem *dirrem, *prevdirrem;
8995         struct inodedep *inodedep;
8996         struct ufsmount *ump;
8997         int direct;
8998
8999         ump = ITOUMP(ip);
9000         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9001             ("softdep_setup_remove called on non-softdep filesystem"));
9002         /*
9003          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9004          * newdirrem() to setup the full directory remove which requires
9005          * isrmdir > 1.
9006          */
9007         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9008         /*
9009          * Add the dirrem to the inodedep's pending remove list for quick
9010          * discovery later.
9011          */
9012         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9013                 panic("softdep_setup_remove: Lost inodedep.");
9014         KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9015         dirrem->dm_state |= ONDEPLIST;
9016         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9017
9018         /*
9019          * If the COMPLETE flag is clear, then there were no active
9020          * entries and we want to roll back to a zeroed entry until
9021          * the new inode is committed to disk. If the COMPLETE flag is
9022          * set then we have deleted an entry that never made it to
9023          * disk. If the entry we deleted resulted from a name change,
9024          * then the old name still resides on disk. We cannot delete
9025          * its inode (returned to us in prevdirrem) until the zeroed
9026          * directory entry gets to disk. The new inode has never been
9027          * referenced on the disk, so can be deleted immediately.
9028          */
9029         if ((dirrem->dm_state & COMPLETE) == 0) {
9030                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9031                     dm_next);
9032                 FREE_LOCK(ump);
9033         } else {
9034                 if (prevdirrem != NULL)
9035                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9036                             prevdirrem, dm_next);
9037                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9038                 direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9039                 FREE_LOCK(ump);
9040                 if (direct)
9041                         handle_workitem_remove(dirrem, 0);
9042         }
9043 }
9044
9045 /*
9046  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9047  * pd_pendinghd list of a pagedep.
9048  */
9049 static struct diradd *
9050 diradd_lookup(pagedep, offset)
9051         struct pagedep *pagedep;
9052         int offset;
9053 {
9054         struct diradd *dap;
9055
9056         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9057                 if (dap->da_offset == offset)
9058                         return (dap);
9059         LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9060                 if (dap->da_offset == offset)
9061                         return (dap);
9062         return (NULL);
9063 }
9064
9065 /*
9066  * Search for a .. diradd dependency in a directory that is being removed.
9067  * If the directory was renamed to a new parent we have a diradd rather
9068  * than a mkdir for the .. entry.  We need to cancel it now before
9069  * it is found in truncate().
9070  */
9071 static struct jremref *
9072 cancel_diradd_dotdot(ip, dirrem, jremref)
9073         struct inode *ip;
9074         struct dirrem *dirrem;
9075         struct jremref *jremref;
9076 {
9077         struct pagedep *pagedep;
9078         struct diradd *dap;
9079         struct worklist *wk;
9080
9081         if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9082                 return (jremref);
9083         dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9084         if (dap == NULL)
9085                 return (jremref);
9086         cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9087         /*
9088          * Mark any journal work as belonging to the parent so it is freed
9089          * with the .. reference.
9090          */
9091         LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9092                 wk->wk_state |= MKDIR_PARENT;
9093         return (NULL);
9094 }
9095
9096 /*
9097  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9098  * replace it with a dirrem/diradd pair as a result of re-parenting a
9099  * directory.  This ensures that we don't simultaneously have a mkdir and
9100  * a diradd for the same .. entry.
9101  */
9102 static struct jremref *
9103 cancel_mkdir_dotdot(ip, dirrem, jremref)
9104         struct inode *ip;
9105         struct dirrem *dirrem;
9106         struct jremref *jremref;
9107 {
9108         struct inodedep *inodedep;
9109         struct jaddref *jaddref;
9110         struct ufsmount *ump;
9111         struct mkdir *mkdir;
9112         struct diradd *dap;
9113         struct mount *mp;
9114
9115         mp = ITOVFS(ip);
9116         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9117                 return (jremref);
9118         dap = inodedep->id_mkdiradd;
9119         if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9120                 return (jremref);
9121         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9122         for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9123             mkdir = LIST_NEXT(mkdir, md_mkdirs))
9124                 if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9125                         break;
9126         if (mkdir == NULL)
9127                 panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9128         if ((jaddref = mkdir->md_jaddref) != NULL) {
9129                 mkdir->md_jaddref = NULL;
9130                 jaddref->ja_state &= ~MKDIR_PARENT;
9131                 if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9132                         panic("cancel_mkdir_dotdot: Lost parent inodedep");
9133                 if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9134                         journal_jremref(dirrem, jremref, inodedep);
9135                         jremref = NULL;
9136                 }
9137         }
9138         if (mkdir->md_state & ONWORKLIST)
9139                 WORKLIST_REMOVE(&mkdir->md_list);
9140         mkdir->md_state |= ALLCOMPLETE;
9141         complete_mkdir(mkdir);
9142         return (jremref);
9143 }
9144
9145 static void
9146 journal_jremref(dirrem, jremref, inodedep)
9147         struct dirrem *dirrem;
9148         struct jremref *jremref;
9149         struct inodedep *inodedep;
9150 {
9151
9152         if (inodedep == NULL)
9153                 if (inodedep_lookup(jremref->jr_list.wk_mp,
9154                     jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9155                         panic("journal_jremref: Lost inodedep");
9156         LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9157         TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9158         add_to_journal(&jremref->jr_list);
9159 }
9160
9161 static void
9162 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9163         struct dirrem *dirrem;
9164         struct jremref *jremref;
9165         struct jremref *dotremref;
9166         struct jremref *dotdotremref;
9167 {
9168         struct inodedep *inodedep;
9169
9170
9171         if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9172             &inodedep) == 0)
9173                 panic("dirrem_journal: Lost inodedep");
9174         journal_jremref(dirrem, jremref, inodedep);
9175         if (dotremref)
9176                 journal_jremref(dirrem, dotremref, inodedep);
9177         if (dotdotremref)
9178                 journal_jremref(dirrem, dotdotremref, NULL);
9179 }
9180
9181 /*
9182  * Allocate a new dirrem if appropriate and return it along with
9183  * its associated pagedep. Called without a lock, returns with lock.
9184  */
9185 static struct dirrem *
9186 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9187         struct buf *bp;         /* buffer containing directory block */
9188         struct inode *dp;       /* inode for the directory being modified */
9189         struct inode *ip;       /* inode for directory entry being removed */
9190         int isrmdir;            /* indicates if doing RMDIR */
9191         struct dirrem **prevdirremp; /* previously referenced inode, if any */
9192 {
9193         int offset;
9194         ufs_lbn_t lbn;
9195         struct diradd *dap;
9196         struct dirrem *dirrem;
9197         struct pagedep *pagedep;
9198         struct jremref *jremref;
9199         struct jremref *dotremref;
9200         struct jremref *dotdotremref;
9201         struct vnode *dvp;
9202         struct ufsmount *ump;
9203
9204         /*
9205          * Whiteouts have no deletion dependencies.
9206          */
9207         if (ip == NULL)
9208                 panic("newdirrem: whiteout");
9209         dvp = ITOV(dp);
9210         ump = ITOUMP(dp);
9211
9212         /*
9213          * If the system is over its limit and our filesystem is
9214          * responsible for more than our share of that usage and
9215          * we are not a snapshot, request some inodedep cleanup.
9216          * Limiting the number of dirrem structures will also limit
9217          * the number of freefile and freeblks structures.
9218          */
9219         ACQUIRE_LOCK(ump);
9220         if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9221                 schedule_cleanup(UFSTOVFS(ump));
9222         else
9223                 FREE_LOCK(ump);
9224         dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9225             M_ZERO);
9226         workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9227         LIST_INIT(&dirrem->dm_jremrefhd);
9228         LIST_INIT(&dirrem->dm_jwork);
9229         dirrem->dm_state = isrmdir ? RMDIR : 0;
9230         dirrem->dm_oldinum = ip->i_number;
9231         *prevdirremp = NULL;
9232         /*
9233          * Allocate remove reference structures to track journal write
9234          * dependencies.  We will always have one for the link and
9235          * when doing directories we will always have one more for dot.
9236          * When renaming a directory we skip the dotdot link change so
9237          * this is not needed.
9238          */
9239         jremref = dotremref = dotdotremref = NULL;
9240         if (DOINGSUJ(dvp)) {
9241                 if (isrmdir) {
9242                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9243                             ip->i_effnlink + 2);
9244                         dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9245                             ip->i_effnlink + 1);
9246                         dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9247                             dp->i_effnlink + 1);
9248                         dotdotremref->jr_state |= MKDIR_PARENT;
9249                 } else
9250                         jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9251                             ip->i_effnlink + 1);
9252         }
9253         ACQUIRE_LOCK(ump);
9254         lbn = lblkno(ump->um_fs, dp->i_offset);
9255         offset = blkoff(ump->um_fs, dp->i_offset);
9256         pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9257             &pagedep);
9258         dirrem->dm_pagedep = pagedep;
9259         dirrem->dm_offset = offset;
9260         /*
9261          * If we're renaming a .. link to a new directory, cancel any
9262          * existing MKDIR_PARENT mkdir.  If it has already been canceled
9263          * the jremref is preserved for any potential diradd in this
9264          * location.  This can not coincide with a rmdir.
9265          */
9266         if (dp->i_offset == DOTDOT_OFFSET) {
9267                 if (isrmdir)
9268                         panic("newdirrem: .. directory change during remove?");
9269                 jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9270         }
9271         /*
9272          * If we're removing a directory search for the .. dependency now and
9273          * cancel it.  Any pending journal work will be added to the dirrem
9274          * to be completed when the workitem remove completes.
9275          */
9276         if (isrmdir)
9277                 dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9278         /*
9279          * Check for a diradd dependency for the same directory entry.
9280          * If present, then both dependencies become obsolete and can
9281          * be de-allocated.
9282          */
9283         dap = diradd_lookup(pagedep, offset);
9284         if (dap == NULL) {
9285                 /*
9286                  * Link the jremref structures into the dirrem so they are
9287                  * written prior to the pagedep.
9288                  */
9289                 if (jremref)
9290                         dirrem_journal(dirrem, jremref, dotremref,
9291                             dotdotremref);
9292                 return (dirrem);
9293         }
9294         /*
9295          * Must be ATTACHED at this point.
9296          */
9297         if ((dap->da_state & ATTACHED) == 0)
9298                 panic("newdirrem: not ATTACHED");
9299         if (dap->da_newinum != ip->i_number)
9300                 panic("newdirrem: inum %ju should be %ju",
9301                     (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9302         /*
9303          * If we are deleting a changed name that never made it to disk,
9304          * then return the dirrem describing the previous inode (which
9305          * represents the inode currently referenced from this entry on disk).
9306          */
9307         if ((dap->da_state & DIRCHG) != 0) {
9308                 *prevdirremp = dap->da_previous;
9309                 dap->da_state &= ~DIRCHG;
9310                 dap->da_pagedep = pagedep;
9311         }
9312         /*
9313          * We are deleting an entry that never made it to disk.
9314          * Mark it COMPLETE so we can delete its inode immediately.
9315          */
9316         dirrem->dm_state |= COMPLETE;
9317         cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9318 #ifdef INVARIANTS
9319         if (isrmdir == 0) {
9320                 struct worklist *wk;
9321
9322                 LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9323                         if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9324                                 panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9325         }
9326 #endif
9327
9328         return (dirrem);
9329 }
9330
9331 /*
9332  * Directory entry change dependencies.
9333  * 
9334  * Changing an existing directory entry requires that an add operation
9335  * be completed first followed by a deletion. The semantics for the addition
9336  * are identical to the description of adding a new entry above except
9337  * that the rollback is to the old inode number rather than zero. Once
9338  * the addition dependency is completed, the removal is done as described
9339  * in the removal routine above.
9340  */
9341
9342 /*
9343  * This routine should be called immediately after changing
9344  * a directory entry.  The inode's link count should not be
9345  * decremented by the calling procedure -- the soft updates
9346  * code will perform this task when it is safe.
9347  */
9348 void 
9349 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9350         struct buf *bp;         /* buffer containing directory block */
9351         struct inode *dp;       /* inode for the directory being modified */
9352         struct inode *ip;       /* inode for directory entry being removed */
9353         ino_t newinum;          /* new inode number for changed entry */
9354         int isrmdir;            /* indicates if doing RMDIR */
9355 {
9356         int offset;
9357         struct diradd *dap = NULL;
9358         struct dirrem *dirrem, *prevdirrem;
9359         struct pagedep *pagedep;
9360         struct inodedep *inodedep;
9361         struct jaddref *jaddref;
9362         struct mount *mp;
9363         struct ufsmount *ump;
9364
9365         mp = ITOVFS(dp);
9366         ump = VFSTOUFS(mp);
9367         offset = blkoff(ump->um_fs, dp->i_offset);
9368         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9369            ("softdep_setup_directory_change called on non-softdep filesystem"));
9370
9371         /*
9372          * Whiteouts do not need diradd dependencies.
9373          */
9374         if (newinum != UFS_WINO) {
9375                 dap = malloc(sizeof(struct diradd),
9376                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9377                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
9378                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9379                 dap->da_offset = offset;
9380                 dap->da_newinum = newinum;
9381                 LIST_INIT(&dap->da_jwork);
9382         }
9383
9384         /*
9385          * Allocate a new dirrem and ACQUIRE_LOCK.
9386          */
9387         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9388         pagedep = dirrem->dm_pagedep;
9389         /*
9390          * The possible values for isrmdir:
9391          *      0 - non-directory file rename
9392          *      1 - directory rename within same directory
9393          *   inum - directory rename to new directory of given inode number
9394          * When renaming to a new directory, we are both deleting and
9395          * creating a new directory entry, so the link count on the new
9396          * directory should not change. Thus we do not need the followup
9397          * dirrem which is usually done in handle_workitem_remove. We set
9398          * the DIRCHG flag to tell handle_workitem_remove to skip the 
9399          * followup dirrem.
9400          */
9401         if (isrmdir > 1)
9402                 dirrem->dm_state |= DIRCHG;
9403
9404         /*
9405          * Whiteouts have no additional dependencies,
9406          * so just put the dirrem on the correct list.
9407          */
9408         if (newinum == UFS_WINO) {
9409                 if ((dirrem->dm_state & COMPLETE) == 0) {
9410                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9411                             dm_next);
9412                 } else {
9413                         dirrem->dm_dirinum = pagedep->pd_ino;
9414                         if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9415                                 add_to_worklist(&dirrem->dm_list, 0);
9416                 }
9417                 FREE_LOCK(ump);
9418                 return;
9419         }
9420         /*
9421          * Add the dirrem to the inodedep's pending remove list for quick
9422          * discovery later.  A valid nlinkdelta ensures that this lookup
9423          * will not fail.
9424          */
9425         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9426                 panic("softdep_setup_directory_change: Lost inodedep.");
9427         dirrem->dm_state |= ONDEPLIST;
9428         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9429
9430         /*
9431          * If the COMPLETE flag is clear, then there were no active
9432          * entries and we want to roll back to the previous inode until
9433          * the new inode is committed to disk. If the COMPLETE flag is
9434          * set, then we have deleted an entry that never made it to disk.
9435          * If the entry we deleted resulted from a name change, then the old
9436          * inode reference still resides on disk. Any rollback that we do
9437          * needs to be to that old inode (returned to us in prevdirrem). If
9438          * the entry we deleted resulted from a create, then there is
9439          * no entry on the disk, so we want to roll back to zero rather
9440          * than the uncommitted inode. In either of the COMPLETE cases we
9441          * want to immediately free the unwritten and unreferenced inode.
9442          */
9443         if ((dirrem->dm_state & COMPLETE) == 0) {
9444                 dap->da_previous = dirrem;
9445         } else {
9446                 if (prevdirrem != NULL) {
9447                         dap->da_previous = prevdirrem;
9448                 } else {
9449                         dap->da_state &= ~DIRCHG;
9450                         dap->da_pagedep = pagedep;
9451                 }
9452                 dirrem->dm_dirinum = pagedep->pd_ino;
9453                 if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9454                         add_to_worklist(&dirrem->dm_list, 0);
9455         }
9456         /*
9457          * Lookup the jaddref for this journal entry.  We must finish
9458          * initializing it and make the diradd write dependent on it.
9459          * If we're not journaling, put it on the id_bufwait list if the
9460          * inode is not yet written. If it is written, do the post-inode
9461          * write processing to put it on the id_pendinghd list.
9462          */
9463         inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9464         if (MOUNTEDSUJ(mp)) {
9465                 jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9466                     inoreflst);
9467                 KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9468                     ("softdep_setup_directory_change: bad jaddref %p",
9469                     jaddref));
9470                 jaddref->ja_diroff = dp->i_offset;
9471                 jaddref->ja_diradd = dap;
9472                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9473                     dap, da_pdlist);
9474                 add_to_journal(&jaddref->ja_list);
9475         } else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9476                 dap->da_state |= COMPLETE;
9477                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9478                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9479         } else {
9480                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9481                     dap, da_pdlist);
9482                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9483         }
9484         /*
9485          * If we're making a new name for a directory that has not been
9486          * committed when need to move the dot and dotdot references to
9487          * this new name.
9488          */
9489         if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9490                 merge_diradd(inodedep, dap);
9491         FREE_LOCK(ump);
9492 }
9493
9494 /*
9495  * Called whenever the link count on an inode is changed.
9496  * It creates an inode dependency so that the new reference(s)
9497  * to the inode cannot be committed to disk until the updated
9498  * inode has been written.
9499  */
9500 void
9501 softdep_change_linkcnt(ip)
9502         struct inode *ip;       /* the inode with the increased link count */
9503 {
9504         struct inodedep *inodedep;
9505         struct ufsmount *ump;
9506
9507         ump = ITOUMP(ip);
9508         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9509             ("softdep_change_linkcnt called on non-softdep filesystem"));
9510         ACQUIRE_LOCK(ump);
9511         inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9512         if (ip->i_nlink < ip->i_effnlink)
9513                 panic("softdep_change_linkcnt: bad delta");
9514         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9515         FREE_LOCK(ump);
9516 }
9517
9518 /*
9519  * Attach a sbdep dependency to the superblock buf so that we can keep
9520  * track of the head of the linked list of referenced but unlinked inodes.
9521  */
9522 void
9523 softdep_setup_sbupdate(ump, fs, bp)
9524         struct ufsmount *ump;
9525         struct fs *fs;
9526         struct buf *bp;
9527 {
9528         struct sbdep *sbdep;
9529         struct worklist *wk;
9530
9531         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9532             ("softdep_setup_sbupdate called on non-softdep filesystem"));
9533         LIST_FOREACH(wk, &bp->b_dep, wk_list)
9534                 if (wk->wk_type == D_SBDEP)
9535                         break;
9536         if (wk != NULL)
9537                 return;
9538         sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9539         workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9540         sbdep->sb_fs = fs;
9541         sbdep->sb_ump = ump;
9542         ACQUIRE_LOCK(ump);
9543         WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9544         FREE_LOCK(ump);
9545 }
9546
9547 /*
9548  * Return the first unlinked inodedep which is ready to be the head of the
9549  * list.  The inodedep and all those after it must have valid next pointers.
9550  */
9551 static struct inodedep *
9552 first_unlinked_inodedep(ump)
9553         struct ufsmount *ump;
9554 {
9555         struct inodedep *inodedep;
9556         struct inodedep *idp;
9557
9558         LOCK_OWNED(ump);
9559         for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9560             inodedep; inodedep = idp) {
9561                 if ((inodedep->id_state & UNLINKNEXT) == 0)
9562                         return (NULL);
9563                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9564                 if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9565                         break;
9566                 if ((inodedep->id_state & UNLINKPREV) == 0)
9567                         break;
9568         }
9569         return (inodedep);
9570 }
9571
9572 /*
9573  * Set the sujfree unlinked head pointer prior to writing a superblock.
9574  */
9575 static void
9576 initiate_write_sbdep(sbdep)
9577         struct sbdep *sbdep;
9578 {
9579         struct inodedep *inodedep;
9580         struct fs *bpfs;
9581         struct fs *fs;
9582
9583         bpfs = sbdep->sb_fs;
9584         fs = sbdep->sb_ump->um_fs;
9585         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9586         if (inodedep) {
9587                 fs->fs_sujfree = inodedep->id_ino;
9588                 inodedep->id_state |= UNLINKPREV;
9589         } else
9590                 fs->fs_sujfree = 0;
9591         bpfs->fs_sujfree = fs->fs_sujfree;
9592         /*
9593          * Because we have made changes to the superblock, we need to
9594          * recompute its check-hash.
9595          */
9596         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9597 }
9598
9599 /*
9600  * After a superblock is written determine whether it must be written again
9601  * due to a changing unlinked list head.
9602  */
9603 static int
9604 handle_written_sbdep(sbdep, bp)
9605         struct sbdep *sbdep;
9606         struct buf *bp;
9607 {
9608         struct inodedep *inodedep;
9609         struct fs *fs;
9610
9611         LOCK_OWNED(sbdep->sb_ump);
9612         fs = sbdep->sb_fs;
9613         /*
9614          * If the superblock doesn't match the in-memory list start over.
9615          */
9616         inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9617         if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9618             (inodedep == NULL && fs->fs_sujfree != 0)) {
9619                 bdirty(bp);
9620                 return (1);
9621         }
9622         WORKITEM_FREE(sbdep, D_SBDEP);
9623         if (fs->fs_sujfree == 0)
9624                 return (0);
9625         /*
9626          * Now that we have a record of this inode in stable store allow it
9627          * to be written to free up pending work.  Inodes may see a lot of
9628          * write activity after they are unlinked which we must not hold up.
9629          */
9630         for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9631                 if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9632                         panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9633                             inodedep, inodedep->id_state);
9634                 if (inodedep->id_state & UNLINKONLIST)
9635                         break;
9636                 inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9637         }
9638
9639         return (0);
9640 }
9641
9642 /*
9643  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9644  */
9645 static void
9646 unlinked_inodedep(mp, inodedep)
9647         struct mount *mp;
9648         struct inodedep *inodedep;
9649 {
9650         struct ufsmount *ump;
9651
9652         ump = VFSTOUFS(mp);
9653         LOCK_OWNED(ump);
9654         if (MOUNTEDSUJ(mp) == 0)
9655                 return;
9656         ump->um_fs->fs_fmod = 1;
9657         if (inodedep->id_state & UNLINKED)
9658                 panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9659         inodedep->id_state |= UNLINKED;
9660         TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9661 }
9662
9663 /*
9664  * Remove an inodedep from the unlinked inodedep list.  This may require
9665  * disk writes if the inode has made it that far.
9666  */
9667 static void
9668 clear_unlinked_inodedep(inodedep)
9669         struct inodedep *inodedep;
9670 {
9671         struct ufs2_dinode *dip;
9672         struct ufsmount *ump;
9673         struct inodedep *idp;
9674         struct inodedep *idn;
9675         struct fs *fs, *bpfs;
9676         struct buf *bp;
9677         ino_t ino;
9678         ino_t nino;
9679         ino_t pino;
9680         int error;
9681
9682         ump = VFSTOUFS(inodedep->id_list.wk_mp);
9683         fs = ump->um_fs;
9684         ino = inodedep->id_ino;
9685         error = 0;
9686         for (;;) {
9687                 LOCK_OWNED(ump);
9688                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9689                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9690                     inodedep));
9691                 /*
9692                  * If nothing has yet been written simply remove us from
9693                  * the in memory list and return.  This is the most common
9694                  * case where handle_workitem_remove() loses the final
9695                  * reference.
9696                  */
9697                 if ((inodedep->id_state & UNLINKLINKS) == 0)
9698                         break;
9699                 /*
9700                  * If we have a NEXT pointer and no PREV pointer we can simply
9701                  * clear NEXT's PREV and remove ourselves from the list.  Be
9702                  * careful not to clear PREV if the superblock points at
9703                  * next as well.
9704                  */
9705                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9706                 if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9707                         if (idn && fs->fs_sujfree != idn->id_ino)
9708                                 idn->id_state &= ~UNLINKPREV;
9709                         break;
9710                 }
9711                 /*
9712                  * Here we have an inodedep which is actually linked into
9713                  * the list.  We must remove it by forcing a write to the
9714                  * link before us, whether it be the superblock or an inode.
9715                  * Unfortunately the list may change while we're waiting
9716                  * on the buf lock for either resource so we must loop until
9717                  * we lock the right one.  If both the superblock and an
9718                  * inode point to this inode we must clear the inode first
9719                  * followed by the superblock.
9720                  */
9721                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9722                 pino = 0;
9723                 if (idp && (idp->id_state & UNLINKNEXT))
9724                         pino = idp->id_ino;
9725                 FREE_LOCK(ump);
9726                 if (pino == 0) {
9727                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9728                             (int)fs->fs_sbsize, 0, 0, 0);
9729                 } else {
9730                         error = bread(ump->um_devvp,
9731                             fsbtodb(fs, ino_to_fsba(fs, pino)),
9732                             (int)fs->fs_bsize, NOCRED, &bp);
9733                         if (error)
9734                                 brelse(bp);
9735                 }
9736                 ACQUIRE_LOCK(ump);
9737                 if (error)
9738                         break;
9739                 /* If the list has changed restart the loop. */
9740                 idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9741                 nino = 0;
9742                 if (idp && (idp->id_state & UNLINKNEXT))
9743                         nino = idp->id_ino;
9744                 if (nino != pino ||
9745                     (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9746                         FREE_LOCK(ump);
9747                         brelse(bp);
9748                         ACQUIRE_LOCK(ump);
9749                         continue;
9750                 }
9751                 nino = 0;
9752                 idn = TAILQ_NEXT(inodedep, id_unlinked);
9753                 if (idn)
9754                         nino = idn->id_ino;
9755                 /*
9756                  * Remove us from the in memory list.  After this we cannot
9757                  * access the inodedep.
9758                  */
9759                 KASSERT((inodedep->id_state & UNLINKED) != 0,
9760                     ("clear_unlinked_inodedep: inodedep %p not unlinked",
9761                     inodedep));
9762                 inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9763                 TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9764                 FREE_LOCK(ump);
9765                 /*
9766                  * The predecessor's next pointer is manually updated here
9767                  * so that the NEXT flag is never cleared for an element
9768                  * that is in the list.
9769                  */
9770                 if (pino == 0) {
9771                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9772                         bpfs = (struct fs *)bp->b_data;
9773                         ffs_oldfscompat_write(bpfs, ump);
9774                         softdep_setup_sbupdate(ump, bpfs, bp);
9775                         /*
9776                          * Because we may have made changes to the superblock,
9777                          * we need to recompute its check-hash.
9778                          */
9779                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9780                 } else if (fs->fs_magic == FS_UFS1_MAGIC) {
9781                         ((struct ufs1_dinode *)bp->b_data +
9782                             ino_to_fsbo(fs, pino))->di_freelink = nino;
9783                 } else {
9784                         dip = (struct ufs2_dinode *)bp->b_data +
9785                             ino_to_fsbo(fs, pino);
9786                         dip->di_freelink = nino;
9787                         ffs_update_dinode_ckhash(fs, dip);
9788                 }
9789                 /*
9790                  * If the bwrite fails we have no recourse to recover.  The
9791                  * filesystem is corrupted already.
9792                  */
9793                 bwrite(bp);
9794                 ACQUIRE_LOCK(ump);
9795                 /*
9796                  * If the superblock pointer still needs to be cleared force
9797                  * a write here.
9798                  */
9799                 if (fs->fs_sujfree == ino) {
9800                         FREE_LOCK(ump);
9801                         bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9802                             (int)fs->fs_sbsize, 0, 0, 0);
9803                         bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9804                         bpfs = (struct fs *)bp->b_data;
9805                         ffs_oldfscompat_write(bpfs, ump);
9806                         softdep_setup_sbupdate(ump, bpfs, bp);
9807                         /*
9808                          * Because we may have made changes to the superblock,
9809                          * we need to recompute its check-hash.
9810                          */
9811                         bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9812                         bwrite(bp);
9813                         ACQUIRE_LOCK(ump);
9814                 }
9815
9816                 if (fs->fs_sujfree != ino)
9817                         return;
9818                 panic("clear_unlinked_inodedep: Failed to clear free head");
9819         }
9820         if (inodedep->id_ino == fs->fs_sujfree)
9821                 panic("clear_unlinked_inodedep: Freeing head of free list");
9822         inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9823         TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9824         return;
9825 }
9826
9827 /*
9828  * This workitem decrements the inode's link count.
9829  * If the link count reaches zero, the file is removed.
9830  */
9831 static int
9832 handle_workitem_remove(dirrem, flags)
9833         struct dirrem *dirrem;
9834         int flags;
9835 {
9836         struct inodedep *inodedep;
9837         struct workhead dotdotwk;
9838         struct worklist *wk;
9839         struct ufsmount *ump;
9840         struct mount *mp;
9841         struct vnode *vp;
9842         struct inode *ip;
9843         ino_t oldinum;
9844
9845         if (dirrem->dm_state & ONWORKLIST)
9846                 panic("handle_workitem_remove: dirrem %p still on worklist",
9847                     dirrem);
9848         oldinum = dirrem->dm_oldinum;
9849         mp = dirrem->dm_list.wk_mp;
9850         ump = VFSTOUFS(mp);
9851         flags |= LK_EXCLUSIVE;
9852         if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9853                 return (EBUSY);
9854         ip = VTOI(vp);
9855         MPASS(ip->i_mode != 0);
9856         ACQUIRE_LOCK(ump);
9857         if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9858                 panic("handle_workitem_remove: lost inodedep");
9859         if (dirrem->dm_state & ONDEPLIST)
9860                 LIST_REMOVE(dirrem, dm_inonext);
9861         KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9862             ("handle_workitem_remove:  Journal entries not written."));
9863
9864         /*
9865          * Move all dependencies waiting on the remove to complete
9866          * from the dirrem to the inode inowait list to be completed
9867          * after the inode has been updated and written to disk.
9868          *
9869          * Any marked MKDIR_PARENT are saved to be completed when the 
9870          * dotdot ref is removed unless DIRCHG is specified.  For
9871          * directory change operations there will be no further
9872          * directory writes and the jsegdeps need to be moved along
9873          * with the rest to be completed when the inode is free or
9874          * stable in the inode free list.
9875          */
9876         LIST_INIT(&dotdotwk);
9877         while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9878                 WORKLIST_REMOVE(wk);
9879                 if ((dirrem->dm_state & DIRCHG) == 0 &&
9880                     wk->wk_state & MKDIR_PARENT) {
9881                         wk->wk_state &= ~MKDIR_PARENT;
9882                         WORKLIST_INSERT(&dotdotwk, wk);
9883                         continue;
9884                 }
9885                 WORKLIST_INSERT(&inodedep->id_inowait, wk);
9886         }
9887         LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9888         /*
9889          * Normal file deletion.
9890          */
9891         if ((dirrem->dm_state & RMDIR) == 0) {
9892                 ip->i_nlink--;
9893                 KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
9894                     "%ju negative i_nlink %d", (intmax_t)ip->i_number,
9895                     ip->i_nlink));
9896                 DIP_SET(ip, i_nlink, ip->i_nlink);
9897                 UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9898                 if (ip->i_nlink < ip->i_effnlink)
9899                         panic("handle_workitem_remove: bad file delta");
9900                 if (ip->i_nlink == 0) 
9901                         unlinked_inodedep(mp, inodedep);
9902                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9903                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9904                     ("handle_workitem_remove: worklist not empty. %s",
9905                     TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9906                 WORKITEM_FREE(dirrem, D_DIRREM);
9907                 FREE_LOCK(ump);
9908                 goto out;
9909         }
9910         /*
9911          * Directory deletion. Decrement reference count for both the
9912          * just deleted parent directory entry and the reference for ".".
9913          * Arrange to have the reference count on the parent decremented
9914          * to account for the loss of "..".
9915          */
9916         ip->i_nlink -= 2;
9917         KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
9918             "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
9919         DIP_SET(ip, i_nlink, ip->i_nlink);
9920         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9921         if (ip->i_nlink < ip->i_effnlink)
9922                 panic("handle_workitem_remove: bad dir delta");
9923         if (ip->i_nlink == 0)
9924                 unlinked_inodedep(mp, inodedep);
9925         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9926         /*
9927          * Rename a directory to a new parent. Since, we are both deleting
9928          * and creating a new directory entry, the link count on the new
9929          * directory should not change. Thus we skip the followup dirrem.
9930          */
9931         if (dirrem->dm_state & DIRCHG) {
9932                 KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9933                     ("handle_workitem_remove: DIRCHG and worklist not empty."));
9934                 WORKITEM_FREE(dirrem, D_DIRREM);
9935                 FREE_LOCK(ump);
9936                 goto out;
9937         }
9938         dirrem->dm_state = ONDEPLIST;
9939         dirrem->dm_oldinum = dirrem->dm_dirinum;
9940         /*
9941          * Place the dirrem on the parent's diremhd list.
9942          */
9943         if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9944                 panic("handle_workitem_remove: lost dir inodedep");
9945         LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9946         /*
9947          * If the allocated inode has never been written to disk, then
9948          * the on-disk inode is zero'ed and we can remove the file
9949          * immediately.  When journaling if the inode has been marked
9950          * unlinked and not DEPCOMPLETE we know it can never be written.
9951          */
9952         inodedep_lookup(mp, oldinum, 0, &inodedep);
9953         if (inodedep == NULL ||
9954             (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9955             check_inode_unwritten(inodedep)) {
9956                 FREE_LOCK(ump);
9957                 vput(vp);
9958                 return handle_workitem_remove(dirrem, flags);
9959         }
9960         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9961         FREE_LOCK(ump);
9962         UFS_INODE_SET_FLAG(ip, IN_CHANGE);
9963 out:
9964         ffs_update(vp, 0);
9965         vput(vp);
9966         return (0);
9967 }
9968
9969 /*
9970  * Inode de-allocation dependencies.
9971  * 
9972  * When an inode's link count is reduced to zero, it can be de-allocated. We
9973  * found it convenient to postpone de-allocation until after the inode is
9974  * written to disk with its new link count (zero).  At this point, all of the
9975  * on-disk inode's block pointers are nullified and, with careful dependency
9976  * list ordering, all dependencies related to the inode will be satisfied and
9977  * the corresponding dependency structures de-allocated.  So, if/when the
9978  * inode is reused, there will be no mixing of old dependencies with new
9979  * ones.  This artificial dependency is set up by the block de-allocation
9980  * procedure above (softdep_setup_freeblocks) and completed by the
9981  * following procedure.
9982  */
9983 static void 
9984 handle_workitem_freefile(freefile)
9985         struct freefile *freefile;
9986 {
9987         struct workhead wkhd;
9988         struct fs *fs;
9989         struct ufsmount *ump;
9990         int error;
9991 #ifdef INVARIANTS
9992         struct inodedep *idp;
9993 #endif
9994
9995         ump = VFSTOUFS(freefile->fx_list.wk_mp);
9996         fs = ump->um_fs;
9997 #ifdef INVARIANTS
9998         ACQUIRE_LOCK(ump);
9999         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10000         FREE_LOCK(ump);
10001         if (error)
10002                 panic("handle_workitem_freefile: inodedep %p survived", idp);
10003 #endif
10004         UFS_LOCK(ump);
10005         fs->fs_pendinginodes -= 1;
10006         UFS_UNLOCK(ump);
10007         LIST_INIT(&wkhd);
10008         LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10009         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10010             freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10011                 softdep_error("handle_workitem_freefile", error);
10012         ACQUIRE_LOCK(ump);
10013         WORKITEM_FREE(freefile, D_FREEFILE);
10014         FREE_LOCK(ump);
10015 }
10016
10017
10018 /*
10019  * Helper function which unlinks marker element from work list and returns
10020  * the next element on the list.
10021  */
10022 static __inline struct worklist *
10023 markernext(struct worklist *marker)
10024 {
10025         struct worklist *next;
10026         
10027         next = LIST_NEXT(marker, wk_list);
10028         LIST_REMOVE(marker, wk_list);
10029         return next;
10030 }
10031
10032 /*
10033  * Disk writes.
10034  * 
10035  * The dependency structures constructed above are most actively used when file
10036  * system blocks are written to disk.  No constraints are placed on when a
10037  * block can be written, but unsatisfied update dependencies are made safe by
10038  * modifying (or replacing) the source memory for the duration of the disk
10039  * write.  When the disk write completes, the memory block is again brought
10040  * up-to-date.
10041  *
10042  * In-core inode structure reclamation.
10043  * 
10044  * Because there are a finite number of "in-core" inode structures, they are
10045  * reused regularly.  By transferring all inode-related dependencies to the
10046  * in-memory inode block and indexing them separately (via "inodedep"s), we
10047  * can allow "in-core" inode structures to be reused at any time and avoid
10048  * any increase in contention.
10049  *
10050  * Called just before entering the device driver to initiate a new disk I/O.
10051  * The buffer must be locked, thus, no I/O completion operations can occur
10052  * while we are manipulating its associated dependencies.
10053  */
10054 static void 
10055 softdep_disk_io_initiation(bp)
10056         struct buf *bp;         /* structure describing disk write to occur */
10057 {
10058         struct worklist *wk;
10059         struct worklist marker;
10060         struct inodedep *inodedep;
10061         struct freeblks *freeblks;
10062         struct jblkdep *jblkdep;
10063         struct newblk *newblk;
10064         struct ufsmount *ump;
10065
10066         /*
10067          * We only care about write operations. There should never
10068          * be dependencies for reads.
10069          */
10070         if (bp->b_iocmd != BIO_WRITE)
10071                 panic("softdep_disk_io_initiation: not write");
10072
10073         if (bp->b_vflags & BV_BKGRDINPROG)
10074                 panic("softdep_disk_io_initiation: Writing buffer with "
10075                     "background write in progress: %p", bp);
10076
10077         ump = softdep_bp_to_mp(bp);
10078         if (ump == NULL)
10079                 return;
10080
10081         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
10082         PHOLD(curproc);                 /* Don't swap out kernel stack */
10083         ACQUIRE_LOCK(ump);
10084         /*
10085          * Do any necessary pre-I/O processing.
10086          */
10087         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10088              wk = markernext(&marker)) {
10089                 LIST_INSERT_AFTER(wk, &marker, wk_list);
10090                 switch (wk->wk_type) {
10091
10092                 case D_PAGEDEP:
10093                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
10094                         continue;
10095
10096                 case D_INODEDEP:
10097                         inodedep = WK_INODEDEP(wk);
10098                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10099                                 initiate_write_inodeblock_ufs1(inodedep, bp);
10100                         else
10101                                 initiate_write_inodeblock_ufs2(inodedep, bp);
10102                         continue;
10103
10104                 case D_INDIRDEP:
10105                         initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10106                         continue;
10107
10108                 case D_BMSAFEMAP:
10109                         initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10110                         continue;
10111
10112                 case D_JSEG:
10113                         WK_JSEG(wk)->js_buf = NULL;
10114                         continue;
10115
10116                 case D_FREEBLKS:
10117                         freeblks = WK_FREEBLKS(wk);
10118                         jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10119                         /*
10120                          * We have to wait for the freeblks to be journaled
10121                          * before we can write an inodeblock with updated
10122                          * pointers.  Be careful to arrange the marker so
10123                          * we revisit the freeblks if it's not removed by
10124                          * the first jwait().
10125                          */
10126                         if (jblkdep != NULL) {
10127                                 LIST_REMOVE(&marker, wk_list);
10128                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10129                                 jwait(&jblkdep->jb_list, MNT_WAIT);
10130                         }
10131                         continue;
10132                 case D_ALLOCDIRECT:
10133                 case D_ALLOCINDIR:
10134                         /*
10135                          * We have to wait for the jnewblk to be journaled
10136                          * before we can write to a block if the contents
10137                          * may be confused with an earlier file's indirect
10138                          * at recovery time.  Handle the marker as described
10139                          * above.
10140                          */
10141                         newblk = WK_NEWBLK(wk);
10142                         if (newblk->nb_jnewblk != NULL &&
10143                             indirblk_lookup(newblk->nb_list.wk_mp,
10144                             newblk->nb_newblkno)) {
10145                                 LIST_REMOVE(&marker, wk_list);
10146                                 LIST_INSERT_BEFORE(wk, &marker, wk_list);
10147                                 jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10148                         }
10149                         continue;
10150
10151                 case D_SBDEP:
10152                         initiate_write_sbdep(WK_SBDEP(wk));
10153                         continue;
10154
10155                 case D_MKDIR:
10156                 case D_FREEWORK:
10157                 case D_FREEDEP:
10158                 case D_JSEGDEP:
10159                         continue;
10160
10161                 default:
10162                         panic("handle_disk_io_initiation: Unexpected type %s",
10163                             TYPENAME(wk->wk_type));
10164                         /* NOTREACHED */
10165                 }
10166         }
10167         FREE_LOCK(ump);
10168         PRELE(curproc);                 /* Allow swapout of kernel stack */
10169 }
10170
10171 /*
10172  * Called from within the procedure above to deal with unsatisfied
10173  * allocation dependencies in a directory. The buffer must be locked,
10174  * thus, no I/O completion operations can occur while we are
10175  * manipulating its associated dependencies.
10176  */
10177 static void
10178 initiate_write_filepage(pagedep, bp)
10179         struct pagedep *pagedep;
10180         struct buf *bp;
10181 {
10182         struct jremref *jremref;
10183         struct jmvref *jmvref;
10184         struct dirrem *dirrem;
10185         struct diradd *dap;
10186         struct direct *ep;
10187         int i;
10188
10189         if (pagedep->pd_state & IOSTARTED) {
10190                 /*
10191                  * This can only happen if there is a driver that does not
10192                  * understand chaining. Here biodone will reissue the call
10193                  * to strategy for the incomplete buffers.
10194                  */
10195                 printf("initiate_write_filepage: already started\n");
10196                 return;
10197         }
10198         pagedep->pd_state |= IOSTARTED;
10199         /*
10200          * Wait for all journal remove dependencies to hit the disk.
10201          * We can not allow any potentially conflicting directory adds
10202          * to be visible before removes and rollback is too difficult.
10203          * The per-filesystem lock may be dropped and re-acquired, however 
10204          * we hold the buf locked so the dependency can not go away.
10205          */
10206         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10207                 while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10208                         jwait(&jremref->jr_list, MNT_WAIT);
10209         while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10210                 jwait(&jmvref->jm_list, MNT_WAIT);
10211         for (i = 0; i < DAHASHSZ; i++) {
10212                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10213                         ep = (struct direct *)
10214                             ((char *)bp->b_data + dap->da_offset);
10215                         if (ep->d_ino != dap->da_newinum)
10216                                 panic("%s: dir inum %ju != new %ju",
10217                                     "initiate_write_filepage",
10218                                     (uintmax_t)ep->d_ino,
10219                                     (uintmax_t)dap->da_newinum);
10220                         if (dap->da_state & DIRCHG)
10221                                 ep->d_ino = dap->da_previous->dm_oldinum;
10222                         else
10223                                 ep->d_ino = 0;
10224                         dap->da_state &= ~ATTACHED;
10225                         dap->da_state |= UNDONE;
10226                 }
10227         }
10228 }
10229
10230 /*
10231  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10232  * Note that any bug fixes made to this routine must be done in the
10233  * version found below.
10234  *
10235  * Called from within the procedure above to deal with unsatisfied
10236  * allocation dependencies in an inodeblock. The buffer must be
10237  * locked, thus, no I/O completion operations can occur while we
10238  * are manipulating its associated dependencies.
10239  */
10240 static void 
10241 initiate_write_inodeblock_ufs1(inodedep, bp)
10242         struct inodedep *inodedep;
10243         struct buf *bp;                 /* The inode block */
10244 {
10245         struct allocdirect *adp, *lastadp;
10246         struct ufs1_dinode *dp;
10247         struct ufs1_dinode *sip;
10248         struct inoref *inoref;
10249         struct ufsmount *ump;
10250         struct fs *fs;
10251         ufs_lbn_t i;
10252 #ifdef INVARIANTS
10253         ufs_lbn_t prevlbn = 0;
10254 #endif
10255         int deplist;
10256
10257         if (inodedep->id_state & IOSTARTED)
10258                 panic("initiate_write_inodeblock_ufs1: already started");
10259         inodedep->id_state |= IOSTARTED;
10260         fs = inodedep->id_fs;
10261         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10262         LOCK_OWNED(ump);
10263         dp = (struct ufs1_dinode *)bp->b_data +
10264             ino_to_fsbo(fs, inodedep->id_ino);
10265
10266         /*
10267          * If we're on the unlinked list but have not yet written our
10268          * next pointer initialize it here.
10269          */
10270         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10271                 struct inodedep *inon;
10272
10273                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10274                 dp->di_freelink = inon ? inon->id_ino : 0;
10275         }
10276         /*
10277          * If the bitmap is not yet written, then the allocated
10278          * inode cannot be written to disk.
10279          */
10280         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10281                 if (inodedep->id_savedino1 != NULL)
10282                         panic("initiate_write_inodeblock_ufs1: I/O underway");
10283                 FREE_LOCK(ump);
10284                 sip = malloc(sizeof(struct ufs1_dinode),
10285                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10286                 ACQUIRE_LOCK(ump);
10287                 inodedep->id_savedino1 = sip;
10288                 *inodedep->id_savedino1 = *dp;
10289                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10290                 dp->di_gen = inodedep->id_savedino1->di_gen;
10291                 dp->di_freelink = inodedep->id_savedino1->di_freelink;
10292                 return;
10293         }
10294         /*
10295          * If no dependencies, then there is nothing to roll back.
10296          */
10297         inodedep->id_savedsize = dp->di_size;
10298         inodedep->id_savedextsize = 0;
10299         inodedep->id_savednlink = dp->di_nlink;
10300         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10301             TAILQ_EMPTY(&inodedep->id_inoreflst))
10302                 return;
10303         /*
10304          * Revert the link count to that of the first unwritten journal entry.
10305          */
10306         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10307         if (inoref)
10308                 dp->di_nlink = inoref->if_nlink;
10309         /*
10310          * Set the dependencies to busy.
10311          */
10312         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10313              adp = TAILQ_NEXT(adp, ad_next)) {
10314 #ifdef INVARIANTS
10315                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10316                         panic("softdep_write_inodeblock: lbn order");
10317                 prevlbn = adp->ad_offset;
10318                 if (adp->ad_offset < UFS_NDADDR &&
10319                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10320                         panic("initiate_write_inodeblock_ufs1: "
10321                             "direct pointer #%jd mismatch %d != %jd",
10322                             (intmax_t)adp->ad_offset,
10323                             dp->di_db[adp->ad_offset],
10324                             (intmax_t)adp->ad_newblkno);
10325                 if (adp->ad_offset >= UFS_NDADDR &&
10326                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10327                         panic("initiate_write_inodeblock_ufs1: "
10328                             "indirect pointer #%jd mismatch %d != %jd",
10329                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10330                             dp->di_ib[adp->ad_offset - UFS_NDADDR],
10331                             (intmax_t)adp->ad_newblkno);
10332                 deplist |= 1 << adp->ad_offset;
10333                 if ((adp->ad_state & ATTACHED) == 0)
10334                         panic("initiate_write_inodeblock_ufs1: "
10335                             "Unknown state 0x%x", adp->ad_state);
10336 #endif /* INVARIANTS */
10337                 adp->ad_state &= ~ATTACHED;
10338                 adp->ad_state |= UNDONE;
10339         }
10340         /*
10341          * The on-disk inode cannot claim to be any larger than the last
10342          * fragment that has been written. Otherwise, the on-disk inode
10343          * might have fragments that were not the last block in the file
10344          * which would corrupt the filesystem.
10345          */
10346         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10347              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10348                 if (adp->ad_offset >= UFS_NDADDR)
10349                         break;
10350                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10351                 /* keep going until hitting a rollback to a frag */
10352                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10353                         continue;
10354                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10355                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10356 #ifdef INVARIANTS
10357                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10358                                 panic("initiate_write_inodeblock_ufs1: "
10359                                     "lost dep1");
10360 #endif /* INVARIANTS */
10361                         dp->di_db[i] = 0;
10362                 }
10363                 for (i = 0; i < UFS_NIADDR; i++) {
10364 #ifdef INVARIANTS
10365                         if (dp->di_ib[i] != 0 &&
10366                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10367                                 panic("initiate_write_inodeblock_ufs1: "
10368                                     "lost dep2");
10369 #endif /* INVARIANTS */
10370                         dp->di_ib[i] = 0;
10371                 }
10372                 return;
10373         }
10374         /*
10375          * If we have zero'ed out the last allocated block of the file,
10376          * roll back the size to the last currently allocated block.
10377          * We know that this last allocated block is a full-sized as
10378          * we already checked for fragments in the loop above.
10379          */
10380         if (lastadp != NULL &&
10381             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10382                 for (i = lastadp->ad_offset; i >= 0; i--)
10383                         if (dp->di_db[i] != 0)
10384                                 break;
10385                 dp->di_size = (i + 1) * fs->fs_bsize;
10386         }
10387         /*
10388          * The only dependencies are for indirect blocks.
10389          *
10390          * The file size for indirect block additions is not guaranteed.
10391          * Such a guarantee would be non-trivial to achieve. The conventional
10392          * synchronous write implementation also does not make this guarantee.
10393          * Fsck should catch and fix discrepancies. Arguably, the file size
10394          * can be over-estimated without destroying integrity when the file
10395          * moves into the indirect blocks (i.e., is large). If we want to
10396          * postpone fsck, we are stuck with this argument.
10397          */
10398         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10399                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10400 }
10401                 
10402 /*
10403  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10404  * Note that any bug fixes made to this routine must be done in the
10405  * version found above.
10406  *
10407  * Called from within the procedure above to deal with unsatisfied
10408  * allocation dependencies in an inodeblock. The buffer must be
10409  * locked, thus, no I/O completion operations can occur while we
10410  * are manipulating its associated dependencies.
10411  */
10412 static void 
10413 initiate_write_inodeblock_ufs2(inodedep, bp)
10414         struct inodedep *inodedep;
10415         struct buf *bp;                 /* The inode block */
10416 {
10417         struct allocdirect *adp, *lastadp;
10418         struct ufs2_dinode *dp;
10419         struct ufs2_dinode *sip;
10420         struct inoref *inoref;
10421         struct ufsmount *ump;
10422         struct fs *fs;
10423         ufs_lbn_t i;
10424 #ifdef INVARIANTS
10425         ufs_lbn_t prevlbn = 0;
10426 #endif
10427         int deplist;
10428
10429         if (inodedep->id_state & IOSTARTED)
10430                 panic("initiate_write_inodeblock_ufs2: already started");
10431         inodedep->id_state |= IOSTARTED;
10432         fs = inodedep->id_fs;
10433         ump = VFSTOUFS(inodedep->id_list.wk_mp);
10434         LOCK_OWNED(ump);
10435         dp = (struct ufs2_dinode *)bp->b_data +
10436             ino_to_fsbo(fs, inodedep->id_ino);
10437
10438         /*
10439          * If we're on the unlinked list but have not yet written our
10440          * next pointer initialize it here.
10441          */
10442         if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10443                 struct inodedep *inon;
10444
10445                 inon = TAILQ_NEXT(inodedep, id_unlinked);
10446                 dp->di_freelink = inon ? inon->id_ino : 0;
10447                 ffs_update_dinode_ckhash(fs, dp);
10448         }
10449         /*
10450          * If the bitmap is not yet written, then the allocated
10451          * inode cannot be written to disk.
10452          */
10453         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10454                 if (inodedep->id_savedino2 != NULL)
10455                         panic("initiate_write_inodeblock_ufs2: I/O underway");
10456                 FREE_LOCK(ump);
10457                 sip = malloc(sizeof(struct ufs2_dinode),
10458                     M_SAVEDINO, M_SOFTDEP_FLAGS);
10459                 ACQUIRE_LOCK(ump);
10460                 inodedep->id_savedino2 = sip;
10461                 *inodedep->id_savedino2 = *dp;
10462                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10463                 dp->di_gen = inodedep->id_savedino2->di_gen;
10464                 dp->di_freelink = inodedep->id_savedino2->di_freelink;
10465                 return;
10466         }
10467         /*
10468          * If no dependencies, then there is nothing to roll back.
10469          */
10470         inodedep->id_savedsize = dp->di_size;
10471         inodedep->id_savedextsize = dp->di_extsize;
10472         inodedep->id_savednlink = dp->di_nlink;
10473         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10474             TAILQ_EMPTY(&inodedep->id_extupdt) &&
10475             TAILQ_EMPTY(&inodedep->id_inoreflst))
10476                 return;
10477         /*
10478          * Revert the link count to that of the first unwritten journal entry.
10479          */
10480         inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10481         if (inoref)
10482                 dp->di_nlink = inoref->if_nlink;
10483
10484         /*
10485          * Set the ext data dependencies to busy.
10486          */
10487         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10488              adp = TAILQ_NEXT(adp, ad_next)) {
10489 #ifdef INVARIANTS
10490                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10491                         panic("initiate_write_inodeblock_ufs2: lbn order");
10492                 prevlbn = adp->ad_offset;
10493                 if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10494                         panic("initiate_write_inodeblock_ufs2: "
10495                             "ext pointer #%jd mismatch %jd != %jd",
10496                             (intmax_t)adp->ad_offset,
10497                             (intmax_t)dp->di_extb[adp->ad_offset],
10498                             (intmax_t)adp->ad_newblkno);
10499                 deplist |= 1 << adp->ad_offset;
10500                 if ((adp->ad_state & ATTACHED) == 0)
10501                         panic("initiate_write_inodeblock_ufs2: Unknown "
10502                             "state 0x%x", adp->ad_state);
10503 #endif /* INVARIANTS */
10504                 adp->ad_state &= ~ATTACHED;
10505                 adp->ad_state |= UNDONE;
10506         }
10507         /*
10508          * The on-disk inode cannot claim to be any larger than the last
10509          * fragment that has been written. Otherwise, the on-disk inode
10510          * might have fragments that were not the last block in the ext
10511          * data which would corrupt the filesystem.
10512          */
10513         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10514              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10515                 dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10516                 /* keep going until hitting a rollback to a frag */
10517                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10518                         continue;
10519                 dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10520                 for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10521 #ifdef INVARIANTS
10522                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10523                                 panic("initiate_write_inodeblock_ufs2: "
10524                                     "lost dep1");
10525 #endif /* INVARIANTS */
10526                         dp->di_extb[i] = 0;
10527                 }
10528                 lastadp = NULL;
10529                 break;
10530         }
10531         /*
10532          * If we have zero'ed out the last allocated block of the ext
10533          * data, roll back the size to the last currently allocated block.
10534          * We know that this last allocated block is a full-sized as
10535          * we already checked for fragments in the loop above.
10536          */
10537         if (lastadp != NULL &&
10538             dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10539                 for (i = lastadp->ad_offset; i >= 0; i--)
10540                         if (dp->di_extb[i] != 0)
10541                                 break;
10542                 dp->di_extsize = (i + 1) * fs->fs_bsize;
10543         }
10544         /*
10545          * Set the file data dependencies to busy.
10546          */
10547         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10548              adp = TAILQ_NEXT(adp, ad_next)) {
10549 #ifdef INVARIANTS
10550                 if (deplist != 0 && prevlbn >= adp->ad_offset)
10551                         panic("softdep_write_inodeblock: lbn order");
10552                 if ((adp->ad_state & ATTACHED) == 0)
10553                         panic("inodedep %p and adp %p not attached", inodedep, adp);
10554                 prevlbn = adp->ad_offset;
10555                 if (adp->ad_offset < UFS_NDADDR &&
10556                     dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10557                         panic("initiate_write_inodeblock_ufs2: "
10558                             "direct pointer #%jd mismatch %jd != %jd",
10559                             (intmax_t)adp->ad_offset,
10560                             (intmax_t)dp->di_db[adp->ad_offset],
10561                             (intmax_t)adp->ad_newblkno);
10562                 if (adp->ad_offset >= UFS_NDADDR &&
10563                     dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10564                         panic("initiate_write_inodeblock_ufs2: "
10565                             "indirect pointer #%jd mismatch %jd != %jd",
10566                             (intmax_t)adp->ad_offset - UFS_NDADDR,
10567                             (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10568                             (intmax_t)adp->ad_newblkno);
10569                 deplist |= 1 << adp->ad_offset;
10570                 if ((adp->ad_state & ATTACHED) == 0)
10571                         panic("initiate_write_inodeblock_ufs2: Unknown "
10572                              "state 0x%x", adp->ad_state);
10573 #endif /* INVARIANTS */
10574                 adp->ad_state &= ~ATTACHED;
10575                 adp->ad_state |= UNDONE;
10576         }
10577         /*
10578          * The on-disk inode cannot claim to be any larger than the last
10579          * fragment that has been written. Otherwise, the on-disk inode
10580          * might have fragments that were not the last block in the file
10581          * which would corrupt the filesystem.
10582          */
10583         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10584              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10585                 if (adp->ad_offset >= UFS_NDADDR)
10586                         break;
10587                 dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10588                 /* keep going until hitting a rollback to a frag */
10589                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10590                         continue;
10591                 dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10592                 for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10593 #ifdef INVARIANTS
10594                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10595                                 panic("initiate_write_inodeblock_ufs2: "
10596                                     "lost dep2");
10597 #endif /* INVARIANTS */
10598                         dp->di_db[i] = 0;
10599                 }
10600                 for (i = 0; i < UFS_NIADDR; i++) {
10601 #ifdef INVARIANTS
10602                         if (dp->di_ib[i] != 0 &&
10603                             (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10604                                 panic("initiate_write_inodeblock_ufs2: "
10605                                     "lost dep3");
10606 #endif /* INVARIANTS */
10607                         dp->di_ib[i] = 0;
10608                 }
10609                 ffs_update_dinode_ckhash(fs, dp);
10610                 return;
10611         }
10612         /*
10613          * If we have zero'ed out the last allocated block of the file,
10614          * roll back the size to the last currently allocated block.
10615          * We know that this last allocated block is a full-sized as
10616          * we already checked for fragments in the loop above.
10617          */
10618         if (lastadp != NULL &&
10619             dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10620                 for (i = lastadp->ad_offset; i >= 0; i--)
10621                         if (dp->di_db[i] != 0)
10622                                 break;
10623                 dp->di_size = (i + 1) * fs->fs_bsize;
10624         }
10625         /*
10626          * The only dependencies are for indirect blocks.
10627          *
10628          * The file size for indirect block additions is not guaranteed.
10629          * Such a guarantee would be non-trivial to achieve. The conventional
10630          * synchronous write implementation also does not make this guarantee.
10631          * Fsck should catch and fix discrepancies. Arguably, the file size
10632          * can be over-estimated without destroying integrity when the file
10633          * moves into the indirect blocks (i.e., is large). If we want to
10634          * postpone fsck, we are stuck with this argument.
10635          */
10636         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10637                 dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10638         ffs_update_dinode_ckhash(fs, dp);
10639 }
10640
10641 /*
10642  * Cancel an indirdep as a result of truncation.  Release all of the
10643  * children allocindirs and place their journal work on the appropriate
10644  * list.
10645  */
10646 static void
10647 cancel_indirdep(indirdep, bp, freeblks)
10648         struct indirdep *indirdep;
10649         struct buf *bp;
10650         struct freeblks *freeblks;
10651 {
10652         struct allocindir *aip;
10653
10654         /*
10655          * None of the indirect pointers will ever be visible,
10656          * so they can simply be tossed. GOINGAWAY ensures
10657          * that allocated pointers will be saved in the buffer
10658          * cache until they are freed. Note that they will
10659          * only be able to be found by their physical address
10660          * since the inode mapping the logical address will
10661          * be gone. The save buffer used for the safe copy
10662          * was allocated in setup_allocindir_phase2 using
10663          * the physical address so it could be used for this
10664          * purpose. Hence we swap the safe copy with the real
10665          * copy, allowing the safe copy to be freed and holding
10666          * on to the real copy for later use in indir_trunc.
10667          */
10668         if (indirdep->ir_state & GOINGAWAY)
10669                 panic("cancel_indirdep: already gone");
10670         if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10671                 indirdep->ir_state |= DEPCOMPLETE;
10672                 LIST_REMOVE(indirdep, ir_next);
10673         }
10674         indirdep->ir_state |= GOINGAWAY;
10675         /*
10676          * Pass in bp for blocks still have journal writes
10677          * pending so we can cancel them on their own.
10678          */
10679         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
10680                 cancel_allocindir(aip, bp, freeblks, 0);
10681         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
10682                 cancel_allocindir(aip, NULL, freeblks, 0);
10683         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
10684                 cancel_allocindir(aip, NULL, freeblks, 0);
10685         while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
10686                 cancel_allocindir(aip, NULL, freeblks, 0);
10687         /*
10688          * If there are pending partial truncations we need to keep the
10689          * old block copy around until they complete.  This is because
10690          * the current b_data is not a perfect superset of the available
10691          * blocks.
10692          */
10693         if (TAILQ_EMPTY(&indirdep->ir_trunc))
10694                 bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10695         else
10696                 bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10697         WORKLIST_REMOVE(&indirdep->ir_list);
10698         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10699         indirdep->ir_bp = NULL;
10700         indirdep->ir_freeblks = freeblks;
10701 }
10702
10703 /*
10704  * Free an indirdep once it no longer has new pointers to track.
10705  */
10706 static void
10707 free_indirdep(indirdep)
10708         struct indirdep *indirdep;
10709 {
10710
10711         KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10712             ("free_indirdep: Indir trunc list not empty."));
10713         KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10714             ("free_indirdep: Complete head not empty."));
10715         KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10716             ("free_indirdep: write head not empty."));
10717         KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10718             ("free_indirdep: done head not empty."));
10719         KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10720             ("free_indirdep: deplist head not empty."));
10721         KASSERT((indirdep->ir_state & DEPCOMPLETE),
10722             ("free_indirdep: %p still on newblk list.", indirdep));
10723         KASSERT(indirdep->ir_saveddata == NULL,
10724             ("free_indirdep: %p still has saved data.", indirdep));
10725         if (indirdep->ir_state & ONWORKLIST)
10726                 WORKLIST_REMOVE(&indirdep->ir_list);
10727         WORKITEM_FREE(indirdep, D_INDIRDEP);
10728 }
10729
10730 /*
10731  * Called before a write to an indirdep.  This routine is responsible for
10732  * rolling back pointers to a safe state which includes only those
10733  * allocindirs which have been completed.
10734  */
10735 static void
10736 initiate_write_indirdep(indirdep, bp)
10737         struct indirdep *indirdep;
10738         struct buf *bp;
10739 {
10740         struct ufsmount *ump;
10741
10742         indirdep->ir_state |= IOSTARTED;
10743         if (indirdep->ir_state & GOINGAWAY)
10744                 panic("disk_io_initiation: indirdep gone");
10745         /*
10746          * If there are no remaining dependencies, this will be writing
10747          * the real pointers.
10748          */
10749         if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10750             TAILQ_EMPTY(&indirdep->ir_trunc))
10751                 return;
10752         /*
10753          * Replace up-to-date version with safe version.
10754          */
10755         if (indirdep->ir_saveddata == NULL) {
10756                 ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10757                 LOCK_OWNED(ump);
10758                 FREE_LOCK(ump);
10759                 indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10760                     M_SOFTDEP_FLAGS);
10761                 ACQUIRE_LOCK(ump);
10762         }
10763         indirdep->ir_state &= ~ATTACHED;
10764         indirdep->ir_state |= UNDONE;
10765         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10766         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10767             bp->b_bcount);
10768 }
10769
10770 /*
10771  * Called when an inode has been cleared in a cg bitmap.  This finally
10772  * eliminates any canceled jaddrefs
10773  */
10774 void
10775 softdep_setup_inofree(mp, bp, ino, wkhd)
10776         struct mount *mp;
10777         struct buf *bp;
10778         ino_t ino;
10779         struct workhead *wkhd;
10780 {
10781         struct worklist *wk, *wkn;
10782         struct inodedep *inodedep;
10783         struct ufsmount *ump;
10784         uint8_t *inosused;
10785         struct cg *cgp;
10786         struct fs *fs;
10787
10788         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10789             ("softdep_setup_inofree called on non-softdep filesystem"));
10790         ump = VFSTOUFS(mp);
10791         ACQUIRE_LOCK(ump);
10792         fs = ump->um_fs;
10793         cgp = (struct cg *)bp->b_data;
10794         inosused = cg_inosused(cgp);
10795         if (isset(inosused, ino % fs->fs_ipg))
10796                 panic("softdep_setup_inofree: inode %ju not freed.",
10797                     (uintmax_t)ino);
10798         if (inodedep_lookup(mp, ino, 0, &inodedep))
10799                 panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10800                     (uintmax_t)ino, inodedep);
10801         if (wkhd) {
10802                 LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10803                         if (wk->wk_type != D_JADDREF)
10804                                 continue;
10805                         WORKLIST_REMOVE(wk);
10806                         /*
10807                          * We can free immediately even if the jaddref
10808                          * isn't attached in a background write as now
10809                          * the bitmaps are reconciled.
10810                          */
10811                         wk->wk_state |= COMPLETE | ATTACHED;
10812                         free_jaddref(WK_JADDREF(wk));
10813                 }
10814                 jwork_move(&bp->b_dep, wkhd);
10815         }
10816         FREE_LOCK(ump);
10817 }
10818
10819 /*
10820  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10821  * map.  Any dependencies waiting for the write to clear are added to the
10822  * buf's list and any jnewblks that are being canceled are discarded
10823  * immediately.
10824  */
10825 void
10826 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10827         struct mount *mp;
10828         struct buf *bp;
10829         ufs2_daddr_t blkno;
10830         int frags;
10831         struct workhead *wkhd;
10832 {
10833         struct bmsafemap *bmsafemap;
10834         struct jnewblk *jnewblk;
10835         struct ufsmount *ump;
10836         struct worklist *wk;
10837         struct fs *fs;
10838 #ifdef INVARIANTS
10839         uint8_t *blksfree;
10840         struct cg *cgp;
10841         ufs2_daddr_t jstart;
10842         ufs2_daddr_t jend;
10843         ufs2_daddr_t end;
10844         long bno;
10845         int i;
10846 #endif
10847
10848         CTR3(KTR_SUJ,
10849             "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10850             blkno, frags, wkhd);
10851
10852         ump = VFSTOUFS(mp);
10853         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10854             ("softdep_setup_blkfree called on non-softdep filesystem"));
10855         ACQUIRE_LOCK(ump);
10856         /* Lookup the bmsafemap so we track when it is dirty. */
10857         fs = ump->um_fs;
10858         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10859         /*
10860          * Detach any jnewblks which have been canceled.  They must linger
10861          * until the bitmap is cleared again by ffs_blkfree() to prevent
10862          * an unjournaled allocation from hitting the disk.
10863          */
10864         if (wkhd) {
10865                 while ((wk = LIST_FIRST(wkhd)) != NULL) {
10866                         CTR2(KTR_SUJ,
10867                             "softdep_setup_blkfree: blkno %jd wk type %d",
10868                             blkno, wk->wk_type);
10869                         WORKLIST_REMOVE(wk);
10870                         if (wk->wk_type != D_JNEWBLK) {
10871                                 WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10872                                 continue;
10873                         }
10874                         jnewblk = WK_JNEWBLK(wk);
10875                         KASSERT(jnewblk->jn_state & GOINGAWAY,
10876                             ("softdep_setup_blkfree: jnewblk not canceled."));
10877 #ifdef INVARIANTS
10878                         /*
10879                          * Assert that this block is free in the bitmap
10880                          * before we discard the jnewblk.
10881                          */
10882                         cgp = (struct cg *)bp->b_data;
10883                         blksfree = cg_blksfree(cgp);
10884                         bno = dtogd(fs, jnewblk->jn_blkno);
10885                         for (i = jnewblk->jn_oldfrags;
10886                             i < jnewblk->jn_frags; i++) {
10887                                 if (isset(blksfree, bno + i))
10888                                         continue;
10889                                 panic("softdep_setup_blkfree: not free");
10890                         }
10891 #endif
10892                         /*
10893                          * Even if it's not attached we can free immediately
10894                          * as the new bitmap is correct.
10895                          */
10896                         wk->wk_state |= COMPLETE | ATTACHED;
10897                         free_jnewblk(jnewblk);
10898                 }
10899         }
10900
10901 #ifdef INVARIANTS
10902         /*
10903          * Assert that we are not freeing a block which has an outstanding
10904          * allocation dependency.
10905          */
10906         fs = VFSTOUFS(mp)->um_fs;
10907         bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10908         end = blkno + frags;
10909         LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10910                 /*
10911                  * Don't match against blocks that will be freed when the
10912                  * background write is done.
10913                  */
10914                 if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10915                     (COMPLETE | DEPCOMPLETE))
10916                         continue;
10917                 jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10918                 jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10919                 if ((blkno >= jstart && blkno < jend) ||
10920                     (end > jstart && end <= jend)) {
10921                         printf("state 0x%X %jd - %d %d dep %p\n",
10922                             jnewblk->jn_state, jnewblk->jn_blkno,
10923                             jnewblk->jn_oldfrags, jnewblk->jn_frags,
10924                             jnewblk->jn_dep);
10925                         panic("softdep_setup_blkfree: "
10926                             "%jd-%jd(%d) overlaps with %jd-%jd",
10927                             blkno, end, frags, jstart, jend);
10928                 }
10929         }
10930 #endif
10931         FREE_LOCK(ump);
10932 }
10933
10934 /*
10935  * Revert a block allocation when the journal record that describes it
10936  * is not yet written.
10937  */
10938 static int
10939 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10940         struct jnewblk *jnewblk;
10941         struct fs *fs;
10942         struct cg *cgp;
10943         uint8_t *blksfree;
10944 {
10945         ufs1_daddr_t fragno;
10946         long cgbno, bbase;
10947         int frags, blk;
10948         int i;
10949
10950         frags = 0;
10951         cgbno = dtogd(fs, jnewblk->jn_blkno);
10952         /*
10953          * We have to test which frags need to be rolled back.  We may
10954          * be operating on a stale copy when doing background writes.
10955          */
10956         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10957                 if (isclr(blksfree, cgbno + i))
10958                         frags++;
10959         if (frags == 0)
10960                 return (0);
10961         /*
10962          * This is mostly ffs_blkfree() sans some validation and
10963          * superblock updates.
10964          */
10965         if (frags == fs->fs_frag) {
10966                 fragno = fragstoblks(fs, cgbno);
10967                 ffs_setblock(fs, blksfree, fragno);
10968                 ffs_clusteracct(fs, cgp, fragno, 1);
10969                 cgp->cg_cs.cs_nbfree++;
10970         } else {
10971                 cgbno += jnewblk->jn_oldfrags;
10972                 bbase = cgbno - fragnum(fs, cgbno);
10973                 /* Decrement the old frags.  */
10974                 blk = blkmap(fs, blksfree, bbase);
10975                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10976                 /* Deallocate the fragment */
10977                 for (i = 0; i < frags; i++)
10978                         setbit(blksfree, cgbno + i);
10979                 cgp->cg_cs.cs_nffree += frags;
10980                 /* Add back in counts associated with the new frags */
10981                 blk = blkmap(fs, blksfree, bbase);
10982                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10983                 /* If a complete block has been reassembled, account for it. */
10984                 fragno = fragstoblks(fs, bbase);
10985                 if (ffs_isblock(fs, blksfree, fragno)) {
10986                         cgp->cg_cs.cs_nffree -= fs->fs_frag;
10987                         ffs_clusteracct(fs, cgp, fragno, 1);
10988                         cgp->cg_cs.cs_nbfree++;
10989                 }
10990         }
10991         stat_jnewblk++;
10992         jnewblk->jn_state &= ~ATTACHED;
10993         jnewblk->jn_state |= UNDONE;
10994
10995         return (frags);
10996 }
10997
10998 static void
10999 initiate_write_bmsafemap(bmsafemap, bp)
11000         struct bmsafemap *bmsafemap;
11001         struct buf *bp;                 /* The cg block. */
11002 {
11003         struct jaddref *jaddref;
11004         struct jnewblk *jnewblk;
11005         uint8_t *inosused;
11006         uint8_t *blksfree;
11007         struct cg *cgp;
11008         struct fs *fs;
11009         ino_t ino;
11010
11011         /*
11012          * If this is a background write, we did this at the time that
11013          * the copy was made, so do not need to do it again.
11014          */
11015         if (bmsafemap->sm_state & IOSTARTED)
11016                 return;
11017         bmsafemap->sm_state |= IOSTARTED;
11018         /*
11019          * Clear any inode allocations which are pending journal writes.
11020          */
11021         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11022                 cgp = (struct cg *)bp->b_data;
11023                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11024                 inosused = cg_inosused(cgp);
11025                 LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11026                         ino = jaddref->ja_ino % fs->fs_ipg;
11027                         if (isset(inosused, ino)) {
11028                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
11029                                         cgp->cg_cs.cs_ndir--;
11030                                 cgp->cg_cs.cs_nifree++;
11031                                 clrbit(inosused, ino);
11032                                 jaddref->ja_state &= ~ATTACHED;
11033                                 jaddref->ja_state |= UNDONE;
11034                                 stat_jaddref++;
11035                         } else
11036                                 panic("initiate_write_bmsafemap: inode %ju "
11037                                     "marked free", (uintmax_t)jaddref->ja_ino);
11038                 }
11039         }
11040         /*
11041          * Clear any block allocations which are pending journal writes.
11042          */
11043         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11044                 cgp = (struct cg *)bp->b_data;
11045                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11046                 blksfree = cg_blksfree(cgp);
11047                 LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11048                         if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11049                                 continue;
11050                         panic("initiate_write_bmsafemap: block %jd "
11051                             "marked free", jnewblk->jn_blkno);
11052                 }
11053         }
11054         /*
11055          * Move allocation lists to the written lists so they can be
11056          * cleared once the block write is complete.
11057          */
11058         LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11059             inodedep, id_deps);
11060         LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11061             newblk, nb_deps);
11062         LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11063             wk_list);
11064 }
11065
11066 /*
11067  * This routine is called during the completion interrupt
11068  * service routine for a disk write (from the procedure called
11069  * by the device driver to inform the filesystem caches of
11070  * a request completion).  It should be called early in this
11071  * procedure, before the block is made available to other
11072  * processes or other routines are called.
11073  *
11074  */
11075 static void 
11076 softdep_disk_write_complete(bp)
11077         struct buf *bp;         /* describes the completed disk write */
11078 {
11079         struct worklist *wk;
11080         struct worklist *owk;
11081         struct ufsmount *ump;
11082         struct workhead reattach;
11083         struct freeblks *freeblks;
11084         struct buf *sbp;
11085
11086         ump = softdep_bp_to_mp(bp);
11087         KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11088             ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11089              "with outstanding dependencies for buffer %p", bp));
11090         if (ump == NULL)
11091                 return;
11092         /*
11093          * If an error occurred while doing the write, then the data
11094          * has not hit the disk and the dependencies cannot be processed.
11095          * But we do have to go through and roll forward any dependencies
11096          * that were rolled back before the disk write.
11097          */
11098         sbp = NULL;
11099         ACQUIRE_LOCK(ump);
11100         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11101                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11102                         switch (wk->wk_type) {
11103
11104                         case D_PAGEDEP:
11105                                 handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11106                                 continue;
11107
11108                         case D_INODEDEP:
11109                                 handle_written_inodeblock(WK_INODEDEP(wk),
11110                                     bp, 0);
11111                                 continue;
11112
11113                         case D_BMSAFEMAP:
11114                                 handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11115                                     bp, 0);
11116                                 continue;
11117
11118                         case D_INDIRDEP:
11119                                 handle_written_indirdep(WK_INDIRDEP(wk),
11120                                     bp, &sbp, 0);
11121                                 continue;
11122                         default:
11123                                 /* nothing to roll forward */
11124                                 continue;
11125                         }
11126                 }
11127                 FREE_LOCK(ump);
11128                 if (sbp)
11129                         brelse(sbp);
11130                 return;
11131         }
11132         LIST_INIT(&reattach);
11133
11134         /*
11135          * Ump SU lock must not be released anywhere in this code segment.
11136          */
11137         owk = NULL;
11138         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11139                 WORKLIST_REMOVE(wk);
11140                 atomic_add_long(&dep_write[wk->wk_type], 1);
11141                 if (wk == owk)
11142                         panic("duplicate worklist: %p\n", wk);
11143                 owk = wk;
11144                 switch (wk->wk_type) {
11145
11146                 case D_PAGEDEP:
11147                         if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11148                             WRITESUCCEEDED))
11149                                 WORKLIST_INSERT(&reattach, wk);
11150                         continue;
11151
11152                 case D_INODEDEP:
11153                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11154                             WRITESUCCEEDED))
11155                                 WORKLIST_INSERT(&reattach, wk);
11156                         continue;
11157
11158                 case D_BMSAFEMAP:
11159                         if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11160                             WRITESUCCEEDED))
11161                                 WORKLIST_INSERT(&reattach, wk);
11162                         continue;
11163
11164                 case D_MKDIR:
11165                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11166                         continue;
11167
11168                 case D_ALLOCDIRECT:
11169                         wk->wk_state |= COMPLETE;
11170                         handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11171                         continue;
11172
11173                 case D_ALLOCINDIR:
11174                         wk->wk_state |= COMPLETE;
11175                         handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11176                         continue;
11177
11178                 case D_INDIRDEP:
11179                         if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11180                             WRITESUCCEEDED))
11181                                 WORKLIST_INSERT(&reattach, wk);
11182                         continue;
11183
11184                 case D_FREEBLKS:
11185                         wk->wk_state |= COMPLETE;
11186                         freeblks = WK_FREEBLKS(wk);
11187                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11188                             LIST_EMPTY(&freeblks->fb_jblkdephd))
11189                                 add_to_worklist(wk, WK_NODELAY);
11190                         continue;
11191
11192                 case D_FREEWORK:
11193                         handle_written_freework(WK_FREEWORK(wk));
11194                         break;
11195
11196                 case D_JSEGDEP:
11197                         free_jsegdep(WK_JSEGDEP(wk));
11198                         continue;
11199
11200                 case D_JSEG:
11201                         handle_written_jseg(WK_JSEG(wk), bp);
11202                         continue;
11203
11204                 case D_SBDEP:
11205                         if (handle_written_sbdep(WK_SBDEP(wk), bp))
11206                                 WORKLIST_INSERT(&reattach, wk);
11207                         continue;
11208
11209                 case D_FREEDEP:
11210                         free_freedep(WK_FREEDEP(wk));
11211                         continue;
11212
11213                 default:
11214                         panic("handle_disk_write_complete: Unknown type %s",
11215                             TYPENAME(wk->wk_type));
11216                         /* NOTREACHED */
11217                 }
11218         }
11219         /*
11220          * Reattach any requests that must be redone.
11221          */
11222         while ((wk = LIST_FIRST(&reattach)) != NULL) {
11223                 WORKLIST_REMOVE(wk);
11224                 WORKLIST_INSERT(&bp->b_dep, wk);
11225         }
11226         FREE_LOCK(ump);
11227         if (sbp)
11228                 brelse(sbp);
11229 }
11230
11231 /*
11232  * Called from within softdep_disk_write_complete above.
11233  */
11234 static void 
11235 handle_allocdirect_partdone(adp, wkhd)
11236         struct allocdirect *adp;        /* the completed allocdirect */
11237         struct workhead *wkhd;          /* Work to do when inode is writtne. */
11238 {
11239         struct allocdirectlst *listhead;
11240         struct allocdirect *listadp;
11241         struct inodedep *inodedep;
11242         long bsize;
11243
11244         LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11245         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11246                 return;
11247         /*
11248          * The on-disk inode cannot claim to be any larger than the last
11249          * fragment that has been written. Otherwise, the on-disk inode
11250          * might have fragments that were not the last block in the file
11251          * which would corrupt the filesystem. Thus, we cannot free any
11252          * allocdirects after one whose ad_oldblkno claims a fragment as
11253          * these blocks must be rolled back to zero before writing the inode.
11254          * We check the currently active set of allocdirects in id_inoupdt
11255          * or id_extupdt as appropriate.
11256          */
11257         inodedep = adp->ad_inodedep;
11258         bsize = inodedep->id_fs->fs_bsize;
11259         if (adp->ad_state & EXTDATA)
11260                 listhead = &inodedep->id_extupdt;
11261         else
11262                 listhead = &inodedep->id_inoupdt;
11263         TAILQ_FOREACH(listadp, listhead, ad_next) {
11264                 /* found our block */
11265                 if (listadp == adp)
11266                         break;
11267                 /* continue if ad_oldlbn is not a fragment */
11268                 if (listadp->ad_oldsize == 0 ||
11269                     listadp->ad_oldsize == bsize)
11270                         continue;
11271                 /* hit a fragment */
11272                 return;
11273         }
11274         /*
11275          * If we have reached the end of the current list without
11276          * finding the just finished dependency, then it must be
11277          * on the future dependency list. Future dependencies cannot
11278          * be freed until they are moved to the current list.
11279          */
11280         if (listadp == NULL) {
11281 #ifdef INVARIANTS
11282                 if (adp->ad_state & EXTDATA)
11283                         listhead = &inodedep->id_newextupdt;
11284                 else
11285                         listhead = &inodedep->id_newinoupdt;
11286                 TAILQ_FOREACH(listadp, listhead, ad_next)
11287                         /* found our block */
11288                         if (listadp == adp)
11289                                 break;
11290                 if (listadp == NULL)
11291                         panic("handle_allocdirect_partdone: lost dep");
11292 #endif /* INVARIANTS */
11293                 return;
11294         }
11295         /*
11296          * If we have found the just finished dependency, then queue
11297          * it along with anything that follows it that is complete.
11298          * Since the pointer has not yet been written in the inode
11299          * as the dependency prevents it, place the allocdirect on the
11300          * bufwait list where it will be freed once the pointer is
11301          * valid.
11302          */
11303         if (wkhd == NULL)
11304                 wkhd = &inodedep->id_bufwait;
11305         for (; adp; adp = listadp) {
11306                 listadp = TAILQ_NEXT(adp, ad_next);
11307                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11308                         return;
11309                 TAILQ_REMOVE(listhead, adp, ad_next);
11310                 WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11311         }
11312 }
11313
11314 /*
11315  * Called from within softdep_disk_write_complete above.  This routine
11316  * completes successfully written allocindirs.
11317  */
11318 static void
11319 handle_allocindir_partdone(aip)
11320         struct allocindir *aip;         /* the completed allocindir */
11321 {
11322         struct indirdep *indirdep;
11323
11324         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11325                 return;
11326         indirdep = aip->ai_indirdep;
11327         LIST_REMOVE(aip, ai_next);
11328         /*
11329          * Don't set a pointer while the buffer is undergoing IO or while
11330          * we have active truncations.
11331          */
11332         if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11333                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11334                 return;
11335         }
11336         if (indirdep->ir_state & UFS1FMT)
11337                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11338                     aip->ai_newblkno;
11339         else
11340                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11341                     aip->ai_newblkno;
11342         /*
11343          * Await the pointer write before freeing the allocindir.
11344          */
11345         LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11346 }
11347
11348 /*
11349  * Release segments held on a jwork list.
11350  */
11351 static void
11352 handle_jwork(wkhd)
11353         struct workhead *wkhd;
11354 {
11355         struct worklist *wk;
11356
11357         while ((wk = LIST_FIRST(wkhd)) != NULL) {
11358                 WORKLIST_REMOVE(wk);
11359                 switch (wk->wk_type) {
11360                 case D_JSEGDEP:
11361                         free_jsegdep(WK_JSEGDEP(wk));
11362                         continue;
11363                 case D_FREEDEP:
11364                         free_freedep(WK_FREEDEP(wk));
11365                         continue;
11366                 case D_FREEFRAG:
11367                         rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11368                         WORKITEM_FREE(wk, D_FREEFRAG);
11369                         continue;
11370                 case D_FREEWORK:
11371                         handle_written_freework(WK_FREEWORK(wk));
11372                         continue;
11373                 default:
11374                         panic("handle_jwork: Unknown type %s\n",
11375                             TYPENAME(wk->wk_type));
11376                 }
11377         }
11378 }
11379
11380 /*
11381  * Handle the bufwait list on an inode when it is safe to release items
11382  * held there.  This normally happens after an inode block is written but
11383  * may be delayed and handled later if there are pending journal items that
11384  * are not yet safe to be released.
11385  */
11386 static struct freefile *
11387 handle_bufwait(inodedep, refhd)
11388         struct inodedep *inodedep;
11389         struct workhead *refhd;
11390 {
11391         struct jaddref *jaddref;
11392         struct freefile *freefile;
11393         struct worklist *wk;
11394
11395         freefile = NULL;
11396         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11397                 WORKLIST_REMOVE(wk);
11398                 switch (wk->wk_type) {
11399                 case D_FREEFILE:
11400                         /*
11401                          * We defer adding freefile to the worklist
11402                          * until all other additions have been made to
11403                          * ensure that it will be done after all the
11404                          * old blocks have been freed.
11405                          */
11406                         if (freefile != NULL)
11407                                 panic("handle_bufwait: freefile");
11408                         freefile = WK_FREEFILE(wk);
11409                         continue;
11410
11411                 case D_MKDIR:
11412                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11413                         continue;
11414
11415                 case D_DIRADD:
11416                         diradd_inode_written(WK_DIRADD(wk), inodedep);
11417                         continue;
11418
11419                 case D_FREEFRAG:
11420                         wk->wk_state |= COMPLETE;
11421                         if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11422                                 add_to_worklist(wk, 0);
11423                         continue;
11424
11425                 case D_DIRREM:
11426                         wk->wk_state |= COMPLETE;
11427                         add_to_worklist(wk, 0);
11428                         continue;
11429
11430                 case D_ALLOCDIRECT:
11431                 case D_ALLOCINDIR:
11432                         free_newblk(WK_NEWBLK(wk));
11433                         continue;
11434
11435                 case D_JNEWBLK:
11436                         wk->wk_state |= COMPLETE;
11437                         free_jnewblk(WK_JNEWBLK(wk));
11438                         continue;
11439
11440                 /*
11441                  * Save freed journal segments and add references on
11442                  * the supplied list which will delay their release
11443                  * until the cg bitmap is cleared on disk.
11444                  */
11445                 case D_JSEGDEP:
11446                         if (refhd == NULL)
11447                                 free_jsegdep(WK_JSEGDEP(wk));
11448                         else
11449                                 WORKLIST_INSERT(refhd, wk);
11450                         continue;
11451
11452                 case D_JADDREF:
11453                         jaddref = WK_JADDREF(wk);
11454                         TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11455                             if_deps);
11456                         /*
11457                          * Transfer any jaddrefs to the list to be freed with
11458                          * the bitmap if we're handling a removed file.
11459                          */
11460                         if (refhd == NULL) {
11461                                 wk->wk_state |= COMPLETE;
11462                                 free_jaddref(jaddref);
11463                         } else
11464                                 WORKLIST_INSERT(refhd, wk);
11465                         continue;
11466
11467                 default:
11468                         panic("handle_bufwait: Unknown type %p(%s)",
11469                             wk, TYPENAME(wk->wk_type));
11470                         /* NOTREACHED */
11471                 }
11472         }
11473         return (freefile);
11474 }
11475 /*
11476  * Called from within softdep_disk_write_complete above to restore
11477  * in-memory inode block contents to their most up-to-date state. Note
11478  * that this routine is always called from interrupt level with further
11479  * interrupts from this device blocked.
11480  *
11481  * If the write did not succeed, we will do all the roll-forward
11482  * operations, but we will not take the actions that will allow its
11483  * dependencies to be processed.
11484  */
11485 static int 
11486 handle_written_inodeblock(inodedep, bp, flags)
11487         struct inodedep *inodedep;
11488         struct buf *bp;         /* buffer containing the inode block */
11489         int flags;
11490 {
11491         struct freefile *freefile;
11492         struct allocdirect *adp, *nextadp;
11493         struct ufs1_dinode *dp1 = NULL;
11494         struct ufs2_dinode *dp2 = NULL;
11495         struct workhead wkhd;
11496         int hadchanges, fstype;
11497         ino_t freelink;
11498
11499         LIST_INIT(&wkhd);
11500         hadchanges = 0;
11501         freefile = NULL;
11502         if ((inodedep->id_state & IOSTARTED) == 0)
11503                 panic("handle_written_inodeblock: not started");
11504         inodedep->id_state &= ~IOSTARTED;
11505         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11506                 fstype = UFS1;
11507                 dp1 = (struct ufs1_dinode *)bp->b_data +
11508                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11509                 freelink = dp1->di_freelink;
11510         } else {
11511                 fstype = UFS2;
11512                 dp2 = (struct ufs2_dinode *)bp->b_data +
11513                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11514                 freelink = dp2->di_freelink;
11515         }
11516         /*
11517          * Leave this inodeblock dirty until it's in the list.
11518          */
11519         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11520             (flags & WRITESUCCEEDED)) {
11521                 struct inodedep *inon;
11522
11523                 inon = TAILQ_NEXT(inodedep, id_unlinked);
11524                 if ((inon == NULL && freelink == 0) ||
11525                     (inon && inon->id_ino == freelink)) {
11526                         if (inon)
11527                                 inon->id_state |= UNLINKPREV;
11528                         inodedep->id_state |= UNLINKNEXT;
11529                 }
11530                 hadchanges = 1;
11531         }
11532         /*
11533          * If we had to rollback the inode allocation because of
11534          * bitmaps being incomplete, then simply restore it.
11535          * Keep the block dirty so that it will not be reclaimed until
11536          * all associated dependencies have been cleared and the
11537          * corresponding updates written to disk.
11538          */
11539         if (inodedep->id_savedino1 != NULL) {
11540                 hadchanges = 1;
11541                 if (fstype == UFS1)
11542                         *dp1 = *inodedep->id_savedino1;
11543                 else
11544                         *dp2 = *inodedep->id_savedino2;
11545                 free(inodedep->id_savedino1, M_SAVEDINO);
11546                 inodedep->id_savedino1 = NULL;
11547                 if ((bp->b_flags & B_DELWRI) == 0)
11548                         stat_inode_bitmap++;
11549                 bdirty(bp);
11550                 /*
11551                  * If the inode is clear here and GOINGAWAY it will never
11552                  * be written.  Process the bufwait and clear any pending
11553                  * work which may include the freefile.
11554                  */
11555                 if (inodedep->id_state & GOINGAWAY)
11556                         goto bufwait;
11557                 return (1);
11558         }
11559         if (flags & WRITESUCCEEDED)
11560                 inodedep->id_state |= COMPLETE;
11561         /*
11562          * Roll forward anything that had to be rolled back before 
11563          * the inode could be updated.
11564          */
11565         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11566                 nextadp = TAILQ_NEXT(adp, ad_next);
11567                 if (adp->ad_state & ATTACHED)
11568                         panic("handle_written_inodeblock: new entry");
11569                 if (fstype == UFS1) {
11570                         if (adp->ad_offset < UFS_NDADDR) {
11571                                 if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11572                                         panic("%s %s #%jd mismatch %d != %jd",
11573                                             "handle_written_inodeblock:",
11574                                             "direct pointer",
11575                                             (intmax_t)adp->ad_offset,
11576                                             dp1->di_db[adp->ad_offset],
11577                                             (intmax_t)adp->ad_oldblkno);
11578                                 dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11579                         } else {
11580                                 if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11581                                     0)
11582                                         panic("%s: %s #%jd allocated as %d",
11583                                             "handle_written_inodeblock",
11584                                             "indirect pointer",
11585                                             (intmax_t)adp->ad_offset -
11586                                             UFS_NDADDR,
11587                                             dp1->di_ib[adp->ad_offset -
11588                                             UFS_NDADDR]);
11589                                 dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11590                                     adp->ad_newblkno;
11591                         }
11592                 } else {
11593                         if (adp->ad_offset < UFS_NDADDR) {
11594                                 if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11595                                         panic("%s: %s #%jd %s %jd != %jd",
11596                                             "handle_written_inodeblock",
11597                                             "direct pointer",
11598                                             (intmax_t)adp->ad_offset, "mismatch",
11599                                             (intmax_t)dp2->di_db[adp->ad_offset],
11600                                             (intmax_t)adp->ad_oldblkno);
11601                                 dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11602                         } else {
11603                                 if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11604                                     0)
11605                                         panic("%s: %s #%jd allocated as %jd",
11606                                             "handle_written_inodeblock",
11607                                             "indirect pointer",
11608                                             (intmax_t)adp->ad_offset -
11609                                             UFS_NDADDR,
11610                                             (intmax_t)
11611                                             dp2->di_ib[adp->ad_offset -
11612                                             UFS_NDADDR]);
11613                                 dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11614                                     adp->ad_newblkno;
11615                         }
11616                 }
11617                 adp->ad_state &= ~UNDONE;
11618                 adp->ad_state |= ATTACHED;
11619                 hadchanges = 1;
11620         }
11621         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11622                 nextadp = TAILQ_NEXT(adp, ad_next);
11623                 if (adp->ad_state & ATTACHED)
11624                         panic("handle_written_inodeblock: new entry");
11625                 if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11626                         panic("%s: direct pointers #%jd %s %jd != %jd",
11627                             "handle_written_inodeblock",
11628                             (intmax_t)adp->ad_offset, "mismatch",
11629                             (intmax_t)dp2->di_extb[adp->ad_offset],
11630                             (intmax_t)adp->ad_oldblkno);
11631                 dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11632                 adp->ad_state &= ~UNDONE;
11633                 adp->ad_state |= ATTACHED;
11634                 hadchanges = 1;
11635         }
11636         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11637                 stat_direct_blk_ptrs++;
11638         /*
11639          * Reset the file size to its most up-to-date value.
11640          */
11641         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11642                 panic("handle_written_inodeblock: bad size");
11643         if (inodedep->id_savednlink > UFS_LINK_MAX)
11644                 panic("handle_written_inodeblock: Invalid link count "
11645                     "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
11646                     inodedep);
11647         if (fstype == UFS1) {
11648                 if (dp1->di_nlink != inodedep->id_savednlink) { 
11649                         dp1->di_nlink = inodedep->id_savednlink;
11650                         hadchanges = 1;
11651                 }
11652                 if (dp1->di_size != inodedep->id_savedsize) {
11653                         dp1->di_size = inodedep->id_savedsize;
11654                         hadchanges = 1;
11655                 }
11656         } else {
11657                 if (dp2->di_nlink != inodedep->id_savednlink) { 
11658                         dp2->di_nlink = inodedep->id_savednlink;
11659                         hadchanges = 1;
11660                 }
11661                 if (dp2->di_size != inodedep->id_savedsize) {
11662                         dp2->di_size = inodedep->id_savedsize;
11663                         hadchanges = 1;
11664                 }
11665                 if (dp2->di_extsize != inodedep->id_savedextsize) {
11666                         dp2->di_extsize = inodedep->id_savedextsize;
11667                         hadchanges = 1;
11668                 }
11669         }
11670         inodedep->id_savedsize = -1;
11671         inodedep->id_savedextsize = -1;
11672         inodedep->id_savednlink = -1;
11673         /*
11674          * If there were any rollbacks in the inode block, then it must be
11675          * marked dirty so that its will eventually get written back in
11676          * its correct form.
11677          */
11678         if (hadchanges) {
11679                 if (fstype == UFS2)
11680                         ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
11681                 bdirty(bp);
11682         }
11683 bufwait:
11684         /*
11685          * If the write did not succeed, we have done all the roll-forward
11686          * operations, but we cannot take the actions that will allow its
11687          * dependencies to be processed.
11688          */
11689         if ((flags & WRITESUCCEEDED) == 0)
11690                 return (hadchanges);
11691         /*
11692          * Process any allocdirects that completed during the update.
11693          */
11694         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11695                 handle_allocdirect_partdone(adp, &wkhd);
11696         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11697                 handle_allocdirect_partdone(adp, &wkhd);
11698         /*
11699          * Process deallocations that were held pending until the
11700          * inode had been written to disk. Freeing of the inode
11701          * is delayed until after all blocks have been freed to
11702          * avoid creation of new <vfsid, inum, lbn> triples
11703          * before the old ones have been deleted.  Completely
11704          * unlinked inodes are not processed until the unlinked
11705          * inode list is written or the last reference is removed.
11706          */
11707         if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11708                 freefile = handle_bufwait(inodedep, NULL);
11709                 if (freefile && !LIST_EMPTY(&wkhd)) {
11710                         WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11711                         freefile = NULL;
11712                 }
11713         }
11714         /*
11715          * Move rolled forward dependency completions to the bufwait list
11716          * now that those that were already written have been processed.
11717          */
11718         if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11719                 panic("handle_written_inodeblock: bufwait but no changes");
11720         jwork_move(&inodedep->id_bufwait, &wkhd);
11721
11722         if (freefile != NULL) {
11723                 /*
11724                  * If the inode is goingaway it was never written.  Fake up
11725                  * the state here so free_inodedep() can succeed.
11726                  */
11727                 if (inodedep->id_state & GOINGAWAY)
11728                         inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11729                 if (free_inodedep(inodedep) == 0)
11730                         panic("handle_written_inodeblock: live inodedep %p",
11731                             inodedep);
11732                 add_to_worklist(&freefile->fx_list, 0);
11733                 return (0);
11734         }
11735
11736         /*
11737          * If no outstanding dependencies, free it.
11738          */
11739         if (free_inodedep(inodedep) ||
11740             (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11741              TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11742              TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11743              LIST_FIRST(&inodedep->id_bufwait) == 0))
11744                 return (0);
11745         return (hadchanges);
11746 }
11747
11748 /*
11749  * Perform needed roll-forwards and kick off any dependencies that
11750  * can now be processed.
11751  *
11752  * If the write did not succeed, we will do all the roll-forward
11753  * operations, but we will not take the actions that will allow its
11754  * dependencies to be processed.
11755  */
11756 static int
11757 handle_written_indirdep(indirdep, bp, bpp, flags)
11758         struct indirdep *indirdep;
11759         struct buf *bp;
11760         struct buf **bpp;
11761         int flags;
11762 {
11763         struct allocindir *aip;
11764         struct buf *sbp;
11765         int chgs;
11766
11767         if (indirdep->ir_state & GOINGAWAY)
11768                 panic("handle_written_indirdep: indirdep gone");
11769         if ((indirdep->ir_state & IOSTARTED) == 0)
11770                 panic("handle_written_indirdep: IO not started");
11771         chgs = 0;
11772         /*
11773          * If there were rollbacks revert them here.
11774          */
11775         if (indirdep->ir_saveddata) {
11776                 bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11777                 if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11778                         free(indirdep->ir_saveddata, M_INDIRDEP);
11779                         indirdep->ir_saveddata = NULL;
11780                 }
11781                 chgs = 1;
11782         }
11783         indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11784         indirdep->ir_state |= ATTACHED;
11785         /*
11786          * If the write did not succeed, we have done all the roll-forward
11787          * operations, but we cannot take the actions that will allow its
11788          * dependencies to be processed.
11789          */
11790         if ((flags & WRITESUCCEEDED) == 0) {
11791                 stat_indir_blk_ptrs++;
11792                 bdirty(bp);
11793                 return (1);
11794         }
11795         /*
11796          * Move allocindirs with written pointers to the completehd if
11797          * the indirdep's pointer is not yet written.  Otherwise
11798          * free them here.
11799          */
11800         while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
11801                 LIST_REMOVE(aip, ai_next);
11802                 if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11803                         LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11804                             ai_next);
11805                         newblk_freefrag(&aip->ai_block);
11806                         continue;
11807                 }
11808                 free_newblk(&aip->ai_block);
11809         }
11810         /*
11811          * Move allocindirs that have finished dependency processing from
11812          * the done list to the write list after updating the pointers.
11813          */
11814         if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11815                 while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
11816                         handle_allocindir_partdone(aip);
11817                         if (aip == LIST_FIRST(&indirdep->ir_donehd))
11818                                 panic("disk_write_complete: not gone");
11819                         chgs = 1;
11820                 }
11821         }
11822         /*
11823          * Preserve the indirdep if there were any changes or if it is not
11824          * yet valid on disk.
11825          */
11826         if (chgs) {
11827                 stat_indir_blk_ptrs++;
11828                 bdirty(bp);
11829                 return (1);
11830         }
11831         /*
11832          * If there were no changes we can discard the savedbp and detach
11833          * ourselves from the buf.  We are only carrying completed pointers
11834          * in this case.
11835          */
11836         sbp = indirdep->ir_savebp;
11837         sbp->b_flags |= B_INVAL | B_NOCACHE;
11838         indirdep->ir_savebp = NULL;
11839         indirdep->ir_bp = NULL;
11840         if (*bpp != NULL)
11841                 panic("handle_written_indirdep: bp already exists.");
11842         *bpp = sbp;
11843         /*
11844          * The indirdep may not be freed until its parent points at it.
11845          */
11846         if (indirdep->ir_state & DEPCOMPLETE)
11847                 free_indirdep(indirdep);
11848
11849         return (0);
11850 }
11851
11852 /*
11853  * Process a diradd entry after its dependent inode has been written.
11854  */
11855 static void
11856 diradd_inode_written(dap, inodedep)
11857         struct diradd *dap;
11858         struct inodedep *inodedep;
11859 {
11860
11861         LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
11862         dap->da_state |= COMPLETE;
11863         complete_diradd(dap);
11864         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11865 }
11866
11867 /*
11868  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11869  * be called with the per-filesystem lock and the buf lock on the cg held.
11870  */
11871 static int
11872 bmsafemap_backgroundwrite(bmsafemap, bp)
11873         struct bmsafemap *bmsafemap;
11874         struct buf *bp;
11875 {
11876         int dirty;
11877
11878         LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11879         dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) | 
11880             !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11881         /*
11882          * If we're initiating a background write we need to process the
11883          * rollbacks as they exist now, not as they exist when IO starts.
11884          * No other consumers will look at the contents of the shadowed
11885          * buf so this is safe to do here.
11886          */
11887         if (bp->b_xflags & BX_BKGRDMARKER)
11888                 initiate_write_bmsafemap(bmsafemap, bp);
11889
11890         return (dirty);
11891 }
11892
11893 /*
11894  * Re-apply an allocation when a cg write is complete.
11895  */
11896 static int
11897 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11898         struct jnewblk *jnewblk;
11899         struct fs *fs;
11900         struct cg *cgp;
11901         uint8_t *blksfree;
11902 {
11903         ufs1_daddr_t fragno;
11904         ufs2_daddr_t blkno;
11905         long cgbno, bbase;
11906         int frags, blk;
11907         int i;
11908
11909         frags = 0;
11910         cgbno = dtogd(fs, jnewblk->jn_blkno);
11911         for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11912                 if (isclr(blksfree, cgbno + i))
11913                         panic("jnewblk_rollforward: re-allocated fragment");
11914                 frags++;
11915         }
11916         if (frags == fs->fs_frag) {
11917                 blkno = fragstoblks(fs, cgbno);
11918                 ffs_clrblock(fs, blksfree, (long)blkno);
11919                 ffs_clusteracct(fs, cgp, blkno, -1);
11920                 cgp->cg_cs.cs_nbfree--;
11921         } else {
11922                 bbase = cgbno - fragnum(fs, cgbno);
11923                 cgbno += jnewblk->jn_oldfrags;
11924                 /* If a complete block had been reassembled, account for it. */
11925                 fragno = fragstoblks(fs, bbase);
11926                 if (ffs_isblock(fs, blksfree, fragno)) {
11927                         cgp->cg_cs.cs_nffree += fs->fs_frag;
11928                         ffs_clusteracct(fs, cgp, fragno, -1);
11929                         cgp->cg_cs.cs_nbfree--;
11930                 }
11931                 /* Decrement the old frags.  */
11932                 blk = blkmap(fs, blksfree, bbase);
11933                 ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11934                 /* Allocate the fragment */
11935                 for (i = 0; i < frags; i++)
11936                         clrbit(blksfree, cgbno + i);
11937                 cgp->cg_cs.cs_nffree -= frags;
11938                 /* Add back in counts associated with the new frags */
11939                 blk = blkmap(fs, blksfree, bbase);
11940                 ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11941         }
11942         return (frags);
11943 }
11944
11945 /*
11946  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11947  * changes if it's not a background write.  Set all written dependencies 
11948  * to DEPCOMPLETE and free the structure if possible.
11949  *
11950  * If the write did not succeed, we will do all the roll-forward
11951  * operations, but we will not take the actions that will allow its
11952  * dependencies to be processed.
11953  */
11954 static int
11955 handle_written_bmsafemap(bmsafemap, bp, flags)
11956         struct bmsafemap *bmsafemap;
11957         struct buf *bp;
11958         int flags;
11959 {
11960         struct newblk *newblk;
11961         struct inodedep *inodedep;
11962         struct jaddref *jaddref, *jatmp;
11963         struct jnewblk *jnewblk, *jntmp;
11964         struct ufsmount *ump;
11965         uint8_t *inosused;
11966         uint8_t *blksfree;
11967         struct cg *cgp;
11968         struct fs *fs;
11969         ino_t ino;
11970         int foreground;
11971         int chgs;
11972
11973         if ((bmsafemap->sm_state & IOSTARTED) == 0)
11974                 panic("handle_written_bmsafemap: Not started\n");
11975         ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11976         chgs = 0;
11977         bmsafemap->sm_state &= ~IOSTARTED;
11978         foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11979         /*
11980          * If write was successful, release journal work that was waiting
11981          * on the write. Otherwise move the work back.
11982          */
11983         if (flags & WRITESUCCEEDED)
11984                 handle_jwork(&bmsafemap->sm_freewr);
11985         else
11986                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
11987                     worklist, wk_list);
11988
11989         /*
11990          * Restore unwritten inode allocation pending jaddref writes.
11991          */
11992         if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11993                 cgp = (struct cg *)bp->b_data;
11994                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11995                 inosused = cg_inosused(cgp);
11996                 LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11997                     ja_bmdeps, jatmp) {
11998                         if ((jaddref->ja_state & UNDONE) == 0)
11999                                 continue;
12000                         ino = jaddref->ja_ino % fs->fs_ipg;
12001                         if (isset(inosused, ino))
12002                                 panic("handle_written_bmsafemap: "
12003                                     "re-allocated inode");
12004                         /* Do the roll-forward only if it's a real copy. */
12005                         if (foreground) {
12006                                 if ((jaddref->ja_mode & IFMT) == IFDIR)
12007                                         cgp->cg_cs.cs_ndir++;
12008                                 cgp->cg_cs.cs_nifree--;
12009                                 setbit(inosused, ino);
12010                                 chgs = 1;
12011                         }
12012                         jaddref->ja_state &= ~UNDONE;
12013                         jaddref->ja_state |= ATTACHED;
12014                         free_jaddref(jaddref);
12015                 }
12016         }
12017         /*
12018          * Restore any block allocations which are pending journal writes.
12019          */
12020         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12021                 cgp = (struct cg *)bp->b_data;
12022                 fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12023                 blksfree = cg_blksfree(cgp);
12024                 LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12025                     jntmp) {
12026                         if ((jnewblk->jn_state & UNDONE) == 0)
12027                                 continue;
12028                         /* Do the roll-forward only if it's a real copy. */
12029                         if (foreground &&
12030                             jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12031                                 chgs = 1;
12032                         jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12033                         jnewblk->jn_state |= ATTACHED;
12034                         free_jnewblk(jnewblk);
12035                 }
12036         }
12037         /*
12038          * If the write did not succeed, we have done all the roll-forward
12039          * operations, but we cannot take the actions that will allow its
12040          * dependencies to be processed.
12041          */
12042         if ((flags & WRITESUCCEEDED) == 0) {
12043                 LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12044                     newblk, nb_deps);
12045                 LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12046                     worklist, wk_list);
12047                 if (foreground)
12048                         bdirty(bp);
12049                 return (1);
12050         }
12051         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12052                 newblk->nb_state |= DEPCOMPLETE;
12053                 newblk->nb_state &= ~ONDEPLIST;
12054                 newblk->nb_bmsafemap = NULL;
12055                 LIST_REMOVE(newblk, nb_deps);
12056                 if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12057                         handle_allocdirect_partdone(
12058                             WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12059                 else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12060                         handle_allocindir_partdone(
12061                             WK_ALLOCINDIR(&newblk->nb_list));
12062                 else if (newblk->nb_list.wk_type != D_NEWBLK)
12063                         panic("handle_written_bmsafemap: Unexpected type: %s",
12064                             TYPENAME(newblk->nb_list.wk_type));
12065         }
12066         while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12067                 inodedep->id_state |= DEPCOMPLETE;
12068                 inodedep->id_state &= ~ONDEPLIST;
12069                 LIST_REMOVE(inodedep, id_deps);
12070                 inodedep->id_bmsafemap = NULL;
12071         }
12072         LIST_REMOVE(bmsafemap, sm_next);
12073         if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12074             LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12075             LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12076             LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12077             LIST_EMPTY(&bmsafemap->sm_freehd)) {
12078                 LIST_REMOVE(bmsafemap, sm_hash);
12079                 WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12080                 return (0);
12081         }
12082         LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12083         if (foreground)
12084                 bdirty(bp);
12085         return (1);
12086 }
12087
12088 /*
12089  * Try to free a mkdir dependency.
12090  */
12091 static void
12092 complete_mkdir(mkdir)
12093         struct mkdir *mkdir;
12094 {
12095         struct diradd *dap;
12096
12097         if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12098                 return;
12099         LIST_REMOVE(mkdir, md_mkdirs);
12100         dap = mkdir->md_diradd;
12101         dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12102         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12103                 dap->da_state |= DEPCOMPLETE;
12104                 complete_diradd(dap);
12105         }
12106         WORKITEM_FREE(mkdir, D_MKDIR);
12107 }
12108
12109 /*
12110  * Handle the completion of a mkdir dependency.
12111  */
12112 static void
12113 handle_written_mkdir(mkdir, type)
12114         struct mkdir *mkdir;
12115         int type;
12116 {
12117
12118         if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12119                 panic("handle_written_mkdir: bad type");
12120         mkdir->md_state |= COMPLETE;
12121         complete_mkdir(mkdir);
12122 }
12123
12124 static int
12125 free_pagedep(pagedep)
12126         struct pagedep *pagedep;
12127 {
12128         int i;
12129
12130         if (pagedep->pd_state & NEWBLOCK)
12131                 return (0);
12132         if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12133                 return (0);
12134         for (i = 0; i < DAHASHSZ; i++)
12135                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12136                         return (0);
12137         if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12138                 return (0);
12139         if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12140                 return (0);
12141         if (pagedep->pd_state & ONWORKLIST)
12142                 WORKLIST_REMOVE(&pagedep->pd_list);
12143         LIST_REMOVE(pagedep, pd_hash);
12144         WORKITEM_FREE(pagedep, D_PAGEDEP);
12145
12146         return (1);
12147 }
12148
12149 /*
12150  * Called from within softdep_disk_write_complete above.
12151  * A write operation was just completed. Removed inodes can
12152  * now be freed and associated block pointers may be committed.
12153  * Note that this routine is always called from interrupt level
12154  * with further interrupts from this device blocked.
12155  *
12156  * If the write did not succeed, we will do all the roll-forward
12157  * operations, but we will not take the actions that will allow its
12158  * dependencies to be processed.
12159  */
12160 static int 
12161 handle_written_filepage(pagedep, bp, flags)
12162         struct pagedep *pagedep;
12163         struct buf *bp;         /* buffer containing the written page */
12164         int flags;
12165 {
12166         struct dirrem *dirrem;
12167         struct diradd *dap, *nextdap;
12168         struct direct *ep;
12169         int i, chgs;
12170
12171         if ((pagedep->pd_state & IOSTARTED) == 0)
12172                 panic("handle_written_filepage: not started");
12173         pagedep->pd_state &= ~IOSTARTED;
12174         if ((flags & WRITESUCCEEDED) == 0)
12175                 goto rollforward;
12176         /*
12177          * Process any directory removals that have been committed.
12178          */
12179         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12180                 LIST_REMOVE(dirrem, dm_next);
12181                 dirrem->dm_state |= COMPLETE;
12182                 dirrem->dm_dirinum = pagedep->pd_ino;
12183                 KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12184                     ("handle_written_filepage: Journal entries not written."));
12185                 add_to_worklist(&dirrem->dm_list, 0);
12186         }
12187         /*
12188          * Free any directory additions that have been committed.
12189          * If it is a newly allocated block, we have to wait until
12190          * the on-disk directory inode claims the new block.
12191          */
12192         if ((pagedep->pd_state & NEWBLOCK) == 0)
12193                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12194                         free_diradd(dap, NULL);
12195 rollforward:
12196         /*
12197          * Uncommitted directory entries must be restored.
12198          */
12199         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12200                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12201                      dap = nextdap) {
12202                         nextdap = LIST_NEXT(dap, da_pdlist);
12203                         if (dap->da_state & ATTACHED)
12204                                 panic("handle_written_filepage: attached");
12205                         ep = (struct direct *)
12206                             ((char *)bp->b_data + dap->da_offset);
12207                         ep->d_ino = dap->da_newinum;
12208                         dap->da_state &= ~UNDONE;
12209                         dap->da_state |= ATTACHED;
12210                         chgs = 1;
12211                         /*
12212                          * If the inode referenced by the directory has
12213                          * been written out, then the dependency can be
12214                          * moved to the pending list.
12215                          */
12216                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12217                                 LIST_REMOVE(dap, da_pdlist);
12218                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12219                                     da_pdlist);
12220                         }
12221                 }
12222         }
12223         /*
12224          * If there were any rollbacks in the directory, then it must be
12225          * marked dirty so that its will eventually get written back in
12226          * its correct form.
12227          */
12228         if (chgs || (flags & WRITESUCCEEDED) == 0) {
12229                 if ((bp->b_flags & B_DELWRI) == 0)
12230                         stat_dir_entry++;
12231                 bdirty(bp);
12232                 return (1);
12233         }
12234         /*
12235          * If we are not waiting for a new directory block to be
12236          * claimed by its inode, then the pagedep will be freed.
12237          * Otherwise it will remain to track any new entries on
12238          * the page in case they are fsync'ed.
12239          */
12240         free_pagedep(pagedep);
12241         return (0);
12242 }
12243
12244 /*
12245  * Writing back in-core inode structures.
12246  * 
12247  * The filesystem only accesses an inode's contents when it occupies an
12248  * "in-core" inode structure.  These "in-core" structures are separate from
12249  * the page frames used to cache inode blocks.  Only the latter are
12250  * transferred to/from the disk.  So, when the updated contents of the
12251  * "in-core" inode structure are copied to the corresponding in-memory inode
12252  * block, the dependencies are also transferred.  The following procedure is
12253  * called when copying a dirty "in-core" inode to a cached inode block.
12254  */
12255
12256 /*
12257  * Called when an inode is loaded from disk. If the effective link count
12258  * differed from the actual link count when it was last flushed, then we
12259  * need to ensure that the correct effective link count is put back.
12260  */
12261 void 
12262 softdep_load_inodeblock(ip)
12263         struct inode *ip;       /* the "in_core" copy of the inode */
12264 {
12265         struct inodedep *inodedep;
12266         struct ufsmount *ump;
12267
12268         ump = ITOUMP(ip);
12269         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12270             ("softdep_load_inodeblock called on non-softdep filesystem"));
12271         /*
12272          * Check for alternate nlink count.
12273          */
12274         ip->i_effnlink = ip->i_nlink;
12275         ACQUIRE_LOCK(ump);
12276         if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12277                 FREE_LOCK(ump);
12278                 return;
12279         }
12280         ip->i_effnlink -= inodedep->id_nlinkdelta;
12281         KASSERT(ip->i_effnlink >= 0,
12282             ("softdep_load_inodeblock: negative i_effnlink"));
12283         FREE_LOCK(ump);
12284 }
12285
12286 /*
12287  * This routine is called just before the "in-core" inode
12288  * information is to be copied to the in-memory inode block.
12289  * Recall that an inode block contains several inodes. If
12290  * the force flag is set, then the dependencies will be
12291  * cleared so that the update can always be made. Note that
12292  * the buffer is locked when this routine is called, so we
12293  * will never be in the middle of writing the inode block 
12294  * to disk.
12295  */
12296 void 
12297 softdep_update_inodeblock(ip, bp, waitfor)
12298         struct inode *ip;       /* the "in_core" copy of the inode */
12299         struct buf *bp;         /* the buffer containing the inode block */
12300         int waitfor;            /* nonzero => update must be allowed */
12301 {
12302         struct inodedep *inodedep;
12303         struct inoref *inoref;
12304         struct ufsmount *ump;
12305         struct worklist *wk;
12306         struct mount *mp;
12307         struct buf *ibp;
12308         struct fs *fs;
12309         int error;
12310
12311         ump = ITOUMP(ip);
12312         mp = UFSTOVFS(ump);
12313         KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12314             ("softdep_update_inodeblock called on non-softdep filesystem"));
12315         fs = ump->um_fs;
12316         /*
12317          * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12318          * does not have access to the in-core ip so must write directly into
12319          * the inode block buffer when setting freelink.
12320          */
12321         if (fs->fs_magic == FS_UFS1_MAGIC)
12322                 DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12323                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12324         else
12325                 DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12326                     ino_to_fsbo(fs, ip->i_number))->di_freelink);
12327         /*
12328          * If the effective link count is not equal to the actual link
12329          * count, then we must track the difference in an inodedep while
12330          * the inode is (potentially) tossed out of the cache. Otherwise,
12331          * if there is no existing inodedep, then there are no dependencies
12332          * to track.
12333          */
12334         ACQUIRE_LOCK(ump);
12335 again:
12336         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12337                 FREE_LOCK(ump);
12338                 if (ip->i_effnlink != ip->i_nlink)
12339                         panic("softdep_update_inodeblock: bad link count");
12340                 return;
12341         }
12342         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12343                 panic("softdep_update_inodeblock: bad delta");
12344         /*
12345          * If we're flushing all dependencies we must also move any waiting
12346          * for journal writes onto the bufwait list prior to I/O.
12347          */
12348         if (waitfor) {
12349                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12350                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12351                             == DEPCOMPLETE) {
12352                                 jwait(&inoref->if_list, MNT_WAIT);
12353                                 goto again;
12354                         }
12355                 }
12356         }
12357         /*
12358          * Changes have been initiated. Anything depending on these
12359          * changes cannot occur until this inode has been written.
12360          */
12361         inodedep->id_state &= ~COMPLETE;
12362         if ((inodedep->id_state & ONWORKLIST) == 0)
12363                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12364         /*
12365          * Any new dependencies associated with the incore inode must 
12366          * now be moved to the list associated with the buffer holding
12367          * the in-memory copy of the inode. Once merged process any
12368          * allocdirects that are completed by the merger.
12369          */
12370         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12371         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12372                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12373                     NULL);
12374         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12375         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12376                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12377                     NULL);
12378         /*
12379          * Now that the inode has been pushed into the buffer, the
12380          * operations dependent on the inode being written to disk
12381          * can be moved to the id_bufwait so that they will be
12382          * processed when the buffer I/O completes.
12383          */
12384         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12385                 WORKLIST_REMOVE(wk);
12386                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12387         }
12388         /*
12389          * Newly allocated inodes cannot be written until the bitmap
12390          * that allocates them have been written (indicated by
12391          * DEPCOMPLETE being set in id_state). If we are doing a
12392          * forced sync (e.g., an fsync on a file), we force the bitmap
12393          * to be written so that the update can be done.
12394          */
12395         if (waitfor == 0) {
12396                 FREE_LOCK(ump);
12397                 return;
12398         }
12399 retry:
12400         if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12401                 FREE_LOCK(ump);
12402                 return;
12403         }
12404         ibp = inodedep->id_bmsafemap->sm_buf;
12405         ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12406         if (ibp == NULL) {
12407                 /*
12408                  * If ibp came back as NULL, the dependency could have been
12409                  * freed while we slept.  Look it up again, and check to see
12410                  * that it has completed.
12411                  */
12412                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12413                         goto retry;
12414                 FREE_LOCK(ump);
12415                 return;
12416         }
12417         FREE_LOCK(ump);
12418         if ((error = bwrite(ibp)) != 0)
12419                 softdep_error("softdep_update_inodeblock: bwrite", error);
12420 }
12421
12422 /*
12423  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12424  * old inode dependency list (such as id_inoupdt).
12425  */
12426 static void
12427 merge_inode_lists(newlisthead, oldlisthead)
12428         struct allocdirectlst *newlisthead;
12429         struct allocdirectlst *oldlisthead;
12430 {
12431         struct allocdirect *listadp, *newadp;
12432
12433         newadp = TAILQ_FIRST(newlisthead);
12434         if (newadp != NULL)
12435                 LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12436         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12437                 if (listadp->ad_offset < newadp->ad_offset) {
12438                         listadp = TAILQ_NEXT(listadp, ad_next);
12439                         continue;
12440                 }
12441                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12442                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12443                 if (listadp->ad_offset == newadp->ad_offset) {
12444                         allocdirect_merge(oldlisthead, newadp,
12445                             listadp);
12446                         listadp = newadp;
12447                 }
12448                 newadp = TAILQ_FIRST(newlisthead);
12449         }
12450         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12451                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
12452                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12453         }
12454 }
12455
12456 /*
12457  * If we are doing an fsync, then we must ensure that any directory
12458  * entries for the inode have been written after the inode gets to disk.
12459  */
12460 int
12461 softdep_fsync(vp)
12462         struct vnode *vp;       /* the "in_core" copy of the inode */
12463 {
12464         struct inodedep *inodedep;
12465         struct pagedep *pagedep;
12466         struct inoref *inoref;
12467         struct ufsmount *ump;
12468         struct worklist *wk;
12469         struct diradd *dap;
12470         struct mount *mp;
12471         struct vnode *pvp;
12472         struct inode *ip;
12473         struct buf *bp;
12474         struct fs *fs;
12475         struct thread *td = curthread;
12476         int error, flushparent, pagedep_new_block;
12477         ino_t parentino;
12478         ufs_lbn_t lbn;
12479
12480         ip = VTOI(vp);
12481         mp = vp->v_mount;
12482         ump = VFSTOUFS(mp);
12483         fs = ump->um_fs;
12484         if (MOUNTEDSOFTDEP(mp) == 0)
12485                 return (0);
12486         ACQUIRE_LOCK(ump);
12487 restart:
12488         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12489                 FREE_LOCK(ump);
12490                 return (0);
12491         }
12492         TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12493                 if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12494                     == DEPCOMPLETE) {
12495                         jwait(&inoref->if_list, MNT_WAIT);
12496                         goto restart;
12497                 }
12498         }
12499         if (!LIST_EMPTY(&inodedep->id_inowait) ||
12500             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12501             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12502             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12503             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12504                 panic("softdep_fsync: pending ops %p", inodedep);
12505         for (error = 0, flushparent = 0; ; ) {
12506                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12507                         break;
12508                 if (wk->wk_type != D_DIRADD)
12509                         panic("softdep_fsync: Unexpected type %s",
12510                             TYPENAME(wk->wk_type));
12511                 dap = WK_DIRADD(wk);
12512                 /*
12513                  * Flush our parent if this directory entry has a MKDIR_PARENT
12514                  * dependency or is contained in a newly allocated block.
12515                  */
12516                 if (dap->da_state & DIRCHG)
12517                         pagedep = dap->da_previous->dm_pagedep;
12518                 else
12519                         pagedep = dap->da_pagedep;
12520                 parentino = pagedep->pd_ino;
12521                 lbn = pagedep->pd_lbn;
12522                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12523                         panic("softdep_fsync: dirty");
12524                 if ((dap->da_state & MKDIR_PARENT) ||
12525                     (pagedep->pd_state & NEWBLOCK))
12526                         flushparent = 1;
12527                 else
12528                         flushparent = 0;
12529                 /*
12530                  * If we are being fsync'ed as part of vgone'ing this vnode,
12531                  * then we will not be able to release and recover the
12532                  * vnode below, so we just have to give up on writing its
12533                  * directory entry out. It will eventually be written, just
12534                  * not now, but then the user was not asking to have it
12535                  * written, so we are not breaking any promises.
12536                  */
12537                 if (VN_IS_DOOMED(vp))
12538                         break;
12539                 /*
12540                  * We prevent deadlock by always fetching inodes from the
12541                  * root, moving down the directory tree. Thus, when fetching
12542                  * our parent directory, we first try to get the lock. If
12543                  * that fails, we must unlock ourselves before requesting
12544                  * the lock on our parent. See the comment in ufs_lookup
12545                  * for details on possible races.
12546                  */
12547                 FREE_LOCK(ump);
12548                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12549                     FFSV_FORCEINSMQ)) {
12550                         /*
12551                          * Unmount cannot proceed after unlock because
12552                          * caller must have called vn_start_write().
12553                          */
12554                         VOP_UNLOCK(vp);
12555                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12556                             &pvp, FFSV_FORCEINSMQ);
12557                         MPASS(VTOI(pvp)->i_mode != 0);
12558                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12559                         if (VN_IS_DOOMED(vp)) {
12560                                 if (error == 0)
12561                                         vput(pvp);
12562                                 error = ENOENT;
12563                         }
12564                         if (error != 0)
12565                                 return (error);
12566                 }
12567                 /*
12568                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12569                  * that are contained in direct blocks will be resolved by 
12570                  * doing a ffs_update. Pagedeps contained in indirect blocks
12571                  * may require a complete sync'ing of the directory. So, we
12572                  * try the cheap and fast ffs_update first, and if that fails,
12573                  * then we do the slower ffs_syncvnode of the directory.
12574                  */
12575                 if (flushparent) {
12576                         int locked;
12577
12578                         if ((error = ffs_update(pvp, 1)) != 0) {
12579                                 vput(pvp);
12580                                 return (error);
12581                         }
12582                         ACQUIRE_LOCK(ump);
12583                         locked = 1;
12584                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12585                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12586                                         if (wk->wk_type != D_DIRADD)
12587                                                 panic("softdep_fsync: Unexpected type %s",
12588                                                       TYPENAME(wk->wk_type));
12589                                         dap = WK_DIRADD(wk);
12590                                         if (dap->da_state & DIRCHG)
12591                                                 pagedep = dap->da_previous->dm_pagedep;
12592                                         else
12593                                                 pagedep = dap->da_pagedep;
12594                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12595                                         FREE_LOCK(ump);
12596                                         locked = 0;
12597                                         if (pagedep_new_block && (error =
12598                                             ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12599                                                 vput(pvp);
12600                                                 return (error);
12601                                         }
12602                                 }
12603                         }
12604                         if (locked)
12605                                 FREE_LOCK(ump);
12606                 }
12607                 /*
12608                  * Flush directory page containing the inode's name.
12609                  */
12610                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12611                     &bp);
12612                 if (error == 0)
12613                         error = bwrite(bp);
12614                 else
12615                         brelse(bp);
12616                 vput(pvp);
12617                 if (error != 0)
12618                         return (error);
12619                 ACQUIRE_LOCK(ump);
12620                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12621                         break;
12622         }
12623         FREE_LOCK(ump);
12624         return (0);
12625 }
12626
12627 /*
12628  * Flush all the dirty bitmaps associated with the block device
12629  * before flushing the rest of the dirty blocks so as to reduce
12630  * the number of dependencies that will have to be rolled back.
12631  *
12632  * XXX Unused?
12633  */
12634 void
12635 softdep_fsync_mountdev(vp)
12636         struct vnode *vp;
12637 {
12638         struct buf *bp, *nbp;
12639         struct worklist *wk;
12640         struct bufobj *bo;
12641
12642         if (!vn_isdisk(vp, NULL))
12643                 panic("softdep_fsync_mountdev: vnode not a disk");
12644         bo = &vp->v_bufobj;
12645 restart:
12646         BO_LOCK(bo);
12647         TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12648                 /* 
12649                  * If it is already scheduled, skip to the next buffer.
12650                  */
12651                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12652                         continue;
12653
12654                 if ((bp->b_flags & B_DELWRI) == 0)
12655                         panic("softdep_fsync_mountdev: not dirty");
12656                 /*
12657                  * We are only interested in bitmaps with outstanding
12658                  * dependencies.
12659                  */
12660                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12661                     wk->wk_type != D_BMSAFEMAP ||
12662                     (bp->b_vflags & BV_BKGRDINPROG)) {
12663                         BUF_UNLOCK(bp);
12664                         continue;
12665                 }
12666                 BO_UNLOCK(bo);
12667                 bremfree(bp);
12668                 (void) bawrite(bp);
12669                 goto restart;
12670         }
12671         drain_output(vp);
12672         BO_UNLOCK(bo);
12673 }
12674
12675 /*
12676  * Sync all cylinder groups that were dirty at the time this function is
12677  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12678  * is used to flush freedep activity that may be holding up writes to a
12679  * indirect block.
12680  */
12681 static int
12682 sync_cgs(mp, waitfor)
12683         struct mount *mp;
12684         int waitfor;
12685 {
12686         struct bmsafemap *bmsafemap;
12687         struct bmsafemap *sentinel;
12688         struct ufsmount *ump;
12689         struct buf *bp;
12690         int error;
12691
12692         sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12693         sentinel->sm_cg = -1;
12694         ump = VFSTOUFS(mp);
12695         error = 0;
12696         ACQUIRE_LOCK(ump);
12697         LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12698         for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12699             bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12700                 /* Skip sentinels and cgs with no work to release. */
12701                 if (bmsafemap->sm_cg == -1 ||
12702                     (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12703                     LIST_EMPTY(&bmsafemap->sm_freewr))) {
12704                         LIST_REMOVE(sentinel, sm_next);
12705                         LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12706                         continue;
12707                 }
12708                 /*
12709                  * If we don't get the lock and we're waiting try again, if
12710                  * not move on to the next buf and try to sync it.
12711                  */
12712                 bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12713                 if (bp == NULL && waitfor == MNT_WAIT)
12714                         continue;
12715                 LIST_REMOVE(sentinel, sm_next);
12716                 LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12717                 if (bp == NULL)
12718                         continue;
12719                 FREE_LOCK(ump);
12720                 if (waitfor == MNT_NOWAIT)
12721                         bawrite(bp);
12722                 else
12723                         error = bwrite(bp);
12724                 ACQUIRE_LOCK(ump);
12725                 if (error)
12726                         break;
12727         }
12728         LIST_REMOVE(sentinel, sm_next);
12729         FREE_LOCK(ump);
12730         free(sentinel, M_BMSAFEMAP);
12731         return (error);
12732 }
12733
12734 /*
12735  * This routine is called when we are trying to synchronously flush a
12736  * file. This routine must eliminate any filesystem metadata dependencies
12737  * so that the syncing routine can succeed.
12738  */
12739 int
12740 softdep_sync_metadata(struct vnode *vp)
12741 {
12742         struct inode *ip;
12743         int error;
12744
12745         ip = VTOI(vp);
12746         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12747             ("softdep_sync_metadata called on non-softdep filesystem"));
12748         /*
12749          * Ensure that any direct block dependencies have been cleared,
12750          * truncations are started, and inode references are journaled.
12751          */
12752         ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
12753         /*
12754          * Write all journal records to prevent rollbacks on devvp.
12755          */
12756         if (vp->v_type == VCHR)
12757                 softdep_flushjournal(vp->v_mount);
12758         error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12759         /*
12760          * Ensure that all truncates are written so we won't find deps on
12761          * indirect blocks.
12762          */
12763         process_truncates(vp);
12764         FREE_LOCK(VFSTOUFS(vp->v_mount));
12765
12766         return (error);
12767 }
12768
12769 /*
12770  * This routine is called when we are attempting to sync a buf with
12771  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12772  * other IO it can but returns EBUSY if the buffer is not yet able to
12773  * be written.  Dependencies which will not cause rollbacks will always
12774  * return 0.
12775  */
12776 int
12777 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12778 {
12779         struct indirdep *indirdep;
12780         struct pagedep *pagedep;
12781         struct allocindir *aip;
12782         struct newblk *newblk;
12783         struct ufsmount *ump;
12784         struct buf *nbp;
12785         struct worklist *wk;
12786         int i, error;
12787
12788         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12789             ("softdep_sync_buf called on non-softdep filesystem"));
12790         /*
12791          * For VCHR we just don't want to force flush any dependencies that
12792          * will cause rollbacks.
12793          */
12794         if (vp->v_type == VCHR) {
12795                 if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12796                         return (EBUSY);
12797                 return (0);
12798         }
12799         ump = VFSTOUFS(vp->v_mount);
12800         ACQUIRE_LOCK(ump);
12801         /*
12802          * As we hold the buffer locked, none of its dependencies
12803          * will disappear.
12804          */
12805         error = 0;
12806 top:
12807         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12808                 switch (wk->wk_type) {
12809
12810                 case D_ALLOCDIRECT:
12811                 case D_ALLOCINDIR:
12812                         newblk = WK_NEWBLK(wk);
12813                         if (newblk->nb_jnewblk != NULL) {
12814                                 if (waitfor == MNT_NOWAIT) {
12815                                         error = EBUSY;
12816                                         goto out_unlock;
12817                                 }
12818                                 jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12819                                 goto top;
12820                         }
12821                         if (newblk->nb_state & DEPCOMPLETE ||
12822                             waitfor == MNT_NOWAIT)
12823                                 continue;
12824                         nbp = newblk->nb_bmsafemap->sm_buf;
12825                         nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12826                         if (nbp == NULL)
12827                                 goto top;
12828                         FREE_LOCK(ump);
12829                         if ((error = bwrite(nbp)) != 0)
12830                                 goto out;
12831                         ACQUIRE_LOCK(ump);
12832                         continue;
12833
12834                 case D_INDIRDEP:
12835                         indirdep = WK_INDIRDEP(wk);
12836                         if (waitfor == MNT_NOWAIT) {
12837                                 if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12838                                     !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12839                                         error = EBUSY;
12840                                         goto out_unlock;
12841                                 }
12842                         }
12843                         if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12844                                 panic("softdep_sync_buf: truncation pending.");
12845                 restart:
12846                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12847                                 newblk = (struct newblk *)aip;
12848                                 if (newblk->nb_jnewblk != NULL) {
12849                                         jwait(&newblk->nb_jnewblk->jn_list,
12850                                             waitfor);
12851                                         goto restart;
12852                                 }
12853                                 if (newblk->nb_state & DEPCOMPLETE)
12854                                         continue;
12855                                 nbp = newblk->nb_bmsafemap->sm_buf;
12856                                 nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12857                                 if (nbp == NULL)
12858                                         goto restart;
12859                                 FREE_LOCK(ump);
12860                                 if ((error = bwrite(nbp)) != 0)
12861                                         goto out;
12862                                 ACQUIRE_LOCK(ump);
12863                                 goto restart;
12864                         }
12865                         continue;
12866
12867                 case D_PAGEDEP:
12868                         /*
12869                          * Only flush directory entries in synchronous passes.
12870                          */
12871                         if (waitfor != MNT_WAIT) {
12872                                 error = EBUSY;
12873                                 goto out_unlock;
12874                         }
12875                         /*
12876                          * While syncing snapshots, we must allow recursive
12877                          * lookups.
12878                          */
12879                         BUF_AREC(bp);
12880                         /*
12881                          * We are trying to sync a directory that may
12882                          * have dependencies on both its own metadata
12883                          * and/or dependencies on the inodes of any
12884                          * recently allocated files. We walk its diradd
12885                          * lists pushing out the associated inode.
12886                          */
12887                         pagedep = WK_PAGEDEP(wk);
12888                         for (i = 0; i < DAHASHSZ; i++) {
12889                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12890                                         continue;
12891                                 if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12892                                     &pagedep->pd_diraddhd[i]))) {
12893                                         BUF_NOREC(bp);
12894                                         goto out_unlock;
12895                                 }
12896                         }
12897                         BUF_NOREC(bp);
12898                         continue;
12899
12900                 case D_FREEWORK:
12901                 case D_FREEDEP:
12902                 case D_JSEGDEP:
12903                 case D_JNEWBLK:
12904                         continue;
12905
12906                 default:
12907                         panic("softdep_sync_buf: Unknown type %s",
12908                             TYPENAME(wk->wk_type));
12909                         /* NOTREACHED */
12910                 }
12911         }
12912 out_unlock:
12913         FREE_LOCK(ump);
12914 out:
12915         return (error);
12916 }
12917
12918 /*
12919  * Flush the dependencies associated with an inodedep.
12920  */
12921 static int
12922 flush_inodedep_deps(vp, mp, ino)
12923         struct vnode *vp;
12924         struct mount *mp;
12925         ino_t ino;
12926 {
12927         struct inodedep *inodedep;
12928         struct inoref *inoref;
12929         struct ufsmount *ump;
12930         int error, waitfor;
12931
12932         /*
12933          * This work is done in two passes. The first pass grabs most
12934          * of the buffers and begins asynchronously writing them. The
12935          * only way to wait for these asynchronous writes is to sleep
12936          * on the filesystem vnode which may stay busy for a long time
12937          * if the filesystem is active. So, instead, we make a second
12938          * pass over the dependencies blocking on each write. In the
12939          * usual case we will be blocking against a write that we
12940          * initiated, so when it is done the dependency will have been
12941          * resolved. Thus the second pass is expected to end quickly.
12942          * We give a brief window at the top of the loop to allow
12943          * any pending I/O to complete.
12944          */
12945         ump = VFSTOUFS(mp);
12946         LOCK_OWNED(ump);
12947         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12948                 if (error)
12949                         return (error);
12950                 FREE_LOCK(ump);
12951                 ACQUIRE_LOCK(ump);
12952 restart:
12953                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12954                         return (0);
12955                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12956                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12957                             == DEPCOMPLETE) {
12958                                 jwait(&inoref->if_list, MNT_WAIT);
12959                                 goto restart;
12960                         }
12961                 }
12962                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12963                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12964                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12965                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12966                         continue;
12967                 /*
12968                  * If pass2, we are done, otherwise do pass 2.
12969                  */
12970                 if (waitfor == MNT_WAIT)
12971                         break;
12972                 waitfor = MNT_WAIT;
12973         }
12974         /*
12975          * Try freeing inodedep in case all dependencies have been removed.
12976          */
12977         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12978                 (void) free_inodedep(inodedep);
12979         return (0);
12980 }
12981
12982 /*
12983  * Flush an inode dependency list.
12984  */
12985 static int
12986 flush_deplist(listhead, waitfor, errorp)
12987         struct allocdirectlst *listhead;
12988         int waitfor;
12989         int *errorp;
12990 {
12991         struct allocdirect *adp;
12992         struct newblk *newblk;
12993         struct ufsmount *ump;
12994         struct buf *bp;
12995
12996         if ((adp = TAILQ_FIRST(listhead)) == NULL)
12997                 return (0);
12998         ump = VFSTOUFS(adp->ad_list.wk_mp);
12999         LOCK_OWNED(ump);
13000         TAILQ_FOREACH(adp, listhead, ad_next) {
13001                 newblk = (struct newblk *)adp;
13002                 if (newblk->nb_jnewblk != NULL) {
13003                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13004                         return (1);
13005                 }
13006                 if (newblk->nb_state & DEPCOMPLETE)
13007                         continue;
13008                 bp = newblk->nb_bmsafemap->sm_buf;
13009                 bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13010                 if (bp == NULL) {
13011                         if (waitfor == MNT_NOWAIT)
13012                                 continue;
13013                         return (1);
13014                 }
13015                 FREE_LOCK(ump);
13016                 if (waitfor == MNT_NOWAIT)
13017                         bawrite(bp);
13018                 else 
13019                         *errorp = bwrite(bp);
13020                 ACQUIRE_LOCK(ump);
13021                 return (1);
13022         }
13023         return (0);
13024 }
13025
13026 /*
13027  * Flush dependencies associated with an allocdirect block.
13028  */
13029 static int
13030 flush_newblk_dep(vp, mp, lbn)
13031         struct vnode *vp;
13032         struct mount *mp;
13033         ufs_lbn_t lbn;
13034 {
13035         struct newblk *newblk;
13036         struct ufsmount *ump;
13037         struct bufobj *bo;
13038         struct inode *ip;
13039         struct buf *bp;
13040         ufs2_daddr_t blkno;
13041         int error;
13042
13043         error = 0;
13044         bo = &vp->v_bufobj;
13045         ip = VTOI(vp);
13046         blkno = DIP(ip, i_db[lbn]);
13047         if (blkno == 0)
13048                 panic("flush_newblk_dep: Missing block");
13049         ump = VFSTOUFS(mp);
13050         ACQUIRE_LOCK(ump);
13051         /*
13052          * Loop until all dependencies related to this block are satisfied.
13053          * We must be careful to restart after each sleep in case a write
13054          * completes some part of this process for us.
13055          */
13056         for (;;) {
13057                 if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13058                         FREE_LOCK(ump);
13059                         break;
13060                 }
13061                 if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13062                         panic("flush_newblk_dep: Bad newblk %p", newblk);
13063                 /*
13064                  * Flush the journal.
13065                  */
13066                 if (newblk->nb_jnewblk != NULL) {
13067                         jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13068                         continue;
13069                 }
13070                 /*
13071                  * Write the bitmap dependency.
13072                  */
13073                 if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13074                         bp = newblk->nb_bmsafemap->sm_buf;
13075                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13076                         if (bp == NULL)
13077                                 continue;
13078                         FREE_LOCK(ump);
13079                         error = bwrite(bp);
13080                         if (error)
13081                                 break;
13082                         ACQUIRE_LOCK(ump);
13083                         continue;
13084                 }
13085                 /*
13086                  * Write the buffer.
13087                  */
13088                 FREE_LOCK(ump);
13089                 BO_LOCK(bo);
13090                 bp = gbincore(bo, lbn);
13091                 if (bp != NULL) {
13092                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13093                             LK_INTERLOCK, BO_LOCKPTR(bo));
13094                         if (error == ENOLCK) {
13095                                 ACQUIRE_LOCK(ump);
13096                                 error = 0;
13097                                 continue; /* Slept, retry */
13098                         }
13099                         if (error != 0)
13100                                 break;  /* Failed */
13101                         if (bp->b_flags & B_DELWRI) {
13102                                 bremfree(bp);
13103                                 error = bwrite(bp);
13104                                 if (error)
13105                                         break;
13106                         } else
13107                                 BUF_UNLOCK(bp);
13108                 } else
13109                         BO_UNLOCK(bo);
13110                 /*
13111                  * We have to wait for the direct pointers to
13112                  * point at the newdirblk before the dependency
13113                  * will go away.
13114                  */
13115                 error = ffs_update(vp, 1);
13116                 if (error)
13117                         break;
13118                 ACQUIRE_LOCK(ump);
13119         }
13120         return (error);
13121 }
13122
13123 /*
13124  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13125  */
13126 static int
13127 flush_pagedep_deps(pvp, mp, diraddhdp)
13128         struct vnode *pvp;
13129         struct mount *mp;
13130         struct diraddhd *diraddhdp;
13131 {
13132         struct inodedep *inodedep;
13133         struct inoref *inoref;
13134         struct ufsmount *ump;
13135         struct diradd *dap;
13136         struct vnode *vp;
13137         int error = 0;
13138         struct buf *bp;
13139         ino_t inum;
13140         struct diraddhd unfinished;
13141
13142         LIST_INIT(&unfinished);
13143         ump = VFSTOUFS(mp);
13144         LOCK_OWNED(ump);
13145 restart:
13146         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13147                 /*
13148                  * Flush ourselves if this directory entry
13149                  * has a MKDIR_PARENT dependency.
13150                  */
13151                 if (dap->da_state & MKDIR_PARENT) {
13152                         FREE_LOCK(ump);
13153                         if ((error = ffs_update(pvp, 1)) != 0)
13154                                 break;
13155                         ACQUIRE_LOCK(ump);
13156                         /*
13157                          * If that cleared dependencies, go on to next.
13158                          */
13159                         if (dap != LIST_FIRST(diraddhdp))
13160                                 continue;
13161                         /*
13162                          * All MKDIR_PARENT dependencies and all the
13163                          * NEWBLOCK pagedeps that are contained in direct
13164                          * blocks were resolved by doing above ffs_update.
13165                          * Pagedeps contained in indirect blocks may
13166                          * require a complete sync'ing of the directory.
13167                          * We are in the midst of doing a complete sync,
13168                          * so if they are not resolved in this pass we
13169                          * defer them for now as they will be sync'ed by
13170                          * our caller shortly.
13171                          */
13172                         LIST_REMOVE(dap, da_pdlist);
13173                         LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13174                         continue;
13175                 }
13176                 /*
13177                  * A newly allocated directory must have its "." and
13178                  * ".." entries written out before its name can be
13179                  * committed in its parent. 
13180                  */
13181                 inum = dap->da_newinum;
13182                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13183                         panic("flush_pagedep_deps: lost inode1");
13184                 /*
13185                  * Wait for any pending journal adds to complete so we don't
13186                  * cause rollbacks while syncing.
13187                  */
13188                 TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13189                         if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13190                             == DEPCOMPLETE) {
13191                                 jwait(&inoref->if_list, MNT_WAIT);
13192                                 goto restart;
13193                         }
13194                 }
13195                 if (dap->da_state & MKDIR_BODY) {
13196                         FREE_LOCK(ump);
13197                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13198                             FFSV_FORCEINSMQ)))
13199                                 break;
13200                         MPASS(VTOI(vp)->i_mode != 0);
13201                         error = flush_newblk_dep(vp, mp, 0);
13202                         /*
13203                          * If we still have the dependency we might need to
13204                          * update the vnode to sync the new link count to
13205                          * disk.
13206                          */
13207                         if (error == 0 && dap == LIST_FIRST(diraddhdp))
13208                                 error = ffs_update(vp, 1);
13209                         vput(vp);
13210                         if (error != 0)
13211                                 break;
13212                         ACQUIRE_LOCK(ump);
13213                         /*
13214                          * If that cleared dependencies, go on to next.
13215                          */
13216                         if (dap != LIST_FIRST(diraddhdp))
13217                                 continue;
13218                         if (dap->da_state & MKDIR_BODY) {
13219                                 inodedep_lookup(UFSTOVFS(ump), inum, 0,
13220                                     &inodedep);
13221                                 panic("flush_pagedep_deps: MKDIR_BODY "
13222                                     "inodedep %p dap %p vp %p",
13223                                     inodedep, dap, vp);
13224                         }
13225                 }
13226                 /*
13227                  * Flush the inode on which the directory entry depends.
13228                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13229                  * the only remaining dependency is that the updated inode
13230                  * count must get pushed to disk. The inode has already
13231                  * been pushed into its inode buffer (via VOP_UPDATE) at
13232                  * the time of the reference count change. So we need only
13233                  * locate that buffer, ensure that there will be no rollback
13234                  * caused by a bitmap dependency, then write the inode buffer.
13235                  */
13236 retry:
13237                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13238                         panic("flush_pagedep_deps: lost inode");
13239                 /*
13240                  * If the inode still has bitmap dependencies,
13241                  * push them to disk.
13242                  */
13243                 if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13244                         bp = inodedep->id_bmsafemap->sm_buf;
13245                         bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13246                         if (bp == NULL)
13247                                 goto retry;
13248                         FREE_LOCK(ump);
13249                         if ((error = bwrite(bp)) != 0)
13250                                 break;
13251                         ACQUIRE_LOCK(ump);
13252                         if (dap != LIST_FIRST(diraddhdp))
13253                                 continue;
13254                 }
13255                 /*
13256                  * If the inode is still sitting in a buffer waiting
13257                  * to be written or waiting for the link count to be
13258                  * adjusted update it here to flush it to disk.
13259                  */
13260                 if (dap == LIST_FIRST(diraddhdp)) {
13261                         FREE_LOCK(ump);
13262                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13263                             FFSV_FORCEINSMQ)))
13264                                 break;
13265                         MPASS(VTOI(vp)->i_mode != 0);
13266                         error = ffs_update(vp, 1);
13267                         vput(vp);
13268                         if (error)
13269                                 break;
13270                         ACQUIRE_LOCK(ump);
13271                 }
13272                 /*
13273                  * If we have failed to get rid of all the dependencies
13274                  * then something is seriously wrong.
13275                  */
13276                 if (dap == LIST_FIRST(diraddhdp)) {
13277                         inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13278                         panic("flush_pagedep_deps: failed to flush " 
13279                             "inodedep %p ino %ju dap %p",
13280                             inodedep, (uintmax_t)inum, dap);
13281                 }
13282         }
13283         if (error)
13284                 ACQUIRE_LOCK(ump);
13285         while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13286                 LIST_REMOVE(dap, da_pdlist);
13287                 LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13288         }
13289         return (error);
13290 }
13291
13292 /*
13293  * A large burst of file addition or deletion activity can drive the
13294  * memory load excessively high. First attempt to slow things down
13295  * using the techniques below. If that fails, this routine requests
13296  * the offending operations to fall back to running synchronously
13297  * until the memory load returns to a reasonable level.
13298  */
13299 int
13300 softdep_slowdown(vp)
13301         struct vnode *vp;
13302 {
13303         struct ufsmount *ump;
13304         int jlow;
13305         int max_softdeps_hard;
13306
13307         KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13308             ("softdep_slowdown called on non-softdep filesystem"));
13309         ump = VFSTOUFS(vp->v_mount);
13310         ACQUIRE_LOCK(ump);
13311         jlow = 0;
13312         /*
13313          * Check for journal space if needed.
13314          */
13315         if (DOINGSUJ(vp)) {
13316                 if (journal_space(ump, 0) == 0)
13317                         jlow = 1;
13318         }
13319         /*
13320          * If the system is under its limits and our filesystem is
13321          * not responsible for more than our share of the usage and
13322          * we are not low on journal space, then no need to slow down.
13323          */
13324         max_softdeps_hard = max_softdeps * 11 / 10;
13325         if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13326             dep_current[D_INODEDEP] < max_softdeps_hard &&
13327             dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13328             dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13329             ump->softdep_curdeps[D_DIRREM] <
13330             (max_softdeps_hard / 2) / stat_flush_threads &&
13331             ump->softdep_curdeps[D_INODEDEP] <
13332             max_softdeps_hard / stat_flush_threads &&
13333             ump->softdep_curdeps[D_INDIRDEP] <
13334             (max_softdeps_hard / 1000) / stat_flush_threads &&
13335             ump->softdep_curdeps[D_FREEBLKS] <
13336             max_softdeps_hard / stat_flush_threads) {
13337                 FREE_LOCK(ump);
13338                 return (0);
13339         }
13340         /*
13341          * If the journal is low or our filesystem is over its limit
13342          * then speedup the cleanup.
13343          */
13344         if (ump->softdep_curdeps[D_INDIRDEP] <
13345             (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13346                 softdep_speedup(ump);
13347         stat_sync_limit_hit += 1;
13348         FREE_LOCK(ump);
13349         /*
13350          * We only slow down the rate at which new dependencies are
13351          * generated if we are not using journaling. With journaling,
13352          * the cleanup should always be sufficient to keep things
13353          * under control.
13354          */
13355         if (DOINGSUJ(vp))
13356                 return (0);
13357         return (1);
13358 }
13359
13360 /*
13361  * Called by the allocation routines when they are about to fail
13362  * in the hope that we can free up the requested resource (inodes
13363  * or disk space).
13364  * 
13365  * First check to see if the work list has anything on it. If it has,
13366  * clean up entries until we successfully free the requested resource.
13367  * Because this process holds inodes locked, we cannot handle any remove
13368  * requests that might block on a locked inode as that could lead to
13369  * deadlock. If the worklist yields none of the requested resource,
13370  * start syncing out vnodes to free up the needed space.
13371  */
13372 int
13373 softdep_request_cleanup(fs, vp, cred, resource)
13374         struct fs *fs;
13375         struct vnode *vp;
13376         struct ucred *cred;
13377         int resource;
13378 {
13379         struct ufsmount *ump;
13380         struct mount *mp;
13381         long starttime;
13382         ufs2_daddr_t needed;
13383         int error, failed_vnode;
13384
13385         /*
13386          * If we are being called because of a process doing a
13387          * copy-on-write, then it is not safe to process any
13388          * worklist items as we will recurse into the copyonwrite
13389          * routine.  This will result in an incoherent snapshot.
13390          * If the vnode that we hold is a snapshot, we must avoid
13391          * handling other resources that could cause deadlock.
13392          */
13393         if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13394                 return (0);
13395
13396         if (resource == FLUSH_BLOCKS_WAIT)
13397                 stat_cleanup_blkrequests += 1;
13398         else
13399                 stat_cleanup_inorequests += 1;
13400
13401         mp = vp->v_mount;
13402         ump = VFSTOUFS(mp);
13403         mtx_assert(UFS_MTX(ump), MA_OWNED);
13404         UFS_UNLOCK(ump);
13405         error = ffs_update(vp, 1);
13406         if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13407                 UFS_LOCK(ump);
13408                 return (0);
13409         }
13410         /*
13411          * If we are in need of resources, start by cleaning up
13412          * any block removals associated with our inode.
13413          */
13414         ACQUIRE_LOCK(ump);
13415         process_removes(vp);
13416         process_truncates(vp);
13417         FREE_LOCK(ump);
13418         /*
13419          * Now clean up at least as many resources as we will need.
13420          *
13421          * When requested to clean up inodes, the number that are needed
13422          * is set by the number of simultaneous writers (mnt_writeopcount)
13423          * plus a bit of slop (2) in case some more writers show up while
13424          * we are cleaning.
13425          *
13426          * When requested to free up space, the amount of space that
13427          * we need is enough blocks to allocate a full-sized segment
13428          * (fs_contigsumsize). The number of such segments that will
13429          * be needed is set by the number of simultaneous writers
13430          * (mnt_writeopcount) plus a bit of slop (2) in case some more
13431          * writers show up while we are cleaning.
13432          *
13433          * Additionally, if we are unpriviledged and allocating space,
13434          * we need to ensure that we clean up enough blocks to get the
13435          * needed number of blocks over the threshold of the minimum
13436          * number of blocks required to be kept free by the filesystem
13437          * (fs_minfree).
13438          */
13439         if (resource == FLUSH_INODES_WAIT) {
13440                 needed = vfs_mount_fetch_counter(vp->v_mount,
13441                     MNT_COUNT_WRITEOPCOUNT) + 2;
13442         } else if (resource == FLUSH_BLOCKS_WAIT) {
13443                 needed = (vfs_mount_fetch_counter(vp->v_mount,
13444                     MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13445                 if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13446                         needed += fragstoblks(fs,
13447                             roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13448                             fs->fs_cstotal.cs_nffree, fs->fs_frag));
13449         } else {
13450                 printf("softdep_request_cleanup: Unknown resource type %d\n",
13451                     resource);
13452                 UFS_LOCK(ump);
13453                 return (0);
13454         }
13455         starttime = time_second;
13456 retry:
13457         if (resource == FLUSH_BLOCKS_WAIT &&
13458             fs->fs_cstotal.cs_nbfree <= needed)
13459                 softdep_send_speedup(ump, needed * fs->fs_bsize,
13460                     BIO_SPEEDUP_TRIM);
13461         if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13462             fs->fs_cstotal.cs_nbfree <= needed) ||
13463             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13464             fs->fs_cstotal.cs_nifree <= needed)) {
13465                 ACQUIRE_LOCK(ump);
13466                 if (ump->softdep_on_worklist > 0 &&
13467                     process_worklist_item(UFSTOVFS(ump),
13468                     ump->softdep_on_worklist, LK_NOWAIT) != 0)
13469                         stat_worklist_push += 1;
13470                 FREE_LOCK(ump);
13471         }
13472         /*
13473          * If we still need resources and there are no more worklist
13474          * entries to process to obtain them, we have to start flushing
13475          * the dirty vnodes to force the release of additional requests
13476          * to the worklist that we can then process to reap addition
13477          * resources. We walk the vnodes associated with the mount point
13478          * until we get the needed worklist requests that we can reap.
13479          *
13480          * If there are several threads all needing to clean the same
13481          * mount point, only one is allowed to walk the mount list.
13482          * When several threads all try to walk the same mount list,
13483          * they end up competing with each other and often end up in
13484          * livelock. This approach ensures that forward progress is
13485          * made at the cost of occational ENOSPC errors being returned
13486          * that might otherwise have been avoided.
13487          */
13488         error = 1;
13489         if ((resource == FLUSH_BLOCKS_WAIT && 
13490              fs->fs_cstotal.cs_nbfree <= needed) ||
13491             (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13492              fs->fs_cstotal.cs_nifree <= needed)) {
13493                 ACQUIRE_LOCK(ump);
13494                 if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13495                         ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13496                         FREE_LOCK(ump);
13497                         failed_vnode = softdep_request_cleanup_flush(mp, ump);
13498                         ACQUIRE_LOCK(ump);
13499                         ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13500                         FREE_LOCK(ump);
13501                         if (ump->softdep_on_worklist > 0) {
13502                                 stat_cleanup_retries += 1;
13503                                 if (!failed_vnode)
13504                                         goto retry;
13505                         }
13506                 } else {
13507                         FREE_LOCK(ump);
13508                         error = 0;
13509                 }
13510                 stat_cleanup_failures += 1;
13511         }
13512         if (time_second - starttime > stat_cleanup_high_delay)
13513                 stat_cleanup_high_delay = time_second - starttime;
13514         UFS_LOCK(ump);
13515         return (error);
13516 }
13517
13518 /*
13519  * Scan the vnodes for the specified mount point flushing out any
13520  * vnodes that can be locked without waiting. Finally, try to flush
13521  * the device associated with the mount point if it can be locked
13522  * without waiting.
13523  *
13524  * We return 0 if we were able to lock every vnode in our scan.
13525  * If we had to skip one or more vnodes, we return 1.
13526  */
13527 static int
13528 softdep_request_cleanup_flush(mp, ump)
13529         struct mount *mp;
13530         struct ufsmount *ump;
13531 {
13532         struct thread *td;
13533         struct vnode *lvp, *mvp;
13534         int failed_vnode;
13535
13536         failed_vnode = 0;
13537         td = curthread;
13538         MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13539                 if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13540                         VI_UNLOCK(lvp);
13541                         continue;
13542                 }
13543                 if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13544                     td) != 0) {
13545                         failed_vnode = 1;
13546                         continue;
13547                 }
13548                 if (lvp->v_vflag & VV_NOSYNC) { /* unlinked */
13549                         vput(lvp);
13550                         continue;
13551                 }
13552                 (void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13553                 vput(lvp);
13554         }
13555         lvp = ump->um_devvp;
13556         if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13557                 VOP_FSYNC(lvp, MNT_NOWAIT, td);
13558                 VOP_UNLOCK(lvp);
13559         }
13560         return (failed_vnode);
13561 }
13562
13563 static bool
13564 softdep_excess_items(struct ufsmount *ump, int item)
13565 {
13566
13567         KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13568         return (dep_current[item] > max_softdeps &&
13569             ump->softdep_curdeps[item] > max_softdeps /
13570             stat_flush_threads);
13571 }
13572
13573 static void
13574 schedule_cleanup(struct mount *mp)
13575 {
13576         struct ufsmount *ump;
13577         struct thread *td;
13578
13579         ump = VFSTOUFS(mp);
13580         LOCK_OWNED(ump);
13581         FREE_LOCK(ump);
13582         td = curthread;
13583         if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13584             (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13585                 /*
13586                  * No ast is delivered to kernel threads, so nobody
13587                  * would deref the mp.  Some kernel threads
13588                  * explicitely check for AST, e.g. NFS daemon does
13589                  * this in the serving loop.
13590                  */
13591                 return;
13592         }
13593         if (td->td_su != NULL)
13594                 vfs_rel(td->td_su);
13595         vfs_ref(mp);
13596         td->td_su = mp;
13597         thread_lock(td);
13598         td->td_flags |= TDF_ASTPENDING;
13599         thread_unlock(td);
13600 }
13601
13602 static void
13603 softdep_ast_cleanup_proc(struct thread *td)
13604 {
13605         struct mount *mp;
13606         struct ufsmount *ump;
13607         int error;
13608         bool req;
13609
13610         while ((mp = td->td_su) != NULL) {
13611                 td->td_su = NULL;
13612                 error = vfs_busy(mp, MBF_NOWAIT);
13613                 vfs_rel(mp);
13614                 if (error != 0)
13615                         return;
13616                 if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13617                         ump = VFSTOUFS(mp);
13618                         for (;;) {
13619                                 req = false;
13620                                 ACQUIRE_LOCK(ump);
13621                                 if (softdep_excess_items(ump, D_INODEDEP)) {
13622                                         req = true;
13623                                         request_cleanup(mp, FLUSH_INODES);
13624                                 }
13625                                 if (softdep_excess_items(ump, D_DIRREM)) {
13626                                         req = true;
13627                                         request_cleanup(mp, FLUSH_BLOCKS);
13628                                 }
13629                                 FREE_LOCK(ump);
13630                                 if (softdep_excess_items(ump, D_NEWBLK) ||
13631                                     softdep_excess_items(ump, D_ALLOCDIRECT) ||
13632                                     softdep_excess_items(ump, D_ALLOCINDIR)) {
13633                                         error = vn_start_write(NULL, &mp,
13634                                             V_WAIT);
13635                                         if (error == 0) {
13636                                                 req = true;
13637                                                 VFS_SYNC(mp, MNT_WAIT);
13638                                                 vn_finished_write(mp);
13639                                         }
13640                                 }
13641                                 if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
13642                                         break;
13643                         }
13644                 }
13645                 vfs_unbusy(mp);
13646         }
13647         if ((mp = td->td_su) != NULL) {
13648                 td->td_su = NULL;
13649                 vfs_rel(mp);
13650         }
13651 }
13652
13653 /*
13654  * If memory utilization has gotten too high, deliberately slow things
13655  * down and speed up the I/O processing.
13656  */
13657 static int
13658 request_cleanup(mp, resource)
13659         struct mount *mp;
13660         int resource;
13661 {
13662         struct thread *td = curthread;
13663         struct ufsmount *ump;
13664
13665         ump = VFSTOUFS(mp);
13666         LOCK_OWNED(ump);
13667         /*
13668          * We never hold up the filesystem syncer or buf daemon.
13669          */
13670         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13671                 return (0);
13672         /*
13673          * First check to see if the work list has gotten backlogged.
13674          * If it has, co-opt this process to help clean up two entries.
13675          * Because this process may hold inodes locked, we cannot
13676          * handle any remove requests that might block on a locked
13677          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13678          * to avoid recursively processing the worklist.
13679          */
13680         if (ump->softdep_on_worklist > max_softdeps / 10) {
13681                 td->td_pflags |= TDP_SOFTDEP;
13682                 process_worklist_item(mp, 2, LK_NOWAIT);
13683                 td->td_pflags &= ~TDP_SOFTDEP;
13684                 stat_worklist_push += 2;
13685                 return(1);
13686         }
13687         /*
13688          * Next, we attempt to speed up the syncer process. If that
13689          * is successful, then we allow the process to continue.
13690          */
13691         if (softdep_speedup(ump) &&
13692             resource != FLUSH_BLOCKS_WAIT &&
13693             resource != FLUSH_INODES_WAIT)
13694                 return(0);
13695         /*
13696          * If we are resource constrained on inode dependencies, try
13697          * flushing some dirty inodes. Otherwise, we are constrained
13698          * by file deletions, so try accelerating flushes of directories
13699          * with removal dependencies. We would like to do the cleanup
13700          * here, but we probably hold an inode locked at this point and 
13701          * that might deadlock against one that we try to clean. So,
13702          * the best that we can do is request the syncer daemon to do
13703          * the cleanup for us.
13704          */
13705         switch (resource) {
13706
13707         case FLUSH_INODES:
13708         case FLUSH_INODES_WAIT:
13709                 ACQUIRE_GBLLOCK(&lk);
13710                 stat_ino_limit_push += 1;
13711                 req_clear_inodedeps += 1;
13712                 FREE_GBLLOCK(&lk);
13713                 stat_countp = &stat_ino_limit_hit;
13714                 break;
13715
13716         case FLUSH_BLOCKS:
13717         case FLUSH_BLOCKS_WAIT:
13718                 ACQUIRE_GBLLOCK(&lk);
13719                 stat_blk_limit_push += 1;
13720                 req_clear_remove += 1;
13721                 FREE_GBLLOCK(&lk);
13722                 stat_countp = &stat_blk_limit_hit;
13723                 break;
13724
13725         default:
13726                 panic("request_cleanup: unknown type");
13727         }
13728         /*
13729          * Hopefully the syncer daemon will catch up and awaken us.
13730          * We wait at most tickdelay before proceeding in any case.
13731          */
13732         ACQUIRE_GBLLOCK(&lk);
13733         FREE_LOCK(ump);
13734         proc_waiting += 1;
13735         if (callout_pending(&softdep_callout) == FALSE)
13736                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13737                     pause_timer, 0);
13738
13739         if ((td->td_pflags & TDP_KTHREAD) == 0)
13740                 msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13741         proc_waiting -= 1;
13742         FREE_GBLLOCK(&lk);
13743         ACQUIRE_LOCK(ump);
13744         return (1);
13745 }
13746
13747 /*
13748  * Awaken processes pausing in request_cleanup and clear proc_waiting
13749  * to indicate that there is no longer a timer running. Pause_timer
13750  * will be called with the global softdep mutex (&lk) locked.
13751  */
13752 static void
13753 pause_timer(arg)
13754         void *arg;
13755 {
13756
13757         GBLLOCK_OWNED(&lk);
13758         /*
13759          * The callout_ API has acquired mtx and will hold it around this
13760          * function call.
13761          */
13762         *stat_countp += proc_waiting;
13763         wakeup(&proc_waiting);
13764 }
13765
13766 /*
13767  * If requested, try removing inode or removal dependencies.
13768  */
13769 static void
13770 check_clear_deps(mp)
13771         struct mount *mp;
13772 {
13773         struct ufsmount *ump;
13774         bool suj_susp;
13775
13776         /*
13777          * Tell the lower layers that any TRIM or WRITE transactions that have
13778          * been delayed for performance reasons should proceed to help alleviate
13779          * the shortage faster. The race between checking req_* and the softdep
13780          * mutex (lk) is fine since this is an advisory operation that at most
13781          * causes deferred work to be done sooner.
13782          */
13783         ump = VFSTOUFS(mp);
13784         suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
13785         if (req_clear_remove || req_clear_inodedeps || suj_susp) {
13786                 FREE_LOCK(ump);
13787                 softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
13788                 ACQUIRE_LOCK(ump);
13789         }
13790
13791         /*
13792          * If we are suspended, it may be because of our using
13793          * too many inodedeps, so help clear them out.
13794          */
13795         if (suj_susp)
13796                 clear_inodedeps(mp);
13797
13798         /*
13799          * General requests for cleanup of backed up dependencies
13800          */
13801         ACQUIRE_GBLLOCK(&lk);
13802         if (req_clear_inodedeps) {
13803                 req_clear_inodedeps -= 1;
13804                 FREE_GBLLOCK(&lk);
13805                 clear_inodedeps(mp);
13806                 ACQUIRE_GBLLOCK(&lk);
13807                 wakeup(&proc_waiting);
13808         }
13809         if (req_clear_remove) {
13810                 req_clear_remove -= 1;
13811                 FREE_GBLLOCK(&lk);
13812                 clear_remove(mp);
13813                 ACQUIRE_GBLLOCK(&lk);
13814                 wakeup(&proc_waiting);
13815         }
13816         FREE_GBLLOCK(&lk);
13817 }
13818
13819 /*
13820  * Flush out a directory with at least one removal dependency in an effort to
13821  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13822  */
13823 static void
13824 clear_remove(mp)
13825         struct mount *mp;
13826 {
13827         struct pagedep_hashhead *pagedephd;
13828         struct pagedep *pagedep;
13829         struct ufsmount *ump;
13830         struct vnode *vp;
13831         struct bufobj *bo;
13832         int error, cnt;
13833         ino_t ino;
13834
13835         ump = VFSTOUFS(mp);
13836         LOCK_OWNED(ump);
13837
13838         for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13839                 pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13840                 if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13841                         ump->pagedep_nextclean = 0;
13842                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13843                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
13844                                 continue;
13845                         ino = pagedep->pd_ino;
13846                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13847                                 continue;
13848                         FREE_LOCK(ump);
13849
13850                         /*
13851                          * Let unmount clear deps
13852                          */
13853                         error = vfs_busy(mp, MBF_NOWAIT);
13854                         if (error != 0)
13855                                 goto finish_write;
13856                         error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13857                              FFSV_FORCEINSMQ);
13858                         vfs_unbusy(mp);
13859                         if (error != 0) {
13860                                 softdep_error("clear_remove: vget", error);
13861                                 goto finish_write;
13862                         }
13863                         MPASS(VTOI(vp)->i_mode != 0);
13864                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13865                                 softdep_error("clear_remove: fsync", error);
13866                         bo = &vp->v_bufobj;
13867                         BO_LOCK(bo);
13868                         drain_output(vp);
13869                         BO_UNLOCK(bo);
13870                         vput(vp);
13871                 finish_write:
13872                         vn_finished_write(mp);
13873                         ACQUIRE_LOCK(ump);
13874                         return;
13875                 }
13876         }
13877 }
13878
13879 /*
13880  * Clear out a block of dirty inodes in an effort to reduce
13881  * the number of inodedep dependency structures.
13882  */
13883 static void
13884 clear_inodedeps(mp)
13885         struct mount *mp;
13886 {
13887         struct inodedep_hashhead *inodedephd;
13888         struct inodedep *inodedep;
13889         struct ufsmount *ump;
13890         struct vnode *vp;
13891         struct fs *fs;
13892         int error, cnt;
13893         ino_t firstino, lastino, ino;
13894
13895         ump = VFSTOUFS(mp);
13896         fs = ump->um_fs;
13897         LOCK_OWNED(ump);
13898         /*
13899          * Pick a random inode dependency to be cleared.
13900          * We will then gather up all the inodes in its block 
13901          * that have dependencies and flush them out.
13902          */
13903         for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13904                 inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13905                 if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13906                         ump->inodedep_nextclean = 0;
13907                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13908                         break;
13909         }
13910         if (inodedep == NULL)
13911                 return;
13912         /*
13913          * Find the last inode in the block with dependencies.
13914          */
13915         firstino = rounddown2(inodedep->id_ino, INOPB(fs));
13916         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13917                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13918                         break;
13919         /*
13920          * Asynchronously push all but the last inode with dependencies.
13921          * Synchronously push the last inode with dependencies to ensure
13922          * that the inode block gets written to free up the inodedeps.
13923          */
13924         for (ino = firstino; ino <= lastino; ino++) {
13925                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13926                         continue;
13927                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13928                         continue;
13929                 FREE_LOCK(ump);
13930                 error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13931                 if (error != 0) {
13932                         vn_finished_write(mp);
13933                         ACQUIRE_LOCK(ump);
13934                         return;
13935                 }
13936                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13937                     FFSV_FORCEINSMQ)) != 0) {
13938                         softdep_error("clear_inodedeps: vget", error);
13939                         vfs_unbusy(mp);
13940                         vn_finished_write(mp);
13941                         ACQUIRE_LOCK(ump);
13942                         return;
13943                 }
13944                 vfs_unbusy(mp);
13945                 if (VTOI(vp)->i_mode == 0) {
13946                         vgone(vp);
13947                 } else if (ino == lastino) {
13948                         if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13949                                 softdep_error("clear_inodedeps: fsync1", error);
13950                 } else {
13951                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13952                                 softdep_error("clear_inodedeps: fsync2", error);
13953                         BO_LOCK(&vp->v_bufobj);
13954                         drain_output(vp);
13955                         BO_UNLOCK(&vp->v_bufobj);
13956                 }
13957                 vput(vp);
13958                 vn_finished_write(mp);
13959                 ACQUIRE_LOCK(ump);
13960         }
13961 }
13962
13963 void
13964 softdep_buf_append(bp, wkhd)
13965         struct buf *bp;
13966         struct workhead *wkhd;
13967 {
13968         struct worklist *wk;
13969         struct ufsmount *ump;
13970
13971         if ((wk = LIST_FIRST(wkhd)) == NULL)
13972                 return;
13973         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13974             ("softdep_buf_append called on non-softdep filesystem"));
13975         ump = VFSTOUFS(wk->wk_mp);
13976         ACQUIRE_LOCK(ump);
13977         while ((wk = LIST_FIRST(wkhd)) != NULL) {
13978                 WORKLIST_REMOVE(wk);
13979                 WORKLIST_INSERT(&bp->b_dep, wk);
13980         }
13981         FREE_LOCK(ump);
13982
13983 }
13984
13985 void
13986 softdep_inode_append(ip, cred, wkhd)
13987         struct inode *ip;
13988         struct ucred *cred;
13989         struct workhead *wkhd;
13990 {
13991         struct buf *bp;
13992         struct fs *fs;
13993         struct ufsmount *ump;
13994         int error;
13995
13996         ump = ITOUMP(ip);
13997         KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
13998             ("softdep_inode_append called on non-softdep filesystem"));
13999         fs = ump->um_fs;
14000         error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14001             (int)fs->fs_bsize, cred, &bp);
14002         if (error) {
14003                 bqrelse(bp);
14004                 softdep_freework(wkhd);
14005                 return;
14006         }
14007         softdep_buf_append(bp, wkhd);
14008         bqrelse(bp);
14009 }
14010
14011 void
14012 softdep_freework(wkhd)
14013         struct workhead *wkhd;
14014 {
14015         struct worklist *wk;
14016         struct ufsmount *ump;
14017
14018         if ((wk = LIST_FIRST(wkhd)) == NULL)
14019                 return;
14020         KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14021             ("softdep_freework called on non-softdep filesystem"));
14022         ump = VFSTOUFS(wk->wk_mp);
14023         ACQUIRE_LOCK(ump);
14024         handle_jwork(wkhd);
14025         FREE_LOCK(ump);
14026 }
14027
14028 static struct ufsmount *
14029 softdep_bp_to_mp(bp)
14030         struct buf *bp;
14031 {
14032         struct mount *mp;
14033         struct vnode *vp;
14034
14035         if (LIST_EMPTY(&bp->b_dep))
14036                 return (NULL);
14037         vp = bp->b_vp;
14038         KASSERT(vp != NULL,
14039             ("%s, buffer with dependencies lacks vnode", __func__));
14040
14041         /*
14042          * The ump mount point is stable after we get a correct
14043          * pointer, since bp is locked and this prevents unmount from
14044          * proceeding.  But to get to it, we cannot dereference bp->b_dep
14045          * head wk_mp, because we do not yet own SU ump lock and
14046          * workitem might be freed while dereferenced.
14047          */
14048 retry:
14049         switch (vp->v_type) {
14050         case VCHR:
14051                 VI_LOCK(vp);
14052                 mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14053                 VI_UNLOCK(vp);
14054                 if (mp == NULL)
14055                         goto retry;
14056                 break;
14057         case VREG:
14058         case VDIR:
14059         case VLNK:
14060         case VFIFO:
14061         case VSOCK:
14062                 mp = vp->v_mount;
14063                 break;
14064         case VBLK:
14065                 vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14066                 /* FALLTHROUGH */
14067         case VNON:
14068         case VBAD:
14069         case VMARKER:
14070                 mp = NULL;
14071                 break;
14072         default:
14073                 vn_printf(vp, "unknown vnode type");
14074                 mp = NULL;
14075                 break;
14076         }
14077         return (VFSTOUFS(mp));
14078 }
14079
14080 /*
14081  * Function to determine if the buffer has outstanding dependencies
14082  * that will cause a roll-back if the buffer is written. If wantcount
14083  * is set, return number of dependencies, otherwise just yes or no.
14084  */
14085 static int
14086 softdep_count_dependencies(bp, wantcount)
14087         struct buf *bp;
14088         int wantcount;
14089 {
14090         struct worklist *wk;
14091         struct ufsmount *ump;
14092         struct bmsafemap *bmsafemap;
14093         struct freework *freework;
14094         struct inodedep *inodedep;
14095         struct indirdep *indirdep;
14096         struct freeblks *freeblks;
14097         struct allocindir *aip;
14098         struct pagedep *pagedep;
14099         struct dirrem *dirrem;
14100         struct newblk *newblk;
14101         struct mkdir *mkdir;
14102         struct diradd *dap;
14103         int i, retval;
14104
14105         ump = softdep_bp_to_mp(bp);
14106         if (ump == NULL)
14107                 return (0);
14108         retval = 0;
14109         ACQUIRE_LOCK(ump);
14110         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14111                 switch (wk->wk_type) {
14112
14113                 case D_INODEDEP:
14114                         inodedep = WK_INODEDEP(wk);
14115                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14116                                 /* bitmap allocation dependency */
14117                                 retval += 1;
14118                                 if (!wantcount)
14119                                         goto out;
14120                         }
14121                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14122                                 /* direct block pointer dependency */
14123                                 retval += 1;
14124                                 if (!wantcount)
14125                                         goto out;
14126                         }
14127                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14128                                 /* direct block pointer dependency */
14129                                 retval += 1;
14130                                 if (!wantcount)
14131                                         goto out;
14132                         }
14133                         if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14134                                 /* Add reference dependency. */
14135                                 retval += 1;
14136                                 if (!wantcount)
14137                                         goto out;
14138                         }
14139                         continue;
14140
14141                 case D_INDIRDEP:
14142                         indirdep = WK_INDIRDEP(wk);
14143
14144                         TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14145                                 /* indirect truncation dependency */
14146                                 retval += 1;
14147                                 if (!wantcount)
14148                                         goto out;
14149                         }
14150
14151                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14152                                 /* indirect block pointer dependency */
14153                                 retval += 1;
14154                                 if (!wantcount)
14155                                         goto out;
14156                         }
14157                         continue;
14158
14159                 case D_PAGEDEP:
14160                         pagedep = WK_PAGEDEP(wk);
14161                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14162                                 if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14163                                         /* Journal remove ref dependency. */
14164                                         retval += 1;
14165                                         if (!wantcount)
14166                                                 goto out;
14167                                 }
14168                         }
14169                         for (i = 0; i < DAHASHSZ; i++) {
14170
14171                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14172                                         /* directory entry dependency */
14173                                         retval += 1;
14174                                         if (!wantcount)
14175                                                 goto out;
14176                                 }
14177                         }
14178                         continue;
14179
14180                 case D_BMSAFEMAP:
14181                         bmsafemap = WK_BMSAFEMAP(wk);
14182                         if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14183                                 /* Add reference dependency. */
14184                                 retval += 1;
14185                                 if (!wantcount)
14186                                         goto out;
14187                         }
14188                         if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14189                                 /* Allocate block dependency. */
14190                                 retval += 1;
14191                                 if (!wantcount)
14192                                         goto out;
14193                         }
14194                         continue;
14195
14196                 case D_FREEBLKS:
14197                         freeblks = WK_FREEBLKS(wk);
14198                         if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14199                                 /* Freeblk journal dependency. */
14200                                 retval += 1;
14201                                 if (!wantcount)
14202                                         goto out;
14203                         }
14204                         continue;
14205
14206                 case D_ALLOCDIRECT:
14207                 case D_ALLOCINDIR:
14208                         newblk = WK_NEWBLK(wk);
14209                         if (newblk->nb_jnewblk) {
14210                                 /* Journal allocate dependency. */
14211                                 retval += 1;
14212                                 if (!wantcount)
14213                                         goto out;
14214                         }
14215                         continue;
14216
14217                 case D_MKDIR:
14218                         mkdir = WK_MKDIR(wk);
14219                         if (mkdir->md_jaddref) {
14220                                 /* Journal reference dependency. */
14221                                 retval += 1;
14222                                 if (!wantcount)
14223                                         goto out;
14224                         }
14225                         continue;
14226
14227                 case D_FREEWORK:
14228                 case D_FREEDEP:
14229                 case D_JSEGDEP:
14230                 case D_JSEG:
14231                 case D_SBDEP:
14232                         /* never a dependency on these blocks */
14233                         continue;
14234
14235                 default:
14236                         panic("softdep_count_dependencies: Unexpected type %s",
14237                             TYPENAME(wk->wk_type));
14238                         /* NOTREACHED */
14239                 }
14240         }
14241 out:
14242         FREE_LOCK(ump);
14243         return (retval);
14244 }
14245
14246 /*
14247  * Acquire exclusive access to a buffer.
14248  * Must be called with a locked mtx parameter.
14249  * Return acquired buffer or NULL on failure.
14250  */
14251 static struct buf *
14252 getdirtybuf(bp, lock, waitfor)
14253         struct buf *bp;
14254         struct rwlock *lock;
14255         int waitfor;
14256 {
14257         int error;
14258
14259         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14260                 if (waitfor != MNT_WAIT)
14261                         return (NULL);
14262                 error = BUF_LOCK(bp,
14263                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14264                 /*
14265                  * Even if we successfully acquire bp here, we have dropped
14266                  * lock, which may violates our guarantee.
14267                  */
14268                 if (error == 0)
14269                         BUF_UNLOCK(bp);
14270                 else if (error != ENOLCK)
14271                         panic("getdirtybuf: inconsistent lock: %d", error);
14272                 rw_wlock(lock);
14273                 return (NULL);
14274         }
14275         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14276                 if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14277                         rw_wunlock(lock);
14278                         BO_LOCK(bp->b_bufobj);
14279                         BUF_UNLOCK(bp);
14280                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14281                                 bp->b_vflags |= BV_BKGRDWAIT;
14282                                 msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14283                                        PRIBIO | PDROP, "getbuf", 0);
14284                         } else
14285                                 BO_UNLOCK(bp->b_bufobj);
14286                         rw_wlock(lock);
14287                         return (NULL);
14288                 }
14289                 BUF_UNLOCK(bp);
14290                 if (waitfor != MNT_WAIT)
14291                         return (NULL);
14292 #ifdef DEBUG_VFS_LOCKS
14293                 if (bp->b_vp->v_type != VCHR)
14294                         ASSERT_BO_WLOCKED(bp->b_bufobj);
14295 #endif
14296                 bp->b_vflags |= BV_BKGRDWAIT;
14297                 rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14298                 return (NULL);
14299         }
14300         if ((bp->b_flags & B_DELWRI) == 0) {
14301                 BUF_UNLOCK(bp);
14302                 return (NULL);
14303         }
14304         bremfree(bp);
14305         return (bp);
14306 }
14307
14308
14309 /*
14310  * Check if it is safe to suspend the file system now.  On entry,
14311  * the vnode interlock for devvp should be held.  Return 0 with
14312  * the mount interlock held if the file system can be suspended now,
14313  * otherwise return EAGAIN with the mount interlock held.
14314  */
14315 int
14316 softdep_check_suspend(struct mount *mp,
14317                       struct vnode *devvp,
14318                       int softdep_depcnt,
14319                       int softdep_accdepcnt,
14320                       int secondary_writes,
14321                       int secondary_accwrites)
14322 {
14323         struct bufobj *bo;
14324         struct ufsmount *ump;
14325         struct inodedep *inodedep;
14326         int error, unlinked;
14327
14328         bo = &devvp->v_bufobj;
14329         ASSERT_BO_WLOCKED(bo);
14330
14331         /*
14332          * If we are not running with soft updates, then we need only
14333          * deal with secondary writes as we try to suspend.
14334          */
14335         if (MOUNTEDSOFTDEP(mp) == 0) {
14336                 MNT_ILOCK(mp);
14337                 while (mp->mnt_secondary_writes != 0) {
14338                         BO_UNLOCK(bo);
14339                         msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14340                             (PUSER - 1) | PDROP, "secwr", 0);
14341                         BO_LOCK(bo);
14342                         MNT_ILOCK(mp);
14343                 }
14344
14345                 /*
14346                  * Reasons for needing more work before suspend:
14347                  * - Dirty buffers on devvp.
14348                  * - Secondary writes occurred after start of vnode sync loop
14349                  */
14350                 error = 0;
14351                 if (bo->bo_numoutput > 0 ||
14352                     bo->bo_dirty.bv_cnt > 0 ||
14353                     secondary_writes != 0 ||
14354                     mp->mnt_secondary_writes != 0 ||
14355                     secondary_accwrites != mp->mnt_secondary_accwrites)
14356                         error = EAGAIN;
14357                 BO_UNLOCK(bo);
14358                 return (error);
14359         }
14360
14361         /*
14362          * If we are running with soft updates, then we need to coordinate
14363          * with them as we try to suspend.
14364          */
14365         ump = VFSTOUFS(mp);
14366         for (;;) {
14367                 if (!TRY_ACQUIRE_LOCK(ump)) {
14368                         BO_UNLOCK(bo);
14369                         ACQUIRE_LOCK(ump);
14370                         FREE_LOCK(ump);
14371                         BO_LOCK(bo);
14372                         continue;
14373                 }
14374                 MNT_ILOCK(mp);
14375                 if (mp->mnt_secondary_writes != 0) {
14376                         FREE_LOCK(ump);
14377                         BO_UNLOCK(bo);
14378                         msleep(&mp->mnt_secondary_writes,
14379                                MNT_MTX(mp),
14380                                (PUSER - 1) | PDROP, "secwr", 0);
14381                         BO_LOCK(bo);
14382                         continue;
14383                 }
14384                 break;
14385         }
14386
14387         unlinked = 0;
14388         if (MOUNTEDSUJ(mp)) {
14389                 for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14390                     inodedep != NULL;
14391                     inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14392                         if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14393                             UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14394                             UNLINKONLIST) ||
14395                             !check_inodedep_free(inodedep))
14396                                 continue;
14397                         unlinked++;
14398                 }
14399         }
14400
14401         /*
14402          * Reasons for needing more work before suspend:
14403          * - Dirty buffers on devvp.
14404          * - Softdep activity occurred after start of vnode sync loop
14405          * - Secondary writes occurred after start of vnode sync loop
14406          */
14407         error = 0;
14408         if (bo->bo_numoutput > 0 ||
14409             bo->bo_dirty.bv_cnt > 0 ||
14410             softdep_depcnt != unlinked ||
14411             ump->softdep_deps != unlinked ||
14412             softdep_accdepcnt != ump->softdep_accdeps ||
14413             secondary_writes != 0 ||
14414             mp->mnt_secondary_writes != 0 ||
14415             secondary_accwrites != mp->mnt_secondary_accwrites)
14416                 error = EAGAIN;
14417         FREE_LOCK(ump);
14418         BO_UNLOCK(bo);
14419         return (error);
14420 }
14421
14422
14423 /*
14424  * Get the number of dependency structures for the file system, both
14425  * the current number and the total number allocated.  These will
14426  * later be used to detect that softdep processing has occurred.
14427  */
14428 void
14429 softdep_get_depcounts(struct mount *mp,
14430                       int *softdep_depsp,
14431                       int *softdep_accdepsp)
14432 {
14433         struct ufsmount *ump;
14434
14435         if (MOUNTEDSOFTDEP(mp) == 0) {
14436                 *softdep_depsp = 0;
14437                 *softdep_accdepsp = 0;
14438                 return;
14439         }
14440         ump = VFSTOUFS(mp);
14441         ACQUIRE_LOCK(ump);
14442         *softdep_depsp = ump->softdep_deps;
14443         *softdep_accdepsp = ump->softdep_accdeps;
14444         FREE_LOCK(ump);
14445 }
14446
14447 /*
14448  * Wait for pending output on a vnode to complete.
14449  */
14450 static void
14451 drain_output(vp)
14452         struct vnode *vp;
14453 {
14454
14455         ASSERT_VOP_LOCKED(vp, "drain_output");
14456         (void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14457 }
14458
14459 /*
14460  * Called whenever a buffer that is being invalidated or reallocated
14461  * contains dependencies. This should only happen if an I/O error has
14462  * occurred. The routine is called with the buffer locked.
14463  */ 
14464 static void
14465 softdep_deallocate_dependencies(bp)
14466         struct buf *bp;
14467 {
14468
14469         if ((bp->b_ioflags & BIO_ERROR) == 0)
14470                 panic("softdep_deallocate_dependencies: dangling deps");
14471         if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14472                 softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14473         else
14474                 printf("softdep_deallocate_dependencies: "
14475                     "got error %d while accessing filesystem\n", bp->b_error);
14476         if (bp->b_error != ENXIO)
14477                 panic("softdep_deallocate_dependencies: unrecovered I/O error");
14478 }
14479
14480 /*
14481  * Function to handle asynchronous write errors in the filesystem.
14482  */
14483 static void
14484 softdep_error(func, error)
14485         char *func;
14486         int error;
14487 {
14488
14489         /* XXX should do something better! */
14490         printf("%s: got error %d while accessing filesystem\n", func, error);
14491 }
14492
14493 #ifdef DDB
14494
14495 /* exported to ffs_vfsops.c */
14496 extern void db_print_ffs(struct ufsmount *ump);
14497 void
14498 db_print_ffs(struct ufsmount *ump)
14499 {
14500         db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14501             ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14502         db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14503             ump->um_fs, ump->softdep_on_worklist,
14504             ump->softdep_deps, ump->softdep_req);
14505 }
14506
14507 static void
14508 worklist_print(struct worklist *wk, int verbose)
14509 {
14510
14511         if (!verbose) {
14512                 db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14513                     (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14514                 return;
14515         }
14516         db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14517             TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14518             LIST_NEXT(wk, wk_list));
14519         db_print_ffs(VFSTOUFS(wk->wk_mp));
14520 }
14521
14522 static void
14523 inodedep_print(struct inodedep *inodedep, int verbose)
14524 {
14525
14526         worklist_print(&inodedep->id_list, 0);
14527         db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14528             inodedep->id_fs,
14529             (intmax_t)inodedep->id_ino,
14530             (intmax_t)fsbtodb(inodedep->id_fs,
14531                 ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14532             (intmax_t)inodedep->id_nlinkdelta,
14533             (intmax_t)inodedep->id_savednlink);
14534
14535         if (verbose == 0)
14536                 return;
14537
14538         db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14539             inodedep->id_bmsafemap,
14540             inodedep->id_mkdiradd,
14541             TAILQ_FIRST(&inodedep->id_inoreflst));
14542         db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14543             LIST_FIRST(&inodedep->id_dirremhd),
14544             LIST_FIRST(&inodedep->id_pendinghd),
14545             LIST_FIRST(&inodedep->id_bufwait));
14546         db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14547             LIST_FIRST(&inodedep->id_inowait),
14548             TAILQ_FIRST(&inodedep->id_inoupdt),
14549             TAILQ_FIRST(&inodedep->id_newinoupdt));
14550         db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14551             TAILQ_FIRST(&inodedep->id_extupdt),
14552             TAILQ_FIRST(&inodedep->id_newextupdt),
14553             TAILQ_FIRST(&inodedep->id_freeblklst));
14554         db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14555             inodedep->id_savedino1,
14556             (intmax_t)inodedep->id_savedsize,
14557             (intmax_t)inodedep->id_savedextsize);
14558 }
14559
14560 static void
14561 newblk_print(struct newblk *nbp)
14562 {
14563
14564         worklist_print(&nbp->nb_list, 0);
14565         db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14566         db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14567             &nbp->nb_jnewblk,
14568             &nbp->nb_bmsafemap,
14569             &nbp->nb_freefrag);
14570         db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14571             LIST_FIRST(&nbp->nb_indirdeps),
14572             LIST_FIRST(&nbp->nb_newdirblk),
14573             LIST_FIRST(&nbp->nb_jwork));
14574 }
14575
14576 static void
14577 allocdirect_print(struct allocdirect *adp)
14578 {
14579
14580         newblk_print(&adp->ad_block);
14581         db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14582             adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14583         db_printf("    offset %d, inodedep %p\n",
14584             adp->ad_offset, adp->ad_inodedep);
14585 }
14586
14587 static void
14588 allocindir_print(struct allocindir *aip)
14589 {
14590
14591         newblk_print(&aip->ai_block);
14592         db_printf("    oldblkno %jd, lbn %jd\n",
14593             (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14594         db_printf("    offset %d, indirdep %p\n",
14595             aip->ai_offset, aip->ai_indirdep);
14596 }
14597
14598 static void
14599 mkdir_print(struct mkdir *mkdir)
14600 {
14601
14602         worklist_print(&mkdir->md_list, 0);
14603         db_printf("    diradd %p, jaddref %p, buf %p\n",
14604                 mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14605 }
14606
14607 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14608 {
14609
14610         if (have_addr == 0) {
14611                 db_printf("inodedep address required\n");
14612                 return;
14613         }
14614         inodedep_print((struct inodedep*)addr, 1);
14615 }
14616
14617 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14618 {
14619         struct inodedep_hashhead *inodedephd;
14620         struct inodedep *inodedep;
14621         struct ufsmount *ump;
14622         int cnt;
14623
14624         if (have_addr == 0) {
14625                 db_printf("ufsmount address required\n");
14626                 return;
14627         }
14628         ump = (struct ufsmount *)addr;
14629         for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14630                 inodedephd = &ump->inodedep_hashtbl[cnt];
14631                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
14632                         inodedep_print(inodedep, 0);
14633                 }
14634         }
14635 }
14636
14637 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
14638 {
14639
14640         if (have_addr == 0) {
14641                 db_printf("worklist address required\n");
14642                 return;
14643         }
14644         worklist_print((struct worklist *)addr, 1);
14645 }
14646
14647 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
14648 {
14649         struct worklist *wk;
14650         struct workhead *wkhd;
14651
14652         if (have_addr == 0) {
14653                 db_printf("worklist address required "
14654                     "(for example value in bp->b_dep)\n");
14655                 return;
14656         }
14657         /*
14658          * We often do not have the address of the worklist head but
14659          * instead a pointer to its first entry (e.g., we have the
14660          * contents of bp->b_dep rather than &bp->b_dep). But the back
14661          * pointer of bp->b_dep will point at the head of the list, so
14662          * we cheat and use that instead. If we are in the middle of
14663          * a list we will still get the same result, so nothing
14664          * unexpected will result.
14665          */
14666         wk = (struct worklist *)addr;
14667         if (wk == NULL)
14668                 return;
14669         wkhd = (struct workhead *)wk->wk_list.le_prev;
14670         LIST_FOREACH(wk, wkhd, wk_list) {
14671                 switch(wk->wk_type) {
14672                 case D_INODEDEP:
14673                         inodedep_print(WK_INODEDEP(wk), 0);
14674                         continue;
14675                 case D_ALLOCDIRECT:
14676                         allocdirect_print(WK_ALLOCDIRECT(wk));
14677                         continue;
14678                 case D_ALLOCINDIR:
14679                         allocindir_print(WK_ALLOCINDIR(wk));
14680                         continue;
14681                 case D_MKDIR:
14682                         mkdir_print(WK_MKDIR(wk));
14683                         continue;
14684                 default:
14685                         worklist_print(wk, 0);
14686                         continue;
14687                 }
14688         }
14689 }
14690
14691 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
14692 {
14693         if (have_addr == 0) {
14694                 db_printf("mkdir address required\n");
14695                 return;
14696         }
14697         mkdir_print((struct mkdir *)addr);
14698 }
14699
14700 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
14701 {
14702         struct mkdirlist *mkdirlisthd;
14703         struct mkdir *mkdir;
14704
14705         if (have_addr == 0) {
14706                 db_printf("mkdir listhead address required\n");
14707                 return;
14708         }
14709         mkdirlisthd = (struct mkdirlist *)addr;
14710         LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14711                 mkdir_print(mkdir);
14712                 if (mkdir->md_diradd != NULL) {
14713                         db_printf("    ");
14714                         worklist_print(&mkdir->md_diradd->da_list, 0);
14715                 }
14716                 if (mkdir->md_jaddref != NULL) {
14717                         db_printf("    ");
14718                         worklist_print(&mkdir->md_jaddref->ja_list, 0);
14719                 }
14720         }
14721 }
14722
14723 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
14724 {
14725         if (have_addr == 0) {
14726                 db_printf("allocdirect address required\n");
14727                 return;
14728         }
14729         allocdirect_print((struct allocdirect *)addr);
14730 }
14731
14732 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
14733 {
14734         if (have_addr == 0) {
14735                 db_printf("allocindir address required\n");
14736                 return;
14737         }
14738         allocindir_print((struct allocindir *)addr);
14739 }
14740
14741 #endif /* DDB */
14742
14743 #endif /* SOFTUPDATES */