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