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