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