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