kernel -- ffs: Replace softupdates critical section locks with lockmgr.
[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, 0);
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         marker.wk_type = D_LAST + 1;    /* Not a normal workitem */
3028         
3029         /*
3030          * Do any necessary pre-I/O processing.
3031          */
3032         for (wk = LIST_FIRST(&bp->b_dep); wk; wk = markernext(&marker)) {
3033                 LIST_INSERT_AFTER(wk, &marker, wk_list);
3034
3035                 switch (wk->wk_type) {
3036                 case D_PAGEDEP:
3037                         initiate_write_filepage(WK_PAGEDEP(wk), bp);
3038                         continue;
3039
3040                 case D_INODEDEP:
3041                         initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3042                         continue;
3043
3044                 case D_INDIRDEP:
3045                         indirdep = WK_INDIRDEP(wk);
3046                         if (indirdep->ir_state & GOINGAWAY)
3047                                 panic("disk_io_initiation: indirdep gone");
3048                         /*
3049                          * If there are no remaining dependencies, this
3050                          * will be writing the real pointers, so the
3051                          * dependency can be freed.
3052                          */
3053                         if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3054                                 indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3055                                 brelse(indirdep->ir_savebp);
3056                                 /* inline expand WORKLIST_REMOVE(wk); */
3057                                 wk->wk_state &= ~ONWORKLIST;
3058                                 LIST_REMOVE(wk, wk_list);
3059                                 WORKITEM_FREE(indirdep, D_INDIRDEP);
3060                                 continue;
3061                         }
3062                         /*
3063                          * Replace up-to-date version with safe version.
3064                          */
3065                         indirdep->ir_saveddata = kmalloc(bp->b_bcount,
3066                                                          M_INDIRDEP,
3067                                                          M_SOFTDEP_FLAGS);
3068                         ACQUIRE_LOCK(&lk);
3069                         indirdep->ir_state &= ~ATTACHED;
3070                         indirdep->ir_state |= UNDONE;
3071                         bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3072                         bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3073                             bp->b_bcount);
3074                         FREE_LOCK(&lk);
3075                         continue;
3076
3077                 case D_MKDIR:
3078                 case D_BMSAFEMAP:
3079                 case D_ALLOCDIRECT:
3080                 case D_ALLOCINDIR:
3081                         continue;
3082
3083                 default:
3084                         panic("handle_disk_io_initiation: Unexpected type %s",
3085                             TYPENAME(wk->wk_type));
3086                         /* NOTREACHED */
3087                 }
3088         }
3089         rel_mplock();
3090 }
3091
3092 /*
3093  * Called from within the procedure above to deal with unsatisfied
3094  * allocation dependencies in a directory. The buffer must be locked,
3095  * thus, no I/O completion operations can occur while we are
3096  * manipulating its associated dependencies.
3097  */
3098 static void
3099 initiate_write_filepage(struct pagedep *pagedep, struct buf *bp)
3100 {
3101         struct diradd *dap;
3102         struct direct *ep;
3103         int i;
3104
3105         if (pagedep->pd_state & IOSTARTED) {
3106                 /*
3107                  * This can only happen if there is a driver that does not
3108                  * understand chaining. Here biodone will reissue the call
3109                  * to strategy for the incomplete buffers.
3110                  */
3111                 kprintf("initiate_write_filepage: already started\n");
3112                 return;
3113         }
3114         pagedep->pd_state |= IOSTARTED;
3115         ACQUIRE_LOCK(&lk);
3116         for (i = 0; i < DAHASHSZ; i++) {
3117                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3118                         ep = (struct direct *)
3119                             ((char *)bp->b_data + dap->da_offset);
3120                         if (ep->d_ino != dap->da_newinum) {
3121                                 FREE_LOCK(&lk);
3122                                 panic("%s: dir inum %d != new %"PRId64,
3123                                     "initiate_write_filepage",
3124                                     ep->d_ino, dap->da_newinum);
3125                         }
3126                         if (dap->da_state & DIRCHG)
3127                                 ep->d_ino = dap->da_previous->dm_oldinum;
3128                         else
3129                                 ep->d_ino = 0;
3130                         dap->da_state &= ~ATTACHED;
3131                         dap->da_state |= UNDONE;
3132                 }
3133         }
3134         FREE_LOCK(&lk);
3135 }
3136
3137 /*
3138  * Called from within the procedure above to deal with unsatisfied
3139  * allocation dependencies in an inodeblock. The buffer must be
3140  * locked, thus, no I/O completion operations can occur while we
3141  * are manipulating its associated dependencies.
3142  *
3143  * Parameters:
3144  *      bp:     The inode block
3145  */
3146 static void 
3147 initiate_write_inodeblock(struct inodedep *inodedep, struct buf *bp)
3148 {
3149         struct allocdirect *adp, *lastadp;
3150         struct ufs1_dinode *dp;
3151         struct ufs1_dinode *sip;
3152         struct fs *fs;
3153         ufs_lbn_t prevlbn = 0;
3154         int i, deplist;
3155
3156         if (inodedep->id_state & IOSTARTED)
3157                 panic("initiate_write_inodeblock: already started");
3158         inodedep->id_state |= IOSTARTED;
3159         fs = inodedep->id_fs;
3160         dp = (struct ufs1_dinode *)bp->b_data +
3161             ino_to_fsbo(fs, inodedep->id_ino);
3162         /*
3163          * If the bitmap is not yet written, then the allocated
3164          * inode cannot be written to disk.
3165          */
3166         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3167                 if (inodedep->id_savedino != NULL)
3168                         panic("initiate_write_inodeblock: already doing I/O");
3169                 sip = kmalloc(sizeof(struct ufs1_dinode), M_INODEDEP,
3170                               M_SOFTDEP_FLAGS);
3171                 inodedep->id_savedino = sip;
3172                 *inodedep->id_savedino = *dp;
3173                 bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
3174                 dp->di_gen = inodedep->id_savedino->di_gen;
3175                 return;
3176         }
3177         /*
3178          * If no dependencies, then there is nothing to roll back.
3179          */
3180         inodedep->id_savedsize = dp->di_size;
3181         if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3182                 return;
3183         /*
3184          * Set the dependencies to busy.
3185          */
3186         ACQUIRE_LOCK(&lk);
3187         for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3188              adp = TAILQ_NEXT(adp, ad_next)) {
3189 #ifdef DIAGNOSTIC
3190                 if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3191                         FREE_LOCK(&lk);
3192                         panic("softdep_write_inodeblock: lbn order");
3193                 }
3194                 prevlbn = adp->ad_lbn;
3195                 if (adp->ad_lbn < NDADDR &&
3196                     dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3197                         FREE_LOCK(&lk);
3198                         panic("%s: direct pointer #%ld mismatch %d != %d",
3199                             "softdep_write_inodeblock", adp->ad_lbn,
3200                             dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3201                 }
3202                 if (adp->ad_lbn >= NDADDR &&
3203                     dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3204                         FREE_LOCK(&lk);
3205                         panic("%s: indirect pointer #%ld mismatch %d != %d",
3206                             "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3207                             dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3208                 }
3209                 deplist |= 1 << adp->ad_lbn;
3210                 if ((adp->ad_state & ATTACHED) == 0) {
3211                         FREE_LOCK(&lk);
3212                         panic("softdep_write_inodeblock: Unknown state 0x%x",
3213                             adp->ad_state);
3214                 }
3215 #endif /* DIAGNOSTIC */
3216                 adp->ad_state &= ~ATTACHED;
3217                 adp->ad_state |= UNDONE;
3218         }
3219         /*
3220          * The on-disk inode cannot claim to be any larger than the last
3221          * fragment that has been written. Otherwise, the on-disk inode
3222          * might have fragments that were not the last block in the file
3223          * which would corrupt the filesystem.
3224          */
3225         for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3226              lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3227                 if (adp->ad_lbn >= NDADDR)
3228                         break;
3229                 dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3230                 /* keep going until hitting a rollback to a frag */
3231                 if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3232                         continue;
3233                 dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3234                 for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3235 #ifdef DIAGNOSTIC
3236                         if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3237                                 FREE_LOCK(&lk);
3238                                 panic("softdep_write_inodeblock: lost dep1");
3239                         }
3240 #endif /* DIAGNOSTIC */
3241                         dp->di_db[i] = 0;
3242                 }
3243                 for (i = 0; i < NIADDR; i++) {
3244 #ifdef DIAGNOSTIC
3245                         if (dp->di_ib[i] != 0 &&
3246                             (deplist & ((1 << NDADDR) << i)) == 0) {
3247                                 FREE_LOCK(&lk);
3248                                 panic("softdep_write_inodeblock: lost dep2");
3249                         }
3250 #endif /* DIAGNOSTIC */
3251                         dp->di_ib[i] = 0;
3252                 }
3253                 FREE_LOCK(&lk);
3254                 return;
3255         }
3256         /*
3257          * If we have zero'ed out the last allocated block of the file,
3258          * roll back the size to the last currently allocated block.
3259          * We know that this last allocated block is a full-sized as
3260          * we already checked for fragments in the loop above.
3261          */
3262         if (lastadp != NULL &&
3263             dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3264                 for (i = lastadp->ad_lbn; i >= 0; i--)
3265                         if (dp->di_db[i] != 0)
3266                                 break;
3267                 dp->di_size = (i + 1) * fs->fs_bsize;
3268         }
3269         /*
3270          * The only dependencies are for indirect blocks.
3271          *
3272          * The file size for indirect block additions is not guaranteed.
3273          * Such a guarantee would be non-trivial to achieve. The conventional
3274          * synchronous write implementation also does not make this guarantee.
3275          * Fsck should catch and fix discrepancies. Arguably, the file size
3276          * can be over-estimated without destroying integrity when the file
3277          * moves into the indirect blocks (i.e., is large). If we want to
3278          * postpone fsck, we are stuck with this argument.
3279          */
3280         for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3281                 dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3282         FREE_LOCK(&lk);
3283 }
3284
3285 /*
3286  * This routine is called during the completion interrupt
3287  * service routine for a disk write (from the procedure called
3288  * by the device driver to inform the filesystem caches of
3289  * a request completion).  It should be called early in this
3290  * procedure, before the block is made available to other
3291  * processes or other routines are called.
3292  *
3293  * bioops callback - hold io_token
3294  *
3295  * Parameters:
3296  *      bp:     describes the completed disk write
3297  */
3298 static void 
3299 softdep_disk_write_complete(struct buf *bp)
3300 {
3301         struct worklist *wk;
3302         struct workhead reattach;
3303         struct newblk *newblk;
3304         struct allocindir *aip;
3305         struct allocdirect *adp;
3306         struct indirdep *indirdep;
3307         struct inodedep *inodedep;
3308         struct bmsafemap *bmsafemap;
3309
3310         ACQUIRE_LOCK(&lk);
3311
3312         LIST_INIT(&reattach);
3313         while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3314                 WORKLIST_REMOVE(wk);
3315                 switch (wk->wk_type) {
3316
3317                 case D_PAGEDEP:
3318                         if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3319                                 WORKLIST_INSERT(&reattach, wk);
3320                         continue;
3321
3322                 case D_INODEDEP:
3323                         if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3324                                 WORKLIST_INSERT(&reattach, wk);
3325                         continue;
3326
3327                 case D_BMSAFEMAP:
3328                         bmsafemap = WK_BMSAFEMAP(wk);
3329                         while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3330                                 newblk->nb_state |= DEPCOMPLETE;
3331                                 newblk->nb_bmsafemap = NULL;
3332                                 LIST_REMOVE(newblk, nb_deps);
3333                         }
3334                         while ((adp =
3335                            LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3336                                 adp->ad_state |= DEPCOMPLETE;
3337                                 adp->ad_buf = NULL;
3338                                 LIST_REMOVE(adp, ad_deps);
3339                                 handle_allocdirect_partdone(adp);
3340                         }
3341                         while ((aip =
3342                             LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3343                                 aip->ai_state |= DEPCOMPLETE;
3344                                 aip->ai_buf = NULL;
3345                                 LIST_REMOVE(aip, ai_deps);
3346                                 handle_allocindir_partdone(aip);
3347                         }
3348                         while ((inodedep =
3349                              LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3350                                 inodedep->id_state |= DEPCOMPLETE;
3351                                 LIST_REMOVE(inodedep, id_deps);
3352                                 inodedep->id_buf = NULL;
3353                         }
3354                         WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3355                         continue;
3356
3357                 case D_MKDIR:
3358                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3359                         continue;
3360
3361                 case D_ALLOCDIRECT:
3362                         adp = WK_ALLOCDIRECT(wk);
3363                         adp->ad_state |= COMPLETE;
3364                         handle_allocdirect_partdone(adp);
3365                         continue;
3366
3367                 case D_ALLOCINDIR:
3368                         aip = WK_ALLOCINDIR(wk);
3369                         aip->ai_state |= COMPLETE;
3370                         handle_allocindir_partdone(aip);
3371                         continue;
3372
3373                 case D_INDIRDEP:
3374                         indirdep = WK_INDIRDEP(wk);
3375                         if (indirdep->ir_state & GOINGAWAY) {
3376                                 panic("disk_write_complete: indirdep gone");
3377                         }
3378                         bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3379                         kfree(indirdep->ir_saveddata, M_INDIRDEP);
3380                         indirdep->ir_saveddata = 0;
3381                         indirdep->ir_state &= ~UNDONE;
3382                         indirdep->ir_state |= ATTACHED;
3383                         while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
3384                                 handle_allocindir_partdone(aip);
3385                                 if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3386                                         panic("disk_write_complete: not gone");
3387                                 }
3388                         }
3389                         WORKLIST_INSERT(&reattach, wk);
3390                         if ((bp->b_flags & B_DELWRI) == 0)
3391                                 stat_indir_blk_ptrs++;
3392                         bdirty(bp);
3393                         continue;
3394
3395                 default:
3396                         panic("handle_disk_write_complete: Unknown type %s",
3397                             TYPENAME(wk->wk_type));
3398                         /* NOTREACHED */
3399                 }
3400         }
3401         /*
3402          * Reattach any requests that must be redone.
3403          */
3404         while ((wk = LIST_FIRST(&reattach)) != NULL) {
3405                 WORKLIST_REMOVE(wk);
3406                 WORKLIST_INSERT_BP(bp, wk);
3407         }
3408
3409         FREE_LOCK(&lk);
3410 }
3411
3412 /*
3413  * Called from within softdep_disk_write_complete above. Note that
3414  * this routine is always called from interrupt level with further
3415  * splbio interrupts blocked.
3416  *
3417  * Parameters:
3418  *      adp:    the completed allocdirect
3419  */
3420 static void 
3421 handle_allocdirect_partdone(struct allocdirect *adp)
3422 {
3423         struct allocdirect *listadp;
3424         struct inodedep *inodedep;
3425         long bsize;
3426
3427         if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3428                 return;
3429         if (adp->ad_buf != NULL) 
3430                 panic("handle_allocdirect_partdone: dangling dep");
3431         
3432         /*
3433          * The on-disk inode cannot claim to be any larger than the last
3434          * fragment that has been written. Otherwise, the on-disk inode
3435          * might have fragments that were not the last block in the file
3436          * which would corrupt the filesystem. Thus, we cannot free any
3437          * allocdirects after one whose ad_oldblkno claims a fragment as
3438          * these blocks must be rolled back to zero before writing the inode.
3439          * We check the currently active set of allocdirects in id_inoupdt.
3440          */
3441         inodedep = adp->ad_inodedep;
3442         bsize = inodedep->id_fs->fs_bsize;
3443         TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3444                 /* found our block */
3445                 if (listadp == adp)
3446                         break;
3447                 /* continue if ad_oldlbn is not a fragment */
3448                 if (listadp->ad_oldsize == 0 ||
3449                     listadp->ad_oldsize == bsize)
3450                         continue;
3451                 /* hit a fragment */
3452                 return;
3453         }
3454         /*
3455          * If we have reached the end of the current list without
3456          * finding the just finished dependency, then it must be
3457          * on the future dependency list. Future dependencies cannot
3458          * be freed until they are moved to the current list.
3459          */
3460         if (listadp == NULL) {
3461 #ifdef DEBUG
3462                 TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3463                         /* found our block */
3464                         if (listadp == adp)
3465                                 break;
3466                 if (listadp == NULL) 
3467                         panic("handle_allocdirect_partdone: lost dep");
3468 #endif /* DEBUG */
3469                 return;
3470         }
3471         /*
3472          * If we have found the just finished dependency, then free
3473          * it along with anything that follows it that is complete.
3474          */
3475         for (; adp; adp = listadp) {
3476                 listadp = TAILQ_NEXT(adp, ad_next);
3477                 if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3478                         return;
3479                 free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3480         }
3481 }
3482
3483 /*
3484  * Called from within softdep_disk_write_complete above. Note that
3485  * this routine is always called from interrupt level with further
3486  * splbio interrupts blocked.
3487  *
3488  * Parameters:
3489  *      aip:    the completed allocindir
3490  */
3491 static void
3492 handle_allocindir_partdone(struct allocindir *aip)
3493 {
3494         struct indirdep *indirdep;
3495
3496         if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3497                 return;
3498         if (aip->ai_buf != NULL) 
3499                 panic("handle_allocindir_partdone: dangling dependency");
3500         
3501         indirdep = aip->ai_indirdep;
3502         if (indirdep->ir_state & UNDONE) {
3503                 LIST_REMOVE(aip, ai_next);
3504                 LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3505                 return;
3506         }
3507         ((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3508             aip->ai_newblkno;
3509         LIST_REMOVE(aip, ai_next);
3510         if (aip->ai_freefrag != NULL)
3511                 add_to_worklist(&aip->ai_freefrag->ff_list);
3512         WORKITEM_FREE(aip, D_ALLOCINDIR);
3513 }
3514
3515 /*
3516  * Called from within softdep_disk_write_complete above to restore
3517  * in-memory inode block contents to their most up-to-date state. Note
3518  * that this routine is always called from interrupt level with further
3519  * splbio interrupts blocked.
3520  *
3521  * Parameters:
3522  *      bp:     buffer containing the inode block
3523  */
3524 static int 
3525 handle_written_inodeblock(struct inodedep *inodedep, struct buf *bp)
3526 {
3527         struct worklist *wk, *filefree;
3528         struct allocdirect *adp, *nextadp;
3529         struct ufs1_dinode *dp;
3530         int hadchanges;
3531
3532         if ((inodedep->id_state & IOSTARTED) == 0) 
3533                 panic("handle_written_inodeblock: not started");
3534         
3535         inodedep->id_state &= ~IOSTARTED;
3536         dp = (struct ufs1_dinode *)bp->b_data +
3537             ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3538         /*
3539          * If we had to rollback the inode allocation because of
3540          * bitmaps being incomplete, then simply restore it.
3541          * Keep the block dirty so that it will not be reclaimed until
3542          * all associated dependencies have been cleared and the
3543          * corresponding updates written to disk.
3544          */
3545         if (inodedep->id_savedino != NULL) {
3546                 *dp = *inodedep->id_savedino;
3547                 kfree(inodedep->id_savedino, M_INODEDEP);
3548                 inodedep->id_savedino = NULL;
3549                 if ((bp->b_flags & B_DELWRI) == 0)
3550                         stat_inode_bitmap++;
3551                 bdirty(bp);
3552                 return (1);
3553         }
3554         inodedep->id_state |= COMPLETE;
3555         /*
3556          * Roll forward anything that had to be rolled back before 
3557          * the inode could be updated.
3558          */
3559         hadchanges = 0;
3560         for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3561                 nextadp = TAILQ_NEXT(adp, ad_next);
3562                 if (adp->ad_state & ATTACHED) 
3563                         panic("handle_written_inodeblock: new entry");
3564                 
3565                 if (adp->ad_lbn < NDADDR) {
3566                         if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3567                                 panic("%s: %s #%ld mismatch %d != %d",
3568                                     "handle_written_inodeblock",
3569                                     "direct pointer", adp->ad_lbn,
3570                                     dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3571                         }
3572                         dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3573                 } else {
3574                         if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3575                                 panic("%s: %s #%ld allocated as %d",
3576                                     "handle_written_inodeblock",
3577                                     "indirect pointer", adp->ad_lbn - NDADDR,
3578                                     dp->di_ib[adp->ad_lbn - NDADDR]);
3579                         }
3580                         dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3581                 }
3582                 adp->ad_state &= ~UNDONE;
3583                 adp->ad_state |= ATTACHED;
3584                 hadchanges = 1;
3585         }
3586         if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3587                 stat_direct_blk_ptrs++;
3588         /*
3589          * Reset the file size to its most up-to-date value.
3590          */
3591         if (inodedep->id_savedsize == -1) {
3592                 panic("handle_written_inodeblock: bad size");
3593         }
3594         if (dp->di_size != inodedep->id_savedsize) {
3595                 dp->di_size = inodedep->id_savedsize;
3596                 hadchanges = 1;
3597         }
3598         inodedep->id_savedsize = -1;
3599         /*
3600          * If there were any rollbacks in the inode block, then it must be
3601          * marked dirty so that its will eventually get written back in
3602          * its correct form.
3603          */
3604         if (hadchanges)
3605                 bdirty(bp);
3606         /*
3607          * Process any allocdirects that completed during the update.
3608          */
3609         if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3610                 handle_allocdirect_partdone(adp);
3611         /*
3612          * Process deallocations that were held pending until the
3613          * inode had been written to disk. Freeing of the inode
3614          * is delayed until after all blocks have been freed to
3615          * avoid creation of new <vfsid, inum, lbn> triples
3616          * before the old ones have been deleted.
3617          */
3618         filefree = NULL;
3619         while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3620                 WORKLIST_REMOVE(wk);
3621                 switch (wk->wk_type) {
3622
3623                 case D_FREEFILE:
3624                         /*
3625                          * We defer adding filefree to the worklist until
3626                          * all other additions have been made to ensure
3627                          * that it will be done after all the old blocks
3628                          * have been freed.
3629                          */
3630                         if (filefree != NULL) {
3631                                 panic("handle_written_inodeblock: filefree");
3632                         }
3633                         filefree = wk;
3634                         continue;
3635
3636                 case D_MKDIR:
3637                         handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3638                         continue;
3639
3640                 case D_DIRADD:
3641                         diradd_inode_written(WK_DIRADD(wk), inodedep);
3642                         continue;
3643
3644                 case D_FREEBLKS:
3645                         wk->wk_state |= COMPLETE;
3646                         if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
3647                                 continue;
3648                         /* -- fall through -- */
3649                 case D_FREEFRAG:
3650                 case D_DIRREM:
3651                         add_to_worklist(wk);
3652                         continue;
3653
3654                 default:
3655                         panic("handle_written_inodeblock: Unknown type %s",
3656                             TYPENAME(wk->wk_type));
3657                         /* NOTREACHED */
3658                 }
3659         }
3660         if (filefree != NULL) {
3661                 if (free_inodedep(inodedep) == 0) {
3662                         panic("handle_written_inodeblock: live inodedep");
3663                 }
3664                 add_to_worklist(filefree);
3665                 return (0);
3666         }
3667
3668         /*
3669          * If no outstanding dependencies, free it.
3670          */
3671         if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3672                 return (0);
3673         return (hadchanges);
3674 }
3675
3676 /*
3677  * Process a diradd entry after its dependent inode has been written.
3678  * This routine must be called with splbio interrupts blocked.
3679  */
3680 static void
3681 diradd_inode_written(struct diradd *dap, struct inodedep *inodedep)
3682 {
3683         struct pagedep *pagedep;
3684
3685         dap->da_state |= COMPLETE;
3686         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3687                 if (dap->da_state & DIRCHG)
3688                         pagedep = dap->da_previous->dm_pagedep;
3689                 else
3690                         pagedep = dap->da_pagedep;
3691                 LIST_REMOVE(dap, da_pdlist);
3692                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3693         }
3694         WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3695 }
3696
3697 /*
3698  * Handle the completion of a mkdir dependency.
3699  */
3700 static void
3701 handle_written_mkdir(struct mkdir *mkdir, int type)
3702 {
3703         struct diradd *dap;
3704         struct pagedep *pagedep;
3705
3706         if (mkdir->md_state != type) {
3707                 panic("handle_written_mkdir: bad type");
3708         }
3709         dap = mkdir->md_diradd;
3710         dap->da_state &= ~type;
3711         if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3712                 dap->da_state |= DEPCOMPLETE;
3713         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3714                 if (dap->da_state & DIRCHG)
3715                         pagedep = dap->da_previous->dm_pagedep;
3716                 else
3717                         pagedep = dap->da_pagedep;
3718                 LIST_REMOVE(dap, da_pdlist);
3719                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3720         }
3721         LIST_REMOVE(mkdir, md_mkdirs);
3722         WORKITEM_FREE(mkdir, D_MKDIR);
3723 }
3724
3725 /*
3726  * Called from within softdep_disk_write_complete above.
3727  * A write operation was just completed. Removed inodes can
3728  * now be freed and associated block pointers may be committed.
3729  * Note that this routine is always called from interrupt level
3730  * with further splbio interrupts blocked.
3731  *
3732  * Parameters:
3733  *      bp:     buffer containing the written page
3734  */
3735 static int 
3736 handle_written_filepage(struct pagedep *pagedep, struct buf *bp)
3737 {
3738         struct dirrem *dirrem;
3739         struct diradd *dap, *nextdap;
3740         struct direct *ep;
3741         int i, chgs;
3742
3743         if ((pagedep->pd_state & IOSTARTED) == 0) {
3744                 panic("handle_written_filepage: not started");
3745         }
3746         pagedep->pd_state &= ~IOSTARTED;
3747         /*
3748          * Process any directory removals that have been committed.
3749          */
3750         while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3751                 LIST_REMOVE(dirrem, dm_next);
3752                 dirrem->dm_dirinum = pagedep->pd_ino;
3753                 add_to_worklist(&dirrem->dm_list);
3754         }
3755         /*
3756          * Free any directory additions that have been committed.
3757          */
3758         while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3759                 free_diradd(dap);
3760         /*
3761          * Uncommitted directory entries must be restored.
3762          */
3763         for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3764                 for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3765                      dap = nextdap) {
3766                         nextdap = LIST_NEXT(dap, da_pdlist);
3767                         if (dap->da_state & ATTACHED) {
3768                                 panic("handle_written_filepage: attached");
3769                         }
3770                         ep = (struct direct *)
3771                             ((char *)bp->b_data + dap->da_offset);
3772                         ep->d_ino = dap->da_newinum;
3773                         dap->da_state &= ~UNDONE;
3774                         dap->da_state |= ATTACHED;
3775                         chgs = 1;
3776                         /*
3777                          * If the inode referenced by the directory has
3778                          * been written out, then the dependency can be
3779                          * moved to the pending list.
3780                          */
3781                         if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3782                                 LIST_REMOVE(dap, da_pdlist);
3783                                 LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3784                                     da_pdlist);
3785                         }
3786                 }
3787         }
3788         /*
3789          * If there were any rollbacks in the directory, then it must be
3790          * marked dirty so that its will eventually get written back in
3791          * its correct form.
3792          */
3793         if (chgs) {
3794                 if ((bp->b_flags & B_DELWRI) == 0)
3795                         stat_dir_entry++;
3796                 bdirty(bp);
3797         }
3798         /*
3799          * If no dependencies remain, the pagedep will be freed.
3800          * Otherwise it will remain to update the page before it
3801          * is written back to disk.
3802          */
3803         if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3804                 for (i = 0; i < DAHASHSZ; i++)
3805                         if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3806                                 break;
3807                 if (i == DAHASHSZ) {
3808                         LIST_REMOVE(pagedep, pd_hash);
3809                         WORKITEM_FREE(pagedep, D_PAGEDEP);
3810                         return (0);
3811                 }
3812         }
3813         return (1);
3814 }
3815
3816 /*
3817  * Writing back in-core inode structures.
3818  * 
3819  * The filesystem only accesses an inode's contents when it occupies an
3820  * "in-core" inode structure.  These "in-core" structures are separate from
3821  * the page frames used to cache inode blocks.  Only the latter are
3822  * transferred to/from the disk.  So, when the updated contents of the
3823  * "in-core" inode structure are copied to the corresponding in-memory inode
3824  * block, the dependencies are also transferred.  The following procedure is
3825  * called when copying a dirty "in-core" inode to a cached inode block.
3826  */
3827
3828 /*
3829  * Called when an inode is loaded from disk. If the effective link count
3830  * differed from the actual link count when it was last flushed, then we
3831  * need to ensure that the correct effective link count is put back.
3832  *
3833  * Parameters:
3834  *      ip:     the "in_core" copy of the inode
3835  */
3836 void 
3837 softdep_load_inodeblock(struct inode *ip)
3838 {
3839         struct inodedep *inodedep;
3840
3841         /*
3842          * Check for alternate nlink count.
3843          */
3844         ip->i_effnlink = ip->i_nlink;
3845         ACQUIRE_LOCK(&lk);
3846         if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3847                 FREE_LOCK(&lk);
3848                 return;
3849         }
3850         ip->i_effnlink -= inodedep->id_nlinkdelta;
3851         FREE_LOCK(&lk);
3852 }
3853
3854 /*
3855  * This routine is called just before the "in-core" inode
3856  * information is to be copied to the in-memory inode block.
3857  * Recall that an inode block contains several inodes. If
3858  * the force flag is set, then the dependencies will be
3859  * cleared so that the update can always be made. Note that
3860  * the buffer is locked when this routine is called, so we
3861  * will never be in the middle of writing the inode block 
3862  * to disk.
3863  *
3864  * Parameters:
3865  *      ip:             the "in_core" copy of the inode
3866  *      bp:             the buffer containing the inode block
3867  *      waitfor:        nonzero => update must be allowed
3868  */
3869 void 
3870 softdep_update_inodeblock(struct inode *ip, struct buf *bp,
3871                           int waitfor)
3872 {
3873         struct inodedep *inodedep;
3874         struct worklist *wk;
3875         int error, gotit;
3876
3877         /*
3878          * If the effective link count is not equal to the actual link
3879          * count, then we must track the difference in an inodedep while
3880          * the inode is (potentially) tossed out of the cache. Otherwise,
3881          * if there is no existing inodedep, then there are no dependencies
3882          * to track.
3883          */
3884         ACQUIRE_LOCK(&lk);
3885         if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3886                 FREE_LOCK(&lk);
3887                 if (ip->i_effnlink != ip->i_nlink)
3888                         panic("softdep_update_inodeblock: bad link count");
3889                 return;
3890         }
3891         if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3892                 FREE_LOCK(&lk);
3893                 panic("softdep_update_inodeblock: bad delta");
3894         }
3895         /*
3896          * Changes have been initiated. Anything depending on these
3897          * changes cannot occur until this inode has been written.
3898          */
3899         inodedep->id_state &= ~COMPLETE;
3900         if ((inodedep->id_state & ONWORKLIST) == 0)
3901                 WORKLIST_INSERT_BP(bp, &inodedep->id_list);
3902         /*
3903          * Any new dependencies associated with the incore inode must 
3904          * now be moved to the list associated with the buffer holding
3905          * the in-memory copy of the inode. Once merged process any
3906          * allocdirects that are completed by the merger.
3907          */
3908         merge_inode_lists(inodedep);
3909         if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3910                 handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3911         /*
3912          * Now that the inode has been pushed into the buffer, the
3913          * operations dependent on the inode being written to disk
3914          * can be moved to the id_bufwait so that they will be
3915          * processed when the buffer I/O completes.
3916          */
3917         while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3918                 WORKLIST_REMOVE(wk);
3919                 WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3920         }
3921         /*
3922          * Newly allocated inodes cannot be written until the bitmap
3923          * that allocates them have been written (indicated by
3924          * DEPCOMPLETE being set in id_state). If we are doing a
3925          * forced sync (e.g., an fsync on a file), we force the bitmap
3926          * to be written so that the update can be done.
3927          */
3928         if (waitfor == 0) {
3929                 FREE_LOCK(&lk);
3930                 return;
3931         }
3932 retry:
3933         if ((inodedep->id_state & DEPCOMPLETE) != 0) {
3934                 FREE_LOCK(&lk);
3935                 return;
3936         }
3937         gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3938         if (gotit == 0) {
3939                 if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) != 0)
3940                         goto retry;
3941                 FREE_LOCK(&lk);
3942                 return;
3943         }
3944         FREE_LOCK(&lk);
3945         if ((error = bwrite(inodedep->id_buf)) != 0)
3946                 softdep_error("softdep_update_inodeblock: bwrite", error);
3947 }
3948
3949 /*
3950  * Merge the new inode dependency list (id_newinoupdt) into the old
3951  * inode dependency list (id_inoupdt). This routine must be called
3952  * with splbio interrupts blocked.
3953  */
3954 static void
3955 merge_inode_lists(struct inodedep *inodedep)
3956 {
3957         struct allocdirect *listadp, *newadp;
3958
3959         newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3960         for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3961                 if (listadp->ad_lbn < newadp->ad_lbn) {
3962                         listadp = TAILQ_NEXT(listadp, ad_next);
3963                         continue;
3964                 }
3965                 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3966                 TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3967                 if (listadp->ad_lbn == newadp->ad_lbn) {
3968                         allocdirect_merge(&inodedep->id_inoupdt, newadp,
3969                             listadp);
3970                         listadp = newadp;
3971                 }
3972                 newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3973         }
3974         while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3975                 TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3976                 TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3977         }
3978 }
3979
3980 /*
3981  * If we are doing an fsync, then we must ensure that any directory
3982  * entries for the inode have been written after the inode gets to disk.
3983  *
3984  * bioops callback - hold io_token
3985  *
3986  * Parameters:
3987  *      vp:     the "in_core" copy of the inode
3988  */
3989 static int
3990 softdep_fsync(struct vnode *vp)
3991 {
3992         struct inodedep *inodedep;
3993         struct pagedep *pagedep;
3994         struct worklist *wk;
3995         struct diradd *dap;
3996         struct mount *mnt;
3997         struct vnode *pvp;
3998         struct inode *ip;
3999         struct buf *bp;
4000         struct fs *fs;
4001         int error, flushparent;
4002         ino_t parentino;
4003         ufs_lbn_t lbn;
4004
4005         /*
4006          * Move check from original kernel code, possibly not needed any
4007          * more with the per-mount bioops.
4008          */
4009         if ((vp->v_mount->mnt_flag & MNT_SOFTDEP) == 0)
4010                 return (0);
4011
4012         get_mplock();
4013         ip = VTOI(vp);
4014         fs = ip->i_fs;
4015         ACQUIRE_LOCK(&lk);
4016         if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
4017                 FREE_LOCK(&lk);
4018                 rel_mplock();
4019                 return (0);
4020         }
4021         if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
4022             LIST_FIRST(&inodedep->id_bufwait) != NULL ||
4023             TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
4024             TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
4025                 FREE_LOCK(&lk);
4026                 panic("softdep_fsync: pending ops");
4027         }
4028         for (error = 0, flushparent = 0; ; ) {
4029                 if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
4030                         break;
4031                 if (wk->wk_type != D_DIRADD) {
4032                         FREE_LOCK(&lk);
4033                         panic("softdep_fsync: Unexpected type %s",
4034                             TYPENAME(wk->wk_type));
4035                 }
4036                 dap = WK_DIRADD(wk);
4037                 /*
4038                  * Flush our parent if this directory entry
4039                  * has a MKDIR_PARENT dependency.
4040                  */
4041                 if (dap->da_state & DIRCHG)
4042                         pagedep = dap->da_previous->dm_pagedep;
4043                 else
4044                         pagedep = dap->da_pagedep;
4045                 mnt = pagedep->pd_mnt;
4046                 parentino = pagedep->pd_ino;
4047                 lbn = pagedep->pd_lbn;
4048                 if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4049                         FREE_LOCK(&lk);
4050                         panic("softdep_fsync: dirty");
4051                 }
4052                 flushparent = dap->da_state & MKDIR_PARENT;
4053                 /*
4054                  * If we are being fsync'ed as part of vgone'ing this vnode,
4055                  * then we will not be able to release and recover the
4056                  * vnode below, so we just have to give up on writing its
4057                  * directory entry out. It will eventually be written, just
4058                  * not now, but then the user was not asking to have it
4059                  * written, so we are not breaking any promises.
4060                  */
4061                 if (vp->v_flag & VRECLAIMED)
4062                         break;
4063                 /*
4064                  * We prevent deadlock by always fetching inodes from the
4065                  * root, moving down the directory tree. Thus, when fetching
4066                  * our parent directory, we must unlock ourselves before
4067                  * requesting the lock on our parent. See the comment in
4068                  * ufs_lookup for details on possible races.
4069                  */
4070                 FREE_LOCK(&lk);
4071                 vn_unlock(vp);
4072                 error = VFS_VGET(mnt, NULL, parentino, &pvp);
4073                 vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4074                 if (error != 0) {
4075                         rel_mplock();
4076                         return (error);
4077                 }
4078                 if (flushparent) {
4079                         if ((error = ffs_update(pvp, 1)) != 0) {
4080                                 vput(pvp);
4081                                 rel_mplock();
4082                                 return (error);
4083                         }
4084                 }
4085                 /*
4086                  * Flush directory page containing the inode's name.
4087                  */
4088                 error = bread(pvp, lblktodoff(fs, lbn), blksize(fs, VTOI(pvp), lbn), &bp);
4089                 if (error == 0)
4090                         error = bwrite(bp);
4091                 vput(pvp);
4092                 if (error != 0) {
4093                         rel_mplock();
4094                         return (error);
4095                 }
4096                 ACQUIRE_LOCK(&lk);
4097                 if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4098                         break;
4099         }
4100         FREE_LOCK(&lk);
4101         rel_mplock();
4102         return (0);
4103 }
4104
4105 /*
4106  * Flush all the dirty bitmaps associated with the block device
4107  * before flushing the rest of the dirty blocks so as to reduce
4108  * the number of dependencies that will have to be rolled back.
4109  */
4110 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4111
4112 void
4113 softdep_fsync_mountdev(struct vnode *vp)
4114 {
4115         if (!vn_isdisk(vp, NULL))
4116                 panic("softdep_fsync_mountdev: vnode not a disk");
4117         ACQUIRE_LOCK(&lk);
4118         lwkt_gettoken(&vp->v_token);
4119         RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
4120                 softdep_fsync_mountdev_bp, vp);
4121         lwkt_reltoken(&vp->v_token);
4122         drain_output(vp, 1);
4123         FREE_LOCK(&lk);
4124 }
4125
4126 static int
4127 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4128 {
4129         struct worklist *wk;
4130         struct vnode *vp = data;
4131
4132         /* 
4133          * If it is already scheduled, skip to the next buffer.
4134          */
4135         if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4136                 return(0);
4137         if (bp->b_vp != vp || (bp->b_flags & B_DELWRI) == 0) {
4138                 BUF_UNLOCK(bp);
4139                 kprintf("softdep_fsync_mountdev_bp: warning, buffer %p ripped out from under vnode %p\n", bp, vp);
4140                 return(0);
4141         }
4142         /*
4143          * We are only interested in bitmaps with outstanding
4144          * dependencies.
4145          */
4146         if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4147             wk->wk_type != D_BMSAFEMAP) {
4148                 BUF_UNLOCK(bp);
4149                 return(0);
4150         }
4151         bremfree(bp);
4152         FREE_LOCK(&lk);
4153         (void) bawrite(bp);
4154         ACQUIRE_LOCK(&lk);
4155         return(0);
4156 }
4157
4158 /*
4159  * This routine is called when we are trying to synchronously flush a
4160  * file. This routine must eliminate any filesystem metadata dependencies
4161  * so that the syncing routine can succeed by pushing the dirty blocks
4162  * associated with the file. If any I/O errors occur, they are returned.
4163  */
4164 struct softdep_sync_metadata_info {
4165         struct vnode *vp;
4166         int waitfor;
4167 };
4168
4169 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4170
4171 int
4172 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4173 {
4174         struct softdep_sync_metadata_info info;
4175         int error, waitfor;
4176
4177         /*
4178          * Check whether this vnode is involved in a filesystem
4179          * that is doing soft dependency processing.
4180          */
4181         if (!vn_isdisk(vp, NULL)) {
4182                 if (!DOINGSOFTDEP(vp))
4183                         return (0);
4184         } else
4185                 if (vp->v_rdev->si_mountpoint == NULL ||
4186                     (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4187                         return (0);
4188         /*
4189          * Ensure that any direct block dependencies have been cleared.
4190          */
4191         ACQUIRE_LOCK(&lk);
4192         if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4193                 FREE_LOCK(&lk);
4194                 return (error);
4195         }
4196         /*
4197          * For most files, the only metadata dependencies are the
4198          * cylinder group maps that allocate their inode or blocks.
4199          * The block allocation dependencies can be found by traversing
4200          * the dependency lists for any buffers that remain on their
4201          * dirty buffer list. The inode allocation dependency will
4202          * be resolved when the inode is updated with MNT_WAIT.
4203          * This work is done in two passes. The first pass grabs most
4204          * of the buffers and begins asynchronously writing them. The
4205          * only way to wait for these asynchronous writes is to sleep
4206          * on the filesystem vnode which may stay busy for a long time
4207          * if the filesystem is active. So, instead, we make a second
4208          * pass over the dependencies blocking on each write. In the
4209          * usual case we will be blocking against a write that we
4210          * initiated, so when it is done the dependency will have been
4211          * resolved. Thus the second pass is expected to end quickly.
4212          */
4213         waitfor = MNT_NOWAIT;
4214 top:
4215         /*
4216          * We must wait for any I/O in progress to finish so that
4217          * all potential buffers on the dirty list will be visible.
4218          */
4219         drain_output(vp, 1);
4220
4221         info.vp = vp;
4222         info.waitfor = waitfor;
4223         lwkt_gettoken(&vp->v_token);
4224         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
4225                         softdep_sync_metadata_bp, &info);
4226         lwkt_reltoken(&vp->v_token);
4227         if (error < 0) {
4228                 FREE_LOCK(&lk);
4229                 return(-error); /* error code */
4230         }
4231
4232         /*
4233          * The brief unlock is to allow any pent up dependency
4234          * processing to be done.  Then proceed with the second pass.
4235          */
4236         if (waitfor & MNT_NOWAIT) {
4237                 waitfor = MNT_WAIT;
4238                 FREE_LOCK(&lk);
4239                 ACQUIRE_LOCK(&lk);
4240                 goto top;
4241         }
4242
4243         /*
4244          * If we have managed to get rid of all the dirty buffers,
4245          * then we are done. For certain directories and block
4246          * devices, we may need to do further work.
4247          *
4248          * We must wait for any I/O in progress to finish so that
4249          * all potential buffers on the dirty list will be visible.
4250          */
4251         drain_output(vp, 1);
4252         if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4253                 FREE_LOCK(&lk);
4254                 return (0);
4255         }
4256
4257         FREE_LOCK(&lk);
4258         /*
4259          * If we are trying to sync a block device, some of its buffers may
4260          * contain metadata that cannot be written until the contents of some
4261          * partially written files have been written to disk. The only easy
4262          * way to accomplish this is to sync the entire filesystem (luckily
4263          * this happens rarely).
4264          */
4265         if (vn_isdisk(vp, NULL) && 
4266             vp->v_rdev &&
4267             vp->v_rdev->si_mountpoint && !vn_islocked(vp) &&
4268             (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT)) != 0)
4269                 return (error);
4270         return (0);
4271 }
4272
4273 static int
4274 softdep_sync_metadata_bp(struct buf *bp, void *data)
4275 {
4276         struct softdep_sync_metadata_info *info = data;
4277         struct pagedep *pagedep;
4278         struct allocdirect *adp;
4279         struct allocindir *aip;
4280         struct worklist *wk;
4281         struct buf *nbp;
4282         int error;
4283         int i;
4284
4285         if (getdirtybuf(&bp, MNT_WAIT) == 0) {
4286                 kprintf("softdep_sync_metadata_bp(1): caught buf %p going away\n", bp);
4287                 return (1);
4288         }
4289         if (bp->b_vp != info->vp || (bp->b_flags & B_DELWRI) == 0) {
4290                 kprintf("softdep_sync_metadata_bp(2): caught buf %p going away vp %p\n", bp, info->vp);
4291                 BUF_UNLOCK(bp);
4292                 return(1);
4293         }
4294
4295         /*
4296          * As we hold the buffer locked, none of its dependencies
4297          * will disappear.
4298          */
4299         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4300                 switch (wk->wk_type) {
4301
4302                 case D_ALLOCDIRECT:
4303                         adp = WK_ALLOCDIRECT(wk);
4304                         if (adp->ad_state & DEPCOMPLETE)
4305                                 break;
4306                         nbp = adp->ad_buf;
4307                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4308                                 break;
4309                         FREE_LOCK(&lk);
4310                         if (info->waitfor & MNT_NOWAIT) {
4311                                 bawrite(nbp);
4312                         } else if ((error = bwrite(nbp)) != 0) {
4313                                 bawrite(bp);
4314                                 ACQUIRE_LOCK(&lk);
4315                                 return (-error);
4316                         }
4317                         ACQUIRE_LOCK(&lk);
4318                         break;
4319
4320                 case D_ALLOCINDIR:
4321                         aip = WK_ALLOCINDIR(wk);
4322                         if (aip->ai_state & DEPCOMPLETE)
4323                                 break;
4324                         nbp = aip->ai_buf;
4325                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4326                                 break;
4327                         FREE_LOCK(&lk);
4328                         if (info->waitfor & MNT_NOWAIT) {
4329                                 bawrite(nbp);
4330                         } else if ((error = bwrite(nbp)) != 0) {
4331                                 bawrite(bp);
4332                                 ACQUIRE_LOCK(&lk);
4333                                 return (-error);
4334                         }
4335                         ACQUIRE_LOCK(&lk);
4336                         break;
4337
4338                 case D_INDIRDEP:
4339                 restart:
4340
4341                         LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4342                                 if (aip->ai_state & DEPCOMPLETE)
4343                                         continue;
4344                                 nbp = aip->ai_buf;
4345                                 if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4346                                         goto restart;
4347                                 FREE_LOCK(&lk);
4348                                 if ((error = bwrite(nbp)) != 0) {
4349                                         bawrite(bp);
4350                                         ACQUIRE_LOCK(&lk);
4351                                         return (-error);
4352                                 }
4353                                 ACQUIRE_LOCK(&lk);
4354                                 goto restart;
4355                         }
4356                         break;
4357
4358                 case D_INODEDEP:
4359                         if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4360                             WK_INODEDEP(wk)->id_ino)) != 0) {
4361                                 FREE_LOCK(&lk);
4362                                 bawrite(bp);
4363                                 ACQUIRE_LOCK(&lk);
4364                                 return (-error);
4365                         }
4366                         break;
4367
4368                 case D_PAGEDEP:
4369                         /*
4370                          * We are trying to sync a directory that may
4371                          * have dependencies on both its own metadata
4372                          * and/or dependencies on the inodes of any
4373                          * recently allocated files. We walk its diradd
4374                          * lists pushing out the associated inode.
4375                          */
4376                         pagedep = WK_PAGEDEP(wk);
4377                         for (i = 0; i < DAHASHSZ; i++) {
4378                                 if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4379                                         continue;
4380                                 if ((error =
4381                                     flush_pagedep_deps(info->vp,
4382                                                 pagedep->pd_mnt,
4383                                                 &pagedep->pd_diraddhd[i]))) {
4384                                         FREE_LOCK(&lk);
4385                                         bawrite(bp);
4386                                         ACQUIRE_LOCK(&lk);
4387                                         return (-error);
4388                                 }
4389                         }
4390                         break;
4391
4392                 case D_MKDIR:
4393                         /*
4394                          * This case should never happen if the vnode has
4395                          * been properly sync'ed. However, if this function
4396                          * is used at a place where the vnode has not yet
4397                          * been sync'ed, this dependency can show up. So,
4398                          * rather than panic, just flush it.
4399                          */
4400                         nbp = WK_MKDIR(wk)->md_buf;
4401                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4402                                 break;
4403                         FREE_LOCK(&lk);
4404                         if (info->waitfor & MNT_NOWAIT) {
4405                                 bawrite(nbp);
4406                         } else if ((error = bwrite(nbp)) != 0) {
4407                                 bawrite(bp);
4408                                 ACQUIRE_LOCK(&lk);
4409                                 return (-error);
4410                         }
4411                         ACQUIRE_LOCK(&lk);
4412                         break;
4413
4414                 case D_BMSAFEMAP:
4415                         /*
4416                          * This case should never happen if the vnode has
4417                          * been properly sync'ed. However, if this function
4418                          * is used at a place where the vnode has not yet
4419                          * been sync'ed, this dependency can show up. So,
4420                          * rather than panic, just flush it.
4421                          *
4422                          * nbp can wind up == bp if a device node for the
4423                          * same filesystem is being fsynced at the same time,
4424                          * leading to a panic if we don't catch the case.
4425                          */
4426                         nbp = WK_BMSAFEMAP(wk)->sm_buf;
4427                         if (nbp == bp)
4428                                 break;
4429                         if (getdirtybuf(&nbp, info->waitfor) == 0)
4430                                 break;
4431                         FREE_LOCK(&lk);
4432                         if (info->waitfor & MNT_NOWAIT) {
4433                                 bawrite(nbp);
4434                         } else if ((error = bwrite(nbp)) != 0) {
4435                                 bawrite(bp);
4436                                 ACQUIRE_LOCK(&lk);
4437                                 return (-error);
4438                         }
4439                         ACQUIRE_LOCK(&lk);
4440                         break;
4441
4442                 default:
4443                         FREE_LOCK(&lk);
4444                         panic("softdep_sync_metadata: Unknown type %s",
4445                             TYPENAME(wk->wk_type));
4446                         /* NOTREACHED */
4447                 }
4448         }
4449         FREE_LOCK(&lk);
4450         bawrite(bp);
4451         ACQUIRE_LOCK(&lk);
4452         return(0);
4453 }
4454
4455 /*
4456  * Flush the dependencies associated with an inodedep.
4457  * Called with splbio blocked.
4458  */
4459 static int
4460 flush_inodedep_deps(struct fs *fs, ino_t ino)
4461 {
4462         struct inodedep *inodedep;
4463         struct allocdirect *adp;
4464         int error, waitfor;
4465         struct buf *bp;
4466
4467         /*
4468          * This work is done in two passes. The first pass grabs most
4469          * of the buffers and begins asynchronously writing them. The
4470          * only way to wait for these asynchronous writes is to sleep
4471          * on the filesystem vnode which may stay busy for a long time
4472          * if the filesystem is active. So, instead, we make a second
4473          * pass over the dependencies blocking on each write. In the
4474          * usual case we will be blocking against a write that we
4475          * initiated, so when it is done the dependency will have been
4476          * resolved. Thus the second pass is expected to end quickly.
4477          * We give a brief window at the top of the loop to allow
4478          * any pending I/O to complete.
4479          */
4480         for (waitfor = MNT_NOWAIT; ; ) {
4481                 FREE_LOCK(&lk);
4482                 ACQUIRE_LOCK(&lk);
4483                 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4484                         return (0);
4485                 TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4486                         if (adp->ad_state & DEPCOMPLETE)
4487                                 continue;
4488                         bp = adp->ad_buf;
4489                         if (getdirtybuf(&bp, waitfor) == 0) {
4490                                 if (waitfor & MNT_NOWAIT)
4491                                         continue;
4492                                 break;
4493                         }
4494                         FREE_LOCK(&lk);
4495                         if (waitfor & MNT_NOWAIT) {
4496                                 bawrite(bp);
4497                         } else if ((error = bwrite(bp)) != 0) {
4498                                 ACQUIRE_LOCK(&lk);
4499                                 return (error);
4500                         }
4501                         ACQUIRE_LOCK(&lk);
4502                         break;
4503                 }
4504                 if (adp != NULL)
4505                         continue;
4506                 TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4507                         if (adp->ad_state & DEPCOMPLETE)
4508                                 continue;
4509                         bp = adp->ad_buf;
4510                         if (getdirtybuf(&bp, waitfor) == 0) {
4511                                 if (waitfor & MNT_NOWAIT)
4512                                         continue;
4513                                 break;
4514                         }
4515                         FREE_LOCK(&lk);
4516                         if (waitfor & MNT_NOWAIT) {
4517                                 bawrite(bp);
4518                         } else if ((error = bwrite(bp)) != 0) {
4519                                 ACQUIRE_LOCK(&lk);
4520                                 return (error);
4521                         }
4522                         ACQUIRE_LOCK(&lk);
4523                         break;
4524                 }
4525                 if (adp != NULL)
4526                         continue;
4527                 /*
4528                  * If pass2, we are done, otherwise do pass 2.
4529                  */
4530                 if (waitfor == MNT_WAIT)
4531                         break;
4532                 waitfor = MNT_WAIT;
4533         }
4534         /*
4535          * Try freeing inodedep in case all dependencies have been removed.
4536          */
4537         if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4538                 (void) free_inodedep(inodedep);
4539         return (0);
4540 }
4541
4542 /*
4543  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4544  * Called with splbio blocked.
4545  */
4546 static int
4547 flush_pagedep_deps(struct vnode *pvp, struct mount *mp,
4548                    struct diraddhd *diraddhdp)
4549 {
4550         struct inodedep *inodedep;
4551         struct ufsmount *ump;
4552         struct diradd *dap;
4553         struct vnode *vp;
4554         int gotit, error = 0;
4555         struct buf *bp;
4556         ino_t inum;
4557
4558         ump = VFSTOUFS(mp);
4559         while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4560                 /*
4561                  * Flush ourselves if this directory entry
4562                  * has a MKDIR_PARENT dependency.
4563                  */
4564                 if (dap->da_state & MKDIR_PARENT) {
4565                         FREE_LOCK(&lk);
4566                         if ((error = ffs_update(pvp, 1)) != 0)
4567                                 break;
4568                         ACQUIRE_LOCK(&lk);
4569                         /*
4570                          * If that cleared dependencies, go on to next.
4571                          */
4572                         if (dap != LIST_FIRST(diraddhdp))
4573                                 continue;
4574                         if (dap->da_state & MKDIR_PARENT) {
4575                                 FREE_LOCK(&lk);
4576                                 panic("flush_pagedep_deps: MKDIR_PARENT");
4577                         }
4578                 }
4579                 /*
4580                  * A newly allocated directory must have its "." and
4581                  * ".." entries written out before its name can be
4582                  * committed in its parent. We do not want or need
4583                  * the full semantics of a synchronous VOP_FSYNC as
4584                  * that may end up here again, once for each directory
4585                  * level in the filesystem. Instead, we push the blocks
4586                  * and wait for them to clear. We have to fsync twice
4587                  * because the first call may choose to defer blocks
4588                  * that still have dependencies, but deferral will
4589                  * happen at most once.
4590                  */
4591                 inum = dap->da_newinum;
4592                 if (dap->da_state & MKDIR_BODY) {
4593                         FREE_LOCK(&lk);
4594                         if ((error = VFS_VGET(mp, NULL, inum, &vp)) != 0)
4595                                 break;
4596                         if ((error=VOP_FSYNC(vp, MNT_NOWAIT, 0)) ||
4597                             (error=VOP_FSYNC(vp, MNT_NOWAIT, 0))) {
4598                                 vput(vp);
4599                                 break;
4600                         }
4601                         drain_output(vp, 0);
4602                         vput(vp);
4603                         ACQUIRE_LOCK(&lk);
4604                         /*
4605                          * If that cleared dependencies, go on to next.
4606                          */
4607                         if (dap != LIST_FIRST(diraddhdp))
4608                                 continue;
4609                         if (dap->da_state & MKDIR_BODY) {
4610                                 FREE_LOCK(&lk);
4611                                 panic("flush_pagedep_deps: MKDIR_BODY");
4612                         }
4613                 }
4614                 /*
4615                  * Flush the inode on which the directory entry depends.
4616                  * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4617                  * the only remaining dependency is that the updated inode
4618                  * count must get pushed to disk. The inode has already
4619                  * been pushed into its inode buffer (via VOP_UPDATE) at
4620                  * the time of the reference count change. So we need only
4621                  * locate that buffer, ensure that there will be no rollback
4622                  * caused by a bitmap dependency, then write the inode buffer.
4623                  */
4624                 if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4625                         FREE_LOCK(&lk);
4626                         panic("flush_pagedep_deps: lost inode");
4627                 }
4628                 /*
4629                  * If the inode still has bitmap dependencies,
4630                  * push them to disk.
4631                  */
4632                 if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4633                         gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4634                         FREE_LOCK(&lk);
4635                         if (gotit && (error = bwrite(inodedep->id_buf)) != 0)
4636                                 break;
4637                         ACQUIRE_LOCK(&lk);
4638                         if (dap != LIST_FIRST(diraddhdp))
4639                                 continue;
4640                 }
4641                 /*
4642                  * If the inode is still sitting in a buffer waiting
4643                  * to be written, push it to disk.
4644                  */
4645                 FREE_LOCK(&lk);
4646                 if ((error = bread(ump->um_devvp,
4647                         fsbtodoff(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4648                     (int)ump->um_fs->fs_bsize, &bp)) != 0)
4649                         break;
4650                 if ((error = bwrite(bp)) != 0)
4651                         break;
4652                 ACQUIRE_LOCK(&lk);
4653                 /*
4654                  * If we have failed to get rid of all the dependencies
4655                  * then something is seriously wrong.
4656                  */
4657                 if (dap == LIST_FIRST(diraddhdp)) {
4658                         FREE_LOCK(&lk);
4659                         panic("flush_pagedep_deps: flush failed");
4660                 }
4661         }
4662         if (error)
4663                 ACQUIRE_LOCK(&lk);
4664         return (error);
4665 }
4666
4667 /*
4668  * A large burst of file addition or deletion activity can drive the
4669  * memory load excessively high. First attempt to slow things down
4670  * using the techniques below. If that fails, this routine requests
4671  * the offending operations to fall back to running synchronously
4672  * until the memory load returns to a reasonable level.
4673  */
4674 int
4675 softdep_slowdown(struct vnode *vp)
4676 {
4677         int max_softdeps_hard;
4678
4679         max_softdeps_hard = max_softdeps * 11 / 10;
4680         if (num_dirrem < max_softdeps_hard / 2 &&
4681             num_inodedep < max_softdeps_hard)
4682                 return (0);
4683         stat_sync_limit_hit += 1;
4684         return (1);
4685 }
4686
4687 /*
4688  * If memory utilization has gotten too high, deliberately slow things
4689  * down and speed up the I/O processing.
4690  */
4691 static int
4692 request_cleanup(int resource, int islocked)
4693 {
4694         struct thread *td = curthread;          /* XXX */
4695
4696         /*
4697          * We never hold up the filesystem syncer process.
4698          */
4699         if (td == filesys_syncer)
4700                 return (0);
4701         /*
4702          * First check to see if the work list has gotten backlogged.
4703          * If it has, co-opt this process to help clean up two entries.
4704          * Because this process may hold inodes locked, we cannot
4705          * handle any remove requests that might block on a locked
4706          * inode as that could lead to deadlock.
4707          */
4708         if (num_on_worklist > max_softdeps / 10) {
4709                 if (islocked)
4710                         FREE_LOCK(&lk);
4711                 process_worklist_item(NULL, LK_NOWAIT);
4712                 process_worklist_item(NULL, LK_NOWAIT);
4713                 stat_worklist_push += 2;
4714                 if (islocked)
4715                         ACQUIRE_LOCK(&lk);
4716                 return(1);
4717         }
4718
4719         /*
4720          * If we are resource constrained on inode dependencies, try
4721          * flushing some dirty inodes. Otherwise, we are constrained
4722          * by file deletions, so try accelerating flushes of directories
4723          * with removal dependencies. We would like to do the cleanup
4724          * here, but we probably hold an inode locked at this point and 
4725          * that might deadlock against one that we try to clean. So,
4726          * the best that we can do is request the syncer daemon to do
4727          * the cleanup for us.
4728          */
4729         switch (resource) {
4730
4731         case FLUSH_INODES:
4732                 stat_ino_limit_push += 1;
4733                 req_clear_inodedeps += 1;
4734                 stat_countp = &stat_ino_limit_hit;
4735                 break;
4736
4737         case FLUSH_REMOVE:
4738                 stat_blk_limit_push += 1;
4739                 req_clear_remove += 1;
4740                 stat_countp = &stat_blk_limit_hit;
4741                 break;
4742
4743         default:
4744                 if (islocked)
4745                         FREE_LOCK(&lk);
4746                 panic("request_cleanup: unknown type");
4747         }
4748         /*
4749          * Hopefully the syncer daemon will catch up and awaken us.
4750          * We wait at most tickdelay before proceeding in any case.
4751          */
4752         if (islocked == 0)
4753                 ACQUIRE_LOCK(&lk);
4754         proc_waiting += 1;
4755         if (!callout_active(&handle))
4756                 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4757                               pause_timer, NULL);
4758         interlocked_sleep(&lk, (caddr_t)&proc_waiting, 0,
4759             "softupdate", 0);
4760         proc_waiting -= 1;
4761         if (islocked == 0)
4762                 FREE_LOCK(&lk);
4763         return (1);
4764 }
4765
4766 /*
4767  * Awaken processes pausing in request_cleanup and clear proc_waiting
4768  * to indicate that there is no longer a timer running.
4769  */
4770 void
4771 pause_timer(void *arg)
4772 {
4773         *stat_countp += 1;
4774         wakeup_one(&proc_waiting);
4775         if (proc_waiting > 0)
4776                 callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4777                               pause_timer, NULL);
4778         else
4779                 callout_deactivate(&handle);
4780 }
4781
4782 /*
4783  * Flush out a directory with at least one removal dependency in an effort to
4784  * reduce the number of dirrem, freefile, and freeblks dependency structures.
4785  */
4786 static void
4787 clear_remove(struct thread *td)
4788 {
4789         struct pagedep_hashhead *pagedephd;
4790         struct pagedep *pagedep;
4791         static int next = 0;
4792         struct mount *mp;
4793         struct vnode *vp;
4794         int error, cnt;
4795         ino_t ino;
4796
4797         ACQUIRE_LOCK(&lk);
4798         for (cnt = 0; cnt < pagedep_hash; cnt++) {
4799                 pagedephd = &pagedep_hashtbl[next++];
4800                 if (next >= pagedep_hash)
4801                         next = 0;
4802                 LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4803                         if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4804                                 continue;
4805                         mp = pagedep->pd_mnt;
4806                         ino = pagedep->pd_ino;
4807                         FREE_LOCK(&lk);
4808                         if ((error = VFS_VGET(mp, NULL, ino, &vp)) != 0) {
4809                                 softdep_error("clear_remove: vget", error);
4810                                 return;
4811                         }
4812                         if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4813                                 softdep_error("clear_remove: fsync", error);
4814                         drain_output(vp, 0);
4815                         vput(vp);
4816                         return;
4817                 }
4818         }
4819         FREE_LOCK(&lk);
4820 }
4821
4822 /*
4823  * Clear out a block of dirty inodes in an effort to reduce
4824  * the number of inodedep dependency structures.
4825  */
4826 struct clear_inodedeps_info {
4827         struct fs *fs;
4828         struct mount *mp;
4829 };
4830
4831 static int
4832 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4833 {
4834         struct clear_inodedeps_info *info = data;
4835
4836         if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4837                 info->mp = mp;
4838                 return(-1);
4839         }
4840         return(0);
4841 }
4842
4843 static void
4844 clear_inodedeps(struct thread *td)
4845 {
4846         struct clear_inodedeps_info info;
4847         struct inodedep_hashhead *inodedephd;
4848         struct inodedep *inodedep;
4849         static int next = 0;
4850         struct vnode *vp;
4851         struct fs *fs;
4852         int error, cnt;
4853         ino_t firstino, lastino, ino;
4854
4855         ACQUIRE_LOCK(&lk);
4856         /*
4857          * Pick a random inode dependency to be cleared.
4858          * We will then gather up all the inodes in its block 
4859          * that have dependencies and flush them out.
4860          */
4861         for (cnt = 0; cnt < inodedep_hash; cnt++) {
4862                 inodedephd = &inodedep_hashtbl[next++];
4863                 if (next >= inodedep_hash)
4864                         next = 0;
4865                 if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4866                         break;
4867         }
4868         if (inodedep == NULL) {
4869                 FREE_LOCK(&lk);
4870                 return;
4871         }
4872         /*
4873          * Ugly code to find mount point given pointer to superblock.
4874          */
4875         fs = inodedep->id_fs;
4876         info.mp = NULL;
4877         info.fs = fs;
4878         mountlist_scan(clear_inodedeps_mountlist_callback, 
4879                         &info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4880         /*
4881          * Find the last inode in the block with dependencies.
4882          */
4883         firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4884         for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4885                 if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4886                         break;
4887         /*
4888          * Asynchronously push all but the last inode with dependencies.
4889          * Synchronously push the last inode with dependencies to ensure
4890          * that the inode block gets written to free up the inodedeps.
4891          */
4892         for (ino = firstino; ino <= lastino; ino++) {
4893                 if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4894                         continue;
4895                 FREE_LOCK(&lk);
4896                 if ((error = VFS_VGET(info.mp, NULL, ino, &vp)) != 0) {
4897                         softdep_error("clear_inodedeps: vget", error);
4898                         return;
4899                 }
4900                 if (ino == lastino) {
4901                         if ((error = VOP_FSYNC(vp, MNT_WAIT, 0)))
4902                                 softdep_error("clear_inodedeps: fsync1", error);
4903                 } else {
4904                         if ((error = VOP_FSYNC(vp, MNT_NOWAIT, 0)))
4905                                 softdep_error("clear_inodedeps: fsync2", error);
4906                         drain_output(vp, 0);
4907                 }
4908                 vput(vp);
4909                 ACQUIRE_LOCK(&lk);
4910         }
4911         FREE_LOCK(&lk);
4912 }
4913
4914 /*
4915  * Function to determine if the buffer has outstanding dependencies
4916  * that will cause a roll-back if the buffer is written. If wantcount
4917  * is set, return number of dependencies, otherwise just yes or no.
4918  *
4919  * bioops callback - hold io_token
4920  */
4921 static int
4922 softdep_count_dependencies(struct buf *bp, int wantcount)
4923 {
4924         struct worklist *wk;
4925         struct inodedep *inodedep;
4926         struct indirdep *indirdep;
4927         struct allocindir *aip;
4928         struct pagedep *pagedep;
4929         struct diradd *dap;
4930         int i, retval;
4931
4932         get_mplock();
4933
4934         retval = 0;
4935         ACQUIRE_LOCK(&lk);
4936
4937         LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4938                 switch (wk->wk_type) {
4939
4940                 case D_INODEDEP:
4941                         inodedep = WK_INODEDEP(wk);
4942                         if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4943                                 /* bitmap allocation dependency */
4944                                 retval += 1;
4945                                 if (!wantcount)
4946                                         goto out;
4947                         }
4948                         if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4949                                 /* direct block pointer dependency */
4950                                 retval += 1;
4951                                 if (!wantcount)
4952                                         goto out;
4953                         }
4954                         continue;
4955
4956                 case D_INDIRDEP:
4957                         indirdep = WK_INDIRDEP(wk);
4958
4959                         LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4960                                 /* indirect block pointer dependency */
4961                                 retval += 1;
4962                                 if (!wantcount)
4963                                         goto out;
4964                         }
4965                         continue;
4966
4967                 case D_PAGEDEP:
4968                         pagedep = WK_PAGEDEP(wk);
4969                         for (i = 0; i < DAHASHSZ; i++) {
4970
4971                                 LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4972                                         /* directory entry dependency */
4973                                         retval += 1;
4974                                         if (!wantcount)
4975                                                 goto out;
4976                                 }
4977                         }
4978                         continue;
4979
4980                 case D_BMSAFEMAP:
4981                 case D_ALLOCDIRECT:
4982                 case D_ALLOCINDIR:
4983                 case D_MKDIR:
4984                         /* never a dependency on these blocks */
4985                         continue;
4986
4987                 default:
4988                         FREE_LOCK(&lk);
4989                         panic("softdep_check_for_rollback: Unexpected type %s",
4990                             TYPENAME(wk->wk_type));
4991                         /* NOTREACHED */
4992                 }
4993         }
4994 out:
4995         FREE_LOCK(&lk);
4996         rel_mplock();
4997
4998         return retval;
4999 }
5000
5001 /*
5002  * getdirtybuf:
5003  *
5004  *      Acquire exclusive access to a buffer. Requires softdep lock
5005  *      to be held on entry. If waitfor is MNT_WAIT, may release/reacquire
5006  *      softdep lock.
5007  *
5008  *      Returns 1 if the buffer was locked, 0 otherwise.
5009  */
5010 static int
5011 getdirtybuf(struct buf **bpp, int waitfor)
5012 {
5013         struct buf *bp;
5014         int error;
5015
5016         bp = *bpp;
5017         if (bp == NULL)
5018                 return (0);
5019
5020         for (;;) {
5021                 /* Must acquire buffer lock with ffs_softdep lock held */
5022                 KKASSERT(lock_held(&lk) > 0);
5023                 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
5024                 if (error == 0)
5025                         break;
5026
5027                 if (waitfor != MNT_WAIT)
5028                         return (0);
5029
5030                 /* 
5031                  * Release ffs_softdep lock around sleep/wait for buffer lock.
5032                  *
5033                  * We must acquire buffer lock with softdep lock held, so
5034                  * we must retry locking the buffer after we wake.
5035                  */
5036                 FREE_LOCK(&lk);
5037                 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL);
5038                 ACQUIRE_LOCK(&lk);
5039                 if (error == 0)
5040                         BUF_UNLOCK(bp);
5041                 else if (error == ENOLCK)
5042                         ;
5043                 else
5044                         panic("getdirtybuf: Inconsistent lock");
5045         }
5046
5047         /* Buffer wasn't dirty */
5048         if ((bp->b_flags & B_DELWRI) == 0) {
5049                 BUF_UNLOCK(bp);
5050                 return (0);
5051         }
5052         bremfree(bp);
5053         return (1);
5054 }
5055
5056 /*
5057  * Wait for pending output on a vnode to complete.
5058  * Must be called with vnode locked.
5059  */
5060 static void
5061 drain_output(struct vnode *vp, int islocked)
5062 {
5063
5064         if (!islocked)
5065                 ACQUIRE_LOCK(&lk);
5066         while (bio_track_active(&vp->v_track_write)) {
5067                 FREE_LOCK(&lk);
5068                 bio_track_wait(&vp->v_track_write, 0, 0);
5069                 ACQUIRE_LOCK(&lk);
5070         }
5071         if (!islocked)
5072                 FREE_LOCK(&lk);
5073 }
5074
5075 /*
5076  * Called whenever a buffer that is being invalidated or reallocated
5077  * contains dependencies. This should only happen if an I/O error has
5078  * occurred. The routine is called with the buffer locked.
5079  *
5080  * bioops callback - hold io_token
5081  */ 
5082 static void
5083 softdep_deallocate_dependencies(struct buf *bp)
5084 {
5085         /* nothing to do, mp lock not needed */
5086         if ((bp->b_flags & B_ERROR) == 0)
5087                 panic("softdep_deallocate_dependencies: dangling deps");
5088         softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5089         panic("softdep_deallocate_dependencies: unrecovered I/O error");
5090 }
5091
5092 /*
5093  * Function to handle asynchronous write errors in the filesystem.
5094  */
5095 void
5096 softdep_error(char *func, int error)
5097 {
5098
5099         /* XXX should do something better! */
5100         kprintf("%s: got error %d while accessing filesystem\n", func, error);
5101 }