Convert the global 'bioops' into per-mount bio_ops. For now we also have
[dragonfly.git] / sys / vfs / ufs / 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  * $FreeBSD: src/sys/ufs/ffs/ffs_softdep.c,v 1.57.2.11 2002/02/05 18:46:53 dillon Exp $
40  * $DragonFly: src/sys/vfs/ufs/ffs_softdep.c,v 1.53 2007/11/06 03:50:02 dillon Exp $
41  */
42
43 /*
44  * For now we want the safety net that the DIAGNOSTIC and DEBUG flags provide.
45  */
46 #ifndef DIAGNOSTIC
47 #define DIAGNOSTIC
48 #endif
49 #ifndef DEBUG
50 #define DEBUG
51 #endif
52
53 #include <sys/param.h>
54 #include <sys/kernel.h>
55 #include <sys/systm.h>
56 #include <sys/buf.h>
57 #include <sys/malloc.h>
58 #include <sys/mount.h>
59 #include <sys/proc.h>
60 #include <sys/syslog.h>
61 #include <sys/vnode.h>
62 #include <sys/conf.h>
63 #include <sys/buf2.h>
64 #include <machine/inttypes.h>
65 #include "dir.h"
66 #include "quota.h"
67 #include "inode.h"
68 #include "ufsmount.h"
69 #include "fs.h"
70 #include "softdep.h"
71 #include "ffs_extern.h"
72 #include "ufs_extern.h"
73
74 #include <sys/thread2.h>
75
76 /*
77  * These definitions need to be adapted to the system to which
78  * this file is being ported.
79  */
80 /*
81  * malloc types defined for the softdep system.
82  */
83 MALLOC_DEFINE(M_PAGEDEP, "pagedep","File page dependencies");
84 MALLOC_DEFINE(M_INODEDEP, "inodedep","Inode dependencies");
85 MALLOC_DEFINE(M_NEWBLK, "newblk","New block allocation");
86 MALLOC_DEFINE(M_BMSAFEMAP, "bmsafemap","Block or frag allocated from cyl group map");
87 MALLOC_DEFINE(M_ALLOCDIRECT, "allocdirect","Block or frag dependency for an inode");
88 MALLOC_DEFINE(M_INDIRDEP, "indirdep","Indirect block dependencies");
89 MALLOC_DEFINE(M_ALLOCINDIR, "allocindir","Block dependency for an indirect block");
90 MALLOC_DEFINE(M_FREEFRAG, "freefrag","Previously used frag for an inode");
91 MALLOC_DEFINE(M_FREEBLKS, "freeblks","Blocks freed from an inode");
92 MALLOC_DEFINE(M_FREEFILE, "freefile","Inode deallocated");
93 MALLOC_DEFINE(M_DIRADD, "diradd","New directory entry");
94 MALLOC_DEFINE(M_MKDIR, "mkdir","New directory");
95 MALLOC_DEFINE(M_DIRREM, "dirrem","Directory entry deleted");
96
97 #define M_SOFTDEP_FLAGS         (M_WAITOK | M_USE_RESERVE)
98
99 #define D_PAGEDEP       0
100 #define D_INODEDEP      1
101 #define D_NEWBLK        2
102 #define D_BMSAFEMAP     3
103 #define D_ALLOCDIRECT   4
104 #define D_INDIRDEP      5
105 #define D_ALLOCINDIR    6
106 #define D_FREEFRAG      7
107 #define D_FREEBLKS      8
108 #define D_FREEFILE      9
109 #define D_DIRADD        10
110 #define D_MKDIR         11
111 #define D_DIRREM        12
112 #define D_LAST          D_DIRREM
113
114 /* 
115  * translate from workitem type to memory type
116  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
117  */
118 static struct malloc_type *memtype[] = {
119         M_PAGEDEP,
120         M_INODEDEP,
121         M_NEWBLK,
122         M_BMSAFEMAP,
123         M_ALLOCDIRECT,
124         M_INDIRDEP,
125         M_ALLOCINDIR,
126         M_FREEFRAG,
127         M_FREEBLKS,
128         M_FREEFILE,
129         M_DIRADD,
130         M_MKDIR,
131         M_DIRREM
132 };
133
134 #define DtoM(type) (memtype[type])
135
136 /*
137  * Names of malloc types.
138  */
139 #define TYPENAME(type)  \
140         ((unsigned)(type) < D_LAST ? memtype[type]->ks_shortdesc : "???")
141 /*
142  * End system adaptaion definitions.
143  */
144
145 /*
146  * Internal function prototypes.
147  */
148 static  void softdep_error(char *, int);
149 static  void drain_output(struct vnode *, int);
150 static  int getdirtybuf(struct buf **, int);
151 static  void clear_remove(struct thread *);
152 static  void clear_inodedeps(struct thread *);
153 static  int flush_pagedep_deps(struct vnode *, struct mount *,
154             struct diraddhd *);
155 static  int flush_inodedep_deps(struct fs *, ino_t);
156 static  int handle_written_filepage(struct pagedep *, struct buf *);
157 static  void diradd_inode_written(struct diradd *, struct inodedep *);
158 static  int handle_written_inodeblock(struct inodedep *, struct buf *);
159 static  void handle_allocdirect_partdone(struct allocdirect *);
160 static  void handle_allocindir_partdone(struct allocindir *);
161 static  void initiate_write_filepage(struct pagedep *, struct buf *);
162 static  void handle_written_mkdir(struct mkdir *, int);
163 static  void initiate_write_inodeblock(struct inodedep *, struct buf *);
164 static  void handle_workitem_freefile(struct freefile *);
165 static  void handle_workitem_remove(struct dirrem *);
166 static  struct dirrem *newdirrem(struct buf *, struct inode *,
167             struct inode *, int, struct dirrem **);
168 static  void free_diradd(struct diradd *);
169 static  void free_allocindir(struct allocindir *, struct inodedep *);
170 static  int indir_trunc (struct inode *, off_t, int, ufs_lbn_t, long *);
171 static  void deallocate_dependencies(struct buf *, struct inodedep *);
172 static  void free_allocdirect(struct allocdirectlst *,
173             struct allocdirect *, int);
174 static  int check_inode_unwritten(struct inodedep *);
175 static  int free_inodedep(struct inodedep *);
176 static  void handle_workitem_freeblocks(struct freeblks *);
177 static  void merge_inode_lists(struct inodedep *);
178 static  void setup_allocindir_phase2(struct buf *, struct inode *,
179             struct allocindir *);
180 static  struct allocindir *newallocindir(struct inode *, int, ufs_daddr_t,
181             ufs_daddr_t);
182 static  void handle_workitem_freefrag(struct freefrag *);
183 static  struct freefrag *newfreefrag(struct inode *, ufs_daddr_t, long);
184 static  void allocdirect_merge(struct allocdirectlst *,
185             struct allocdirect *, struct allocdirect *);
186 static  struct bmsafemap *bmsafemap_lookup(struct buf *);
187 static  int newblk_lookup(struct fs *, ufs_daddr_t, int,
188             struct newblk **);
189 static  int inodedep_lookup(struct fs *, ino_t, int, struct inodedep **);
190 static  int pagedep_lookup(struct inode *, ufs_lbn_t, int,
191             struct pagedep **);
192 static  void pause_timer(void *);
193 static  int request_cleanup(int, int);
194 static  int process_worklist_item(struct mount *, int);
195 static  void add_to_worklist(struct worklist *);
196
197 /*
198  * Exported softdep operations.
199  */
200 static  void softdep_disk_io_initiation(struct buf *);
201 static  void softdep_disk_write_complete(struct buf *);
202 static  void softdep_deallocate_dependencies(struct buf *);
203 static  int softdep_fsync(struct vnode *);
204 static  int softdep_process_worklist(struct mount *);
205 static  void softdep_move_dependencies(struct buf *, struct buf *);
206 static  int softdep_count_dependencies(struct buf *bp, int);
207
208 static struct bio_ops softdep_bioops = {
209         .io_start = softdep_disk_io_initiation,
210         .io_complete = softdep_disk_write_complete,
211         .io_deallocate = softdep_deallocate_dependencies,
212         .io_fsync = softdep_fsync,
213         .io_sync = softdep_process_worklist,
214         .io_movedeps = softdep_move_dependencies,
215         .io_countdeps = softdep_count_dependencies,
216 };
217
218 /*
219  * Locking primitives.
220  *
221  * For a uniprocessor, all we need to do is protect against disk
222  * interrupts. For a multiprocessor, this lock would have to be
223  * a mutex. A single mutex is used throughout this file, though
224  * finer grain locking could be used if contention warranted it.
225  *
226  * For a multiprocessor, the sleep call would accept a lock and
227  * release it after the sleep processing was complete. In a uniprocessor
228  * implementation there is no such interlock, so we simple mark
229  * the places where it needs to be done with the `interlocked' form
230  * of the lock calls. Since the uniprocessor sleep already interlocks
231  * the spl, there is nothing that really needs to be done.
232  */
233 #ifndef /* NOT */ DEBUG
234 static struct lockit {
235 } lk = { 0 };
236 #define ACQUIRE_LOCK(lk)                crit_enter_id("softupdates");
237 #define FREE_LOCK(lk)                   crit_exit_id("softupdates");
238
239 #else /* DEBUG */
240 #define NOHOLDER        ((struct thread *)-1)
241 #define SPECIAL_FLAG    ((struct thread *)-2)
242 static struct lockit {
243         int     lkt_spl;
244         struct thread *lkt_held;
245 } lk = { 0, NOHOLDER };
246 static int lockcnt;
247
248 static  void acquire_lock(struct lockit *);
249 static  void free_lock(struct lockit *);
250 void    softdep_panic(char *);
251
252 #define ACQUIRE_LOCK(lk)                acquire_lock(lk)
253 #define FREE_LOCK(lk)                   free_lock(lk)
254
255 static void
256 acquire_lock(struct lockit *lk)
257 {
258         thread_t holder;
259
260         if (lk->lkt_held != NOHOLDER) {
261                 holder = lk->lkt_held;
262                 FREE_LOCK(lk);
263                 if (holder == curthread)
264                         panic("softdep_lock: locking against myself");
265                 else
266                         panic("softdep_lock: lock held by %p", holder);
267         }
268         crit_enter_id("softupdates");
269         lk->lkt_held = curthread;
270         lockcnt++;
271 }
272
273 static void
274 free_lock(struct lockit *lk)
275 {
276
277         if (lk->lkt_held == NOHOLDER)
278                 panic("softdep_unlock: lock not held");
279         lk->lkt_held = NOHOLDER;
280         crit_exit_id("softupdates");
281 }
282
283 /*
284  * Function to release soft updates lock and panic.
285  */
286 void
287 softdep_panic(char *msg)
288 {
289
290         if (lk.lkt_held != NOHOLDER)
291                 FREE_LOCK(&lk);
292         panic(msg);
293 }
294 #endif /* DEBUG */
295
296 static  int interlocked_sleep(struct lockit *, int, void *, int,
297             const char *, int);
298
299 /*
300  * When going to sleep, we must save our SPL so that it does
301  * not get lost if some other process uses the lock while we
302  * are sleeping. We restore it after we have slept. This routine
303  * wraps the interlocking with functions that sleep. The list
304  * below enumerates the available set of operations.
305  */
306 #define UNKNOWN         0
307 #define SLEEP           1
308 #define LOCKBUF         2
309
310 static int
311 interlocked_sleep(struct lockit *lk, int op, void *ident, int flags,
312                   const char *wmesg, int timo)
313 {
314         thread_t holder;
315         int s, retval;
316
317         s = lk->lkt_spl;
318 #       ifdef DEBUG
319         if (lk->lkt_held == NOHOLDER)
320                 panic("interlocked_sleep: lock not held");
321         lk->lkt_held = NOHOLDER;
322 #       endif /* DEBUG */
323         switch (op) {
324         case SLEEP:
325                 retval = tsleep(ident, flags, wmesg, timo);
326                 break;
327         case LOCKBUF:
328                 retval = BUF_LOCK((struct buf *)ident, flags);
329                 break;
330         default:
331                 panic("interlocked_sleep: unknown operation");
332         }
333 #       ifdef DEBUG
334         if (lk->lkt_held != NOHOLDER) {
335                 holder = lk->lkt_held;
336                 FREE_LOCK(lk);
337                 if (holder == curthread)
338                         panic("interlocked_sleep: locking against self");
339                 else
340                         panic("interlocked_sleep: lock held by %p", holder);
341         }
342         lk->lkt_held = curthread;
343         lockcnt++;
344 #       endif /* DEBUG */
345         lk->lkt_spl = s;
346         return (retval);
347 }
348
349 /*
350  * Place holder for real semaphores.
351  */
352 struct sema {
353         int     value;
354         thread_t holder;
355         char    *name;
356         int     prio;
357         int     timo;
358 };
359 static  void sema_init(struct sema *, char *, int, int);
360 static  int sema_get(struct sema *, struct lockit *);
361 static  void sema_release(struct sema *);
362
363 static void
364 sema_init(struct sema *semap, char *name, int prio, int timo)
365 {
366
367         semap->holder = NOHOLDER;
368         semap->value = 0;
369         semap->name = name;
370         semap->prio = prio;
371         semap->timo = timo;
372 }
373
374 static int
375 sema_get(struct sema *semap, struct lockit *interlock)
376 {
377
378         if (semap->value++ > 0) {
379                 if (interlock != NULL) {
380                         interlocked_sleep(interlock, SLEEP, (caddr_t)semap,
381                             semap->prio, semap->name, semap->timo);
382                         FREE_LOCK(interlock);
383                 } else {
384                         tsleep((caddr_t)semap, semap->prio, semap->name,
385                             semap->timo);
386                 }
387                 return (0);
388         }
389         semap->holder = curthread;
390         if (interlock != NULL)
391                 FREE_LOCK(interlock);
392         return (1);
393 }
394
395 static void
396 sema_release(struct sema *semap)
397 {
398
399         if (semap->value <= 0 || semap->holder != curthread) {
400                 if (lk.lkt_held != NOHOLDER)
401                         FREE_LOCK(&lk);
402                 panic("sema_release: not held");
403         }
404         if (--semap->value > 0) {
405                 semap->value = 0;
406                 wakeup(semap);
407         }
408         semap->holder = NOHOLDER;
409 }
410
411 /*
412  * Worklist queue management.
413  * These routines require that the lock be held.
414  */
415 #ifndef /* NOT */ DEBUG
416 #define WORKLIST_INSERT(head, item) do {        \
417         (item)->wk_state |= ONWORKLIST;         \
418         LIST_INSERT_HEAD(head, item, wk_list);  \
419 } while (0)
420
421 #define WORKLIST_INSERT_BP(bp, item) do {       \
422         (item)->wk_state |= ONWORKLIST;         \
423         (bp)->b_ops = &softdep_bioops;          \
424         LIST_INSERT_HEAD(&(bp)->b_dep, item, wk_list);  \
425 } while (0)
426
427 #define WORKLIST_REMOVE(item) do {              \
428         (item)->wk_state &= ~ONWORKLIST;        \
429         LIST_REMOVE(item, wk_list);             \
430 } while (0)
431
432 #define WORKITEM_FREE(item, type) FREE(item, DtoM(type))
433
434 #else /* DEBUG */
435 static  void worklist_insert(struct workhead *, struct worklist *);
436 static  void worklist_remove(struct worklist *);
437 static  void workitem_free(struct worklist *, int);
438
439 #define WORKLIST_INSERT_BP(bp, item) do {       \
440         (bp)->b_ops = &softdep_bioops;          \
441         worklist_insert(&(bp)->b_dep, item);    \
442 } while (0)
443
444 #define WORKLIST_INSERT(head, item) worklist_insert(head, item)
445 #define WORKLIST_REMOVE(item) worklist_remove(item)
446 #define WORKITEM_FREE(item, type) workitem_free((struct worklist *)item, type)
447
448 static void
449 worklist_insert(struct workhead *head, struct worklist *item)
450 {
451
452         if (lk.lkt_held == NOHOLDER)
453                 panic("worklist_insert: lock not held");
454         if (item->wk_state & ONWORKLIST) {
455                 FREE_LOCK(&lk);
456                 panic("worklist_insert: already on list");
457         }
458         item->wk_state |= ONWORKLIST;
459         LIST_INSERT_HEAD(head, item, wk_list);
460 }
461
462 static void
463 worklist_remove(struct worklist *item)
464 {
465
466         if (lk.lkt_held == NOHOLDER)
467                 panic("worklist_remove: lock not held");
468         if ((item->wk_state & ONWORKLIST) == 0) {
469                 FREE_LOCK(&lk);
470                 panic("worklist_remove: not on list");
471         }
472         item->wk_state &= ~ONWORKLIST;
473         LIST_REMOVE(item, wk_list);
474 }
475
476 static void
477 workitem_free(struct worklist *item, int type)
478 {
479
480         if (item->wk_state & ONWORKLIST) {
481                 if (lk.lkt_held != NOHOLDER)
482                         FREE_LOCK(&lk);
483                 panic("workitem_free: still on list");
484         }
485         if (item->wk_type != type) {
486                 if (lk.lkt_held != NOHOLDER)
487                         FREE_LOCK(&lk);
488                 panic("workitem_free: type mismatch");
489         }
490         FREE(item, DtoM(type));
491 }
492 #endif /* DEBUG */
493
494 /*
495  * Workitem queue management
496  */
497 static struct workhead softdep_workitem_pending;
498 static int num_on_worklist;     /* number of worklist items to be processed */
499 static int softdep_worklist_busy; /* 1 => trying to do unmount */
500 static int softdep_worklist_req; /* serialized waiters */
501 static int max_softdeps;        /* maximum number of structs before slowdown */
502 static int tickdelay = 2;       /* number of ticks to pause during slowdown */
503 static int *stat_countp;        /* statistic to count in proc_waiting timeout */
504 static int proc_waiting;        /* tracks whether we have a timeout posted */
505 static struct callout handle; /* handle on posted proc_waiting timeout */
506 static struct thread *filesys_syncer; /* proc of filesystem syncer process */
507 static int req_clear_inodedeps; /* syncer process flush some inodedeps */
508 #define FLUSH_INODES    1
509 static int req_clear_remove;    /* syncer process flush some freeblks */
510 #define FLUSH_REMOVE    2
511 /*
512  * runtime statistics
513  */
514 static int stat_worklist_push;  /* number of worklist cleanups */
515 static int stat_blk_limit_push; /* number of times block limit neared */
516 static int stat_ino_limit_push; /* number of times inode limit neared */
517 static int stat_blk_limit_hit;  /* number of times block slowdown imposed */
518 static int stat_ino_limit_hit;  /* number of times inode slowdown imposed */
519 static int stat_sync_limit_hit; /* number of synchronous slowdowns imposed */
520 static int stat_indir_blk_ptrs; /* bufs redirtied as indir ptrs not written */
521 static int stat_inode_bitmap;   /* bufs redirtied as inode bitmap not written */
522 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
523 static int stat_dir_entry;      /* bufs redirtied as dir entry cannot write */
524 #ifdef DEBUG
525 #include <vm/vm.h>
526 #include <sys/sysctl.h>
527 SYSCTL_INT(_debug, OID_AUTO, max_softdeps, CTLFLAG_RW, &max_softdeps, 0, "");
528 SYSCTL_INT(_debug, OID_AUTO, tickdelay, CTLFLAG_RW, &tickdelay, 0, "");
529 SYSCTL_INT(_debug, OID_AUTO, worklist_push, CTLFLAG_RW, &stat_worklist_push, 0,"");
530 SYSCTL_INT(_debug, OID_AUTO, blk_limit_push, CTLFLAG_RW, &stat_blk_limit_push, 0,"");
531 SYSCTL_INT(_debug, OID_AUTO, ino_limit_push, CTLFLAG_RW, &stat_ino_limit_push, 0,"");
532 SYSCTL_INT(_debug, OID_AUTO, blk_limit_hit, CTLFLAG_RW, &stat_blk_limit_hit, 0, "");
533 SYSCTL_INT(_debug, OID_AUTO, ino_limit_hit, CTLFLAG_RW, &stat_ino_limit_hit, 0, "");
534 SYSCTL_INT(_debug, OID_AUTO, sync_limit_hit, CTLFLAG_RW, &stat_sync_limit_hit, 0, "");
535 SYSCTL_INT(_debug, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW, &stat_indir_blk_ptrs, 0, "");
536 SYSCTL_INT(_debug, OID_AUTO, inode_bitmap, CTLFLAG_RW, &stat_inode_bitmap, 0, "");
537 SYSCTL_INT(_debug, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW, &stat_direct_blk_ptrs, 0, "");
538 SYSCTL_INT(_debug, OID_AUTO, dir_entry, CTLFLAG_RW, &stat_dir_entry, 0, "");
539 #endif /* DEBUG */
540
541 /*
542  * Add an item to the end of the work queue.
543  * This routine requires that the lock be held.
544  * This is the only routine that adds items to the list.
545  * The following routine is the only one that removes items
546  * and does so in order from first to last.
547  */
548 static void
549 add_to_worklist(struct worklist *wk)
550 {
551         static struct worklist *worklist_tail;
552
553         if (wk->wk_state & ONWORKLIST) {
554                 if (lk.lkt_held != NOHOLDER)
555                         FREE_LOCK(&lk);
556                 panic("add_to_worklist: already on list");
557         }
558         wk->wk_state |= ONWORKLIST;
559         if (LIST_FIRST(&softdep_workitem_pending) == NULL)
560                 LIST_INSERT_HEAD(&softdep_workitem_pending, wk, wk_list);
561         else
562                 LIST_INSERT_AFTER(worklist_tail, wk, wk_list);
563         worklist_tail = wk;
564         num_on_worklist += 1;
565 }
566
567 /*
568  * Process that runs once per second to handle items in the background queue.
569  *
570  * Note that we ensure that everything is done in the order in which they
571  * appear in the queue. The code below depends on this property to ensure
572  * that blocks of a file are freed before the inode itself is freed. This
573  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
574  * until all the old ones have been purged from the dependency lists.
575  */
576 static int 
577 softdep_process_worklist(struct mount *matchmnt)
578 {
579         thread_t td = curthread;
580         int matchcnt, loopcount;
581         long starttime;
582
583         /*
584          * Record the process identifier of our caller so that we can give
585          * this process preferential treatment in request_cleanup below.
586          */
587         filesys_syncer = td;
588         matchcnt = 0;
589
590         /*
591          * There is no danger of having multiple processes run this
592          * code, but we have to single-thread it when softdep_flushfiles()
593          * is in operation to get an accurate count of the number of items
594          * related to its mount point that are in the list.
595          */
596         if (matchmnt == NULL) {
597                 if (softdep_worklist_busy < 0)
598                         return(-1);
599                 softdep_worklist_busy += 1;
600         }
601
602         /*
603          * If requested, try removing inode or removal dependencies.
604          */
605         if (req_clear_inodedeps) {
606                 clear_inodedeps(td);
607                 req_clear_inodedeps -= 1;
608                 wakeup_one(&proc_waiting);
609         }
610         if (req_clear_remove) {
611                 clear_remove(td);
612                 req_clear_remove -= 1;
613                 wakeup_one(&proc_waiting);
614         }
615         loopcount = 1;
616         starttime = time_second;
617         while (num_on_worklist > 0) {
618                 matchcnt += process_worklist_item(matchmnt, 0);
619
620                 /*
621                  * If a umount operation wants to run the worklist
622                  * accurately, abort.
623                  */
624                 if (softdep_worklist_req && matchmnt == NULL) {
625                         matchcnt = -1;
626                         break;
627                 }
628
629                 /*
630                  * If requested, try removing inode or removal dependencies.
631                  */
632                 if (req_clear_inodedeps) {
633                         clear_inodedeps(td);
634                         req_clear_inodedeps -= 1;
635                         wakeup_one(&proc_waiting);
636                 }
637                 if (req_clear_remove) {
638                         clear_remove(td);
639                         req_clear_remove -= 1;
640                         wakeup_one(&proc_waiting);
641                 }
642                 /*
643                  * We do not generally want to stop for buffer space, but if
644                  * we are really being a buffer hog, we will stop and wait.
645                  */
646                 if (loopcount++ % 128 == 0)
647                         bwillwrite();
648                 /*
649                  * Never allow processing to run for more than one
650                  * second. Otherwise the other syncer tasks may get
651                  * excessively backlogged.
652                  */
653                 if (starttime != time_second && matchmnt == NULL) {
654                         matchcnt = -1;
655                         break;
656                 }
657         }
658         if (matchmnt == NULL) {
659                 --softdep_worklist_busy;
660                 if (softdep_worklist_req && softdep_worklist_busy == 0)
661                         wakeup(&softdep_worklist_req);
662         }
663         return (matchcnt);
664 }
665
666 /*
667  * Process one item on the worklist.
668  */
669 static int
670 process_worklist_item(struct mount *matchmnt, int flags)
671 {
672         struct worklist *wk;
673         struct dirrem *dirrem;
674         struct fs *matchfs;
675         struct vnode *vp;
676         int matchcnt = 0;
677
678         matchfs = NULL;
679         if (matchmnt != NULL)
680                 matchfs = VFSTOUFS(matchmnt)->um_fs;
681         ACQUIRE_LOCK(&lk);
682         /*
683          * Normally we just process each item on the worklist in order.
684          * However, if we are in a situation where we cannot lock any
685          * inodes, we have to skip over any dirrem requests whose
686          * vnodes are resident and locked.
687          */
688         LIST_FOREACH(wk, &softdep_workitem_pending, wk_list) {
689                 if ((flags & LK_NOWAIT) == 0 || wk->wk_type != D_DIRREM)
690                         break;
691                 dirrem = WK_DIRREM(wk);
692                 vp = ufs_ihashlookup(VFSTOUFS(dirrem->dm_mnt)->um_dev,
693                     dirrem->dm_oldinum);
694                 if (vp == NULL || !vn_islocked(vp))
695                         break;
696         }
697         if (wk == 0) {
698                 FREE_LOCK(&lk);
699                 return (0);
700         }
701         WORKLIST_REMOVE(wk);
702         num_on_worklist -= 1;
703         FREE_LOCK(&lk);
704         switch (wk->wk_type) {
705
706         case D_DIRREM:
707                 /* removal of a directory entry */
708                 if (WK_DIRREM(wk)->dm_mnt == matchmnt)
709                         matchcnt += 1;
710                 handle_workitem_remove(WK_DIRREM(wk));
711                 break;
712
713         case D_FREEBLKS:
714                 /* releasing blocks and/or fragments from a file */
715                 if (WK_FREEBLKS(wk)->fb_fs == matchfs)
716                         matchcnt += 1;
717                 handle_workitem_freeblocks(WK_FREEBLKS(wk));
718                 break;
719
720         case D_FREEFRAG:
721                 /* releasing a fragment when replaced as a file grows */
722                 if (WK_FREEFRAG(wk)->ff_fs == matchfs)
723                         matchcnt += 1;
724                 handle_workitem_freefrag(WK_FREEFRAG(wk));
725                 break;
726
727         case D_FREEFILE:
728                 /* releasing an inode when its link count drops to 0 */
729                 if (WK_FREEFILE(wk)->fx_fs == matchfs)
730                         matchcnt += 1;
731                 handle_workitem_freefile(WK_FREEFILE(wk));
732                 break;
733
734         default:
735                 panic("%s_process_worklist: Unknown type %s",
736                     "softdep", TYPENAME(wk->wk_type));
737                 /* NOTREACHED */
738         }
739         return (matchcnt);
740 }
741
742 /*
743  * Move dependencies from one buffer to another.
744  */
745 static void
746 softdep_move_dependencies(struct buf *oldbp, struct buf *newbp)
747 {
748         struct worklist *wk, *wktail;
749
750         if (LIST_FIRST(&newbp->b_dep) != NULL)
751                 panic("softdep_move_dependencies: need merge code");
752         wktail = NULL;
753         ACQUIRE_LOCK(&lk);
754         while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
755                 LIST_REMOVE(wk, wk_list);
756                 if (wktail == NULL)
757                         LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
758                 else
759                         LIST_INSERT_AFTER(wktail, wk, wk_list);
760                 wktail = wk;
761                 newbp->b_ops = &softdep_bioops;
762         }
763         FREE_LOCK(&lk);
764 }
765
766 /*
767  * Purge the work list of all items associated with a particular mount point.
768  */
769 int
770 softdep_flushfiles(struct mount *oldmnt, int flags)
771 {
772         struct vnode *devvp;
773         int error, loopcnt;
774
775         /*
776          * Await our turn to clear out the queue, then serialize access.
777          */
778         while (softdep_worklist_busy != 0) {
779                 softdep_worklist_req += 1;
780                 tsleep(&softdep_worklist_req, 0, "softflush", 0);
781                 softdep_worklist_req -= 1;
782         }
783         softdep_worklist_busy = -1;
784
785         if ((error = ffs_flushfiles(oldmnt, flags)) != 0) {
786                 softdep_worklist_busy = 0;
787                 if (softdep_worklist_req)
788                         wakeup(&softdep_worklist_req);
789                 return (error);
790         }
791         /*
792          * Alternately flush the block device associated with the mount
793          * point and process any dependencies that the flushing
794          * creates. In theory, this loop can happen at most twice,
795          * but we give it a few extra just to be sure.
796          */
797         devvp = VFSTOUFS(oldmnt)->um_devvp;
798         for (loopcnt = 10; loopcnt > 0; ) {
799                 if (softdep_process_worklist(oldmnt) == 0) {
800                         loopcnt--;
801                         /*
802                          * Do another flush in case any vnodes were brought in
803                          * as part of the cleanup operations.
804                          */
805                         if ((error = ffs_flushfiles(oldmnt, flags)) != 0)
806                                 break;
807                         /*
808                          * If we still found nothing to do, we are really done.
809                          */
810                         if (softdep_process_worklist(oldmnt) == 0)
811                                 break;
812                 }
813                 vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
814                 error = VOP_FSYNC(devvp, MNT_WAIT);
815                 vn_unlock(devvp);
816                 if (error)
817                         break;
818         }
819         softdep_worklist_busy = 0;
820         if (softdep_worklist_req)
821                 wakeup(&softdep_worklist_req);
822
823         /*
824          * If we are unmounting then it is an error to fail. If we
825          * are simply trying to downgrade to read-only, then filesystem
826          * activity can keep us busy forever, so we just fail with EBUSY.
827          */
828         if (loopcnt == 0) {
829                 if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
830                         panic("softdep_flushfiles: looping");
831                 error = EBUSY;
832         }
833         return (error);
834 }
835
836 /*
837  * Structure hashing.
838  * 
839  * There are three types of structures that can be looked up:
840  *      1) pagedep structures identified by mount point, inode number,
841  *         and logical block.
842  *      2) inodedep structures identified by mount point and inode number.
843  *      3) newblk structures identified by mount point and
844  *         physical block number.
845  *
846  * The "pagedep" and "inodedep" dependency structures are hashed
847  * separately from the file blocks and inodes to which they correspond.
848  * This separation helps when the in-memory copy of an inode or
849  * file block must be replaced. It also obviates the need to access
850  * an inode or file page when simply updating (or de-allocating)
851  * dependency structures. Lookup of newblk structures is needed to
852  * find newly allocated blocks when trying to associate them with
853  * their allocdirect or allocindir structure.
854  *
855  * The lookup routines optionally create and hash a new instance when
856  * an existing entry is not found.
857  */
858 #define DEPALLOC        0x0001  /* allocate structure if lookup fails */
859 #define NODELAY         0x0002  /* cannot do background work */
860
861 /*
862  * Structures and routines associated with pagedep caching.
863  */
864 LIST_HEAD(pagedep_hashhead, pagedep) *pagedep_hashtbl;
865 u_long  pagedep_hash;           /* size of hash table - 1 */
866 #define PAGEDEP_HASH(mp, inum, lbn) \
867         (&pagedep_hashtbl[((((register_t)(mp)) >> 13) + (inum) + (lbn)) & \
868             pagedep_hash])
869 static struct sema pagedep_in_progress;
870
871 /*
872  * Helper routine for pagedep_lookup()
873  */
874 static __inline
875 struct pagedep *
876 pagedep_find(struct pagedep_hashhead *pagedephd, ino_t ino, ufs_lbn_t lbn,
877              struct mount *mp)
878 {
879         struct pagedep *pagedep;
880
881         LIST_FOREACH(pagedep, pagedephd, pd_hash) {
882                 if (ino == pagedep->pd_ino &&
883                     lbn == pagedep->pd_lbn &&
884                     mp == pagedep->pd_mnt) {
885                         return (pagedep);
886                 }
887         }
888         return(NULL);
889 }
890
891 /*
892  * Look up a pagedep. Return 1 if found, 0 if not found.
893  * If not found, allocate if DEPALLOC flag is passed.
894  * Found or allocated entry is returned in pagedeppp.
895  * This routine must be called with splbio interrupts blocked.
896  */
897 static int
898 pagedep_lookup(struct inode *ip, ufs_lbn_t lbn, int flags,
899                struct pagedep **pagedeppp)
900 {
901         struct pagedep *pagedep;
902         struct pagedep_hashhead *pagedephd;
903         struct mount *mp;
904         int i;
905
906 #ifdef DEBUG
907         if (lk.lkt_held == NOHOLDER)
908                 panic("pagedep_lookup: lock not held");
909 #endif
910         mp = ITOV(ip)->v_mount;
911         pagedephd = PAGEDEP_HASH(mp, ip->i_number, lbn);
912 top:
913         *pagedeppp = pagedep_find(pagedephd, ip->i_number, lbn, mp);
914         if (*pagedeppp)
915                 return(1);
916         if ((flags & DEPALLOC) == 0)
917                 return (0);
918         if (sema_get(&pagedep_in_progress, &lk) == 0) {
919                 ACQUIRE_LOCK(&lk);
920                 goto top;
921         }
922         MALLOC(pagedep, struct pagedep *, sizeof(struct pagedep), M_PAGEDEP,
923                 M_SOFTDEP_FLAGS | M_ZERO);
924
925         if (pagedep_find(pagedephd, ip->i_number, lbn, mp)) {
926                 kprintf("pagedep_lookup: blocking race avoided\n");
927                 ACQUIRE_LOCK(&lk);
928                 sema_release(&pagedep_in_progress);
929                 kfree(pagedep, M_PAGEDEP);
930                 goto top;
931         }
932
933         pagedep->pd_list.wk_type = D_PAGEDEP;
934         pagedep->pd_mnt = mp;
935         pagedep->pd_ino = ip->i_number;
936         pagedep->pd_lbn = lbn;
937         LIST_INIT(&pagedep->pd_dirremhd);
938         LIST_INIT(&pagedep->pd_pendinghd);
939         for (i = 0; i < DAHASHSZ; i++)
940                 LIST_INIT(&pagedep->pd_diraddhd[i]);
941         ACQUIRE_LOCK(&lk);
942         LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
943         sema_release(&pagedep_in_progress);
944         *pagedeppp = pagedep;
945         return (0);
946 }
947
948 /*
949  * Structures and routines associated with inodedep caching.
950  */
951 LIST_HEAD(inodedep_hashhead, inodedep) *inodedep_hashtbl;
952 static u_long   inodedep_hash;  /* size of hash table - 1 */
953 static long     num_inodedep;   /* number of inodedep allocated */
954 #define INODEDEP_HASH(fs, inum) \
955       (&inodedep_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & inodedep_hash])
956 static struct sema inodedep_in_progress;
957
958 /*
959  * Helper routine for inodedep_lookup()
960  */
961 static __inline
962 struct inodedep *
963 inodedep_find(struct inodedep_hashhead *inodedephd, struct fs *fs, ino_t inum)
964 {
965         struct inodedep *inodedep;
966
967         LIST_FOREACH(inodedep, inodedephd, id_hash) {
968                 if (inum == inodedep->id_ino && fs == inodedep->id_fs)
969                         return(inodedep);
970         }
971         return (NULL);
972 }
973
974 /*
975  * Look up a inodedep. Return 1 if found, 0 if not found.
976  * If not found, allocate if DEPALLOC flag is passed.
977  * Found or allocated entry is returned in inodedeppp.
978  * This routine must be called with splbio interrupts blocked.
979  */
980 static int
981 inodedep_lookup(struct fs *fs, ino_t inum, int flags,
982                 struct inodedep **inodedeppp)
983 {
984         struct inodedep *inodedep;
985         struct inodedep_hashhead *inodedephd;
986         int firsttry;
987
988 #ifdef DEBUG
989         if (lk.lkt_held == NOHOLDER)
990                 panic("inodedep_lookup: lock not held");
991 #endif
992         firsttry = 1;
993         inodedephd = INODEDEP_HASH(fs, inum);
994 top:
995         *inodedeppp = inodedep_find(inodedephd, fs, inum);
996         if (*inodedeppp)
997                 return (1);
998         if ((flags & DEPALLOC) == 0)
999                 return (0);
1000         /*
1001          * If we are over our limit, try to improve the situation.
1002          */
1003         if (num_inodedep > max_softdeps && firsttry && 
1004             speedup_syncer() == 0 && (flags & NODELAY) == 0 &&
1005             request_cleanup(FLUSH_INODES, 1)) {
1006                 firsttry = 0;
1007                 goto top;
1008         }
1009         if (sema_get(&inodedep_in_progress, &lk) == 0) {
1010                 ACQUIRE_LOCK(&lk);
1011                 goto top;
1012         }
1013         MALLOC(inodedep, struct inodedep *, sizeof(struct inodedep),
1014                 M_INODEDEP, M_SOFTDEP_FLAGS | M_ZERO);
1015         if (inodedep_find(inodedephd, fs, inum)) {
1016                 kprintf("inodedep_lookup: blocking race avoided\n");
1017                 ACQUIRE_LOCK(&lk);
1018                 sema_release(&inodedep_in_progress);
1019                 kfree(inodedep, M_INODEDEP);
1020                 goto top;
1021         }
1022         inodedep->id_list.wk_type = D_INODEDEP;
1023         inodedep->id_fs = fs;
1024         inodedep->id_ino = inum;
1025         inodedep->id_state = ALLCOMPLETE;
1026         inodedep->id_nlinkdelta = 0;
1027         inodedep->id_savedino = NULL;
1028         inodedep->id_savedsize = -1;
1029         inodedep->id_buf = NULL;
1030         LIST_INIT(&inodedep->id_pendinghd);
1031         LIST_INIT(&inodedep->id_inowait);
1032         LIST_INIT(&inodedep->id_bufwait);
1033         TAILQ_INIT(&inodedep->id_inoupdt);
1034         TAILQ_INIT(&inodedep->id_newinoupdt);
1035         ACQUIRE_LOCK(&lk);
1036         num_inodedep += 1;
1037         LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
1038         sema_release(&inodedep_in_progress);
1039         *inodedeppp = inodedep;
1040         return (0);
1041 }
1042
1043 /*
1044  * Structures and routines associated with newblk caching.
1045  */
1046 LIST_HEAD(newblk_hashhead, newblk) *newblk_hashtbl;
1047 u_long  newblk_hash;            /* size of hash table - 1 */
1048 #define NEWBLK_HASH(fs, inum) \
1049         (&newblk_hashtbl[((((register_t)(fs)) >> 13) + (inum)) & newblk_hash])
1050 static struct sema newblk_in_progress;
1051
1052 /*
1053  * Helper routine for newblk_lookup()
1054  */
1055 static __inline
1056 struct newblk *
1057 newblk_find(struct newblk_hashhead *newblkhd, struct fs *fs, 
1058             ufs_daddr_t newblkno)
1059 {
1060         struct newblk *newblk;
1061
1062         LIST_FOREACH(newblk, newblkhd, nb_hash) {
1063                 if (newblkno == newblk->nb_newblkno && fs == newblk->nb_fs)
1064                         return (newblk);
1065         }
1066         return(NULL);
1067 }
1068
1069 /*
1070  * Look up a newblk. Return 1 if found, 0 if not found.
1071  * If not found, allocate if DEPALLOC flag is passed.
1072  * Found or allocated entry is returned in newblkpp.
1073  */
1074 static int
1075 newblk_lookup(struct fs *fs, ufs_daddr_t newblkno, int flags,
1076               struct newblk **newblkpp)
1077 {
1078         struct newblk *newblk;
1079         struct newblk_hashhead *newblkhd;
1080
1081         newblkhd = NEWBLK_HASH(fs, newblkno);
1082 top:
1083         *newblkpp = newblk_find(newblkhd, fs, newblkno);
1084         if (*newblkpp)
1085                 return(1);
1086         if ((flags & DEPALLOC) == 0)
1087                 return (0);
1088         if (sema_get(&newblk_in_progress, 0) == 0)
1089                 goto top;
1090         MALLOC(newblk, struct newblk *, sizeof(struct newblk),
1091                 M_NEWBLK, M_SOFTDEP_FLAGS | M_ZERO);
1092
1093         if (newblk_find(newblkhd, fs, newblkno)) {
1094                 kprintf("newblk_lookup: blocking race avoided\n");
1095                 sema_release(&pagedep_in_progress);
1096                 kfree(newblk, M_NEWBLK);
1097                 goto top;
1098         }
1099         newblk->nb_state = 0;
1100         newblk->nb_fs = fs;
1101         newblk->nb_newblkno = newblkno;
1102         LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
1103         sema_release(&newblk_in_progress);
1104         *newblkpp = newblk;
1105         return (0);
1106 }
1107
1108 /*
1109  * Executed during filesystem system initialization before
1110  * mounting any filesystems.
1111  */
1112 void 
1113 softdep_initialize(void)
1114 {
1115         callout_init(&handle);
1116
1117         LIST_INIT(&mkdirlisthd);
1118         LIST_INIT(&softdep_workitem_pending);
1119         max_softdeps = min(desiredvnodes * 8,
1120                 M_INODEDEP->ks_limit / (2 * sizeof(struct inodedep)));
1121         pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
1122             &pagedep_hash);
1123         sema_init(&pagedep_in_progress, "pagedep", 0, 0);
1124         inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP, &inodedep_hash);
1125         sema_init(&inodedep_in_progress, "inodedep", 0, 0);
1126         newblk_hashtbl = hashinit(64, M_NEWBLK, &newblk_hash);
1127         sema_init(&newblk_in_progress, "newblk", 0, 0);
1128         add_bio_ops(&softdep_bioops);
1129 }
1130
1131 /*
1132  * Called at mount time to notify the dependency code that a
1133  * filesystem wishes to use it.
1134  */
1135 int
1136 softdep_mount(struct vnode *devvp, struct mount *mp, struct fs *fs)
1137 {
1138         struct csum cstotal;
1139         struct cg *cgp;
1140         struct buf *bp;
1141         int error, cyl;
1142
1143         mp->mnt_flag &= ~MNT_ASYNC;
1144         mp->mnt_flag |= MNT_SOFTDEP;
1145         mp->mnt_bioops = &softdep_bioops;
1146         /*
1147          * When doing soft updates, the counters in the
1148          * superblock may have gotten out of sync, so we have
1149          * to scan the cylinder groups and recalculate them.
1150          */
1151         if (fs->fs_clean != 0)
1152                 return (0);
1153         bzero(&cstotal, sizeof cstotal);
1154         for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
1155                 if ((error = bread(devvp, fsbtodoff(fs, cgtod(fs, cyl)),
1156                                    fs->fs_cgsize, &bp)) != 0) {
1157                         brelse(bp);
1158                         return (error);
1159                 }
1160                 cgp = (struct cg *)bp->b_data;
1161                 cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
1162                 cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
1163                 cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
1164                 cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
1165                 fs->fs_cs(fs, cyl) = cgp->cg_cs;
1166                 brelse(bp);
1167         }
1168 #ifdef DEBUG
1169         if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
1170                 kprintf("ffs_mountfs: superblock updated for soft updates\n");
1171 #endif
1172         bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
1173         return (0);
1174 }
1175
1176 /*
1177  * Protecting the freemaps (or bitmaps).
1178  * 
1179  * To eliminate the need to execute fsck before mounting a filesystem
1180  * after a power failure, one must (conservatively) guarantee that the
1181  * on-disk copy of the bitmaps never indicate that a live inode or block is
1182  * free.  So, when a block or inode is allocated, the bitmap should be
1183  * updated (on disk) before any new pointers.  When a block or inode is
1184  * freed, the bitmap should not be updated until all pointers have been
1185  * reset.  The latter dependency is handled by the delayed de-allocation
1186  * approach described below for block and inode de-allocation.  The former
1187  * dependency is handled by calling the following procedure when a block or
1188  * inode is allocated. When an inode is allocated an "inodedep" is created
1189  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
1190  * Each "inodedep" is also inserted into the hash indexing structure so
1191  * that any additional link additions can be made dependent on the inode
1192  * allocation.
1193  * 
1194  * The ufs filesystem maintains a number of free block counts (e.g., per
1195  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
1196  * in addition to the bitmaps.  These counts are used to improve efficiency
1197  * during allocation and therefore must be consistent with the bitmaps.
1198  * There is no convenient way to guarantee post-crash consistency of these
1199  * counts with simple update ordering, for two main reasons: (1) The counts
1200  * and bitmaps for a single cylinder group block are not in the same disk
1201  * sector.  If a disk write is interrupted (e.g., by power failure), one may
1202  * be written and the other not.  (2) Some of the counts are located in the
1203  * superblock rather than the cylinder group block. So, we focus our soft
1204  * updates implementation on protecting the bitmaps. When mounting a
1205  * filesystem, we recompute the auxiliary counts from the bitmaps.
1206  */
1207
1208 /*
1209  * Called just after updating the cylinder group block to allocate an inode.
1210  *
1211  * Parameters:
1212  *      bp:             buffer for cylgroup block with inode map
1213  *      ip:             inode related to allocation
1214  *      newinum:        new inode number being allocated
1215  */
1216 void
1217 softdep_setup_inomapdep(struct buf *bp, struct inode *ip, ino_t newinum)
1218 {
1219         struct inodedep *inodedep;
1220         struct bmsafemap *bmsafemap;
1221
1222         /*
1223          * Create a dependency for the newly allocated inode.
1224          * Panic if it already exists as something is seriously wrong.
1225          * Otherwise add it to the dependency list for the buffer holding
1226          * the cylinder group map from which it was allocated.
1227          */
1228         ACQUIRE_LOCK(&lk);
1229         if ((inodedep_lookup(ip->i_fs, newinum, DEPALLOC|NODELAY, &inodedep))) {
1230                 FREE_LOCK(&lk);
1231                 panic("softdep_setup_inomapdep: found inode");
1232         }
1233         inodedep->id_buf = bp;
1234         inodedep->id_state &= ~DEPCOMPLETE;
1235         bmsafemap = bmsafemap_lookup(bp);
1236         LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
1237         FREE_LOCK(&lk);
1238 }
1239
1240 /*
1241  * Called just after updating the cylinder group block to
1242  * allocate block or fragment.
1243  *
1244  * Parameters:
1245  *      bp:             buffer for cylgroup block with block map
1246  *      fs:             filesystem doing allocation
1247  *      newblkno:       number of newly allocated block
1248  */
1249 void
1250 softdep_setup_blkmapdep(struct buf *bp, struct fs *fs,
1251                         ufs_daddr_t newblkno)
1252 {
1253         struct newblk *newblk;
1254         struct bmsafemap *bmsafemap;
1255
1256         /*
1257          * Create a dependency for the newly allocated block.
1258          * Add it to the dependency list for the buffer holding
1259          * the cylinder group map from which it was allocated.
1260          */
1261         if (newblk_lookup(fs, newblkno, DEPALLOC, &newblk) != 0)
1262                 panic("softdep_setup_blkmapdep: found block");
1263         ACQUIRE_LOCK(&lk);
1264         newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(bp);
1265         LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
1266         FREE_LOCK(&lk);
1267 }
1268
1269 /*
1270  * Find the bmsafemap associated with a cylinder group buffer.
1271  * If none exists, create one. The buffer must be locked when
1272  * this routine is called and this routine must be called with
1273  * splbio interrupts blocked.
1274  */
1275 static struct bmsafemap *
1276 bmsafemap_lookup(struct buf *bp)
1277 {
1278         struct bmsafemap *bmsafemap;
1279         struct worklist *wk;
1280
1281 #ifdef DEBUG
1282         if (lk.lkt_held == NOHOLDER)
1283                 panic("bmsafemap_lookup: lock not held");
1284 #endif
1285         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1286                 if (wk->wk_type == D_BMSAFEMAP)
1287                         return (WK_BMSAFEMAP(wk));
1288         }
1289         FREE_LOCK(&lk);
1290         MALLOC(bmsafemap, struct bmsafemap *, sizeof(struct bmsafemap),
1291                 M_BMSAFEMAP, M_SOFTDEP_FLAGS);
1292         bmsafemap->sm_list.wk_type = D_BMSAFEMAP;
1293         bmsafemap->sm_list.wk_state = 0;
1294         bmsafemap->sm_buf = bp;
1295         LIST_INIT(&bmsafemap->sm_allocdirecthd);
1296         LIST_INIT(&bmsafemap->sm_allocindirhd);
1297         LIST_INIT(&bmsafemap->sm_inodedephd);
1298         LIST_INIT(&bmsafemap->sm_newblkhd);
1299         ACQUIRE_LOCK(&lk);
1300         WORKLIST_INSERT_BP(bp, &bmsafemap->sm_list);
1301         return (bmsafemap);
1302 }
1303
1304 /*
1305  * Direct block allocation dependencies.
1306  * 
1307  * When a new block is allocated, the corresponding disk locations must be
1308  * initialized (with zeros or new data) before the on-disk inode points to
1309  * them.  Also, the freemap from which the block was allocated must be
1310  * updated (on disk) before the inode's pointer. These two dependencies are
1311  * independent of each other and are needed for all file blocks and indirect
1312  * blocks that are pointed to directly by the inode.  Just before the
1313  * "in-core" version of the inode is updated with a newly allocated block
1314  * number, a procedure (below) is called to setup allocation dependency
1315  * structures.  These structures are removed when the corresponding
1316  * dependencies are satisfied or when the block allocation becomes obsolete
1317  * (i.e., the file is deleted, the block is de-allocated, or the block is a
1318  * fragment that gets upgraded).  All of these cases are handled in
1319  * procedures described later.
1320  * 
1321  * When a file extension causes a fragment to be upgraded, either to a larger
1322  * fragment or to a full block, the on-disk location may change (if the
1323  * previous fragment could not simply be extended). In this case, the old
1324  * fragment must be de-allocated, but not until after the inode's pointer has
1325  * been updated. In most cases, this is handled by later procedures, which
1326  * will construct a "freefrag" structure to be added to the workitem queue
1327  * when the inode update is complete (or obsolete).  The main exception to
1328  * this is when an allocation occurs while a pending allocation dependency
1329  * (for the same block pointer) remains.  This case is handled in the main
1330  * allocation dependency setup procedure by immediately freeing the
1331  * unreferenced fragments.
1332  *
1333  * Parameters:
1334  *      ip:             inode to which block is being added
1335  *      lbn:            block pointer within inode
1336  *      newblkno:       disk block number being added
1337  *      oldblkno:       previous block number, 0 unless frag
1338  *      newsize:        size of new block
1339  *      oldsize:        size of new block
1340  *      bp:             bp for allocated block
1341  */ 
1342 void 
1343 softdep_setup_allocdirect(struct inode *ip, ufs_lbn_t lbn, ufs_daddr_t newblkno,
1344                           ufs_daddr_t oldblkno, long newsize, long oldsize,
1345                           struct buf *bp)
1346 {
1347         struct allocdirect *adp, *oldadp;
1348         struct allocdirectlst *adphead;
1349         struct bmsafemap *bmsafemap;
1350         struct inodedep *inodedep;
1351         struct pagedep *pagedep;
1352         struct newblk *newblk;
1353
1354         MALLOC(adp, struct allocdirect *, sizeof(struct allocdirect),
1355                 M_ALLOCDIRECT, M_SOFTDEP_FLAGS);
1356         bzero(adp, sizeof(struct allocdirect));
1357         adp->ad_list.wk_type = D_ALLOCDIRECT;
1358         adp->ad_lbn = lbn;
1359         adp->ad_newblkno = newblkno;
1360         adp->ad_oldblkno = oldblkno;
1361         adp->ad_newsize = newsize;
1362         adp->ad_oldsize = oldsize;
1363         adp->ad_state = ATTACHED;
1364         if (newblkno == oldblkno)
1365                 adp->ad_freefrag = NULL;
1366         else
1367                 adp->ad_freefrag = newfreefrag(ip, oldblkno, oldsize);
1368
1369         if (newblk_lookup(ip->i_fs, newblkno, 0, &newblk) == 0)
1370                 panic("softdep_setup_allocdirect: lost block");
1371
1372         ACQUIRE_LOCK(&lk);
1373         inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC | NODELAY, &inodedep);
1374         adp->ad_inodedep = inodedep;
1375
1376         if (newblk->nb_state == DEPCOMPLETE) {
1377                 adp->ad_state |= DEPCOMPLETE;
1378                 adp->ad_buf = NULL;
1379         } else {
1380                 bmsafemap = newblk->nb_bmsafemap;
1381                 adp->ad_buf = bmsafemap->sm_buf;
1382                 LIST_REMOVE(newblk, nb_deps);
1383                 LIST_INSERT_HEAD(&bmsafemap->sm_allocdirecthd, adp, ad_deps);
1384         }
1385         LIST_REMOVE(newblk, nb_hash);
1386         FREE(newblk, M_NEWBLK);
1387
1388         WORKLIST_INSERT_BP(bp, &adp->ad_list);
1389         if (lbn >= NDADDR) {
1390                 /* allocating an indirect block */
1391                 if (oldblkno != 0) {
1392                         FREE_LOCK(&lk);
1393                         panic("softdep_setup_allocdirect: non-zero indir");
1394                 }
1395         } else {
1396                 /*
1397                  * Allocating a direct block.
1398                  *
1399                  * If we are allocating a directory block, then we must
1400                  * allocate an associated pagedep to track additions and
1401                  * deletions.
1402                  */
1403                 if ((ip->i_mode & IFMT) == IFDIR &&
1404                     pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0) {
1405                         WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
1406                 }
1407         }
1408         /*
1409          * The list of allocdirects must be kept in sorted and ascending
1410          * order so that the rollback routines can quickly determine the
1411          * first uncommitted block (the size of the file stored on disk
1412          * ends at the end of the lowest committed fragment, or if there
1413          * are no fragments, at the end of the highest committed block).
1414          * Since files generally grow, the typical case is that the new
1415          * block is to be added at the end of the list. We speed this
1416          * special case by checking against the last allocdirect in the
1417          * list before laboriously traversing the list looking for the
1418          * insertion point.
1419          */
1420         adphead = &inodedep->id_newinoupdt;
1421         oldadp = TAILQ_LAST(adphead, allocdirectlst);
1422         if (oldadp == NULL || oldadp->ad_lbn <= lbn) {
1423                 /* insert at end of list */
1424                 TAILQ_INSERT_TAIL(adphead, adp, ad_next);
1425                 if (oldadp != NULL && oldadp->ad_lbn == lbn)
1426                         allocdirect_merge(adphead, adp, oldadp);
1427                 FREE_LOCK(&lk);
1428                 return;
1429         }
1430         TAILQ_FOREACH(oldadp, adphead, ad_next) {
1431                 if (oldadp->ad_lbn >= lbn)
1432                         break;
1433         }
1434         if (oldadp == NULL) {
1435                 FREE_LOCK(&lk);
1436                 panic("softdep_setup_allocdirect: lost entry");
1437         }
1438         /* insert in middle of list */
1439         TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
1440         if (oldadp->ad_lbn == lbn)
1441                 allocdirect_merge(adphead, adp, oldadp);
1442         FREE_LOCK(&lk);
1443 }
1444
1445 /*
1446  * Replace an old allocdirect dependency with a newer one.
1447  * This routine must be called with splbio interrupts blocked.
1448  *
1449  * Parameters:
1450  *      adphead:        head of list holding allocdirects
1451  *      newadp:         allocdirect being added
1452  *      oldadp:         existing allocdirect being checked
1453  */
1454 static void
1455 allocdirect_merge(struct allocdirectlst *adphead,
1456                   struct allocdirect *newadp,
1457                   struct allocdirect *oldadp)
1458 {
1459         struct freefrag *freefrag;
1460
1461 #ifdef DEBUG
1462         if (lk.lkt_held == NOHOLDER)
1463                 panic("allocdirect_merge: lock not held");
1464 #endif
1465         if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
1466             newadp->ad_oldsize != oldadp->ad_newsize ||
1467             newadp->ad_lbn >= NDADDR) {
1468                 FREE_LOCK(&lk);
1469                 panic("allocdirect_check: old %d != new %d || lbn %ld >= %d",
1470                     newadp->ad_oldblkno, oldadp->ad_newblkno, newadp->ad_lbn,
1471                     NDADDR);
1472         }
1473         newadp->ad_oldblkno = oldadp->ad_oldblkno;
1474         newadp->ad_oldsize = oldadp->ad_oldsize;
1475         /*
1476          * If the old dependency had a fragment to free or had never
1477          * previously had a block allocated, then the new dependency
1478          * can immediately post its freefrag and adopt the old freefrag.
1479          * This action is done by swapping the freefrag dependencies.
1480          * The new dependency gains the old one's freefrag, and the
1481          * old one gets the new one and then immediately puts it on
1482          * the worklist when it is freed by free_allocdirect. It is
1483          * not possible to do this swap when the old dependency had a
1484          * non-zero size but no previous fragment to free. This condition
1485          * arises when the new block is an extension of the old block.
1486          * Here, the first part of the fragment allocated to the new
1487          * dependency is part of the block currently claimed on disk by
1488          * the old dependency, so cannot legitimately be freed until the
1489          * conditions for the new dependency are fulfilled.
1490          */
1491         if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
1492                 freefrag = newadp->ad_freefrag;
1493                 newadp->ad_freefrag = oldadp->ad_freefrag;
1494                 oldadp->ad_freefrag = freefrag;
1495         }
1496         free_allocdirect(adphead, oldadp, 0);
1497 }
1498                 
1499 /*
1500  * Allocate a new freefrag structure if needed.
1501  */
1502 static struct freefrag *
1503 newfreefrag(struct inode *ip, ufs_daddr_t blkno, long size)
1504 {
1505         struct freefrag *freefrag;
1506         struct fs *fs;
1507
1508         if (blkno == 0)
1509                 return (NULL);
1510         fs = ip->i_fs;
1511         if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
1512                 panic("newfreefrag: frag size");
1513         MALLOC(freefrag, struct freefrag *, sizeof(struct freefrag),
1514                 M_FREEFRAG, M_SOFTDEP_FLAGS);
1515         freefrag->ff_list.wk_type = D_FREEFRAG;
1516         freefrag->ff_state = ip->i_uid & ~ONWORKLIST;   /* XXX - used below */
1517         freefrag->ff_inum = ip->i_number;
1518         freefrag->ff_fs = fs;
1519         freefrag->ff_devvp = ip->i_devvp;
1520         freefrag->ff_blkno = blkno;
1521         freefrag->ff_fragsize = size;
1522         return (freefrag);
1523 }
1524
1525 /*
1526  * This workitem de-allocates fragments that were replaced during
1527  * file block allocation.
1528  */
1529 static void 
1530 handle_workitem_freefrag(struct freefrag *freefrag)
1531 {
1532         struct inode tip;
1533
1534         tip.i_fs = freefrag->ff_fs;
1535         tip.i_devvp = freefrag->ff_devvp;
1536         tip.i_dev = freefrag->ff_devvp->v_rdev;
1537         tip.i_number = freefrag->ff_inum;
1538         tip.i_uid = freefrag->ff_state & ~ONWORKLIST;   /* XXX - set above */
1539         ffs_blkfree(&tip, freefrag->ff_blkno, freefrag->ff_fragsize);
1540         FREE(freefrag, M_FREEFRAG);
1541 }
1542
1543 /*
1544  * Indirect block allocation dependencies.
1545  * 
1546  * The same dependencies that exist for a direct block also exist when
1547  * a new block is allocated and pointed to by an entry in a block of
1548  * indirect pointers. The undo/redo states described above are also
1549  * used here. Because an indirect block contains many pointers that
1550  * may have dependencies, a second copy of the entire in-memory indirect
1551  * block is kept. The buffer cache copy is always completely up-to-date.
1552  * The second copy, which is used only as a source for disk writes,
1553  * contains only the safe pointers (i.e., those that have no remaining
1554  * update dependencies). The second copy is freed when all pointers
1555  * are safe. The cache is not allowed to replace indirect blocks with
1556  * pending update dependencies. If a buffer containing an indirect
1557  * block with dependencies is written, these routines will mark it
1558  * dirty again. It can only be successfully written once all the
1559  * dependencies are removed. The ffs_fsync routine in conjunction with
1560  * softdep_sync_metadata work together to get all the dependencies
1561  * removed so that a file can be successfully written to disk. Three
1562  * procedures are used when setting up indirect block pointer
1563  * dependencies. The division is necessary because of the organization
1564  * of the "balloc" routine and because of the distinction between file
1565  * pages and file metadata blocks.
1566  */
1567
1568 /*
1569  * Allocate a new allocindir structure.
1570  *
1571  * Parameters:
1572  *      ip:             inode for file being extended
1573  *      ptrno:          offset of pointer in indirect block
1574  *      newblkno:       disk block number being added
1575  *      oldblkno:       previous block number, 0 if none
1576  */
1577 static struct allocindir *
1578 newallocindir(struct inode *ip, int ptrno, ufs_daddr_t newblkno,
1579               ufs_daddr_t oldblkno)
1580 {
1581         struct allocindir *aip;
1582
1583         MALLOC(aip, struct allocindir *, sizeof(struct allocindir),
1584                 M_ALLOCINDIR, M_SOFTDEP_FLAGS);
1585         bzero(aip, sizeof(struct allocindir));
1586         aip->ai_list.wk_type = D_ALLOCINDIR;
1587         aip->ai_state = ATTACHED;
1588         aip->ai_offset = ptrno;
1589         aip->ai_newblkno = newblkno;
1590         aip->ai_oldblkno = oldblkno;
1591         aip->ai_freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize);
1592         return (aip);
1593 }
1594
1595 /*
1596  * Called just before setting an indirect block pointer
1597  * to a newly allocated file page.
1598  *
1599  * Parameters:
1600  *      ip:             inode for file being extended
1601  *      lbn:            allocated block number within file
1602  *      bp:             buffer with indirect blk referencing page
1603  *      ptrno:          offset of pointer in indirect block
1604  *      newblkno:       disk block number being added
1605  *      oldblkno:       previous block number, 0 if none
1606  *      nbp:            buffer holding allocated page
1607  */
1608 void
1609 softdep_setup_allocindir_page(struct inode *ip, ufs_lbn_t lbn,
1610                               struct buf *bp, int ptrno,
1611                               ufs_daddr_t newblkno, ufs_daddr_t oldblkno,
1612                               struct buf *nbp)
1613 {
1614         struct allocindir *aip;
1615         struct pagedep *pagedep;
1616
1617         aip = newallocindir(ip, ptrno, newblkno, oldblkno);
1618         ACQUIRE_LOCK(&lk);
1619         /*
1620          * If we are allocating a directory page, then we must
1621          * allocate an associated pagedep to track additions and
1622          * deletions.
1623          */
1624         if ((ip->i_mode & IFMT) == IFDIR &&
1625             pagedep_lookup(ip, lbn, DEPALLOC, &pagedep) == 0)
1626                 WORKLIST_INSERT_BP(nbp, &pagedep->pd_list);
1627         WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1628         FREE_LOCK(&lk);
1629         setup_allocindir_phase2(bp, ip, aip);
1630 }
1631
1632 /*
1633  * Called just before setting an indirect block pointer to a
1634  * newly allocated indirect block.
1635  * Parameters:
1636  *      nbp:            newly allocated indirect block
1637  *      ip:             inode for file being extended
1638  *      bp:             indirect block referencing allocated block
1639  *      ptrno:          offset of pointer in indirect block
1640  *      newblkno:       disk block number being added
1641  */
1642 void
1643 softdep_setup_allocindir_meta(struct buf *nbp, struct inode *ip,
1644                               struct buf *bp, int ptrno,
1645                               ufs_daddr_t newblkno)
1646 {
1647         struct allocindir *aip;
1648
1649         aip = newallocindir(ip, ptrno, newblkno, 0);
1650         ACQUIRE_LOCK(&lk);
1651         WORKLIST_INSERT_BP(nbp, &aip->ai_list);
1652         FREE_LOCK(&lk);
1653         setup_allocindir_phase2(bp, ip, aip);
1654 }
1655
1656 /*
1657  * Called to finish the allocation of the "aip" allocated
1658  * by one of the two routines above.
1659  *
1660  * Parameters:
1661  *      bp:     in-memory copy of the indirect block
1662  *      ip:     inode for file being extended
1663  *      aip:    allocindir allocated by the above routines
1664  */
1665 static void 
1666 setup_allocindir_phase2(struct buf *bp, struct inode *ip,
1667                         struct allocindir *aip)
1668 {
1669         struct worklist *wk;
1670         struct indirdep *indirdep, *newindirdep;
1671         struct bmsafemap *bmsafemap;
1672         struct allocindir *oldaip;
1673         struct freefrag *freefrag;
1674         struct newblk *newblk;
1675
1676         if (bp->b_loffset >= 0)
1677                 panic("setup_allocindir_phase2: not indir blk");
1678         for (indirdep = NULL, newindirdep = NULL; ; ) {
1679                 ACQUIRE_LOCK(&lk);
1680                 LIST_FOREACH(wk, &bp->b_dep, wk_list) {
1681                         if (wk->wk_type != D_INDIRDEP)
1682                                 continue;
1683                         indirdep = WK_INDIRDEP(wk);
1684                         break;
1685                 }
1686                 if (indirdep == NULL && newindirdep) {
1687                         indirdep = newindirdep;
1688                         WORKLIST_INSERT_BP(bp, &indirdep->ir_list);
1689                         newindirdep = NULL;
1690                 }
1691                 FREE_LOCK(&lk);
1692                 if (indirdep) {
1693                         if (newblk_lookup(ip->i_fs, aip->ai_newblkno, 0,
1694                             &newblk) == 0)
1695                                 panic("setup_allocindir: lost block");
1696                         ACQUIRE_LOCK(&lk);
1697                         if (newblk->nb_state == DEPCOMPLETE) {
1698                                 aip->ai_state |= DEPCOMPLETE;
1699                                 aip->ai_buf = NULL;
1700                         } else {
1701                                 bmsafemap = newblk->nb_bmsafemap;
1702                                 aip->ai_buf = bmsafemap->sm_buf;
1703                                 LIST_REMOVE(newblk, nb_deps);
1704                                 LIST_INSERT_HEAD(&bmsafemap->sm_allocindirhd,
1705                                     aip, ai_deps);
1706                         }
1707                         LIST_REMOVE(newblk, nb_hash);
1708                         FREE(newblk, M_NEWBLK);
1709                         aip->ai_indirdep = indirdep;
1710                         /*
1711                          * Check to see if there is an existing dependency
1712                          * for this block. If there is, merge the old
1713                          * dependency into the new one.
1714                          */
1715                         if (aip->ai_oldblkno == 0)
1716                                 oldaip = NULL;
1717                         else
1718
1719                                 LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next)
1720                                         if (oldaip->ai_offset == aip->ai_offset)
1721                                                 break;
1722                         if (oldaip != NULL) {
1723                                 if (oldaip->ai_newblkno != aip->ai_oldblkno) {
1724                                         FREE_LOCK(&lk);
1725                                         panic("setup_allocindir_phase2: blkno");
1726                                 }
1727                                 aip->ai_oldblkno = oldaip->ai_oldblkno;
1728                                 freefrag = oldaip->ai_freefrag;
1729                                 oldaip->ai_freefrag = aip->ai_freefrag;
1730                                 aip->ai_freefrag = freefrag;
1731                                 free_allocindir(oldaip, NULL);
1732                         }
1733                         LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
1734                         ((ufs_daddr_t *)indirdep->ir_savebp->b_data)
1735                             [aip->ai_offset] = aip->ai_oldblkno;
1736                         FREE_LOCK(&lk);
1737                 }
1738                 if (newindirdep) {
1739                         /*
1740                          * Avoid any possibility of data corruption by 
1741                          * ensuring that our old version is thrown away.
1742                          */
1743                         newindirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
1744                         brelse(newindirdep->ir_savebp);
1745                         WORKITEM_FREE((caddr_t)newindirdep, D_INDIRDEP);
1746                 }
1747                 if (indirdep)
1748                         break;
1749                 MALLOC(newindirdep, struct indirdep *, sizeof(struct indirdep),
1750                         M_INDIRDEP, M_SOFTDEP_FLAGS);
1751                 newindirdep->ir_list.wk_type = D_INDIRDEP;
1752                 newindirdep->ir_state = ATTACHED;
1753                 LIST_INIT(&newindirdep->ir_deplisthd);
1754                 LIST_INIT(&newindirdep->ir_donehd);
1755                 if (bp->b_bio2.bio_offset == NOOFFSET) {
1756                         VOP_BMAP(bp->b_vp, bp->b_bio1.bio_offset, 
1757                                  &bp->b_bio2.bio_offset, NULL, NULL);
1758                 }
1759                 KKASSERT(bp->b_bio2.bio_offset != NOOFFSET);
1760                 newindirdep->ir_savebp = getblk(ip->i_devvp,
1761                                                 bp->b_bio2.bio_offset,
1762                                                 bp->b_bcount, 0, 0);
1763                 BUF_KERNPROC(newindirdep->ir_savebp);
1764                 bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
1765         }
1766 }
1767
1768 /*
1769  * Block de-allocation dependencies.
1770  * 
1771  * When blocks are de-allocated, the on-disk pointers must be nullified before
1772  * the blocks are made available for use by other files.  (The true
1773  * requirement is that old pointers must be nullified before new on-disk
1774  * pointers are set.  We chose this slightly more stringent requirement to
1775  * reduce complexity.) Our implementation handles this dependency by updating
1776  * the inode (or indirect block) appropriately but delaying the actual block
1777  * de-allocation (i.e., freemap and free space count manipulation) until
1778  * after the updated versions reach stable storage.  After the disk is
1779  * updated, the blocks can be safely de-allocated whenever it is convenient.
1780  * This implementation handles only the common case of reducing a file's
1781  * length to zero. Other cases are handled by the conventional synchronous
1782  * write approach.
1783  *
1784  * The ffs implementation with which we worked double-checks
1785  * the state of the block pointers and file size as it reduces
1786  * a file's length.  Some of this code is replicated here in our
1787  * soft updates implementation.  The freeblks->fb_chkcnt field is
1788  * used to transfer a part of this information to the procedure
1789  * that eventually de-allocates the blocks.
1790  *
1791  * This routine should be called from the routine that shortens
1792  * a file's length, before the inode's size or block pointers
1793  * are modified. It will save the block pointer information for
1794  * later release and zero the inode so that the calling routine
1795  * can release it.
1796  */
1797 struct softdep_setup_freeblocks_info {
1798         struct fs *fs;
1799         struct inode *ip;
1800 };
1801
1802 static int softdep_setup_freeblocks_bp(struct buf *bp, void *data);
1803
1804 /*
1805  * Parameters:
1806  *      ip:     The inode whose length is to be reduced
1807  *      length: The new length for the file
1808  */
1809 void
1810 softdep_setup_freeblocks(struct inode *ip, off_t length)
1811 {
1812         struct softdep_setup_freeblocks_info info;
1813         struct freeblks *freeblks;
1814         struct inodedep *inodedep;
1815         struct allocdirect *adp;
1816         struct vnode *vp;
1817         struct buf *bp;
1818         struct fs *fs;
1819         int i, error, delay;
1820         int count;
1821
1822         fs = ip->i_fs;
1823         if (length != 0)
1824                 panic("softde_setup_freeblocks: non-zero length");
1825         MALLOC(freeblks, struct freeblks *, sizeof(struct freeblks),
1826                 M_FREEBLKS, M_SOFTDEP_FLAGS);
1827         bzero(freeblks, sizeof(struct freeblks));
1828         freeblks->fb_list.wk_type = D_FREEBLKS;
1829         freeblks->fb_state = ATTACHED;
1830         freeblks->fb_uid = ip->i_uid;
1831         freeblks->fb_previousinum = ip->i_number;
1832         freeblks->fb_devvp = ip->i_devvp;
1833         freeblks->fb_fs = fs;
1834         freeblks->fb_oldsize = ip->i_size;
1835         freeblks->fb_newsize = length;
1836         freeblks->fb_chkcnt = ip->i_blocks;
1837         for (i = 0; i < NDADDR; i++) {
1838                 freeblks->fb_dblks[i] = ip->i_db[i];
1839                 ip->i_db[i] = 0;
1840         }
1841         for (i = 0; i < NIADDR; i++) {
1842                 freeblks->fb_iblks[i] = ip->i_ib[i];
1843                 ip->i_ib[i] = 0;
1844         }
1845         ip->i_blocks = 0;
1846         ip->i_size = 0;
1847         /*
1848          * Push the zero'ed inode to to its disk buffer so that we are free
1849          * to delete its dependencies below. Once the dependencies are gone
1850          * the buffer can be safely released.
1851          */
1852         if ((error = bread(ip->i_devvp,
1853                             fsbtodoff(fs, ino_to_fsba(fs, ip->i_number)),
1854             (int)fs->fs_bsize, &bp)) != 0)
1855                 softdep_error("softdep_setup_freeblocks", error);
1856         *((struct ufs1_dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1857             ip->i_din;
1858         /*
1859          * Find and eliminate any inode dependencies.
1860          */
1861         ACQUIRE_LOCK(&lk);
1862         (void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1863         if ((inodedep->id_state & IOSTARTED) != 0) {
1864                 FREE_LOCK(&lk);
1865                 panic("softdep_setup_freeblocks: inode busy");
1866         }
1867         /*
1868          * Add the freeblks structure to the list of operations that
1869          * must await the zero'ed inode being written to disk. If we
1870          * still have a bitmap dependency (delay == 0), then the inode
1871          * has never been written to disk, so we can process the
1872          * freeblks below once we have deleted the dependencies.
1873          */
1874         delay = (inodedep->id_state & DEPCOMPLETE);
1875         if (delay)
1876                 WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1877         /*
1878          * Because the file length has been truncated to zero, any
1879          * pending block allocation dependency structures associated
1880          * with this inode are obsolete and can simply be de-allocated.
1881          * We must first merge the two dependency lists to get rid of
1882          * any duplicate freefrag structures, then purge the merged list.
1883          */
1884         merge_inode_lists(inodedep);
1885         while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
1886                 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1887         FREE_LOCK(&lk);
1888         bdwrite(bp);
1889         /*
1890          * We must wait for any I/O in progress to finish so that
1891          * all potential buffers on the dirty list will be visible.
1892          * Once they are all there, walk the list and get rid of
1893          * any dependencies.
1894          */
1895         vp = ITOV(ip);
1896         ACQUIRE_LOCK(&lk);
1897         drain_output(vp, 1);
1898
1899         info.fs = fs;
1900         info.ip = ip;
1901         do {
1902                 count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
1903                                 softdep_setup_freeblocks_bp, &info);
1904         } while (count != 0);
1905         if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1906                 (void)free_inodedep(inodedep);
1907
1908         if (delay) {
1909                 freeblks->fb_state |= DEPCOMPLETE;
1910                 /*
1911                  * If the inode with zeroed block pointers is now on disk
1912                  * we can start freeing blocks. Add freeblks to the worklist
1913                  * instead of calling  handle_workitem_freeblocks directly as
1914                  * it is more likely that additional IO is needed to complete
1915                  * the request here than in the !delay case.
1916                  */
1917                 if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1918                         add_to_worklist(&freeblks->fb_list);
1919         }
1920
1921         FREE_LOCK(&lk);
1922         /*
1923          * If the inode has never been written to disk (delay == 0),
1924          * then we can process the freeblks now that we have deleted
1925          * the dependencies.
1926          */
1927         if (!delay)
1928                 handle_workitem_freeblocks(freeblks);
1929 }
1930
1931 static int
1932 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1933 {
1934         struct softdep_setup_freeblocks_info *info = data;
1935         struct inodedep *inodedep;
1936
1937         if (getdirtybuf(&bp, MNT_WAIT) == 0) {
1938                 kprintf("softdep_setup_freeblocks_bp(1): caught bp %p going away\n", bp);
1939                 return(-1);
1940         }
1941         if (bp->b_vp != ITOV(info->ip) || (bp->b_flags & B_DELWRI) == 0) {
1942                 kprintf("softdep_setup_freeblocks_bp(2): caught bp %p going away\n", bp);
1943                 BUF_UNLOCK(bp);
1944                 return(-1);
1945         }
1946         (void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1947         deallocate_dependencies(bp, inodedep);
1948         bp->b_flags |= B_INVAL | B_NOCACHE;
1949         FREE_LOCK(&lk);
1950         brelse(bp);
1951         ACQUIRE_LOCK(&lk);
1952         return(1);
1953 }
1954
1955 /*
1956  * Reclaim any dependency structures from a buffer that is about to
1957  * be reallocated to a new vnode. The buffer must be locked, thus,
1958  * no I/O completion operations can occur while we are manipulating
1959  * its associated dependencies. The mutex is held so that other I/O's
1960  * associated with related dependencies do not occur.
1961  */
1962 static void
1963 deallocate_dependencies(struct buf *bp, struct inodedep *inodedep)
1964 {
1965         struct worklist *wk;
1966         struct indirdep *indirdep;
1967         struct allocindir *aip;
1968         struct pagedep *pagedep;
1969         struct dirrem *dirrem;
1970         struct diradd *dap;
1971         int i;
1972
1973         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1974                 switch (wk->wk_type) {
1975
1976                 case D_INDIRDEP:
1977                         indirdep = WK_INDIRDEP(wk);
1978                         /*
1979                          * None of the indirect pointers will ever be visible,
1980                          * so they can simply be tossed. GOINGAWAY ensures
1981                          * that allocated pointers will be saved in the buffer
1982                          * cache until they are freed. Note that they will
1983                          * only be able to be found by their physical address
1984                          * since the inode mapping the logical address will
1985                          * be gone. The save buffer used for the safe copy
1986                          * was allocated in setup_allocindir_phase2 using
1987                          * the physical address so it could be used for this
1988                          * purpose. Hence we swap the safe copy with the real
1989                          * copy, allowing the safe copy to be freed and holding
1990                          * on to the real copy for later use in indir_trunc.
1991                          *
1992                          * NOTE: ir_savebp is relative to the block device
1993                          * so b_bio1 contains the device block number.
1994                          */
1995                         if (indirdep->ir_state & GOINGAWAY) {
1996                                 FREE_LOCK(&lk);
1997                                 panic("deallocate_dependencies: already gone");
1998                         }
1999                         indirdep->ir_state |= GOINGAWAY;
2000                         while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
2001                                 free_allocindir(aip, inodedep);
2002                         if (bp->b_bio1.bio_offset >= 0 ||
2003                             bp->b_bio2.bio_offset != indirdep->ir_savebp->b_bio1.bio_offset) {
2004                                 FREE_LOCK(&lk);
2005                                 panic("deallocate_dependencies: not indir");
2006                         }
2007                         bcopy(bp->b_data, indirdep->ir_savebp->b_data,
2008                             bp->b_bcount);
2009                         WORKLIST_REMOVE(wk);
2010                         WORKLIST_INSERT_BP(indirdep->ir_savebp, wk);
2011                         continue;
2012
2013                 case D_PAGEDEP:
2014                         pagedep = WK_PAGEDEP(wk);
2015                         /*
2016                          * None of the directory additions will ever be
2017                          * visible, so they can simply be tossed.
2018                          */
2019                         for (i = 0; i < DAHASHSZ; i++)
2020                                 while ((dap =
2021                                     LIST_FIRST(&pagedep->pd_diraddhd[i])))
2022                                         free_diradd(dap);
2023                         while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != 0)
2024                                 free_diradd(dap);
2025                         /*
2026                          * Copy any directory remove dependencies to the list
2027                          * to be processed after the zero'ed inode is written.
2028                          * If the inode has already been written, then they 
2029                          * can be dumped directly onto the work list.
2030                          */
2031                         LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
2032                                 LIST_REMOVE(dirrem, dm_next);
2033                                 dirrem->dm_dirinum = pagedep->pd_ino;
2034                                 if (inodedep == NULL ||
2035                                     (inodedep->id_state & ALLCOMPLETE) ==
2036                                      ALLCOMPLETE)
2037                                         add_to_worklist(&dirrem->dm_list);
2038                                 else
2039                                         WORKLIST_INSERT(&inodedep->id_bufwait,
2040                                             &dirrem->dm_list);
2041                         }
2042                         WORKLIST_REMOVE(&pagedep->pd_list);
2043                         LIST_REMOVE(pagedep, pd_hash);
2044                         WORKITEM_FREE(pagedep, D_PAGEDEP);
2045                         continue;
2046
2047                 case D_ALLOCINDIR:
2048                         free_allocindir(WK_ALLOCINDIR(wk), inodedep);
2049                         continue;
2050
2051                 case D_ALLOCDIRECT:
2052                 case D_INODEDEP:
2053                         FREE_LOCK(&lk);
2054                         panic("deallocate_dependencies: Unexpected type %s",
2055                             TYPENAME(wk->wk_type));
2056                         /* NOTREACHED */
2057
2058                 default:
2059                         FREE_LOCK(&lk);
2060                         panic("deallocate_dependencies: Unknown type %s",
2061                             TYPENAME(wk->wk_type));
2062                         /* NOTREACHED */
2063                 }
2064         }
2065 }
2066
2067 /*
2068  * Free an allocdirect. Generate a new freefrag work request if appropriate.
2069  * This routine must be called with splbio interrupts blocked.
2070  */
2071 static void
2072 free_allocdirect(struct allocdirectlst *adphead,
2073                  struct allocdirect *adp, int delay)
2074 {
2075
2076 #ifdef DEBUG
2077         if (lk.lkt_held == NOHOLDER)
2078                 panic("free_allocdirect: lock not held");
2079 #endif
2080         if ((adp->ad_state & DEPCOMPLETE) == 0)
2081                 LIST_REMOVE(adp, ad_deps);
2082         TAILQ_REMOVE(adphead, adp, ad_next);
2083         if ((adp->ad_state & COMPLETE) == 0)
2084                 WORKLIST_REMOVE(&adp->ad_list);
2085         if (adp->ad_freefrag != NULL) {
2086                 if (delay)
2087                         WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2088                             &adp->ad_freefrag->ff_list);
2089                 else
2090                         add_to_worklist(&adp->ad_freefrag->ff_list);
2091         }
2092         WORKITEM_FREE(adp, D_ALLOCDIRECT);
2093 }
2094
2095 /*
2096  * Prepare an inode to be freed. The actual free operation is not
2097  * done until the zero'ed inode has been written to disk.
2098  */
2099 void
2100 softdep_freefile(struct vnode *pvp, ino_t ino, int mode)
2101 {
2102         struct inode *ip = VTOI(pvp);
2103         struct inodedep *inodedep;
2104         struct freefile *freefile;
2105
2106         /*
2107          * This sets up the inode de-allocation dependency.
2108          */
2109         MALLOC(freefile, struct freefile *, sizeof(struct freefile),
2110                 M_FREEFILE, M_SOFTDEP_FLAGS);
2111         freefile->fx_list.wk_type = D_FREEFILE;
2112         freefile->fx_list.wk_state = 0;
2113         freefile->fx_mode = mode;
2114         freefile->fx_oldinum = ino;
2115         freefile->fx_devvp = ip->i_devvp;
2116         freefile->fx_fs = ip->i_fs;
2117
2118         /*
2119          * If the inodedep does not exist, then the zero'ed inode has
2120          * been written to disk. If the allocated inode has never been
2121          * written to disk, then the on-disk inode is zero'ed. In either
2122          * case we can free the file immediately.
2123          */
2124         ACQUIRE_LOCK(&lk);
2125         if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2126             check_inode_unwritten(inodedep)) {
2127                 FREE_LOCK(&lk);
2128                 handle_workitem_freefile(freefile);
2129                 return;
2130         }
2131         WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2132         FREE_LOCK(&lk);
2133 }
2134
2135 /*
2136  * Check to see if an inode has never been written to disk. If
2137  * so free the inodedep and return success, otherwise return failure.
2138  * This routine must be called with splbio interrupts blocked.
2139  *
2140  * If we still have a bitmap dependency, then the inode has never
2141  * been written to disk. Drop the dependency as it is no longer
2142  * necessary since the inode is being deallocated. We set the
2143  * ALLCOMPLETE flags since the bitmap now properly shows that the
2144  * inode is not allocated. Even if the inode is actively being
2145  * written, it has been rolled back to its zero'ed state, so we
2146  * are ensured that a zero inode is what is on the disk. For short
2147  * lived files, this change will usually result in removing all the
2148  * dependencies from the inode so that it can be freed immediately.
2149  */
2150 static int
2151 check_inode_unwritten(struct inodedep *inodedep)
2152 {
2153
2154         if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2155             LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2156             LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2157             LIST_FIRST(&inodedep->id_inowait) != NULL ||
2158             TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2159             TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2160             inodedep->id_nlinkdelta != 0)
2161                 return (0);
2162
2163         /*
2164          * Another process might be in initiate_write_inodeblock
2165          * trying to allocate memory without holding "Softdep Lock".
2166          */
2167         if ((inodedep->id_state & IOSTARTED) != 0 &&
2168             inodedep->id_savedino == NULL)
2169                 return(0);
2170
2171         inodedep->id_state |= ALLCOMPLETE;
2172         LIST_REMOVE(inodedep, id_deps);
2173         inodedep->id_buf = NULL;
2174         if (inodedep->id_state & ONWORKLIST)
2175                 WORKLIST_REMOVE(&inodedep->id_list);
2176         if (inodedep->id_savedino != NULL) {
2177                 FREE(inodedep->id_savedino, M_INODEDEP);
2178                 inodedep->id_savedino = NULL;
2179         }
2180         if (free_inodedep(inodedep) == 0) {
2181                 FREE_LOCK(&lk);
2182                 panic("check_inode_unwritten: busy inode");
2183         }
2184         return (1);
2185 }
2186
2187 /*
2188  * Try to free an inodedep structure. Return 1 if it could be freed.
2189  */
2190 static int
2191 free_inodedep(struct inodedep *inodedep)
2192 {
2193
2194         if ((inodedep->id_state & ONWORKLIST) != 0 ||
2195             (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2196             LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2197             LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2198             LIST_FIRST(&inodedep->id_inowait) != NULL ||
2199             TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2200             TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2201             inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2202                 return (0);
2203         LIST_REMOVE(inodedep, id_hash);
2204         WORKITEM_FREE(inodedep, D_INODEDEP);
2205         num_inodedep -= 1;
2206         return (1);
2207 }
2208
2209 /*
2210  * This workitem routine performs the block de-allocation.
2211  * The workitem is added to the pending list after the updated
2212  * inode block has been written to disk.  As mentioned above,
2213  * checks regarding the number of blocks de-allocated (compared
2214  * to the number of blocks allocated for the file) are also
2215  * performed in this function.
2216  */
2217 static void
2218 handle_workitem_freeblocks(struct freeblks *freeblks)
2219 {
2220         struct inode tip;
2221         ufs_daddr_t bn;
2222         struct fs *fs;
2223         int i, level, bsize;
2224         long nblocks, blocksreleased = 0;
2225         int error, allerror = 0;
2226         ufs_lbn_t baselbns[NIADDR], tmpval;
2227
2228         tip.i_number = freeblks->fb_previousinum;
2229         tip.i_devvp = freeblks->fb_devvp;
2230         tip.i_dev = freeblks->fb_devvp->v_rdev;
2231         tip.i_fs = freeblks->fb_fs;
2232         tip.i_size = freeblks->fb_oldsize;
2233         tip.i_uid = freeblks->fb_uid;
2234         fs = freeblks->fb_fs;
2235         tmpval = 1;
2236         baselbns[0] = NDADDR;
2237         for (i = 1; i < NIADDR; i++) {
2238                 tmpval *= NINDIR(fs);
2239                 baselbns[i] = baselbns[i - 1] + tmpval;
2240         }
2241         nblocks = btodb(fs->fs_bsize);
2242         blocksreleased = 0;
2243         /*
2244          * Indirect blocks first.
2245          */
2246         for (level = (NIADDR - 1); level >= 0; level--) {
2247                 if ((bn = freeblks->fb_iblks[level]) == 0)
2248                         continue;
2249                 if ((error = indir_trunc(&tip, fsbtodoff(fs, bn), level,
2250                     baselbns[level], &blocksreleased)) == 0)
2251                         allerror = error;
2252                 ffs_blkfree(&tip, bn, fs->fs_bsize);
2253                 blocksreleased += nblocks;
2254         }
2255         /*
2256          * All direct blocks or frags.
2257          */
2258         for (i = (NDADDR - 1); i >= 0; i--) {
2259                 if ((bn = freeblks->fb_dblks[i]) == 0)
2260                         continue;
2261                 bsize = blksize(fs, &tip, i);
2262                 ffs_blkfree(&tip, bn, bsize);
2263                 blocksreleased += btodb(bsize);
2264         }
2265
2266 #ifdef DIAGNOSTIC
2267         if (freeblks->fb_chkcnt != blocksreleased)
2268                 kprintf("handle_workitem_freeblocks: block count\n");
2269         if (allerror)
2270                 softdep_error("handle_workitem_freeblks", allerror);
2271 #endif /* DIAGNOSTIC */
2272         WORKITEM_FREE(freeblks, D_FREEBLKS);
2273 }
2274
2275 /*
2276  * Release blocks associated with the inode ip and stored in the indirect
2277  * block at doffset. If level is greater than SINGLE, the block is an
2278  * indirect block and recursive calls to indirtrunc must be used to
2279  * cleanse other indirect blocks.
2280  */
2281 static int
2282 indir_trunc(struct inode *ip, off_t doffset, int level, ufs_lbn_t lbn,
2283             long *countp)
2284 {
2285         struct buf *bp;
2286         ufs_daddr_t *bap;
2287         ufs_daddr_t nb;
2288         struct fs *fs;
2289         struct worklist *wk;
2290         struct indirdep *indirdep;
2291         int i, lbnadd, nblocks;
2292         int error, allerror = 0;
2293
2294         fs = ip->i_fs;
2295         lbnadd = 1;
2296         for (i = level; i > 0; i--)
2297                 lbnadd *= NINDIR(fs);
2298         /*
2299          * Get buffer of block pointers to be freed. This routine is not
2300          * called until the zero'ed inode has been written, so it is safe
2301          * to free blocks as they are encountered. Because the inode has
2302          * been zero'ed, calls to bmap on these blocks will fail. So, we
2303          * have to use the on-disk address and the block device for the
2304          * filesystem to look them up. If the file was deleted before its
2305          * indirect blocks were all written to disk, the routine that set
2306          * us up (deallocate_dependencies) will have arranged to leave
2307          * a complete copy of the indirect block in memory for our use.
2308          * Otherwise we have to read the blocks in from the disk.
2309          */
2310         ACQUIRE_LOCK(&lk);
2311         if ((bp = findblk(ip->i_devvp, doffset)) != NULL &&
2312             (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2313                 /*
2314                  * bp must be ir_savebp, which is held locked for our use.
2315                  */
2316                 if (wk->wk_type != D_INDIRDEP ||
2317                     (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2318                     (indirdep->ir_state & GOINGAWAY) == 0) {
2319                         FREE_LOCK(&lk);
2320                         panic("indir_trunc: lost indirdep");
2321                 }
2322                 WORKLIST_REMOVE(wk);
2323                 WORKITEM_FREE(indirdep, D_INDIRDEP);
2324                 if (LIST_FIRST(&bp->b_dep) != NULL) {
2325                         FREE_LOCK(&lk);
2326                         panic("indir_trunc: dangling dep");
2327                 }
2328                 FREE_LOCK(&lk);
2329         } else {
2330                 FREE_LOCK(&lk);
2331                 error = bread(ip->i_devvp, doffset, (int)fs->fs_bsize, &bp);
2332                 if (error)
2333                         return (error);
2334         }
2335         /*
2336          * Recursively free indirect blocks.
2337          */
2338         bap = (ufs_daddr_t *)bp->b_data;
2339         nblocks = btodb(fs->fs_bsize);
2340         for (i = NINDIR(fs) - 1; i >= 0; i--) {
2341                 if ((nb = bap[i]) == 0)
2342                         continue;
2343                 if (level != 0) {
2344                         if ((error = indir_trunc(ip, fsbtodoff(fs, nb),
2345                              level - 1, lbn + (i * lbnadd), countp)) != 0)
2346                                 allerror = error;
2347                 }
2348                 ffs_blkfree(ip, nb, fs->fs_bsize);
2349                 *countp += nblocks;
2350         }
2351         bp->b_flags |= B_INVAL | B_NOCACHE;
2352         brelse(bp);
2353         return (allerror);
2354 }
2355
2356 /*
2357  * Free an allocindir.
2358  * This routine must be called with splbio interrupts blocked.
2359  */
2360 static void
2361 free_allocindir(struct allocindir *aip, struct inodedep *inodedep)
2362 {
2363         struct freefrag *freefrag;
2364
2365 #ifdef DEBUG
2366         if (lk.lkt_held == NOHOLDER)
2367                 panic("free_allocindir: lock not held");
2368 #endif
2369         if ((aip->ai_state & DEPCOMPLETE) == 0)
2370                 LIST_REMOVE(aip, ai_deps);
2371         if (aip->ai_state & ONWORKLIST)
2372                 WORKLIST_REMOVE(&aip->ai_list);
2373         LIST_REMOVE(aip, ai_next);
2374         if ((freefrag = aip->ai_freefrag) != NULL) {
2375                 if (inodedep == NULL)
2376                         add_to_worklist(&freefrag->ff_list);
2377                 else
2378                         WORKLIST_INSERT(&inodedep->id_bufwait,
2379                             &freefrag->ff_list);
2380         }
2381         WORKITEM_FREE(aip, D_ALLOCINDIR);
2382 }
2383
2384 /*
2385  * Directory entry addition dependencies.
2386  * 
2387  * When adding a new directory entry, the inode (with its incremented link
2388  * count) must be written to disk before the directory entry's pointer to it.
2389  * Also, if the inode is newly allocated, the corresponding freemap must be
2390  * updated (on disk) before the directory entry's pointer. These requirements
2391  * are met via undo/redo on the directory entry's pointer, which consists
2392  * simply of the inode number.
2393  * 
2394  * As directory entries are added and deleted, the free space within a
2395  * directory block can become fragmented.  The ufs filesystem will compact
2396  * a fragmented directory block to make space for a new entry. When this
2397  * occurs, the offsets of previously added entries change. Any "diradd"
2398  * dependency structures corresponding to these entries must be updated with
2399  * the new offsets.
2400  */
2401
2402 /*
2403  * This routine is called after the in-memory inode's link
2404  * count has been incremented, but before the directory entry's
2405  * pointer to the inode has been set.
2406  *
2407  * Parameters:
2408  *      bp:             buffer containing directory block
2409  *      dp:             inode for directory
2410  *      diroffset:      offset of new entry in directory
2411  *      newinum:        inode referenced by new directory entry
2412  *      newdirbp:       non-NULL => contents of new mkdir
2413  */
2414 void 
2415 softdep_setup_directory_add(struct buf *bp, struct inode *dp, off_t diroffset,
2416                             ino_t newinum, struct buf *newdirbp)
2417 {
2418         int offset;             /* offset of new entry within directory block */
2419         ufs_lbn_t lbn;          /* block in directory containing new entry */
2420         struct fs *fs;
2421         struct diradd *dap;
2422         struct pagedep *pagedep;
2423         struct inodedep *inodedep;
2424         struct mkdir *mkdir1, *mkdir2;
2425
2426         /*
2427          * Whiteouts have no dependencies.
2428          */
2429         if (newinum == WINO) {
2430                 if (newdirbp != NULL)
2431                         bdwrite(newdirbp);
2432                 return;
2433         }
2434
2435         fs = dp->i_fs;
2436         lbn = lblkno(fs, diroffset);
2437         offset = blkoff(fs, diroffset);
2438         MALLOC(dap, struct diradd *, sizeof(struct diradd), M_DIRADD,
2439             M_SOFTDEP_FLAGS);
2440         bzero(dap, sizeof(struct diradd));
2441         dap->da_list.wk_type = D_DIRADD;
2442         dap->da_offset = offset;
2443         dap->da_newinum = newinum;
2444         dap->da_state = ATTACHED;
2445         if (newdirbp == NULL) {
2446                 dap->da_state |= DEPCOMPLETE;
2447                 ACQUIRE_LOCK(&lk);
2448         } else {
2449                 dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2450                 MALLOC(mkdir1, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2451                     M_SOFTDEP_FLAGS);
2452                 mkdir1->md_list.wk_type = D_MKDIR;
2453                 mkdir1->md_state = MKDIR_BODY;
2454                 mkdir1->md_diradd = dap;
2455                 MALLOC(mkdir2, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2456                     M_SOFTDEP_FLAGS);
2457                 mkdir2->md_list.wk_type = D_MKDIR;
2458                 mkdir2->md_state = MKDIR_PARENT;
2459                 mkdir2->md_diradd = dap;
2460                 /*
2461                  * Dependency on "." and ".." being written to disk.
2462                  */
2463                 mkdir1->md_buf = newdirbp;
2464                 ACQUIRE_LOCK(&lk);
2465                 LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2466                 WORKLIST_INSERT_BP(newdirbp, &mkdir1->md_list);
2467                 FREE_LOCK(&lk);
2468                 bdwrite(newdirbp);
2469                 /*
2470                  * Dependency on link count increase for parent directory
2471                  */
2472                 ACQUIRE_LOCK(&lk);
2473                 if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2474                     || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2475                         dap->da_state &= ~MKDIR_PARENT;
2476                         WORKITEM_FREE(mkdir2, D_MKDIR);
2477                 } else {
2478                         LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2479                         WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2480                 }
2481         }
2482         /*
2483          * Link into parent directory pagedep to await its being written.
2484          */
2485         if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2486                 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2487         dap->da_pagedep = pagedep;
2488         LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2489             da_pdlist);
2490         /*
2491          * Link into its inodedep. Put it on the id_bufwait list if the inode
2492          * is not yet written. If it is written, do the post-inode write
2493          * processing to put it on the id_pendinghd list.
2494          */
2495         (void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2496         if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2497                 diradd_inode_written(dap, inodedep);
2498         else
2499                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2500         FREE_LOCK(&lk);
2501 }
2502
2503 /*
2504  * This procedure is called to change the offset of a directory
2505  * entry when compacting a directory block which must be owned
2506  * exclusively by the caller. Note that the actual entry movement
2507  * must be done in this procedure to ensure that no I/O completions
2508  * occur while the move is in progress.
2509  *
2510  * Parameters:
2511  *      dp:     inode for directory
2512  *      base:           address of dp->i_offset
2513  *      oldloc:         address of old directory location
2514  *      newloc:         address of new directory location
2515  *      entrysize:      size of directory entry
2516  */
2517 void 
2518 softdep_change_directoryentry_offset(struct inode *dp, caddr_t base,
2519                                      caddr_t oldloc, caddr_t newloc,
2520                                      int entrysize)
2521 {
2522         int offset, oldoffset, newoffset;
2523         struct pagedep *pagedep;
2524         struct diradd *dap;
2525         ufs_lbn_t lbn;
2526
2527         ACQUIRE_LOCK(&lk);
2528         lbn = lblkno(dp->i_fs, dp->i_offset);
2529         offset = blkoff(dp->i_fs, dp->i_offset);
2530         if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2531                 goto done;
2532         oldoffset = offset + (oldloc - base);
2533         newoffset = offset + (newloc - base);
2534
2535         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2536                 if (dap->da_offset != oldoffset)
2537                         continue;
2538                 dap->da_offset = newoffset;
2539                 if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2540                         break;
2541                 LIST_REMOVE(dap, da_pdlist);
2542                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2543                     dap, da_pdlist);
2544                 break;
2545         }
2546         if (dap == NULL) {
2547
2548                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2549                         if (dap->da_offset == oldoffset) {
2550                                 dap->da_offset = newoffset;
2551                                 break;
2552                         }
2553                 }
2554         }
2555 done:
2556         bcopy(oldloc, newloc, entrysize);
2557         FREE_LOCK(&lk);
2558 }
2559
2560 /*
2561  * Free a diradd dependency structure. This routine must be called
2562  * with splbio interrupts blocked.
2563  */
2564 static void
2565 free_diradd(struct diradd *dap)
2566 {
2567         struct dirrem *dirrem;
2568         struct pagedep *pagedep;
2569         struct inodedep *inodedep;
2570         struct mkdir *mkdir, *nextmd;
2571
2572 #ifdef DEBUG
2573         if (lk.lkt_held == NOHOLDER)
2574                 panic("free_diradd: lock not held");
2575 #endif
2576         WORKLIST_REMOVE(&dap->da_list);
2577         LIST_REMOVE(dap, da_pdlist);
2578         if ((dap->da_state & DIRCHG) == 0) {
2579                 pagedep = dap->da_pagedep;
2580         } else {
2581                 dirrem = dap->da_previous;
2582                 pagedep = dirrem->dm_pagedep;
2583                 dirrem->dm_dirinum = pagedep->pd_ino;
2584                 add_to_worklist(&dirrem->dm_list);
2585         }
2586         if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2587             0, &inodedep) != 0)
2588                 (void) free_inodedep(inodedep);
2589         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2590                 for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2591                         nextmd = LIST_NEXT(mkdir, md_mkdirs);
2592                         if (mkdir->md_diradd != dap)
2593                                 continue;
2594                         dap->da_state &= ~mkdir->md_state;
2595                         WORKLIST_REMOVE(&mkdir->md_list);
2596                         LIST_REMOVE(mkdir, md_mkdirs);
2597                         WORKITEM_FREE(mkdir, D_MKDIR);
2598                 }
2599                 if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2600                         FREE_LOCK(&lk);
2601                         panic("free_diradd: unfound ref");
2602                 }
2603         }
2604         WORKITEM_FREE(dap, D_DIRADD);
2605 }
2606
2607 /*
2608  * Directory entry removal dependencies.
2609  * 
2610  * When removing a directory entry, the entry's inode pointer must be
2611  * zero'ed on disk before the corresponding inode's link count is decremented
2612  * (possibly freeing the inode for re-use). This dependency is handled by
2613  * updating the directory entry but delaying the inode count reduction until
2614  * after the directory block has been written to disk. After this point, the
2615  * inode count can be decremented whenever it is convenient.
2616  */
2617
2618 /*
2619  * This routine should be called immediately after removing
2620  * a directory entry.  The inode's link count should not be
2621  * decremented by the calling procedure -- the soft updates
2622  * code will do this task when it is safe.
2623  *
2624  * Parameters:
2625  *      bp:             buffer containing directory block
2626  *      dp:             inode for the directory being modified
2627  *      ip:             inode for directory entry being removed
2628  *      isrmdir:        indicates if doing RMDIR
2629  */
2630 void 
2631 softdep_setup_remove(struct buf *bp, struct inode *dp, struct inode *ip,
2632                      int isrmdir)
2633 {
2634         struct dirrem *dirrem, *prevdirrem;
2635
2636         /*
2637          * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2638          */
2639         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2640
2641         /*
2642          * If the COMPLETE flag is clear, then there were no active
2643          * entries and we want to roll back to a zeroed entry until
2644          * the new inode is committed to disk. If the COMPLETE flag is
2645          * set then we have deleted an entry that never made it to
2646          * disk. If the entry we deleted resulted from a name change,
2647          * then the old name still resides on disk. We cannot delete
2648          * its inode (returned to us in prevdirrem) until the zeroed
2649          * directory entry gets to disk. The new inode has never been
2650          * referenced on the disk, so can be deleted immediately.
2651          */
2652         if ((dirrem->dm_state & COMPLETE) == 0) {
2653                 LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2654                     dm_next);
2655                 FREE_LOCK(&lk);
2656         } else {
2657                 if (prevdirrem != NULL)
2658                         LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2659                             prevdirrem, dm_next);
2660                 dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2661                 FREE_LOCK(&lk);
2662                 handle_workitem_remove(dirrem);
2663         }
2664 }
2665
2666 /*
2667  * Allocate a new dirrem if appropriate and return it along with
2668  * its associated pagedep. Called without a lock, returns with lock.
2669  */
2670 static long num_dirrem;         /* number of dirrem allocated */
2671
2672 /*
2673  * Parameters:
2674  *      bp:             buffer containing directory block
2675  *      dp:             inode for the directory being modified
2676  *      ip:             inode for directory entry being removed
2677  *      isrmdir:        indicates if doing RMDIR
2678  *      prevdirremp:    previously referenced inode, if any
2679  */
2680 static struct dirrem *
2681 newdirrem(struct buf *bp, struct inode *dp, struct inode *ip,
2682           int isrmdir, struct dirrem **prevdirremp)
2683 {
2684         int offset;
2685         ufs_lbn_t lbn;
2686         struct diradd *dap;
2687         struct dirrem *dirrem;
2688         struct pagedep *pagedep;
2689
2690         /*
2691          * Whiteouts have no deletion dependencies.
2692          */
2693         if (ip == NULL)
2694                 panic("newdirrem: whiteout");
2695         /*
2696          * If we are over our limit, try to improve the situation.
2697          * Limiting the number of dirrem structures will also limit
2698          * the number of freefile and freeblks structures.
2699          */
2700         if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2701                 (void) request_cleanup(FLUSH_REMOVE, 0);
2702         num_dirrem += 1;
2703         MALLOC(dirrem, struct dirrem *, sizeof(struct dirrem),
2704                 M_DIRREM, M_SOFTDEP_FLAGS);
2705         bzero(dirrem, sizeof(struct dirrem));
2706         dirrem->dm_list.wk_type = D_DIRREM;
2707         dirrem->dm_state = isrmdir ? RMDIR : 0;
2708         dirrem->dm_mnt = ITOV(ip)->v_mount;
2709         dirrem->dm_oldinum = ip->i_number;
2710         *prevdirremp = NULL;
2711
2712         ACQUIRE_LOCK(&lk);
2713         lbn = lblkno(dp->i_fs, dp->i_offset);
2714         offset = blkoff(dp->i_fs, dp->i_offset);
2715         if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2716                 WORKLIST_INSERT_BP(bp, &pagedep->pd_list);
2717         dirrem->dm_pagedep = pagedep;
2718         /*
2719          * Check for a diradd dependency for the same directory entry.
2720          * If present, then both dependencies become obsolete and can
2721          * be de-allocated. Check for an entry on both the pd_dirraddhd
2722          * list and the pd_pendinghd list.
2723          */
2724
2725         LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2726                 if (dap->da_offset == offset)
2727                         break;
2728         if (dap == NULL) {
2729
2730                 LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2731                         if (dap->da_offset == offset)
2732                                 break;
2733                 if (dap == NULL)
2734                         return (dirrem);
2735         }
2736         /*
2737          * Must be ATTACHED at this point.
2738          */
2739         if ((dap->da_state & ATTACHED) == 0) {
2740                 FREE_LOCK(&lk);
2741                 panic("newdirrem: not ATTACHED");
2742         }
2743         if (dap->da_newinum != ip->i_number) {
2744                 FREE_LOCK(&lk);
2745                 panic("newdirrem: inum %"PRId64" should be %"PRId64,
2746                     ip->i_number, dap->da_newinum);
2747         }
2748         /*
2749          * If we are deleting a changed name that never made it to disk,
2750          * then return the dirrem describing the previous inode (which
2751          * represents the inode currently referenced from this entry on disk).
2752          */
2753         if ((dap->da_state & DIRCHG) != 0) {
2754                 *prevdirremp = dap->da_previous;
2755                 dap->da_state &= ~DIRCHG;
2756                 dap->da_pagedep = pagedep;
2757         }
2758         /*
2759          * We are deleting an entry that never made it to disk.
2760          * Mark it COMPLETE so we can delete its inode immediately.
2761          */
2762         dirrem->dm_state |= COMPLETE;
2763         free_diradd(dap);
2764         return (dirrem);
2765 }
2766
2767 /*
2768  * Directory entry change dependencies.
2769  * 
2770  * Changing an existing directory entry requires that an add operation
2771  * be completed first followed by a deletion. The semantics for the addition
2772  * are identical to the description of adding a new entry above except
2773  * that the rollback is to the old inode number rather than zero. Once
2774  * the addition dependency is completed, the removal is done as described
2775  * in the removal routine above.
2776  */
2777
2778 /*
2779  * This routine should be called immediately after changing
2780  * a directory entry.  The inode's link count should not be
2781  * decremented by the calling procedure -- the soft updates
2782  * code will perform this task when it is safe.
2783  *
2784  * Parameters:
2785  *      bp:             buffer containing directory block
2786  *      dp:             inode for the directory being modified
2787  *      ip:             inode for directory entry being removed
2788  *      newinum:        new inode number for changed entry
2789  *      isrmdir:        indicates if doing RMDIR
2790  */
2791 void 
2792 softdep_setup_directory_change(struct buf *bp, struct inode *dp,
2793                                struct inode *ip, ino_t newinum,
2794                                int isrmdir)
2795 {
2796         int offset;
2797         struct diradd *dap = NULL;
2798         struct dirrem *dirrem, *prevdirrem;
2799         struct pagedep *pagedep;
2800         struct inodedep *inodedep;
2801
2802         offset = blkoff(dp->i_fs, dp->i_offset);
2803
2804         /*
2805          * Whiteouts do not need diradd dependencies.
2806          */
2807         if (newinum != WINO) {
2808                 MALLOC(dap, struct diradd *, sizeof(struct diradd),
2809                     M_DIRADD, M_SOFTDEP_FLAGS);
2810                 bzero(dap, sizeof(struct diradd));
2811                 dap->da_list.wk_type = D_DIRADD;
2812                 dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2813                 dap->da_offset = offset;
2814                 dap->da_newinum = newinum;
2815         }
2816
2817         /*
2818          * Allocate a new dirrem and ACQUIRE_LOCK.
2819          */
2820         dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2821         pagedep = dirrem->dm_pagedep;
2822         /*
2823          * The possible values for isrmdir:
2824          *      0 - non-directory file rename
2825          *      1 - directory rename within same directory
2826          *   inum - directory rename to new directory of given inode number
2827          * When renaming to a new directory, we are both deleting and
2828          * creating a new directory entry, so the link count on the new
2829          * directory should not change. Thus we do not need the followup
2830          * dirrem which is usually done in handle_workitem_remove. We set
2831          * the DIRCHG flag to tell handle_workitem_remove to skip the 
2832          * followup dirrem.
2833          */
2834         if (isrmdir > 1)
2835                 dirrem->dm_state |= DIRCHG;
2836
2837         /*
2838          * Whiteouts have no additional dependencies,
2839          * so just put the dirrem on the correct list.
2840          */
2841         if (newinum == WINO) {
2842                 if ((dirrem->dm_state & COMPLETE) == 0) {
2843                         LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2844                             dm_next);
2845                 } else {
2846                         dirrem->dm_dirinum = pagedep->pd_ino;
2847                         add_to_worklist(&dirrem->dm_list);
2848                 }
2849                 FREE_LOCK(&lk);
2850                 return;
2851         }
2852
2853         /*
2854          * If the COMPLETE flag is clear, then there were no active
2855          * entries and we want to roll back to the previous inode until
2856          * the new inode is committed to disk. If the COMPLETE flag is
2857          * set, then we have deleted an entry that never made it to disk.
2858          * If the entry we deleted resulted from a name change, then the old
2859          * inode reference still resides on disk. Any rollback that we do
2860          * needs to be to that old inode (returned to us in prevdirrem). If
2861          * the entry we deleted resulted from a create, then there is
2862          * no entry on the disk, so we want to roll back to zero rather
2863          * than the uncommitted inode. In either of the COMPLETE cases we
2864          * want to immediately free the unwritten and unreferenced inode.
2865          */
2866         if ((dirrem->dm_state & COMPLETE) == 0) {
2867                 dap->da_previous = dirrem;
2868         } else {
2869                 if (prevdirrem != NULL) {
2870                         dap->da_previous = prevdirrem;
2871                 } else {
2872                         dap->da_state &= ~DIRCHG;
2873                         dap->da_pagedep = pagedep;
2874                 }
2875                 dirrem->dm_dirinum = pagedep->pd_ino;
2876                 add_to_worklist(&dirrem->dm_list);
2877         }
2878         /*
2879          * Link into its inodedep. Put it on the id_bufwait list if the inode
2880          * is not yet written. If it is written, do the post-inode write
2881          * processing to put it on the id_pendinghd list.
2882          */
2883         if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2884             (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2885                 dap->da_state |= COMPLETE;
2886                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2887                 WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2888         } else {
2889                 LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2890                     dap, da_pdlist);
2891                 WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2892         }
2893         FREE_LOCK(&lk);
2894 }
2895
2896 /*
2897  * Called whenever the link count on an inode is changed.
2898  * It creates an inode dependency so that the new reference(s)
2899  * to the inode cannot be committed to disk until the updated
2900  * inode has been written.
2901  *
2902  * Parameters:
2903  *      ip:     the inode with the increased link count
2904  */
2905 void
2906 softdep_change_linkcnt(struct inode *ip)
2907 {
2908         struct inodedep *inodedep;
2909
2910         ACQUIRE_LOCK(&lk);
2911         (void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2912         if (ip->i_nlink < ip->i_effnlink) {
2913                 FREE_LOCK(&lk);
2914                 panic("softdep_change_linkcnt: bad delta");
2915         }
2916         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2917         FREE_LOCK(&lk);
2918 }
2919
2920 /*
2921  * This workitem decrements the inode's link count.
2922  * If the link count reaches zero, the file is removed.
2923  */
2924 static void 
2925 handle_workitem_remove(struct dirrem *dirrem)
2926 {
2927         struct inodedep *inodedep;
2928         struct vnode *vp;
2929         struct inode *ip;
2930         ino_t oldinum;
2931         int error;
2932
2933         if ((error = VFS_VGET(dirrem->dm_mnt, dirrem->dm_oldinum, &vp)) != 0) {
2934                 softdep_error("handle_workitem_remove: vget", error);
2935                 return;
2936         }
2937         ip = VTOI(vp);
2938         ACQUIRE_LOCK(&lk);
2939         if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2940                 FREE_LOCK(&lk);
2941                 panic("handle_workitem_remove: lost inodedep");
2942         }
2943         /*
2944          * Normal file deletion.
2945          */
2946         if ((dirrem->dm_state & RMDIR) == 0) {
2947                 ip->i_nlink--;
2948                 ip->i_flag |= IN_CHANGE;
2949                 if (ip->i_nlink < ip->i_effnlink) {
2950                         FREE_LOCK(&lk);
2951                         panic("handle_workitem_remove: bad file delta");
2952                 }
2953                 inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2954                 FREE_LOCK(&lk);
2955                 vput(vp);
2956                 num_dirrem -= 1;
2957                 WORKITEM_FREE(dirrem, D_DIRREM);
2958                 return;
2959         }
2960         /*
2961          * Directory deletion. Decrement reference count for both the
2962          * just deleted parent directory entry and the reference for ".".
2963          * Next truncate the directory to length zero. When the
2964          * truncation completes, arrange to have the reference count on
2965          * the parent decremented to account for the loss of "..".
2966          */
2967         ip->i_nlink -= 2;
2968         ip->i_flag |= IN_CHANGE;
2969         if (ip->i_nlink < ip->i_effnlink) {
2970                 FREE_LOCK(&lk);
2971                 panic("handle_workitem_remove: bad dir delta");
2972         }
2973         inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2974         FREE_LOCK(&lk);
2975         if ((error = ffs_truncate(vp, (off_t)0, 0, proc0.p_ucred)) != 0)
2976                 softdep_error("handle_workitem_remove: truncate", error);
2977         /*
2978          * Rename a directory to a new parent. Since, we are both deleting
2979          * and creating a new directory entry, the link count on the new
2980          * directory should not change. Thus we skip the followup dirrem.
2981          */
2982         if (dirrem->dm_state & DIRCHG) {
2983                 vput(vp);
2984                 num_dirrem -= 1;
2985                 WORKITEM_FREE(dirrem, D_DIRREM);
2986                 return;
2987         }
2988         /*
2989          * If the inodedep does not exist, then the zero'ed inode has
2990          * been written to disk. If the allocated inode has never been
2991          * written to disk, then the on-disk inode is zero'ed. In either
2992          * case we can remove the file immediately.
2993          */
2994         ACQUIRE_LOCK(&lk);
2995         dirrem->dm_state = 0;
2996         oldinum = dirrem->dm_oldinum;
2997         dirrem->dm_oldinum = dirrem->dm_dirinum;
2998         if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2999             check_inode_unwritten(inodedep)) {
3000                 FREE_LOCK(&lk);
3001                 vput(vp);
3002                 handle_workitem_remove(dirrem);
3003                 return;
3004         }
3005         WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
3006         FREE_LOCK(&lk);
3007         ip->i_flag |= IN_CHANGE;
3008         ffs_update(vp, 0);
3009         vput(vp);
3010 }
3011
3012 /*
3013  * Inode de-allocation dependencies.
3014  * 
3015  * When an inode's link count is reduced to zero, it can be de-allocated. We
3016  * found it convenient to postpone de-allocation until after the inode is
3017  * written to disk with its new link count (zero).  At this point, all of the
3018  * on-disk inode's block pointers are nullified and, with careful dependency
3019  * list ordering, all dependencies related to the inode will be satisfied and
3020  * the corresponding dependency structures de-allocated.  So, if/when the
3021  * inode is reused, there will be no mixing of old dependencies with new
3022  * ones.  This artificial dependency is set up by the block de-allocation
3023  * procedure above (softdep_setup_freeblocks) and completed by the
3024  * following procedure.
3025  */
3026 static void 
3027 handle_workitem_freefile(struct freefile *freefile)
3028 {
3029         struct vnode vp;
3030         struct inode tip;
3031         struct inodedep *idp;
3032         int error;
3033
3034 #ifdef DEBUG
3035         ACQUIRE_LOCK(&lk);
3036         error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
3037         FREE_LOCK(&lk);
3038         if (error)
3039                 panic("handle_workitem_freefile: inodedep survived");
3040 #endif
3041         tip.i_devvp = freefile->fx_devvp;
3042         tip.i_dev = freefile->fx_devvp->v_rdev;
3043         tip.i_fs = freefile->fx_fs;
3044         vp.v_data = &tip;
3045         if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
3046                 softdep_error("handle_workitem_freefile", error);
3047         WORKITEM_FREE(freefile, D_FREEFILE);
3048 }
3049
3050 /*
3051  * Helper function which unlinks marker element from work list and returns
3052  * the next element on the list.
3053  */
3054 static __inline struct worklist *
3055 markernext(struct worklist *marker)
3056 {
3057         struct worklist *next;
3058
3059         next = LIST_NEXT(marker, wk_list);
3060         LIST_REMOVE(marker, wk_list);
3061         return next;
3062 }
3063
3064 /*
3065  * Disk writes.
3066  * 
3067  * The dependency structures constructed above are most actively used when file
3068  * system blocks are written to disk.  No constraints are placed on when a
3069  * block can be written, but unsatisfied update dependencies are made safe by
3070  * modifying (or replacing) the source memory for the duration of the disk
3071  * write.  When the disk write completes, the memory block is again brought
3072  * up-to-date.
3073  *
3074  * In-core inode structure reclamation.
3075  * 
3076  * Because there are a finite number of "in-core" inode structures, they are
3077  * reused regularly.  By transferring all inode-related dependencies to the
3078  * in-memory inode block and indexing them separately (via "inodedep"s), we
3079  * can allow "in-core" inode structures to be reused at any time and avoid
3080  * any increase in contention.
3081  *
3082  * Called just before entering the device driver to initiate a new disk I/O.
3083  * The buffer must be locked, thus, no I/O completion operations can occur
3084  * while we are manipulating its associated dependencies.
3085  *
3086  * Parameters:
3087  *      bp:     structure describing disk write to occur
3088  */
3089 static void 
3090 softdep_disk_io_initiation(struct buf *bp)
3091 {
3092         struct worklist *wk;
3093         struct worklist marker;
3094         struct indirdep *indirdep;
3095
3096         /*
3097          * We only care about write operations. There should never
3098          * be dependencies for reads.
3099          */
3100         if (bp->b_cmd == BUF_CMD_READ)
3101                 panic("softdep_disk_io_initiation: read");
3102
3103         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
3104         
3105         /*
3106          * Do any necessary pre-I/O processing.
3107          */
3108         for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3109                 LIST_INSERT_AFTER(wk, &marker, wk_list);
3110
3111                 switch (wk->wk_type) {
3112
3113                 case D_PAGEDEP:
3114                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
3115                         continue;
3116
3117                 case D_INODEDEP:
3118                         initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3119                         continue;
3120
3121                 case D_INDIRDEP:
3122                         indirdep = WK_INDIRDEP(wk);
3123                         if (indirdep->ir_state & GOINGAWAY)
3124                                 panic("disk_io_initiation: indirdep gone");
3125                         /*
3126                          * If there are no remaining dependencies, this
3127                          * will be writing the real pointers, so the
3128                          * dependency can be freed.
3129                          */
3130                         if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3131                                 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3132                                 brelse(indirdep->ir_savebp);
3133                                 /* inline expand WORKLIST_REMOVE(wk); */
3134                                 wk->wk_state &= ~ONWORKLIST;
3135                                 LIST_REMOVE(wk, wk_list);
3136                                 WORKITEM_FREE(indirdep, D_INDIRDEP);
3137                                 continue;
3138                         }
3139                         /*
3140                          * Replace up-to-date version with safe version.
3141                          */
3142                         MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
3143                             M_INDIRDEP, M_SOFTDEP_FLAGS);
3144                         ACQUIRE_LOCK(&lk);
3145                         indirdep->ir_state &= ~ATTACHED;
3146                         indirdep->ir_state |= UNDONE;
3147                         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3148                         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3149                             bp->b_bcount);
3150                         FREE_LOCK(&lk);
3151                         continue;
3152
3153                 case D_MKDIR:
3154                 case D_BMSAFEMAP:
3155                 case D_ALLOCDIRECT:
3156                 case D_ALLOCINDIR:
3157                         continue;
3158
3159                 default:
3160                         panic("handle_disk_io_initiation: Unexpected type %s",
3161                             TYPENAME(wk->wk_type));
3162                         /* NOTREACHED */
3163                 }
3164         }
3165 }
3166
3167 /*
3168  * Called from within the procedure above to deal with unsatisfied
3169  * allocation dependencies in a directory. The buffer must be locked,
3170  * thus, no I/O completion operations can occur while we are
3171  * manipulating its associated dependencies.
3172  */
3173 static void
3174 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3175 {
3176         struct diradd *dap;
3177         struct direct *ep;
3178         int i;
3179
3180         if (pagedep->pd_state & IOSTARTED) {
3181                 /*
3182                  * This can only happen if there is a driver that does not
3183                  * understand chaining. Here biodone will reissue the call
3184                  * to strategy for the incomplete buffers.
3185                  */
3186                 kprintf("initiate_write_filepage: already started\n");
3187                 return;
3188         }
3189         pagedep->pd_state |= IOSTARTED;
3190         ACQUIRE_LOCK(&lk);
3191         for (i = 0; i < DAHASHSZ; i++) {
3192                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3193                         ep = (struct direct *)
3194                             ((char *)bp->b_data + dap->da_offset);
3195                         if (ep->d_ino != dap->da_newinum) {
3196                                 FREE_LOCK(&lk);
3197                                 panic("%s: dir inum %d != new %"PRId64,
3198                                     "initiate_write_filepage",
3199                                     ep->d_ino, dap->da_newinum);
3200                         }
3201                         if (dap->da_state & DIRCHG)
3202                                 ep->d_ino = dap->da_previous->dm_oldinum;
3203                         else
3204                                 ep->d_ino = 0;
3205                         dap->da_state &= ~ATTACHED;
3206                         dap->da_state |= UNDONE;
3207                 }
3208         }
3209         FREE_LOCK(&lk);
3210 }
3211
3212 /*
3213  * Called from within the procedure above to deal with unsatisfied
3214  * allocation dependencies in an inodeblock. The buffer must be
3215  * locked, thus, no I/O completion operations can occur while we
3216  * are manipulating its associated dependencies.
3217  *
3218  * Parameters:
3219  *      bp:     The inode block
3220  */
3221 static void 
3222 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3223 {
3224         struct allocdirect *adp, *lastadp;
3225         struct ufs1_dinode *dp;
3226         struct ufs1_dinode *sip;
3227         struct fs *fs;
3228         ufs_lbn_t prevlbn = 0;
3229         int i, deplist;
3230
3231         if (inodedep->id_state & IOSTARTED)
3232                 panic("initiate_write_inodeblock: already started");
3233         inodedep->id_state |= IOSTARTED;
3234         fs = inodedep->id_fs;
3235         dp = (struct ufs1_dinode *)bp->b_data +
3236             ino_to_fsbo(fs, inodedep->id_ino);
3237         /*
3238          * If the bitmap is not yet written, then the allocated
3239          * inode cannot be written to disk.
3240          */
3241         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3242                 if (inodedep->id_savedino != NULL)
3243                         panic("initiate_write_inodeblock: already doing I/O");
3244                 MALLOC(sip, struct ufs1_dinode *,
3245                     sizeof(struct ufs1_dinode), M_INODEDEP, M_SOFTDEP_FLAGS);
3246                 inodedep->id_savedino = sip;
3247                 *inodedep->id_savedino = *dp;
3248                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3249                 dp->di_gen = inodedep->id_savedino->di_gen;
3250                 return;
3251         }
3252         /*
3253          * If no dependencies, then there is nothing to roll back.
3254          */
3255         inodedep->id_savedsize = dp->di_size;
3256         if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3257                 return;
3258         /*
3259          * Set the dependencies to busy.
3260          */
3261         ACQUIRE_LOCK(&lk);
3262         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3263              adp = TAILQ_NEXT(adp, ad_next)) {
3264 #ifdef DIAGNOSTIC
3265                 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3266                         FREE_LOCK(&lk);
3267                         panic("softdep_write_inodeblock: lbn order");
3268                 }
3269                 prevlbn = adp->ad_lbn;
3270                 if (adp->ad_lbn < NDADDR &&
3271                     dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3272                         FREE_LOCK(&lk);
3273                         panic("%s: direct pointer #%ld mismatch %d != %d",
3274                             "softdep_write_inodeblock", adp->ad_lbn,
3275                             dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3276                 }
3277                 if (adp->ad_lbn >= NDADDR &&
3278                     dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3279                         FREE_LOCK(&lk);
3280                         panic("%s: indirect pointer #%ld mismatch %d != %d",
3281                             "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3282                             dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3283                 }
3284                 deplist |= 1 << adp->ad_lbn;
3285                 if ((adp->ad_state & ATTACHED) == 0) {
3286                         FREE_LOCK(&lk);
3287                         panic("softdep_write_inodeblock: Unknown state 0x%x",
3288                             adp->ad_state);
3289                 }
3290 #endif /* DIAGNOSTIC */
3291                 adp->ad_state &= ~ATTACHED;
3292                 adp->ad_state |= UNDONE;
3293         }
3294         /*
3295          * The on-disk inode cannot claim to be any larger than the last
3296          * fragment that has been written. Otherwise, the on-disk inode
3297          * might have fragments that were not the last block in the file
3298          * which would corrupt the filesystem.
3299          */
3300         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3301              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3302                 if (adp->ad_lbn >= NDADDR)
3303                         break;
3304                 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3305                 /* keep going until hitting a rollback to a frag */
3306                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3307                         continue;
3308                 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3309                 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3310 #ifdef DIAGNOSTIC
3311                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3312                                 FREE_LOCK(&lk);
3313                                 panic("softdep_write_inodeblock: lost dep1");
3314                         }
3315 #endif /* DIAGNOSTIC */
3316                         dp->di_db[i] = 0;
3317                 }
3318                 for (i = 0; i < NIADDR; i++) {
3319 #ifdef DIAGNOSTIC
3320                         if (dp->di_ib[i] != 0 &&
3321                             (deplist & ((1 << NDADDR) << i)) == 0) {
3322                                 FREE_LOCK(&lk);
3323                                 panic("softdep_write_inodeblock: lost dep2");
3324                         }
3325 #endif /* DIAGNOSTIC */
3326                         dp->di_ib[i] = 0;
3327                 }
3328                 FREE_LOCK(&lk);
3329                 return;
3330         }
3331         /*
3332          * If we have zero'ed out the last allocated block of the file,
3333          * roll back the size to the last currently allocated block.
3334          * We know that this last allocated block is a full-sized as
3335          * we already checked for fragments in the loop above.
3336          */
3337         if (lastadp != NULL &&
3338             dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3339                 for (i = lastadp->ad_lbn; i >= 0; i--)
3340                         if (dp->di_db[i] != 0)
3341                                 break;
3342                 dp->di_size = (i + 1) * fs->fs_bsize;
3343         }
3344         /*
3345          * The only dependencies are for indirect blocks.
3346          *
3347          * The file size for indirect block additions is not guaranteed.
3348          * Such a guarantee would be non-trivial to achieve. The conventional
3349          * synchronous write implementation also does not make this guarantee.
3350          * Fsck should catch and fix discrepancies. Arguably, the file size
3351          * can be over-estimated without destroying integrity when the file
3352          * moves into the indirect blocks (i.e., is large). If we want to
3353          * postpone fsck, we are stuck with this argument.
3354          */
3355         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3356                 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3357         FREE_LOCK(&lk);
3358 }
3359
3360 /*
3361  * This routine is called during the completion interrupt
3362  * service routine for a disk write (from the procedure called
3363  * by the device driver to inform the filesystem caches of
3364  * a request completion).  It should be called early in this
3365  * procedure, before the block is made available to other
3366  * processes or other routines are called.
3367  *
3368  * Parameters:
3369  *      bp:     describes the completed disk write
3370  */
3371 static void 
3372 softdep_disk_write_complete(struct buf *bp)
3373 {
3374         struct worklist *wk;
3375         struct workhead reattach;
3376         struct newblk *newblk;
3377         struct allocindir *aip;
3378         struct allocdirect *adp;
3379         struct indirdep *indirdep;
3380         struct inodedep *inodedep;
3381         struct bmsafemap *bmsafemap;
3382
3383 #ifdef DEBUG
3384         if (lk.lkt_held != NOHOLDER)
3385                 panic("softdep_disk_write_complete: lock is held");
3386         lk.lkt_held = SPECIAL_FLAG;
3387 #endif
3388         LIST_INIT(&reattach);
3389         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3390                 WORKLIST_REMOVE(wk);
3391                 switch (wk->wk_type) {
3392
3393                 case D_PAGEDEP:
3394                         if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3395                                 WORKLIST_INSERT(&reattach, wk);
3396                         continue;
3397
3398                 case D_INODEDEP:
3399                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3400                                 WORKLIST_INSERT(&reattach, wk);
3401                         continue;
3402
3403                 case D_BMSAFEMAP:
3404                         bmsafemap = WK_BMSAFEMAP(wk);
3405                         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3406                                 newblk->nb_state |= DEPCOMPLETE;
3407                                 newblk->nb_bmsafemap = NULL;
3408                                 LIST_REMOVE(newblk, nb_deps);
3409                         }
3410                         while ((adp =
3411                            LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3412                                 adp->ad_state |= DEPCOMPLETE;
3413                                 adp->ad_buf = NULL;
3414                                 LIST_REMOVE(adp, ad_deps);
3415                                 handle_allocdirect_partdone(adp);
3416                         }
3417                         while ((aip =
3418                             LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3419                                 aip->ai_state |= DEPCOMPLETE;
3420                                 aip->ai_buf = NULL;
3421                                 LIST_REMOVE(aip, ai_deps);
3422                                 handle_allocindir_partdone(aip);
3423                         }
3424                         while ((inodedep =
3425                              LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3426                                 inodedep->id_state |= DEPCOMPLETE;
3427                                 LIST_REMOVE(inodedep, id_deps);
3428                                 inodedep->id_buf = NULL;
3429                         }
3430                         WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3431                         continue;
3432
3433                 case D_MKDIR:
3434                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3435                         continue;
3436
3437                 case D_ALLOCDIRECT:
3438                         adp = WK_ALLOCDIRECT(wk);
3439                         adp->ad_state |= COMPLETE;
3440                         handle_allocdirect_partdone(adp);
3441                         continue;
3442
3443                 case D_ALLOCINDIR:
3444                         aip = WK_ALLOCINDIR(wk);
3445                         aip->ai_state |= COMPLETE;
3446                         handle_allocindir_partdone(aip);
3447                         continue;
3448
3449                 case D_INDIRDEP:
3450                         indirdep = WK_INDIRDEP(wk);
3451                         if (indirdep->ir_state & GOINGAWAY) {
3452                                 lk.lkt_held = NOHOLDER;
3453                                 panic("disk_write_complete: indirdep gone");
3454                         }
3455                         bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3456                         FREE(indirdep->ir_saveddata, M_INDIRDEP);
3457                         indirdep->ir_saveddata = 0;
3458                         indirdep->ir_state &= ~UNDONE;
3459                         indirdep->ir_state |= ATTACHED;
3460                         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
3461                                 handle_allocindir_partdone(aip);
3462                                 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3463                                         lk.lkt_held = NOHOLDER;
3464                                         panic("disk_write_complete: not gone");
3465                                 }
3466                         }
3467                         WORKLIST_INSERT(&reattach, wk);
3468                         if ((bp->b_flags & B_DELWRI) == 0)
3469                                 stat_indir_blk_ptrs++;
3470                         bdirty(bp);
3471                         continue;
3472
3473                 default:
3474                         lk.lkt_held = NOHOLDER;
3475                         panic("handle_disk_write_complete: Unknown type %s",
3476                             TYPENAME(wk->wk_type));
3477                         /* NOTREACHED */
3478                 }
3479         }
3480         /*
3481          * Reattach any requests that must be redone.
3482          */
3483         while ((wk = LIST_FIRST(&reattach)) != NULL) {
3484                 WORKLIST_REMOVE(wk);
3485                 WORKLIST_INSERT_BP(bp, wk);
3486         }
3487 #ifdef DEBUG
3488         if (lk.lkt_held != SPECIAL_FLAG)
3489                 panic("softdep_disk_write_complete: lock lost");
3490         lk.lkt_held = NOHOLDER;
3491 #endif
3492 }
3493
3494 /*
3495  * Called from within softdep_disk_write_complete above. Note that
3496  * this routine is always called from interrupt level with further
3497  * splbio interrupts blocked.
3498  *
3499  * Parameters:
3500  *      adp:    the completed allocdirect
3501  */
3502 static void 
3503 handle_allocdirect_partdone(struct allocdirect *adp)
3504 {
3505         struct allocdirect *listadp;
3506         struct inodedep *inodedep;
3507         long bsize;
3508
3509         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3510                 return;
3511         if (adp->ad_buf != NULL) {
3512                 lk.lkt_held = NOHOLDER;
3513                 panic("handle_allocdirect_partdone: dangling dep");
3514         }
3515         /*
3516          * The on-disk inode cannot claim to be any larger than the last
3517          * fragment that has been written. Otherwise, the on-disk inode
3518          * might have fragments that were not the last block in the file
3519          * which would corrupt the filesystem. Thus, we cannot free any
3520          * allocdirects after one whose ad_oldblkno claims a fragment as
3521          * these blocks must be rolled back to zero before writing the inode.
3522          * We check the currently active set of allocdirects in id_inoupdt.
3523          */
3524         inodedep = adp->ad_inodedep;
3525         bsize = inodedep->id_fs->fs_bsize;
3526         TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3527                 /* found our block */
3528                 if (listadp == adp)
3529                         break;
3530                 /* continue if ad_oldlbn is not a fragment */
3531                 if (listadp->ad_oldsize == 0 ||
3532                     listadp->ad_oldsize == bsize)
3533                         continue;
3534                 /* hit a fragment */
3535                 return;
3536         }
3537         /*
3538          * If we have reached the end of the current list without
3539          * finding the just finished dependency, then it must be
3540          * on the future dependency list. Future dependencies cannot
3541          * be freed until they are moved to the current list.
3542          */
3543         if (listadp == NULL) {
3544 #ifdef DEBUG
3545                 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3546                         /* found our block */
3547                         if (listadp == adp)
3548                                 break;
3549                 if (listadp == NULL) {
3550                         lk.lkt_held = NOHOLDER;
3551                         panic("handle_allocdirect_partdone: lost dep");
3552                 }
3553 #endif /* DEBUG */
3554                 return;
3555         }
3556         /*
3557          * If we have found the just finished dependency, then free
3558          * it along with anything that follows it that is complete.
3559          */
3560         for (; adp; adp = listadp) {
3561                 listadp = TAILQ_NEXT(adp, ad_next);
3562                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3563                         return;
3564                 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3565         }
3566 }
3567
3568 /*
3569  * Called from within softdep_disk_write_complete above. Note that
3570  * this routine is always called from interrupt level with further
3571  * splbio interrupts blocked.
3572  *
3573  * Parameters:
3574  *      aip:    the completed allocindir
3575  */
3576 static void
3577 handle_allocindir_partdone(struct allocindir *aip)
3578 {
3579         struct indirdep *indirdep;
3580
3581         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3582                 return;
3583         if (aip->ai_buf != NULL) {
3584                 lk.lkt_held = NOHOLDER;
3585                 panic("handle_allocindir_partdone: dangling dependency");
3586         }
3587         indirdep = aip->ai_indirdep;
3588         if (indirdep->ir_state & UNDONE) {
3589                 LIST_REMOVE(aip, ai_next);
3590                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3591                 return;
3592         }
3593         ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3594             aip->ai_newblkno;
3595         LIST_REMOVE(aip, ai_next);
3596         if (aip->ai_freefrag != NULL)
3597                 add_to_worklist(&aip->ai_freefrag->ff_list);
3598         WORKITEM_FREE(aip, D_ALLOCINDIR);
3599 }
3600
3601 /*
3602  * Called from within softdep_disk_write_complete above to restore
3603  * in-memory inode block contents to their most up-to-date state. Note
3604  * that this routine is always called from interrupt level with further
3605  * splbio interrupts blocked.
3606  *
3607  * Parameters:
3608  *      bp:     buffer containing the inode block
3609  */
3610 static int 
3611 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3612 {
3613         struct worklist *wk, *filefree;
3614         struct allocdirect *adp, *nextadp;
3615         struct ufs1_dinode *dp;
3616         int hadchanges;
3617
3618         if ((inodedep->id_state & IOSTARTED) == 0) {
3619                 lk.lkt_held = NOHOLDER;
3620                 panic("handle_written_inodeblock: not started");
3621         }
3622         inodedep->id_state &= ~IOSTARTED;
3623         dp = (struct ufs1_dinode *)bp->b_data +
3624             ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3625         /*
3626          * If we had to rollback the inode allocation because of
3627          * bitmaps being incomplete, then simply restore it.
3628          * Keep the block dirty so that it will not be reclaimed until
3629          * all associated dependencies have been cleared and the
3630          * corresponding updates written to disk.
3631          */
3632         if (inodedep->id_savedino != NULL) {
3633                 *dp = *inodedep->id_savedino;
3634                 FREE(inodedep->id_savedino, M_INODEDEP);
3635                 inodedep->id_savedino = NULL;
3636                 if ((bp->b_flags & B_DELWRI) == 0)
3637                         stat_inode_bitmap++;
3638                 bdirty(bp);
3639                 return (1);
3640         }
3641         inodedep->id_state |= COMPLETE;
3642         /*
3643          * Roll forward anything that had to be rolled back before 
3644          * the inode could be updated.
3645          */
3646         hadchanges = 0;
3647         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3648                 nextadp = TAILQ_NEXT(adp, ad_next);
3649                 if (adp->ad_state & ATTACHED) {
3650                         lk.lkt_held = NOHOLDER;
3651                         panic("handle_written_inodeblock: new entry");
3652                 }
3653                 if (adp->ad_lbn < NDADDR) {
3654                         if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3655                                 lk.lkt_held = NOHOLDER;
3656                                 panic("%s: %s #%ld mismatch %d != %d",
3657                                     "handle_written_inodeblock",
3658                                     "direct pointer", adp->ad_lbn,
3659                                     dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3660                         }
3661                         dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3662                 } else {
3663                         if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3664                                 lk.lkt_held = NOHOLDER;
3665                                 panic("%s: %s #%ld allocated as %d",
3666                                     "handle_written_inodeblock",
3667                                     "indirect pointer", adp->ad_lbn - NDADDR,
3668                                     dp->di_ib[adp->ad_lbn - NDADDR]);
3669                         }
3670                         dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3671                 }
3672                 adp->ad_state &= ~UNDONE;
3673                 adp->ad_state |= ATTACHED;
3674                 hadchanges = 1;
3675         }
3676         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3677                 stat_direct_blk_ptrs++;
3678         /*
3679          * Reset the file size to its most up-to-date value.
3680          */
3681         if (inodedep->id_savedsize == -1) {
3682                 lk.lkt_held = NOHOLDER;
3683                 panic("handle_written_inodeblock: bad size");
3684         }
3685         if (dp->di_size != inodedep->id_savedsize) {
3686                 dp->di_size = inodedep->id_savedsize;
3687                 hadchanges = 1;
3688         }
3689         inodedep->id_savedsize = -1;
3690         /*
3691          * If there were any rollbacks in the inode block, then it must be
3692          * marked dirty so that its will eventually get written back in
3693          * its correct form.
3694          */
3695         if (hadchanges)
3696                 bdirty(bp);
3697         /*
3698          * Process any allocdirects that completed during the update.
3699          */
3700         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3701                 handle_allocdirect_partdone(adp);
3702         /*
3703          * Process deallocations that were held pending until the
3704          * inode had been written to disk. Freeing of the inode
3705          * is delayed until after all blocks have been freed to
3706          * avoid creation of new <vfsid, inum, lbn> triples
3707          * before the old ones have been deleted.
3708          */
3709         filefree = NULL;
3710         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3711                 WORKLIST_REMOVE(wk);
3712                 switch (wk->wk_type) {
3713
3714                 case D_FREEFILE:
3715                         /*
3716                          * We defer adding filefree to the worklist until
3717                          * all other additions have been made to ensure
3718                          * that it will be done after all the old blocks
3719                          * have been freed.
3720                          */
3721                         if (filefree != NULL) {
3722                                 lk.lkt_held = NOHOLDER;
3723                                 panic("handle_written_inodeblock: filefree");
3724                         }
3725                         filefree = wk;
3726                         continue;
3727
3728                 case D_MKDIR:
3729                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3730                         continue;
3731
3732                 case D_DIRADD:
3733                         diradd_inode_written(WK_DIRADD(wk), inodedep);
3734                         continue;
3735
3736                 case D_FREEBLKS:
3737                         wk->wk_state |= COMPLETE;
3738                         if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
3739                                 continue;
3740                         /* -- fall through -- */
3741                 case D_FREEFRAG:
3742                 case D_DIRREM:
3743                         add_to_worklist(wk);
3744                         continue;
3745
3746                 default:
3747                         lk.lkt_held = NOHOLDER;
3748                         panic("handle_written_inodeblock: Unknown type %s",
3749                             TYPENAME(wk->wk_type));
3750                         /* NOTREACHED */
3751                 }
3752         }
3753         if (filefree != NULL) {
3754                 if (free_inodedep(inodedep) == 0) {
3755                         lk.lkt_held = NOHOLDER;
3756                         panic("handle_written_inodeblock: live inodedep");
3757                 }
3758                 add_to_worklist(filefree);
3759                 return (0);
3760         }
3761
3762         /*
3763          * If no outstanding dependencies, free it.
3764          */
3765         if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3766                 return (0);
3767         return (hadchanges);
3768 }
3769
3770 /*
3771  * Process a diradd entry after its dependent inode has been written.
3772  * This routine must be called with splbio interrupts blocked.
3773  */
3774 static void
3775 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3776 {
3777         struct pagedep *pagedep;
3778
3779         dap->da_state |= COMPLETE;
3780         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3781                 if (dap->da_state & DIRCHG)
3782                         pagedep = dap->da_previous->dm_pagedep;
3783                 else
3784                         pagedep = dap->da_pagedep;
3785                 LIST_REMOVE(dap, da_pdlist);
3786                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3787         }
3788         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3789 }
3790
3791 /*
3792  * Handle the completion of a mkdir dependency.
3793  */
3794 static void
3795 handle_written_mkdir(struct mkdir *mkdir, int type)
3796 {
3797         struct diradd *dap;
3798         struct pagedep *pagedep;
3799
3800         if (mkdir->md_state != type) {
3801                 lk.lkt_held = NOHOLDER;
3802                 panic("handle_written_mkdir: bad type");
3803         }
3804         dap = mkdir->md_diradd;
3805         dap->da_state &= ~type;
3806         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3807                 dap->da_state |= DEPCOMPLETE;
3808         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3809                 if (dap->da_state & DIRCHG)
3810                         pagedep = dap->da_previous->dm_pagedep;
3811                 else
3812                         pagedep = dap->da_pagedep;
3813                 LIST_REMOVE(dap, da_pdlist);
3814                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3815         }
3816         LIST_REMOVE(mkdir, md_mkdirs);
3817         WORKITEM_FREE(mkdir, D_MKDIR);
3818 }
3819
3820 /*
3821  * Called from within softdep_disk_write_complete above.
3822  * A write operation was just completed. Removed inodes can
3823  * now be freed and associated block pointers may be committed.
3824  * Note that this routine is always called from interrupt level
3825  * with further splbio interrupts blocked.
3826  *
3827  * Parameters:
3828  *      bp:     buffer containing the written page
3829  */
3830 static int 
3831 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3832 {
3833         struct dirrem *dirrem;
3834         struct diradd *dap, *nextdap;
3835         struct direct *ep;
3836         int i, chgs;
3837
3838         if ((pagedep->pd_state & IOSTARTED) == 0) {
3839                 lk.lkt_held = NOHOLDER;
3840                 panic("handle_written_filepage: not started");
3841         }
3842         pagedep->pd_state &= ~IOSTARTED;
3843         /*
3844          * Process any directory removals that have been committed.
3845          */
3846         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3847                 LIST_REMOVE(dirrem, dm_next);
3848                 dirrem->dm_dirinum = pagedep->pd_ino;
3849                 add_to_worklist(&dirrem->dm_list);
3850         }
3851         /*
3852          * Free any directory additions that have been committed.
3853          */
3854         while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3855                 free_diradd(dap);
3856         /*
3857          * Uncommitted directory entries must be restored.
3858          */
3859         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3860                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3861                      dap = nextdap) {
3862                         nextdap = LIST_NEXT(dap, da_pdlist);
3863                         if (dap->da_state & ATTACHED) {
3864                                 lk.lkt_held = NOHOLDER;
3865                                 panic("handle_written_filepage: attached");
3866                         }
3867                         ep = (struct direct *)
3868                             ((char *)bp->b_data + dap->da_offset);
3869                         ep->d_ino = dap->da_newinum;
3870                         dap->da_state &= ~UNDONE;
3871                         dap->da_state |= ATTACHED;
3872                         chgs = 1;
3873                         /*
3874                          * If the inode referenced by the directory has
3875                          * been written out, then the dependency can be
3876                          * moved to the pending list.
3877                          */
3878                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3879                                 LIST_REMOVE(dap, da_pdlist);
3880                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3881                                     da_pdlist);
3882                         }
3883                 }
3884         }
3885         /*
3886          * If there were any rollbacks in the directory, then it must be
3887          * marked dirty so that its will eventually get written back in
3888          * its correct form.
3889          */
3890         if (chgs) {
3891                 if ((bp->b_flags & B_DELWRI) == 0)
3892                         stat_dir_entry++;
3893                 bdirty(bp);
3894         }
3895         /*
3896          * If no dependencies remain, the pagedep will be freed.
3897          * Otherwise it will remain to update the page before it
3898          * is written back to disk.
3899          */
3900         if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3901                 for (i = 0; i < DAHASHSZ; i++)
3902                         if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3903                                 break;
3904                 if (i == DAHASHSZ) {
3905                         LIST_REMOVE(pagedep, pd_hash);
3906                         WORKITEM_FREE(pagedep, D_PAGEDEP);
3907                         return (0);
3908                 }
3909         }
3910         return (1);
3911 }
3912
3913 /*
3914  * Writing back in-core inode structures.
3915  * 
3916  * The filesystem only accesses an inode's contents when it occupies an
3917  * "in-core" inode structure.  These "in-core" structures are separate from
3918  * the page frames used to cache inode blocks.  Only the latter are
3919  * transferred to/from the disk.  So, when the updated contents of the
3920  * "in-core" inode structure are copied to the corresponding in-memory inode
3921  * block, the dependencies are also transferred.  The following procedure is
3922  * called when copying a dirty "in-core" inode to a cached inode block.
3923  */
3924
3925 /*
3926  * Called when an inode is loaded from disk. If the effective link count
3927  * differed from the actual link count when it was last flushed, then we
3928  * need to ensure that the correct effective link count is put back.
3929  *
3930  * Parameters:
3931  *      ip:     the "in_core" copy of the inode
3932  */
3933 void 
3934 softdep_load_inodeblock(struct inode *ip)
3935 {
3936         struct inodedep *inodedep;
3937
3938         /*
3939          * Check for alternate nlink count.
3940          */
3941         ip->i_effnlink = ip->i_nlink;
3942         ACQUIRE_LOCK(&lk);
3943         if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3944                 FREE_LOCK(&lk);
3945                 return;
3946         }
3947         ip->i_effnlink -= inodedep->id_nlinkdelta;
3948         FREE_LOCK(&lk);
3949 }
3950
3951 /*
3952  * This routine is called just before the "in-core" inode
3953  * information is to be copied to the in-memory inode block.
3954  * Recall that an inode block contains several inodes. If
3955  * the force flag is set, then the dependencies will be
3956  * cleared so that the update can always be made. Note that
3957  * the buffer is locked when this routine is called, so we
3958  * will never be in the middle of writing the inode block 
3959  * to disk.
3960  *
3961  * Parameters:
3962  *      ip:             the "in_core" copy of the inode
3963  *      bp:             the buffer containing the inode block
3964  *      waitfor:        nonzero => update must be allowed
3965  */
3966 void 
3967 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3968                           int waitfor)
3969 {
3970         struct inodedep *inodedep;
3971         struct worklist *wk;
3972         int error, gotit;
3973
3974         /*
3975          * If the effective link count is not equal to the actual link
3976          * count, then we must track the difference in an inodedep while
3977          * the inode is (potentially) tossed out of the cache. Otherwise,
3978          * if there is no existing inodedep, then there are no dependencies
3979          * to track.
3980          */
3981         ACQUIRE_LOCK(&lk);
3982         if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3983                 FREE_LOCK(&lk);
3984                 if (ip->i_effnlink != ip->i_nlink)
3985                         panic("softdep_update_inodeblock: bad link count");
3986                 return;
3987         }
3988         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3989                 FREE_LOCK(&lk);
3990                 panic("softdep_update_inodeblock: bad delta");
3991         }
3992         /*
3993          * Changes have been initiated. Anything depending on these
3994          * changes cannot occur until this inode has been written.
3995          */
3996         inodedep->id_state &= ~COMPLETE;
3997         if ((inodedep->id_state & ONWORKLIST) == 0)
3998                 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3999         /*
4000          * Any new dependencies associated with the incore inode must 
4001          * now be moved to the list associated with the buffer holding
4002          * the in-memory copy of the inode. Once merged process any
4003          * allocdirects that are completed by the merger.
4004          */
4005         merge_inode_lists(inodedep);
4006         if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
4007                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
4008         /*
4009          * Now that the inode has been pushed into the buffer, the
4010          * operations dependent on the inode being written to disk
4011          * can be moved to the id_bufwait so that they will be
4012          * processed when the buffer I/O completes.
4013          */
4014         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
4015                 WORKLIST_REMOVE(wk);
4016                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
4017         }
4018         /*
4019          * Newly allocated inodes cannot be written until the bitmap
4020          * that allocates them have been written (indicated by
4021          * DEPCOMPLETE being set in id_state). If we are doing a
4022          * forced sync (e.g., an fsync on a file), we force the bitmap
4023          * to be written so that the update can be done.
4024          */
4025         if ((inodedep->id_state & DEPCOMPLETE) != 0 || waitfor == 0) {
4026                 FREE_LOCK(&lk);
4027                 return;
4028         }
4029         gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4030         FREE_LOCK(&lk);
4031         if (gotit &&
4032             (error = bwrite(inodedep->id_buf)) != 0)
4033                 softdep_error("softdep_update_inodeblock: bwrite", error);
4034 }
4035
4036 /*
4037  * Merge the new inode dependency list (id_newinoupdt) into the old
4038  * inode dependency list (id_inoupdt). This routine must be called
4039  * with splbio interrupts blocked.
4040  */
4041 static void
4042 merge_inode_lists(struct inodedep *inodedep)
4043 {
4044         struct allocdirect *listadp, *newadp;
4045
4046         newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
4047         for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
4048                 if (listadp->ad_lbn < newadp->ad_lbn) {
4049                         listadp = TAILQ_NEXT(listadp, ad_next);
4050                         continue;
4051                 }
4052                 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
4053                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
4054                 if (listadp->ad_lbn == newadp->ad_lbn) {
4055                         allocdirect_merge(&inodedep->id_inoupdt, newadp,
4056                             listadp);
4057                         listadp = newadp;
4058                 }
4059                 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
4060         }
4061         while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
4062                 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
4063                 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
4064         }
4065 }
4066
4067 /*
4068  * If we are doing an fsync, then we must ensure that any directory
4069  * entries for the inode have been written after the inode gets to disk.
4070  *
4071  * Parameters:
4072  *      vp:     the "in_core" copy of the inode
4073  */
4074 static int
4075 softdep_fsync(struct vnode *vp)
4076 {
4077         struct inodedep *inodedep;
4078         struct pagedep *pagedep;
4079         struct worklist *wk;
4080         struct diradd *dap;
4081         struct mount *mnt;
4082         struct vnode *pvp;
4083         struct inode *ip;
4084         struct buf *bp;
4085         struct fs *fs;
4086         int error, flushparent;
4087         ino_t parentino;
4088         ufs_lbn_t lbn;
4089
4090         /*
4091          * Move check from original kernel code, possibly not needed any
4092          * more with the per-mount bioops.
4093          */
4094         if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4095                 return (0);
4096
4097         ip = VTOI(vp);
4098         fs = ip->i_fs;
4099         ACQUIRE_LOCK(&lk);
4100         if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4101                 FREE_LOCK(&lk);
4102                 return (0);
4103         }
4104         if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4105             LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4106             TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4107             TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4108                 FREE_LOCK(&lk);
4109                 panic("softdep_fsync: pending ops");
4110         }
4111         for (error = 0, flushparent = 0; ; ) {
4112                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4113                         break;
4114                 if (wk->wk_type != D_DIRADD) {
4115                         FREE_LOCK(&lk);
4116                         panic("softdep_fsync: Unexpected type %s",
4117                             TYPENAME(wk->wk_type));
4118                 }
4119                 dap = WK_DIRADD(wk);
4120                 /*
4121                  * Flush our parent if this directory entry
4122                  * has a MKDIR_PARENT dependency.
4123                  */
4124                 if (dap->da_state & DIRCHG)
4125                         pagedep = dap->da_previous->dm_pagedep;
4126                 else
4127                         pagedep = dap->da_pagedep;
4128                 mnt = pagedep->pd_mnt;
4129                 parentino = pagedep->pd_ino;
4130                 lbn = pagedep->pd_lbn;
4131                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4132                         FREE_LOCK(&lk);
4133                         panic("softdep_fsync: dirty");
4134                 }
4135                 flushparent = dap->da_state & MKDIR_PARENT;
4136                 /*
4137                  * If we are being fsync'ed as part of vgone'ing this vnode,
4138                  * then we will not be able to release and recover the
4139                  * vnode below, so we just have to give up on writing its
4140                  * directory entry out. It will eventually be written, just
4141                  * not now, but then the user was not asking to have it
4142                  * written, so we are not breaking any promises.
4143                  */
4144                 if (vp->v_flag & VRECLAIMED)
4145                         break;
4146                 /*
4147                  * We prevent deadlock by always fetching inodes from the
4148                  * root, moving down the directory tree. Thus, when fetching
4149                  * our parent directory, we must unlock ourselves before
4150                  * requesting the lock on our parent. See the comment in
4151                  * ufs_lookup for details on possible races.
4152                  */
4153                 FREE_LOCK(&lk);
4154                 vn_unlock(vp);
4155                 error = VFS_VGET(mnt, parentino, &pvp);
4156                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4157                 if (error != 0)
4158                         return (error);
4159                 if (flushparent) {
4160                         if ((error = ffs_update(pvp, 1)) != 0) {
4161                                 vput(pvp);
4162                                 return (error);
4163                         }
4164                 }
4165                 /*
4166                  * Flush directory page containing the inode's name.
4167                  */
4168                 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4169                 if (error == 0)
4170                         error = bwrite(bp);
4171                 vput(pvp);
4172                 if (error != 0)
4173                         return (error);
4174                 ACQUIRE_LOCK(&lk);
4175                 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4176                         break;
4177         }
4178         FREE_LOCK(&lk);
4179         return (0);
4180 }
4181
4182 /*
4183  * Flush all the dirty bitmaps associated with the block device
4184  * before flushing the rest of the dirty blocks so as to reduce
4185  * the number of dependencies that will have to be rolled back.
4186  */
4187 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4188
4189 void
4190 softdep_fsync_mountdev(struct vnode *vp)
4191 {
4192         if (!vn_isdisk(vp, NULL))
4193                 panic("softdep_fsync_mountdev: vnode not a disk");
4194         ACQUIRE_LOCK(&lk);
4195         RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
4196                 softdep_fsync_mountdev_bp, vp);
4197         drain_output(vp, 1);
4198         FREE_LOCK(&lk);
4199 }
4200
4201 static int
4202 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4203 {
4204         struct worklist *wk;
4205         struct vnode *vp = data;
4206
4207         /* 
4208          * If it is already scheduled, skip to the next buffer.
4209          */
4210         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4211                 return(0);
4212         if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4213                 BUF_UNLOCK(bp);
4214                 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4215                 return(0);
4216         }
4217         /*
4218          * We are only interested in bitmaps with outstanding
4219          * dependencies.
4220          */
4221         if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4222             wk->wk_type != D_BMSAFEMAP) {
4223                 BUF_UNLOCK(bp);
4224                 return(0);
4225         }
4226         bremfree(bp);
4227         FREE_LOCK(&lk);
4228         (void) bawrite(bp);
4229         ACQUIRE_LOCK(&lk);
4230         return(0);
4231 }
4232
4233 /*
4234  * This routine is called when we are trying to synchronously flush a
4235  * file. This routine must eliminate any filesystem metadata dependencies
4236  * so that the syncing routine can succeed by pushing the dirty blocks
4237  * associated with the file. If any I/O errors occur, they are returned.
4238  */
4239 struct softdep_sync_metadata_info {
4240         struct vnode *vp;
4241         int waitfor;
4242 };
4243
4244 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4245
4246 int
4247 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4248 {
4249         struct softdep_sync_metadata_info info;
4250         int error, waitfor;
4251
4252         /*
4253          * Check whether this vnode is involved in a filesystem
4254          * that is doing soft dependency processing.
4255          */
4256         if (!vn_isdisk(vp, NULL)) {
4257                 if (!DOINGSOFTDEP(vp))
4258                         return (0);
4259         } else
4260                 if (vp->v_rdev->si_mountpoint == NULL ||
4261                     (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4262                         return (0);
4263         /*
4264          * Ensure that any direct block dependencies have been cleared.
4265          */
4266         ACQUIRE_LOCK(&lk);
4267         if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4268                 FREE_LOCK(&lk);
4269                 return (error);
4270         }
4271         /*
4272          * For most files, the only metadata dependencies are the
4273          * cylinder group maps that allocate their inode or blocks.
4274          * The block allocation dependencies can be found by traversing
4275          * the dependency lists for any buffers that remain on their
4276          * dirty buffer list. The inode allocation dependency will
4277          * be resolved when the inode is updated with MNT_WAIT.
4278          * This work is done in two passes. The first pass grabs most
4279          * of the buffers and begins asynchronously writing them. The
4280          * only way to wait for these asynchronous writes is to sleep
4281          * on the filesystem vnode which may stay busy for a long time
4282          * if the filesystem is active. So, instead, we make a second
4283          * pass over the dependencies blocking on each write. In the
4284          * usual case we will be blocking against a write that we
4285          * initiated, so when it is done the dependency will have been
4286          * resolved. Thus the second pass is expected to end quickly.
4287          */
4288         waitfor = MNT_NOWAIT;
4289 top:
4290         /*
4291          * We must wait for any I/O in progress to finish so that
4292          * all potential buffers on the dirty list will be visible.
4293          */
4294         drain_output(vp, 1);
4295         info.vp = vp;
4296         info.waitfor = waitfor;
4297         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
4298                         softdep_sync_metadata_bp, &info);
4299         if (error < 0) {
4300                 FREE_LOCK(&lk);
4301                 return(-error); /* error code */
4302         }
4303
4304         /*
4305          * The brief unlock is to allow any pent up dependency
4306          * processing to be done.  Then proceed with the second pass.
4307          */
4308         if (waitfor == MNT_NOWAIT) {
4309                 waitfor = MNT_WAIT;
4310                 FREE_LOCK(&lk);
4311                 ACQUIRE_LOCK(&lk);
4312                 goto top;
4313         }
4314
4315         /*
4316          * If we have managed to get rid of all the dirty buffers,
4317          * then we are done. For certain directories and block
4318          * devices, we may need to do further work.
4319          *
4320          * We must wait for any I/O in progress to finish so that
4321          * all potential buffers on the dirty list will be visible.
4322          */
4323         drain_output(vp, 1);
4324         if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4325                 FREE_LOCK(&lk);
4326                 return (0);
4327         }
4328
4329         FREE_LOCK(&lk);
4330         /*
4331          * If we are trying to sync a block device, some of its buffers may
4332          * contain metadata that cannot be written until the contents of some
4333          * partially written files have been written to disk. The only easy
4334          * way to accomplish this is to sync the entire filesystem (luckily
4335          * this happens rarely).
4336          */
4337         if (vn_isdisk(vp, NULL) && 
4338             vp->v_rdev &&
4339             vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4340             (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4341                 return (error);
4342         return (0);
4343 }
4344
4345 static int
4346 softdep_sync_metadata_bp(struct buf *bp, void *data)
4347 {
4348         struct softdep_sync_metadata_info *info = data;
4349         struct pagedep *pagedep;
4350         struct allocdirect *adp;
4351         struct allocindir *aip;
4352         struct worklist *wk;
4353         struct buf *nbp;
4354         int error;
4355         int i;
4356
4357         if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4358                 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4359                 return (1);
4360         }
4361         if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4362                 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4363                 BUF_UNLOCK(bp);
4364                 return(1);
4365         }
4366
4367         /*
4368          * As we hold the buffer locked, none of its dependencies
4369          * will disappear.
4370          */
4371         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4372                 switch (wk->wk_type) {
4373
4374                 case D_ALLOCDIRECT:
4375                         adp = WK_ALLOCDIRECT(wk);
4376                         if (adp->ad_state & DEPCOMPLETE)
4377                                 break;
4378                         nbp = adp->ad_buf;
4379                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4380                                 break;
4381                         FREE_LOCK(&lk);
4382                         if (info->waitfor == MNT_NOWAIT) {
4383                                 bawrite(nbp);
4384                         } else if ((error = bwrite(nbp)) != 0) {
4385                                 bawrite(bp);
4386                                 ACQUIRE_LOCK(&lk);
4387                                 return (-error);
4388                         }
4389                         ACQUIRE_LOCK(&lk);
4390                         break;
4391
4392                 case D_ALLOCINDIR:
4393                         aip = WK_ALLOCINDIR(wk);
4394                         if (aip->ai_state & DEPCOMPLETE)
4395                                 break;
4396                         nbp = aip->ai_buf;
4397                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4398                                 break;
4399                         FREE_LOCK(&lk);
4400                         if (info->waitfor == MNT_NOWAIT) {
4401                                 bawrite(nbp);
4402                         } else if ((error = bwrite(nbp)) != 0) {
4403                                 bawrite(bp);
4404                                 ACQUIRE_LOCK(&lk);
4405                                 return (-error);
4406                         }
4407                         ACQUIRE_LOCK(&lk);
4408                         break;
4409
4410                 case D_INDIRDEP:
4411                 restart:
4412
4413                         LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4414                                 if (aip->ai_state & DEPCOMPLETE)
4415                                         continue;
4416                                 nbp = aip->ai_buf;
4417                                 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4418                                         goto restart;
4419                                 FREE_LOCK(&lk);
4420                                 if ((error = bwrite(nbp)) != 0) {
4421                                         bawrite(bp);
4422                                         ACQUIRE_LOCK(&lk);
4423                                         return (-error);
4424                                 }
4425                                 ACQUIRE_LOCK(&lk);
4426                                 goto restart;
4427                         }
4428                         break;
4429
4430                 case D_INODEDEP:
4431                         if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4432                             WK_INODEDEP(wk)->id_ino)) != 0) {
4433                                 FREE_LOCK(&lk);
4434                                 bawrite(bp);
4435                                 ACQUIRE_LOCK(&lk);
4436                                 return (-error);
4437                         }
4438                         break;
4439
4440                 case D_PAGEDEP:
4441                         /*
4442                          * We are trying to sync a directory that may
4443                          * have dependencies on both its own metadata
4444                          * and/or dependencies on the inodes of any
4445                          * recently allocated files. We walk its diradd
4446                          * lists pushing out the associated inode.
4447                          */
4448                         pagedep = WK_PAGEDEP(wk);
4449                         for (i = 0; i < DAHASHSZ; i++) {
4450                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4451                                         continue;
4452                                 if ((error =
4453                                     flush_pagedep_deps(info->vp,
4454                                                 pagedep->pd_mnt,
4455                                                 &pagedep->pd_diraddhd[i]))) {
4456                                         FREE_LOCK(&lk);
4457                                         bawrite(bp);
4458                                         ACQUIRE_LOCK(&lk);
4459                                         return (-error);
4460                                 }
4461                         }
4462                         break;
4463
4464                 case D_MKDIR:
4465                         /*
4466                          * This case should never happen if the vnode has
4467                          * been properly sync'ed. However, if this function
4468                          * is used at a place where the vnode has not yet
4469                          * been sync'ed, this dependency can show up. So,
4470                          * rather than panic, just flush it.
4471                          */
4472                         nbp = WK_MKDIR(wk)->md_buf;
4473                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4474                                 break;
4475                         FREE_LOCK(&lk);
4476                         if (info->waitfor == MNT_NOWAIT) {
4477                                 bawrite(nbp);
4478                         } else if ((error = bwrite(nbp)) != 0) {
4479                                 bawrite(bp);
4480                                 ACQUIRE_LOCK(&lk);
4481                                 return (-error);
4482                         }
4483                         ACQUIRE_LOCK(&lk);
4484                         break;
4485
4486                 case D_BMSAFEMAP:
4487                         /*
4488                          * This case should never happen if the vnode has
4489                          * been properly sync'ed. However, if this function
4490                          * is used at a place where the vnode has not yet
4491                          * been sync'ed, this dependency can show up. So,
4492                          * rather than panic, just flush it.
4493                          *
4494                          * nbp can wind up == bp if a device node for the
4495                          * same filesystem is being fsynced at the same time,
4496                          * leading to a panic if we don't catch the case.
4497                          */
4498                         nbp = WK_BMSAFEMAP(wk)->sm_buf;
4499                         if (nbp == bp)
4500                                 break;
4501                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4502                                 break;
4503                         FREE_LOCK(&lk);
4504                         if (info->waitfor == MNT_NOWAIT) {
4505                                 bawrite(nbp);
4506                         } else if ((error = bwrite(nbp)) != 0) {
4507                                 bawrite(bp);
4508                                 ACQUIRE_LOCK(&lk);
4509                                 return (-error);
4510                         }
4511                         ACQUIRE_LOCK(&lk);
4512                         break;
4513
4514                 default:
4515                         FREE_LOCK(&lk);
4516                         panic("softdep_sync_metadata: Unknown type %s",
4517                             TYPENAME(wk->wk_type));
4518                         /* NOTREACHED */
4519                 }
4520         }
4521         FREE_LOCK(&lk);
4522         bawrite(bp);
4523         ACQUIRE_LOCK(&lk);
4524         return(0);
4525 }
4526
4527 /*
4528  * Flush the dependencies associated with an inodedep.
4529  * Called with splbio blocked.
4530  */
4531 static int
4532 flush_inodedep_deps(struct fs *fs, ino_t ino)
4533 {
4534         struct inodedep *inodedep;
4535         struct allocdirect *adp;
4536         int error, waitfor;
4537         struct buf *bp;
4538
4539         /*
4540          * This work is done in two passes. The first pass grabs most
4541          * of the buffers and begins asynchronously writing them. The
4542          * only way to wait for these asynchronous writes is to sleep
4543          * on the filesystem vnode which may stay busy for a long time
4544          * if the filesystem is active. So, instead, we make a second
4545          * pass over the dependencies blocking on each write. In the
4546          * usual case we will be blocking against a write that we
4547          * initiated, so when it is done the dependency will have been
4548          * resolved. Thus the second pass is expected to end quickly.
4549          * We give a brief window at the top of the loop to allow
4550          * any pending I/O to complete.
4551          */
4552         for (waitfor = MNT_NOWAIT; ; ) {
4553                 FREE_LOCK(&lk);
4554                 ACQUIRE_LOCK(&lk);
4555                 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4556                         return (0);
4557                 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4558                         if (adp->ad_state & DEPCOMPLETE)
4559                                 continue;
4560                         bp = adp->ad_buf;
4561                         if (getdirtybuf(&bp, waitfor) == 0) {
4562                                 if (waitfor == MNT_NOWAIT)
4563                                         continue;
4564                                 break;
4565                         }
4566                         FREE_LOCK(&lk);
4567                         if (waitfor == MNT_NOWAIT) {
4568                                 bawrite(bp);
4569                         } else if ((error = bwrite(bp)) != 0) {
4570                                 ACQUIRE_LOCK(&lk);
4571                                 return (error);
4572                         }
4573                         ACQUIRE_LOCK(&lk);
4574                         break;
4575                 }
4576                 if (adp != NULL)
4577                         continue;
4578                 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4579                         if (adp->ad_state & DEPCOMPLETE)
4580                                 continue;
4581                         bp = adp->ad_buf;
4582                         if (getdirtybuf(&bp, waitfor) == 0) {
4583                                 if (waitfor == MNT_NOWAIT)
4584                                         continue;
4585                                 break;
4586                         }
4587                         FREE_LOCK(&lk);
4588                         if (waitfor == MNT_NOWAIT) {
4589                                 bawrite(bp);
4590                         } else if ((error = bwrite(bp)) != 0) {
4591                                 ACQUIRE_LOCK(&lk);
4592                                 return (error);
4593                         }
4594                         ACQUIRE_LOCK(&lk);
4595                         break;
4596                 }
4597                 if (adp != NULL)
4598                         continue;
4599                 /*
4600                  * If pass2, we are done, otherwise do pass 2.
4601                  */
4602                 if (waitfor == MNT_WAIT)
4603                         break;
4604                 waitfor = MNT_WAIT;
4605         }
4606         /*
4607          * Try freeing inodedep in case all dependencies have been removed.
4608          */
4609         if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4610                 (void) free_inodedep(inodedep);
4611         return (0);
4612 }
4613
4614 /*
4615  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4616  * Called with splbio blocked.
4617  */
4618 static int
4619 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4620                    struct diraddhd *diraddhdp)
4621 {
4622         struct inodedep *inodedep;
4623         struct ufsmount *ump;
4624         struct diradd *dap;
4625         struct vnode *vp;
4626         int gotit, error = 0;
4627         struct buf *bp;
4628         ino_t inum;
4629
4630         ump = VFSTOUFS(mp);
4631         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4632                 /*
4633                  * Flush ourselves if this directory entry
4634                  * has a MKDIR_PARENT dependency.
4635                  */
4636                 if (dap->da_state & MKDIR_PARENT) {
4637                         FREE_LOCK(&lk);
4638                         if ((error = ffs_update(pvp, 1)) != 0)
4639                                 break;
4640                         ACQUIRE_LOCK(&lk);
4641                         /*
4642                          * If that cleared dependencies, go on to next.
4643                          */
4644                         if (dap != LIST_FIRST(diraddhdp))
4645                                 continue;
4646                         if (dap->da_state & MKDIR_PARENT) {
4647                                 FREE_LOCK(&lk);
4648                                 panic("flush_pagedep_deps: MKDIR_PARENT");
4649                         }
4650                 }
4651                 /*
4652                  * A newly allocated directory must have its "." and
4653                  * ".." entries written out before its name can be
4654                  * committed in its parent. We do not want or need
4655                  * the full semantics of a synchronous VOP_FSYNC as
4656                  * that may end up here again, once for each directory
4657                  * level in the filesystem. Instead, we push the blocks
4658                  * and wait for them to clear. We have to fsync twice
4659                  * because the first call may choose to defer blocks
4660                  * that still have dependencies, but deferral will
4661                  * happen at most once.
4662                  */
4663                 inum = dap->da_newinum;
4664                 if (dap->da_state & MKDIR_BODY) {
4665                         FREE_LOCK(&lk);
4666                         if ((error = VFS_VGET(mp, inum, &vp)) != 0)
4667                                 break;
4668                         if ((error=VOP_FSYNC(vp, MNT_NOWAIT)) ||
4669                             (error=VOP_FSYNC(vp, MNT_NOWAIT))) {
4670                                 vput(vp);
4671                                 break;
4672                         }
4673                         drain_output(vp, 0);
4674                         vput(vp);
4675                         ACQUIRE_LOCK(&lk);
4676                         /*
4677                          * If that cleared dependencies, go on to next.
4678                          */
4679                         if (dap != LIST_FIRST(diraddhdp))
4680                                 continue;
4681                         if (dap->da_state & MKDIR_BODY) {
4682                                 FREE_LOCK(&lk);
4683                                 panic("flush_pagedep_deps: MKDIR_BODY");
4684                         }
4685                 }
4686                 /*
4687                  * Flush the inode on which the directory entry depends.
4688                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4689                  * the only remaining dependency is that the updated inode
4690                  * count must get pushed to disk. The inode has already
4691                  * been pushed into its inode buffer (via VOP_UPDATE) at
4692                  * the time of the reference count change. So we need only
4693                  * locate that buffer, ensure that there will be no rollback
4694                  * caused by a bitmap dependency, then write the inode buffer.
4695                  */
4696                 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4697                         FREE_LOCK(&lk);
4698                         panic("flush_pagedep_deps: lost inode");
4699                 }
4700                 /*
4701                  * If the inode still has bitmap dependencies,
4702                  * push them to disk.
4703                  */
4704                 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4705                         gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4706                         FREE_LOCK(&lk);
4707                         if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4708                                 break;
4709                         ACQUIRE_LOCK(&lk);
4710                         if (dap != LIST_FIRST(diraddhdp))
4711                                 continue;
4712                 }
4713                 /*
4714                  * If the inode is still sitting in a buffer waiting
4715                  * to be written, push it to disk.
4716                  */
4717                 FREE_LOCK(&lk);
4718                 if ((error = bread(ump->um_devvp,
4719                         fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4720                     (int)ump->um_fs->fs_bsize, &bp)) != 0)
4721                         break;
4722                 if ((error = bwrite(bp)) != 0)
4723                         break;
4724                 ACQUIRE_LOCK(&lk);
4725                 /*
4726                  * If we have failed to get rid of all the dependencies
4727                  * then something is seriously wrong.
4728                  */
4729                 if (dap == LIST_FIRST(diraddhdp)) {
4730                         FREE_LOCK(&lk);
4731                         panic("flush_pagedep_deps: flush failed");
4732                 }
4733         }
4734         if (error)
4735                 ACQUIRE_LOCK(&lk);
4736         return (error);
4737 }
4738
4739 /*
4740  * A large burst of file addition or deletion activity can drive the
4741  * memory load excessively high. First attempt to slow things down
4742  * using the techniques below. If that fails, this routine requests
4743  * the offending operations to fall back to running synchronously
4744  * until the memory load returns to a reasonable level.
4745  */
4746 int
4747 softdep_slowdown(struct vnode *vp)
4748 {
4749         int max_softdeps_hard;
4750
4751         max_softdeps_hard = max_softdeps * 11 / 10;
4752         if (num_dirrem < max_softdeps_hard / 2 &&
4753             num_inodedep < max_softdeps_hard)
4754                 return (0);
4755         stat_sync_limit_hit += 1;
4756         return (1);
4757 }
4758
4759 /*
4760  * If memory utilization has gotten too high, deliberately slow things
4761  * down and speed up the I/O processing.
4762  */
4763 static int
4764 request_cleanup(int resource, int islocked)
4765 {
4766         struct thread *td = curthread;          /* XXX */
4767
4768         /*
4769          * We never hold up the filesystem syncer process.
4770          */
4771         if (td == filesys_syncer)
4772                 return (0);
4773         /*
4774          * First check to see if the work list has gotten backlogged.
4775          * If it has, co-opt this process to help clean up two entries.
4776          * Because this process may hold inodes locked, we cannot
4777          * handle any remove requests that might block on a locked
4778          * inode as that could lead to deadlock.
4779          */
4780         if (num_on_worklist > max_softdeps / 10) {
4781                 if (islocked)
4782                         FREE_LOCK(&lk);
4783                 process_worklist_item(NULL, LK_NOWAIT);
4784                 process_worklist_item(NULL, LK_NOWAIT);
4785                 stat_worklist_push += 2;
4786                 if (islocked)
4787                         ACQUIRE_LOCK(&lk);
4788                 return(1);
4789         }
4790
4791         /*
4792          * If we are resource constrained on inode dependencies, try
4793          * flushing some dirty inodes. Otherwise, we are constrained
4794          * by file deletions, so try accelerating flushes of directories
4795          * with removal dependencies. We would like to do the cleanup
4796          * here, but we probably hold an inode locked at this point and 
4797          * that might deadlock against one that we try to clean. So,
4798          * the best that we can do is request the syncer daemon to do
4799          * the cleanup for us.
4800          */
4801         switch (resource) {
4802
4803         case FLUSH_INODES:
4804                 stat_ino_limit_push += 1;
4805                 req_clear_inodedeps += 1;
4806                 stat_countp = &stat_ino_limit_hit;
4807                 break;
4808
4809         case FLUSH_REMOVE:
4810                 stat_blk_limit_push += 1;
4811                 req_clear_remove += 1;
4812                 stat_countp = &stat_blk_limit_hit;
4813                 break;
4814
4815         default:
4816                 if (islocked)
4817                         FREE_LOCK(&lk);
4818                 panic("request_cleanup: unknown type");
4819         }
4820         /*
4821          * Hopefully the syncer daemon will catch up and awaken us.
4822          * We wait at most tickdelay before proceeding in any case.
4823          */
4824         if (islocked == 0)
4825                 ACQUIRE_LOCK(&lk);
4826         proc_waiting += 1;
4827         if (!callout_active(&handle))
4828                 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4829                               pause_timer, NULL);
4830         interlocked_sleep(&lk, SLEEP, (caddr_t)&proc_waiting, 0,
4831             "softupdate", 0);
4832         proc_waiting -= 1;
4833         if (islocked == 0)
4834                 FREE_LOCK(&lk);
4835         return (1);
4836 }
4837
4838 /*
4839  * Awaken processes pausing in request_cleanup and clear proc_waiting
4840  * to indicate that there is no longer a timer running.
4841  */
4842 void
4843 pause_timer(void *arg)
4844 {
4845         *stat_countp += 1;
4846         wakeup_one(&proc_waiting);
4847         if (proc_waiting > 0)
4848                 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4849                               pause_timer, NULL);
4850         else
4851                 callout_deactivate(&handle);
4852 }
4853
4854 /*
4855  * Flush out a directory with at least one removal dependency in an effort to
4856  * reduce the number of dirrem, freefile, and freeblks dependency structures.
4857  */
4858 static void
4859 clear_remove(struct thread *td)
4860 {
4861         struct pagedep_hashhead *pagedephd;
4862         struct pagedep *pagedep;
4863         static int next = 0;
4864         struct mount *mp;
4865         struct vnode *vp;
4866         int error, cnt;
4867         ino_t ino;
4868
4869         ACQUIRE_LOCK(&lk);
4870         for (cnt = 0; cnt < pagedep_hash; cnt++) {
4871                 pagedephd = &pagedep_hashtbl[next++];
4872                 if (next >= pagedep_hash)
4873                         next = 0;
4874                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4875                         if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4876                                 continue;
4877                         mp = pagedep->pd_mnt;
4878                         ino = pagedep->pd_ino;
4879                         FREE_LOCK(&lk);
4880                         if ((error = VFS_VGET(mp, ino, &vp)) != 0) {
4881                                 softdep_error("clear_remove: vget", error);
4882                                 return;
4883                         }
4884                         if ((error = VOP_FSYNC(vp, MNT_NOWAIT)))
4885                                 softdep_error("clear_remove: fsync", error);
4886                         drain_output(vp, 0);
4887                         vput(vp);
4888                         return;
4889                 }
4890         }
4891         FREE_LOCK(&lk);
4892 }
4893
4894 /*
4895  * Clear out a block of dirty inodes in an effort to reduce
4896  * the number of inodedep dependency structures.
4897  */
4898 struct clear_inodedeps_info {
4899         struct fs *fs;
4900         struct mount *mp;
4901 };
4902
4903 static int
4904 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4905 {
4906         struct clear_inodedeps_info *info = data;
4907
4908         if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4909                 info->mp = mp;
4910                 return(-1);
4911         }
4912         return(0);
4913 }
4914
4915 static void
4916 clear_inodedeps(struct thread *td)
4917 {
4918         struct clear_inodedeps_info info;
4919         struct inodedep_hashhead *inodedephd;
4920         struct inodedep *inodedep;
4921         static int next = 0;
4922         struct vnode *vp;
4923         struct fs *fs;
4924         int error, cnt;
4925         ino_t firstino, lastino, ino;
4926
4927         ACQUIRE_LOCK(&lk);
4928         /*
4929          * Pick a random inode dependency to be cleared.
4930          * We will then gather up all the inodes in its block 
4931          * that have dependencies and flush them out.
4932          */
4933         for (cnt = 0; cnt < inodedep_hash; cnt++) {
4934                 inodedephd = &inodedep_hashtbl[next++];
4935                 if (next >= inodedep_hash)
4936                         next = 0;
4937                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4938                         break;
4939         }
4940         if (inodedep == NULL) {
4941                 FREE_LOCK(&lk);
4942                 return;
4943         }
4944         /*
4945          * Ugly code to find mount point given pointer to superblock.
4946          */
4947         fs = inodedep->id_fs;
4948         info.mp = NULL;
4949         info.fs = fs;
4950         mountlist_scan(clear_inodedeps_mountlist_callback, 
4951                         &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4952         /*
4953          * Find the last inode in the block with dependencies.
4954          */
4955         firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4956         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4957                 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4958                         break;
4959         /*
4960          * Asynchronously push all but the last inode with dependencies.
4961          * Synchronously push the last inode with dependencies to ensure
4962          * that the inode block gets written to free up the inodedeps.
4963          */
4964         for (ino = firstino; ino <= lastino; ino++) {
4965                 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4966                         continue;
4967                 FREE_LOCK(&lk);
4968                 if ((error = VFS_VGET(info.mp, ino, &vp)) != 0) {
4969                         softdep_error("clear_inodedeps: vget", error);
4970                         return;
4971                 }
4972                 if (ino == lastino) {
4973                         if ((error = VOP_FSYNC(vp, MNT_WAIT)))
4974                                 softdep_error("clear_inodedeps: fsync1", error);
4975                 } else {
4976                         if ((error = VOP_FSYNC(vp, MNT_NOWAIT)))
4977                                 softdep_error("clear_inodedeps: fsync2", error);
4978                         drain_output(vp, 0);
4979                 }
4980                 vput(vp);
4981                 ACQUIRE_LOCK(&lk);
4982         }
4983         FREE_LOCK(&lk);
4984 }
4985
4986 /*
4987  * Function to determine if the buffer has outstanding dependencies
4988  * that will cause a roll-back if the buffer is written. If wantcount
4989  * is set, return number of dependencies, otherwise just yes or no.
4990  */
4991 static int
4992 softdep_count_dependencies(struct buf *bp, int wantcount)
4993 {
4994         struct worklist *wk;
4995         struct inodedep *inodedep;
4996         struct indirdep *indirdep;
4997         struct allocindir *aip;
4998         struct pagedep *pagedep;
4999         struct diradd *dap;
5000         int i, retval;
5001
5002         retval = 0;
5003         ACQUIRE_LOCK(&lk);
5004         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5005                 switch (wk->wk_type) {
5006
5007                 case D_INODEDEP:
5008                         inodedep = WK_INODEDEP(wk);
5009                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
5010                                 /* bitmap allocation dependency */
5011                                 retval += 1;
5012                                 if (!wantcount)
5013                                         goto out;
5014                         }
5015                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
5016                                 /* direct block pointer dependency */
5017                                 retval += 1;
5018                                 if (!wantcount)
5019                                         goto out;
5020                         }
5021                         continue;
5022
5023                 case D_INDIRDEP:
5024                         indirdep = WK_INDIRDEP(wk);
5025
5026                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
5027                                 /* indirect block pointer dependency */
5028                                 retval += 1;
5029                                 if (!wantcount)
5030                                         goto out;
5031                         }
5032                         continue;
5033
5034                 case D_PAGEDEP:
5035                         pagedep = WK_PAGEDEP(wk);
5036                         for (i = 0; i < DAHASHSZ; i++) {
5037
5038                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
5039                                         /* directory entry dependency */
5040                                         retval += 1;
5041                                         if (!wantcount)
5042                                                 goto out;
5043                                 }
5044                         }
5045                         continue;
5046
5047                 case D_BMSAFEMAP:
5048                 case D_ALLOCDIRECT:
5049                 case D_ALLOCINDIR:
5050                 case D_MKDIR:
5051                         /* never a dependency on these blocks */
5052                         continue;
5053
5054                 default:
5055                         FREE_LOCK(&lk);
5056                         panic("softdep_check_for_rollback: Unexpected type %s",
5057                             TYPENAME(wk->wk_type));
5058                         /* NOTREACHED */
5059                 }
5060         }
5061 out:
5062         FREE_LOCK(&lk);
5063         return retval;
5064 }
5065
5066 /*
5067  * Acquire exclusive access to a buffer.
5068  * Must be called with splbio blocked.
5069  * Return 1 if buffer was acquired.
5070  */
5071 static int
5072 getdirtybuf(struct buf **bpp, int waitfor)
5073 {
5074         struct buf *bp;
5075         int error;
5076
5077         for (;;) {
5078                 if ((bp = *bpp) == NULL)
5079                         return (0);
5080                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0)
5081                         break;
5082                 if (waitfor != MNT_WAIT)
5083                         return (0);
5084                 error = interlocked_sleep(&lk, LOCKBUF, bp,
5085                     LK_EXCLUSIVE | LK_SLEEPFAIL, 0, 0);
5086                 if (error != ENOLCK) {
5087                         FREE_LOCK(&lk);
5088                         panic("getdirtybuf: inconsistent lock");
5089                 }
5090         }
5091         if ((bp->b_flags & B_DELWRI) == 0) {
5092                 BUF_UNLOCK(bp);
5093                 return (0);
5094         }
5095         bremfree(bp);
5096         return (1);
5097 }
5098
5099 /*
5100  * Wait for pending output on a vnode to complete.
5101  * Must be called with vnode locked.
5102  */
5103 static void
5104 drain_output(struct vnode *vp, int islocked)
5105 {
5106
5107         if (!islocked)
5108                 ACQUIRE_LOCK(&lk);
5109         while (vp->v_track_write.bk_active) {
5110                 vp->v_track_write.bk_waitflag = 1;
5111                 interlocked_sleep(&lk, SLEEP, &vp->v_track_write,
5112                                   0, "drainvp", 0);
5113         }
5114         if (!islocked)
5115                 FREE_LOCK(&lk);
5116 }
5117
5118 /*
5119  * Called whenever a buffer that is being invalidated or reallocated
5120  * contains dependencies. This should only happen if an I/O error has
5121  * occurred. The routine is called with the buffer locked.
5122  */ 
5123 static void
5124 softdep_deallocate_dependencies(struct buf *bp)
5125 {
5126         if ((bp->b_flags & B_ERROR) == 0)
5127                 panic("softdep_deallocate_dependencies: dangling deps");
5128         softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5129         panic("softdep_deallocate_dependencies: unrecovered I/O error");
5130 }
5131
5132 /*
5133  * Function to handle asynchronous write errors in the filesystem.
5134  */
5135 void
5136 softdep_error(char *func, int error)
5137 {
5138
5139         /* XXX should do something better! */
5140         kprintf("%s: got error %d while accessing filesystem\n", func, error);
5141 }