]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sys/ufs/ffs/ffs_softdep.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sys / ufs / ffs / ffs_softdep.c
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick. All Rights Reserved.
3  *
4  * The soft updates code is derived from the appendix of a University
5  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
6  * "Soft Updates: A Solution to the Metadata Update Problem in File
7  * Systems", CSE-TR-254-95, August 1995).
8  *
9  * Further information about soft updates can be obtained from:
10  *
11  *      Marshall Kirk McKusick          http://www.mckusick.com/softdep/
12  *      1614 Oxford Street              mckusick@mckusick.com
13  *      Berkeley, CA 94709-1608         +1-510-843-9542
14  *      USA
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  *
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY MARSHALL KIRK MCKUSICK ``AS IS'' AND ANY
27  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
28  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
29  * DISCLAIMED.  IN NO EVENT SHALL MARSHALL KIRK MCKUSICK BE LIABLE FOR
30  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      from: @(#)ffs_softdep.c 9.59 (McKusick) 6/21/00
39  */
40
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43
44 #include "opt_ffs.h"
45 #include "opt_ddb.h"
46
47 /*
48  * For now we want the safety net that DEBUG flags provide.
49  */
50 #ifndef DEBUG
51 #define DEBUG
52 #endif
53
54 #include <sys/param.h>
55 #include <sys/kernel.h>
56 #include <sys/systm.h>
57 #include <sys/bio.h>
58 #include <sys/buf.h>
59 #include <sys/kdb.h>
60 #include <sys/kthread.h>
61 #include <sys/lock.h>
62 #include <sys/malloc.h>
63 #include <sys/mount.h>
64 #include <sys/mutex.h>
65 #include <sys/proc.h>
66 #include <sys/stat.h>
67 #include <sys/sysctl.h>
68 #include <sys/syslog.h>
69 #include <sys/vnode.h>
70 #include <sys/conf.h>
71 #include <ufs/ufs/dir.h>
72 #include <ufs/ufs/extattr.h>
73 #include <ufs/ufs/quota.h>
74 #include <ufs/ufs/inode.h>
75 #include <ufs/ufs/ufsmount.h>
76 #include <ufs/ffs/fs.h>
77 #include <ufs/ffs/softdep.h>
78 #include <ufs/ffs/ffs_extern.h>
79 #include <ufs/ufs/ufs_extern.h>
80
81 #include <vm/vm.h>
82
83 #include <ddb/ddb.h>
84 #include "opt_quota.h"
85
86 #ifndef SOFTUPDATES
87
88 int
89 softdep_flushfiles(oldmnt, flags, td)
90         struct mount *oldmnt;
91         int flags;
92         struct thread *td;
93 {
94
95         panic("softdep_flushfiles called");
96 }
97
98 int
99 softdep_mount(devvp, mp, fs, cred)
100         struct vnode *devvp;
101         struct mount *mp;
102         struct fs *fs;
103         struct ucred *cred;
104 {
105
106         return (0);
107 }
108
109 void 
110 softdep_initialize()
111 {
112
113         return;
114 }
115
116 void
117 softdep_uninitialize()
118 {
119
120         return;
121 }
122
123 void
124 softdep_setup_inomapdep(bp, ip, newinum)
125         struct buf *bp;
126         struct inode *ip;
127         ino_t newinum;
128 {
129
130         panic("softdep_setup_inomapdep called");
131 }
132
133 void
134 softdep_setup_blkmapdep(bp, mp, newblkno)
135         struct buf *bp;
136         struct mount *mp;
137         ufs2_daddr_t newblkno;
138 {
139
140         panic("softdep_setup_blkmapdep called");
141 }
142
143 void 
144 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
145         struct inode *ip;
146         ufs_lbn_t lbn;
147         ufs2_daddr_t newblkno;
148         ufs2_daddr_t oldblkno;
149         long newsize;
150         long oldsize;
151         struct buf *bp;
152 {
153         
154         panic("softdep_setup_allocdirect called");
155 }
156
157 void 
158 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
159         struct inode *ip;
160         ufs_lbn_t lbn;
161         ufs2_daddr_t newblkno;
162         ufs2_daddr_t oldblkno;
163         long newsize;
164         long oldsize;
165         struct buf *bp;
166 {
167         
168         panic("softdep_setup_allocext called");
169 }
170
171 void
172 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
173         struct inode *ip;
174         ufs_lbn_t lbn;
175         struct buf *bp;
176         int ptrno;
177         ufs2_daddr_t newblkno;
178         ufs2_daddr_t oldblkno;
179         struct buf *nbp;
180 {
181
182         panic("softdep_setup_allocindir_page called");
183 }
184
185 void
186 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
187         struct buf *nbp;
188         struct inode *ip;
189         struct buf *bp;
190         int ptrno;
191         ufs2_daddr_t newblkno;
192 {
193
194         panic("softdep_setup_allocindir_meta called");
195 }
196
197 void
198 softdep_setup_freeblocks(ip, length, flags)
199         struct inode *ip;
200         off_t length;
201         int flags;
202 {
203         
204         panic("softdep_setup_freeblocks called");
205 }
206
207 void
208 softdep_freefile(pvp, ino, mode)
209                 struct vnode *pvp;
210                 ino_t ino;
211                 int mode;
212 {
213
214         panic("softdep_freefile called");
215 }
216
217 int 
218 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
219         struct buf *bp;
220         struct inode *dp;
221         off_t diroffset;
222         ino_t newinum;
223         struct buf *newdirbp;
224         int isnewblk;
225 {
226
227         panic("softdep_setup_directory_add called");
228 }
229
230 void 
231 softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
232         struct inode *dp;
233         caddr_t base;
234         caddr_t oldloc;
235         caddr_t newloc;
236         int entrysize;
237 {
238
239         panic("softdep_change_directoryentry_offset called");
240 }
241
242 void 
243 softdep_setup_remove(bp, dp, ip, isrmdir)
244         struct buf *bp;
245         struct inode *dp;
246         struct inode *ip;
247         int isrmdir;
248 {
249         
250         panic("softdep_setup_remove called");
251 }
252
253 void 
254 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
255         struct buf *bp;
256         struct inode *dp;
257         struct inode *ip;
258         ino_t newinum;
259         int isrmdir;
260 {
261
262         panic("softdep_setup_directory_change called");
263 }
264
265 void
266 softdep_change_linkcnt(ip)
267         struct inode *ip;
268 {
269
270         panic("softdep_change_linkcnt called");
271 }
272
273 void 
274 softdep_load_inodeblock(ip)
275         struct inode *ip;
276 {
277
278         panic("softdep_load_inodeblock called");
279 }
280
281 void 
282 softdep_update_inodeblock(ip, bp, waitfor)
283         struct inode *ip;
284         struct buf *bp;
285         int waitfor;
286 {
287
288         panic("softdep_update_inodeblock called");
289 }
290
291 int
292 softdep_fsync(vp)
293         struct vnode *vp;       /* the "in_core" copy of the inode */
294 {
295
296         return (0);
297 }
298
299 void
300 softdep_fsync_mountdev(vp)
301         struct vnode *vp;
302 {
303
304         return;
305 }
306
307 int
308 softdep_flushworklist(oldmnt, countp, td)
309         struct mount *oldmnt;
310         int *countp;
311         struct thread *td;
312 {
313
314         *countp = 0;
315         return (0);
316 }
317
318 int
319 softdep_sync_metadata(struct vnode *vp)
320 {
321
322         return (0);
323 }
324
325 int
326 softdep_slowdown(vp)
327         struct vnode *vp;
328 {
329
330         panic("softdep_slowdown called");
331 }
332
333 void
334 softdep_releasefile(ip)
335         struct inode *ip;       /* inode with the zero effective link count */
336 {
337
338         panic("softdep_releasefile called");
339 }
340
341 int
342 softdep_request_cleanup(fs, vp)
343         struct fs *fs;
344         struct vnode *vp;
345 {
346
347         return (0);
348 }
349
350 int
351 softdep_check_suspend(struct mount *mp,
352                       struct vnode *devvp,
353                       int softdep_deps,
354                       int softdep_accdeps,
355                       int secondary_writes,
356                       int secondary_accwrites)
357 {
358         struct bufobj *bo;
359         int error;
360         
361         (void) softdep_deps,
362         (void) softdep_accdeps;
363
364         ASSERT_VI_LOCKED(devvp, "softdep_check_suspend");
365         bo = &devvp->v_bufobj;
366
367         for (;;) {
368                 if (!MNT_ITRYLOCK(mp)) {
369                         VI_UNLOCK(devvp);
370                         MNT_ILOCK(mp);
371                         MNT_IUNLOCK(mp);
372                         VI_LOCK(devvp);
373                         continue;
374                 }
375                 if (mp->mnt_secondary_writes != 0) {
376                         VI_UNLOCK(devvp);
377                         msleep(&mp->mnt_secondary_writes,
378                                MNT_MTX(mp),
379                                (PUSER - 1) | PDROP, "secwr", 0);
380                         VI_LOCK(devvp);
381                         continue;
382                 }
383                 break;
384         }
385
386         /*
387          * Reasons for needing more work before suspend:
388          * - Dirty buffers on devvp.
389          * - Secondary writes occurred after start of vnode sync loop
390          */
391         error = 0;
392         if (bo->bo_numoutput > 0 ||
393             bo->bo_dirty.bv_cnt > 0 ||
394             secondary_writes != 0 ||
395             mp->mnt_secondary_writes != 0 ||
396             secondary_accwrites != mp->mnt_secondary_accwrites)
397                 error = EAGAIN;
398         VI_UNLOCK(devvp);
399         return (error);
400 }
401
402 void
403 softdep_get_depcounts(struct mount *mp,
404                       int *softdepactivep,
405                       int *softdepactiveaccp)
406 {
407         (void) mp;
408         *softdepactivep = 0;
409         *softdepactiveaccp = 0;
410 }
411
412 #else
413 /*
414  * These definitions need to be adapted to the system to which
415  * this file is being ported.
416  */
417 /*
418  * malloc types defined for the softdep system.
419  */
420 static MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
421 static MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
422 static MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
423 static MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
424 static MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
425 static MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
426 static MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
427 static MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
428 static MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
429 static MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
430 static MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
431 static MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
432 static MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
433 static MALLOC_DEFINE(M_NEWDIRBLK, "newdirblk","Unclaimed new directory block");
434 static MALLOC_DEFINE(M_SAVEDINO, "savedino","Saved inodes");
435
436 #define M_SOFTDEP_FLAGS (M_WAITOK | M_USE_RESERVE)
437
438 #define D_PAGEDEP       0
439 #define D_INODEDEP      1
440 #define D_NEWBLK        2
441 #define D_BMSAFEMAP     3
442 #define D_ALLOCDIRECT   4
443 #define D_INDIRDEP      5
444 #define D_ALLOCINDIR    6
445 #define D_FREEFRAG      7
446 #define D_FREEBLKS      8
447 #define D_FREEFILE      9
448 #define D_DIRADD        10
449 #define D_MKDIR         11
450 #define D_DIRREM        12
451 #define D_NEWDIRBLK     13
452 #define D_LAST          D_NEWDIRBLK
453
454 /* 
455  * translate from workitem type to memory type
456  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
457  */
458 static struct malloc_type *memtype[] = {
459         M_PAGEDEP,
460         M_INODEDEP,
461         M_NEWBLK,
462         M_BMSAFEMAP,
463         M_ALLOCDIRECT,
464         M_INDIRDEP,
465         M_ALLOCINDIR,
466         M_FREEFRAG,
467         M_FREEBLKS,
468         M_FREEFILE,
469         M_DIRADD,
470         M_MKDIR,
471         M_DIRREM,
472         M_NEWDIRBLK
473 };
474
475 #define DtoM(type) (memtype[type])
476
477 /*
478  * Names of malloc types.
479  */
480 #define TYPENAME(type)  \
481         ((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
482 /*
483  * End system adaptation definitions.
484  */
485
486 /*
487  * Forward declarations.
488  */
489 struct inodedep_hashhead;
490 struct newblk_hashhead;
491 struct pagedep_hashhead;
492
493 /*
494  * Internal function prototypes.
495  */
496 static  void softdep_error(char *, int);
497 static  void drain_output(struct vnode *);
498 static  struct buf *getdirtybuf(struct buf *, struct mtx *, int);
499 static  void clear_remove(struct thread *);
500 static  void clear_inodedeps(struct thread *);
501 static  int flush_pagedep_deps(struct vnode *, struct mount *,
502             struct diraddhd *);
503 static  int flush_inodedep_deps(struct mount *, ino_t);
504 static  int flush_deplist(struct allocdirectlst *, int, int *);
505 static  int handle_written_filepage(struct pagedep *, struct buf *);
506 static  void diradd_inode_written(struct diradd *, struct inodedep *);
507 static  int handle_written_inodeblock(struct inodedep *, struct buf *);
508 static  void handle_allocdirect_partdone(struct allocdirect *);
509 static  void handle_allocindir_partdone(struct allocindir *);
510 static  void initiate_write_filepage(struct pagedep *, struct buf *);
511 static  void handle_written_mkdir(struct mkdir *, int);
512 static  void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
513 static  void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
514 static  void handle_workitem_freefile(struct freefile *);
515 static  void handle_workitem_remove(struct dirrem *, struct vnode *);
516 static  struct dirrem *newdirrem(struct buf *, struct inode *,
517             struct inode *, int, struct dirrem **);
518 static  void free_diradd(struct diradd *);
519 static  void free_allocindir(struct allocindir *, struct inodedep *);
520 static  void free_newdirblk(struct newdirblk *);
521 static  int indir_trunc(struct freeblks *, ufs2_daddr_t, int, ufs_lbn_t,
522             ufs2_daddr_t *);
523 static  void deallocate_dependencies(struct buf *, struct inodedep *);
524 static  void free_allocdirect(struct allocdirectlst *,
525             struct allocdirect *, int);
526 static  int check_inode_unwritten(struct inodedep *);
527 static  int free_inodedep(struct inodedep *);
528 static  void handle_workitem_freeblocks(struct freeblks *, int);
529 static  void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
530 static  void setup_allocindir_phase2(struct buf *, struct inode *,
531             struct allocindir *);
532 static  struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
533             ufs2_daddr_t);
534 static  void handle_workitem_freefrag(struct freefrag *);
535 static  struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long);
536 static  void allocdirect_merge(struct allocdirectlst *,
537             struct allocdirect *, struct allocdirect *);
538 static  struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *);
539 static  int newblk_find(struct newblk_hashhead *, struct fs *, ufs2_daddr_t,
540             struct newblk **);
541 static  int newblk_lookup(struct fs *, ufs2_daddr_t, int, struct newblk **);
542 static  int inodedep_find(struct inodedep_hashhead *, struct fs *, ino_t,
543             struct inodedep **);
544 static  int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
545 static  int pagedep_lookup(struct inode *, ufs_lbn_t, int, struct pagedep **);
546 static  int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
547             struct mount *mp, int, struct pagedep **);
548 static  void pause_timer(void *);
549 static  int request_cleanup(struct mount *, int);
550 static  int process_worklist_item(struct mount *, int);
551 static  void add_to_worklist(struct worklist *);
552 static  void softdep_flush(void);
553 static  int softdep_speedup(void);
554
555 /*
556  * Exported softdep operations.
557  */
558 static  void softdep_disk_io_initiation(struct buf *);
559 static  void softdep_disk_write_complete(struct buf *);
560 static  void softdep_deallocate_dependencies(struct buf *);
561 static  int softdep_count_dependencies(struct buf *bp, int);
562
563 static struct mtx lk;
564 MTX_SYSINIT(softdep_lock, &lk, "Softdep Lock", MTX_DEF);
565
566 #define TRY_ACQUIRE_LOCK(lk)            mtx_trylock(lk)
567 #define ACQUIRE_LOCK(lk)                mtx_lock(lk)
568 #define FREE_LOCK(lk)                   mtx_unlock(lk)
569
570 /*
571  * Worklist queue management.
572  * These routines require that the lock be held.
573  */
574 #ifndef /* NOT */ DEBUG
575 #define WORKLIST_INSERT(head, item) do {        \
576         (item)->wk_state |= ONWORKLIST;         \
577         LIST_INSERT_HEAD(head, item, wk_list);  \
578 } while (0)
579 #define WORKLIST_REMOVE(item) do {              \
580         (item)->wk_state &= ~ONWORKLIST;        \
581         LIST_REMOVE(item, wk_list);             \
582 } while (0)
583 #else /* DEBUG */
584 static  void worklist_insert(struct workhead *, struct worklist *);
585 static  void worklist_remove(struct worklist *);
586
587 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
588 #define WORKLIST_REMOVE(item) worklist_remove(item)
589
590 static void
591 worklist_insert(head, item)
592         struct workhead *head;
593         struct worklist *item;
594 {
595
596         mtx_assert(&lk, MA_OWNED);
597         if (item->wk_state & ONWORKLIST)
598                 panic("worklist_insert: already on list");
599         item->wk_state |= ONWORKLIST;
600         LIST_INSERT_HEAD(head, item, wk_list);
601 }
602
603 static void
604 worklist_remove(item)
605         struct worklist *item;
606 {
607
608         mtx_assert(&lk, MA_OWNED);
609         if ((item->wk_state & ONWORKLIST) == 0)
610                 panic("worklist_remove: not on list");
611         item->wk_state &= ~ONWORKLIST;
612         LIST_REMOVE(item, wk_list);
613 }
614 #endif /* DEBUG */
615
616 /*
617  * Routines for tracking and managing workitems.
618  */
619 static  void workitem_free(struct worklist *, int);
620 static  void workitem_alloc(struct worklist *, int, struct mount *);
621
622 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)(item), (type))
623
624 static void
625 workitem_free(item, type)
626         struct worklist *item;
627         int type;
628 {
629         struct ufsmount *ump;
630         mtx_assert(&lk, MA_OWNED);
631
632 #ifdef DEBUG
633         if (item->wk_state & ONWORKLIST)
634                 panic("workitem_free: still on list");
635         if (item->wk_type != type)
636                 panic("workitem_free: type mismatch");
637 #endif
638         ump = VFSTOUFS(item->wk_mp);
639         if (--ump->softdep_deps == 0 && ump->softdep_req)
640                 wakeup(&ump->softdep_deps);
641         FREE(item, DtoM(type));
642 }
643
644 static void
645 workitem_alloc(item, type, mp)
646         struct worklist *item;
647         int type;
648         struct mount *mp;
649 {
650         item->wk_type = type;
651         item->wk_mp = mp;
652         item->wk_state = 0;
653         ACQUIRE_LOCK(&lk);
654         VFSTOUFS(mp)->softdep_deps++;
655         VFSTOUFS(mp)->softdep_accdeps++;
656         FREE_LOCK(&lk);
657 }
658
659 /*
660  * Workitem queue management
661  */
662 static int max_softdeps;        /* maximum number of structs before slowdown */
663 static int maxindirdeps = 50;   /* max number of indirdeps before slowdown */
664 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
665 static int proc_waiting;        /* tracks whether we have a timeout posted */
666 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
667 static struct callout softdep_callout;
668 static int req_pending;
669 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
670 #define FLUSH_INODES            1
671 static int req_clear_remove;    /* syncer process flush some freeblks */
672 #define FLUSH_REMOVE            2
673 #define FLUSH_REMOVE_WAIT       3
674 /*
675  * runtime statistics
676  */
677 static int stat_worklist_push;  /* number of worklist cleanups */
678 static int stat_blk_limit_push; /* number of times block limit neared */
679 static int stat_ino_limit_push; /* number of times inode limit neared */
680 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
681 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
682 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
683 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
684 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
685 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
686 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
687
688 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0, "");
689 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0, "");
690 SYSCTL_INT(_debug, OID_AUTO, maxindirdeps, CTLFLAG_RW, &maxindirdeps, 0, "");
691 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,"");
692 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,"");
693 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,"");
694 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0, "");
695 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0, "");
696 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0, "");
697 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0, "");
698 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0, "");
699 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0, "");
700 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0, "");
701 /* SYSCTL_INT(_debug, OID_AUTO, worklist_num, CTLFLAG_RD, &softdep_on_worklist, 0, ""); */
702
703 SYSCTL_DECL(_vfs_ffs);
704
705 static int compute_summary_at_mount = 0;        /* Whether to recompute the summary at mount time */
706 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
707            &compute_summary_at_mount, 0, "Recompute summary at mount");
708
709 static struct proc *softdepproc;
710 static struct kproc_desc softdep_kp = {
711         "softdepflush",
712         softdep_flush,
713         &softdepproc
714 };
715 SYSINIT(sdproc, SI_SUB_KTHREAD_UPDATE, SI_ORDER_ANY, kproc_start,
716     &softdep_kp);
717
718 static void
719 softdep_flush(void)
720 {
721         struct mount *nmp;
722         struct mount *mp;
723         struct ufsmount *ump;
724         struct thread *td;
725         int remaining;
726         int vfslocked;
727
728         td = curthread;
729         td->td_pflags |= TDP_NORUNNINGBUF;
730
731         for (;;) {      
732                 kthread_suspend_check(softdepproc);
733                 vfslocked = VFS_LOCK_GIANT((struct mount *)NULL);
734                 ACQUIRE_LOCK(&lk);
735                 /*
736                  * If requested, try removing inode or removal dependencies.
737                  */
738                 if (req_clear_inodedeps) {
739                         clear_inodedeps(td);
740                         req_clear_inodedeps -= 1;
741                         wakeup_one(&proc_waiting);
742                 }
743                 if (req_clear_remove) {
744                         clear_remove(td);
745                         req_clear_remove -= 1;
746                         wakeup_one(&proc_waiting);
747                 }
748                 FREE_LOCK(&lk);
749                 VFS_UNLOCK_GIANT(vfslocked);
750                 remaining = 0;
751                 mtx_lock(&mountlist_mtx);
752                 for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp)  {
753                         nmp = TAILQ_NEXT(mp, mnt_list);
754                         if ((mp->mnt_flag & MNT_SOFTDEP) == 0)
755                                 continue;
756                         if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
757                                 continue;
758                         vfslocked = VFS_LOCK_GIANT(mp);
759                         softdep_process_worklist(mp, 0);
760                         ump = VFSTOUFS(mp);
761                         remaining += ump->softdep_on_worklist -
762                                 ump->softdep_on_worklist_inprogress;
763                         VFS_UNLOCK_GIANT(vfslocked);
764                         mtx_lock(&mountlist_mtx);
765                         nmp = TAILQ_NEXT(mp, mnt_list);
766                         vfs_unbusy(mp, td);
767                 }
768                 mtx_unlock(&mountlist_mtx);
769                 if (remaining)
770                         continue;
771                 ACQUIRE_LOCK(&lk);
772                 if (!req_pending)
773                         msleep(&req_pending, &lk, PVM, "sdflush", hz);
774                 req_pending = 0;
775                 FREE_LOCK(&lk);
776         }
777 }
778
779 static int
780 softdep_speedup(void)
781 {
782
783         mtx_assert(&lk, MA_OWNED);
784         if (req_pending == 0) {
785                 req_pending = 1;
786                 wakeup(&req_pending);
787         }
788
789         return speedup_syncer();
790 }
791
792 /*
793  * Add an item to the end of the work queue.
794  * This routine requires that the lock be held.
795  * This is the only routine that adds items to the list.
796  * The following routine is the only one that removes items
797  * and does so in order from first to last.
798  */
799 static void
800 add_to_worklist(wk)
801         struct worklist *wk;
802 {
803         struct ufsmount *ump;
804
805         mtx_assert(&lk, MA_OWNED);
806         ump = VFSTOUFS(wk->wk_mp);
807         if (wk->wk_state & ONWORKLIST)
808                 panic("add_to_worklist: already on list");
809         wk->wk_state |= ONWORKLIST;
810         if (LIST_EMPTY(&ump->softdep_workitem_pending))
811                 LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
812         else
813                 LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
814         ump->softdep_worklist_tail = wk;
815         ump->softdep_on_worklist += 1;
816 }
817
818 /*
819  * Process that runs once per second to handle items in the background queue.
820  *
821  * Note that we ensure that everything is done in the order in which they
822  * appear in the queue. The code below depends on this property to ensure
823  * that blocks of a file are freed before the inode itself is freed. This
824  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
825  * until all the old ones have been purged from the dependency lists.
826  */
827 int 
828 softdep_process_worklist(mp, full)
829         struct mount *mp;
830         int full;
831 {
832         struct thread *td = curthread;
833         int cnt, matchcnt, loopcount;
834         struct ufsmount *ump;
835         long starttime;
836
837         KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
838         /*
839          * Record the process identifier of our caller so that we can give
840          * this process preferential treatment in request_cleanup below.
841          */
842         matchcnt = 0;
843         ump = VFSTOUFS(mp);
844         ACQUIRE_LOCK(&lk);
845         loopcount = 1;
846         starttime = time_second;
847         while (ump->softdep_on_worklist > 0) {
848                 if ((cnt = process_worklist_item(mp, 0)) == -1)
849                         break;
850                 else
851                         matchcnt += cnt;
852                 /*
853                  * If requested, try removing inode or removal dependencies.
854                  */
855                 if (req_clear_inodedeps) {
856                         clear_inodedeps(td);
857                         req_clear_inodedeps -= 1;
858                         wakeup_one(&proc_waiting);
859                 }
860                 if (req_clear_remove) {
861                         clear_remove(td);
862                         req_clear_remove -= 1;
863                         wakeup_one(&proc_waiting);
864                 }
865                 /*
866                  * We do not generally want to stop for buffer space, but if
867                  * we are really being a buffer hog, we will stop and wait.
868                  */
869                 if (loopcount++ % 128 == 0) {
870                         FREE_LOCK(&lk);
871                         uio_yield();
872                         bwillwrite();
873                         ACQUIRE_LOCK(&lk);
874                 }
875                 /*
876                  * Never allow processing to run for more than one
877                  * second. Otherwise the other mountpoints may get
878                  * excessively backlogged.
879                  */
880                 if (!full && starttime != time_second) {
881                         matchcnt = -1;
882                         break;
883                 }
884         }
885         FREE_LOCK(&lk);
886         return (matchcnt);
887 }
888
889 /*
890  * Process one item on the worklist.
891  */
892 static int
893 process_worklist_item(mp, flags)
894         struct mount *mp;
895         int flags;
896 {
897         struct worklist *wk, *wkend;
898         struct ufsmount *ump;
899         struct vnode *vp;
900         int matchcnt = 0;
901
902         mtx_assert(&lk, MA_OWNED);
903         KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
904         /*
905          * If we are being called because of a process doing a
906          * copy-on-write, then it is not safe to write as we may
907          * recurse into the copy-on-write routine.
908          */
909         if (curthread->td_pflags & TDP_COWINPROGRESS)
910                 return (-1);
911         /*
912          * Normally we just process each item on the worklist in order.
913          * However, if we are in a situation where we cannot lock any
914          * inodes, we have to skip over any dirrem requests whose
915          * vnodes are resident and locked.
916          */
917         ump = VFSTOUFS(mp);
918         vp = NULL;
919         LIST_FOREACH(wk, &ump->softdep_workitem_pending, wk_list) {
920                 if (wk->wk_state & INPROGRESS)
921                         continue;
922                 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
923                         break;
924                 wk->wk_state |= INPROGRESS;
925                 ump->softdep_on_worklist_inprogress++;
926                 FREE_LOCK(&lk);
927                 ffs_vgetf(mp, WK_DIRREM(wk)->dm_oldinum,
928                     LK_NOWAIT | LK_EXCLUSIVE, &vp, FFSV_FORCEINSMQ);
929                 ACQUIRE_LOCK(&lk);
930                 wk->wk_state &= ~INPROGRESS;
931                 ump->softdep_on_worklist_inprogress--;
932                 if (vp != NULL)
933                         break;
934         }
935         if (wk == 0)
936                 return (-1);
937         /*
938          * Remove the item to be processed. If we are removing the last
939          * item on the list, we need to recalculate the tail pointer.
940          * As this happens rarely and usually when the list is short,
941          * we just run down the list to find it rather than tracking it
942          * in the above loop.
943          */
944         WORKLIST_REMOVE(wk);
945         if (wk == ump->softdep_worklist_tail) {
946                 LIST_FOREACH(wkend, &ump->softdep_workitem_pending, wk_list)
947                         if (LIST_NEXT(wkend, wk_list) == NULL)
948                                 break;
949                 ump->softdep_worklist_tail = wkend;
950         }
951         ump->softdep_on_worklist -= 1;
952         FREE_LOCK(&lk);
953         if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
954                 panic("process_worklist_item: suspended filesystem");
955         matchcnt++;
956         switch (wk->wk_type) {
957
958         case D_DIRREM:
959                 /* removal of a directory entry */
960                 handle_workitem_remove(WK_DIRREM(wk), vp);
961                 break;
962
963         case D_FREEBLKS:
964                 /* releasing blocks and/or fragments from a file */
965                 handle_workitem_freeblocks(WK_FREEBLKS(wk), flags & LK_NOWAIT);
966                 break;
967
968         case D_FREEFRAG:
969                 /* releasing a fragment when replaced as a file grows */
970                 handle_workitem_freefrag(WK_FREEFRAG(wk));
971                 break;
972
973         case D_FREEFILE:
974                 /* releasing an inode when its link count drops to 0 */
975                 handle_workitem_freefile(WK_FREEFILE(wk));
976                 break;
977
978         default:
979                 panic("%s_process_worklist: Unknown type %s",
980                     "softdep", TYPENAME(wk->wk_type));
981                 /* NOTREACHED */
982         }
983         vn_finished_secondary_write(mp);
984         ACQUIRE_LOCK(&lk);
985         return (matchcnt);
986 }
987
988 /*
989  * Move dependencies from one buffer to another.
990  */
991 void
992 softdep_move_dependencies(oldbp, newbp)
993         struct buf *oldbp;
994         struct buf *newbp;
995 {
996         struct worklist *wk, *wktail;
997
998         if (!LIST_EMPTY(&newbp->b_dep))
999                 panic("softdep_move_dependencies: need merge code");
1000         wktail = 0;
1001         ACQUIRE_LOCK(&lk);
1002         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1003                 LIST_REMOVE(wk, wk_list);
1004                 if (wktail == 0)
1005                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1006                 else
1007                         LIST_INSERT_AFTER(wktail, wk, wk_list);
1008                 wktail = wk;
1009         }
1010         FREE_LOCK(&lk);
1011 }
1012
1013 /*
1014  * Purge the work list of all items associated with a particular mount point.
1015  */
1016 int
1017 softdep_flushworklist(oldmnt, countp, td)
1018         struct mount *oldmnt;
1019         int *countp;
1020         struct thread *td;
1021 {
1022         struct vnode *devvp;
1023         int count, error = 0;
1024         struct ufsmount *ump;
1025
1026         /*
1027          * Alternately flush the block device associated with the mount
1028          * point and process any dependencies that the flushing
1029          * creates. We continue until no more worklist dependencies
1030          * are found.
1031          */
1032         *countp = 0;
1033         ump = VFSTOUFS(oldmnt);
1034         devvp = ump->um_devvp;
1035         while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1036                 *countp += count;
1037                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY, td);
1038                 error = VOP_FSYNC(devvp, MNT_WAIT, td);
1039                 VOP_UNLOCK(devvp, 0, td);
1040                 if (error)
1041                         break;
1042         }
1043         return (error);
1044 }
1045
1046 int
1047 softdep_waitidle(struct mount *mp)
1048 {
1049         struct ufsmount *ump;
1050         int error;
1051         int i;
1052
1053         ump = VFSTOUFS(mp);
1054         ACQUIRE_LOCK(&lk);
1055         for (i = 0; i < 10 && ump->softdep_deps; i++) {
1056                 ump->softdep_req = 1;
1057                 if (ump->softdep_on_worklist)
1058                         panic("softdep_waitidle: work added after flush.");
1059                 msleep(&ump->softdep_deps, &lk, PVM, "softdeps", 1);
1060         }
1061         ump->softdep_req = 0;
1062         FREE_LOCK(&lk);
1063         error = 0;
1064         if (i == 10) {
1065                 error = EBUSY;
1066                 printf("softdep_waitidle: Failed to flush worklist for %p\n",
1067                     mp);
1068         }
1069
1070         return (error);
1071 }
1072
1073 /*
1074  * Flush all vnodes and worklist items associated with a specified mount point.
1075  */
1076 int
1077 softdep_flushfiles(oldmnt, flags, td)
1078         struct mount *oldmnt;
1079         int flags;
1080         struct thread *td;
1081 {
1082         int error, depcount, loopcnt, retry_flush_count, retry;
1083
1084         loopcnt = 10;
1085         retry_flush_count = 3;
1086 retry_flush:
1087         error = 0;
1088
1089         /*
1090          * Alternately flush the vnodes associated with the mount
1091          * point and process any dependencies that the flushing
1092          * creates. In theory, this loop can happen at most twice,
1093          * but we give it a few extra just to be sure.
1094          */
1095         for (; loopcnt > 0; loopcnt--) {
1096                 /*
1097                  * Do another flush in case any vnodes were brought in
1098                  * as part of the cleanup operations.
1099                  */
1100                 if ((error = ffs_flushfiles(oldmnt, flags, td)) != 0)
1101                         break;
1102                 if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1103                     depcount == 0)
1104                         break;
1105         }
1106         /*
1107          * If we are unmounting then it is an error to fail. If we
1108          * are simply trying to downgrade to read-only, then filesystem
1109          * activity can keep us busy forever, so we just fail with EBUSY.
1110          */
1111         if (loopcnt == 0) {
1112                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
1113                         panic("softdep_flushfiles: looping");
1114                 error = EBUSY;
1115         }
1116         if (!error)
1117                 error = softdep_waitidle(oldmnt);
1118         if (!error) {
1119                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
1120                         retry = 0;
1121                         MNT_ILOCK(oldmnt);
1122                         KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
1123                             ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
1124                         if (oldmnt->mnt_nvnodelistsize > 0) {
1125                                 if (--retry_flush_count > 0) {
1126                                         retry = 1;
1127                                         loopcnt = 3;
1128                                 } else
1129                                         error = EBUSY;
1130                         }
1131                         MNT_IUNLOCK(oldmnt);
1132                         if (retry)
1133                                 goto retry_flush;
1134                 }
1135         }
1136         return (error);
1137 }
1138
1139 /*
1140  * Structure hashing.
1141  * 
1142  * There are three types of structures that can be looked up:
1143  *      1) pagedep structures identified by mount point, inode number,
1144  *         and logical block.
1145  *      2) inodedep structures identified by mount point and inode number.
1146  *      3) newblk structures identified by mount point and
1147  *         physical block number.
1148  *
1149  * The "pagedep" and "inodedep" dependency structures are hashed
1150  * separately from the file blocks and inodes to which they correspond.
1151  * This separation helps when the in-memory copy of an inode or
1152  * file block must be replaced. It also obviates the need to access
1153  * an inode or file page when simply updating (or de-allocating)
1154  * dependency structures. Lookup of newblk structures is needed to
1155  * find newly allocated blocks when trying to associate them with
1156  * their allocdirect or allocindir structure.
1157  *
1158  * The lookup routines optionally create and hash a new instance when
1159  * an existing entry is not found.
1160  */
1161 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
1162 #define NODELAY         0x0002  /* cannot do background work */
1163
1164 /*
1165  * Structures and routines associated with pagedep caching.
1166  */
1167 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
1168 u_long  pagedep_hash;           /* size of hash table - 1 */
1169 #define PAGEDEP_HASH(mp, inum, lbn) \
1170         (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
1171             pagedep_hash])
1172
1173 static int
1174 pagedep_find(pagedephd, ino, lbn, mp, flags, pagedeppp)
1175         struct pagedep_hashhead *pagedephd;
1176         ino_t ino;
1177         ufs_lbn_t lbn;
1178         struct mount *mp;
1179         int flags;
1180         struct pagedep **pagedeppp;
1181 {
1182         struct pagedep *pagedep;
1183
1184         LIST_FOREACH(pagedep, pagedephd, pd_hash)
1185                 if (ino == pagedep->pd_ino &&
1186                     lbn == pagedep->pd_lbn &&
1187                     mp == pagedep->pd_list.wk_mp)
1188                         break;
1189         if (pagedep) {
1190                 *pagedeppp = pagedep;
1191                 if ((flags & DEPALLOC) != 0 &&
1192                     (pagedep->pd_state & ONWORKLIST) == 0)
1193                         return (0);
1194                 return (1);
1195         }
1196         *pagedeppp = NULL;
1197         return (0);
1198 }
1199 /*
1200  * Look up a pagedep. Return 1 if found, 0 if not found or found
1201  * when asked to allocate but not associated with any buffer.
1202  * If not found, allocate if DEPALLOC flag is passed.
1203  * Found or allocated entry is returned in pagedeppp.
1204  * This routine must be called with splbio interrupts blocked.
1205  */
1206 static int
1207 pagedep_lookup(ip, lbn, flags, pagedeppp)
1208         struct inode *ip;
1209         ufs_lbn_t lbn;
1210         int flags;
1211         struct pagedep **pagedeppp;
1212 {
1213         struct pagedep *pagedep;
1214         struct pagedep_hashhead *pagedephd;
1215         struct mount *mp;
1216         int ret;
1217         int i;
1218
1219         mtx_assert(&lk, MA_OWNED);
1220         mp = ITOV(ip)->v_mount;
1221         pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
1222
1223         ret = pagedep_find(pagedephd, ip->i_number, lbn, mp, flags, pagedeppp);
1224         if (*pagedeppp || (flags & DEPALLOC) == 0)
1225                 return (ret);
1226         FREE_LOCK(&lk);
1227         MALLOC(pagedep, struct pagedep *, sizeof(struct pagedep),
1228             M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
1229         workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
1230         ACQUIRE_LOCK(&lk);
1231         ret = pagedep_find(pagedephd, ip->i_number, lbn, mp, flags, pagedeppp);
1232         if (*pagedeppp) {
1233                 WORKITEM_FREE(pagedep, D_PAGEDEP);
1234                 return (ret);
1235         }
1236         pagedep->pd_ino = ip->i_number;
1237         pagedep->pd_lbn = lbn;
1238         LIST_INIT(&pagedep->pd_dirremhd);
1239         LIST_INIT(&pagedep->pd_pendinghd);
1240         for (i = 0; i < DAHASHSZ; i++)
1241                 LIST_INIT(&pagedep->pd_diraddhd[i]);
1242         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
1243         *pagedeppp = pagedep;
1244         return (0);
1245 }
1246
1247 /*
1248  * Structures and routines associated with inodedep caching.
1249  */
1250 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
1251 static u_long   inodedep_hash;  /* size of hash table - 1 */
1252 static long     num_inodedep;   /* number of inodedep allocated */
1253 #define INODEDEP_HASH(fs, inum) \
1254       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
1255
1256 static int
1257 inodedep_find(inodedephd, fs, inum, inodedeppp)
1258         struct inodedep_hashhead *inodedephd;
1259         struct fs *fs;
1260         ino_t inum;
1261         struct inodedep **inodedeppp;
1262 {
1263         struct inodedep *inodedep;
1264
1265         LIST_FOREACH(inodedep, inodedephd, id_hash)
1266                 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
1267                         break;
1268         if (inodedep) {
1269                 *inodedeppp = inodedep;
1270                 return (1);
1271         }
1272         *inodedeppp = NULL;
1273
1274         return (0);
1275 }
1276 /*
1277  * Look up an inodedep. Return 1 if found, 0 if not found.
1278  * If not found, allocate if DEPALLOC flag is passed.
1279  * Found or allocated entry is returned in inodedeppp.
1280  * This routine must be called with splbio interrupts blocked.
1281  */
1282 static int
1283 inodedep_lookup(mp, inum, flags, inodedeppp)
1284         struct mount *mp;
1285         ino_t inum;
1286         int flags;
1287         struct inodedep **inodedeppp;
1288 {
1289         struct inodedep *inodedep;
1290         struct inodedep_hashhead *inodedephd;
1291         struct fs *fs;
1292
1293         mtx_assert(&lk, MA_OWNED);
1294         fs = VFSTOUFS(mp)->um_fs;
1295         inodedephd = INODEDEP_HASH(fs, inum);
1296
1297         if (inodedep_find(inodedephd, fs, inum, inodedeppp))
1298                 return (1);
1299         if ((flags & DEPALLOC) == 0)
1300                 return (0);
1301         /*
1302          * If we are over our limit, try to improve the situation.
1303          */
1304         if (num_inodedep > max_softdeps && (flags & NODELAY) == 0)
1305                 request_cleanup(mp, FLUSH_INODES);
1306         FREE_LOCK(&lk);
1307         MALLOC(inodedep, struct inodedep *, sizeof(struct inodedep),
1308                 M_INODEDEP, M_SOFTDEP_FLAGS);
1309         workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
1310         ACQUIRE_LOCK(&lk);
1311         if (inodedep_find(inodedephd, fs, inum, inodedeppp)) {
1312                 WORKITEM_FREE(inodedep, D_INODEDEP);
1313                 return (1);
1314         }
1315         num_inodedep += 1;
1316         inodedep->id_fs = fs;
1317         inodedep->id_ino = inum;
1318         inodedep->id_state = ALLCOMPLETE;
1319         inodedep->id_nlinkdelta = 0;
1320         inodedep->id_savedino1 = NULL;
1321         inodedep->id_savedsize = -1;
1322         inodedep->id_savedextsize = -1;
1323         inodedep->id_buf = NULL;
1324         LIST_INIT(&inodedep->id_pendinghd);
1325         LIST_INIT(&inodedep->id_inowait);
1326         LIST_INIT(&inodedep->id_bufwait);
1327         TAILQ_INIT(&inodedep->id_inoupdt);
1328         TAILQ_INIT(&inodedep->id_newinoupdt);
1329         TAILQ_INIT(&inodedep->id_extupdt);
1330         TAILQ_INIT(&inodedep->id_newextupdt);
1331         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
1332         *inodedeppp = inodedep;
1333         return (0);
1334 }
1335
1336 /*
1337  * Structures and routines associated with newblk caching.
1338  */
1339 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
1340 u_long  newblk_hash;            /* size of hash table - 1 */
1341 #define NEWBLK_HASH(fs, inum) \
1342         (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
1343
1344 static int
1345 newblk_find(newblkhd, fs, newblkno, newblkpp)
1346         struct newblk_hashhead *newblkhd;
1347         struct fs *fs;
1348         ufs2_daddr_t newblkno;
1349         struct newblk **newblkpp;
1350 {
1351         struct newblk *newblk;
1352
1353         LIST_FOREACH(newblk, newblkhd, nb_hash)
1354                 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
1355                         break;
1356         if (newblk) {
1357                 *newblkpp = newblk;
1358                 return (1);
1359         }
1360         *newblkpp = NULL;
1361         return (0);
1362 }
1363
1364 /*
1365  * Look up a newblk. Return 1 if found, 0 if not found.
1366  * If not found, allocate if DEPALLOC flag is passed.
1367  * Found or allocated entry is returned in newblkpp.
1368  */
1369 static int
1370 newblk_lookup(fs, newblkno, flags, newblkpp)
1371         struct fs *fs;
1372         ufs2_daddr_t newblkno;
1373         int flags;
1374         struct newblk **newblkpp;
1375 {
1376         struct newblk *newblk;
1377         struct newblk_hashhead *newblkhd;
1378
1379         newblkhd = NEWBLK_HASH(fs, newblkno);
1380         if (newblk_find(newblkhd, fs, newblkno, newblkpp))
1381                 return (1);
1382         if ((flags & DEPALLOC) == 0)
1383                 return (0);
1384         FREE_LOCK(&lk);
1385         MALLOC(newblk, struct newblk *, sizeof(struct newblk),
1386                 M_NEWBLK, M_SOFTDEP_FLAGS);
1387         ACQUIRE_LOCK(&lk);
1388         if (newblk_find(newblkhd, fs, newblkno, newblkpp)) {
1389                 FREE(newblk, M_NEWBLK);
1390                 return (1);
1391         }
1392         newblk->nb_state = 0;
1393         newblk->nb_fs = fs;
1394         newblk->nb_newblkno = newblkno;
1395         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1396         *newblkpp = newblk;
1397         return (0);
1398 }
1399
1400 /*
1401  * Executed during filesystem system initialization before
1402  * mounting any filesystems.
1403  */
1404 void 
1405 softdep_initialize()
1406 {
1407
1408         LIST_INIT(&mkdirlisthd);
1409         max_softdeps = desiredvnodes * 4;
1410         pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1411             &pagedep_hash);
1412         inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1413         newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1414
1415         /* initialise bioops hack */
1416         bioops.io_start = softdep_disk_io_initiation;
1417         bioops.io_complete = softdep_disk_write_complete;
1418         bioops.io_deallocate = softdep_deallocate_dependencies;
1419         bioops.io_countdeps = softdep_count_dependencies;
1420
1421         /* Initialize the callout with an mtx. */
1422         callout_init_mtx(&softdep_callout, &lk, 0);
1423 }
1424
1425 /*
1426  * Executed after all filesystems have been unmounted during
1427  * filesystem module unload.
1428  */
1429 void
1430 softdep_uninitialize()
1431 {
1432
1433         callout_drain(&softdep_callout);
1434         hashdestroy(pagedep_hashtbl, M_PAGEDEP, pagedep_hash);
1435         hashdestroy(inodedep_hashtbl, M_INODEDEP, inodedep_hash);
1436         hashdestroy(newblk_hashtbl, M_NEWBLK, newblk_hash);
1437 }
1438
1439 /*
1440  * Called at mount time to notify the dependency code that a
1441  * filesystem wishes to use it.
1442  */
1443 int
1444 softdep_mount(devvp, mp, fs, cred)
1445         struct vnode *devvp;
1446         struct mount *mp;
1447         struct fs *fs;
1448         struct ucred *cred;
1449 {
1450         struct csum_total cstotal;
1451         struct ufsmount *ump;
1452         struct cg *cgp;
1453         struct buf *bp;
1454         int error, cyl;
1455
1456         MNT_ILOCK(mp);
1457         mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
1458         if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
1459                 mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) | 
1460                         MNTK_SOFTDEP;
1461                 mp->mnt_noasync++;
1462         }
1463         MNT_IUNLOCK(mp);
1464         ump = VFSTOUFS(mp);
1465         LIST_INIT(&ump->softdep_workitem_pending);
1466         ump->softdep_worklist_tail = NULL;
1467         ump->softdep_on_worklist = 0;
1468         ump->softdep_deps = 0;
1469         /*
1470          * When doing soft updates, the counters in the
1471          * superblock may have gotten out of sync. Recomputation
1472          * can take a long time and can be deferred for background
1473          * fsck.  However, the old behavior of scanning the cylinder
1474          * groups and recalculating them at mount time is available
1475          * by setting vfs.ffs.compute_summary_at_mount to one.
1476          */
1477         if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
1478                 return (0);
1479         bzero(&cstotal, sizeof cstotal);
1480         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1481                 if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
1482                     fs->fs_cgsize, cred, &bp)) != 0) {
1483                         brelse(bp);
1484                         return (error);
1485                 }
1486                 cgp = (struct cg *)bp->b_data;
1487                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1488                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1489                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1490                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1491                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1492                 brelse(bp);
1493         }
1494 #ifdef DEBUG
1495         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1496                 printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
1497 #endif
1498         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1499         return (0);
1500 }
1501
1502 /*
1503  * Protecting the freemaps (or bitmaps).
1504  * 
1505  * To eliminate the need to execute fsck before mounting a filesystem
1506  * after a power failure, one must (conservatively) guarantee that the
1507  * on-disk copy of the bitmaps never indicate that a live inode or block is
1508  * free.  So, when a block or inode is allocated, the bitmap should be
1509  * updated (on disk) before any new pointers.  When a block or inode is
1510  * freed, the bitmap should not be updated until all pointers have been
1511  * reset.  The latter dependency is handled by the delayed de-allocation
1512  * approach described below for block and inode de-allocation.  The former
1513  * dependency is handled by calling the following procedure when a block or
1514  * inode is allocated. When an inode is allocated an "inodedep" is created
1515  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1516  * Each "inodedep" is also inserted into the hash indexing structure so
1517  * that any additional link additions can be made dependent on the inode
1518  * allocation.
1519  * 
1520  * The ufs filesystem maintains a number of free block counts (e.g., per
1521  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1522  * in addition to the bitmaps.  These counts are used to improve efficiency
1523  * during allocation and therefore must be consistent with the bitmaps.
1524  * There is no convenient way to guarantee post-crash consistency of these
1525  * counts with simple update ordering, for two main reasons: (1) The counts
1526  * and bitmaps for a single cylinder group block are not in the same disk
1527  * sector.  If a disk write is interrupted (e.g., by power failure), one may
1528  * be written and the other not.  (2) Some of the counts are located in the
1529  * superblock rather than the cylinder group block. So, we focus our soft
1530  * updates implementation on protecting the bitmaps. When mounting a
1531  * filesystem, we recompute the auxiliary counts from the bitmaps.
1532  */
1533
1534 /*
1535  * Called just after updating the cylinder group block to allocate an inode.
1536  */
1537 void
1538 softdep_setup_inomapdep(bp, ip, newinum)
1539         struct buf *bp;         /* buffer for cylgroup block with inode map */
1540         struct inode *ip;       /* inode related to allocation */
1541         ino_t newinum;          /* new inode number being allocated */
1542 {
1543         struct inodedep *inodedep;
1544         struct bmsafemap *bmsafemap;
1545
1546         /*
1547          * Create a dependency for the newly allocated inode.
1548          * Panic if it already exists as something is seriously wrong.
1549          * Otherwise add it to the dependency list for the buffer holding
1550          * the cylinder group map from which it was allocated.
1551          */
1552         ACQUIRE_LOCK(&lk);
1553         if ((inodedep_lookup(UFSTOVFS(ip->i_ump), newinum, DEPALLOC|NODELAY,
1554             &inodedep)))
1555                 panic("softdep_setup_inomapdep: dependency for new inode "
1556                     "already exists");
1557         inodedep->id_buf = bp;
1558         inodedep->id_state &= ~DEPCOMPLETE;
1559         bmsafemap = bmsafemap_lookup(inodedep->id_list.wk_mp, bp);
1560         LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1561         FREE_LOCK(&lk);
1562 }
1563
1564 /*
1565  * Called just after updating the cylinder group block to
1566  * allocate block or fragment.
1567  */
1568 void
1569 softdep_setup_blkmapdep(bp, mp, newblkno)
1570         struct buf *bp;         /* buffer for cylgroup block with block map */
1571         struct mount *mp;       /* filesystem doing allocation */
1572         ufs2_daddr_t newblkno;  /* number of newly allocated block */
1573 {
1574         struct newblk *newblk;
1575         struct bmsafemap *bmsafemap;
1576         struct fs *fs;
1577
1578         fs = VFSTOUFS(mp)->um_fs;
1579         /*
1580          * Create a dependency for the newly allocated block.
1581          * Add it to the dependency list for the buffer holding
1582          * the cylinder group map from which it was allocated.
1583          */
1584         ACQUIRE_LOCK(&lk);
1585         if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1586                 panic("softdep_setup_blkmapdep: found block");
1587         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp);
1588         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1589         FREE_LOCK(&lk);
1590 }
1591
1592 /*
1593  * Find the bmsafemap associated with a cylinder group buffer.
1594  * If none exists, create one. The buffer must be locked when
1595  * this routine is called and this routine must be called with
1596  * splbio interrupts blocked.
1597  */
1598 static struct bmsafemap *
1599 bmsafemap_lookup(mp, bp)
1600         struct mount *mp;
1601         struct buf *bp;
1602 {
1603         struct bmsafemap *bmsafemap;
1604         struct worklist *wk;
1605
1606         mtx_assert(&lk, MA_OWNED);
1607         LIST_FOREACH(wk, &bp->b_dep, wk_list)
1608                 if (wk->wk_type == D_BMSAFEMAP)
1609                         return (WK_BMSAFEMAP(wk));
1610         FREE_LOCK(&lk);
1611         MALLOC(bmsafemap, struct bmsafemap *, sizeof(struct bmsafemap),
1612                 M_BMSAFEMAP, M_SOFTDEP_FLAGS);
1613         workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
1614         bmsafemap->sm_buf = bp;
1615         LIST_INIT(&bmsafemap->sm_allocdirecthd);
1616         LIST_INIT(&bmsafemap->sm_allocindirhd);
1617         LIST_INIT(&bmsafemap->sm_inodedephd);
1618         LIST_INIT(&bmsafemap->sm_newblkhd);
1619         ACQUIRE_LOCK(&lk);
1620         WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
1621         return (bmsafemap);
1622 }
1623
1624 /*
1625  * Direct block allocation dependencies.
1626  * 
1627  * When a new block is allocated, the corresponding disk locations must be
1628  * initialized (with zeros or new data) before the on-disk inode points to
1629  * them.  Also, the freemap from which the block was allocated must be
1630  * updated (on disk) before the inode's pointer. These two dependencies are
1631  * independent of each other and are needed for all file blocks and indirect
1632  * blocks that are pointed to directly by the inode.  Just before the
1633  * "in-core" version of the inode is updated with a newly allocated block
1634  * number, a procedure (below) is called to setup allocation dependency
1635  * structures.  These structures are removed when the corresponding
1636  * dependencies are satisfied or when the block allocation becomes obsolete
1637  * (i.e., the file is deleted, the block is de-allocated, or the block is a
1638  * fragment that gets upgraded).  All of these cases are handled in
1639  * procedures described later.
1640  * 
1641  * When a file extension causes a fragment to be upgraded, either to a larger
1642  * fragment or to a full block, the on-disk location may change (if the
1643  * previous fragment could not simply be extended). In this case, the old
1644  * fragment must be de-allocated, but not until after the inode's pointer has
1645  * been updated. In most cases, this is handled by later procedures, which
1646  * will construct a "freefrag" structure to be added to the workitem queue
1647  * when the inode update is complete (or obsolete).  The main exception to
1648  * this is when an allocation occurs while a pending allocation dependency
1649  * (for the same block pointer) remains.  This case is handled in the main
1650  * allocation dependency setup procedure by immediately freeing the
1651  * unreferenced fragments.
1652  */ 
1653 void 
1654 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
1655         struct inode *ip;       /* inode to which block is being added */
1656         ufs_lbn_t lbn;          /* block pointer within inode */
1657         ufs2_daddr_t newblkno;  /* disk block number being added */
1658         ufs2_daddr_t oldblkno;  /* previous block number, 0 unless frag */
1659         long newsize;           /* size of new block */
1660         long oldsize;           /* size of new block */
1661         struct buf *bp;         /* bp for allocated block */
1662 {
1663         struct allocdirect *adp, *oldadp;
1664         struct allocdirectlst *adphead;
1665         struct bmsafemap *bmsafemap;
1666         struct inodedep *inodedep;
1667         struct pagedep *pagedep;
1668         struct newblk *newblk;
1669         struct mount *mp;
1670
1671         mp = UFSTOVFS(ip->i_ump);
1672         MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1673                 M_ALLOCDIRECT, M_SOFTDEP_FLAGS|M_ZERO);
1674         workitem_alloc(&adp->ad_list, D_ALLOCDIRECT, mp);
1675         adp->ad_lbn = lbn;
1676         adp->ad_newblkno = newblkno;
1677         adp->ad_oldblkno = oldblkno;
1678         adp->ad_newsize = newsize;
1679         adp->ad_oldsize = oldsize;
1680         adp->ad_state = ATTACHED;
1681         LIST_INIT(&adp->ad_newdirblk);
1682         if (newblkno == oldblkno)
1683                 adp->ad_freefrag = NULL;
1684         else
1685                 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1686
1687         ACQUIRE_LOCK(&lk);
1688         if (lbn >= NDADDR) {
1689                 /* allocating an indirect block */
1690                 if (oldblkno != 0)
1691                         panic("softdep_setup_allocdirect: non-zero indir");
1692         } else {
1693                 /*
1694                  * Allocating a direct block.
1695                  *
1696                  * If we are allocating a directory block, then we must
1697                  * allocate an associated pagedep to track additions and
1698                  * deletions.
1699                  */
1700                 if ((ip->i_mode & IFMT) == IFDIR &&
1701                     pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1702                         WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
1703         }
1704         if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1705                 panic("softdep_setup_allocdirect: lost block");
1706         if (newblk->nb_state == DEPCOMPLETE) {
1707                 adp->ad_state |= DEPCOMPLETE;
1708                 adp->ad_buf = NULL;
1709         } else {
1710                 bmsafemap = newblk->nb_bmsafemap;
1711                 adp->ad_buf = bmsafemap->sm_buf;
1712                 LIST_REMOVE(newblk, nb_deps);
1713                 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1714         }
1715         LIST_REMOVE(newblk, nb_hash);
1716         FREE(newblk, M_NEWBLK);
1717
1718         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1719         adp->ad_inodedep = inodedep;
1720         WORKLIST_INSERT(&bp->b_dep, &adp->ad_list);
1721         /*
1722          * The list of allocdirects must be kept in sorted and ascending
1723          * order so that the rollback routines can quickly determine the
1724          * first uncommitted block (the size of the file stored on disk
1725          * ends at the end of the lowest committed fragment, or if there
1726          * are no fragments, at the end of the highest committed block).
1727          * Since files generally grow, the typical case is that the new
1728          * block is to be added at the end of the list. We speed this
1729          * special case by checking against the last allocdirect in the
1730          * list before laboriously traversing the list looking for the
1731          * insertion point.
1732          */
1733         adphead = &inodedep->id_newinoupdt;
1734         oldadp = TAILQ_LAST(adphead, allocdirectlst);
1735         if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1736                 /* insert at end of list */
1737                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1738                 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1739                         allocdirect_merge(adphead, adp, oldadp);
1740                 FREE_LOCK(&lk);
1741                 return;
1742         }
1743         TAILQ_FOREACH(oldadp, adphead, ad_next) {
1744                 if (oldadp->ad_lbn >= lbn)
1745                         break;
1746         }
1747         if (oldadp == NULL)
1748                 panic("softdep_setup_allocdirect: lost entry");
1749         /* insert in middle of list */
1750         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1751         if (oldadp->ad_lbn == lbn)
1752                 allocdirect_merge(adphead, adp, oldadp);
1753         FREE_LOCK(&lk);
1754 }
1755
1756 /*
1757  * Replace an old allocdirect dependency with a newer one.
1758  * This routine must be called with splbio interrupts blocked.
1759  */
1760 static void
1761 allocdirect_merge(adphead, newadp, oldadp)
1762         struct allocdirectlst *adphead; /* head of list holding allocdirects */
1763         struct allocdirect *newadp;     /* allocdirect being added */
1764         struct allocdirect *oldadp;     /* existing allocdirect being checked */
1765 {
1766         struct worklist *wk;
1767         struct freefrag *freefrag;
1768         struct newdirblk *newdirblk;
1769
1770         mtx_assert(&lk, MA_OWNED);
1771         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1772             newadp->ad_oldsize != oldadp->ad_newsize ||
1773             newadp->ad_lbn >= NDADDR)
1774                 panic("%s %jd != new %jd || old size %ld != new %ld",
1775                     "allocdirect_merge: old blkno",
1776                     (intmax_t)newadp->ad_oldblkno,
1777                     (intmax_t)oldadp->ad_newblkno,
1778                     newadp->ad_oldsize, oldadp->ad_newsize);
1779         newadp->ad_oldblkno = oldadp->ad_oldblkno;
1780         newadp->ad_oldsize = oldadp->ad_oldsize;
1781         /*
1782          * If the old dependency had a fragment to free or had never
1783          * previously had a block allocated, then the new dependency
1784          * can immediately post its freefrag and adopt the old freefrag.
1785          * This action is done by swapping the freefrag dependencies.
1786          * The new dependency gains the old one's freefrag, and the
1787          * old one gets the new one and then immediately puts it on
1788          * the worklist when it is freed by free_allocdirect. It is
1789          * not possible to do this swap when the old dependency had a
1790          * non-zero size but no previous fragment to free. This condition
1791          * arises when the new block is an extension of the old block.
1792          * Here, the first part of the fragment allocated to the new
1793          * dependency is part of the block currently claimed on disk by
1794          * the old dependency, so cannot legitimately be freed until the
1795          * conditions for the new dependency are fulfilled.
1796          */
1797         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1798                 freefrag = newadp->ad_freefrag;
1799                 newadp->ad_freefrag = oldadp->ad_freefrag;
1800                 oldadp->ad_freefrag = freefrag;
1801         }
1802         /*
1803          * If we are tracking a new directory-block allocation,
1804          * move it from the old allocdirect to the new allocdirect.
1805          */
1806         if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
1807                 newdirblk = WK_NEWDIRBLK(wk);
1808                 WORKLIST_REMOVE(&newdirblk->db_list);
1809                 if (!LIST_EMPTY(&oldadp->ad_newdirblk))
1810                         panic("allocdirect_merge: extra newdirblk");
1811                 WORKLIST_INSERT(&newadp->ad_newdirblk, &newdirblk->db_list);
1812         }
1813         free_allocdirect(adphead, oldadp, 0);
1814 }
1815                 
1816 /*
1817  * Allocate a new freefrag structure if needed.
1818  */
1819 static struct freefrag *
1820 newfreefrag(ip, blkno, size)
1821         struct inode *ip;
1822         ufs2_daddr_t blkno;
1823         long size;
1824 {
1825         struct freefrag *freefrag;
1826         struct fs *fs;
1827
1828         if (blkno == 0)
1829                 return (NULL);
1830         fs = ip->i_fs;
1831         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1832                 panic("newfreefrag: frag size");
1833         MALLOC(freefrag, struct freefrag *, sizeof(struct freefrag),
1834                 M_FREEFRAG, M_SOFTDEP_FLAGS);
1835         workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
1836         freefrag->ff_inum = ip->i_number;
1837         freefrag->ff_blkno = blkno;
1838         freefrag->ff_fragsize = size;
1839         return (freefrag);
1840 }
1841
1842 /*
1843  * This workitem de-allocates fragments that were replaced during
1844  * file block allocation.
1845  */
1846 static void 
1847 handle_workitem_freefrag(freefrag)
1848         struct freefrag *freefrag;
1849 {
1850         struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
1851
1852         ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
1853             freefrag->ff_fragsize, freefrag->ff_inum);
1854         ACQUIRE_LOCK(&lk);
1855         WORKITEM_FREE(freefrag, D_FREEFRAG);
1856         FREE_LOCK(&lk);
1857 }
1858
1859 /*
1860  * Set up a dependency structure for an external attributes data block.
1861  * This routine follows much of the structure of softdep_setup_allocdirect.
1862  * See the description of softdep_setup_allocdirect above for details.
1863  */
1864 void 
1865 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
1866         struct inode *ip;
1867         ufs_lbn_t lbn;
1868         ufs2_daddr_t newblkno;
1869         ufs2_daddr_t oldblkno;
1870         long newsize;
1871         long oldsize;
1872         struct buf *bp;
1873 {
1874         struct allocdirect *adp, *oldadp;
1875         struct allocdirectlst *adphead;
1876         struct bmsafemap *bmsafemap;
1877         struct inodedep *inodedep;
1878         struct newblk *newblk;
1879         struct mount *mp;
1880
1881         mp = UFSTOVFS(ip->i_ump);
1882         MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1883                 M_ALLOCDIRECT, M_SOFTDEP_FLAGS|M_ZERO);
1884         workitem_alloc(&adp->ad_list, D_ALLOCDIRECT, mp);
1885         adp->ad_lbn = lbn;
1886         adp->ad_newblkno = newblkno;
1887         adp->ad_oldblkno = oldblkno;
1888         adp->ad_newsize = newsize;
1889         adp->ad_oldsize = oldsize;
1890         adp->ad_state = ATTACHED | EXTDATA;
1891         LIST_INIT(&adp->ad_newdirblk);
1892         if (newblkno == oldblkno)
1893                 adp->ad_freefrag = NULL;
1894         else
1895                 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1896
1897         ACQUIRE_LOCK(&lk);
1898         if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1899                 panic("softdep_setup_allocext: lost block");
1900
1901         inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1902         adp->ad_inodedep = inodedep;
1903
1904         if (newblk->nb_state == DEPCOMPLETE) {
1905                 adp->ad_state |= DEPCOMPLETE;
1906                 adp->ad_buf = NULL;
1907         } else {
1908                 bmsafemap = newblk->nb_bmsafemap;
1909                 adp->ad_buf = bmsafemap->sm_buf;
1910                 LIST_REMOVE(newblk, nb_deps);
1911                 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1912         }
1913         LIST_REMOVE(newblk, nb_hash);
1914         FREE(newblk, M_NEWBLK);
1915
1916         WORKLIST_INSERT(&bp->b_dep, &adp->ad_list);
1917         if (lbn >= NXADDR)
1918                 panic("softdep_setup_allocext: lbn %lld > NXADDR",
1919                     (long long)lbn);
1920         /*
1921          * The list of allocdirects must be kept in sorted and ascending
1922          * order so that the rollback routines can quickly determine the
1923          * first uncommitted block (the size of the file stored on disk
1924          * ends at the end of the lowest committed fragment, or if there
1925          * are no fragments, at the end of the highest committed block).
1926          * Since files generally grow, the typical case is that the new
1927          * block is to be added at the end of the list. We speed this
1928          * special case by checking against the last allocdirect in the
1929          * list before laboriously traversing the list looking for the
1930          * insertion point.
1931          */
1932         adphead = &inodedep->id_newextupdt;
1933         oldadp = TAILQ_LAST(adphead, allocdirectlst);
1934         if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1935                 /* insert at end of list */
1936                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1937                 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1938                         allocdirect_merge(adphead, adp, oldadp);
1939                 FREE_LOCK(&lk);
1940                 return;
1941         }
1942         TAILQ_FOREACH(oldadp, adphead, ad_next) {
1943                 if (oldadp->ad_lbn >= lbn)
1944                         break;
1945         }
1946         if (oldadp == NULL)
1947                 panic("softdep_setup_allocext: lost entry");
1948         /* insert in middle of list */
1949         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1950         if (oldadp->ad_lbn == lbn)
1951                 allocdirect_merge(adphead, adp, oldadp);
1952         FREE_LOCK(&lk);
1953 }
1954
1955 /*
1956  * Indirect block allocation dependencies.
1957  * 
1958  * The same dependencies that exist for a direct block also exist when
1959  * a new block is allocated and pointed to by an entry in a block of
1960  * indirect pointers. The undo/redo states described above are also
1961  * used here. Because an indirect block contains many pointers that
1962  * may have dependencies, a second copy of the entire in-memory indirect
1963  * block is kept. The buffer cache copy is always completely up-to-date.
1964  * The second copy, which is used only as a source for disk writes,
1965  * contains only the safe pointers (i.e., those that have no remaining
1966  * update dependencies). The second copy is freed when all pointers
1967  * are safe. The cache is not allowed to replace indirect blocks with
1968  * pending update dependencies. If a buffer containing an indirect
1969  * block with dependencies is written, these routines will mark it
1970  * dirty again. It can only be successfully written once all the
1971  * dependencies are removed. The ffs_fsync routine in conjunction with
1972  * softdep_sync_metadata work together to get all the dependencies
1973  * removed so that a file can be successfully written to disk. Three
1974  * procedures are used when setting up indirect block pointer
1975  * dependencies. The division is necessary because of the organization
1976  * of the "balloc" routine and because of the distinction between file
1977  * pages and file metadata blocks.
1978  */
1979
1980 /*
1981  * Allocate a new allocindir structure.
1982  */
1983 static struct allocindir *
1984 newallocindir(ip, ptrno, newblkno, oldblkno)
1985         struct inode *ip;       /* inode for file being extended */
1986         int ptrno;              /* offset of pointer in indirect block */
1987         ufs2_daddr_t newblkno;  /* disk block number being added */
1988         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
1989 {
1990         struct allocindir *aip;
1991
1992         MALLOC(aip, struct allocindir *, sizeof(struct allocindir),
1993                 M_ALLOCINDIR, M_SOFTDEP_FLAGS|M_ZERO);
1994         workitem_alloc(&aip->ai_list, D_ALLOCINDIR, UFSTOVFS(ip->i_ump));
1995         aip->ai_state = ATTACHED;
1996         aip->ai_offset = ptrno;
1997         aip->ai_newblkno = newblkno;
1998         aip->ai_oldblkno = oldblkno;
1999         aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
2000         return (aip);
2001 }
2002
2003 /*
2004  * Called just before setting an indirect block pointer
2005  * to a newly allocated file page.
2006  */
2007 void
2008 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
2009         struct inode *ip;       /* inode for file being extended */
2010         ufs_lbn_t lbn;          /* allocated block number within file */
2011         struct buf *bp;         /* buffer with indirect blk referencing page */
2012         int ptrno;              /* offset of pointer in indirect block */
2013         ufs2_daddr_t newblkno;  /* disk block number being added */
2014         ufs2_daddr_t oldblkno;  /* previous block number, 0 if none */
2015         struct buf *nbp;        /* buffer holding allocated page */
2016 {
2017         struct allocindir *aip;
2018         struct pagedep *pagedep;
2019
2020         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
2021         aip = newallocindir(ip, ptrno, newblkno, oldblkno);
2022         ACQUIRE_LOCK(&lk);
2023         /*
2024          * If we are allocating a directory page, then we must
2025          * allocate an associated pagedep to track additions and
2026          * deletions.
2027          */
2028         if ((ip->i_mode & IFMT) == IFDIR &&
2029             pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
2030                 WORKLIST_INSERT(&nbp->b_dep, &pagedep->pd_list);
2031         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
2032         setup_allocindir_phase2(bp, ip, aip);
2033         FREE_LOCK(&lk);
2034 }
2035
2036 /*
2037  * Called just before setting an indirect block pointer to a
2038  * newly allocated indirect block.
2039  */
2040 void
2041 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
2042         struct buf *nbp;        /* newly allocated indirect block */
2043         struct inode *ip;       /* inode for file being extended */
2044         struct buf *bp;         /* indirect block referencing allocated block */
2045         int ptrno;              /* offset of pointer in indirect block */
2046         ufs2_daddr_t newblkno;  /* disk block number being added */
2047 {
2048         struct allocindir *aip;
2049
2050         ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
2051         aip = newallocindir(ip, ptrno, newblkno, 0);
2052         ACQUIRE_LOCK(&lk);
2053         WORKLIST_INSERT(&nbp->b_dep, &aip->ai_list);
2054         setup_allocindir_phase2(bp, ip, aip);
2055         FREE_LOCK(&lk);
2056 }
2057
2058 /*
2059  * Called to finish the allocation of the "aip" allocated
2060  * by one of the two routines above.
2061  */
2062 static void 
2063 setup_allocindir_phase2(bp, ip, aip)
2064         struct buf *bp;         /* in-memory copy of the indirect block */
2065         struct inode *ip;       /* inode for file being extended */
2066         struct allocindir *aip; /* allocindir allocated by the above routines */
2067 {
2068         struct worklist *wk;
2069         struct indirdep *indirdep, *newindirdep;
2070         struct bmsafemap *bmsafemap;
2071         struct allocindir *oldaip;
2072         struct freefrag *freefrag;
2073         struct newblk *newblk;
2074         ufs2_daddr_t blkno;
2075
2076         mtx_assert(&lk, MA_OWNED);
2077         if (bp->b_lblkno >= 0)
2078                 panic("setup_allocindir_phase2: not indir blk");
2079         for (indirdep = NULL, newindirdep = NULL; ; ) {
2080                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2081                         if (wk->wk_type != D_INDIRDEP)
2082                                 continue;
2083                         indirdep = WK_INDIRDEP(wk);
2084                         break;
2085                 }
2086                 if (indirdep == NULL && newindirdep) {
2087                         indirdep = newindirdep;
2088                         WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
2089                         newindirdep = NULL;
2090                 }
2091                 if (indirdep) {
2092                         if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
2093                             &newblk) == 0)
2094                                 panic("setup_allocindir: lost block");
2095                         if (newblk->nb_state == DEPCOMPLETE) {
2096                                 aip->ai_state |= DEPCOMPLETE;
2097                                 aip->ai_buf = NULL;
2098                         } else {
2099                                 bmsafemap = newblk->nb_bmsafemap;
2100                                 aip->ai_buf = bmsafemap->sm_buf;
2101                                 LIST_REMOVE(newblk, nb_deps);
2102                                 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
2103                                     aip, ai_deps);
2104                         }
2105                         LIST_REMOVE(newblk, nb_hash);
2106                         FREE(newblk, M_NEWBLK);
2107                         aip->ai_indirdep = indirdep;
2108                         /*
2109                          * Check to see if there is an existing dependency
2110                          * for this block. If there is, merge the old
2111                          * dependency into the new one.
2112                          */
2113                         if (aip->ai_oldblkno == 0)
2114                                 oldaip = NULL;
2115                         else
2116
2117                                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
2118                                         if (oldaip->ai_offset == aip->ai_offset)
2119                                                 break;
2120                         freefrag = NULL;
2121                         if (oldaip != NULL) {
2122                                 if (oldaip->ai_newblkno != aip->ai_oldblkno)
2123                                         panic("setup_allocindir_phase2: blkno");
2124                                 aip->ai_oldblkno = oldaip->ai_oldblkno;
2125                                 freefrag = aip->ai_freefrag;
2126                                 aip->ai_freefrag = oldaip->ai_freefrag;
2127                                 oldaip->ai_freefrag = NULL;
2128                                 free_allocindir(oldaip, NULL);
2129                         }
2130                         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
2131                         if (ip->i_ump->um_fstype == UFS1)
2132                                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)
2133                                     [aip->ai_offset] = aip->ai_oldblkno;
2134                         else
2135                                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)
2136                                     [aip->ai_offset] = aip->ai_oldblkno;
2137                         FREE_LOCK(&lk);
2138                         if (freefrag != NULL)
2139                                 handle_workitem_freefrag(freefrag);
2140                 } else
2141                         FREE_LOCK(&lk);
2142                 if (newindirdep) {
2143                         newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
2144                         brelse(newindirdep->ir_savebp);
2145                         ACQUIRE_LOCK(&lk);
2146                         WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
2147                         if (indirdep)
2148                                 break;
2149                         FREE_LOCK(&lk);
2150                 }
2151                 if (indirdep) {
2152                         ACQUIRE_LOCK(&lk);
2153                         break;
2154                 }
2155                 MALLOC(newindirdep, struct indirdep *, sizeof(struct indirdep),
2156                         M_INDIRDEP, M_SOFTDEP_FLAGS);
2157                 workitem_alloc(&newindirdep->ir_list, D_INDIRDEP,
2158                     UFSTOVFS(ip->i_ump));
2159                 newindirdep->ir_state = ATTACHED;
2160                 if (ip->i_ump->um_fstype == UFS1)
2161                         newindirdep->ir_state |= UFS1FMT;
2162                 LIST_INIT(&newindirdep->ir_deplisthd);
2163                 LIST_INIT(&newindirdep->ir_donehd);
2164                 if (bp->b_blkno == bp->b_lblkno) {
2165                         ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
2166                             NULL, NULL);
2167                         bp->b_blkno = blkno;
2168                 }
2169                 newindirdep->ir_savebp =
2170                     getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
2171                 BUF_KERNPROC(newindirdep->ir_savebp);
2172                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
2173                 ACQUIRE_LOCK(&lk);
2174         }
2175 }
2176
2177 /*
2178  * Block de-allocation dependencies.
2179  * 
2180  * When blocks are de-allocated, the on-disk pointers must be nullified before
2181  * the blocks are made available for use by other files.  (The true
2182  * requirement is that old pointers must be nullified before new on-disk
2183  * pointers are set.  We chose this slightly more stringent requirement to
2184  * reduce complexity.) Our implementation handles this dependency by updating
2185  * the inode (or indirect block) appropriately but delaying the actual block
2186  * de-allocation (i.e., freemap and free space count manipulation) until
2187  * after the updated versions reach stable storage.  After the disk is
2188  * updated, the blocks can be safely de-allocated whenever it is convenient.
2189  * This implementation handles only the common case of reducing a file's
2190  * length to zero. Other cases are handled by the conventional synchronous
2191  * write approach.
2192  *
2193  * The ffs implementation with which we worked double-checks
2194  * the state of the block pointers and file size as it reduces
2195  * a file's length.  Some of this code is replicated here in our
2196  * soft updates implementation.  The freeblks->fb_chkcnt field is
2197  * used to transfer a part of this information to the procedure
2198  * that eventually de-allocates the blocks.
2199  *
2200  * This routine should be called from the routine that shortens
2201  * a file's length, before the inode's size or block pointers
2202  * are modified. It will save the block pointer information for
2203  * later release and zero the inode so that the calling routine
2204  * can release it.
2205  */
2206 void
2207 softdep_setup_freeblocks(ip, length, flags)
2208         struct inode *ip;       /* The inode whose length is to be reduced */
2209         off_t length;           /* The new length for the file */
2210         int flags;              /* IO_EXT and/or IO_NORMAL */
2211 {
2212         struct freeblks *freeblks;
2213         struct inodedep *inodedep;
2214         struct allocdirect *adp;
2215         struct vnode *vp;
2216         struct buf *bp;
2217         struct fs *fs;
2218         ufs2_daddr_t extblocks, datablocks;
2219         struct mount *mp;
2220         int i, delay, error;
2221
2222         fs = ip->i_fs;
2223         mp = UFSTOVFS(ip->i_ump);
2224         if (length != 0)
2225                 panic("softdep_setup_freeblocks: non-zero length");
2226         MALLOC(freeblks, struct freeblks *, sizeof(struct freeblks),
2227                 M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
2228         workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
2229         freeblks->fb_state = ATTACHED;
2230         freeblks->fb_uid = ip->i_uid;
2231         freeblks->fb_previousinum = ip->i_number;
2232         freeblks->fb_devvp = ip->i_devvp;
2233         extblocks = 0;
2234         if (fs->fs_magic == FS_UFS2_MAGIC)
2235                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
2236         datablocks = DIP(ip, i_blocks) - extblocks;
2237         if ((flags & IO_NORMAL) == 0) {
2238                 freeblks->fb_oldsize = 0;
2239                 freeblks->fb_chkcnt = 0;
2240         } else {
2241                 freeblks->fb_oldsize = ip->i_size;
2242                 ip->i_size = 0;
2243                 DIP_SET(ip, i_size, 0);
2244                 freeblks->fb_chkcnt = datablocks;
2245                 for (i = 0; i < NDADDR; i++) {
2246                         freeblks->fb_dblks[i] = DIP(ip, i_db[i]);
2247                         DIP_SET(ip, i_db[i], 0);
2248                 }
2249                 for (i = 0; i < NIADDR; i++) {
2250                         freeblks->fb_iblks[i] = DIP(ip, i_ib[i]);
2251                         DIP_SET(ip, i_ib[i], 0);
2252                 }
2253                 /*
2254                  * If the file was removed, then the space being freed was
2255                  * accounted for then (see softdep_releasefile()). If the
2256                  * file is merely being truncated, then we account for it now.
2257                  */
2258                 if ((ip->i_flag & IN_SPACECOUNTED) == 0) {
2259                         UFS_LOCK(ip->i_ump);
2260                         fs->fs_pendingblocks += datablocks;
2261                         UFS_UNLOCK(ip->i_ump);
2262                 }
2263         }
2264         if ((flags & IO_EXT) == 0) {
2265                 freeblks->fb_oldextsize = 0;
2266         } else {
2267                 freeblks->fb_oldextsize = ip->i_din2->di_extsize;
2268                 ip->i_din2->di_extsize = 0;
2269                 freeblks->fb_chkcnt += extblocks;
2270                 for (i = 0; i < NXADDR; i++) {
2271                         freeblks->fb_eblks[i] = ip->i_din2->di_extb[i];
2272                         ip->i_din2->di_extb[i] = 0;
2273                 }
2274         }
2275         DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - freeblks->fb_chkcnt);
2276         /*
2277          * Push the zero'ed inode to to its disk buffer so that we are free
2278          * to delete its dependencies below. Once the dependencies are gone
2279          * the buffer can be safely released.
2280          */
2281         if ((error = bread(ip->i_devvp,
2282             fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
2283             (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
2284                 brelse(bp);
2285                 softdep_error("softdep_setup_freeblocks", error);
2286         }
2287         if (ip->i_ump->um_fstype == UFS1)
2288                 *((struct ufs1_dinode *)bp->b_data +
2289                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
2290         else
2291                 *((struct ufs2_dinode *)bp->b_data +
2292                     ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
2293         /*
2294          * Find and eliminate any inode dependencies.
2295          */
2296         ACQUIRE_LOCK(&lk);
2297         (void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
2298         if ((inodedep->id_state & IOSTARTED) != 0)
2299                 panic("softdep_setup_freeblocks: inode busy");
2300         /*
2301          * Add the freeblks structure to the list of operations that
2302          * must await the zero'ed inode being written to disk. If we
2303          * still have a bitmap dependency (delay == 0), then the inode
2304          * has never been written to disk, so we can process the
2305          * freeblks below once we have deleted the dependencies.
2306          */
2307         delay = (inodedep->id_state & DEPCOMPLETE);
2308         if (delay)
2309                 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
2310         /*
2311          * Because the file length has been truncated to zero, any
2312          * pending block allocation dependency structures associated
2313          * with this inode are obsolete and can simply be de-allocated.
2314          * We must first merge the two dependency lists to get rid of
2315          * any duplicate freefrag structures, then purge the merged list.
2316          * If we still have a bitmap dependency, then the inode has never
2317          * been written to disk, so we can free any fragments without delay.
2318          */
2319         if (flags & IO_NORMAL) {
2320                 merge_inode_lists(&inodedep->id_newinoupdt,
2321                     &inodedep->id_inoupdt);
2322                 while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
2323                         free_allocdirect(&inodedep->id_inoupdt, adp, delay);
2324         }
2325         if (flags & IO_EXT) {
2326                 merge_inode_lists(&inodedep->id_newextupdt,
2327                     &inodedep->id_extupdt);
2328                 while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
2329                         free_allocdirect(&inodedep->id_extupdt, adp, delay);
2330         }
2331         FREE_LOCK(&lk);
2332         bdwrite(bp);
2333         /*
2334          * We must wait for any I/O in progress to finish so that
2335          * all potential buffers on the dirty list will be visible.
2336          * Once they are all there, walk the list and get rid of
2337          * any dependencies.
2338          */
2339         vp = ITOV(ip);
2340         VI_LOCK(vp);
2341         drain_output(vp);
2342 restart:
2343         TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs) {
2344                 if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
2345                     ((flags & IO_NORMAL) == 0 &&
2346                       (bp->b_xflags & BX_ALTDATA) == 0))
2347                         continue;
2348                 if ((bp = getdirtybuf(bp, VI_MTX(vp), MNT_WAIT)) == NULL)
2349                         goto restart;
2350                 VI_UNLOCK(vp);
2351                 ACQUIRE_LOCK(&lk);
2352                 (void) inodedep_lookup(mp, ip->i_number, 0, &inodedep);
2353                 deallocate_dependencies(bp, inodedep);
2354                 FREE_LOCK(&lk);
2355                 bp->b_flags |= B_INVAL | B_NOCACHE;
2356                 brelse(bp);
2357                 VI_LOCK(vp);
2358                 goto restart;
2359         }
2360         VI_UNLOCK(vp);
2361         ACQUIRE_LOCK(&lk);
2362         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
2363                 (void) free_inodedep(inodedep);
2364
2365         if(delay) {
2366                 freeblks->fb_state |= DEPCOMPLETE;
2367                 /*
2368                  * If the inode with zeroed block pointers is now on disk
2369                  * we can start freeing blocks. Add freeblks to the worklist
2370                  * instead of calling  handle_workitem_freeblocks directly as
2371                  * it is more likely that additional IO is needed to complete
2372                  * the request here than in the !delay case.
2373                  */  
2374                 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
2375                         add_to_worklist(&freeblks->fb_list);
2376         }
2377
2378         FREE_LOCK(&lk);
2379         /*
2380          * If the inode has never been written to disk (delay == 0),
2381          * then we can process the freeblks now that we have deleted
2382          * the dependencies.
2383          */
2384         if (!delay)
2385                 handle_workitem_freeblocks(freeblks, 0);
2386 }
2387
2388 /*
2389  * Reclaim any dependency structures from a buffer that is about to
2390  * be reallocated to a new vnode. The buffer must be locked, thus,
2391  * no I/O completion operations can occur while we are manipulating
2392  * its associated dependencies. The mutex is held so that other I/O's
2393  * associated with related dependencies do not occur.
2394  */
2395 static void
2396 deallocate_dependencies(bp, inodedep)
2397         struct buf *bp;
2398         struct inodedep *inodedep;
2399 {
2400         struct worklist *wk;
2401         struct indirdep *indirdep;
2402         struct allocindir *aip;
2403         struct pagedep *pagedep;
2404         struct dirrem *dirrem;
2405         struct diradd *dap;
2406         int i;
2407
2408         mtx_assert(&lk, MA_OWNED);
2409         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2410                 switch (wk->wk_type) {
2411
2412                 case D_INDIRDEP:
2413                         indirdep = WK_INDIRDEP(wk);
2414                         /*
2415                          * None of the indirect pointers will ever be visible,
2416                          * so they can simply be tossed. GOINGAWAY ensures
2417                          * that allocated pointers will be saved in the buffer
2418                          * cache until they are freed. Note that they will
2419                          * only be able to be found by their physical address
2420                          * since the inode mapping the logical address will
2421                          * be gone. The save buffer used for the safe copy
2422                          * was allocated in setup_allocindir_phase2 using
2423                          * the physical address so it could be used for this
2424                          * purpose. Hence we swap the safe copy with the real
2425                          * copy, allowing the safe copy to be freed and holding
2426                          * on to the real copy for later use in indir_trunc.
2427                          */
2428                         if (indirdep->ir_state & GOINGAWAY)
2429                                 panic("deallocate_dependencies: already gone");
2430                         indirdep->ir_state |= GOINGAWAY;
2431                         VFSTOUFS(bp->b_vp->v_mount)->um_numindirdeps += 1;
2432                         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
2433                                 free_allocindir(aip, inodedep);
2434                         if (bp->b_lblkno >= 0 ||
2435                             bp->b_blkno != indirdep->ir_savebp->b_lblkno)
2436                                 panic("deallocate_dependencies: not indir");
2437                         bcopy(bp->b_data, indirdep->ir_savebp->b_data,
2438                             bp->b_bcount);
2439                         WORKLIST_REMOVE(wk);
2440                         WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, wk);
2441                         continue;
2442
2443                 case D_PAGEDEP:
2444                         pagedep = WK_PAGEDEP(wk);
2445                         /*
2446                          * None of the directory additions will ever be
2447                          * visible, so they can simply be tossed.
2448                          */
2449                         for (i = 0; i < DAHASHSZ; i++)
2450                                 while ((dap =
2451                                     LIST_FIRST(&pagedep->pd_diraddhd[i])))
2452                                         free_diradd(dap);
2453                         while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != 0)
2454                                 free_diradd(dap);
2455                         /*
2456                          * Copy any directory remove dependencies to the list
2457                          * to be processed after the zero'ed inode is written.
2458                          * If the inode has already been written, then they 
2459                          * can be dumped directly onto the work list.
2460                          */
2461                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
2462                                 LIST_REMOVE(dirrem, dm_next);
2463                                 dirrem->dm_dirinum = pagedep->pd_ino;
2464                                 if (inodedep == NULL ||
2465                                     (inodedep->id_state & ALLCOMPLETE) ==
2466                                      ALLCOMPLETE)
2467                                         add_to_worklist(&dirrem->dm_list);
2468                                 else
2469                                         WORKLIST_INSERT(&inodedep->id_bufwait,
2470                                             &dirrem->dm_list);
2471                         }
2472                         if ((pagedep->pd_state & NEWBLOCK) != 0) {
2473                                 LIST_FOREACH(wk, &inodedep->id_bufwait, wk_list)
2474                                         if (wk->wk_type == D_NEWDIRBLK &&
2475                                             WK_NEWDIRBLK(wk)->db_pagedep ==
2476                                               pagedep)
2477                                                 break;
2478                                 if (wk != NULL) {
2479                                         WORKLIST_REMOVE(wk);
2480                                         free_newdirblk(WK_NEWDIRBLK(wk));
2481                                 } else
2482                                         panic("deallocate_dependencies: "
2483                                               "lost pagedep");
2484                         }
2485                         WORKLIST_REMOVE(&pagedep->pd_list);
2486                         LIST_REMOVE(pagedep, pd_hash);
2487                         WORKITEM_FREE(pagedep, D_PAGEDEP);
2488                         continue;
2489
2490                 case D_ALLOCINDIR:
2491                         free_allocindir(WK_ALLOCINDIR(wk), inodedep);
2492                         continue;
2493
2494                 case D_ALLOCDIRECT:
2495                 case D_INODEDEP:
2496                         panic("deallocate_dependencies: Unexpected type %s",
2497                             TYPENAME(wk->wk_type));
2498                         /* NOTREACHED */
2499
2500                 default:
2501                         panic("deallocate_dependencies: Unknown type %s",
2502                             TYPENAME(wk->wk_type));
2503                         /* NOTREACHED */
2504                 }
2505         }
2506 }
2507
2508 /*
2509  * Free an allocdirect. Generate a new freefrag work request if appropriate.
2510  * This routine must be called with splbio interrupts blocked.
2511  */
2512 static void
2513 free_allocdirect(adphead, adp, delay)
2514         struct allocdirectlst *adphead;
2515         struct allocdirect *adp;
2516         int delay;
2517 {
2518         struct newdirblk *newdirblk;
2519         struct worklist *wk;
2520
2521         mtx_assert(&lk, MA_OWNED);
2522         if ((adp->ad_state & DEPCOMPLETE) == 0)
2523                 LIST_REMOVE(adp, ad_deps);
2524         TAILQ_REMOVE(adphead, adp, ad_next);
2525         if ((adp->ad_state & COMPLETE) == 0)
2526                 WORKLIST_REMOVE(&adp->ad_list);
2527         if (adp->ad_freefrag != NULL) {
2528                 if (delay)
2529                         WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2530                             &adp->ad_freefrag->ff_list);
2531                 else
2532                         add_to_worklist(&adp->ad_freefrag->ff_list);
2533         }
2534         if ((wk = LIST_FIRST(&adp->ad_newdirblk)) != NULL) {
2535                 newdirblk = WK_NEWDIRBLK(wk);
2536                 WORKLIST_REMOVE(&newdirblk->db_list);
2537                 if (!LIST_EMPTY(&adp->ad_newdirblk))
2538                         panic("free_allocdirect: extra newdirblk");
2539                 if (delay)
2540                         WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2541                             &newdirblk->db_list);
2542                 else
2543                         free_newdirblk(newdirblk);
2544         }
2545         WORKITEM_FREE(adp, D_ALLOCDIRECT);
2546 }
2547
2548 /*
2549  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
2550  * This routine must be called with splbio interrupts blocked.
2551  */
2552 static void
2553 free_newdirblk(newdirblk)
2554         struct newdirblk *newdirblk;
2555 {
2556         struct pagedep *pagedep;
2557         struct diradd *dap;
2558         int i;
2559
2560         mtx_assert(&lk, MA_OWNED);
2561         /*
2562          * If the pagedep is still linked onto the directory buffer
2563          * dependency chain, then some of the entries on the
2564          * pd_pendinghd list may not be committed to disk yet. In
2565          * this case, we will simply clear the NEWBLOCK flag and
2566          * let the pd_pendinghd list be processed when the pagedep
2567          * is next written. If the pagedep is no longer on the buffer
2568          * dependency chain, then all the entries on the pd_pending
2569          * list are committed to disk and we can free them here.
2570          */
2571         pagedep = newdirblk->db_pagedep;
2572         pagedep->pd_state &= ~NEWBLOCK;
2573         if ((pagedep->pd_state & ONWORKLIST) == 0)
2574                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
2575                         free_diradd(dap);
2576         /*
2577          * If no dependencies remain, the pagedep will be freed.
2578          */
2579         for (i = 0; i < DAHASHSZ; i++)
2580                 if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
2581                         break;
2582         if (i == DAHASHSZ && (pagedep->pd_state & ONWORKLIST) == 0) {
2583                 LIST_REMOVE(pagedep, pd_hash);
2584                 WORKITEM_FREE(pagedep, D_PAGEDEP);
2585         }
2586         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
2587 }
2588
2589 /*
2590  * Prepare an inode to be freed. The actual free operation is not
2591  * done until the zero'ed inode has been written to disk.
2592  */
2593 void
2594 softdep_freefile(pvp, ino, mode)
2595         struct vnode *pvp;
2596         ino_t ino;
2597         int mode;
2598 {
2599         struct inode *ip = VTOI(pvp);
2600         struct inodedep *inodedep;
2601         struct freefile *freefile;
2602
2603         /*
2604          * This sets up the inode de-allocation dependency.
2605          */
2606         MALLOC(freefile, struct freefile *, sizeof(struct freefile),
2607                 M_FREEFILE, M_SOFTDEP_FLAGS);
2608         workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
2609         freefile->fx_mode = mode;
2610         freefile->fx_oldinum = ino;
2611         freefile->fx_devvp = ip->i_devvp;
2612         if ((ip->i_flag & IN_SPACECOUNTED) == 0) {
2613                 UFS_LOCK(ip->i_ump);
2614                 ip->i_fs->fs_pendinginodes += 1;
2615                 UFS_UNLOCK(ip->i_ump);
2616         }
2617
2618         /*
2619          * If the inodedep does not exist, then the zero'ed inode has
2620          * been written to disk. If the allocated inode has never been
2621          * written to disk, then the on-disk inode is zero'ed. In either
2622          * case we can free the file immediately.
2623          */
2624         ACQUIRE_LOCK(&lk);
2625         if (inodedep_lookup(pvp->v_mount, ino, 0, &inodedep) == 0 ||
2626             check_inode_unwritten(inodedep)) {
2627                 FREE_LOCK(&lk);
2628                 handle_workitem_freefile(freefile);
2629                 return;
2630         }
2631         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2632         FREE_LOCK(&lk);
2633         if (ip->i_number == ino)
2634                 ip->i_flag |= IN_MODIFIED;
2635 }
2636
2637 /*
2638  * Check to see if an inode has never been written to disk. If
2639  * so free the inodedep and return success, otherwise return failure.
2640  * This routine must be called with splbio interrupts blocked.
2641  *
2642  * If we still have a bitmap dependency, then the inode has never
2643  * been written to disk. Drop the dependency as it is no longer
2644  * necessary since the inode is being deallocated. We set the
2645  * ALLCOMPLETE flags since the bitmap now properly shows that the
2646  * inode is not allocated. Even if the inode is actively being
2647  * written, it has been rolled back to its zero'ed state, so we
2648  * are ensured that a zero inode is what is on the disk. For short
2649  * lived files, this change will usually result in removing all the
2650  * dependencies from the inode so that it can be freed immediately.
2651  */
2652 static int
2653 check_inode_unwritten(inodedep)
2654         struct inodedep *inodedep;
2655 {
2656
2657         mtx_assert(&lk, MA_OWNED);
2658         if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2659             !LIST_EMPTY(&inodedep->id_pendinghd) ||
2660             !LIST_EMPTY(&inodedep->id_bufwait) ||
2661             !LIST_EMPTY(&inodedep->id_inowait) ||
2662             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
2663             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
2664             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
2665             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
2666             inodedep->id_nlinkdelta != 0)
2667                 return (0);
2668
2669         /*
2670          * Another process might be in initiate_write_inodeblock_ufs[12]
2671          * trying to allocate memory without holding "Softdep Lock".
2672          */
2673         if ((inodedep->id_state & IOSTARTED) != 0 &&
2674             inodedep->id_savedino1 == NULL)
2675                 return (0);
2676
2677         inodedep->id_state |= ALLCOMPLETE;
2678         LIST_REMOVE(inodedep, id_deps);
2679         inodedep->id_buf = NULL;
2680         if (inodedep->id_state & ONWORKLIST)
2681                 WORKLIST_REMOVE(&inodedep->id_list);
2682         if (inodedep->id_savedino1 != NULL) {
2683                 FREE(inodedep->id_savedino1, M_SAVEDINO);
2684                 inodedep->id_savedino1 = NULL;
2685         }
2686         if (free_inodedep(inodedep) == 0)
2687                 panic("check_inode_unwritten: busy inode");
2688         return (1);
2689 }
2690
2691 /*
2692  * Try to free an inodedep structure. Return 1 if it could be freed.
2693  */
2694 static int
2695 free_inodedep(inodedep)
2696         struct inodedep *inodedep;
2697 {
2698
2699         mtx_assert(&lk, MA_OWNED);
2700         if ((inodedep->id_state & ONWORKLIST) != 0 ||
2701             (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2702             !LIST_EMPTY(&inodedep->id_pendinghd) ||
2703             !LIST_EMPTY(&inodedep->id_bufwait) ||
2704             !LIST_EMPTY(&inodedep->id_inowait) ||
2705             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
2706             !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
2707             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
2708             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
2709             inodedep->id_nlinkdelta != 0 || inodedep->id_savedino1 != NULL)
2710                 return (0);
2711         LIST_REMOVE(inodedep, id_hash);
2712         WORKITEM_FREE(inodedep, D_INODEDEP);
2713         num_inodedep -= 1;
2714         return (1);
2715 }
2716
2717 /*
2718  * This workitem routine performs the block de-allocation.
2719  * The workitem is added to the pending list after the updated
2720  * inode block has been written to disk.  As mentioned above,
2721  * checks regarding the number of blocks de-allocated (compared
2722  * to the number of blocks allocated for the file) are also
2723  * performed in this function.
2724  */
2725 static void
2726 handle_workitem_freeblocks(freeblks, flags)
2727         struct freeblks *freeblks;
2728         int flags;
2729 {
2730         struct inode *ip;
2731         struct vnode *vp;
2732         struct fs *fs;
2733         struct ufsmount *ump;
2734         int i, nblocks, level, bsize;
2735         ufs2_daddr_t bn, blocksreleased = 0;
2736         int error, allerror = 0;
2737         ufs_lbn_t baselbns[NIADDR], tmpval;
2738         int fs_pendingblocks;
2739
2740         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
2741         fs = ump->um_fs;
2742         fs_pendingblocks = 0;
2743         tmpval = 1;
2744         baselbns[0] = NDADDR;
2745         for (i = 1; i < NIADDR; i++) {
2746                 tmpval *= NINDIR(fs);
2747                 baselbns[i] = baselbns[i - 1] + tmpval;
2748         }
2749         nblocks = btodb(fs->fs_bsize);
2750         blocksreleased = 0;
2751         /*
2752          * Release all extended attribute blocks or frags.
2753          */
2754         if (freeblks->fb_oldextsize > 0) {
2755                 for (i = (NXADDR - 1); i >= 0; i--) {
2756                         if ((bn = freeblks->fb_eblks[i]) == 0)
2757                                 continue;
2758                         bsize = sblksize(fs, freeblks->fb_oldextsize, i);
2759                         ffs_blkfree(ump, fs, freeblks->fb_devvp, bn, bsize,
2760                             freeblks->fb_previousinum);
2761                         blocksreleased += btodb(bsize);
2762                 }
2763         }
2764         /*
2765          * Release all data blocks or frags.
2766          */
2767         if (freeblks->fb_oldsize > 0) {
2768                 /*
2769                  * Indirect blocks first.
2770                  */
2771                 for (level = (NIADDR - 1); level >= 0; level--) {
2772                         if ((bn = freeblks->fb_iblks[level]) == 0)
2773                                 continue;
2774                         if ((error = indir_trunc(freeblks, fsbtodb(fs, bn),
2775                             level, baselbns[level], &blocksreleased)) != 0)
2776                                 allerror = error;
2777                         ffs_blkfree(ump, fs, freeblks->fb_devvp, bn,
2778                             fs->fs_bsize, freeblks->fb_previousinum);
2779                         fs_pendingblocks += nblocks;
2780                         blocksreleased += nblocks;
2781                 }
2782                 /*
2783                  * All direct blocks or frags.
2784                  */
2785                 for (i = (NDADDR - 1); i >= 0; i--) {
2786                         if ((bn = freeblks->fb_dblks[i]) == 0)
2787                                 continue;
2788                         bsize = sblksize(fs, freeblks->fb_oldsize, i);
2789                         ffs_blkfree(ump, fs, freeblks->fb_devvp, bn, bsize,
2790                             freeblks->fb_previousinum);
2791                         fs_pendingblocks += btodb(bsize);
2792                         blocksreleased += btodb(bsize);
2793                 }
2794         }
2795         UFS_LOCK(ump);
2796         fs->fs_pendingblocks -= fs_pendingblocks;
2797         UFS_UNLOCK(ump);
2798         /*
2799          * If we still have not finished background cleanup, then check
2800          * to see if the block count needs to be adjusted.
2801          */
2802         if (freeblks->fb_chkcnt != blocksreleased &&
2803             (fs->fs_flags & FS_UNCLEAN) != 0 &&
2804             ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_previousinum,
2805                 (flags & LK_NOWAIT) | LK_EXCLUSIVE, &vp, FFSV_FORCEINSMQ)
2806             == 0) {
2807                 ip = VTOI(vp);
2808                 DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + \
2809                     freeblks->fb_chkcnt - blocksreleased);
2810                 ip->i_flag |= IN_CHANGE;
2811                 vput(vp);
2812         }
2813
2814 #ifdef INVARIANTS
2815         if (freeblks->fb_chkcnt != blocksreleased &&
2816             ((fs->fs_flags & FS_UNCLEAN) == 0 || (flags & LK_NOWAIT) != 0))
2817                 printf("handle_workitem_freeblocks: block count\n");
2818         if (allerror)
2819                 softdep_error("handle_workitem_freeblks", allerror);
2820 #endif /* INVARIANTS */
2821
2822         ACQUIRE_LOCK(&lk);
2823         WORKITEM_FREE(freeblks, D_FREEBLKS);
2824         FREE_LOCK(&lk);
2825 }
2826
2827 /*
2828  * Release blocks associated with the inode ip and stored in the indirect
2829  * block dbn. If level is greater than SINGLE, the block is an indirect block
2830  * and recursive calls to indirtrunc must be used to cleanse other indirect
2831  * blocks.
2832  */
2833 static int
2834 indir_trunc(freeblks, dbn, level, lbn, countp)
2835         struct freeblks *freeblks;
2836         ufs2_daddr_t dbn;
2837         int level;
2838         ufs_lbn_t lbn;
2839         ufs2_daddr_t *countp;
2840 {
2841         struct buf *bp;
2842         struct fs *fs;
2843         struct worklist *wk;
2844         struct indirdep *indirdep;
2845         struct ufsmount *ump;
2846         ufs1_daddr_t *bap1 = 0;
2847         ufs2_daddr_t nb, *bap2 = 0;
2848         ufs_lbn_t lbnadd;
2849         int i, nblocks, ufs1fmt;
2850         int error, allerror = 0;
2851         int fs_pendingblocks;
2852
2853         ump = VFSTOUFS(freeblks->fb_list.wk_mp);
2854         fs = ump->um_fs;
2855         fs_pendingblocks = 0;
2856         lbnadd = 1;
2857         for (i = level; i > 0; i--)
2858                 lbnadd *= NINDIR(fs);
2859         /*
2860          * Get buffer of block pointers to be freed. This routine is not
2861          * called until the zero'ed inode has been written, so it is safe
2862          * to free blocks as they are encountered. Because the inode has
2863          * been zero'ed, calls to bmap on these blocks will fail. So, we
2864          * have to use the on-disk address and the block device for the
2865          * filesystem to look them up. If the file was deleted before its
2866          * indirect blocks were all written to disk, the routine that set
2867          * us up (deallocate_dependencies) will have arranged to leave
2868          * a complete copy of the indirect block in memory for our use.
2869          * Otherwise we have to read the blocks in from the disk.
2870          */
2871 #ifdef notyet
2872         bp = getblk(freeblks->fb_devvp, dbn, (int)fs->fs_bsize, 0, 0,
2873             GB_NOCREAT);
2874 #else
2875         bp = incore(&freeblks->fb_devvp->v_bufobj, dbn);
2876 #endif
2877         ACQUIRE_LOCK(&lk);
2878         if (bp != NULL && (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2879                 if (wk->wk_type != D_INDIRDEP ||
2880                     (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2881                     (indirdep->ir_state & GOINGAWAY) == 0)
2882                         panic("indir_trunc: lost indirdep");
2883                 WORKLIST_REMOVE(wk);
2884                 WORKITEM_FREE(indirdep, D_INDIRDEP);
2885                 if (!LIST_EMPTY(&bp->b_dep))
2886                         panic("indir_trunc: dangling dep");
2887                 ump->um_numindirdeps -= 1;
2888                 FREE_LOCK(&lk);
2889         } else {
2890 #ifdef notyet
2891                 if (bp)
2892                         brelse(bp);
2893 #endif
2894                 FREE_LOCK(&lk);
2895                 error = bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
2896                     NOCRED, &bp);
2897                 if (error) {
2898                         brelse(bp);
2899                         return (error);
2900                 }
2901         }
2902         /*
2903          * Recursively free indirect blocks.
2904          */
2905         if (ump->um_fstype == UFS1) {
2906                 ufs1fmt = 1;
2907                 bap1 = (ufs1_daddr_t *)bp->b_data;
2908         } else {
2909                 ufs1fmt = 0;
2910                 bap2 = (ufs2_daddr_t *)bp->b_data;
2911         }
2912         nblocks = btodb(fs->fs_bsize);
2913         for (i = NINDIR(fs) - 1; i >= 0; i--) {
2914                 if (ufs1fmt)
2915                         nb = bap1[i];
2916                 else
2917                         nb = bap2[i];
2918                 if (nb == 0)
2919                         continue;
2920                 if (level != 0) {
2921                         if ((error = indir_trunc(freeblks, fsbtodb(fs, nb),
2922                              level - 1, lbn + (i * lbnadd), countp)) != 0)
2923                                 allerror = error;
2924                 }
2925                 ffs_blkfree(ump, fs, freeblks->fb_devvp, nb, fs->fs_bsize,
2926                     freeblks->fb_previousinum);
2927                 fs_pendingblocks += nblocks;
2928                 *countp += nblocks;
2929         }
2930         UFS_LOCK(ump);
2931         fs->fs_pendingblocks -= fs_pendingblocks;
2932         UFS_UNLOCK(ump);
2933         bp->b_flags |= B_INVAL | B_NOCACHE;
2934         brelse(bp);
2935         return (allerror);
2936 }
2937
2938 /*
2939  * Free an allocindir.
2940  * This routine must be called with splbio interrupts blocked.
2941  */
2942 static void
2943 free_allocindir(aip, inodedep)
2944         struct allocindir *aip;
2945         struct inodedep *inodedep;
2946 {
2947         struct freefrag *freefrag;
2948
2949         mtx_assert(&lk, MA_OWNED);
2950         if ((aip->ai_state & DEPCOMPLETE) == 0)
2951                 LIST_REMOVE(aip, ai_deps);
2952         if (aip->ai_state & ONWORKLIST)
2953                 WORKLIST_REMOVE(&aip->ai_list);
2954         LIST_REMOVE(aip, ai_next);
2955         if ((freefrag = aip->ai_freefrag) != NULL) {
2956                 if (inodedep == NULL)
2957                         add_to_worklist(&freefrag->ff_list);
2958                 else
2959                         WORKLIST_INSERT(&inodedep->id_bufwait,
2960                             &freefrag->ff_list);
2961         }
2962         WORKITEM_FREE(aip, D_ALLOCINDIR);
2963 }
2964
2965 /*
2966  * Directory entry addition dependencies.
2967  * 
2968  * When adding a new directory entry, the inode (with its incremented link
2969  * count) must be written to disk before the directory entry's pointer to it.
2970  * Also, if the inode is newly allocated, the corresponding freemap must be
2971  * updated (on disk) before the directory entry's pointer. These requirements
2972  * are met via undo/redo on the directory entry's pointer, which consists
2973  * simply of the inode number.
2974  * 
2975  * As directory entries are added and deleted, the free space within a
2976  * directory block can become fragmented.  The ufs filesystem will compact
2977  * a fragmented directory block to make space for a new entry. When this
2978  * occurs, the offsets of previously added entries change. Any "diradd"
2979  * dependency structures corresponding to these entries must be updated with
2980  * the new offsets.
2981  */
2982
2983 /*
2984  * This routine is called after the in-memory inode's link
2985  * count has been incremented, but before the directory entry's
2986  * pointer to the inode has been set.
2987  */
2988 int
2989 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
2990         struct buf *bp;         /* buffer containing directory block */
2991         struct inode *dp;       /* inode for directory */
2992         off_t diroffset;        /* offset of new entry in directory */
2993         ino_t newinum;          /* inode referenced by new directory entry */
2994         struct buf *newdirbp;   /* non-NULL => contents of new mkdir */
2995         int isnewblk;           /* entry is in a newly allocated block */
2996 {
2997         int offset;             /* offset of new entry within directory block */
2998         ufs_lbn_t lbn;          /* block in directory containing new entry */
2999         struct fs *fs;
3000         struct diradd *dap;
3001         struct allocdirect *adp;
3002         struct pagedep *pagedep;
3003         struct inodedep *inodedep;
3004         struct newdirblk *newdirblk = 0;
3005         struct mkdir *mkdir1, *mkdir2;
3006         struct mount *mp;
3007
3008         /*
3009          * Whiteouts have no dependencies.
3010          */
3011         if (newinum == WINO) {
3012                 if (newdirbp != NULL)
3013                         bdwrite(newdirbp);
3014                 return (0);
3015         }
3016         mp = UFSTOVFS(dp->i_ump);
3017         fs = dp->i_fs;
3018         lbn = lblkno(fs, diroffset);
3019         offset = blkoff(fs, diroffset);
3020         MALLOC(dap, struct diradd *, sizeof(struct diradd), M_DIRADD,
3021                 M_SOFTDEP_FLAGS|M_ZERO);
3022         workitem_alloc(&dap->da_list, D_DIRADD, mp);
3023         dap->da_offset = offset;
3024         dap->da_newinum = newinum;
3025         dap->da_state = ATTACHED;
3026         if (isnewblk && lbn < NDADDR && fragoff(fs, diroffset) == 0) {
3027                 MALLOC(newdirblk, struct newdirblk *, sizeof(struct newdirblk),
3028                     M_NEWDIRBLK, M_SOFTDEP_FLAGS);
3029                 workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
3030         }
3031         if (newdirbp == NULL) {
3032                 dap->da_state |= DEPCOMPLETE;
3033                 ACQUIRE_LOCK(&lk);
3034         } else {
3035                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
3036                 MALLOC(mkdir1, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
3037                     M_SOFTDEP_FLAGS);
3038                 workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
3039                 mkdir1->md_state = MKDIR_BODY;
3040                 mkdir1->md_diradd = dap;
3041                 MALLOC(mkdir2, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
3042                     M_SOFTDEP_FLAGS);
3043                 workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
3044                 mkdir2->md_state = MKDIR_PARENT;
3045                 mkdir2->md_diradd = dap;
3046                 /*
3047                  * Dependency on "." and ".." being written to disk.
3048                  */
3049                 mkdir1->md_buf = newdirbp;
3050                 ACQUIRE_LOCK(&lk);
3051                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
3052                 WORKLIST_INSERT(&newdirbp->b_dep, &mkdir1->md_list);
3053                 FREE_LOCK(&lk);
3054                 bdwrite(newdirbp);
3055                 /*
3056                  * Dependency on link count increase for parent directory
3057                  */
3058                 ACQUIRE_LOCK(&lk);
3059                 if (inodedep_lookup(mp, dp->i_number, 0, &inodedep) == 0
3060                     || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
3061                         dap->da_state &= ~MKDIR_PARENT;
3062                         WORKITEM_FREE(mkdir2, D_MKDIR);
3063                 } else {
3064                         LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
3065                         WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
3066                 }
3067         }
3068         /*
3069          * Link into parent directory pagedep to await its being written.
3070          */
3071         if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
3072                 WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
3073         dap->da_pagedep = pagedep;
3074         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
3075             da_pdlist);
3076         /*
3077          * Link into its inodedep. Put it on the id_bufwait list if the inode
3078          * is not yet written. If it is written, do the post-inode write
3079          * processing to put it on the id_pendinghd list.
3080          */
3081         (void) inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
3082         if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
3083                 diradd_inode_written(dap, inodedep);
3084         else
3085                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
3086         if (isnewblk) {
3087                 /*
3088                  * Directories growing into indirect blocks are rare
3089                  * enough and the frequency of new block allocation
3090                  * in those cases even more rare, that we choose not
3091                  * to bother tracking them. Rather we simply force the
3092                  * new directory entry to disk.
3093                  */
3094                 if (lbn >= NDADDR) {
3095                         FREE_LOCK(&lk);
3096                         /*
3097                          * We only have a new allocation when at the
3098                          * beginning of a new block, not when we are
3099                          * expanding into an existing block.
3100                          */
3101                         if (blkoff(fs, diroffset) == 0)
3102                                 return (1);
3103                         return (0);
3104                 }
3105                 /*
3106                  * We only have a new allocation when at the beginning
3107                  * of a new fragment, not when we are expanding into an
3108                  * existing fragment. Also, there is nothing to do if we
3109                  * are already tracking this block.
3110                  */
3111                 if (fragoff(fs, diroffset) != 0) {
3112                         FREE_LOCK(&lk);
3113                         return (0);
3114                 }
3115                 if ((pagedep->pd_state & NEWBLOCK) != 0) {
3116                         WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
3117                         FREE_LOCK(&lk);
3118                         return (0);
3119                 }
3120                 /*
3121                  * Find our associated allocdirect and have it track us.
3122                  */
3123                 if (inodedep_lookup(mp, dp->i_number, 0, &inodedep) == 0)
3124                         panic("softdep_setup_directory_add: lost inodedep");
3125                 adp = TAILQ_LAST(&inodedep->id_newinoupdt, allocdirectlst);
3126                 if (adp == NULL || adp->ad_lbn != lbn)
3127                         panic("softdep_setup_directory_add: lost entry");
3128                 pagedep->pd_state |= NEWBLOCK;
3129                 newdirblk->db_pagedep = pagedep;
3130                 WORKLIST_INSERT(&adp->ad_newdirblk, &newdirblk->db_list);
3131         }
3132         FREE_LOCK(&lk);
3133         return (0);
3134 }
3135
3136 /*
3137  * This procedure is called to change the offset of a directory
3138  * entry when compacting a directory block which must be owned
3139  * exclusively by the caller. Note that the actual entry movement
3140  * must be done in this procedure to ensure that no I/O completions
3141  * occur while the move is in progress.
3142  */
3143 void 
3144 softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
3145         struct inode *dp;       /* inode for directory */
3146         caddr_t base;           /* address of dp->i_offset */
3147         caddr_t oldloc;         /* address of old directory location */
3148         caddr_t newloc;         /* address of new directory location */
3149         int entrysize;          /* size of directory entry */
3150 {
3151         int offset, oldoffset, newoffset;
3152         struct pagedep *pagedep;
3153         struct diradd *dap;
3154         ufs_lbn_t lbn;
3155
3156         ACQUIRE_LOCK(&lk);
3157         lbn = lblkno(dp->i_fs, dp->i_offset);
3158         offset = blkoff(dp->i_fs, dp->i_offset);
3159         if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
3160                 goto done;
3161         oldoffset = offset + (oldloc - base);
3162         newoffset = offset + (newloc - base);
3163
3164         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
3165                 if (dap->da_offset != oldoffset)
3166                         continue;
3167                 dap->da_offset = newoffset;
3168                 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
3169                         break;
3170                 LIST_REMOVE(dap, da_pdlist);
3171                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
3172                     dap, da_pdlist);
3173                 break;
3174         }
3175         if (dap == NULL) {
3176
3177                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
3178                         if (dap->da_offset == oldoffset) {
3179                                 dap->da_offset = newoffset;
3180                                 break;
3181                         }
3182                 }
3183         }
3184 done:
3185         bcopy(oldloc, newloc, entrysize);
3186         FREE_LOCK(&lk);
3187 }
3188
3189 /*
3190  * Free a diradd dependency structure. This routine must be called
3191  * with splbio interrupts blocked.
3192  */
3193 static void
3194 free_diradd(dap)
3195         struct diradd *dap;
3196 {
3197         struct dirrem *dirrem;
3198         struct pagedep *pagedep;
3199         struct inodedep *inodedep;
3200         struct mkdir *mkdir, *nextmd;
3201
3202         mtx_assert(&lk, MA_OWNED);
3203         WORKLIST_REMOVE(&dap->da_list);
3204         LIST_REMOVE(dap, da_pdlist);
3205         if ((dap->da_state & DIRCHG) == 0) {
3206                 pagedep = dap->da_pagedep;
3207         } else {
3208                 dirrem = dap->da_previous;
3209                 pagedep = dirrem->dm_pagedep;
3210                 dirrem->dm_dirinum = pagedep->pd_ino;
3211                 add_to_worklist(&dirrem->dm_list);
3212         }
3213         if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
3214             0, &inodedep) != 0)
3215                 (void) free_inodedep(inodedep);
3216         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
3217                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
3218                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
3219                         if (mkdir->md_diradd != dap)
3220                                 continue;
3221                         dap->da_state &= ~mkdir->md_state;
3222                         WORKLIST_REMOVE(&mkdir->md_list);
3223                         LIST_REMOVE(mkdir, md_mkdirs);
3224                         WORKITEM_FREE(mkdir, D_MKDIR);
3225                 }
3226                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
3227                         panic("free_diradd: unfound ref");
3228         }
3229         WORKITEM_FREE(dap, D_DIRADD);
3230 }
3231
3232 /*
3233  * Directory entry removal dependencies.
3234  * 
3235  * When removing a directory entry, the entry's inode pointer must be
3236  * zero'ed on disk before the corresponding inode's link count is decremented
3237  * (possibly freeing the inode for re-use). This dependency is handled by
3238  * updating the directory entry but delaying the inode count reduction until
3239  * after the directory block has been written to disk. After this point, the
3240  * inode count can be decremented whenever it is convenient.
3241  */
3242
3243 /*
3244  * This routine should be called immediately after removing
3245  * a directory entry.  The inode's link count should not be
3246  * decremented by the calling procedure -- the soft updates
3247  * code will do this task when it is safe.
3248  */
3249 void 
3250 softdep_setup_remove(bp, dp, ip, isrmdir)
3251         struct buf *bp;         /* buffer containing directory block */
3252         struct inode *dp;       /* inode for the directory being modified */
3253         struct inode *ip;       /* inode for directory entry being removed */
3254         int isrmdir;            /* indicates if doing RMDIR */
3255 {
3256         struct dirrem *dirrem, *prevdirrem;
3257
3258         /*
3259          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
3260          */
3261         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
3262
3263         /*
3264          * If the COMPLETE flag is clear, then there were no active
3265          * entries and we want to roll back to a zeroed entry until
3266          * the new inode is committed to disk. If the COMPLETE flag is
3267          * set then we have deleted an entry that never made it to
3268          * disk. If the entry we deleted resulted from a name change,
3269          * then the old name still resides on disk. We cannot delete
3270          * its inode (returned to us in prevdirrem) until the zeroed
3271          * directory entry gets to disk. The new inode has never been
3272          * referenced on the disk, so can be deleted immediately.
3273          */
3274         if ((dirrem->dm_state & COMPLETE) == 0) {
3275                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
3276                     dm_next);
3277                 FREE_LOCK(&lk);
3278         } else {
3279                 if (prevdirrem != NULL)
3280                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
3281                             prevdirrem, dm_next);
3282                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
3283                 FREE_LOCK(&lk);
3284                 handle_workitem_remove(dirrem, NULL);
3285         }
3286 }
3287
3288 /*
3289  * Allocate a new dirrem if appropriate and return it along with
3290  * its associated pagedep. Called without a lock, returns with lock.
3291  */
3292 static long num_dirrem;         /* number of dirrem allocated */
3293 static struct dirrem *
3294 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
3295         struct buf *bp;         /* buffer containing directory block */
3296         struct inode *dp;       /* inode for the directory being modified */
3297         struct inode *ip;       /* inode for directory entry being removed */
3298         int isrmdir;            /* indicates if doing RMDIR */
3299         struct dirrem **prevdirremp; /* previously referenced inode, if any */
3300 {
3301         int offset;
3302         ufs_lbn_t lbn;
3303         struct diradd *dap;
3304         struct dirrem *dirrem;
3305         struct pagedep *pagedep;
3306
3307         /*
3308          * Whiteouts have no deletion dependencies.
3309          */
3310         if (ip == NULL)
3311                 panic("newdirrem: whiteout");
3312         /*
3313          * If we are over our limit, try to improve the situation.
3314          * Limiting the number of dirrem structures will also limit
3315          * the number of freefile and freeblks structures.
3316          */
3317         ACQUIRE_LOCK(&lk);
3318         if (num_dirrem > max_softdeps / 2)
3319                 (void) request_cleanup(ITOV(dp)->v_mount, FLUSH_REMOVE);
3320         num_dirrem += 1;
3321         FREE_LOCK(&lk);
3322         MALLOC(dirrem, struct dirrem *, sizeof(struct dirrem),
3323                 M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
3324         workitem_alloc(&dirrem->dm_list, D_DIRREM, ITOV(dp)->v_mount);
3325         dirrem->dm_state = isrmdir ? RMDIR : 0;
3326         dirrem->dm_oldinum = ip->i_number;
3327         *prevdirremp = NULL;
3328
3329         ACQUIRE_LOCK(&lk);
3330         lbn = lblkno(dp->i_fs, dp->i_offset);
3331         offset = blkoff(dp->i_fs, dp->i_offset);
3332         if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
3333                 WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
3334         dirrem->dm_pagedep = pagedep;
3335         /*
3336          * Check for a diradd dependency for the same directory entry.
3337          * If present, then both dependencies become obsolete and can
3338          * be de-allocated. Check for an entry on both the pd_dirraddhd
3339          * list and the pd_pendinghd list.
3340          */
3341
3342         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
3343                 if (dap->da_offset == offset)
3344                         break;
3345         if (dap == NULL) {
3346
3347                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
3348                         if (dap->da_offset == offset)
3349                                 break;
3350                 if (dap == NULL)
3351                         return (dirrem);
3352         }
3353         /*
3354          * Must be ATTACHED at this point.
3355          */
3356         if ((dap->da_state & ATTACHED) == 0)
3357                 panic("newdirrem: not ATTACHED");
3358         if (dap->da_newinum != ip->i_number)
3359                 panic("newdirrem: inum %d should be %d",
3360                     ip->i_number, dap->da_newinum);
3361         /*
3362          * If we are deleting a changed name that never made it to disk,
3363          * then return the dirrem describing the previous inode (which
3364          * represents the inode currently referenced from this entry on disk).
3365          */
3366         if ((dap->da_state & DIRCHG) != 0) {
3367                 *prevdirremp = dap->da_previous;
3368                 dap->da_state &= ~DIRCHG;
3369                 dap->da_pagedep = pagedep;
3370         }
3371         /*
3372          * We are deleting an entry that never made it to disk.
3373          * Mark it COMPLETE so we can delete its inode immediately.
3374          */
3375         dirrem->dm_state |= COMPLETE;
3376         free_diradd(dap);
3377         return (dirrem);
3378 }
3379
3380 /*
3381  * Directory entry change dependencies.
3382  * 
3383  * Changing an existing directory entry requires that an add operation
3384  * be completed first followed by a deletion. The semantics for the addition
3385  * are identical to the description of adding a new entry above except
3386  * that the rollback is to the old inode number rather than zero. Once
3387  * the addition dependency is completed, the removal is done as described
3388  * in the removal routine above.
3389  */
3390
3391 /*
3392  * This routine should be called immediately after changing
3393  * a directory entry.  The inode's link count should not be
3394  * decremented by the calling procedure -- the soft updates
3395  * code will perform this task when it is safe.
3396  */
3397 void 
3398 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
3399         struct buf *bp;         /* buffer containing directory block */
3400         struct inode *dp;       /* inode for the directory being modified */
3401         struct inode *ip;       /* inode for directory entry being removed */
3402         ino_t newinum;          /* new inode number for changed entry */
3403         int isrmdir;            /* indicates if doing RMDIR */
3404 {
3405         int offset;
3406         struct diradd *dap = NULL;
3407         struct dirrem *dirrem, *prevdirrem;
3408         struct pagedep *pagedep;
3409         struct inodedep *inodedep;
3410         struct mount *mp;
3411
3412         offset = blkoff(dp->i_fs, dp->i_offset);
3413         mp = UFSTOVFS(dp->i_ump);
3414
3415         /*
3416          * Whiteouts do not need diradd dependencies.
3417          */
3418         if (newinum != WINO) {
3419                 MALLOC(dap, struct diradd *, sizeof(struct diradd),
3420                     M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
3421                 workitem_alloc(&dap->da_list, D_DIRADD, mp);
3422                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
3423                 dap->da_offset = offset;
3424                 dap->da_newinum = newinum;
3425         }
3426
3427         /*
3428          * Allocate a new dirrem and ACQUIRE_LOCK.
3429          */
3430         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
3431         pagedep = dirrem->dm_pagedep;
3432         /*
3433          * The possible values for isrmdir:
3434          *      0 - non-directory file rename
3435          *      1 - directory rename within same directory
3436          *   inum - directory rename to new directory of given inode number
3437          * When renaming to a new directory, we are both deleting and
3438          * creating a new directory entry, so the link count on the new
3439          * directory should not change. Thus we do not need the followup
3440          * dirrem which is usually done in handle_workitem_remove. We set
3441          * the DIRCHG flag to tell handle_workitem_remove to skip the 
3442          * followup dirrem.
3443          */
3444         if (isrmdir > 1)
3445                 dirrem->dm_state |= DIRCHG;
3446
3447         /*
3448          * Whiteouts have no additional dependencies,
3449          * so just put the dirrem on the correct list.
3450          */
3451         if (newinum == WINO) {
3452                 if ((dirrem->dm_state & COMPLETE) == 0) {
3453                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
3454                             dm_next);
3455                 } else {
3456                         dirrem->dm_dirinum = pagedep->pd_ino;
3457                         add_to_worklist(&dirrem->dm_list);
3458                 }
3459                 FREE_LOCK(&lk);
3460                 return;
3461         }
3462
3463         /*
3464          * If the COMPLETE flag is clear, then there were no active
3465          * entries and we want to roll back to the previous inode until
3466          * the new inode is committed to disk. If the COMPLETE flag is
3467          * set, then we have deleted an entry that never made it to disk.
3468          * If the entry we deleted resulted from a name change, then the old
3469          * inode reference still resides on disk. Any rollback that we do
3470          * needs to be to that old inode (returned to us in prevdirrem). If
3471          * the entry we deleted resulted from a create, then there is
3472          * no entry on the disk, so we want to roll back to zero rather
3473          * than the uncommitted inode. In either of the COMPLETE cases we
3474          * want to immediately free the unwritten and unreferenced inode.
3475          */
3476         if ((dirrem->dm_state & COMPLETE) == 0) {
3477                 dap->da_previous = dirrem;
3478         } else {
3479                 if (prevdirrem != NULL) {
3480                         dap->da_previous = prevdirrem;
3481                 } else {
3482                         dap->da_state &= ~DIRCHG;
3483                         dap->da_pagedep = pagedep;
3484                 }
3485                 dirrem->dm_dirinum = pagedep->pd_ino;
3486                 add_to_worklist(&dirrem->dm_list);
3487         }
3488         /*
3489          * Link into its inodedep. Put it on the id_bufwait list if the inode
3490          * is not yet written. If it is written, do the post-inode write
3491          * processing to put it on the id_pendinghd list.
3492          */
3493         if (inodedep_lookup(mp, newinum, DEPALLOC, &inodedep) == 0 ||
3494             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
3495                 dap->da_state |= COMPLETE;
3496                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3497                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3498         } else {
3499                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
3500                     dap, da_pdlist);
3501                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
3502         }
3503         FREE_LOCK(&lk);
3504 }
3505
3506 /*
3507  * Called whenever the link count on an inode is changed.
3508  * It creates an inode dependency so that the new reference(s)
3509  * to the inode cannot be committed to disk until the updated
3510  * inode has been written.
3511  */
3512 void
3513 softdep_change_linkcnt(ip)
3514         struct inode *ip;       /* the inode with the increased link count */
3515 {
3516         struct inodedep *inodedep;
3517
3518         ACQUIRE_LOCK(&lk);
3519         (void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number,
3520             DEPALLOC, &inodedep);
3521         if (ip->i_nlink < ip->i_effnlink)
3522                 panic("softdep_change_linkcnt: bad delta");
3523         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3524         FREE_LOCK(&lk);
3525 }
3526
3527 /*
3528  * Called when the effective link count and the reference count
3529  * on an inode drops to zero. At this point there are no names
3530  * referencing the file in the filesystem and no active file
3531  * references. The space associated with the file will be freed
3532  * as soon as the necessary soft dependencies are cleared.
3533  */
3534 void
3535 softdep_releasefile(ip)
3536         struct inode *ip;       /* inode with the zero effective link count */
3537 {
3538         struct inodedep *inodedep;
3539         struct fs *fs;
3540         int extblocks;
3541
3542         if (ip->i_effnlink > 0)
3543                 panic("softdep_releasefile: file still referenced");
3544         /*
3545          * We may be called several times as the on-disk link count
3546          * drops to zero. We only want to account for the space once.
3547          */
3548         if (ip->i_flag & IN_SPACECOUNTED)
3549                 return;
3550         /*
3551          * We have to deactivate a snapshot otherwise copyonwrites may
3552          * add blocks and the cleanup may remove blocks after we have
3553          * tried to account for them.
3554          */
3555         if ((ip->i_flags & SF_SNAPSHOT) != 0)
3556                 ffs_snapremove(ITOV(ip));
3557         /*
3558          * If we are tracking an nlinkdelta, we have to also remember
3559          * whether we accounted for the freed space yet.
3560          */
3561         ACQUIRE_LOCK(&lk);
3562         if ((inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0, &inodedep)))
3563                 inodedep->id_state |= SPACECOUNTED;
3564         FREE_LOCK(&lk);
3565         fs = ip->i_fs;
3566         extblocks = 0;
3567         if (fs->fs_magic == FS_UFS2_MAGIC)
3568                 extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
3569         UFS_LOCK(ip->i_ump);
3570         ip->i_fs->fs_pendingblocks += DIP(ip, i_blocks) - extblocks;
3571         ip->i_fs->fs_pendinginodes += 1;
3572         UFS_UNLOCK(ip->i_ump);
3573         ip->i_flag |= IN_SPACECOUNTED;
3574 }
3575
3576 /*
3577  * This workitem decrements the inode's link count.
3578  * If the link count reaches zero, the file is removed.
3579  */
3580 static void 
3581 handle_workitem_remove(dirrem, xp)
3582         struct dirrem *dirrem;
3583         struct vnode *xp;
3584 {
3585         struct thread *td = curthread;
3586         struct inodedep *inodedep;
3587         struct vnode *vp;
3588         struct inode *ip;
3589         ino_t oldinum;
3590         int error;
3591
3592         if ((vp = xp) == NULL &&
3593             (error = ffs_vgetf(dirrem->dm_list.wk_mp,
3594                     dirrem->dm_oldinum, LK_EXCLUSIVE, &vp, FFSV_FORCEINSMQ)) != 0) {
3595                 softdep_error("handle_workitem_remove: vget", error);
3596                 return;
3597         }
3598         ip = VTOI(vp);
3599         ACQUIRE_LOCK(&lk);
3600         if ((inodedep_lookup(dirrem->dm_list.wk_mp,
3601             dirrem->dm_oldinum, 0, &inodedep)) == 0)
3602                 panic("handle_workitem_remove: lost inodedep");
3603         /*
3604          * Normal file deletion.
3605          */
3606         if ((dirrem->dm_state & RMDIR) == 0) {
3607                 ip->i_nlink--;
3608                 DIP_SET(ip, i_nlink, ip->i_nlink);
3609                 ip->i_flag |= IN_CHANGE;
3610                 if (ip->i_nlink < ip->i_effnlink)
3611                         panic("handle_workitem_remove: bad file delta");
3612                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3613                 num_dirrem -= 1;
3614                 WORKITEM_FREE(dirrem, D_DIRREM);
3615                 FREE_LOCK(&lk);
3616                 vput(vp);
3617                 return;
3618         }
3619         /*
3620          * Directory deletion. Decrement reference count for both the
3621          * just deleted parent directory entry and the reference for ".".
3622          * Next truncate the directory to length zero. When the
3623          * truncation completes, arrange to have the reference count on
3624          * the parent decremented to account for the loss of "..".
3625          */
3626         ip->i_nlink -= 2;
3627         DIP_SET(ip, i_nlink, ip->i_nlink);
3628         ip->i_flag |= IN_CHANGE;
3629         if (ip->i_nlink < ip->i_effnlink)
3630                 panic("handle_workitem_remove: bad dir delta");
3631         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
3632         FREE_LOCK(&lk);
3633         if ((error = ffs_truncate(vp, (off_t)0, 0, td->td_ucred, td)) != 0)
3634                 softdep_error("handle_workitem_remove: truncate", error);
3635         ACQUIRE_LOCK(&lk);
3636         /*
3637          * Rename a directory to a new parent. Since, we are both deleting
3638          * and creating a new directory entry, the link count on the new
3639          * directory should not change. Thus we skip the followup dirrem.
3640          */
3641         if (dirrem->dm_state & DIRCHG) {
3642                 num_dirrem -= 1;
3643                 WORKITEM_FREE(dirrem, D_DIRREM);
3644                 FREE_LOCK(&lk);
3645                 vput(vp);
3646                 return;
3647         }
3648         /*
3649          * If the inodedep does not exist, then the zero'ed inode has
3650          * been written to disk. If the allocated inode has never been
3651          * written to disk, then the on-disk inode is zero'ed. In either
3652          * case we can remove the file immediately.
3653          */
3654         dirrem->dm_state = 0;
3655         oldinum = dirrem->dm_oldinum;
3656         dirrem->dm_oldinum = dirrem->dm_dirinum;
3657         if (inodedep_lookup(dirrem->dm_list.wk_mp, oldinum,
3658             0, &inodedep) == 0 || check_inode_unwritten(inodedep)) {
3659                 if (xp != NULL)
3660                         add_to_worklist(&dirrem->dm_list);
3661                 FREE_LOCK(&lk);
3662                 vput(vp);
3663                 if (xp == NULL)
3664                         handle_workitem_remove(dirrem, NULL);
3665                 return;
3666         }
3667         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
3668         FREE_LOCK(&lk);
3669         ip->i_flag |= IN_CHANGE;
3670         ffs_update(vp, 0);
3671         vput(vp);
3672 }
3673
3674 /*
3675  * Inode de-allocation dependencies.
3676  * 
3677  * When an inode's link count is reduced to zero, it can be de-allocated. We
3678  * found it convenient to postpone de-allocation until after the inode is
3679  * written to disk with its new link count (zero).  At this point, all of the
3680  * on-disk inode's block pointers are nullified and, with careful dependency
3681  * list ordering, all dependencies related to the inode will be satisfied and
3682  * the corresponding dependency structures de-allocated.  So, if/when the
3683  * inode is reused, there will be no mixing of old dependencies with new
3684  * ones.  This artificial dependency is set up by the block de-allocation
3685  * procedure above (softdep_setup_freeblocks) and completed by the
3686  * following procedure.
3687  */
3688 static void 
3689 handle_workitem_freefile(freefile)
3690         struct freefile *freefile;
3691 {
3692         struct fs *fs;
3693         struct inodedep *idp;
3694         struct ufsmount *ump;
3695         int error;
3696
3697         ump = VFSTOUFS(freefile->fx_list.wk_mp);
3698         fs = ump->um_fs;
3699 #ifdef DEBUG
3700         ACQUIRE_LOCK(&lk);
3701         error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
3702         FREE_LOCK(&lk);
3703         if (error)
3704                 panic("handle_workitem_freefile: inodedep survived");
3705 #endif
3706         UFS_LOCK(ump);
3707         fs->fs_pendinginodes -= 1;
3708         UFS_UNLOCK(ump);
3709         if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
3710             freefile->fx_oldinum, freefile->fx_mode)) != 0)
3711                 softdep_error("handle_workitem_freefile", error);
3712         ACQUIRE_LOCK(&lk);
3713         WORKITEM_FREE(freefile, D_FREEFILE);
3714         FREE_LOCK(&lk);
3715 }
3716
3717
3718 /*
3719  * Helper function which unlinks marker element from work list and returns
3720  * the next element on the list.
3721  */
3722 static __inline struct worklist *
3723 markernext(struct worklist *marker)
3724 {
3725         struct worklist *next;
3726         
3727         next = LIST_NEXT(marker, wk_list);
3728         LIST_REMOVE(marker, wk_list);
3729         return next;
3730 }
3731
3732 /*
3733  * Disk writes.
3734  * 
3735  * The dependency structures constructed above are most actively used when file
3736  * system blocks are written to disk.  No constraints are placed on when a
3737  * block can be written, but unsatisfied update dependencies are made safe by
3738  * modifying (or replacing) the source memory for the duration of the disk
3739  * write.  When the disk write completes, the memory block is again brought
3740  * up-to-date.
3741  *
3742  * In-core inode structure reclamation.
3743  * 
3744  * Because there are a finite number of "in-core" inode structures, they are
3745  * reused regularly.  By transferring all inode-related dependencies to the
3746  * in-memory inode block and indexing them separately (via "inodedep"s), we
3747  * can allow "in-core" inode structures to be reused at any time and avoid
3748  * any increase in contention.
3749  *
3750  * Called just before entering the device driver to initiate a new disk I/O.
3751  * The buffer must be locked, thus, no I/O completion operations can occur
3752  * while we are manipulating its associated dependencies.
3753  */
3754 static void 
3755 softdep_disk_io_initiation(bp)
3756         struct buf *bp;         /* structure describing disk write to occur */
3757 {
3758         struct worklist *wk;
3759         struct worklist marker;
3760         struct indirdep *indirdep;
3761         struct inodedep *inodedep;
3762
3763         /*
3764          * We only care about write operations. There should never
3765          * be dependencies for reads.
3766          */
3767         if (bp->b_iocmd != BIO_WRITE)
3768                 panic("softdep_disk_io_initiation: not write");
3769
3770         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
3771         PHOLD(curproc);                 /* Don't swap out kernel stack */
3772
3773         ACQUIRE_LOCK(&lk);
3774         /*
3775          * Do any necessary pre-I/O processing.
3776          */
3777         for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
3778              wk = markernext(&marker)) {
3779                 LIST_INSERT_AFTER(wk, &marker, wk_list);
3780                 switch (wk->wk_type) {
3781
3782                 case D_PAGEDEP:
3783                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
3784                         continue;
3785
3786                 case D_INODEDEP:
3787                         inodedep = WK_INODEDEP(wk);
3788                         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
3789                                 initiate_write_inodeblock_ufs1(inodedep, bp);
3790                         else
3791                                 initiate_write_inodeblock_ufs2(inodedep, bp);
3792                         continue;
3793
3794                 case D_INDIRDEP:
3795                         indirdep = WK_INDIRDEP(wk);
3796                         if (indirdep->ir_state & GOINGAWAY)
3797                                 panic("disk_io_initiation: indirdep gone");
3798                         /*
3799                          * If there are no remaining dependencies, this
3800                          * will be writing the real pointers, so the
3801                          * dependency can be freed.
3802                          */
3803                         if (LIST_EMPTY(&indirdep->ir_deplisthd)) {
3804                                 struct buf *bp;
3805
3806                                 bp = indirdep->ir_savebp;
3807                                 bp->b_flags |= B_INVAL | B_NOCACHE;
3808                                 /* inline expand WORKLIST_REMOVE(wk); */
3809                                 wk->wk_state &= ~ONWORKLIST;
3810                                 LIST_REMOVE(wk, wk_list);
3811                                 WORKITEM_FREE(indirdep, D_INDIRDEP);
3812                                 FREE_LOCK(&lk);
3813                                 brelse(bp);
3814                                 ACQUIRE_LOCK(&lk);
3815                                 continue;
3816                         }
3817                         /*
3818                          * Replace up-to-date version with safe version.
3819                          */
3820                         FREE_LOCK(&lk);
3821                         MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
3822                             M_INDIRDEP, M_SOFTDEP_FLAGS);
3823                         ACQUIRE_LOCK(&lk);
3824                         indirdep->ir_state &= ~ATTACHED;
3825                         indirdep->ir_state |= UNDONE;
3826                         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3827                         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3828                             bp->b_bcount);
3829                         continue;
3830
3831                 case D_MKDIR:
3832                 case D_BMSAFEMAP:
3833                 case D_ALLOCDIRECT:
3834                 case D_ALLOCINDIR:
3835                         continue;
3836
3837                 default:
3838                         panic("handle_disk_io_initiation: Unexpected type %s",
3839                             TYPENAME(wk->wk_type));
3840                         /* NOTREACHED */
3841                 }
3842         }
3843         FREE_LOCK(&lk);
3844         PRELE(curproc);                 /* Allow swapout of kernel stack */
3845 }
3846
3847 /*
3848  * Called from within the procedure above to deal with unsatisfied
3849  * allocation dependencies in a directory. The buffer must be locked,
3850  * thus, no I/O completion operations can occur while we are
3851  * manipulating its associated dependencies.
3852  */
3853 static void
3854 initiate_write_filepage(pagedep, bp)
3855         struct pagedep *pagedep;
3856         struct buf *bp;
3857 {
3858         struct diradd *dap;
3859         struct direct *ep;
3860         int i;
3861
3862         if (pagedep->pd_state & IOSTARTED) {
3863                 /*
3864                  * This can only happen if there is a driver that does not
3865                  * understand chaining. Here biodone will reissue the call
3866                  * to strategy for the incomplete buffers.
3867                  */
3868                 printf("initiate_write_filepage: already started\n");
3869                 return;
3870         }
3871         pagedep->pd_state |= IOSTARTED;
3872         for (i = 0; i < DAHASHSZ; i++) {
3873                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3874                         ep = (struct direct *)
3875                             ((char *)bp->b_data + dap->da_offset);
3876                         if (ep->d_ino != dap->da_newinum)
3877                                 panic("%s: dir inum %d != new %d",
3878                                     "initiate_write_filepage",
3879                                     ep->d_ino, dap->da_newinum);
3880                         if (dap->da_state & DIRCHG)
3881                                 ep->d_ino = dap->da_previous->dm_oldinum;
3882                         else
3883                                 ep->d_ino = 0;
3884                         dap->da_state &= ~ATTACHED;
3885                         dap->da_state |= UNDONE;
3886                 }
3887         }
3888 }
3889
3890 /*
3891  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
3892  * Note that any bug fixes made to this routine must be done in the
3893  * version found below.
3894  *
3895  * Called from within the procedure above to deal with unsatisfied
3896  * allocation dependencies in an inodeblock. The buffer must be
3897  * locked, thus, no I/O completion operations can occur while we
3898  * are manipulating its associated dependencies.
3899  */
3900 static void 
3901 initiate_write_inodeblock_ufs1(inodedep, bp)
3902         struct inodedep *inodedep;
3903         struct buf *bp;                 /* The inode block */
3904 {
3905         struct allocdirect *adp, *lastadp;
3906         struct ufs1_dinode *dp;
3907         struct ufs1_dinode *sip;
3908         struct fs *fs;
3909         ufs_lbn_t i;
3910 #ifdef INVARIANTS
3911         ufs_lbn_t prevlbn = 0;
3912 #endif
3913         int deplist;
3914
3915         if (inodedep->id_state & IOSTARTED)
3916                 panic("initiate_write_inodeblock_ufs1: already started");
3917         inodedep->id_state |= IOSTARTED;
3918         fs = inodedep->id_fs;
3919         dp = (struct ufs1_dinode *)bp->b_data +
3920             ino_to_fsbo(fs, inodedep->id_ino);
3921         /*
3922          * If the bitmap is not yet written, then the allocated
3923          * inode cannot be written to disk.
3924          */
3925         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3926                 if (inodedep->id_savedino1 != NULL)
3927                         panic("initiate_write_inodeblock_ufs1: I/O underway");
3928                 FREE_LOCK(&lk);
3929                 MALLOC(sip, struct ufs1_dinode *,
3930                     sizeof(struct ufs1_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
3931                 ACQUIRE_LOCK(&lk);
3932                 inodedep->id_savedino1 = sip;
3933                 *inodedep->id_savedino1 = *dp;
3934                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3935                 dp->di_gen = inodedep->id_savedino1->di_gen;
3936                 return;
3937         }
3938         /*
3939          * If no dependencies, then there is nothing to roll back.
3940          */
3941         inodedep->id_savedsize = dp->di_size;
3942         inodedep->id_savedextsize = 0;
3943         if (TAILQ_EMPTY(&inodedep->id_inoupdt))
3944                 return;
3945         /*
3946          * Set the dependencies to busy.
3947          */
3948         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3949              adp = TAILQ_NEXT(adp, ad_next)) {
3950 #ifdef INVARIANTS
3951                 if (deplist != 0 && prevlbn >= adp->ad_lbn)
3952                         panic("softdep_write_inodeblock: lbn order");
3953                 prevlbn = adp->ad_lbn;
3954                 if (adp->ad_lbn < NDADDR &&
3955                     dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
3956                         panic("%s: direct pointer #%jd mismatch %d != %jd",
3957                             "softdep_write_inodeblock",
3958                             (intmax_t)adp->ad_lbn,
3959                             dp->di_db[adp->ad_lbn],
3960                             (intmax_t)adp->ad_newblkno);
3961                 if (adp->ad_lbn >= NDADDR &&
3962                     dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
3963                         panic("%s: indirect pointer #%jd mismatch %d != %jd",
3964                             "softdep_write_inodeblock",
3965                             (intmax_t)adp->ad_lbn - NDADDR,
3966                             dp->di_ib[adp->ad_lbn - NDADDR],
3967                             (intmax_t)adp->ad_newblkno);
3968                 deplist |= 1 << adp->ad_lbn;
3969                 if ((adp->ad_state & ATTACHED) == 0)
3970                         panic("softdep_write_inodeblock: Unknown state 0x%x",
3971                             adp->ad_state);
3972 #endif /* INVARIANTS */
3973                 adp->ad_state &= ~ATTACHED;
3974                 adp->ad_state |= UNDONE;
3975         }
3976         /*
3977          * The on-disk inode cannot claim to be any larger than the last
3978          * fragment that has been written. Otherwise, the on-disk inode
3979          * might have fragments that were not the last block in the file
3980          * which would corrupt the filesystem.
3981          */
3982         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3983              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3984                 if (adp->ad_lbn >= NDADDR)
3985                         break;
3986                 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3987                 /* keep going until hitting a rollback to a frag */
3988                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3989                         continue;
3990                 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3991                 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3992 #ifdef INVARIANTS
3993                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
3994                                 panic("softdep_write_inodeblock: lost dep1");
3995 #endif /* INVARIANTS */
3996                         dp->di_db[i] = 0;
3997                 }
3998                 for (i = 0; i < NIADDR; i++) {
3999 #ifdef INVARIANTS
4000                         if (dp->di_ib[i] != 0 &&
4001                             (deplist & ((1 << NDADDR) << i)) == 0)
4002                                 panic("softdep_write_inodeblock: lost dep2");
4003 #endif /* INVARIANTS */
4004                         dp->di_ib[i] = 0;
4005                 }
4006                 return;
4007         }
4008         /*
4009          * If we have zero'ed out the last allocated block of the file,
4010          * roll back the size to the last currently allocated block.
4011          * We know that this last allocated block is a full-sized as
4012          * we already checked for fragments in the loop above.
4013          */
4014         if (lastadp != NULL &&
4015             dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4016                 for (i = lastadp->ad_lbn; i >= 0; i--)
4017                         if (dp->di_db[i] != 0)
4018                                 break;
4019                 dp->di_size = (i + 1) * fs->fs_bsize;
4020         }
4021         /*
4022          * The only dependencies are for indirect blocks.
4023          *
4024          * The file size for indirect block additions is not guaranteed.
4025          * Such a guarantee would be non-trivial to achieve. The conventional
4026          * synchronous write implementation also does not make this guarantee.
4027          * Fsck should catch and fix discrepancies. Arguably, the file size
4028          * can be over-estimated without destroying integrity when the file
4029          * moves into the indirect blocks (i.e., is large). If we want to
4030          * postpone fsck, we are stuck with this argument.
4031          */
4032         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
4033                 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
4034 }
4035                 
4036 /*
4037  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
4038  * Note that any bug fixes made to this routine must be done in the
4039  * version found above.
4040  *
4041  * Called from within the procedure above to deal with unsatisfied
4042  * allocation dependencies in an inodeblock. The buffer must be
4043  * locked, thus, no I/O completion operations can occur while we
4044  * are manipulating its associated dependencies.
4045  */
4046 static void 
4047 initiate_write_inodeblock_ufs2(inodedep, bp)
4048         struct inodedep *inodedep;
4049         struct buf *bp;                 /* The inode block */
4050 {
4051         struct allocdirect *adp, *lastadp;
4052         struct ufs2_dinode *dp;
4053         struct ufs2_dinode *sip;
4054         struct fs *fs;
4055         ufs_lbn_t i;
4056 #ifdef INVARIANTS
4057         ufs_lbn_t prevlbn = 0;
4058 #endif
4059         int deplist;
4060
4061         if (inodedep->id_state & IOSTARTED)
4062                 panic("initiate_write_inodeblock_ufs2: already started");
4063         inodedep->id_state |= IOSTARTED;
4064         fs = inodedep->id_fs;
4065         dp = (struct ufs2_dinode *)bp->b_data +
4066             ino_to_fsbo(fs, inodedep->id_ino);
4067         /*
4068          * If the bitmap is not yet written, then the allocated
4069          * inode cannot be written to disk.
4070          */
4071         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4072                 if (inodedep->id_savedino2 != NULL)
4073                         panic("initiate_write_inodeblock_ufs2: I/O underway");
4074                 FREE_LOCK(&lk);
4075                 MALLOC(sip, struct ufs2_dinode *,
4076                     sizeof(struct ufs2_dinode), M_SAVEDINO, M_SOFTDEP_FLAGS);
4077                 ACQUIRE_LOCK(&lk);
4078                 inodedep->id_savedino2 = sip;
4079                 *inodedep->id_savedino2 = *dp;
4080                 bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
4081                 dp->di_gen = inodedep->id_savedino2->di_gen;
4082                 return;
4083         }
4084         /*
4085          * If no dependencies, then there is nothing to roll back.
4086          */
4087         inodedep->id_savedsize = dp->di_size;
4088         inodedep->id_savedextsize = dp->di_extsize;
4089         if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
4090             TAILQ_EMPTY(&inodedep->id_extupdt))
4091                 return;
4092         /*
4093          * Set the ext data dependencies to busy.
4094          */
4095         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
4096              adp = TAILQ_NEXT(adp, ad_next)) {
4097 #ifdef INVARIANTS
4098                 if (deplist != 0 && prevlbn >= adp->ad_lbn)
4099                         panic("softdep_write_inodeblock: lbn order");
4100                 prevlbn = adp->ad_lbn;
4101                 if (dp->di_extb[adp->ad_lbn] != adp->ad_newblkno)
4102                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
4103                             "softdep_write_inodeblock",
4104                             (intmax_t)adp->ad_lbn,
4105                             (intmax_t)dp->di_extb[adp->ad_lbn],
4106                             (intmax_t)adp->ad_newblkno);
4107                 deplist |= 1 << adp->ad_lbn;
4108                 if ((adp->ad_state & ATTACHED) == 0)
4109                         panic("softdep_write_inodeblock: Unknown state 0x%x",
4110                             adp->ad_state);
4111 #endif /* INVARIANTS */
4112                 adp->ad_state &= ~ATTACHED;
4113                 adp->ad_state |= UNDONE;
4114         }
4115         /*
4116          * The on-disk inode cannot claim to be any larger than the last
4117          * fragment that has been written. Otherwise, the on-disk inode
4118          * might have fragments that were not the last block in the ext
4119          * data which would corrupt the filesystem.
4120          */
4121         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
4122              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4123                 dp->di_extb[adp->ad_lbn] = adp->ad_oldblkno;
4124                 /* keep going until hitting a rollback to a frag */
4125                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4126                         continue;
4127                 dp->di_extsize = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4128                 for (i = adp->ad_lbn + 1; i < NXADDR; i++) {
4129 #ifdef INVARIANTS
4130                         if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
4131                                 panic("softdep_write_inodeblock: lost dep1");
4132 #endif /* INVARIANTS */
4133                         dp->di_extb[i] = 0;
4134                 }
4135                 lastadp = NULL;
4136                 break;
4137         }
4138         /*
4139          * If we have zero'ed out the last allocated block of the ext
4140          * data, roll back the size to the last currently allocated block.
4141          * We know that this last allocated block is a full-sized as
4142          * we already checked for fragments in the loop above.
4143          */
4144         if (lastadp != NULL &&
4145             dp->di_extsize <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4146                 for (i = lastadp->ad_lbn; i >= 0; i--)
4147                         if (dp->di_extb[i] != 0)
4148                                 break;
4149                 dp->di_extsize = (i + 1) * fs->fs_bsize;
4150         }
4151         /*
4152          * Set the file data dependencies to busy.
4153          */
4154         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4155              adp = TAILQ_NEXT(adp, ad_next)) {
4156 #ifdef INVARIANTS
4157                 if (deplist != 0 && prevlbn >= adp->ad_lbn)
4158                         panic("softdep_write_inodeblock: lbn order");
4159                 prevlbn = adp->ad_lbn;
4160                 if (adp->ad_lbn < NDADDR &&
4161                     dp->di_db[adp->ad_lbn] != adp->ad_newblkno)
4162                         panic("%s: direct pointer #%jd mismatch %jd != %jd",
4163                             "softdep_write_inodeblock",
4164                             (intmax_t)adp->ad_lbn,
4165                             (intmax_t)dp->di_db[adp->ad_lbn],
4166                             (intmax_t)adp->ad_newblkno);
4167                 if (adp->ad_lbn >= NDADDR &&
4168                     dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno)
4169                         panic("%s indirect pointer #%jd mismatch %jd != %jd",
4170                             "softdep_write_inodeblock:",
4171                             (intmax_t)adp->ad_lbn - NDADDR,
4172                             (intmax_t)dp->di_ib[adp->ad_lbn - NDADDR],
4173                             (intmax_t)adp->ad_newblkno);
4174                 deplist |= 1 << adp->ad_lbn;
4175                 if ((adp->ad_state & ATTACHED) == 0)
4176                         panic("softdep_write_inodeblock: Unknown state 0x%x",
4177                             adp->ad_state);
4178 #endif /* INVARIANTS */
4179                 adp->ad_state &= ~ATTACHED;
4180                 adp->ad_state |= UNDONE;
4181         }
4182         /*
4183          * The on-disk inode cannot claim to be any larger than the last
4184          * fragment that has been written. Otherwise, the on-disk inode
4185          * might have fragments that were not the last block in the file
4186          * which would corrupt the filesystem.
4187          */
4188         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
4189              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
4190                 if (adp->ad_lbn >= NDADDR)
4191                         break;
4192                 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
4193                 /* keep going until hitting a rollback to a frag */
4194                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
4195                         continue;
4196                 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
4197                 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
4198 #ifdef INVARIANTS
4199                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
4200                                 panic("softdep_write_inodeblock: lost dep2");
4201 #endif /* INVARIANTS */
4202                         dp->di_db[i] = 0;
4203                 }
4204                 for (i = 0; i < NIADDR; i++) {
4205 #ifdef INVARIANTS
4206                         if (dp->di_ib[i] != 0 &&
4207                             (deplist & ((1 << NDADDR) << i)) == 0)
4208                                 panic("softdep_write_inodeblock: lost dep3");
4209 #endif /* INVARIANTS */
4210                         dp->di_ib[i] = 0;
4211                 }
4212                 return;
4213         }
4214         /*
4215          * If we have zero'ed out the last allocated block of the file,
4216          * roll back the size to the last currently allocated block.
4217          * We know that this last allocated block is a full-sized as
4218          * we already checked for fragments in the loop above.
4219          */
4220         if (lastadp != NULL &&
4221             dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
4222                 for (i = lastadp->ad_lbn; i >= 0; i--)
4223                         if (dp->di_db[i] != 0)
4224                                 break;
4225                 dp->di_size = (i + 1) * fs->fs_bsize;
4226         }
4227         /*
4228          * The only dependencies are for indirect blocks.
4229          *
4230          * The file size for indirect block additions is not guaranteed.
4231          * Such a guarantee would be non-trivial to achieve. The conventional
4232          * synchronous write implementation also does not make this guarantee.
4233          * Fsck should catch and fix discrepancies. Arguably, the file size
4234          * can be over-estimated without destroying integrity when the file
4235          * moves into the indirect blocks (i.e., is large). If we want to
4236          * postpone fsck, we are stuck with this argument.
4237          */
4238         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
4239                 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
4240 }
4241
4242 /*
4243  * This routine is called during the completion interrupt
4244  * service routine for a disk write (from the procedure called
4245  * by the device driver to inform the filesystem caches of
4246  * a request completion).  It should be called early in this
4247  * procedure, before the block is made available to other
4248  * processes or other routines are called.
4249  */
4250 static void 
4251 softdep_disk_write_complete(bp)
4252         struct buf *bp;         /* describes the completed disk write */
4253 {
4254         struct worklist *wk;
4255         struct worklist *owk;
4256         struct workhead reattach;
4257         struct newblk *newblk;
4258         struct allocindir *aip;
4259         struct allocdirect *adp;
4260         struct indirdep *indirdep;
4261         struct inodedep *inodedep;
4262         struct bmsafemap *bmsafemap;
4263
4264         /*
4265          * If an error occurred while doing the write, then the data
4266          * has not hit the disk and the dependencies cannot be unrolled.
4267          */
4268         if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
4269                 return;
4270         LIST_INIT(&reattach);
4271         /*
4272          * This lock must not be released anywhere in this code segment.
4273          */
4274         ACQUIRE_LOCK(&lk);
4275         owk = NULL;
4276         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
4277                 WORKLIST_REMOVE(wk);
4278                 if (wk == owk)
4279                         panic("duplicate worklist: %p\n", wk);
4280                 owk = wk;
4281                 switch (wk->wk_type) {
4282
4283                 case D_PAGEDEP:
4284                         if (handle_written_filepage(WK_PAGEDEP(wk), bp))
4285                                 WORKLIST_INSERT(&reattach, wk);
4286                         continue;
4287
4288                 case D_INODEDEP:
4289                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
4290                                 WORKLIST_INSERT(&reattach, wk);
4291                         continue;
4292
4293                 case D_BMSAFEMAP:
4294                         bmsafemap = WK_BMSAFEMAP(wk);
4295                         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
4296                                 newblk->nb_state |= DEPCOMPLETE;
4297                                 newblk->nb_bmsafemap = NULL;
4298                                 LIST_REMOVE(newblk, nb_deps);
4299                         }
4300                         while ((adp =
4301                            LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
4302                                 adp->ad_state |= DEPCOMPLETE;
4303                                 adp->ad_buf = NULL;
4304                                 LIST_REMOVE(adp, ad_deps);
4305                                 handle_allocdirect_partdone(adp);
4306                         }
4307                         while ((aip =
4308                             LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
4309                                 aip->ai_state |= DEPCOMPLETE;
4310                                 aip->ai_buf = NULL;
4311                                 LIST_REMOVE(aip, ai_deps);
4312                                 handle_allocindir_partdone(aip);
4313                         }
4314                         while ((inodedep =
4315                              LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
4316                                 inodedep->id_state |= DEPCOMPLETE;
4317                                 LIST_REMOVE(inodedep, id_deps);
4318                                 inodedep->id_buf = NULL;
4319                         }
4320                         WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
4321                         continue;
4322
4323                 case D_MKDIR:
4324                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
4325                         continue;
4326
4327                 case D_ALLOCDIRECT:
4328                         adp = WK_ALLOCDIRECT(wk);
4329                         adp->ad_state |= COMPLETE;
4330                         handle_allocdirect_partdone(adp);
4331                         continue;
4332
4333                 case D_ALLOCINDIR:
4334                         aip = WK_ALLOCINDIR(wk);
4335                         aip->ai_state |= COMPLETE;
4336                         handle_allocindir_partdone(aip);
4337                         continue;
4338
4339                 case D_INDIRDEP:
4340                         indirdep = WK_INDIRDEP(wk);
4341                         if (indirdep->ir_state & GOINGAWAY)
4342                                 panic("disk_write_complete: indirdep gone");
4343                         bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
4344                         FREE(indirdep->ir_saveddata, M_INDIRDEP);
4345                         indirdep->ir_saveddata = 0;
4346                         indirdep->ir_state &= ~UNDONE;
4347                         indirdep->ir_state |= ATTACHED;
4348                         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
4349                                 handle_allocindir_partdone(aip);
4350                                 if (aip == LIST_FIRST(&indirdep->ir_donehd))
4351                                         panic("disk_write_complete: not gone");
4352                         }
4353                         WORKLIST_INSERT(&reattach, wk);
4354                         if ((bp->b_flags & B_DELWRI) == 0)
4355                                 stat_indir_blk_ptrs++;
4356                         bdirty(bp);
4357                         continue;
4358
4359                 default:
4360                         panic("handle_disk_write_complete: Unknown type %s",
4361                             TYPENAME(wk->wk_type));
4362                         /* NOTREACHED */
4363                 }
4364         }
4365         /*
4366          * Reattach any requests that must be redone.
4367          */
4368         while ((wk = LIST_FIRST(&reattach)) != NULL) {
4369                 WORKLIST_REMOVE(wk);
4370                 WORKLIST_INSERT(&bp->b_dep, wk);
4371         }
4372         FREE_LOCK(&lk);
4373 }
4374
4375 /*
4376  * Called from within softdep_disk_write_complete above. Note that
4377  * this routine is always called from interrupt level with further
4378  * splbio interrupts blocked.
4379  */
4380 static void 
4381 handle_allocdirect_partdone(adp)
4382         struct allocdirect *adp;        /* the completed allocdirect */
4383 {
4384         struct allocdirectlst *listhead;
4385         struct allocdirect *listadp;
4386         struct inodedep *inodedep;
4387         long bsize, delay;
4388
4389         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4390                 return;
4391         if (adp->ad_buf != NULL)
4392                 panic("handle_allocdirect_partdone: dangling dep");
4393         /*
4394          * The on-disk inode cannot claim to be any larger than the last
4395          * fragment that has been written. Otherwise, the on-disk inode
4396          * might have fragments that were not the last block in the file
4397          * which would corrupt the filesystem. Thus, we cannot free any
4398          * allocdirects after one whose ad_oldblkno claims a fragment as
4399          * these blocks must be rolled back to zero before writing the inode.
4400          * We check the currently active set of allocdirects in id_inoupdt
4401          * or id_extupdt as appropriate.
4402          */
4403         inodedep = adp->ad_inodedep;
4404         bsize = inodedep->id_fs->fs_bsize;
4405         if (adp->ad_state & EXTDATA)
4406                 listhead = &inodedep->id_extupdt;
4407         else
4408                 listhead = &inodedep->id_inoupdt;
4409         TAILQ_FOREACH(listadp, listhead, ad_next) {
4410                 /* found our block */
4411                 if (listadp == adp)
4412                         break;
4413                 /* continue if ad_oldlbn is not a fragment */
4414                 if (listadp->ad_oldsize == 0 ||
4415                     listadp->ad_oldsize == bsize)
4416                         continue;
4417                 /* hit a fragment */
4418                 return;
4419         }
4420         /*
4421          * If we have reached the end of the current list without
4422          * finding the just finished dependency, then it must be
4423          * on the future dependency list. Future dependencies cannot
4424          * be freed until they are moved to the current list.
4425          */
4426         if (listadp == NULL) {
4427 #ifdef DEBUG
4428                 if (adp->ad_state & EXTDATA)
4429                         listhead = &inodedep->id_newextupdt;
4430                 else
4431                         listhead = &inodedep->id_newinoupdt;
4432                 TAILQ_FOREACH(listadp, listhead, ad_next)
4433                         /* found our block */
4434                         if (listadp == adp)
4435                                 break;
4436                 if (listadp == NULL)
4437                         panic("handle_allocdirect_partdone: lost dep");
4438 #endif /* DEBUG */
4439                 return;
4440         }
4441         /*
4442          * If we have found the just finished dependency, then free
4443          * it along with anything that follows it that is complete.
4444          * If the inode still has a bitmap dependency, then it has
4445          * never been written to disk, hence the on-disk inode cannot
4446          * reference the old fragment so we can free it without delay.
4447          */
4448         delay = (inodedep->id_state & DEPCOMPLETE);
4449         for (; adp; adp = listadp) {
4450                 listadp = TAILQ_NEXT(adp, ad_next);
4451                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
4452                         return;
4453                 free_allocdirect(listhead, adp, delay);
4454         }
4455 }
4456
4457 /*
4458  * Called from within softdep_disk_write_complete above. Note that
4459  * this routine is always called from interrupt level with further
4460  * splbio interrupts blocked.
4461  */
4462 static void
4463 handle_allocindir_partdone(aip)
4464         struct allocindir *aip;         /* the completed allocindir */
4465 {
4466         struct indirdep *indirdep;
4467
4468         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
4469                 return;
4470         if (aip->ai_buf != NULL)
4471                 panic("handle_allocindir_partdone: dangling dependency");
4472         indirdep = aip->ai_indirdep;
4473         if (indirdep->ir_state & UNDONE) {
4474                 LIST_REMOVE(aip, ai_next);
4475                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
4476                 return;
4477         }
4478         if (indirdep->ir_state & UFS1FMT)
4479                 ((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4480                     aip->ai_newblkno;
4481         else
4482                 ((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
4483                     aip->ai_newblkno;
4484         LIST_REMOVE(aip, ai_next);
4485         if (aip->ai_freefrag != NULL)
4486                 add_to_worklist(&aip->ai_freefrag->ff_list);
4487         WORKITEM_FREE(aip, D_ALLOCINDIR);
4488 }
4489
4490 /*
4491  * Called from within softdep_disk_write_complete above to restore
4492  * in-memory inode block contents to their most up-to-date state. Note
4493  * that this routine is always called from interrupt level with further
4494  * splbio interrupts blocked.
4495  */
4496 static int 
4497 handle_written_inodeblock(inodedep, bp)
4498         struct inodedep *inodedep;
4499         struct buf *bp;         /* buffer containing the inode block */
4500 {
4501         struct worklist *wk, *filefree;
4502         struct allocdirect *adp, *nextadp;
4503         struct ufs1_dinode *dp1 = NULL;
4504         struct ufs2_dinode *dp2 = NULL;
4505         int hadchanges, fstype;
4506
4507         if ((inodedep->id_state & IOSTARTED) == 0)
4508                 panic("handle_written_inodeblock: not started");
4509         inodedep->id_state &= ~IOSTARTED;
4510         if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
4511                 fstype = UFS1;
4512                 dp1 = (struct ufs1_dinode *)bp->b_data +
4513                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4514         } else {
4515                 fstype = UFS2;
4516                 dp2 = (struct ufs2_dinode *)bp->b_data +
4517                     ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
4518         }
4519         /*
4520          * If we had to rollback the inode allocation because of
4521          * bitmaps being incomplete, then simply restore it.
4522          * Keep the block dirty so that it will not be reclaimed until
4523          * all associated dependencies have been cleared and the
4524          * corresponding updates written to disk.
4525          */
4526         if (inodedep->id_savedino1 != NULL) {
4527                 if (fstype == UFS1)
4528                         *dp1 = *inodedep->id_savedino1;
4529                 else
4530                         *dp2 = *inodedep->id_savedino2;
4531                 FREE(inodedep->id_savedino1, M_SAVEDINO);
4532                 inodedep->id_savedino1 = NULL;
4533                 if ((bp->b_flags & B_DELWRI) == 0)
4534                         stat_inode_bitmap++;
4535                 bdirty(bp);
4536                 return (1);
4537         }
4538         inodedep->id_state |= COMPLETE;
4539         /*
4540          * Roll forward anything that had to be rolled back before 
4541          * the inode could be updated.
4542          */
4543         hadchanges = 0;
4544         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
4545                 nextadp = TAILQ_NEXT(adp, ad_next);
4546                 if (adp->ad_state & ATTACHED)
4547                         panic("handle_written_inodeblock: new entry");
4548                 if (fstype == UFS1) {
4549                         if (adp->ad_lbn < NDADDR) {
4550                                 if (dp1->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4551                                         panic("%s %s #%jd mismatch %d != %jd",
4552                                             "handle_written_inodeblock:",
4553                                             "direct pointer",
4554                                             (intmax_t)adp->ad_lbn,
4555                                             dp1->di_db[adp->ad_lbn],
4556                                             (intmax_t)adp->ad_oldblkno);
4557                                 dp1->di_db[adp->ad_lbn] = adp->ad_newblkno;
4558                         } else {
4559                                 if (dp1->di_ib[adp->ad_lbn - NDADDR] != 0)
4560                                         panic("%s: %s #%jd allocated as %d",
4561                                             "handle_written_inodeblock",
4562                                             "indirect pointer",
4563                                             (intmax_t)adp->ad_lbn - NDADDR,
4564                                             dp1->di_ib[adp->ad_lbn - NDADDR]);
4565                                 dp1->di_ib[adp->ad_lbn - NDADDR] =
4566                                     adp->ad_newblkno;
4567                         }
4568                 } else {
4569                         if (adp->ad_lbn < NDADDR) {
4570                                 if (dp2->di_db[adp->ad_lbn]!=adp->ad_oldblkno)
4571                                         panic("%s: %s #%jd %s %jd != %jd",
4572                                             "handle_written_inodeblock",
4573                                             "direct pointer",
4574                                             (intmax_t)adp->ad_lbn, "mismatch",
4575                                             (intmax_t)dp2->di_db[adp->ad_lbn],
4576                                             (intmax_t)adp->ad_oldblkno);
4577                                 dp2->di_db[adp->ad_lbn] = adp->ad_newblkno;
4578                         } else {
4579                                 if (dp2->di_ib[adp->ad_lbn - NDADDR] != 0)
4580                                         panic("%s: %s #%jd allocated as %jd",
4581                                             "handle_written_inodeblock",
4582                                             "indirect pointer",
4583                                             (intmax_t)adp->ad_lbn - NDADDR,
4584                                             (intmax_t)
4585                                             dp2->di_ib[adp->ad_lbn - NDADDR]);
4586                                 dp2->di_ib[adp->ad_lbn - NDADDR] =
4587                                     adp->ad_newblkno;
4588                         }
4589                 }
4590                 adp->ad_state &= ~UNDONE;
4591                 adp->ad_state |= ATTACHED;
4592                 hadchanges = 1;
4593         }
4594         for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
4595                 nextadp = TAILQ_NEXT(adp, ad_next);
4596                 if (adp->ad_state & ATTACHED)
4597                         panic("handle_written_inodeblock: new entry");
4598                 if (dp2->di_extb[adp->ad_lbn] != adp->ad_oldblkno)
4599                         panic("%s: direct pointers #%jd %s %jd != %jd",
4600                             "handle_written_inodeblock",
4601                             (intmax_t)adp->ad_lbn, "mismatch",
4602                             (intmax_t)dp2->di_extb[adp->ad_lbn],
4603                             (intmax_t)adp->ad_oldblkno);
4604                 dp2->di_extb[adp->ad_lbn] = adp->ad_newblkno;
4605                 adp->ad_state &= ~UNDONE;
4606                 adp->ad_state |= ATTACHED;
4607                 hadchanges = 1;
4608         }
4609         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
4610                 stat_direct_blk_ptrs++;
4611         /*
4612          * Reset the file size to its most up-to-date value.
4613          */
4614         if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
4615                 panic("handle_written_inodeblock: bad size");
4616         if (fstype == UFS1) {
4617                 if (dp1->di_size != inodedep->id_savedsize) {
4618                         dp1->di_size = inodedep->id_savedsize;
4619                         hadchanges = 1;
4620                 }
4621         } else {
4622                 if (dp2->di_size != inodedep->id_savedsize) {
4623                         dp2->di_size = inodedep->id_savedsize;
4624                         hadchanges = 1;
4625                 }
4626                 if (dp2->di_extsize != inodedep->id_savedextsize) {
4627                         dp2->di_extsize = inodedep->id_savedextsize;
4628                         hadchanges = 1;
4629                 }
4630         }
4631         inodedep->id_savedsize = -1;
4632         inodedep->id_savedextsize = -1;
4633         /*
4634          * If there were any rollbacks in the inode block, then it must be
4635          * marked dirty so that its will eventually get written back in
4636          * its correct form.
4637          */
4638         if (hadchanges)
4639                 bdirty(bp);
4640         /*
4641          * Process any allocdirects that completed during the update.
4642          */
4643         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
4644                 handle_allocdirect_partdone(adp);
4645         if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
4646                 handle_allocdirect_partdone(adp);
4647         /*
4648          * Process deallocations that were held pending until the
4649          * inode had been written to disk. Freeing of the inode
4650          * is delayed until after all blocks have been freed to
4651          * avoid creation of new <vfsid, inum, lbn> triples
4652          * before the old ones have been deleted.
4653          */
4654         filefree = NULL;
4655         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
4656                 WORKLIST_REMOVE(wk);
4657                 switch (wk->wk_type) {
4658
4659                 case D_FREEFILE:
4660                         /*
4661                          * We defer adding filefree to the worklist until
4662                          * all other additions have been made to ensure
4663                          * that it will be done after all the old blocks
4664                          * have been freed.
4665                          */
4666                         if (filefree != NULL)
4667                                 panic("handle_written_inodeblock: filefree");
4668                         filefree = wk;
4669                         continue;
4670
4671                 case D_MKDIR:
4672                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
4673                         continue;
4674
4675                 case D_DIRADD:
4676                         diradd_inode_written(WK_DIRADD(wk), inodedep);
4677                         continue;
4678
4679                 case D_FREEBLKS:
4680                         wk->wk_state |= COMPLETE;
4681                         if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
4682                                 continue;
4683                          /* -- fall through -- */
4684                 case D_FREEFRAG:
4685                 case D_DIRREM:
4686                         add_to_worklist(wk);
4687                         continue;
4688
4689                 case D_NEWDIRBLK:
4690                         free_newdirblk(WK_NEWDIRBLK(wk));
4691                         continue;
4692
4693                 default:
4694                         panic("handle_written_inodeblock: Unknown type %s",
4695                             TYPENAME(wk->wk_type));
4696                         /* NOTREACHED */
4697                 }
4698         }
4699         if (filefree != NULL) {
4700                 if (free_inodedep(inodedep) == 0)
4701                         panic("handle_written_inodeblock: live inodedep");
4702                 add_to_worklist(filefree);
4703                 return (0);
4704         }
4705
4706         /*
4707          * If no outstanding dependencies, free it.
4708          */
4709         if (free_inodedep(inodedep) ||
4710             (TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
4711              TAILQ_FIRST(&inodedep->id_extupdt) == 0))
4712                 return (0);
4713         return (hadchanges);
4714 }
4715
4716 /*
4717  * Process a diradd entry after its dependent inode has been written.
4718  * This routine must be called with splbio interrupts blocked.
4719  */
4720 static void
4721 diradd_inode_written(dap, inodedep)
4722         struct diradd *dap;
4723         struct inodedep *inodedep;
4724 {
4725         struct pagedep *pagedep;
4726
4727         dap->da_state |= COMPLETE;
4728         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4729                 if (dap->da_state & DIRCHG)
4730                         pagedep = dap->da_previous->dm_pagedep;
4731                 else
4732                         pagedep = dap->da_pagedep;
4733                 LIST_REMOVE(dap, da_pdlist);
4734                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4735         }
4736         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
4737 }
4738
4739 /*
4740  * Handle the completion of a mkdir dependency.
4741  */
4742 static void
4743 handle_written_mkdir(mkdir, type)
4744         struct mkdir *mkdir;
4745         int type;
4746 {
4747         struct diradd *dap;
4748         struct pagedep *pagedep;
4749
4750         if (mkdir->md_state != type)
4751                 panic("handle_written_mkdir: bad type");
4752         dap = mkdir->md_diradd;
4753         dap->da_state &= ~type;
4754         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
4755                 dap->da_state |= DEPCOMPLETE;
4756         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4757                 if (dap->da_state & DIRCHG)
4758                         pagedep = dap->da_previous->dm_pagedep;
4759                 else
4760                         pagedep = dap->da_pagedep;
4761                 LIST_REMOVE(dap, da_pdlist);
4762                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
4763         }
4764         LIST_REMOVE(mkdir, md_mkdirs);
4765         WORKITEM_FREE(mkdir, D_MKDIR);
4766 }
4767
4768 /*
4769  * Called from within softdep_disk_write_complete above.
4770  * A write operation was just completed. Removed inodes can
4771  * now be freed and associated block pointers may be committed.
4772  * Note that this routine is always called from interrupt level
4773  * with further splbio interrupts blocked.
4774  */
4775 static int 
4776 handle_written_filepage(pagedep, bp)
4777         struct pagedep *pagedep;
4778         struct buf *bp;         /* buffer containing the written page */
4779 {
4780         struct dirrem *dirrem;
4781         struct diradd *dap, *nextdap;
4782         struct direct *ep;
4783         int i, chgs;
4784
4785         if ((pagedep->pd_state & IOSTARTED) == 0)
4786                 panic("handle_written_filepage: not started");
4787         pagedep->pd_state &= ~IOSTARTED;
4788         /*
4789          * Process any directory removals that have been committed.
4790          */
4791         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
4792                 LIST_REMOVE(dirrem, dm_next);
4793                 dirrem->dm_dirinum = pagedep->pd_ino;
4794                 add_to_worklist(&dirrem->dm_list);
4795         }
4796         /*
4797          * Free any directory additions that have been committed.
4798          * If it is a newly allocated block, we have to wait until
4799          * the on-disk directory inode claims the new block.
4800          */
4801         if ((pagedep->pd_state & NEWBLOCK) == 0)
4802                 while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
4803                         free_diradd(dap);
4804         /*
4805          * Uncommitted directory entries must be restored.
4806          */
4807         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
4808                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
4809                      dap = nextdap) {
4810                         nextdap = LIST_NEXT(dap, da_pdlist);
4811                         if (dap->da_state & ATTACHED)
4812                                 panic("handle_written_filepage: attached");
4813                         ep = (struct direct *)
4814                             ((char *)bp->b_data + dap->da_offset);
4815                         ep->d_ino = dap->da_newinum;
4816                         dap->da_state &= ~UNDONE;
4817                         dap->da_state |= ATTACHED;
4818                         chgs = 1;
4819                         /*
4820                          * If the inode referenced by the directory has
4821                          * been written out, then the dependency can be
4822                          * moved to the pending list.
4823                          */
4824                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
4825                                 LIST_REMOVE(dap, da_pdlist);
4826                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
4827                                     da_pdlist);
4828                         }
4829                 }
4830         }
4831         /*
4832          * If there were any rollbacks in the directory, then it must be
4833          * marked dirty so that its will eventually get written back in
4834          * its correct form.
4835          */
4836         if (chgs) {
4837                 if ((bp->b_flags & B_DELWRI) == 0)
4838                         stat_dir_entry++;
4839                 bdirty(bp);
4840                 return (1);
4841         }
4842         /*
4843          * If we are not waiting for a new directory block to be
4844          * claimed by its inode, then the pagedep will be freed.
4845          * Otherwise it will remain to track any new entries on
4846          * the page in case they are fsync'ed.
4847          */
4848         if ((pagedep->pd_state & NEWBLOCK) == 0) {
4849                 LIST_REMOVE(pagedep, pd_hash);
4850                 WORKITEM_FREE(pagedep, D_PAGEDEP);
4851         }
4852         return (0);
4853 }
4854
4855 /*
4856  * Writing back in-core inode structures.
4857  * 
4858  * The filesystem only accesses an inode's contents when it occupies an
4859  * "in-core" inode structure.  These "in-core" structures are separate from
4860  * the page frames used to cache inode blocks.  Only the latter are
4861  * transferred to/from the disk.  So, when the updated contents of the
4862  * "in-core" inode structure are copied to the corresponding in-memory inode
4863  * block, the dependencies are also transferred.  The following procedure is
4864  * called when copying a dirty "in-core" inode to a cached inode block.
4865  */
4866
4867 /*
4868  * Called when an inode is loaded from disk. If the effective link count
4869  * differed from the actual link count when it was last flushed, then we
4870  * need to ensure that the correct effective link count is put back.
4871  */
4872 void 
4873 softdep_load_inodeblock(ip)
4874         struct inode *ip;       /* the "in_core" copy of the inode */
4875 {
4876         struct inodedep *inodedep;
4877
4878         /*
4879          * Check for alternate nlink count.
4880          */
4881         ip->i_effnlink = ip->i_nlink;
4882         ACQUIRE_LOCK(&lk);
4883         if (inodedep_lookup(UFSTOVFS(ip->i_ump),
4884             ip->i_number, 0, &inodedep) == 0) {
4885                 FREE_LOCK(&lk);
4886                 return;
4887         }
4888         ip->i_effnlink -= inodedep->id_nlinkdelta;
4889         if (inodedep->id_state & SPACECOUNTED)
4890                 ip->i_flag |= IN_SPACECOUNTED;
4891         FREE_LOCK(&lk);
4892 }
4893
4894 /*
4895  * This routine is called just before the "in-core" inode
4896  * information is to be copied to the in-memory inode block.
4897  * Recall that an inode block contains several inodes. If
4898  * the force flag is set, then the dependencies will be
4899  * cleared so that the update can always be made. Note that
4900  * the buffer is locked when this routine is called, so we
4901  * will never be in the middle of writing the inode block 
4902  * to disk.
4903  */
4904 void 
4905 softdep_update_inodeblock(ip, bp, waitfor)
4906         struct inode *ip;       /* the "in_core" copy of the inode */
4907         struct buf *bp;         /* the buffer containing the inode block */
4908         int waitfor;            /* nonzero => update must be allowed */
4909 {
4910         struct inodedep *inodedep;
4911         struct worklist *wk;
4912         struct mount *mp;
4913         struct buf *ibp;
4914         int error;
4915
4916         /*
4917          * If the effective link count is not equal to the actual link
4918          * count, then we must track the difference in an inodedep while
4919          * the inode is (potentially) tossed out of the cache. Otherwise,
4920          * if there is no existing inodedep, then there are no dependencies
4921          * to track.
4922          */
4923         mp = UFSTOVFS(ip->i_ump);
4924         ACQUIRE_LOCK(&lk);
4925         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
4926                 FREE_LOCK(&lk);
4927                 if (ip->i_effnlink != ip->i_nlink)
4928                         panic("softdep_update_inodeblock: bad link count");
4929                 return;
4930         }
4931         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
4932                 panic("softdep_update_inodeblock: bad delta");
4933         /*
4934          * Changes have been initiated. Anything depending on these
4935          * changes cannot occur until this inode has been written.
4936          */
4937         inodedep->id_state &= ~COMPLETE;
4938         if ((inodedep->id_state & ONWORKLIST) == 0)
4939                 WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
4940         /*
4941          * Any new dependencies associated with the incore inode must 
4942          * now be moved to the list associated with the buffer holding
4943          * the in-memory copy of the inode. Once merged process any
4944          * allocdirects that are completed by the merger.
4945          */
4946         merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
4947         if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
4948                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
4949         merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
4950         if (!TAILQ_EMPTY(&inodedep->id_extupdt))
4951                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt));
4952         /*
4953          * Now that the inode has been pushed into the buffer, the
4954          * operations dependent on the inode being written to disk
4955          * can be moved to the id_bufwait so that they will be
4956          * processed when the buffer I/O completes.
4957          */
4958         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
4959                 WORKLIST_REMOVE(wk);
4960                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
4961         }
4962         /*
4963          * Newly allocated inodes cannot be written until the bitmap
4964          * that allocates them have been written (indicated by
4965          * DEPCOMPLETE being set in id_state). If we are doing a
4966          * forced sync (e.g., an fsync on a file), we force the bitmap
4967          * to be written so that the update can be done.
4968          */
4969         if (waitfor == 0) {
4970                 FREE_LOCK(&lk);
4971                 return;
4972         }
4973 retry:
4974         if ((inodedep->id_state & DEPCOMPLETE) != 0) {
4975                 FREE_LOCK(&lk);
4976                 return;
4977         }
4978         ibp = inodedep->id_buf;
4979         ibp = getdirtybuf(ibp, &lk, MNT_WAIT);
4980         if (ibp == NULL) {
4981                 /*
4982                  * If ibp came back as NULL, the dependency could have been
4983                  * freed while we slept.  Look it up again, and check to see
4984                  * that it has completed.
4985                  */
4986                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
4987                         goto retry;
4988                 FREE_LOCK(&lk);
4989                 return;
4990         }
4991         FREE_LOCK(&lk);
4992         if ((error = bwrite(ibp)) != 0)
4993                 softdep_error("softdep_update_inodeblock: bwrite", error);
4994 }
4995
4996 /*
4997  * Merge the a new inode dependency list (such as id_newinoupdt) into an
4998  * old inode dependency list (such as id_inoupdt). This routine must be
4999  * called with splbio interrupts blocked.
5000  */
5001 static void
5002 merge_inode_lists(newlisthead, oldlisthead)
5003         struct allocdirectlst *newlisthead;
5004         struct allocdirectlst *oldlisthead;
5005 {
5006         struct allocdirect *listadp, *newadp;
5007
5008         newadp = TAILQ_FIRST(newlisthead);
5009         for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
5010                 if (listadp->ad_lbn < newadp->ad_lbn) {
5011                         listadp = TAILQ_NEXT(listadp, ad_next);
5012                         continue;
5013                 }
5014                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
5015                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
5016                 if (listadp->ad_lbn == newadp->ad_lbn) {
5017                         allocdirect_merge(oldlisthead, newadp,
5018                             listadp);
5019                         listadp = newadp;
5020                 }
5021                 newadp = TAILQ_FIRST(newlisthead);
5022         }
5023         while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
5024                 TAILQ_REMOVE(newlisthead, newadp, ad_next);
5025                 TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
5026         }
5027 }
5028
5029 /*
5030  * If we are doing an fsync, then we must ensure that any directory
5031  * entries for the inode have been written after the inode gets to disk.
5032  */
5033 int
5034 softdep_fsync(vp)
5035         struct vnode *vp;       /* the "in_core" copy of the inode */
5036 {
5037         struct inodedep *inodedep;
5038         struct pagedep *pagedep;
5039         struct worklist *wk;
5040         struct diradd *dap;
5041         struct mount *mp;
5042         struct vnode *pvp;
5043         struct inode *ip;
5044         struct buf *bp;
5045         struct fs *fs;
5046         struct thread *td = curthread;
5047         int error, flushparent, pagedep_new_block;
5048         ino_t parentino;
5049         ufs_lbn_t lbn;
5050
5051         ip = VTOI(vp);
5052         fs = ip->i_fs;
5053         mp = vp->v_mount;
5054         ACQUIRE_LOCK(&lk);
5055         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
5056                 FREE_LOCK(&lk);
5057                 return (0);
5058         }
5059         if (!LIST_EMPTY(&inodedep->id_inowait) ||
5060             !LIST_EMPTY(&inodedep->id_bufwait) ||
5061             !TAILQ_EMPTY(&inodedep->id_extupdt) ||
5062             !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
5063             !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
5064             !TAILQ_EMPTY(&inodedep->id_newinoupdt))
5065                 panic("softdep_fsync: pending ops");
5066         for (error = 0, flushparent = 0; ; ) {
5067                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
5068                         break;
5069                 if (wk->wk_type != D_DIRADD)
5070                         panic("softdep_fsync: Unexpected type %s",
5071                             TYPENAME(wk->wk_type));
5072                 dap = WK_DIRADD(wk);
5073                 /*
5074                  * Flush our parent if this directory entry has a MKDIR_PARENT
5075                  * dependency or is contained in a newly allocated block.
5076                  */
5077                 if (dap->da_state & DIRCHG)
5078                         pagedep = dap->da_previous->dm_pagedep;
5079                 else
5080                         pagedep = dap->da_pagedep;
5081                 parentino = pagedep->pd_ino;
5082                 lbn = pagedep->pd_lbn;
5083                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
5084                         panic("softdep_fsync: dirty");
5085                 if ((dap->da_state & MKDIR_PARENT) ||
5086                     (pagedep->pd_state & NEWBLOCK))
5087                         flushparent = 1;
5088                 else
5089                         flushparent = 0;
5090                 /*
5091                  * If we are being fsync'ed as part of vgone'ing this vnode,
5092                  * then we will not be able to release and recover the
5093                  * vnode below, so we just have to give up on writing its
5094                  * directory entry out. It will eventually be written, just
5095                  * not now, but then the user was not asking to have it
5096                  * written, so we are not breaking any promises.
5097                  */
5098                 if (vp->v_iflag & VI_DOOMED)
5099                         break;
5100                 /*
5101                  * We prevent deadlock by always fetching inodes from the
5102                  * root, moving down the directory tree. Thus, when fetching
5103                  * our parent directory, we first try to get the lock. If
5104                  * that fails, we must unlock ourselves before requesting
5105                  * the lock on our parent. See the comment in ufs_lookup
5106                  * for details on possible races.
5107                  */
5108                 FREE_LOCK(&lk);
5109                 if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
5110                     FFSV_FORCEINSMQ)) {
5111                         VOP_UNLOCK(vp, 0, td);
5112                         error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
5113                             &pvp, FFSV_FORCEINSMQ);
5114                         vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
5115                         if (error != 0)
5116                                 return (error);
5117                 }
5118                 /*
5119                  * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
5120                  * that are contained in direct blocks will be resolved by 
5121                  * doing a ffs_update. Pagedeps contained in indirect blocks
5122                  * may require a complete sync'ing of the directory. So, we
5123                  * try the cheap and fast ffs_update first, and if that fails,
5124                  * then we do the slower ffs_syncvnode of the directory.
5125                  */
5126                 if (flushparent) {
5127                         int locked;
5128
5129                         if ((error = ffs_update(pvp, 1)) != 0) {
5130                                 vput(pvp);
5131                                 return (error);
5132                         }
5133                         ACQUIRE_LOCK(&lk);
5134                         locked = 1;
5135                         if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
5136                                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
5137                                         if (wk->wk_type != D_DIRADD)
5138                                                 panic("softdep_fsync: Unexpected type %s",
5139                                                       TYPENAME(wk->wk_type));
5140                                         dap = WK_DIRADD(wk);
5141                                         if (dap->da_state & DIRCHG)
5142                                                 pagedep = dap->da_previous->dm_pagedep;
5143                                         else
5144                                                 pagedep = dap->da_pagedep;
5145                                         pagedep_new_block = pagedep->pd_state & NEWBLOCK;
5146                                         FREE_LOCK(&lk);
5147                                         locked = 0;
5148                                         if (pagedep_new_block &&
5149                                             (error = ffs_syncvnode(pvp, MNT_WAIT))) {
5150                                                 vput(pvp);
5151                                                 return (error);
5152                                         }
5153                                 }
5154                         }
5155                         if (locked)
5156                                 FREE_LOCK(&lk);
5157                 }
5158                 /*
5159                  * Flush directory page containing the inode's name.
5160                  */
5161                 error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
5162                     &bp);
5163                 if (error == 0)
5164                         error = bwrite(bp);
5165                 else
5166                         brelse(bp);
5167                 vput(pvp);
5168                 if (error != 0)
5169                         return (error);
5170                 ACQUIRE_LOCK(&lk);
5171                 if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
5172                         break;
5173         }
5174         FREE_LOCK(&lk);
5175         return (0);
5176 }
5177
5178 /*
5179  * Flush all the dirty bitmaps associated with the block device
5180  * before flushing the rest of the dirty blocks so as to reduce
5181  * the number of dependencies that will have to be rolled back.
5182  */
5183 void
5184 softdep_fsync_mountdev(vp)
5185         struct vnode *vp;
5186 {
5187         struct buf *bp, *nbp;
5188         struct worklist *wk;
5189
5190         if (!vn_isdisk(vp, NULL))
5191                 panic("softdep_fsync_mountdev: vnode not a disk");
5192 restart:
5193         ACQUIRE_LOCK(&lk);
5194         VI_LOCK(vp);
5195         TAILQ_FOREACH_SAFE(bp, &vp->v_bufobj.bo_dirty.bv_hd, b_bobufs, nbp) {
5196                 /* 
5197                  * If it is already scheduled, skip to the next buffer.
5198                  */
5199                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
5200                         continue;
5201
5202                 if ((bp->b_flags & B_DELWRI) == 0)
5203                         panic("softdep_fsync_mountdev: not dirty");
5204                 /*
5205                  * We are only interested in bitmaps with outstanding
5206                  * dependencies.
5207                  */
5208                 if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
5209                     wk->wk_type != D_BMSAFEMAP ||
5210                     (bp->b_vflags & BV_BKGRDINPROG)) {
5211                         BUF_UNLOCK(bp);
5212                         continue;
5213                 }
5214                 VI_UNLOCK(vp);
5215                 FREE_LOCK(&lk);
5216                 bremfree(bp);
5217                 (void) bawrite(bp);
5218                 goto restart;
5219         }
5220         FREE_LOCK(&lk);
5221         drain_output(vp);
5222         VI_UNLOCK(vp);
5223 }
5224
5225 /*
5226  * This routine is called when we are trying to synchronously flush a
5227  * file. This routine must eliminate any filesystem metadata dependencies
5228  * so that the syncing routine can succeed by pushing the dirty blocks
5229  * associated with the file. If any I/O errors occur, they are returned.
5230  */
5231 int
5232 softdep_sync_metadata(struct vnode *vp)
5233 {
5234         struct pagedep *pagedep;
5235         struct allocdirect *adp;
5236         struct allocindir *aip;
5237         struct buf *bp, *nbp;
5238         struct worklist *wk;
5239         int i, error, waitfor;
5240
5241         if (!DOINGSOFTDEP(vp))
5242                 return (0);
5243         /*
5244          * Ensure that any direct block dependencies have been cleared.
5245          */
5246         ACQUIRE_LOCK(&lk);
5247         if ((error = flush_inodedep_deps(vp->v_mount, VTOI(vp)->i_number))) {
5248                 FREE_LOCK(&lk);
5249                 return (error);
5250         }
5251         FREE_LOCK(&lk);
5252         /*
5253          * For most files, the only metadata dependencies are the
5254          * cylinder group maps that allocate their inode or blocks.
5255          * The block allocation dependencies can be found by traversing
5256          * the dependency lists for any buffers that remain on their
5257          * dirty buffer list. The inode allocation dependency will
5258          * be resolved when the inode is updated with MNT_WAIT.
5259          * This work is done in two passes. The first pass grabs most
5260          * of the buffers and begins asynchronously writing them. The
5261          * only way to wait for these asynchronous writes is to sleep
5262          * on the filesystem vnode which may stay busy for a long time
5263          * if the filesystem is active. So, instead, we make a second
5264          * pass over the dependencies blocking on each write. In the
5265          * usual case we will be blocking against a write that we
5266          * initiated, so when it is done the dependency will have been
5267          * resolved. Thus the second pass is expected to end quickly.
5268          */
5269         waitfor = MNT_NOWAIT;
5270
5271 top:
5272         /*
5273          * We must wait for any I/O in progress to finish so that
5274          * all potential buffers on the dirty list will be visible.
5275          */
5276         VI_LOCK(vp);
5277         drain_output(vp);
5278         while ((bp = TAILQ_FIRST(&vp->v_bufobj.bo_dirty.bv_hd)) != NULL) {
5279                 bp = getdirtybuf(bp, VI_MTX(vp), MNT_WAIT);
5280                 if (bp)
5281                         break;
5282         }
5283         VI_UNLOCK(vp);
5284         if (bp == NULL)
5285                 return (0);
5286 loop:
5287         /* While syncing snapshots, we must allow recursive lookups */
5288         bp->b_lock.lk_flags |= LK_CANRECURSE;
5289         ACQUIRE_LOCK(&lk);
5290         /*
5291          * As we hold the buffer locked, none of its dependencies
5292          * will disappear.
5293          */
5294         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5295                 switch (wk->wk_type) {
5296
5297                 case D_ALLOCDIRECT:
5298                         adp = WK_ALLOCDIRECT(wk);
5299                         if (adp->ad_state & DEPCOMPLETE)
5300                                 continue;
5301                         nbp = adp->ad_buf;
5302                         nbp = getdirtybuf(nbp, &lk, waitfor);
5303                         if (nbp == NULL)
5304                                 continue;
5305                         FREE_LOCK(&lk);
5306                         if (waitfor == MNT_NOWAIT) {
5307                                 bawrite(nbp);
5308                         } else if ((error = bwrite(nbp)) != 0) {
5309                                 break;
5310                         }
5311                         ACQUIRE_LOCK(&lk);
5312                         continue;
5313
5314                 case D_ALLOCINDIR:
5315                         aip = WK_ALLOCINDIR(wk);
5316                         if (aip->ai_state & DEPCOMPLETE)
5317                                 continue;
5318                         nbp = aip->ai_buf;
5319                         nbp = getdirtybuf(nbp, &lk, waitfor);
5320                         if (nbp == NULL)
5321                                 continue;
5322                         FREE_LOCK(&lk);
5323                         if (waitfor == MNT_NOWAIT) {
5324                                 bawrite(nbp);
5325                         } else if ((error = bwrite(nbp)) != 0) {
5326                                 break;
5327                         }
5328                         ACQUIRE_LOCK(&lk);
5329                         continue;
5330
5331                 case D_INDIRDEP:
5332                 restart:
5333
5334                         LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
5335                                 if (aip->ai_state & DEPCOMPLETE)
5336                                         continue;
5337                                 nbp = aip->ai_buf;
5338                                 nbp = getdirtybuf(nbp, &lk, MNT_WAIT);
5339                                 if (nbp == NULL)
5340                                         goto restart;
5341                                 FREE_LOCK(&lk);
5342                                 if ((error = bwrite(nbp)) != 0) {
5343                                         goto loop_end;
5344                                 }
5345                                 ACQUIRE_LOCK(&lk);
5346                                 goto restart;
5347                         }
5348                         continue;
5349
5350                 case D_INODEDEP:
5351                         if ((error = flush_inodedep_deps(wk->wk_mp,
5352                             WK_INODEDEP(wk)->id_ino)) != 0) {
5353                                 FREE_LOCK(&lk);
5354                                 break;
5355                         }
5356                         continue;
5357
5358                 case D_PAGEDEP:
5359                         /*
5360                          * We are trying to sync a directory that may
5361                          * have dependencies on both its own metadata
5362                          * and/or dependencies on the inodes of any
5363                          * recently allocated files. We walk its diradd
5364                          * lists pushing out the associated inode.
5365                          */
5366                         pagedep = WK_PAGEDEP(wk);
5367                         for (i = 0; i < DAHASHSZ; i++) {
5368                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
5369                                         continue;
5370                                 if ((error =
5371                                     flush_pagedep_deps(vp, wk->wk_mp,
5372                                                 &pagedep->pd_diraddhd[i]))) {
5373                                         FREE_LOCK(&lk);
5374                                         goto loop_end;
5375                                 }
5376                         }
5377                         continue;
5378
5379                 case D_MKDIR:
5380                         /*
5381                          * This case should never happen if the vnode has
5382                          * been properly sync'ed. However, if this function
5383                          * is used at a place where the vnode has not yet
5384                          * been sync'ed, this dependency can show up. So,
5385                          * rather than panic, just flush it.
5386                          */
5387                         nbp = WK_MKDIR(wk)->md_buf;
5388                         nbp = getdirtybuf(nbp, &lk, waitfor);
5389                         if (nbp == NULL)
5390                                 continue;
5391                         FREE_LOCK(&lk);
5392                         if (waitfor == MNT_NOWAIT) {
5393                                 bawrite(nbp);
5394                         } else if ((error = bwrite(nbp)) != 0) {
5395                                 break;
5396                         }
5397                         ACQUIRE_LOCK(&lk);
5398                         continue;
5399
5400                 case D_BMSAFEMAP:
5401                         /*
5402                          * This case should never happen if the vnode has
5403                          * been properly sync'ed. However, if this function
5404                          * is used at a place where the vnode has not yet
5405                          * been sync'ed, this dependency can show up. So,
5406                          * rather than panic, just flush it.
5407                          */
5408                         nbp = WK_BMSAFEMAP(wk)->sm_buf;
5409                         nbp = getdirtybuf(nbp, &lk, waitfor);
5410                         if (nbp == NULL)
5411                                 continue;
5412                         FREE_LOCK(&lk);
5413                         if (waitfor == MNT_NOWAIT) {
5414                                 bawrite(nbp);
5415                         } else if ((error = bwrite(nbp)) != 0) {
5416                                 break;
5417                         }
5418                         ACQUIRE_LOCK(&lk);
5419                         continue;
5420
5421                 default:
5422                         panic("softdep_sync_metadata: Unknown type %s",
5423                             TYPENAME(wk->wk_type));
5424                         /* NOTREACHED */
5425                 }
5426         loop_end:
5427                 /* We reach here only in error and unlocked */
5428                 if (error == 0)
5429                         panic("softdep_sync_metadata: zero error");
5430                 bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5431                 bawrite(bp);
5432                 return (error);
5433         }
5434         FREE_LOCK(&lk);
5435         VI_LOCK(vp);
5436         while ((nbp = TAILQ_NEXT(bp, b_bobufs)) != NULL) {
5437                 nbp = getdirtybuf(nbp, VI_MTX(vp), MNT_WAIT);
5438                 if (nbp)
5439                         break;
5440         }
5441         VI_UNLOCK(vp);
5442         bp->b_lock.lk_flags &= ~LK_CANRECURSE;
5443         bawrite(bp);
5444         if (nbp != NULL) {
5445                 bp = nbp;
5446                 goto loop;
5447         }
5448         /*
5449          * The brief unlock is to allow any pent up dependency
5450          * processing to be done. Then proceed with the second pass.
5451          */
5452         if (waitfor == MNT_NOWAIT) {
5453                 waitfor = MNT_WAIT;
5454                 goto top;
5455         }
5456
5457         /*
5458          * If we have managed to get rid of all the dirty buffers,
5459          * then we are done. For certain directories and block
5460          * devices, we may need to do further work.
5461          *
5462          * We must wait for any I/O in progress to finish so that
5463          * all potential buffers on the dirty list will be visible.
5464          */
5465         VI_LOCK(vp);
5466         drain_output(vp);
5467         VI_UNLOCK(vp);
5468         return (0);
5469 }
5470
5471 /*
5472  * Flush the dependencies associated with an inodedep.
5473  * Called with splbio blocked.
5474  */
5475 static int
5476 flush_inodedep_deps(mp, ino)
5477         struct mount *mp;
5478         ino_t ino;
5479 {
5480         struct inodedep *inodedep;
5481         int error, waitfor;
5482
5483         /*
5484          * This work is done in two passes. The first pass grabs most
5485          * of the buffers and begins asynchronously writing them. The
5486          * only way to wait for these asynchronous writes is to sleep
5487          * on the filesystem vnode which may stay busy for a long time
5488          * if the filesystem is active. So, instead, we make a second
5489          * pass over the dependencies blocking on each write. In the
5490          * usual case we will be blocking against a write that we
5491          * initiated, so when it is done the dependency will have been
5492          * resolved. Thus the second pass is expected to end quickly.
5493          * We give a brief window at the top of the loop to allow
5494          * any pending I/O to complete.
5495          */
5496         for (error = 0, waitfor = MNT_NOWAIT; ; ) {
5497                 if (error)
5498                         return (error);
5499                 FREE_LOCK(&lk);
5500                 ACQUIRE_LOCK(&lk);
5501                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
5502                         return (0);
5503                 if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
5504                     flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
5505                     flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
5506                     flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
5507                         continue;
5508                 /*
5509                  * If pass2, we are done, otherwise do pass 2.
5510                  */
5511                 if (waitfor == MNT_WAIT)
5512                         break;
5513                 waitfor = MNT_WAIT;
5514         }
5515         /*
5516          * Try freeing inodedep in case all dependencies have been removed.
5517          */
5518         if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
5519                 (void) free_inodedep(inodedep);
5520         return (0);
5521 }
5522
5523 /*
5524  * Flush an inode dependency list.
5525  * Called with splbio blocked.
5526  */
5527 static int
5528 flush_deplist(listhead, waitfor, errorp)
5529         struct allocdirectlst *listhead;
5530         int waitfor;
5531         int *errorp;
5532 {
5533         struct allocdirect *adp;
5534         struct buf *bp;
5535
5536         mtx_assert(&lk, MA_OWNED);
5537         TAILQ_FOREACH(adp, listhead, ad_next) {
5538                 if (adp->ad_state & DEPCOMPLETE)
5539                         continue;
5540                 bp = adp->ad_buf;
5541                 bp = getdirtybuf(bp, &lk, waitfor);
5542                 if (bp == NULL) {
5543                         if (waitfor == MNT_NOWAIT)
5544                                 continue;
5545                         return (1);
5546                 }
5547                 FREE_LOCK(&lk);
5548                 if (waitfor == MNT_NOWAIT) {
5549                         bawrite(bp);
5550                 } else if ((*errorp = bwrite(bp)) != 0) {
5551                         ACQUIRE_LOCK(&lk);
5552                         return (1);
5553                 }
5554                 ACQUIRE_LOCK(&lk);
5555                 return (1);
5556         }
5557         return (0);
5558 }
5559
5560 /*
5561  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
5562  * Called with splbio blocked.
5563  */
5564 static int
5565 flush_pagedep_deps(pvp, mp, diraddhdp)
5566         struct vnode *pvp;
5567         struct mount *mp;
5568         struct diraddhd *diraddhdp;
5569 {
5570         struct inodedep *inodedep;
5571         struct ufsmount *ump;
5572         struct diradd *dap;
5573         struct vnode *vp;
5574         int error = 0;
5575         struct buf *bp;
5576         ino_t inum;
5577         struct worklist *wk;
5578
5579         ump = VFSTOUFS(mp);
5580         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
5581                 /*
5582                  * Flush ourselves if this directory entry
5583                  * has a MKDIR_PARENT dependency.
5584                  */
5585                 if (dap->da_state & MKDIR_PARENT) {
5586                         FREE_LOCK(&lk);
5587                         if ((error = ffs_update(pvp, 1)) != 0)
5588                                 break;
5589                         ACQUIRE_LOCK(&lk);
5590                         /*
5591                          * If that cleared dependencies, go on to next.
5592                          */
5593                         if (dap != LIST_FIRST(diraddhdp))
5594                                 continue;
5595                         if (dap->da_state & MKDIR_PARENT)
5596                                 panic("flush_pagedep_deps: MKDIR_PARENT");
5597                 }
5598                 /*
5599                  * A newly allocated directory must have its "." and
5600                  * ".." entries written out before its name can be
5601                  * committed in its parent. We do not want or need
5602                  * the full semantics of a synchronous ffs_syncvnode as
5603                  * that may end up here again, once for each directory
5604                  * level in the filesystem. Instead, we push the blocks
5605                  * and wait for them to clear. We have to fsync twice
5606                  * because the first call may choose to defer blocks
5607                  * that still have dependencies, but deferral will
5608                  * happen at most once.
5609                  */
5610                 inum = dap->da_newinum;
5611                 if (dap->da_state & MKDIR_BODY) {
5612                         FREE_LOCK(&lk);
5613                         if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
5614                             FFSV_FORCEINSMQ)))
5615                                 break;
5616                         if ((error=ffs_syncvnode(vp, MNT_NOWAIT)) ||
5617                             (error=ffs_syncvnode(vp, MNT_NOWAIT))) {
5618                                 vput(vp);
5619                                 break;
5620                         }
5621                         VI_LOCK(vp);
5622                         drain_output(vp);
5623                         /*
5624                          * If first block is still dirty with a D_MKDIR
5625                          * dependency then it needs to be written now.
5626                          */
5627                         for (;;) {
5628                                 error = 0;
5629                                 bp = gbincore(&vp->v_bufobj, 0);
5630                                 if (bp == NULL)
5631                                         break;  /* First block not present */
5632                                 error = BUF_LOCK(bp,
5633                                                  LK_EXCLUSIVE |
5634                                                  LK_SLEEPFAIL |
5635                                                  LK_INTERLOCK,
5636                                                  VI_MTX(vp));
5637                                 VI_LOCK(vp);
5638                                 if (error == ENOLCK)
5639                                         continue;       /* Slept, retry */
5640                                 if (error != 0)
5641                                         break;          /* Failed */
5642                                 if ((bp->b_flags & B_DELWRI) == 0) {
5643                                         BUF_UNLOCK(bp);
5644                                         break;  /* Buffer not dirty */
5645                                 }
5646                                 for (wk = LIST_FIRST(&bp->b_dep);
5647                                      wk != NULL;
5648                                      wk = LIST_NEXT(wk, wk_list))
5649                                         if (wk->wk_type == D_MKDIR)
5650                                                 break;
5651                                 if (wk == NULL)
5652                                         BUF_UNLOCK(bp); /* Dependency gone */
5653                                 else {
5654                                         /*
5655                                          * D_MKDIR dependency remains,
5656                                          * must write buffer to stable
5657                                          * storage.
5658                                          */
5659                                         VI_UNLOCK(vp);
5660                                         bremfree(bp);
5661                                         error = bwrite(bp);
5662                                         VI_LOCK(vp);
5663                                 }
5664                                 break;
5665                         }
5666                         VI_UNLOCK(vp);
5667                         vput(vp);
5668                         if (error != 0)
5669                                 break;  /* Flushing of first block failed */
5670                         ACQUIRE_LOCK(&lk);
5671                         /*
5672                          * If that cleared dependencies, go on to next.
5673                          */
5674                         if (dap != LIST_FIRST(diraddhdp))
5675                                 continue;
5676                         if (dap->da_state & MKDIR_BODY)
5677                                 panic("flush_pagedep_deps: MKDIR_BODY");
5678                 }
5679                 /*
5680                  * Flush the inode on which the directory entry depends.
5681                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
5682                  * the only remaining dependency is that the updated inode
5683                  * count must get pushed to disk. The inode has already
5684                  * been pushed into its inode buffer (via VOP_UPDATE) at
5685                  * the time of the reference count change. So we need only
5686                  * locate that buffer, ensure that there will be no rollback
5687                  * caused by a bitmap dependency, then write the inode buffer.
5688                  */
5689 retry:
5690                 if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
5691                         panic("flush_pagedep_deps: lost inode");
5692                 /*
5693                  * If the inode still has bitmap dependencies,
5694                  * push them to disk.
5695                  */
5696                 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
5697                         bp = inodedep->id_buf;
5698                         bp = getdirtybuf(bp, &lk, MNT_WAIT);
5699                         if (bp == NULL)
5700                                 goto retry;
5701                         FREE_LOCK(&lk);
5702                         if ((error = bwrite(bp)) != 0)
5703                                 break;
5704                         ACQUIRE_LOCK(&lk);
5705                         if (dap != LIST_FIRST(diraddhdp))
5706                                 continue;
5707                 }
5708                 /*
5709                  * If the inode is still sitting in a buffer waiting
5710                  * to be written, push it to disk.
5711                  */
5712                 FREE_LOCK(&lk);
5713                 if ((error = bread(ump->um_devvp,
5714                     fsbtodb(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
5715                     (int)ump->um_fs->fs_bsize, NOCRED, &bp)) != 0) {
5716                         brelse(bp);
5717                         break;
5718                 }
5719                 if ((error = bwrite(bp)) != 0)
5720                         break;
5721                 ACQUIRE_LOCK(&lk);
5722                 /*
5723                  * If we have failed to get rid of all the dependencies
5724                  * then something is seriously wrong.
5725                  */
5726                 if (dap == LIST_FIRST(diraddhdp))
5727                         panic("flush_pagedep_deps: flush failed");
5728         }
5729         if (error)
5730                 ACQUIRE_LOCK(&lk);
5731         return (error);
5732 }
5733
5734 /*
5735  * A large burst of file addition or deletion activity can drive the
5736  * memory load excessively high. First attempt to slow things down
5737  * using the techniques below. If that fails, this routine requests
5738  * the offending operations to fall back to running synchronously
5739  * until the memory load returns to a reasonable level.
5740  */
5741 int
5742 softdep_slowdown(vp)
5743         struct vnode *vp;
5744 {
5745         int max_softdeps_hard;
5746
5747         ACQUIRE_LOCK(&lk);
5748         max_softdeps_hard = max_softdeps * 11 / 10;
5749         if (num_dirrem < max_softdeps_hard / 2 &&
5750             num_inodedep < max_softdeps_hard &&
5751             VFSTOUFS(vp->v_mount)->um_numindirdeps < maxindirdeps) {
5752                 FREE_LOCK(&lk);
5753                 return (0);
5754         }
5755         if (VFSTOUFS(vp->v_mount)->um_numindirdeps >= maxindirdeps)
5756                 softdep_speedup();
5757         stat_sync_limit_hit += 1;
5758         FREE_LOCK(&lk);
5759         return (1);
5760 }
5761
5762 /*
5763  * Called by the allocation routines when they are about to fail
5764  * in the hope that we can free up some disk space.
5765  * 
5766  * First check to see if the work list has anything on it. If it has,
5767  * clean up entries until we successfully free some space. Because this
5768  * process holds inodes locked, we cannot handle any remove requests
5769  * that might block on a locked inode as that could lead to deadlock.
5770  * If the worklist yields no free space, encourage the syncer daemon
5771  * to help us. In no event will we try for longer than tickdelay seconds.
5772  */
5773 int
5774 softdep_request_cleanup(fs, vp)
5775         struct fs *fs;
5776         struct vnode *vp;
5777 {
5778         struct ufsmount *ump;
5779         long starttime;
5780         ufs2_daddr_t needed;
5781         int error;
5782
5783         ump = VTOI(vp)->i_ump;
5784         mtx_assert(UFS_MTX(ump), MA_OWNED);
5785         needed = fs->fs_cstotal.cs_nbfree + fs->fs_contigsumsize;
5786         starttime = time_second + tickdelay;
5787         /*
5788          * If we are being called because of a process doing a
5789          * copy-on-write, then it is not safe to update the vnode
5790          * as we may recurse into the copy-on-write routine.
5791          */
5792         if (!(curthread->td_pflags & TDP_COWINPROGRESS)) {
5793                 UFS_UNLOCK(ump);
5794                 error = ffs_update(vp, 1);
5795                 UFS_LOCK(ump);
5796                 if (error != 0)
5797                         return (0);
5798         }
5799         while (fs->fs_pendingblocks > 0 && fs->fs_cstotal.cs_nbfree <= needed) {
5800                 if (time_second > starttime)
5801                         return (0);
5802                 UFS_UNLOCK(ump);
5803                 ACQUIRE_LOCK(&lk);
5804                 if (ump->softdep_on_worklist > 0 &&
5805                     process_worklist_item(UFSTOVFS(ump), LK_NOWAIT) != -1) {
5806                         stat_worklist_push += 1;
5807                         FREE_LOCK(&lk);
5808                         UFS_LOCK(ump);
5809                         continue;
5810                 }
5811                 request_cleanup(UFSTOVFS(ump), FLUSH_REMOVE_WAIT);
5812                 FREE_LOCK(&lk);
5813                 UFS_LOCK(ump);
5814         }
5815         return (1);
5816 }
5817
5818 /*
5819  * If memory utilization has gotten too high, deliberately slow things
5820  * down and speed up the I/O processing.
5821  */
5822 extern struct thread *syncertd;
5823 static int
5824 request_cleanup(mp, resource)
5825         struct mount *mp;
5826         int resource;
5827 {
5828         struct thread *td = curthread;
5829         struct ufsmount *ump;
5830
5831         mtx_assert(&lk, MA_OWNED);
5832         /*
5833          * We never hold up the filesystem syncer or buf daemon.
5834          */
5835         if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
5836                 return (0);
5837         ump = VFSTOUFS(mp);
5838         /*
5839          * First check to see if the work list has gotten backlogged.
5840          * If it has, co-opt this process to help clean up two entries.
5841          * Because this process may hold inodes locked, we cannot
5842          * handle any remove requests that might block on a locked
5843          * inode as that could lead to deadlock.  We set TDP_SOFTDEP
5844          * to avoid recursively processing the worklist.
5845          */
5846         if (ump->softdep_on_worklist > max_softdeps / 10) {
5847                 td->td_pflags |= TDP_SOFTDEP;
5848                 process_worklist_item(mp, LK_NOWAIT);
5849                 process_worklist_item(mp, LK_NOWAIT);
5850                 td->td_pflags &= ~TDP_SOFTDEP;
5851                 stat_worklist_push += 2;
5852                 return(1);
5853         }
5854         /*
5855          * Next, we attempt to speed up the syncer process. If that
5856          * is successful, then we allow the process to continue.
5857          */
5858         if (softdep_speedup() && resource != FLUSH_REMOVE_WAIT)
5859                 return(0);
5860         /*
5861          * If we are resource constrained on inode dependencies, try
5862          * flushing some dirty inodes. Otherwise, we are constrained
5863          * by file deletions, so try accelerating flushes of directories
5864          * with removal dependencies. We would like to do the cleanup
5865          * here, but we probably hold an inode locked at this point and 
5866          * that might deadlock against one that we try to clean. So,
5867          * the best that we can do is request the syncer daemon to do
5868          * the cleanup for us.
5869          */
5870         switch (resource) {
5871
5872         case FLUSH_INODES:
5873                 stat_ino_limit_push += 1;
5874                 req_clear_inodedeps += 1;
5875                 stat_countp = &stat_ino_limit_hit;
5876                 break;
5877
5878         case FLUSH_REMOVE:
5879         case FLUSH_REMOVE_WAIT:
5880                 stat_blk_limit_push += 1;
5881                 req_clear_remove += 1;
5882                 stat_countp = &stat_blk_limit_hit;
5883                 break;
5884
5885         default:
5886                 panic("request_cleanup: unknown type");
5887         }
5888         /*
5889          * Hopefully the syncer daemon will catch up and awaken us.
5890          * We wait at most tickdelay before proceeding in any case.
5891          */
5892         proc_waiting += 1;
5893         if (callout_pending(&softdep_callout) == FALSE)
5894                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
5895                     pause_timer, 0);
5896
5897         msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
5898         proc_waiting -= 1;
5899         return (1);
5900 }
5901
5902 /*
5903  * Awaken processes pausing in request_cleanup and clear proc_waiting
5904  * to indicate that there is no longer a timer running.
5905  */
5906 static void
5907 pause_timer(arg)
5908         void *arg;
5909 {
5910
5911         /*
5912          * The callout_ API has acquired mtx and will hold it around this
5913          * function call.
5914          */
5915         *stat_countp += 1;
5916         wakeup_one(&proc_waiting);
5917         if (proc_waiting > 0)
5918                 callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
5919                     pause_timer, 0);
5920 }
5921
5922 /*
5923  * Flush out a directory with at least one removal dependency in an effort to
5924  * reduce the number of dirrem, freefile, and freeblks dependency structures.
5925  */
5926 static void
5927 clear_remove(td)
5928         struct thread *td;
5929 {
5930         struct pagedep_hashhead *pagedephd;
5931         struct pagedep *pagedep;
5932         static int next = 0;
5933         struct mount *mp;
5934         struct vnode *vp;
5935         int error, cnt;
5936         ino_t ino;
5937
5938         mtx_assert(&lk, MA_OWNED);
5939
5940         for (cnt = 0; cnt < pagedep_hash; cnt++) {
5941                 pagedephd = &pagedep_hashtbl[next++];
5942                 if (next >= pagedep_hash)
5943                         next = 0;
5944                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
5945                         if (LIST_EMPTY(&pagedep->pd_dirremhd))
5946                                 continue;
5947                         mp = pagedep->pd_list.wk_mp;
5948                         ino = pagedep->pd_ino;
5949                         if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
5950                                 continue;
5951                         FREE_LOCK(&lk);
5952                         if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
5953                              FFSV_FORCEINSMQ))) {
5954                                 softdep_error("clear_remove: vget", error);
5955                                 vn_finished_write(mp);
5956                                 ACQUIRE_LOCK(&lk);
5957                                 return;
5958                         }
5959                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
5960                                 softdep_error("clear_remove: fsync", error);
5961                         VI_LOCK(vp);
5962                         drain_output(vp);
5963                         VI_UNLOCK(vp);
5964                         vput(vp);
5965                         vn_finished_write(mp);
5966                         ACQUIRE_LOCK(&lk);
5967                         return;
5968                 }
5969         }
5970 }
5971
5972 /*
5973  * Clear out a block of dirty inodes in an effort to reduce
5974  * the number of inodedep dependency structures.
5975  */
5976 static void
5977 clear_inodedeps(td)
5978         struct thread *td;
5979 {
5980         struct inodedep_hashhead *inodedephd;
5981         struct inodedep *inodedep;
5982         static int next = 0;
5983         struct mount *mp;
5984         struct vnode *vp;
5985         struct fs *fs;
5986         int error, cnt;
5987         ino_t firstino, lastino, ino;
5988
5989         mtx_assert(&lk, MA_OWNED);
5990         /*
5991          * Pick a random inode dependency to be cleared.
5992          * We will then gather up all the inodes in its block 
5993          * that have dependencies and flush them out.
5994          */
5995         for (cnt = 0; cnt < inodedep_hash; cnt++) {
5996                 inodedephd = &inodedep_hashtbl[next++];
5997                 if (next >= inodedep_hash)
5998                         next = 0;
5999                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
6000                         break;
6001         }
6002         if (inodedep == NULL)
6003                 return;
6004         fs = inodedep->id_fs;
6005         mp = inodedep->id_list.wk_mp;
6006         /*
6007          * Find the last inode in the block with dependencies.
6008          */
6009         firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
6010         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
6011                 if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
6012                         break;
6013         /*
6014          * Asynchronously push all but the last inode with dependencies.
6015          * Synchronously push the last inode with dependencies to ensure
6016          * that the inode block gets written to free up the inodedeps.
6017          */
6018         for (ino = firstino; ino <= lastino; ino++) {
6019                 if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
6020                         continue;
6021                 if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
6022                         continue;
6023                 FREE_LOCK(&lk);
6024                 if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
6025                     FFSV_FORCEINSMQ)) != 0) {
6026                         softdep_error("clear_inodedeps: vget", error);
6027                         vn_finished_write(mp);
6028                         ACQUIRE_LOCK(&lk);
6029                         return;
6030                 }
6031                 if (ino == lastino) {
6032                         if ((error = ffs_syncvnode(vp, MNT_WAIT)))
6033                                 softdep_error("clear_inodedeps: fsync1", error);
6034                 } else {
6035                         if ((error = ffs_syncvnode(vp, MNT_NOWAIT)))
6036                                 softdep_error("clear_inodedeps: fsync2", error);
6037                         VI_LOCK(vp);
6038                         drain_output(vp);
6039                         VI_UNLOCK(vp);
6040                 }
6041                 vput(vp);
6042                 vn_finished_write(mp);
6043                 ACQUIRE_LOCK(&lk);
6044         }
6045 }
6046
6047 /*
6048  * Function to determine if the buffer has outstanding dependencies
6049  * that will cause a roll-back if the buffer is written. If wantcount
6050  * is set, return number of dependencies, otherwise just yes or no.
6051  */
6052 static int
6053 softdep_count_dependencies(bp, wantcount)
6054         struct buf *bp;
6055         int wantcount;
6056 {
6057         struct worklist *wk;
6058         struct inodedep *inodedep;
6059         struct indirdep *indirdep;
6060         struct allocindir *aip;
6061         struct pagedep *pagedep;
6062         struct diradd *dap;
6063         int i, retval;
6064
6065         retval = 0;
6066         ACQUIRE_LOCK(&lk);
6067         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6068                 switch (wk->wk_type) {
6069
6070                 case D_INODEDEP:
6071                         inodedep = WK_INODEDEP(wk);
6072                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
6073                                 /* bitmap allocation dependency */
6074                                 retval += 1;
6075                                 if (!wantcount)
6076                                         goto out;
6077                         }
6078                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
6079                                 /* direct block pointer dependency */
6080                                 retval += 1;
6081                                 if (!wantcount)
6082                                         goto out;
6083                         }
6084                         if (TAILQ_FIRST(&inodedep->id_extupdt)) {
6085                                 /* direct block pointer dependency */
6086                                 retval += 1;
6087                                 if (!wantcount)
6088                                         goto out;
6089                         }
6090                         continue;
6091
6092                 case D_INDIRDEP:
6093                         indirdep = WK_INDIRDEP(wk);
6094
6095                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
6096                                 /* indirect block pointer dependency */
6097                                 retval += 1;
6098                                 if (!wantcount)
6099                                         goto out;
6100                         }
6101                         continue;
6102
6103                 case D_PAGEDEP:
6104                         pagedep = WK_PAGEDEP(wk);
6105                         for (i = 0; i < DAHASHSZ; i++) {
6106
6107                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
6108                                         /* directory entry dependency */
6109                                         retval += 1;
6110                                         if (!wantcount)
6111                                                 goto out;
6112                                 }
6113                         }
6114                         continue;
6115
6116                 case D_BMSAFEMAP:
6117                 case D_ALLOCDIRECT:
6118                 case D_ALLOCINDIR:
6119                 case D_MKDIR:
6120                         /* never a dependency on these blocks */
6121                         continue;
6122
6123                 default:
6124                         panic("softdep_check_for_rollback: Unexpected type %s",
6125                             TYPENAME(wk->wk_type));
6126                         /* NOTREACHED */
6127                 }
6128         }
6129 out:
6130         FREE_LOCK(&lk);
6131         return retval;
6132 }
6133
6134 /*
6135  * Acquire exclusive access to a buffer.
6136  * Must be called with a locked mtx parameter.
6137  * Return acquired buffer or NULL on failure.
6138  */
6139 static struct buf *
6140 getdirtybuf(bp, mtx, waitfor)
6141         struct buf *bp;
6142         struct mtx *mtx;
6143         int waitfor;
6144 {
6145         int error;
6146
6147         mtx_assert(mtx, MA_OWNED);
6148         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
6149                 if (waitfor != MNT_WAIT)
6150                         return (NULL);
6151                 error = BUF_LOCK(bp,
6152                     LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, mtx);
6153                 /*
6154                  * Even if we sucessfully acquire bp here, we have dropped
6155                  * mtx, which may violates our guarantee.
6156                  */
6157                 if (error == 0)
6158                         BUF_UNLOCK(bp);
6159                 else if (error != ENOLCK)
6160                         panic("getdirtybuf: inconsistent lock: %d", error);
6161                 mtx_lock(mtx);
6162                 return (NULL);
6163         }
6164         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
6165                 if (mtx == &lk && waitfor == MNT_WAIT) {
6166                         mtx_unlock(mtx);
6167                         BO_LOCK(bp->b_bufobj);
6168                         BUF_UNLOCK(bp);
6169                         if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
6170                                 bp->b_vflags |= BV_BKGRDWAIT;
6171                                 msleep(&bp->b_xflags, BO_MTX(bp->b_bufobj),
6172                                        PRIBIO | PDROP, "getbuf", 0);
6173                         } else
6174                                 BO_UNLOCK(bp->b_bufobj);
6175                         mtx_lock(mtx);
6176                         return (NULL);
6177                 }
6178                 BUF_UNLOCK(bp);
6179                 if (waitfor != MNT_WAIT)
6180                         return (NULL);
6181                 /*
6182                  * The mtx argument must be bp->b_vp's mutex in
6183                  * this case.
6184                  */
6185 #ifdef  DEBUG_VFS_LOCKS
6186                 if (bp->b_vp->v_type != VCHR)
6187                         ASSERT_VI_LOCKED(bp->b_vp, "getdirtybuf");
6188 #endif
6189                 bp->b_vflags |= BV_BKGRDWAIT;
6190                 msleep(&bp->b_xflags, mtx, PRIBIO, "getbuf", 0);
6191                 return (NULL);
6192         }
6193         if ((bp->b_flags & B_DELWRI) == 0) {
6194                 BUF_UNLOCK(bp);
6195                 return (NULL);
6196         }
6197         bremfree(bp);
6198         return (bp);
6199 }
6200
6201
6202 /*
6203  * Check if it is safe to suspend the file system now.  On entry,
6204  * the vnode interlock for devvp should be held.  Return 0 with
6205  * the mount interlock held if the file system can be suspended now,
6206  * otherwise return EAGAIN with the mount interlock held.
6207  */
6208 int
6209 softdep_check_suspend(struct mount *mp,
6210                       struct vnode *devvp,
6211                       int softdep_deps,
6212                       int softdep_accdeps,
6213                       int secondary_writes,
6214                       int secondary_accwrites)
6215 {
6216         struct bufobj *bo;
6217         struct ufsmount *ump;
6218         int error;
6219
6220         ASSERT_VI_LOCKED(devvp, "softdep_check_suspend");
6221         ump = VFSTOUFS(mp);
6222         bo = &devvp->v_bufobj;
6223
6224         for (;;) {
6225                 if (!TRY_ACQUIRE_LOCK(&lk)) {
6226                         VI_UNLOCK(devvp);
6227                         ACQUIRE_LOCK(&lk);
6228                         FREE_LOCK(&lk);
6229                         VI_LOCK(devvp);
6230                         continue;
6231                 }
6232                 if (!MNT_ITRYLOCK(mp)) {
6233                         FREE_LOCK(&lk);
6234                         VI_UNLOCK(devvp);
6235                         MNT_ILOCK(mp);
6236                         MNT_IUNLOCK(mp);
6237                         VI_LOCK(devvp);
6238                         continue;
6239                 }
6240                 if (mp->mnt_secondary_writes != 0) {
6241                         FREE_LOCK(&lk);
6242                         VI_UNLOCK(devvp);
6243                         msleep(&mp->mnt_secondary_writes,
6244                                MNT_MTX(mp),
6245                                (PUSER - 1) | PDROP, "secwr", 0);
6246                         VI_LOCK(devvp);
6247                         continue;
6248                 }
6249                 break;
6250         }
6251
6252         /*
6253          * Reasons for needing more work before suspend:
6254          * - Dirty buffers on devvp.
6255          * - Softdep activity occurred after start of vnode sync loop
6256          * - Secondary writes occurred after start of vnode sync loop
6257          */
6258         error = 0;
6259         if (bo->bo_numoutput > 0 ||
6260             bo->bo_dirty.bv_cnt > 0 ||
6261             softdep_deps != 0 ||
6262             ump->softdep_deps != 0 ||
6263             softdep_accdeps != ump->softdep_accdeps ||
6264             secondary_writes != 0 ||
6265             mp->mnt_secondary_writes != 0 ||
6266             secondary_accwrites != mp->mnt_secondary_accwrites)
6267                 error = EAGAIN;
6268         FREE_LOCK(&lk);
6269         VI_UNLOCK(devvp);
6270         return (error);
6271 }
6272
6273
6274 /*
6275  * Get the number of dependency structures for the file system, both
6276  * the current number and the total number allocated.  These will
6277  * later be used to detect that softdep processing has occurred.
6278  */
6279 void
6280 softdep_get_depcounts(struct mount *mp,
6281                       int *softdep_depsp,
6282                       int *softdep_accdepsp)
6283 {
6284         struct ufsmount *ump;
6285
6286         ump = VFSTOUFS(mp);
6287         ACQUIRE_LOCK(&lk);
6288         *softdep_depsp = ump->softdep_deps;
6289         *softdep_accdepsp = ump->softdep_accdeps;
6290         FREE_LOCK(&lk);
6291 }
6292
6293 /*
6294  * Wait for pending output on a vnode to complete.
6295  * Must be called with vnode lock and interlock locked.
6296  *
6297  * XXX: Should just be a call to bufobj_wwait().
6298  */
6299 static void
6300 drain_output(vp)
6301         struct vnode *vp;
6302 {
6303         ASSERT_VOP_LOCKED(vp, "drain_output");
6304         ASSERT_VI_LOCKED(vp, "drain_output");
6305
6306         while (vp->v_bufobj.bo_numoutput) {
6307                 vp->v_bufobj.bo_flag |= BO_WWAIT;
6308                 msleep((caddr_t)&vp->v_bufobj.bo_numoutput,
6309                     VI_MTX(vp), PRIBIO + 1, "drainvp", 0);
6310         }
6311 }
6312
6313 /*
6314  * Called whenever a buffer that is being invalidated or reallocated
6315  * contains dependencies. This should only happen if an I/O error has
6316  * occurred. The routine is called with the buffer locked.
6317  */ 
6318 static void
6319 softdep_deallocate_dependencies(bp)
6320         struct buf *bp;
6321 {
6322
6323         if ((bp->b_ioflags & BIO_ERROR) == 0)
6324                 panic("softdep_deallocate_dependencies: dangling deps");
6325         softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
6326         panic("softdep_deallocate_dependencies: unrecovered I/O error");
6327 }
6328
6329 /*
6330  * Function to handle asynchronous write errors in the filesystem.
6331  */
6332 static void
6333 softdep_error(func, error)
6334         char *func;
6335         int error;
6336 {
6337
6338         /* XXX should do something better! */
6339         printf("%s: got error %d while accessing filesystem\n", func, error);
6340 }
6341
6342 #ifdef DDB
6343
6344 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
6345 {
6346         struct inodedep_hashhead *inodedephd;
6347         struct inodedep *inodedep;
6348         struct fs *fs;
6349         int cnt;
6350
6351         fs = have_addr ? (struct fs *)addr : NULL;
6352         for (cnt = 0; cnt < inodedep_hash; cnt++) {
6353                 inodedephd = &inodedep_hashtbl[cnt];
6354                 LIST_FOREACH(inodedep, inodedephd, id_hash) {
6355                         if (fs != NULL && fs != inodedep->id_fs)
6356                                 continue;
6357                         db_printf("%p fs %p st %x ino %jd inoblk %jd\n",
6358                             inodedep, inodedep->id_fs, inodedep->id_state,
6359                             (intmax_t)inodedep->id_ino,
6360                             (intmax_t)fsbtodb(inodedep->id_fs,
6361                             ino_to_fsba(inodedep->id_fs, inodedep->id_ino)));
6362                 }
6363         }
6364 }
6365
6366 #endif /* DDB */
6367
6368 #endif /* SOFTUPDATES */