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