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