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