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