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