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