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