xref: /dragonfly/sys/vfs/ufs/ffs_softdep.c (revision 1bf4b486)
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.27 2005/07/31 22:25:46 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_state = ATTACHED;
1768 	freeblks->fb_uid = ip->i_uid;
1769 	freeblks->fb_previousinum = ip->i_number;
1770 	freeblks->fb_devvp = ip->i_devvp;
1771 	freeblks->fb_fs = fs;
1772 	freeblks->fb_oldsize = ip->i_size;
1773 	freeblks->fb_newsize = length;
1774 	freeblks->fb_chkcnt = ip->i_blocks;
1775 	for (i = 0; i < NDADDR; i++) {
1776 		freeblks->fb_dblks[i] = ip->i_db[i];
1777 		ip->i_db[i] = 0;
1778 	}
1779 	for (i = 0; i < NIADDR; i++) {
1780 		freeblks->fb_iblks[i] = ip->i_ib[i];
1781 		ip->i_ib[i] = 0;
1782 	}
1783 	ip->i_blocks = 0;
1784 	ip->i_size = 0;
1785 	/*
1786 	 * Push the zero'ed inode to to its disk buffer so that we are free
1787 	 * to delete its dependencies below. Once the dependencies are gone
1788 	 * the buffer can be safely released.
1789 	 */
1790 	if ((error = bread(ip->i_devvp,
1791 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
1792 	    (int)fs->fs_bsize, &bp)) != 0)
1793 		softdep_error("softdep_setup_freeblocks", error);
1794 	*((struct dinode *)bp->b_data + ino_to_fsbo(fs, ip->i_number)) =
1795 	    ip->i_din;
1796 	/*
1797 	 * Find and eliminate any inode dependencies.
1798 	 */
1799 	ACQUIRE_LOCK(&lk);
1800 	(void) inodedep_lookup(fs, ip->i_number, DEPALLOC, &inodedep);
1801 	if ((inodedep->id_state & IOSTARTED) != 0) {
1802 		FREE_LOCK(&lk);
1803 		panic("softdep_setup_freeblocks: inode busy");
1804 	}
1805 	/*
1806 	 * Add the freeblks structure to the list of operations that
1807 	 * must await the zero'ed inode being written to disk. If we
1808 	 * still have a bitmap dependency (delay == 0), then the inode
1809 	 * has never been written to disk, so we can process the
1810 	 * freeblks below once we have deleted the dependencies.
1811 	 */
1812 	delay = (inodedep->id_state & DEPCOMPLETE);
1813 	if (delay)
1814 		WORKLIST_INSERT(&inodedep->id_bufwait, &freeblks->fb_list);
1815 	/*
1816 	 * Because the file length has been truncated to zero, any
1817 	 * pending block allocation dependency structures associated
1818 	 * with this inode are obsolete and can simply be de-allocated.
1819 	 * We must first merge the two dependency lists to get rid of
1820 	 * any duplicate freefrag structures, then purge the merged list.
1821 	 */
1822 	merge_inode_lists(inodedep);
1823 	while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
1824 		free_allocdirect(&inodedep->id_inoupdt, adp, 1);
1825 	FREE_LOCK(&lk);
1826 	bdwrite(bp);
1827 	/*
1828 	 * We must wait for any I/O in progress to finish so that
1829 	 * all potential buffers on the dirty list will be visible.
1830 	 * Once they are all there, walk the list and get rid of
1831 	 * any dependencies.
1832 	 */
1833 	vp = ITOV(ip);
1834 	ACQUIRE_LOCK(&lk);
1835 	drain_output(vp, 1);
1836 
1837 	info.fs = fs;
1838 	info.ip = ip;
1839 	do {
1840 		count = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
1841 				softdep_setup_freeblocks_bp, &info);
1842 	} while (count > 0);
1843 	if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) != 0)
1844 		(void)free_inodedep(inodedep);
1845 
1846 	if (delay) {
1847 		freeblks->fb_state |= DEPCOMPLETE;
1848 		/*
1849 		 * If the inode with zeroed block pointers is now on disk
1850 		 * we can start freeing blocks. Add freeblks to the worklist
1851 		 * instead of calling  handle_workitem_freeblocks directly as
1852 		 * it is more likely that additional IO is needed to complete
1853 		 * the request here than in the !delay case.
1854 		 */
1855 		if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
1856 			add_to_worklist(&freeblks->fb_list);
1857 	}
1858 
1859 	FREE_LOCK(&lk);
1860 	/*
1861 	 * If the inode has never been written to disk (delay == 0),
1862 	 * then we can process the freeblks now that we have deleted
1863 	 * the dependencies.
1864 	 */
1865 	if (!delay)
1866 		handle_workitem_freeblocks(freeblks);
1867 }
1868 
1869 static int
1870 softdep_setup_freeblocks_bp(struct buf *bp, void *data)
1871 {
1872 	struct softdep_setup_freeblocks_info *info = data;
1873 	struct inodedep *inodedep;
1874 
1875 	if (getdirtybuf(&bp, MNT_WAIT) == 0)
1876 		return(-1);
1877 	(void) inodedep_lookup(info->fs, info->ip->i_number, 0, &inodedep);
1878 	deallocate_dependencies(bp, inodedep);
1879 	bp->b_flags |= B_INVAL | B_NOCACHE;
1880 	FREE_LOCK(&lk);
1881 	brelse(bp);
1882 	ACQUIRE_LOCK(&lk);
1883 	return(1);
1884 }
1885 
1886 /*
1887  * Reclaim any dependency structures from a buffer that is about to
1888  * be reallocated to a new vnode. The buffer must be locked, thus,
1889  * no I/O completion operations can occur while we are manipulating
1890  * its associated dependencies. The mutex is held so that other I/O's
1891  * associated with related dependencies do not occur.
1892  */
1893 static void
1894 deallocate_dependencies(bp, inodedep)
1895 	struct buf *bp;
1896 	struct inodedep *inodedep;
1897 {
1898 	struct worklist *wk;
1899 	struct indirdep *indirdep;
1900 	struct allocindir *aip;
1901 	struct pagedep *pagedep;
1902 	struct dirrem *dirrem;
1903 	struct diradd *dap;
1904 	int i;
1905 
1906 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
1907 		switch (wk->wk_type) {
1908 
1909 		case D_INDIRDEP:
1910 			indirdep = WK_INDIRDEP(wk);
1911 			/*
1912 			 * None of the indirect pointers will ever be visible,
1913 			 * so they can simply be tossed. GOINGAWAY ensures
1914 			 * that allocated pointers will be saved in the buffer
1915 			 * cache until they are freed. Note that they will
1916 			 * only be able to be found by their physical address
1917 			 * since the inode mapping the logical address will
1918 			 * be gone. The save buffer used for the safe copy
1919 			 * was allocated in setup_allocindir_phase2 using
1920 			 * the physical address so it could be used for this
1921 			 * purpose. Hence we swap the safe copy with the real
1922 			 * copy, allowing the safe copy to be freed and holding
1923 			 * on to the real copy for later use in indir_trunc.
1924 			 */
1925 			if (indirdep->ir_state & GOINGAWAY) {
1926 				FREE_LOCK(&lk);
1927 				panic("deallocate_dependencies: already gone");
1928 			}
1929 			indirdep->ir_state |= GOINGAWAY;
1930 			while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
1931 				free_allocindir(aip, inodedep);
1932 			if (bp->b_lblkno >= 0 ||
1933 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno) {
1934 				FREE_LOCK(&lk);
1935 				panic("deallocate_dependencies: not indir");
1936 			}
1937 			bcopy(bp->b_data, indirdep->ir_savebp->b_data,
1938 			    bp->b_bcount);
1939 			WORKLIST_REMOVE(wk);
1940 			WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, wk);
1941 			continue;
1942 
1943 		case D_PAGEDEP:
1944 			pagedep = WK_PAGEDEP(wk);
1945 			/*
1946 			 * None of the directory additions will ever be
1947 			 * visible, so they can simply be tossed.
1948 			 */
1949 			for (i = 0; i < DAHASHSZ; i++)
1950 				while ((dap =
1951 				    LIST_FIRST(&pagedep->pd_diraddhd[i])))
1952 					free_diradd(dap);
1953 			while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != 0)
1954 				free_diradd(dap);
1955 			/*
1956 			 * Copy any directory remove dependencies to the list
1957 			 * to be processed after the zero'ed inode is written.
1958 			 * If the inode has already been written, then they
1959 			 * can be dumped directly onto the work list.
1960 			 */
1961 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
1962 				LIST_REMOVE(dirrem, dm_next);
1963 				dirrem->dm_dirinum = pagedep->pd_ino;
1964 				if (inodedep == NULL ||
1965 				    (inodedep->id_state & ALLCOMPLETE) ==
1966 				     ALLCOMPLETE)
1967 					add_to_worklist(&dirrem->dm_list);
1968 				else
1969 					WORKLIST_INSERT(&inodedep->id_bufwait,
1970 					    &dirrem->dm_list);
1971 			}
1972 			WORKLIST_REMOVE(&pagedep->pd_list);
1973 			LIST_REMOVE(pagedep, pd_hash);
1974 			WORKITEM_FREE(pagedep, D_PAGEDEP);
1975 			continue;
1976 
1977 		case D_ALLOCINDIR:
1978 			free_allocindir(WK_ALLOCINDIR(wk), inodedep);
1979 			continue;
1980 
1981 		case D_ALLOCDIRECT:
1982 		case D_INODEDEP:
1983 			FREE_LOCK(&lk);
1984 			panic("deallocate_dependencies: Unexpected type %s",
1985 			    TYPENAME(wk->wk_type));
1986 			/* NOTREACHED */
1987 
1988 		default:
1989 			FREE_LOCK(&lk);
1990 			panic("deallocate_dependencies: Unknown type %s",
1991 			    TYPENAME(wk->wk_type));
1992 			/* NOTREACHED */
1993 		}
1994 	}
1995 }
1996 
1997 /*
1998  * Free an allocdirect. Generate a new freefrag work request if appropriate.
1999  * This routine must be called with splbio interrupts blocked.
2000  */
2001 static void
2002 free_allocdirect(adphead, adp, delay)
2003 	struct allocdirectlst *adphead;
2004 	struct allocdirect *adp;
2005 	int delay;
2006 {
2007 
2008 #ifdef DEBUG
2009 	if (lk.lkt_held == NOHOLDER)
2010 		panic("free_allocdirect: lock not held");
2011 #endif
2012 	if ((adp->ad_state & DEPCOMPLETE) == 0)
2013 		LIST_REMOVE(adp, ad_deps);
2014 	TAILQ_REMOVE(adphead, adp, ad_next);
2015 	if ((adp->ad_state & COMPLETE) == 0)
2016 		WORKLIST_REMOVE(&adp->ad_list);
2017 	if (adp->ad_freefrag != NULL) {
2018 		if (delay)
2019 			WORKLIST_INSERT(&adp->ad_inodedep->id_bufwait,
2020 			    &adp->ad_freefrag->ff_list);
2021 		else
2022 			add_to_worklist(&adp->ad_freefrag->ff_list);
2023 	}
2024 	WORKITEM_FREE(adp, D_ALLOCDIRECT);
2025 }
2026 
2027 /*
2028  * Prepare an inode to be freed. The actual free operation is not
2029  * done until the zero'ed inode has been written to disk.
2030  */
2031 void
2032 softdep_freefile(pvp, ino, mode)
2033 		struct vnode *pvp;
2034 		ino_t ino;
2035 		int mode;
2036 {
2037 	struct inode *ip = VTOI(pvp);
2038 	struct inodedep *inodedep;
2039 	struct freefile *freefile;
2040 
2041 	/*
2042 	 * This sets up the inode de-allocation dependency.
2043 	 */
2044 	MALLOC(freefile, struct freefile *, sizeof(struct freefile),
2045 		M_FREEFILE, M_SOFTDEP_FLAGS);
2046 	freefile->fx_list.wk_type = D_FREEFILE;
2047 	freefile->fx_list.wk_state = 0;
2048 	freefile->fx_mode = mode;
2049 	freefile->fx_oldinum = ino;
2050 	freefile->fx_devvp = ip->i_devvp;
2051 	freefile->fx_fs = ip->i_fs;
2052 
2053 	/*
2054 	 * If the inodedep does not exist, then the zero'ed inode has
2055 	 * been written to disk. If the allocated inode has never been
2056 	 * written to disk, then the on-disk inode is zero'ed. In either
2057 	 * case we can free the file immediately.
2058 	 */
2059 	ACQUIRE_LOCK(&lk);
2060 	if (inodedep_lookup(ip->i_fs, ino, 0, &inodedep) == 0 ||
2061 	    check_inode_unwritten(inodedep)) {
2062 		FREE_LOCK(&lk);
2063 		handle_workitem_freefile(freefile);
2064 		return;
2065 	}
2066 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
2067 	FREE_LOCK(&lk);
2068 }
2069 
2070 /*
2071  * Check to see if an inode has never been written to disk. If
2072  * so free the inodedep and return success, otherwise return failure.
2073  * This routine must be called with splbio interrupts blocked.
2074  *
2075  * If we still have a bitmap dependency, then the inode has never
2076  * been written to disk. Drop the dependency as it is no longer
2077  * necessary since the inode is being deallocated. We set the
2078  * ALLCOMPLETE flags since the bitmap now properly shows that the
2079  * inode is not allocated. Even if the inode is actively being
2080  * written, it has been rolled back to its zero'ed state, so we
2081  * are ensured that a zero inode is what is on the disk. For short
2082  * lived files, this change will usually result in removing all the
2083  * dependencies from the inode so that it can be freed immediately.
2084  */
2085 static int
2086 check_inode_unwritten(inodedep)
2087 	struct inodedep *inodedep;
2088 {
2089 
2090 	if ((inodedep->id_state & DEPCOMPLETE) != 0 ||
2091 	    LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2092 	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2093 	    LIST_FIRST(&inodedep->id_inowait) != NULL ||
2094 	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2095 	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2096 	    inodedep->id_nlinkdelta != 0)
2097 		return (0);
2098 	inodedep->id_state |= ALLCOMPLETE;
2099 	LIST_REMOVE(inodedep, id_deps);
2100 	inodedep->id_buf = NULL;
2101 	if (inodedep->id_state & ONWORKLIST)
2102 		WORKLIST_REMOVE(&inodedep->id_list);
2103 	if (inodedep->id_savedino != NULL) {
2104 		FREE(inodedep->id_savedino, M_INODEDEP);
2105 		inodedep->id_savedino = NULL;
2106 	}
2107 	if (free_inodedep(inodedep) == 0) {
2108 		FREE_LOCK(&lk);
2109 		panic("check_inode_unwritten: busy inode");
2110 	}
2111 	return (1);
2112 }
2113 
2114 /*
2115  * Try to free an inodedep structure. Return 1 if it could be freed.
2116  */
2117 static int
2118 free_inodedep(inodedep)
2119 	struct inodedep *inodedep;
2120 {
2121 
2122 	if ((inodedep->id_state & ONWORKLIST) != 0 ||
2123 	    (inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
2124 	    LIST_FIRST(&inodedep->id_pendinghd) != NULL ||
2125 	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
2126 	    LIST_FIRST(&inodedep->id_inowait) != NULL ||
2127 	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
2128 	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL ||
2129 	    inodedep->id_nlinkdelta != 0 || inodedep->id_savedino != NULL)
2130 		return (0);
2131 	LIST_REMOVE(inodedep, id_hash);
2132 	WORKITEM_FREE(inodedep, D_INODEDEP);
2133 	num_inodedep -= 1;
2134 	return (1);
2135 }
2136 
2137 /*
2138  * This workitem routine performs the block de-allocation.
2139  * The workitem is added to the pending list after the updated
2140  * inode block has been written to disk.  As mentioned above,
2141  * checks regarding the number of blocks de-allocated (compared
2142  * to the number of blocks allocated for the file) are also
2143  * performed in this function.
2144  */
2145 static void
2146 handle_workitem_freeblocks(freeblks)
2147 	struct freeblks *freeblks;
2148 {
2149 	struct inode tip;
2150 	ufs_daddr_t bn;
2151 	struct fs *fs;
2152 	int i, level, bsize;
2153 	long nblocks, blocksreleased = 0;
2154 	int error, allerror = 0;
2155 	ufs_lbn_t baselbns[NIADDR], tmpval;
2156 
2157 	tip.i_number = freeblks->fb_previousinum;
2158 	tip.i_devvp = freeblks->fb_devvp;
2159 	tip.i_dev = freeblks->fb_devvp->v_rdev;
2160 	tip.i_fs = freeblks->fb_fs;
2161 	tip.i_size = freeblks->fb_oldsize;
2162 	tip.i_uid = freeblks->fb_uid;
2163 	fs = freeblks->fb_fs;
2164 	tmpval = 1;
2165 	baselbns[0] = NDADDR;
2166 	for (i = 1; i < NIADDR; i++) {
2167 		tmpval *= NINDIR(fs);
2168 		baselbns[i] = baselbns[i - 1] + tmpval;
2169 	}
2170 	nblocks = btodb(fs->fs_bsize);
2171 	blocksreleased = 0;
2172 	/*
2173 	 * Indirect blocks first.
2174 	 */
2175 	for (level = (NIADDR - 1); level >= 0; level--) {
2176 		if ((bn = freeblks->fb_iblks[level]) == 0)
2177 			continue;
2178 		if ((error = indir_trunc(&tip, fsbtodb(fs, bn), level,
2179 		    baselbns[level], &blocksreleased)) == 0)
2180 			allerror = error;
2181 		ffs_blkfree(&tip, bn, fs->fs_bsize);
2182 		blocksreleased += nblocks;
2183 	}
2184 	/*
2185 	 * All direct blocks or frags.
2186 	 */
2187 	for (i = (NDADDR - 1); i >= 0; i--) {
2188 		if ((bn = freeblks->fb_dblks[i]) == 0)
2189 			continue;
2190 		bsize = blksize(fs, &tip, i);
2191 		ffs_blkfree(&tip, bn, bsize);
2192 		blocksreleased += btodb(bsize);
2193 	}
2194 
2195 #ifdef DIAGNOSTIC
2196 	if (freeblks->fb_chkcnt != blocksreleased)
2197 		printf("handle_workitem_freeblocks: block count\n");
2198 	if (allerror)
2199 		softdep_error("handle_workitem_freeblks", allerror);
2200 #endif /* DIAGNOSTIC */
2201 	WORKITEM_FREE(freeblks, D_FREEBLKS);
2202 }
2203 
2204 /*
2205  * Release blocks associated with the inode ip and stored in the indirect
2206  * block dbn. If level is greater than SINGLE, the block is an indirect block
2207  * and recursive calls to indirtrunc must be used to cleanse other indirect
2208  * blocks.
2209  */
2210 static int
2211 indir_trunc(ip, dbn, level, lbn, countp)
2212 	struct inode *ip;
2213 	ufs_daddr_t dbn;
2214 	int level;
2215 	ufs_lbn_t lbn;
2216 	long *countp;
2217 {
2218 	struct buf *bp;
2219 	ufs_daddr_t *bap;
2220 	ufs_daddr_t nb;
2221 	struct fs *fs;
2222 	struct worklist *wk;
2223 	struct indirdep *indirdep;
2224 	int i, lbnadd, nblocks;
2225 	int error, allerror = 0;
2226 
2227 	fs = ip->i_fs;
2228 	lbnadd = 1;
2229 	for (i = level; i > 0; i--)
2230 		lbnadd *= NINDIR(fs);
2231 	/*
2232 	 * Get buffer of block pointers to be freed. This routine is not
2233 	 * called until the zero'ed inode has been written, so it is safe
2234 	 * to free blocks as they are encountered. Because the inode has
2235 	 * been zero'ed, calls to bmap on these blocks will fail. So, we
2236 	 * have to use the on-disk address and the block device for the
2237 	 * filesystem to look them up. If the file was deleted before its
2238 	 * indirect blocks were all written to disk, the routine that set
2239 	 * us up (deallocate_dependencies) will have arranged to leave
2240 	 * a complete copy of the indirect block in memory for our use.
2241 	 * Otherwise we have to read the blocks in from the disk.
2242 	 */
2243 	ACQUIRE_LOCK(&lk);
2244 	if ((bp = incore(ip->i_devvp, dbn)) != NULL &&
2245 	    (wk = LIST_FIRST(&bp->b_dep)) != NULL) {
2246 		if (wk->wk_type != D_INDIRDEP ||
2247 		    (indirdep = WK_INDIRDEP(wk))->ir_savebp != bp ||
2248 		    (indirdep->ir_state & GOINGAWAY) == 0) {
2249 			FREE_LOCK(&lk);
2250 			panic("indir_trunc: lost indirdep");
2251 		}
2252 		WORKLIST_REMOVE(wk);
2253 		WORKITEM_FREE(indirdep, D_INDIRDEP);
2254 		if (LIST_FIRST(&bp->b_dep) != NULL) {
2255 			FREE_LOCK(&lk);
2256 			panic("indir_trunc: dangling dep");
2257 		}
2258 		FREE_LOCK(&lk);
2259 	} else {
2260 		FREE_LOCK(&lk);
2261 		error = bread(ip->i_devvp, dbn, (int)fs->fs_bsize, &bp);
2262 		if (error)
2263 			return (error);
2264 	}
2265 	/*
2266 	 * Recursively free indirect blocks.
2267 	 */
2268 	bap = (ufs_daddr_t *)bp->b_data;
2269 	nblocks = btodb(fs->fs_bsize);
2270 	for (i = NINDIR(fs) - 1; i >= 0; i--) {
2271 		if ((nb = bap[i]) == 0)
2272 			continue;
2273 		if (level != 0) {
2274 			if ((error = indir_trunc(ip, fsbtodb(fs, nb),
2275 			     level - 1, lbn + (i * lbnadd), countp)) != 0)
2276 				allerror = error;
2277 		}
2278 		ffs_blkfree(ip, nb, fs->fs_bsize);
2279 		*countp += nblocks;
2280 	}
2281 	bp->b_flags |= B_INVAL | B_NOCACHE;
2282 	brelse(bp);
2283 	return (allerror);
2284 }
2285 
2286 /*
2287  * Free an allocindir.
2288  * This routine must be called with splbio interrupts blocked.
2289  */
2290 static void
2291 free_allocindir(aip, inodedep)
2292 	struct allocindir *aip;
2293 	struct inodedep *inodedep;
2294 {
2295 	struct freefrag *freefrag;
2296 
2297 #ifdef DEBUG
2298 	if (lk.lkt_held == NOHOLDER)
2299 		panic("free_allocindir: lock not held");
2300 #endif
2301 	if ((aip->ai_state & DEPCOMPLETE) == 0)
2302 		LIST_REMOVE(aip, ai_deps);
2303 	if (aip->ai_state & ONWORKLIST)
2304 		WORKLIST_REMOVE(&aip->ai_list);
2305 	LIST_REMOVE(aip, ai_next);
2306 	if ((freefrag = aip->ai_freefrag) != NULL) {
2307 		if (inodedep == NULL)
2308 			add_to_worklist(&freefrag->ff_list);
2309 		else
2310 			WORKLIST_INSERT(&inodedep->id_bufwait,
2311 			    &freefrag->ff_list);
2312 	}
2313 	WORKITEM_FREE(aip, D_ALLOCINDIR);
2314 }
2315 
2316 /*
2317  * Directory entry addition dependencies.
2318  *
2319  * When adding a new directory entry, the inode (with its incremented link
2320  * count) must be written to disk before the directory entry's pointer to it.
2321  * Also, if the inode is newly allocated, the corresponding freemap must be
2322  * updated (on disk) before the directory entry's pointer. These requirements
2323  * are met via undo/redo on the directory entry's pointer, which consists
2324  * simply of the inode number.
2325  *
2326  * As directory entries are added and deleted, the free space within a
2327  * directory block can become fragmented.  The ufs filesystem will compact
2328  * a fragmented directory block to make space for a new entry. When this
2329  * occurs, the offsets of previously added entries change. Any "diradd"
2330  * dependency structures corresponding to these entries must be updated with
2331  * the new offsets.
2332  */
2333 
2334 /*
2335  * This routine is called after the in-memory inode's link
2336  * count has been incremented, but before the directory entry's
2337  * pointer to the inode has been set.
2338  */
2339 void
2340 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp)
2341 	struct buf *bp;		/* buffer containing directory block */
2342 	struct inode *dp;	/* inode for directory */
2343 	off_t diroffset;	/* offset of new entry in directory */
2344 	ino_t newinum;		/* inode referenced by new directory entry */
2345 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
2346 {
2347 	int offset;		/* offset of new entry within directory block */
2348 	ufs_lbn_t lbn;		/* block in directory containing new entry */
2349 	struct fs *fs;
2350 	struct diradd *dap;
2351 	struct pagedep *pagedep;
2352 	struct inodedep *inodedep;
2353 	struct mkdir *mkdir1, *mkdir2;
2354 
2355 	/*
2356 	 * Whiteouts have no dependencies.
2357 	 */
2358 	if (newinum == WINO) {
2359 		if (newdirbp != NULL)
2360 			bdwrite(newdirbp);
2361 		return;
2362 	}
2363 
2364 	fs = dp->i_fs;
2365 	lbn = lblkno(fs, diroffset);
2366 	offset = blkoff(fs, diroffset);
2367 	MALLOC(dap, struct diradd *, sizeof(struct diradd), M_DIRADD,
2368 	    M_SOFTDEP_FLAGS);
2369 	bzero(dap, sizeof(struct diradd));
2370 	dap->da_list.wk_type = D_DIRADD;
2371 	dap->da_offset = offset;
2372 	dap->da_newinum = newinum;
2373 	dap->da_state = ATTACHED;
2374 	if (newdirbp == NULL) {
2375 		dap->da_state |= DEPCOMPLETE;
2376 		ACQUIRE_LOCK(&lk);
2377 	} else {
2378 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
2379 		MALLOC(mkdir1, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2380 		    M_SOFTDEP_FLAGS);
2381 		mkdir1->md_list.wk_type = D_MKDIR;
2382 		mkdir1->md_state = MKDIR_BODY;
2383 		mkdir1->md_diradd = dap;
2384 		MALLOC(mkdir2, struct mkdir *, sizeof(struct mkdir), M_MKDIR,
2385 		    M_SOFTDEP_FLAGS);
2386 		mkdir2->md_list.wk_type = D_MKDIR;
2387 		mkdir2->md_state = MKDIR_PARENT;
2388 		mkdir2->md_diradd = dap;
2389 		/*
2390 		 * Dependency on "." and ".." being written to disk.
2391 		 */
2392 		mkdir1->md_buf = newdirbp;
2393 		ACQUIRE_LOCK(&lk);
2394 		LIST_INSERT_HEAD(&mkdirlisthd, mkdir1, md_mkdirs);
2395 		WORKLIST_INSERT(&newdirbp->b_dep, &mkdir1->md_list);
2396 		FREE_LOCK(&lk);
2397 		bdwrite(newdirbp);
2398 		/*
2399 		 * Dependency on link count increase for parent directory
2400 		 */
2401 		ACQUIRE_LOCK(&lk);
2402 		if (inodedep_lookup(dp->i_fs, dp->i_number, 0, &inodedep) == 0
2403 		    || (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2404 			dap->da_state &= ~MKDIR_PARENT;
2405 			WORKITEM_FREE(mkdir2, D_MKDIR);
2406 		} else {
2407 			LIST_INSERT_HEAD(&mkdirlisthd, mkdir2, md_mkdirs);
2408 			WORKLIST_INSERT(&inodedep->id_bufwait,&mkdir2->md_list);
2409 		}
2410 	}
2411 	/*
2412 	 * Link into parent directory pagedep to await its being written.
2413 	 */
2414 	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2415 		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2416 	dap->da_pagedep = pagedep;
2417 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
2418 	    da_pdlist);
2419 	/*
2420 	 * Link into its inodedep. Put it on the id_bufwait list if the inode
2421 	 * is not yet written. If it is written, do the post-inode write
2422 	 * processing to put it on the id_pendinghd list.
2423 	 */
2424 	(void) inodedep_lookup(fs, newinum, DEPALLOC, &inodedep);
2425 	if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
2426 		diradd_inode_written(dap, inodedep);
2427 	else
2428 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2429 	FREE_LOCK(&lk);
2430 }
2431 
2432 /*
2433  * This procedure is called to change the offset of a directory
2434  * entry when compacting a directory block which must be owned
2435  * exclusively by the caller. Note that the actual entry movement
2436  * must be done in this procedure to ensure that no I/O completions
2437  * occur while the move is in progress.
2438  */
2439 void
2440 softdep_change_directoryentry_offset(dp, base, oldloc, newloc, entrysize)
2441 	struct inode *dp;	/* inode for directory */
2442 	caddr_t base;		/* address of dp->i_offset */
2443 	caddr_t oldloc;		/* address of old directory location */
2444 	caddr_t newloc;		/* address of new directory location */
2445 	int entrysize;		/* size of directory entry */
2446 {
2447 	int offset, oldoffset, newoffset;
2448 	struct pagedep *pagedep;
2449 	struct diradd *dap;
2450 	ufs_lbn_t lbn;
2451 
2452 	ACQUIRE_LOCK(&lk);
2453 	lbn = lblkno(dp->i_fs, dp->i_offset);
2454 	offset = blkoff(dp->i_fs, dp->i_offset);
2455 	if (pagedep_lookup(dp, lbn, 0, &pagedep) == 0)
2456 		goto done;
2457 	oldoffset = offset + (oldloc - base);
2458 	newoffset = offset + (newloc - base);
2459 
2460 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(oldoffset)], da_pdlist) {
2461 		if (dap->da_offset != oldoffset)
2462 			continue;
2463 		dap->da_offset = newoffset;
2464 		if (DIRADDHASH(newoffset) == DIRADDHASH(oldoffset))
2465 			break;
2466 		LIST_REMOVE(dap, da_pdlist);
2467 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(newoffset)],
2468 		    dap, da_pdlist);
2469 		break;
2470 	}
2471 	if (dap == NULL) {
2472 
2473 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist) {
2474 			if (dap->da_offset == oldoffset) {
2475 				dap->da_offset = newoffset;
2476 				break;
2477 			}
2478 		}
2479 	}
2480 done:
2481 	bcopy(oldloc, newloc, entrysize);
2482 	FREE_LOCK(&lk);
2483 }
2484 
2485 /*
2486  * Free a diradd dependency structure. This routine must be called
2487  * with splbio interrupts blocked.
2488  */
2489 static void
2490 free_diradd(dap)
2491 	struct diradd *dap;
2492 {
2493 	struct dirrem *dirrem;
2494 	struct pagedep *pagedep;
2495 	struct inodedep *inodedep;
2496 	struct mkdir *mkdir, *nextmd;
2497 
2498 #ifdef DEBUG
2499 	if (lk.lkt_held == NOHOLDER)
2500 		panic("free_diradd: lock not held");
2501 #endif
2502 	WORKLIST_REMOVE(&dap->da_list);
2503 	LIST_REMOVE(dap, da_pdlist);
2504 	if ((dap->da_state & DIRCHG) == 0) {
2505 		pagedep = dap->da_pagedep;
2506 	} else {
2507 		dirrem = dap->da_previous;
2508 		pagedep = dirrem->dm_pagedep;
2509 		dirrem->dm_dirinum = pagedep->pd_ino;
2510 		add_to_worklist(&dirrem->dm_list);
2511 	}
2512 	if (inodedep_lookup(VFSTOUFS(pagedep->pd_mnt)->um_fs, dap->da_newinum,
2513 	    0, &inodedep) != 0)
2514 		(void) free_inodedep(inodedep);
2515 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2516 		for (mkdir = LIST_FIRST(&mkdirlisthd); mkdir; mkdir = nextmd) {
2517 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
2518 			if (mkdir->md_diradd != dap)
2519 				continue;
2520 			dap->da_state &= ~mkdir->md_state;
2521 			WORKLIST_REMOVE(&mkdir->md_list);
2522 			LIST_REMOVE(mkdir, md_mkdirs);
2523 			WORKITEM_FREE(mkdir, D_MKDIR);
2524 		}
2525 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
2526 			FREE_LOCK(&lk);
2527 			panic("free_diradd: unfound ref");
2528 		}
2529 	}
2530 	WORKITEM_FREE(dap, D_DIRADD);
2531 }
2532 
2533 /*
2534  * Directory entry removal dependencies.
2535  *
2536  * When removing a directory entry, the entry's inode pointer must be
2537  * zero'ed on disk before the corresponding inode's link count is decremented
2538  * (possibly freeing the inode for re-use). This dependency is handled by
2539  * updating the directory entry but delaying the inode count reduction until
2540  * after the directory block has been written to disk. After this point, the
2541  * inode count can be decremented whenever it is convenient.
2542  */
2543 
2544 /*
2545  * This routine should be called immediately after removing
2546  * a directory entry.  The inode's link count should not be
2547  * decremented by the calling procedure -- the soft updates
2548  * code will do this task when it is safe.
2549  */
2550 void
2551 softdep_setup_remove(bp, dp, ip, isrmdir)
2552 	struct buf *bp;		/* buffer containing directory block */
2553 	struct inode *dp;	/* inode for the directory being modified */
2554 	struct inode *ip;	/* inode for directory entry being removed */
2555 	int isrmdir;		/* indicates if doing RMDIR */
2556 {
2557 	struct dirrem *dirrem, *prevdirrem;
2558 
2559 	/*
2560 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.
2561 	 */
2562 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2563 
2564 	/*
2565 	 * If the COMPLETE flag is clear, then there were no active
2566 	 * entries and we want to roll back to a zeroed entry until
2567 	 * the new inode is committed to disk. If the COMPLETE flag is
2568 	 * set then we have deleted an entry that never made it to
2569 	 * disk. If the entry we deleted resulted from a name change,
2570 	 * then the old name still resides on disk. We cannot delete
2571 	 * its inode (returned to us in prevdirrem) until the zeroed
2572 	 * directory entry gets to disk. The new inode has never been
2573 	 * referenced on the disk, so can be deleted immediately.
2574 	 */
2575 	if ((dirrem->dm_state & COMPLETE) == 0) {
2576 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
2577 		    dm_next);
2578 		FREE_LOCK(&lk);
2579 	} else {
2580 		if (prevdirrem != NULL)
2581 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
2582 			    prevdirrem, dm_next);
2583 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
2584 		FREE_LOCK(&lk);
2585 		handle_workitem_remove(dirrem);
2586 	}
2587 }
2588 
2589 /*
2590  * Allocate a new dirrem if appropriate and return it along with
2591  * its associated pagedep. Called without a lock, returns with lock.
2592  */
2593 static long num_dirrem;		/* number of dirrem allocated */
2594 static struct dirrem *
2595 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
2596 	struct buf *bp;		/* buffer containing directory block */
2597 	struct inode *dp;	/* inode for the directory being modified */
2598 	struct inode *ip;	/* inode for directory entry being removed */
2599 	int isrmdir;		/* indicates if doing RMDIR */
2600 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
2601 {
2602 	int offset;
2603 	ufs_lbn_t lbn;
2604 	struct diradd *dap;
2605 	struct dirrem *dirrem;
2606 	struct pagedep *pagedep;
2607 
2608 	/*
2609 	 * Whiteouts have no deletion dependencies.
2610 	 */
2611 	if (ip == NULL)
2612 		panic("newdirrem: whiteout");
2613 	/*
2614 	 * If we are over our limit, try to improve the situation.
2615 	 * Limiting the number of dirrem structures will also limit
2616 	 * the number of freefile and freeblks structures.
2617 	 */
2618 	if (num_dirrem > max_softdeps / 2 && speedup_syncer() == 0)
2619 		(void) request_cleanup(FLUSH_REMOVE, 0);
2620 	num_dirrem += 1;
2621 	MALLOC(dirrem, struct dirrem *, sizeof(struct dirrem),
2622 		M_DIRREM, M_SOFTDEP_FLAGS);
2623 	bzero(dirrem, sizeof(struct dirrem));
2624 	dirrem->dm_list.wk_type = D_DIRREM;
2625 	dirrem->dm_state = isrmdir ? RMDIR : 0;
2626 	dirrem->dm_mnt = ITOV(ip)->v_mount;
2627 	dirrem->dm_oldinum = ip->i_number;
2628 	*prevdirremp = NULL;
2629 
2630 	ACQUIRE_LOCK(&lk);
2631 	lbn = lblkno(dp->i_fs, dp->i_offset);
2632 	offset = blkoff(dp->i_fs, dp->i_offset);
2633 	if (pagedep_lookup(dp, lbn, DEPALLOC, &pagedep) == 0)
2634 		WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2635 	dirrem->dm_pagedep = pagedep;
2636 	/*
2637 	 * Check for a diradd dependency for the same directory entry.
2638 	 * If present, then both dependencies become obsolete and can
2639 	 * be de-allocated. Check for an entry on both the pd_dirraddhd
2640 	 * list and the pd_pendinghd list.
2641 	 */
2642 
2643 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
2644 		if (dap->da_offset == offset)
2645 			break;
2646 	if (dap == NULL) {
2647 
2648 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
2649 			if (dap->da_offset == offset)
2650 				break;
2651 		if (dap == NULL)
2652 			return (dirrem);
2653 	}
2654 	/*
2655 	 * Must be ATTACHED at this point.
2656 	 */
2657 	if ((dap->da_state & ATTACHED) == 0) {
2658 		FREE_LOCK(&lk);
2659 		panic("newdirrem: not ATTACHED");
2660 	}
2661 	if (dap->da_newinum != ip->i_number) {
2662 		FREE_LOCK(&lk);
2663 		panic("newdirrem: inum %d should be %d",
2664 		    ip->i_number, dap->da_newinum);
2665 	}
2666 	/*
2667 	 * If we are deleting a changed name that never made it to disk,
2668 	 * then return the dirrem describing the previous inode (which
2669 	 * represents the inode currently referenced from this entry on disk).
2670 	 */
2671 	if ((dap->da_state & DIRCHG) != 0) {
2672 		*prevdirremp = dap->da_previous;
2673 		dap->da_state &= ~DIRCHG;
2674 		dap->da_pagedep = pagedep;
2675 	}
2676 	/*
2677 	 * We are deleting an entry that never made it to disk.
2678 	 * Mark it COMPLETE so we can delete its inode immediately.
2679 	 */
2680 	dirrem->dm_state |= COMPLETE;
2681 	free_diradd(dap);
2682 	return (dirrem);
2683 }
2684 
2685 /*
2686  * Directory entry change dependencies.
2687  *
2688  * Changing an existing directory entry requires that an add operation
2689  * be completed first followed by a deletion. The semantics for the addition
2690  * are identical to the description of adding a new entry above except
2691  * that the rollback is to the old inode number rather than zero. Once
2692  * the addition dependency is completed, the removal is done as described
2693  * in the removal routine above.
2694  */
2695 
2696 /*
2697  * This routine should be called immediately after changing
2698  * a directory entry.  The inode's link count should not be
2699  * decremented by the calling procedure -- the soft updates
2700  * code will perform this task when it is safe.
2701  */
2702 void
2703 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
2704 	struct buf *bp;		/* buffer containing directory block */
2705 	struct inode *dp;	/* inode for the directory being modified */
2706 	struct inode *ip;	/* inode for directory entry being removed */
2707 	ino_t newinum;		/* new inode number for changed entry */
2708 	int isrmdir;		/* indicates if doing RMDIR */
2709 {
2710 	int offset;
2711 	struct diradd *dap = NULL;
2712 	struct dirrem *dirrem, *prevdirrem;
2713 	struct pagedep *pagedep;
2714 	struct inodedep *inodedep;
2715 
2716 	offset = blkoff(dp->i_fs, dp->i_offset);
2717 
2718 	/*
2719 	 * Whiteouts do not need diradd dependencies.
2720 	 */
2721 	if (newinum != WINO) {
2722 		MALLOC(dap, struct diradd *, sizeof(struct diradd),
2723 		    M_DIRADD, M_SOFTDEP_FLAGS);
2724 		bzero(dap, sizeof(struct diradd));
2725 		dap->da_list.wk_type = D_DIRADD;
2726 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
2727 		dap->da_offset = offset;
2728 		dap->da_newinum = newinum;
2729 	}
2730 
2731 	/*
2732 	 * Allocate a new dirrem and ACQUIRE_LOCK.
2733 	 */
2734 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
2735 	pagedep = dirrem->dm_pagedep;
2736 	/*
2737 	 * The possible values for isrmdir:
2738 	 *	0 - non-directory file rename
2739 	 *	1 - directory rename within same directory
2740 	 *   inum - directory rename to new directory of given inode number
2741 	 * When renaming to a new directory, we are both deleting and
2742 	 * creating a new directory entry, so the link count on the new
2743 	 * directory should not change. Thus we do not need the followup
2744 	 * dirrem which is usually done in handle_workitem_remove. We set
2745 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
2746 	 * followup dirrem.
2747 	 */
2748 	if (isrmdir > 1)
2749 		dirrem->dm_state |= DIRCHG;
2750 
2751 	/*
2752 	 * Whiteouts have no additional dependencies,
2753 	 * so just put the dirrem on the correct list.
2754 	 */
2755 	if (newinum == WINO) {
2756 		if ((dirrem->dm_state & COMPLETE) == 0) {
2757 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
2758 			    dm_next);
2759 		} else {
2760 			dirrem->dm_dirinum = pagedep->pd_ino;
2761 			add_to_worklist(&dirrem->dm_list);
2762 		}
2763 		FREE_LOCK(&lk);
2764 		return;
2765 	}
2766 
2767 	/*
2768 	 * If the COMPLETE flag is clear, then there were no active
2769 	 * entries and we want to roll back to the previous inode until
2770 	 * the new inode is committed to disk. If the COMPLETE flag is
2771 	 * set, then we have deleted an entry that never made it to disk.
2772 	 * If the entry we deleted resulted from a name change, then the old
2773 	 * inode reference still resides on disk. Any rollback that we do
2774 	 * needs to be to that old inode (returned to us in prevdirrem). If
2775 	 * the entry we deleted resulted from a create, then there is
2776 	 * no entry on the disk, so we want to roll back to zero rather
2777 	 * than the uncommitted inode. In either of the COMPLETE cases we
2778 	 * want to immediately free the unwritten and unreferenced inode.
2779 	 */
2780 	if ((dirrem->dm_state & COMPLETE) == 0) {
2781 		dap->da_previous = dirrem;
2782 	} else {
2783 		if (prevdirrem != NULL) {
2784 			dap->da_previous = prevdirrem;
2785 		} else {
2786 			dap->da_state &= ~DIRCHG;
2787 			dap->da_pagedep = pagedep;
2788 		}
2789 		dirrem->dm_dirinum = pagedep->pd_ino;
2790 		add_to_worklist(&dirrem->dm_list);
2791 	}
2792 	/*
2793 	 * Link into its inodedep. Put it on the id_bufwait list if the inode
2794 	 * is not yet written. If it is written, do the post-inode write
2795 	 * processing to put it on the id_pendinghd list.
2796 	 */
2797 	if (inodedep_lookup(dp->i_fs, newinum, DEPALLOC, &inodedep) == 0 ||
2798 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
2799 		dap->da_state |= COMPLETE;
2800 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
2801 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
2802 	} else {
2803 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
2804 		    dap, da_pdlist);
2805 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
2806 	}
2807 	FREE_LOCK(&lk);
2808 }
2809 
2810 /*
2811  * Called whenever the link count on an inode is changed.
2812  * It creates an inode dependency so that the new reference(s)
2813  * to the inode cannot be committed to disk until the updated
2814  * inode has been written.
2815  */
2816 void
2817 softdep_change_linkcnt(ip)
2818 	struct inode *ip;	/* the inode with the increased link count */
2819 {
2820 	struct inodedep *inodedep;
2821 
2822 	ACQUIRE_LOCK(&lk);
2823 	(void) inodedep_lookup(ip->i_fs, ip->i_number, DEPALLOC, &inodedep);
2824 	if (ip->i_nlink < ip->i_effnlink) {
2825 		FREE_LOCK(&lk);
2826 		panic("softdep_change_linkcnt: bad delta");
2827 	}
2828 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2829 	FREE_LOCK(&lk);
2830 }
2831 
2832 /*
2833  * This workitem decrements the inode's link count.
2834  * If the link count reaches zero, the file is removed.
2835  */
2836 static void
2837 handle_workitem_remove(dirrem)
2838 	struct dirrem *dirrem;
2839 {
2840 	struct thread *td = curthread;	/* XXX */
2841 	struct inodedep *inodedep;
2842 	struct vnode *vp;
2843 	struct inode *ip;
2844 	ino_t oldinum;
2845 	int error;
2846 
2847 	if ((error = VFS_VGET(dirrem->dm_mnt, dirrem->dm_oldinum, &vp)) != 0) {
2848 		softdep_error("handle_workitem_remove: vget", error);
2849 		return;
2850 	}
2851 	ip = VTOI(vp);
2852 	ACQUIRE_LOCK(&lk);
2853 	if ((inodedep_lookup(ip->i_fs, dirrem->dm_oldinum, 0, &inodedep)) == 0){
2854 		FREE_LOCK(&lk);
2855 		panic("handle_workitem_remove: lost inodedep");
2856 	}
2857 	/*
2858 	 * Normal file deletion.
2859 	 */
2860 	if ((dirrem->dm_state & RMDIR) == 0) {
2861 		ip->i_nlink--;
2862 		ip->i_flag |= IN_CHANGE;
2863 		if (ip->i_nlink < ip->i_effnlink) {
2864 			FREE_LOCK(&lk);
2865 			panic("handle_workitem_remove: bad file delta");
2866 		}
2867 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2868 		FREE_LOCK(&lk);
2869 		vput(vp);
2870 		num_dirrem -= 1;
2871 		WORKITEM_FREE(dirrem, D_DIRREM);
2872 		return;
2873 	}
2874 	/*
2875 	 * Directory deletion. Decrement reference count for both the
2876 	 * just deleted parent directory entry and the reference for ".".
2877 	 * Next truncate the directory to length zero. When the
2878 	 * truncation completes, arrange to have the reference count on
2879 	 * the parent decremented to account for the loss of "..".
2880 	 */
2881 	ip->i_nlink -= 2;
2882 	ip->i_flag |= IN_CHANGE;
2883 	if (ip->i_nlink < ip->i_effnlink) {
2884 		FREE_LOCK(&lk);
2885 		panic("handle_workitem_remove: bad dir delta");
2886 	}
2887 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
2888 	FREE_LOCK(&lk);
2889 	if ((error = UFS_TRUNCATE(vp, (off_t)0, 0, proc0.p_ucred, td)) != 0)
2890 		softdep_error("handle_workitem_remove: truncate", error);
2891 	/*
2892 	 * Rename a directory to a new parent. Since, we are both deleting
2893 	 * and creating a new directory entry, the link count on the new
2894 	 * directory should not change. Thus we skip the followup dirrem.
2895 	 */
2896 	if (dirrem->dm_state & DIRCHG) {
2897 		vput(vp);
2898 		num_dirrem -= 1;
2899 		WORKITEM_FREE(dirrem, D_DIRREM);
2900 		return;
2901 	}
2902 	/*
2903 	 * If the inodedep does not exist, then the zero'ed inode has
2904 	 * been written to disk. If the allocated inode has never been
2905 	 * written to disk, then the on-disk inode is zero'ed. In either
2906 	 * case we can remove the file immediately.
2907 	 */
2908 	ACQUIRE_LOCK(&lk);
2909 	dirrem->dm_state = 0;
2910 	oldinum = dirrem->dm_oldinum;
2911 	dirrem->dm_oldinum = dirrem->dm_dirinum;
2912 	if (inodedep_lookup(ip->i_fs, oldinum, 0, &inodedep) == 0 ||
2913 	    check_inode_unwritten(inodedep)) {
2914 		FREE_LOCK(&lk);
2915 		vput(vp);
2916 		handle_workitem_remove(dirrem);
2917 		return;
2918 	}
2919 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
2920 	FREE_LOCK(&lk);
2921 	vput(vp);
2922 }
2923 
2924 /*
2925  * Inode de-allocation dependencies.
2926  *
2927  * When an inode's link count is reduced to zero, it can be de-allocated. We
2928  * found it convenient to postpone de-allocation until after the inode is
2929  * written to disk with its new link count (zero).  At this point, all of the
2930  * on-disk inode's block pointers are nullified and, with careful dependency
2931  * list ordering, all dependencies related to the inode will be satisfied and
2932  * the corresponding dependency structures de-allocated.  So, if/when the
2933  * inode is reused, there will be no mixing of old dependencies with new
2934  * ones.  This artificial dependency is set up by the block de-allocation
2935  * procedure above (softdep_setup_freeblocks) and completed by the
2936  * following procedure.
2937  */
2938 static void
2939 handle_workitem_freefile(freefile)
2940 	struct freefile *freefile;
2941 {
2942 	struct vnode vp;
2943 	struct inode tip;
2944 	struct inodedep *idp;
2945 	int error;
2946 
2947 #ifdef DEBUG
2948 	ACQUIRE_LOCK(&lk);
2949 	error = inodedep_lookup(freefile->fx_fs, freefile->fx_oldinum, 0, &idp);
2950 	FREE_LOCK(&lk);
2951 	if (error)
2952 		panic("handle_workitem_freefile: inodedep survived");
2953 #endif
2954 	tip.i_devvp = freefile->fx_devvp;
2955 	tip.i_dev = freefile->fx_devvp->v_rdev;
2956 	tip.i_fs = freefile->fx_fs;
2957 	vp.v_data = &tip;
2958 	if ((error = ffs_freefile(&vp, freefile->fx_oldinum, freefile->fx_mode)) != 0)
2959 		softdep_error("handle_workitem_freefile", error);
2960 	WORKITEM_FREE(freefile, D_FREEFILE);
2961 }
2962 
2963 /*
2964  * Disk writes.
2965  *
2966  * The dependency structures constructed above are most actively used when file
2967  * system blocks are written to disk.  No constraints are placed on when a
2968  * block can be written, but unsatisfied update dependencies are made safe by
2969  * modifying (or replacing) the source memory for the duration of the disk
2970  * write.  When the disk write completes, the memory block is again brought
2971  * up-to-date.
2972  *
2973  * In-core inode structure reclamation.
2974  *
2975  * Because there are a finite number of "in-core" inode structures, they are
2976  * reused regularly.  By transferring all inode-related dependencies to the
2977  * in-memory inode block and indexing them separately (via "inodedep"s), we
2978  * can allow "in-core" inode structures to be reused at any time and avoid
2979  * any increase in contention.
2980  *
2981  * Called just before entering the device driver to initiate a new disk I/O.
2982  * The buffer must be locked, thus, no I/O completion operations can occur
2983  * while we are manipulating its associated dependencies.
2984  */
2985 static void
2986 softdep_disk_io_initiation(bp)
2987 	struct buf *bp;		/* structure describing disk write to occur */
2988 {
2989 	struct worklist *wk, *nextwk;
2990 	struct indirdep *indirdep;
2991 
2992 	/*
2993 	 * We only care about write operations. There should never
2994 	 * be dependencies for reads.
2995 	 */
2996 	if (bp->b_flags & B_READ)
2997 		panic("softdep_disk_io_initiation: read");
2998 	/*
2999 	 * Do any necessary pre-I/O processing.
3000 	 */
3001 	for (wk = LIST_FIRST(&bp->b_dep); wk; wk = nextwk) {
3002 		nextwk = LIST_NEXT(wk, wk_list);
3003 		switch (wk->wk_type) {
3004 
3005 		case D_PAGEDEP:
3006 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
3007 			continue;
3008 
3009 		case D_INODEDEP:
3010 			initiate_write_inodeblock(WK_INODEDEP(wk), bp);
3011 			continue;
3012 
3013 		case D_INDIRDEP:
3014 			indirdep = WK_INDIRDEP(wk);
3015 			if (indirdep->ir_state & GOINGAWAY)
3016 				panic("disk_io_initiation: indirdep gone");
3017 			/*
3018 			 * If there are no remaining dependencies, this
3019 			 * will be writing the real pointers, so the
3020 			 * dependency can be freed.
3021 			 */
3022 			if (LIST_FIRST(&indirdep->ir_deplisthd) == NULL) {
3023 				indirdep->ir_savebp->b_flags |= B_INVAL | B_NOCACHE;
3024 				brelse(indirdep->ir_savebp);
3025 				/* inline expand WORKLIST_REMOVE(wk); */
3026 				wk->wk_state &= ~ONWORKLIST;
3027 				LIST_REMOVE(wk, wk_list);
3028 				WORKITEM_FREE(indirdep, D_INDIRDEP);
3029 				continue;
3030 			}
3031 			/*
3032 			 * Replace up-to-date version with safe version.
3033 			 */
3034 			MALLOC(indirdep->ir_saveddata, caddr_t, bp->b_bcount,
3035 			    M_INDIRDEP, M_SOFTDEP_FLAGS);
3036 			ACQUIRE_LOCK(&lk);
3037 			indirdep->ir_state &= ~ATTACHED;
3038 			indirdep->ir_state |= UNDONE;
3039 			bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
3040 			bcopy(indirdep->ir_savebp->b_data, bp->b_data,
3041 			    bp->b_bcount);
3042 			FREE_LOCK(&lk);
3043 			continue;
3044 
3045 		case D_MKDIR:
3046 		case D_BMSAFEMAP:
3047 		case D_ALLOCDIRECT:
3048 		case D_ALLOCINDIR:
3049 			continue;
3050 
3051 		default:
3052 			panic("handle_disk_io_initiation: Unexpected type %s",
3053 			    TYPENAME(wk->wk_type));
3054 			/* NOTREACHED */
3055 		}
3056 	}
3057 }
3058 
3059 /*
3060  * Called from within the procedure above to deal with unsatisfied
3061  * allocation dependencies in a directory. The buffer must be locked,
3062  * thus, no I/O completion operations can occur while we are
3063  * manipulating its associated dependencies.
3064  */
3065 static void
3066 initiate_write_filepage(pagedep, bp)
3067 	struct pagedep *pagedep;
3068 	struct buf *bp;
3069 {
3070 	struct diradd *dap;
3071 	struct direct *ep;
3072 	int i;
3073 
3074 	if (pagedep->pd_state & IOSTARTED) {
3075 		/*
3076 		 * This can only happen if there is a driver that does not
3077 		 * understand chaining. Here biodone will reissue the call
3078 		 * to strategy for the incomplete buffers.
3079 		 */
3080 		printf("initiate_write_filepage: already started\n");
3081 		return;
3082 	}
3083 	pagedep->pd_state |= IOSTARTED;
3084 	ACQUIRE_LOCK(&lk);
3085 	for (i = 0; i < DAHASHSZ; i++) {
3086 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
3087 			ep = (struct direct *)
3088 			    ((char *)bp->b_data + dap->da_offset);
3089 			if (ep->d_ino != dap->da_newinum) {
3090 				FREE_LOCK(&lk);
3091 				panic("%s: dir inum %d != new %d",
3092 				    "initiate_write_filepage",
3093 				    ep->d_ino, dap->da_newinum);
3094 			}
3095 			if (dap->da_state & DIRCHG)
3096 				ep->d_ino = dap->da_previous->dm_oldinum;
3097 			else
3098 				ep->d_ino = 0;
3099 			dap->da_state &= ~ATTACHED;
3100 			dap->da_state |= UNDONE;
3101 		}
3102 	}
3103 	FREE_LOCK(&lk);
3104 }
3105 
3106 /*
3107  * Called from within the procedure above to deal with unsatisfied
3108  * allocation dependencies in an inodeblock. The buffer must be
3109  * locked, thus, no I/O completion operations can occur while we
3110  * are manipulating its associated dependencies.
3111  */
3112 static void
3113 initiate_write_inodeblock(inodedep, bp)
3114 	struct inodedep *inodedep;
3115 	struct buf *bp;			/* The inode block */
3116 {
3117 	struct allocdirect *adp, *lastadp;
3118 	struct dinode *dp;
3119 	struct fs *fs;
3120 	ufs_lbn_t prevlbn = 0;
3121 	int i, deplist;
3122 
3123 	if (inodedep->id_state & IOSTARTED)
3124 		panic("initiate_write_inodeblock: already started");
3125 	inodedep->id_state |= IOSTARTED;
3126 	fs = inodedep->id_fs;
3127 	dp = (struct dinode *)bp->b_data +
3128 	    ino_to_fsbo(fs, inodedep->id_ino);
3129 	/*
3130 	 * If the bitmap is not yet written, then the allocated
3131 	 * inode cannot be written to disk.
3132 	 */
3133 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
3134 		if (inodedep->id_savedino != NULL)
3135 			panic("initiate_write_inodeblock: already doing I/O");
3136 		MALLOC(inodedep->id_savedino, struct dinode *,
3137 		    sizeof(struct dinode), M_INODEDEP, M_SOFTDEP_FLAGS);
3138 		*inodedep->id_savedino = *dp;
3139 		bzero((caddr_t)dp, sizeof(struct dinode));
3140 		return;
3141 	}
3142 	/*
3143 	 * If no dependencies, then there is nothing to roll back.
3144 	 */
3145 	inodedep->id_savedsize = dp->di_size;
3146 	if (TAILQ_FIRST(&inodedep->id_inoupdt) == NULL)
3147 		return;
3148 	/*
3149 	 * Set the dependencies to busy.
3150 	 */
3151 	ACQUIRE_LOCK(&lk);
3152 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3153 	     adp = TAILQ_NEXT(adp, ad_next)) {
3154 #ifdef DIAGNOSTIC
3155 		if (deplist != 0 && prevlbn >= adp->ad_lbn) {
3156 			FREE_LOCK(&lk);
3157 			panic("softdep_write_inodeblock: lbn order");
3158 		}
3159 		prevlbn = adp->ad_lbn;
3160 		if (adp->ad_lbn < NDADDR &&
3161 		    dp->di_db[adp->ad_lbn] != adp->ad_newblkno) {
3162 			FREE_LOCK(&lk);
3163 			panic("%s: direct pointer #%ld mismatch %d != %d",
3164 			    "softdep_write_inodeblock", adp->ad_lbn,
3165 			    dp->di_db[adp->ad_lbn], adp->ad_newblkno);
3166 		}
3167 		if (adp->ad_lbn >= NDADDR &&
3168 		    dp->di_ib[adp->ad_lbn - NDADDR] != adp->ad_newblkno) {
3169 			FREE_LOCK(&lk);
3170 			panic("%s: indirect pointer #%ld mismatch %d != %d",
3171 			    "softdep_write_inodeblock", adp->ad_lbn - NDADDR,
3172 			    dp->di_ib[adp->ad_lbn - NDADDR], adp->ad_newblkno);
3173 		}
3174 		deplist |= 1 << adp->ad_lbn;
3175 		if ((adp->ad_state & ATTACHED) == 0) {
3176 			FREE_LOCK(&lk);
3177 			panic("softdep_write_inodeblock: Unknown state 0x%x",
3178 			    adp->ad_state);
3179 		}
3180 #endif /* DIAGNOSTIC */
3181 		adp->ad_state &= ~ATTACHED;
3182 		adp->ad_state |= UNDONE;
3183 	}
3184 	/*
3185 	 * The on-disk inode cannot claim to be any larger than the last
3186 	 * fragment that has been written. Otherwise, the on-disk inode
3187 	 * might have fragments that were not the last block in the file
3188 	 * which would corrupt the filesystem.
3189 	 */
3190 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
3191 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
3192 		if (adp->ad_lbn >= NDADDR)
3193 			break;
3194 		dp->di_db[adp->ad_lbn] = adp->ad_oldblkno;
3195 		/* keep going until hitting a rollback to a frag */
3196 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
3197 			continue;
3198 		dp->di_size = fs->fs_bsize * adp->ad_lbn + adp->ad_oldsize;
3199 		for (i = adp->ad_lbn + 1; i < NDADDR; i++) {
3200 #ifdef DIAGNOSTIC
3201 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0) {
3202 				FREE_LOCK(&lk);
3203 				panic("softdep_write_inodeblock: lost dep1");
3204 			}
3205 #endif /* DIAGNOSTIC */
3206 			dp->di_db[i] = 0;
3207 		}
3208 		for (i = 0; i < NIADDR; i++) {
3209 #ifdef DIAGNOSTIC
3210 			if (dp->di_ib[i] != 0 &&
3211 			    (deplist & ((1 << NDADDR) << i)) == 0) {
3212 				FREE_LOCK(&lk);
3213 				panic("softdep_write_inodeblock: lost dep2");
3214 			}
3215 #endif /* DIAGNOSTIC */
3216 			dp->di_ib[i] = 0;
3217 		}
3218 		FREE_LOCK(&lk);
3219 		return;
3220 	}
3221 	/*
3222 	 * If we have zero'ed out the last allocated block of the file,
3223 	 * roll back the size to the last currently allocated block.
3224 	 * We know that this last allocated block is a full-sized as
3225 	 * we already checked for fragments in the loop above.
3226 	 */
3227 	if (lastadp != NULL &&
3228 	    dp->di_size <= (lastadp->ad_lbn + 1) * fs->fs_bsize) {
3229 		for (i = lastadp->ad_lbn; i >= 0; i--)
3230 			if (dp->di_db[i] != 0)
3231 				break;
3232 		dp->di_size = (i + 1) * fs->fs_bsize;
3233 	}
3234 	/*
3235 	 * The only dependencies are for indirect blocks.
3236 	 *
3237 	 * The file size for indirect block additions is not guaranteed.
3238 	 * Such a guarantee would be non-trivial to achieve. The conventional
3239 	 * synchronous write implementation also does not make this guarantee.
3240 	 * Fsck should catch and fix discrepancies. Arguably, the file size
3241 	 * can be over-estimated without destroying integrity when the file
3242 	 * moves into the indirect blocks (i.e., is large). If we want to
3243 	 * postpone fsck, we are stuck with this argument.
3244 	 */
3245 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
3246 		dp->di_ib[adp->ad_lbn - NDADDR] = 0;
3247 	FREE_LOCK(&lk);
3248 }
3249 
3250 /*
3251  * This routine is called during the completion interrupt
3252  * service routine for a disk write (from the procedure called
3253  * by the device driver to inform the filesystem caches of
3254  * a request completion).  It should be called early in this
3255  * procedure, before the block is made available to other
3256  * processes or other routines are called.
3257  */
3258 static void
3259 softdep_disk_write_complete(bp)
3260 	struct buf *bp;		/* describes the completed disk write */
3261 {
3262 	struct worklist *wk;
3263 	struct workhead reattach;
3264 	struct newblk *newblk;
3265 	struct allocindir *aip;
3266 	struct allocdirect *adp;
3267 	struct indirdep *indirdep;
3268 	struct inodedep *inodedep;
3269 	struct bmsafemap *bmsafemap;
3270 
3271 #ifdef DEBUG
3272 	if (lk.lkt_held != NOHOLDER)
3273 		panic("softdep_disk_write_complete: lock is held");
3274 	lk.lkt_held = SPECIAL_FLAG;
3275 #endif
3276 	LIST_INIT(&reattach);
3277 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
3278 		WORKLIST_REMOVE(wk);
3279 		switch (wk->wk_type) {
3280 
3281 		case D_PAGEDEP:
3282 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
3283 				WORKLIST_INSERT(&reattach, wk);
3284 			continue;
3285 
3286 		case D_INODEDEP:
3287 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
3288 				WORKLIST_INSERT(&reattach, wk);
3289 			continue;
3290 
3291 		case D_BMSAFEMAP:
3292 			bmsafemap = WK_BMSAFEMAP(wk);
3293 			while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkhd))) {
3294 				newblk->nb_state |= DEPCOMPLETE;
3295 				newblk->nb_bmsafemap = NULL;
3296 				LIST_REMOVE(newblk, nb_deps);
3297 			}
3298 			while ((adp =
3299 			   LIST_FIRST(&bmsafemap->sm_allocdirecthd))) {
3300 				adp->ad_state |= DEPCOMPLETE;
3301 				adp->ad_buf = NULL;
3302 				LIST_REMOVE(adp, ad_deps);
3303 				handle_allocdirect_partdone(adp);
3304 			}
3305 			while ((aip =
3306 			    LIST_FIRST(&bmsafemap->sm_allocindirhd))) {
3307 				aip->ai_state |= DEPCOMPLETE;
3308 				aip->ai_buf = NULL;
3309 				LIST_REMOVE(aip, ai_deps);
3310 				handle_allocindir_partdone(aip);
3311 			}
3312 			while ((inodedep =
3313 			     LIST_FIRST(&bmsafemap->sm_inodedephd)) != NULL) {
3314 				inodedep->id_state |= DEPCOMPLETE;
3315 				LIST_REMOVE(inodedep, id_deps);
3316 				inodedep->id_buf = NULL;
3317 			}
3318 			WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
3319 			continue;
3320 
3321 		case D_MKDIR:
3322 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
3323 			continue;
3324 
3325 		case D_ALLOCDIRECT:
3326 			adp = WK_ALLOCDIRECT(wk);
3327 			adp->ad_state |= COMPLETE;
3328 			handle_allocdirect_partdone(adp);
3329 			continue;
3330 
3331 		case D_ALLOCINDIR:
3332 			aip = WK_ALLOCINDIR(wk);
3333 			aip->ai_state |= COMPLETE;
3334 			handle_allocindir_partdone(aip);
3335 			continue;
3336 
3337 		case D_INDIRDEP:
3338 			indirdep = WK_INDIRDEP(wk);
3339 			if (indirdep->ir_state & GOINGAWAY) {
3340 				lk.lkt_held = NOHOLDER;
3341 				panic("disk_write_complete: indirdep gone");
3342 			}
3343 			bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
3344 			FREE(indirdep->ir_saveddata, M_INDIRDEP);
3345 			indirdep->ir_saveddata = 0;
3346 			indirdep->ir_state &= ~UNDONE;
3347 			indirdep->ir_state |= ATTACHED;
3348 			while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
3349 				handle_allocindir_partdone(aip);
3350 				if (aip == LIST_FIRST(&indirdep->ir_donehd)) {
3351 					lk.lkt_held = NOHOLDER;
3352 					panic("disk_write_complete: not gone");
3353 				}
3354 			}
3355 			WORKLIST_INSERT(&reattach, wk);
3356 			if ((bp->b_flags & B_DELWRI) == 0)
3357 				stat_indir_blk_ptrs++;
3358 			bdirty(bp);
3359 			continue;
3360 
3361 		default:
3362 			lk.lkt_held = NOHOLDER;
3363 			panic("handle_disk_write_complete: Unknown type %s",
3364 			    TYPENAME(wk->wk_type));
3365 			/* NOTREACHED */
3366 		}
3367 	}
3368 	/*
3369 	 * Reattach any requests that must be redone.
3370 	 */
3371 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
3372 		WORKLIST_REMOVE(wk);
3373 		WORKLIST_INSERT(&bp->b_dep, wk);
3374 	}
3375 #ifdef DEBUG
3376 	if (lk.lkt_held != SPECIAL_FLAG)
3377 		panic("softdep_disk_write_complete: lock lost");
3378 	lk.lkt_held = NOHOLDER;
3379 #endif
3380 }
3381 
3382 /*
3383  * Called from within softdep_disk_write_complete above. Note that
3384  * this routine is always called from interrupt level with further
3385  * splbio interrupts blocked.
3386  */
3387 static void
3388 handle_allocdirect_partdone(adp)
3389 	struct allocdirect *adp;	/* the completed allocdirect */
3390 {
3391 	struct allocdirect *listadp;
3392 	struct inodedep *inodedep;
3393 	long bsize;
3394 
3395 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3396 		return;
3397 	if (adp->ad_buf != NULL) {
3398 		lk.lkt_held = NOHOLDER;
3399 		panic("handle_allocdirect_partdone: dangling dep");
3400 	}
3401 	/*
3402 	 * The on-disk inode cannot claim to be any larger than the last
3403 	 * fragment that has been written. Otherwise, the on-disk inode
3404 	 * might have fragments that were not the last block in the file
3405 	 * which would corrupt the filesystem. Thus, we cannot free any
3406 	 * allocdirects after one whose ad_oldblkno claims a fragment as
3407 	 * these blocks must be rolled back to zero before writing the inode.
3408 	 * We check the currently active set of allocdirects in id_inoupdt.
3409 	 */
3410 	inodedep = adp->ad_inodedep;
3411 	bsize = inodedep->id_fs->fs_bsize;
3412 	TAILQ_FOREACH(listadp, &inodedep->id_inoupdt, ad_next) {
3413 		/* found our block */
3414 		if (listadp == adp)
3415 			break;
3416 		/* continue if ad_oldlbn is not a fragment */
3417 		if (listadp->ad_oldsize == 0 ||
3418 		    listadp->ad_oldsize == bsize)
3419 			continue;
3420 		/* hit a fragment */
3421 		return;
3422 	}
3423 	/*
3424 	 * If we have reached the end of the current list without
3425 	 * finding the just finished dependency, then it must be
3426 	 * on the future dependency list. Future dependencies cannot
3427 	 * be freed until they are moved to the current list.
3428 	 */
3429 	if (listadp == NULL) {
3430 #ifdef DEBUG
3431 		TAILQ_FOREACH(listadp, &inodedep->id_newinoupdt, ad_next)
3432 			/* found our block */
3433 			if (listadp == adp)
3434 				break;
3435 		if (listadp == NULL) {
3436 			lk.lkt_held = NOHOLDER;
3437 			panic("handle_allocdirect_partdone: lost dep");
3438 		}
3439 #endif /* DEBUG */
3440 		return;
3441 	}
3442 	/*
3443 	 * If we have found the just finished dependency, then free
3444 	 * it along with anything that follows it that is complete.
3445 	 */
3446 	for (; adp; adp = listadp) {
3447 		listadp = TAILQ_NEXT(adp, ad_next);
3448 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
3449 			return;
3450 		free_allocdirect(&inodedep->id_inoupdt, adp, 1);
3451 	}
3452 }
3453 
3454 /*
3455  * Called from within softdep_disk_write_complete above. Note that
3456  * this routine is always called from interrupt level with further
3457  * splbio interrupts blocked.
3458  */
3459 static void
3460 handle_allocindir_partdone(aip)
3461 	struct allocindir *aip;		/* the completed allocindir */
3462 {
3463 	struct indirdep *indirdep;
3464 
3465 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
3466 		return;
3467 	if (aip->ai_buf != NULL) {
3468 		lk.lkt_held = NOHOLDER;
3469 		panic("handle_allocindir_partdone: dangling dependency");
3470 	}
3471 	indirdep = aip->ai_indirdep;
3472 	if (indirdep->ir_state & UNDONE) {
3473 		LIST_REMOVE(aip, ai_next);
3474 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
3475 		return;
3476 	}
3477 	((ufs_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
3478 	    aip->ai_newblkno;
3479 	LIST_REMOVE(aip, ai_next);
3480 	if (aip->ai_freefrag != NULL)
3481 		add_to_worklist(&aip->ai_freefrag->ff_list);
3482 	WORKITEM_FREE(aip, D_ALLOCINDIR);
3483 }
3484 
3485 /*
3486  * Called from within softdep_disk_write_complete above to restore
3487  * in-memory inode block contents to their most up-to-date state. Note
3488  * that this routine is always called from interrupt level with further
3489  * splbio interrupts blocked.
3490  */
3491 static int
3492 handle_written_inodeblock(inodedep, bp)
3493 	struct inodedep *inodedep;
3494 	struct buf *bp;		/* buffer containing the inode block */
3495 {
3496 	struct worklist *wk, *filefree;
3497 	struct allocdirect *adp, *nextadp;
3498 	struct dinode *dp;
3499 	int hadchanges;
3500 
3501 	if ((inodedep->id_state & IOSTARTED) == 0) {
3502 		lk.lkt_held = NOHOLDER;
3503 		panic("handle_written_inodeblock: not started");
3504 	}
3505 	inodedep->id_state &= ~IOSTARTED;
3506 	inodedep->id_state |= COMPLETE;
3507 	dp = (struct dinode *)bp->b_data +
3508 	    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
3509 	/*
3510 	 * If we had to rollback the inode allocation because of
3511 	 * bitmaps being incomplete, then simply restore it.
3512 	 * Keep the block dirty so that it will not be reclaimed until
3513 	 * all associated dependencies have been cleared and the
3514 	 * corresponding updates written to disk.
3515 	 */
3516 	if (inodedep->id_savedino != NULL) {
3517 		*dp = *inodedep->id_savedino;
3518 		FREE(inodedep->id_savedino, M_INODEDEP);
3519 		inodedep->id_savedino = NULL;
3520 		if ((bp->b_flags & B_DELWRI) == 0)
3521 			stat_inode_bitmap++;
3522 		bdirty(bp);
3523 		return (1);
3524 	}
3525 	/*
3526 	 * Roll forward anything that had to be rolled back before
3527 	 * the inode could be updated.
3528 	 */
3529 	hadchanges = 0;
3530 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
3531 		nextadp = TAILQ_NEXT(adp, ad_next);
3532 		if (adp->ad_state & ATTACHED) {
3533 			lk.lkt_held = NOHOLDER;
3534 			panic("handle_written_inodeblock: new entry");
3535 		}
3536 		if (adp->ad_lbn < NDADDR) {
3537 			if (dp->di_db[adp->ad_lbn] != adp->ad_oldblkno) {
3538 				lk.lkt_held = NOHOLDER;
3539 				panic("%s: %s #%ld mismatch %d != %d",
3540 				    "handle_written_inodeblock",
3541 				    "direct pointer", adp->ad_lbn,
3542 				    dp->di_db[adp->ad_lbn], adp->ad_oldblkno);
3543 			}
3544 			dp->di_db[adp->ad_lbn] = adp->ad_newblkno;
3545 		} else {
3546 			if (dp->di_ib[adp->ad_lbn - NDADDR] != 0) {
3547 				lk.lkt_held = NOHOLDER;
3548 				panic("%s: %s #%ld allocated as %d",
3549 				    "handle_written_inodeblock",
3550 				    "indirect pointer", adp->ad_lbn - NDADDR,
3551 				    dp->di_ib[adp->ad_lbn - NDADDR]);
3552 			}
3553 			dp->di_ib[adp->ad_lbn - NDADDR] = adp->ad_newblkno;
3554 		}
3555 		adp->ad_state &= ~UNDONE;
3556 		adp->ad_state |= ATTACHED;
3557 		hadchanges = 1;
3558 	}
3559 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
3560 		stat_direct_blk_ptrs++;
3561 	/*
3562 	 * Reset the file size to its most up-to-date value.
3563 	 */
3564 	if (inodedep->id_savedsize == -1) {
3565 		lk.lkt_held = NOHOLDER;
3566 		panic("handle_written_inodeblock: bad size");
3567 	}
3568 	if (dp->di_size != inodedep->id_savedsize) {
3569 		dp->di_size = inodedep->id_savedsize;
3570 		hadchanges = 1;
3571 	}
3572 	inodedep->id_savedsize = -1;
3573 	/*
3574 	 * If there were any rollbacks in the inode block, then it must be
3575 	 * marked dirty so that its will eventually get written back in
3576 	 * its correct form.
3577 	 */
3578 	if (hadchanges)
3579 		bdirty(bp);
3580 	/*
3581 	 * Process any allocdirects that completed during the update.
3582 	 */
3583 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
3584 		handle_allocdirect_partdone(adp);
3585 	/*
3586 	 * Process deallocations that were held pending until the
3587 	 * inode had been written to disk. Freeing of the inode
3588 	 * is delayed until after all blocks have been freed to
3589 	 * avoid creation of new <vfsid, inum, lbn> triples
3590 	 * before the old ones have been deleted.
3591 	 */
3592 	filefree = NULL;
3593 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
3594 		WORKLIST_REMOVE(wk);
3595 		switch (wk->wk_type) {
3596 
3597 		case D_FREEFILE:
3598 			/*
3599 			 * We defer adding filefree to the worklist until
3600 			 * all other additions have been made to ensure
3601 			 * that it will be done after all the old blocks
3602 			 * have been freed.
3603 			 */
3604 			if (filefree != NULL) {
3605 				lk.lkt_held = NOHOLDER;
3606 				panic("handle_written_inodeblock: filefree");
3607 			}
3608 			filefree = wk;
3609 			continue;
3610 
3611 		case D_MKDIR:
3612 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
3613 			continue;
3614 
3615 		case D_DIRADD:
3616 			diradd_inode_written(WK_DIRADD(wk), inodedep);
3617 			continue;
3618 
3619 		case D_FREEBLKS:
3620 			wk->wk_state |= COMPLETE;
3621 			if ((wk->wk_state  & ALLCOMPLETE) != ALLCOMPLETE)
3622 				continue;
3623 			/* -- fall through -- */
3624 		case D_FREEFRAG:
3625 		case D_DIRREM:
3626 			add_to_worklist(wk);
3627 			continue;
3628 
3629 		default:
3630 			lk.lkt_held = NOHOLDER;
3631 			panic("handle_written_inodeblock: Unknown type %s",
3632 			    TYPENAME(wk->wk_type));
3633 			/* NOTREACHED */
3634 		}
3635 	}
3636 	if (filefree != NULL) {
3637 		if (free_inodedep(inodedep) == 0) {
3638 			lk.lkt_held = NOHOLDER;
3639 			panic("handle_written_inodeblock: live inodedep");
3640 		}
3641 		add_to_worklist(filefree);
3642 		return (0);
3643 	}
3644 
3645 	/*
3646 	 * If no outstanding dependencies, free it.
3647 	 */
3648 	if (free_inodedep(inodedep) || TAILQ_FIRST(&inodedep->id_inoupdt) == 0)
3649 		return (0);
3650 	return (hadchanges);
3651 }
3652 
3653 /*
3654  * Process a diradd entry after its dependent inode has been written.
3655  * This routine must be called with splbio interrupts blocked.
3656  */
3657 static void
3658 diradd_inode_written(dap, inodedep)
3659 	struct diradd *dap;
3660 	struct inodedep *inodedep;
3661 {
3662 	struct pagedep *pagedep;
3663 
3664 	dap->da_state |= COMPLETE;
3665 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3666 		if (dap->da_state & DIRCHG)
3667 			pagedep = dap->da_previous->dm_pagedep;
3668 		else
3669 			pagedep = dap->da_pagedep;
3670 		LIST_REMOVE(dap, da_pdlist);
3671 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3672 	}
3673 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
3674 }
3675 
3676 /*
3677  * Handle the completion of a mkdir dependency.
3678  */
3679 static void
3680 handle_written_mkdir(mkdir, type)
3681 	struct mkdir *mkdir;
3682 	int type;
3683 {
3684 	struct diradd *dap;
3685 	struct pagedep *pagedep;
3686 
3687 	if (mkdir->md_state != type) {
3688 		lk.lkt_held = NOHOLDER;
3689 		panic("handle_written_mkdir: bad type");
3690 	}
3691 	dap = mkdir->md_diradd;
3692 	dap->da_state &= ~type;
3693 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
3694 		dap->da_state |= DEPCOMPLETE;
3695 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3696 		if (dap->da_state & DIRCHG)
3697 			pagedep = dap->da_previous->dm_pagedep;
3698 		else
3699 			pagedep = dap->da_pagedep;
3700 		LIST_REMOVE(dap, da_pdlist);
3701 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
3702 	}
3703 	LIST_REMOVE(mkdir, md_mkdirs);
3704 	WORKITEM_FREE(mkdir, D_MKDIR);
3705 }
3706 
3707 /*
3708  * Called from within softdep_disk_write_complete above.
3709  * A write operation was just completed. Removed inodes can
3710  * now be freed and associated block pointers may be committed.
3711  * Note that this routine is always called from interrupt level
3712  * with further splbio interrupts blocked.
3713  */
3714 static int
3715 handle_written_filepage(pagedep, bp)
3716 	struct pagedep *pagedep;
3717 	struct buf *bp;		/* buffer containing the written page */
3718 {
3719 	struct dirrem *dirrem;
3720 	struct diradd *dap, *nextdap;
3721 	struct direct *ep;
3722 	int i, chgs;
3723 
3724 	if ((pagedep->pd_state & IOSTARTED) == 0) {
3725 		lk.lkt_held = NOHOLDER;
3726 		panic("handle_written_filepage: not started");
3727 	}
3728 	pagedep->pd_state &= ~IOSTARTED;
3729 	/*
3730 	 * Process any directory removals that have been committed.
3731 	 */
3732 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
3733 		LIST_REMOVE(dirrem, dm_next);
3734 		dirrem->dm_dirinum = pagedep->pd_ino;
3735 		add_to_worklist(&dirrem->dm_list);
3736 	}
3737 	/*
3738 	 * Free any directory additions that have been committed.
3739 	 */
3740 	while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
3741 		free_diradd(dap);
3742 	/*
3743 	 * Uncommitted directory entries must be restored.
3744 	 */
3745 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
3746 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
3747 		     dap = nextdap) {
3748 			nextdap = LIST_NEXT(dap, da_pdlist);
3749 			if (dap->da_state & ATTACHED) {
3750 				lk.lkt_held = NOHOLDER;
3751 				panic("handle_written_filepage: attached");
3752 			}
3753 			ep = (struct direct *)
3754 			    ((char *)bp->b_data + dap->da_offset);
3755 			ep->d_ino = dap->da_newinum;
3756 			dap->da_state &= ~UNDONE;
3757 			dap->da_state |= ATTACHED;
3758 			chgs = 1;
3759 			/*
3760 			 * If the inode referenced by the directory has
3761 			 * been written out, then the dependency can be
3762 			 * moved to the pending list.
3763 			 */
3764 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
3765 				LIST_REMOVE(dap, da_pdlist);
3766 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
3767 				    da_pdlist);
3768 			}
3769 		}
3770 	}
3771 	/*
3772 	 * If there were any rollbacks in the directory, then it must be
3773 	 * marked dirty so that its will eventually get written back in
3774 	 * its correct form.
3775 	 */
3776 	if (chgs) {
3777 		if ((bp->b_flags & B_DELWRI) == 0)
3778 			stat_dir_entry++;
3779 		bdirty(bp);
3780 	}
3781 	/*
3782 	 * If no dependencies remain, the pagedep will be freed.
3783 	 * Otherwise it will remain to update the page before it
3784 	 * is written back to disk.
3785 	 */
3786 	if (LIST_FIRST(&pagedep->pd_pendinghd) == 0) {
3787 		for (i = 0; i < DAHASHSZ; i++)
3788 			if (LIST_FIRST(&pagedep->pd_diraddhd[i]) != NULL)
3789 				break;
3790 		if (i == DAHASHSZ) {
3791 			LIST_REMOVE(pagedep, pd_hash);
3792 			WORKITEM_FREE(pagedep, D_PAGEDEP);
3793 			return (0);
3794 		}
3795 	}
3796 	return (1);
3797 }
3798 
3799 /*
3800  * Writing back in-core inode structures.
3801  *
3802  * The filesystem only accesses an inode's contents when it occupies an
3803  * "in-core" inode structure.  These "in-core" structures are separate from
3804  * the page frames used to cache inode blocks.  Only the latter are
3805  * transferred to/from the disk.  So, when the updated contents of the
3806  * "in-core" inode structure are copied to the corresponding in-memory inode
3807  * block, the dependencies are also transferred.  The following procedure is
3808  * called when copying a dirty "in-core" inode to a cached inode block.
3809  */
3810 
3811 /*
3812  * Called when an inode is loaded from disk. If the effective link count
3813  * differed from the actual link count when it was last flushed, then we
3814  * need to ensure that the correct effective link count is put back.
3815  */
3816 void
3817 softdep_load_inodeblock(ip)
3818 	struct inode *ip;	/* the "in_core" copy of the inode */
3819 {
3820 	struct inodedep *inodedep;
3821 
3822 	/*
3823 	 * Check for alternate nlink count.
3824 	 */
3825 	ip->i_effnlink = ip->i_nlink;
3826 	ACQUIRE_LOCK(&lk);
3827 	if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3828 		FREE_LOCK(&lk);
3829 		return;
3830 	}
3831 	ip->i_effnlink -= inodedep->id_nlinkdelta;
3832 	FREE_LOCK(&lk);
3833 }
3834 
3835 /*
3836  * This routine is called just before the "in-core" inode
3837  * information is to be copied to the in-memory inode block.
3838  * Recall that an inode block contains several inodes. If
3839  * the force flag is set, then the dependencies will be
3840  * cleared so that the update can always be made. Note that
3841  * the buffer is locked when this routine is called, so we
3842  * will never be in the middle of writing the inode block
3843  * to disk.
3844  */
3845 void
3846 softdep_update_inodeblock(ip, bp, waitfor)
3847 	struct inode *ip;	/* the "in_core" copy of the inode */
3848 	struct buf *bp;		/* the buffer containing the inode block */
3849 	int waitfor;		/* nonzero => update must be allowed */
3850 {
3851 	struct inodedep *inodedep;
3852 	struct worklist *wk;
3853 	int error, gotit;
3854 
3855 	/*
3856 	 * If the effective link count is not equal to the actual link
3857 	 * count, then we must track the difference in an inodedep while
3858 	 * the inode is (potentially) tossed out of the cache. Otherwise,
3859 	 * if there is no existing inodedep, then there are no dependencies
3860 	 * to track.
3861 	 */
3862 	ACQUIRE_LOCK(&lk);
3863 	if (inodedep_lookup(ip->i_fs, ip->i_number, 0, &inodedep) == 0) {
3864 		FREE_LOCK(&lk);
3865 		if (ip->i_effnlink != ip->i_nlink)
3866 			panic("softdep_update_inodeblock: bad link count");
3867 		return;
3868 	}
3869 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink) {
3870 		FREE_LOCK(&lk);
3871 		panic("softdep_update_inodeblock: bad delta");
3872 	}
3873 	/*
3874 	 * Changes have been initiated. Anything depending on these
3875 	 * changes cannot occur until this inode has been written.
3876 	 */
3877 	inodedep->id_state &= ~COMPLETE;
3878 	if ((inodedep->id_state & ONWORKLIST) == 0)
3879 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
3880 	/*
3881 	 * Any new dependencies associated with the incore inode must
3882 	 * now be moved to the list associated with the buffer holding
3883 	 * the in-memory copy of the inode. Once merged process any
3884 	 * allocdirects that are completed by the merger.
3885 	 */
3886 	merge_inode_lists(inodedep);
3887 	if (TAILQ_FIRST(&inodedep->id_inoupdt) != NULL)
3888 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt));
3889 	/*
3890 	 * Now that the inode has been pushed into the buffer, the
3891 	 * operations dependent on the inode being written to disk
3892 	 * can be moved to the id_bufwait so that they will be
3893 	 * processed when the buffer I/O completes.
3894 	 */
3895 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
3896 		WORKLIST_REMOVE(wk);
3897 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
3898 	}
3899 	/*
3900 	 * Newly allocated inodes cannot be written until the bitmap
3901 	 * that allocates them have been written (indicated by
3902 	 * DEPCOMPLETE being set in id_state). If we are doing a
3903 	 * forced sync (e.g., an fsync on a file), we force the bitmap
3904 	 * to be written so that the update can be done.
3905 	 */
3906 	if ((inodedep->id_state & DEPCOMPLETE) != 0 || waitfor == 0) {
3907 		FREE_LOCK(&lk);
3908 		return;
3909 	}
3910 	gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
3911 	FREE_LOCK(&lk);
3912 	if (gotit &&
3913 	    (error = VOP_BWRITE(inodedep->id_buf->b_vp, inodedep->id_buf)) != 0)
3914 		softdep_error("softdep_update_inodeblock: bwrite", error);
3915 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
3916 		panic("softdep_update_inodeblock: update failed");
3917 }
3918 
3919 /*
3920  * Merge the new inode dependency list (id_newinoupdt) into the old
3921  * inode dependency list (id_inoupdt). This routine must be called
3922  * with splbio interrupts blocked.
3923  */
3924 static void
3925 merge_inode_lists(inodedep)
3926 	struct inodedep *inodedep;
3927 {
3928 	struct allocdirect *listadp, *newadp;
3929 
3930 	newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3931 	for (listadp = TAILQ_FIRST(&inodedep->id_inoupdt); listadp && newadp;) {
3932 		if (listadp->ad_lbn < newadp->ad_lbn) {
3933 			listadp = TAILQ_NEXT(listadp, ad_next);
3934 			continue;
3935 		}
3936 		TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3937 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
3938 		if (listadp->ad_lbn == newadp->ad_lbn) {
3939 			allocdirect_merge(&inodedep->id_inoupdt, newadp,
3940 			    listadp);
3941 			listadp = newadp;
3942 		}
3943 		newadp = TAILQ_FIRST(&inodedep->id_newinoupdt);
3944 	}
3945 	while ((newadp = TAILQ_FIRST(&inodedep->id_newinoupdt)) != NULL) {
3946 		TAILQ_REMOVE(&inodedep->id_newinoupdt, newadp, ad_next);
3947 		TAILQ_INSERT_TAIL(&inodedep->id_inoupdt, newadp, ad_next);
3948 	}
3949 }
3950 
3951 /*
3952  * If we are doing an fsync, then we must ensure that any directory
3953  * entries for the inode have been written after the inode gets to disk.
3954  */
3955 static int
3956 softdep_fsync(vp)
3957 	struct vnode *vp;	/* the "in_core" copy of the inode */
3958 {
3959 	struct inodedep *inodedep;
3960 	struct pagedep *pagedep;
3961 	struct worklist *wk;
3962 	struct diradd *dap;
3963 	struct mount *mnt;
3964 	struct vnode *pvp;
3965 	struct inode *ip;
3966 	struct buf *bp;
3967 	struct fs *fs;
3968 	struct thread *td = curthread;		/* XXX */
3969 	int error, flushparent;
3970 	ino_t parentino;
3971 	ufs_lbn_t lbn;
3972 
3973 	ip = VTOI(vp);
3974 	fs = ip->i_fs;
3975 	ACQUIRE_LOCK(&lk);
3976 	if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0) {
3977 		FREE_LOCK(&lk);
3978 		return (0);
3979 	}
3980 	if (LIST_FIRST(&inodedep->id_inowait) != NULL ||
3981 	    LIST_FIRST(&inodedep->id_bufwait) != NULL ||
3982 	    TAILQ_FIRST(&inodedep->id_inoupdt) != NULL ||
3983 	    TAILQ_FIRST(&inodedep->id_newinoupdt) != NULL) {
3984 		FREE_LOCK(&lk);
3985 		panic("softdep_fsync: pending ops");
3986 	}
3987 	for (error = 0, flushparent = 0; ; ) {
3988 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
3989 			break;
3990 		if (wk->wk_type != D_DIRADD) {
3991 			FREE_LOCK(&lk);
3992 			panic("softdep_fsync: Unexpected type %s",
3993 			    TYPENAME(wk->wk_type));
3994 		}
3995 		dap = WK_DIRADD(wk);
3996 		/*
3997 		 * Flush our parent if this directory entry
3998 		 * has a MKDIR_PARENT dependency.
3999 		 */
4000 		if (dap->da_state & DIRCHG)
4001 			pagedep = dap->da_previous->dm_pagedep;
4002 		else
4003 			pagedep = dap->da_pagedep;
4004 		mnt = pagedep->pd_mnt;
4005 		parentino = pagedep->pd_ino;
4006 		lbn = pagedep->pd_lbn;
4007 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE) {
4008 			FREE_LOCK(&lk);
4009 			panic("softdep_fsync: dirty");
4010 		}
4011 		flushparent = dap->da_state & MKDIR_PARENT;
4012 		/*
4013 		 * If we are being fsync'ed as part of vgone'ing this vnode,
4014 		 * then we will not be able to release and recover the
4015 		 * vnode below, so we just have to give up on writing its
4016 		 * directory entry out. It will eventually be written, just
4017 		 * not now, but then the user was not asking to have it
4018 		 * written, so we are not breaking any promises.
4019 		 */
4020 		if (vp->v_flag & VRECLAIMED)
4021 			break;
4022 		/*
4023 		 * We prevent deadlock by always fetching inodes from the
4024 		 * root, moving down the directory tree. Thus, when fetching
4025 		 * our parent directory, we must unlock ourselves before
4026 		 * requesting the lock on our parent. See the comment in
4027 		 * ufs_lookup for details on possible races.
4028 		 */
4029 		FREE_LOCK(&lk);
4030 		VOP_UNLOCK(vp, 0, td);
4031 		error = VFS_VGET(mnt, parentino, &pvp);
4032 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
4033 		if (error != 0)
4034 			return (error);
4035 		if (flushparent) {
4036 			if ((error = UFS_UPDATE(pvp, 1)) != 0) {
4037 				vput(pvp);
4038 				return (error);
4039 			}
4040 		}
4041 		/*
4042 		 * Flush directory page containing the inode's name.
4043 		 */
4044 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), &bp);
4045 		if (error == 0)
4046 			error = VOP_BWRITE(bp->b_vp, bp);
4047 		vput(pvp);
4048 		if (error != 0)
4049 			return (error);
4050 		ACQUIRE_LOCK(&lk);
4051 		if (inodedep_lookup(fs, ip->i_number, 0, &inodedep) == 0)
4052 			break;
4053 	}
4054 	FREE_LOCK(&lk);
4055 	return (0);
4056 }
4057 
4058 /*
4059  * Flush all the dirty bitmaps associated with the block device
4060  * before flushing the rest of the dirty blocks so as to reduce
4061  * the number of dependencies that will have to be rolled back.
4062  */
4063 static int softdep_fsync_mountdev_bp(struct buf *bp, void *data);
4064 
4065 void
4066 softdep_fsync_mountdev(vp)
4067 	struct vnode *vp;
4068 {
4069 	if (!vn_isdisk(vp, NULL))
4070 		panic("softdep_fsync_mountdev: vnode not a disk");
4071 	ACQUIRE_LOCK(&lk);
4072 	RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4073 		softdep_fsync_mountdev_bp, NULL);
4074 	drain_output(vp, 1);
4075 	FREE_LOCK(&lk);
4076 }
4077 
4078 static int
4079 softdep_fsync_mountdev_bp(struct buf *bp, void *data)
4080 {
4081 	struct worklist *wk;
4082 
4083 	/*
4084 	 * If it is already scheduled, skip to the next buffer.
4085 	 */
4086 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
4087 		return(0);
4088 	if ((bp->b_flags & B_DELWRI) == 0) {
4089 		FREE_LOCK(&lk);
4090 		panic("softdep_fsync_mountdev: not dirty");
4091 	}
4092 	/*
4093 	 * We are only interested in bitmaps with outstanding
4094 	 * dependencies.
4095 	 */
4096 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
4097 	    wk->wk_type != D_BMSAFEMAP ||
4098 	    (bp->b_xflags & BX_BKGRDINPROG)) {
4099 		BUF_UNLOCK(bp);
4100 		return(0);
4101 	}
4102 	bremfree(bp);
4103 	FREE_LOCK(&lk);
4104 	(void) bawrite(bp);
4105 	ACQUIRE_LOCK(&lk);
4106 	return(0);
4107 }
4108 
4109 /*
4110  * This routine is called when we are trying to synchronously flush a
4111  * file. This routine must eliminate any filesystem metadata dependencies
4112  * so that the syncing routine can succeed by pushing the dirty blocks
4113  * associated with the file. If any I/O errors occur, they are returned.
4114  */
4115 struct softdep_sync_metadata_info {
4116 	struct vnode *vp;
4117 	int waitfor;
4118 };
4119 
4120 static int softdep_sync_metadata_bp(struct buf *bp, void *data);
4121 
4122 int
4123 softdep_sync_metadata(struct vnode *vp, struct thread *td)
4124 {
4125 	struct softdep_sync_metadata_info info;
4126 	int error, waitfor;
4127 
4128 	/*
4129 	 * Check whether this vnode is involved in a filesystem
4130 	 * that is doing soft dependency processing.
4131 	 */
4132 	if (!vn_isdisk(vp, NULL)) {
4133 		if (!DOINGSOFTDEP(vp))
4134 			return (0);
4135 	} else
4136 		if (vp->v_rdev->si_mountpoint == NULL ||
4137 		    (vp->v_rdev->si_mountpoint->mnt_flag & MNT_SOFTDEP) == 0)
4138 			return (0);
4139 	/*
4140 	 * Ensure that any direct block dependencies have been cleared.
4141 	 */
4142 	ACQUIRE_LOCK(&lk);
4143 	if ((error = flush_inodedep_deps(VTOI(vp)->i_fs, VTOI(vp)->i_number))) {
4144 		FREE_LOCK(&lk);
4145 		return (error);
4146 	}
4147 	/*
4148 	 * For most files, the only metadata dependencies are the
4149 	 * cylinder group maps that allocate their inode or blocks.
4150 	 * The block allocation dependencies can be found by traversing
4151 	 * the dependency lists for any buffers that remain on their
4152 	 * dirty buffer list. The inode allocation dependency will
4153 	 * be resolved when the inode is updated with MNT_WAIT.
4154 	 * This work is done in two passes. The first pass grabs most
4155 	 * of the buffers and begins asynchronously writing them. The
4156 	 * only way to wait for these asynchronous writes is to sleep
4157 	 * on the filesystem vnode which may stay busy for a long time
4158 	 * if the filesystem is active. So, instead, we make a second
4159 	 * pass over the dependencies blocking on each write. In the
4160 	 * usual case we will be blocking against a write that we
4161 	 * initiated, so when it is done the dependency will have been
4162 	 * resolved. Thus the second pass is expected to end quickly.
4163 	 */
4164 	waitfor = MNT_NOWAIT;
4165 top:
4166 	/*
4167 	 * We must wait for any I/O in progress to finish so that
4168 	 * all potential buffers on the dirty list will be visible.
4169 	 */
4170 	drain_output(vp, 1);
4171 	info.vp = vp;
4172 	info.waitfor = waitfor;
4173 	error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL,
4174 			softdep_sync_metadata_bp, &info);
4175 	if (error < 0) {
4176 		FREE_LOCK(&lk);
4177 		return(-error);	/* error code */
4178 	}
4179 
4180 	/*
4181 	 * The brief unlock is to allow any pent up dependency
4182 	 * processing to be done.  Then proceed with the second pass.
4183 	 */
4184 	if (waitfor == MNT_NOWAIT) {
4185 		waitfor = MNT_WAIT;
4186 		FREE_LOCK(&lk);
4187 		ACQUIRE_LOCK(&lk);
4188 		goto top;
4189 	}
4190 
4191 	/*
4192 	 * If we have managed to get rid of all the dirty buffers,
4193 	 * then we are done. For certain directories and block
4194 	 * devices, we may need to do further work.
4195 	 *
4196 	 * We must wait for any I/O in progress to finish so that
4197 	 * all potential buffers on the dirty list will be visible.
4198 	 */
4199 	drain_output(vp, 1);
4200 	if (RB_EMPTY(&vp->v_rbdirty_tree)) {
4201 		FREE_LOCK(&lk);
4202 		return (0);
4203 	}
4204 
4205 	FREE_LOCK(&lk);
4206 	/*
4207 	 * If we are trying to sync a block device, some of its buffers may
4208 	 * contain metadata that cannot be written until the contents of some
4209 	 * partially written files have been written to disk. The only easy
4210 	 * way to accomplish this is to sync the entire filesystem (luckily
4211 	 * this happens rarely).
4212 	 */
4213 	if (vn_isdisk(vp, NULL) &&
4214 	    vp->v_rdev &&
4215 	    vp->v_rdev->si_mountpoint && !VOP_ISLOCKED(vp, NULL) &&
4216 	    (error = VFS_SYNC(vp->v_rdev->si_mountpoint, MNT_WAIT, td)) != 0)
4217 		return (error);
4218 	return (0);
4219 }
4220 
4221 static int
4222 softdep_sync_metadata_bp(struct buf *bp, void *data)
4223 {
4224 	struct softdep_sync_metadata_info *info = data;
4225 	struct pagedep *pagedep;
4226 	struct allocdirect *adp;
4227 	struct allocindir *aip;
4228 	struct worklist *wk;
4229 	struct buf *nbp;
4230 	int error;
4231 	int i;
4232 
4233 	if (getdirtybuf(&bp, MNT_WAIT) == 0)
4234 		return (0);
4235 
4236 	/*
4237 	 * As we hold the buffer locked, none of its dependencies
4238 	 * will disappear.
4239 	 */
4240 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4241 		switch (wk->wk_type) {
4242 
4243 		case D_ALLOCDIRECT:
4244 			adp = WK_ALLOCDIRECT(wk);
4245 			if (adp->ad_state & DEPCOMPLETE)
4246 				break;
4247 			nbp = adp->ad_buf;
4248 			if (getdirtybuf(&nbp, info->waitfor) == 0)
4249 				break;
4250 			FREE_LOCK(&lk);
4251 			if (info->waitfor == MNT_NOWAIT) {
4252 				bawrite(nbp);
4253 			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
4254 				bawrite(bp);
4255 				ACQUIRE_LOCK(&lk);
4256 				return (-error);
4257 			}
4258 			ACQUIRE_LOCK(&lk);
4259 			break;
4260 
4261 		case D_ALLOCINDIR:
4262 			aip = WK_ALLOCINDIR(wk);
4263 			if (aip->ai_state & DEPCOMPLETE)
4264 				break;
4265 			nbp = aip->ai_buf;
4266 			if (getdirtybuf(&nbp, info->waitfor) == 0)
4267 				break;
4268 			FREE_LOCK(&lk);
4269 			if (info->waitfor == MNT_NOWAIT) {
4270 				bawrite(nbp);
4271 			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
4272 				bawrite(bp);
4273 				ACQUIRE_LOCK(&lk);
4274 				return (-error);
4275 			}
4276 			ACQUIRE_LOCK(&lk);
4277 			break;
4278 
4279 		case D_INDIRDEP:
4280 		restart:
4281 
4282 			LIST_FOREACH(aip, &WK_INDIRDEP(wk)->ir_deplisthd, ai_next) {
4283 				if (aip->ai_state & DEPCOMPLETE)
4284 					continue;
4285 				nbp = aip->ai_buf;
4286 				if (getdirtybuf(&nbp, MNT_WAIT) == 0)
4287 					goto restart;
4288 				FREE_LOCK(&lk);
4289 				if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
4290 					bawrite(bp);
4291 					ACQUIRE_LOCK(&lk);
4292 					return (-error);
4293 				}
4294 				ACQUIRE_LOCK(&lk);
4295 				goto restart;
4296 			}
4297 			break;
4298 
4299 		case D_INODEDEP:
4300 			if ((error = flush_inodedep_deps(WK_INODEDEP(wk)->id_fs,
4301 			    WK_INODEDEP(wk)->id_ino)) != 0) {
4302 				FREE_LOCK(&lk);
4303 				bawrite(bp);
4304 				ACQUIRE_LOCK(&lk);
4305 				return (-error);
4306 			}
4307 			break;
4308 
4309 		case D_PAGEDEP:
4310 			/*
4311 			 * We are trying to sync a directory that may
4312 			 * have dependencies on both its own metadata
4313 			 * and/or dependencies on the inodes of any
4314 			 * recently allocated files. We walk its diradd
4315 			 * lists pushing out the associated inode.
4316 			 */
4317 			pagedep = WK_PAGEDEP(wk);
4318 			for (i = 0; i < DAHASHSZ; i++) {
4319 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
4320 					continue;
4321 				if ((error =
4322 				    flush_pagedep_deps(info->vp,
4323 						pagedep->pd_mnt,
4324 						&pagedep->pd_diraddhd[i]))) {
4325 					FREE_LOCK(&lk);
4326 					bawrite(bp);
4327 					ACQUIRE_LOCK(&lk);
4328 					return (-error);
4329 				}
4330 			}
4331 			break;
4332 
4333 		case D_MKDIR:
4334 			/*
4335 			 * This case should never happen if the vnode has
4336 			 * been properly sync'ed. However, if this function
4337 			 * is used at a place where the vnode has not yet
4338 			 * been sync'ed, this dependency can show up. So,
4339 			 * rather than panic, just flush it.
4340 			 */
4341 			nbp = WK_MKDIR(wk)->md_buf;
4342 			if (getdirtybuf(&nbp, info->waitfor) == 0)
4343 				break;
4344 			FREE_LOCK(&lk);
4345 			if (info->waitfor == MNT_NOWAIT) {
4346 				bawrite(nbp);
4347 			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
4348 				bawrite(bp);
4349 				ACQUIRE_LOCK(&lk);
4350 				return (-error);
4351 			}
4352 			ACQUIRE_LOCK(&lk);
4353 			break;
4354 
4355 		case D_BMSAFEMAP:
4356 			/*
4357 			 * This case should never happen if the vnode has
4358 			 * been properly sync'ed. However, if this function
4359 			 * is used at a place where the vnode has not yet
4360 			 * been sync'ed, this dependency can show up. So,
4361 			 * rather than panic, just flush it.
4362 			 */
4363 			nbp = WK_BMSAFEMAP(wk)->sm_buf;
4364 			if (getdirtybuf(&nbp, info->waitfor) == 0)
4365 				break;
4366 			FREE_LOCK(&lk);
4367 			if (info->waitfor == MNT_NOWAIT) {
4368 				bawrite(nbp);
4369 			} else if ((error = VOP_BWRITE(nbp->b_vp, nbp)) != 0) {
4370 				bawrite(bp);
4371 				ACQUIRE_LOCK(&lk);
4372 				return (-error);
4373 			}
4374 			ACQUIRE_LOCK(&lk);
4375 			break;
4376 
4377 		default:
4378 			FREE_LOCK(&lk);
4379 			panic("softdep_sync_metadata: Unknown type %s",
4380 			    TYPENAME(wk->wk_type));
4381 			/* NOTREACHED */
4382 		}
4383 	}
4384 	FREE_LOCK(&lk);
4385 	bawrite(bp);
4386 	ACQUIRE_LOCK(&lk);
4387 	return(0);
4388 }
4389 
4390 /*
4391  * Flush the dependencies associated with an inodedep.
4392  * Called with splbio blocked.
4393  */
4394 static int
4395 flush_inodedep_deps(fs, ino)
4396 	struct fs *fs;
4397 	ino_t ino;
4398 {
4399 	struct inodedep *inodedep;
4400 	struct allocdirect *adp;
4401 	int error, waitfor;
4402 	struct buf *bp;
4403 
4404 	/*
4405 	 * This work is done in two passes. The first pass grabs most
4406 	 * of the buffers and begins asynchronously writing them. The
4407 	 * only way to wait for these asynchronous writes is to sleep
4408 	 * on the filesystem vnode which may stay busy for a long time
4409 	 * if the filesystem is active. So, instead, we make a second
4410 	 * pass over the dependencies blocking on each write. In the
4411 	 * usual case we will be blocking against a write that we
4412 	 * initiated, so when it is done the dependency will have been
4413 	 * resolved. Thus the second pass is expected to end quickly.
4414 	 * We give a brief window at the top of the loop to allow
4415 	 * any pending I/O to complete.
4416 	 */
4417 	for (waitfor = MNT_NOWAIT; ; ) {
4418 		FREE_LOCK(&lk);
4419 		ACQUIRE_LOCK(&lk);
4420 		if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4421 			return (0);
4422 		TAILQ_FOREACH(adp, &inodedep->id_inoupdt, ad_next) {
4423 			if (adp->ad_state & DEPCOMPLETE)
4424 				continue;
4425 			bp = adp->ad_buf;
4426 			if (getdirtybuf(&bp, waitfor) == 0) {
4427 				if (waitfor == MNT_NOWAIT)
4428 					continue;
4429 				break;
4430 			}
4431 			FREE_LOCK(&lk);
4432 			if (waitfor == MNT_NOWAIT) {
4433 				bawrite(bp);
4434 			} else if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0) {
4435 				ACQUIRE_LOCK(&lk);
4436 				return (error);
4437 			}
4438 			ACQUIRE_LOCK(&lk);
4439 			break;
4440 		}
4441 		if (adp != NULL)
4442 			continue;
4443 		TAILQ_FOREACH(adp, &inodedep->id_newinoupdt, ad_next) {
4444 			if (adp->ad_state & DEPCOMPLETE)
4445 				continue;
4446 			bp = adp->ad_buf;
4447 			if (getdirtybuf(&bp, waitfor) == 0) {
4448 				if (waitfor == MNT_NOWAIT)
4449 					continue;
4450 				break;
4451 			}
4452 			FREE_LOCK(&lk);
4453 			if (waitfor == MNT_NOWAIT) {
4454 				bawrite(bp);
4455 			} else if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0) {
4456 				ACQUIRE_LOCK(&lk);
4457 				return (error);
4458 			}
4459 			ACQUIRE_LOCK(&lk);
4460 			break;
4461 		}
4462 		if (adp != NULL)
4463 			continue;
4464 		/*
4465 		 * If pass2, we are done, otherwise do pass 2.
4466 		 */
4467 		if (waitfor == MNT_WAIT)
4468 			break;
4469 		waitfor = MNT_WAIT;
4470 	}
4471 	/*
4472 	 * Try freeing inodedep in case all dependencies have been removed.
4473 	 */
4474 	if (inodedep_lookup(fs, ino, 0, &inodedep) != 0)
4475 		(void) free_inodedep(inodedep);
4476 	return (0);
4477 }
4478 
4479 /*
4480  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
4481  * Called with splbio blocked.
4482  */
4483 static int
4484 flush_pagedep_deps(pvp, mp, diraddhdp)
4485 	struct vnode *pvp;
4486 	struct mount *mp;
4487 	struct diraddhd *diraddhdp;
4488 {
4489 	struct thread *td = curthread;		/* XXX */
4490 	struct inodedep *inodedep;
4491 	struct ufsmount *ump;
4492 	struct diradd *dap;
4493 	struct vnode *vp;
4494 	int gotit, error = 0;
4495 	struct buf *bp;
4496 	ino_t inum;
4497 
4498 	ump = VFSTOUFS(mp);
4499 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
4500 		/*
4501 		 * Flush ourselves if this directory entry
4502 		 * has a MKDIR_PARENT dependency.
4503 		 */
4504 		if (dap->da_state & MKDIR_PARENT) {
4505 			FREE_LOCK(&lk);
4506 			if ((error = UFS_UPDATE(pvp, 1)) != 0)
4507 				break;
4508 			ACQUIRE_LOCK(&lk);
4509 			/*
4510 			 * If that cleared dependencies, go on to next.
4511 			 */
4512 			if (dap != LIST_FIRST(diraddhdp))
4513 				continue;
4514 			if (dap->da_state & MKDIR_PARENT) {
4515 				FREE_LOCK(&lk);
4516 				panic("flush_pagedep_deps: MKDIR_PARENT");
4517 			}
4518 		}
4519 		/*
4520 		 * A newly allocated directory must have its "." and
4521 		 * ".." entries written out before its name can be
4522 		 * committed in its parent. We do not want or need
4523 		 * the full semantics of a synchronous VOP_FSYNC as
4524 		 * that may end up here again, once for each directory
4525 		 * level in the filesystem. Instead, we push the blocks
4526 		 * and wait for them to clear. We have to fsync twice
4527 		 * because the first call may choose to defer blocks
4528 		 * that still have dependencies, but deferral will
4529 		 * happen at most once.
4530 		 */
4531 		inum = dap->da_newinum;
4532 		if (dap->da_state & MKDIR_BODY) {
4533 			FREE_LOCK(&lk);
4534 			if ((error = VFS_VGET(mp, inum, &vp)) != 0)
4535 				break;
4536 			if ((error=VOP_FSYNC(vp, MNT_NOWAIT, td)) ||
4537 			    (error=VOP_FSYNC(vp, MNT_NOWAIT, td))) {
4538 				vput(vp);
4539 				break;
4540 			}
4541 			drain_output(vp, 0);
4542 			vput(vp);
4543 			ACQUIRE_LOCK(&lk);
4544 			/*
4545 			 * If that cleared dependencies, go on to next.
4546 			 */
4547 			if (dap != LIST_FIRST(diraddhdp))
4548 				continue;
4549 			if (dap->da_state & MKDIR_BODY) {
4550 				FREE_LOCK(&lk);
4551 				panic("flush_pagedep_deps: MKDIR_BODY");
4552 			}
4553 		}
4554 		/*
4555 		 * Flush the inode on which the directory entry depends.
4556 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
4557 		 * the only remaining dependency is that the updated inode
4558 		 * count must get pushed to disk. The inode has already
4559 		 * been pushed into its inode buffer (via VOP_UPDATE) at
4560 		 * the time of the reference count change. So we need only
4561 		 * locate that buffer, ensure that there will be no rollback
4562 		 * caused by a bitmap dependency, then write the inode buffer.
4563 		 */
4564 		if (inodedep_lookup(ump->um_fs, inum, 0, &inodedep) == 0) {
4565 			FREE_LOCK(&lk);
4566 			panic("flush_pagedep_deps: lost inode");
4567 		}
4568 		/*
4569 		 * If the inode still has bitmap dependencies,
4570 		 * push them to disk.
4571 		 */
4572 		if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4573 			gotit = getdirtybuf(&inodedep->id_buf, MNT_WAIT);
4574 			FREE_LOCK(&lk);
4575 			if (gotit &&
4576 			    (error = VOP_BWRITE(inodedep->id_buf->b_vp,
4577 			     inodedep->id_buf)) != 0)
4578 				break;
4579 			ACQUIRE_LOCK(&lk);
4580 			if (dap != LIST_FIRST(diraddhdp))
4581 				continue;
4582 		}
4583 		/*
4584 		 * If the inode is still sitting in a buffer waiting
4585 		 * to be written, push it to disk.
4586 		 */
4587 		FREE_LOCK(&lk);
4588 		if ((error = bread(ump->um_devvp,
4589 		    fsbtodb(ump->um_fs, ino_to_fsba(ump->um_fs, inum)),
4590 		    (int)ump->um_fs->fs_bsize, &bp)) != 0)
4591 			break;
4592 		if ((error = VOP_BWRITE(bp->b_vp, bp)) != 0)
4593 			break;
4594 		ACQUIRE_LOCK(&lk);
4595 		/*
4596 		 * If we have failed to get rid of all the dependencies
4597 		 * then something is seriously wrong.
4598 		 */
4599 		if (dap == LIST_FIRST(diraddhdp)) {
4600 			FREE_LOCK(&lk);
4601 			panic("flush_pagedep_deps: flush failed");
4602 		}
4603 	}
4604 	if (error)
4605 		ACQUIRE_LOCK(&lk);
4606 	return (error);
4607 }
4608 
4609 /*
4610  * A large burst of file addition or deletion activity can drive the
4611  * memory load excessively high. First attempt to slow things down
4612  * using the techniques below. If that fails, this routine requests
4613  * the offending operations to fall back to running synchronously
4614  * until the memory load returns to a reasonable level.
4615  */
4616 int
4617 softdep_slowdown(vp)
4618 	struct vnode *vp;
4619 {
4620 	int max_softdeps_hard;
4621 
4622 	max_softdeps_hard = max_softdeps * 11 / 10;
4623 	if (num_dirrem < max_softdeps_hard / 2 &&
4624 	    num_inodedep < max_softdeps_hard)
4625 		return (0);
4626 	stat_sync_limit_hit += 1;
4627 	return (1);
4628 }
4629 
4630 /*
4631  * If memory utilization has gotten too high, deliberately slow things
4632  * down and speed up the I/O processing.
4633  */
4634 static int
4635 request_cleanup(resource, islocked)
4636 	int resource;
4637 	int islocked;
4638 {
4639 	struct thread *td = curthread;		/* XXX */
4640 
4641 	/*
4642 	 * We never hold up the filesystem syncer process.
4643 	 */
4644 	if (td == filesys_syncer)
4645 		return (0);
4646 	/*
4647 	 * First check to see if the work list has gotten backlogged.
4648 	 * If it has, co-opt this process to help clean up two entries.
4649 	 * Because this process may hold inodes locked, we cannot
4650 	 * handle any remove requests that might block on a locked
4651 	 * inode as that could lead to deadlock.
4652 	 */
4653 	if (num_on_worklist > max_softdeps / 10) {
4654 		if (islocked)
4655 			FREE_LOCK(&lk);
4656 		process_worklist_item(NULL, LK_NOWAIT);
4657 		process_worklist_item(NULL, LK_NOWAIT);
4658 		stat_worklist_push += 2;
4659 		if (islocked)
4660 			ACQUIRE_LOCK(&lk);
4661 		return(1);
4662 	}
4663 
4664 	/*
4665 	 * If we are resource constrained on inode dependencies, try
4666 	 * flushing some dirty inodes. Otherwise, we are constrained
4667 	 * by file deletions, so try accelerating flushes of directories
4668 	 * with removal dependencies. We would like to do the cleanup
4669 	 * here, but we probably hold an inode locked at this point and
4670 	 * that might deadlock against one that we try to clean. So,
4671 	 * the best that we can do is request the syncer daemon to do
4672 	 * the cleanup for us.
4673 	 */
4674 	switch (resource) {
4675 
4676 	case FLUSH_INODES:
4677 		stat_ino_limit_push += 1;
4678 		req_clear_inodedeps += 1;
4679 		stat_countp = &stat_ino_limit_hit;
4680 		break;
4681 
4682 	case FLUSH_REMOVE:
4683 		stat_blk_limit_push += 1;
4684 		req_clear_remove += 1;
4685 		stat_countp = &stat_blk_limit_hit;
4686 		break;
4687 
4688 	default:
4689 		if (islocked)
4690 			FREE_LOCK(&lk);
4691 		panic("request_cleanup: unknown type");
4692 	}
4693 	/*
4694 	 * Hopefully the syncer daemon will catch up and awaken us.
4695 	 * We wait at most tickdelay before proceeding in any case.
4696 	 */
4697 	if (islocked == 0)
4698 		ACQUIRE_LOCK(&lk);
4699 	crit_enter();
4700 	proc_waiting += 1;
4701 	if (!callout_active(&handle))
4702 		callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4703 			      pause_timer, NULL);
4704 	interlocked_sleep(&lk, SLEEP, (caddr_t)&proc_waiting, 0,
4705 	    "softupdate", 0);
4706 	proc_waiting -= 1;
4707 	crit_exit();
4708 	if (islocked == 0)
4709 		FREE_LOCK(&lk);
4710 	return (1);
4711 }
4712 
4713 /*
4714  * Awaken processes pausing in request_cleanup and clear proc_waiting
4715  * to indicate that there is no longer a timer running.
4716  */
4717 void
4718 pause_timer(arg)
4719 	void *arg;
4720 {
4721 	*stat_countp += 1;
4722 	wakeup_one(&proc_waiting);
4723 	if (proc_waiting > 0)
4724 		callout_reset(&handle, tickdelay > 2 ? tickdelay : 2,
4725 			      pause_timer, NULL);
4726 	else
4727 		callout_deactivate(&handle);
4728 }
4729 
4730 /*
4731  * Flush out a directory with at least one removal dependency in an effort to
4732  * reduce the number of dirrem, freefile, and freeblks dependency structures.
4733  */
4734 static void
4735 clear_remove(struct thread *td)
4736 {
4737 	struct pagedep_hashhead *pagedephd;
4738 	struct pagedep *pagedep;
4739 	static int next = 0;
4740 	struct mount *mp;
4741 	struct vnode *vp;
4742 	int error, cnt;
4743 	ino_t ino;
4744 
4745 	ACQUIRE_LOCK(&lk);
4746 	for (cnt = 0; cnt < pagedep_hash; cnt++) {
4747 		pagedephd = &pagedep_hashtbl[next++];
4748 		if (next >= pagedep_hash)
4749 			next = 0;
4750 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
4751 			if (LIST_FIRST(&pagedep->pd_dirremhd) == NULL)
4752 				continue;
4753 			mp = pagedep->pd_mnt;
4754 			ino = pagedep->pd_ino;
4755 			FREE_LOCK(&lk);
4756 			if ((error = VFS_VGET(mp, ino, &vp)) != 0) {
4757 				softdep_error("clear_remove: vget", error);
4758 				return;
4759 			}
4760 			if ((error = VOP_FSYNC(vp, MNT_NOWAIT, td)))
4761 				softdep_error("clear_remove: fsync", error);
4762 			drain_output(vp, 0);
4763 			vput(vp);
4764 			return;
4765 		}
4766 	}
4767 	FREE_LOCK(&lk);
4768 }
4769 
4770 /*
4771  * Clear out a block of dirty inodes in an effort to reduce
4772  * the number of inodedep dependency structures.
4773  */
4774 struct clear_inodedeps_info {
4775 	struct fs *fs;
4776 	struct mount *mp;
4777 };
4778 
4779 static int
4780 clear_inodedeps_mountlist_callback(struct mount *mp, void *data)
4781 {
4782 	struct clear_inodedeps_info *info = data;
4783 
4784 	if ((mp->mnt_flag & MNT_SOFTDEP) && info->fs == VFSTOUFS(mp)->um_fs) {
4785 		info->mp = mp;
4786 		return(-1);
4787 	}
4788 	return(0);
4789 }
4790 
4791 static void
4792 clear_inodedeps(struct thread *td)
4793 {
4794 	struct clear_inodedeps_info info;
4795 	struct inodedep_hashhead *inodedephd;
4796 	struct inodedep *inodedep;
4797 	static int next = 0;
4798 	struct vnode *vp;
4799 	struct fs *fs;
4800 	int error, cnt;
4801 	ino_t firstino, lastino, ino;
4802 
4803 	ACQUIRE_LOCK(&lk);
4804 	/*
4805 	 * Pick a random inode dependency to be cleared.
4806 	 * We will then gather up all the inodes in its block
4807 	 * that have dependencies and flush them out.
4808 	 */
4809 	for (cnt = 0; cnt < inodedep_hash; cnt++) {
4810 		inodedephd = &inodedep_hashtbl[next++];
4811 		if (next >= inodedep_hash)
4812 			next = 0;
4813 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
4814 			break;
4815 	}
4816 	if (inodedep == NULL) {
4817 		FREE_LOCK(&lk);
4818 		return;
4819 	}
4820 	/*
4821 	 * Ugly code to find mount point given pointer to superblock.
4822 	 */
4823 	fs = inodedep->id_fs;
4824 	info.mp = NULL;
4825 	info.fs = fs;
4826 	mountlist_scan(clear_inodedeps_mountlist_callback,
4827 			&info, MNTSCAN_FORWARD|MNTSCAN_NOBUSY);
4828 	/*
4829 	 * Find the last inode in the block with dependencies.
4830 	 */
4831 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
4832 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
4833 		if (inodedep_lookup(fs, lastino, 0, &inodedep) != 0)
4834 			break;
4835 	/*
4836 	 * Asynchronously push all but the last inode with dependencies.
4837 	 * Synchronously push the last inode with dependencies to ensure
4838 	 * that the inode block gets written to free up the inodedeps.
4839 	 */
4840 	for (ino = firstino; ino <= lastino; ino++) {
4841 		if (inodedep_lookup(fs, ino, 0, &inodedep) == 0)
4842 			continue;
4843 		FREE_LOCK(&lk);
4844 		if ((error = VFS_VGET(info.mp, ino, &vp)) != 0) {
4845 			softdep_error("clear_inodedeps: vget", error);
4846 			return;
4847 		}
4848 		if (ino == lastino) {
4849 			if ((error = VOP_FSYNC(vp, MNT_WAIT, td)))
4850 				softdep_error("clear_inodedeps: fsync1", error);
4851 		} else {
4852 			if ((error = VOP_FSYNC(vp, MNT_NOWAIT, td)))
4853 				softdep_error("clear_inodedeps: fsync2", error);
4854 			drain_output(vp, 0);
4855 		}
4856 		vput(vp);
4857 		ACQUIRE_LOCK(&lk);
4858 	}
4859 	FREE_LOCK(&lk);
4860 }
4861 
4862 /*
4863  * Function to determine if the buffer has outstanding dependencies
4864  * that will cause a roll-back if the buffer is written. If wantcount
4865  * is set, return number of dependencies, otherwise just yes or no.
4866  */
4867 static int
4868 softdep_count_dependencies(bp, wantcount)
4869 	struct buf *bp;
4870 	int wantcount;
4871 {
4872 	struct worklist *wk;
4873 	struct inodedep *inodedep;
4874 	struct indirdep *indirdep;
4875 	struct allocindir *aip;
4876 	struct pagedep *pagedep;
4877 	struct diradd *dap;
4878 	int i, retval;
4879 
4880 	retval = 0;
4881 	ACQUIRE_LOCK(&lk);
4882 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
4883 		switch (wk->wk_type) {
4884 
4885 		case D_INODEDEP:
4886 			inodedep = WK_INODEDEP(wk);
4887 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
4888 				/* bitmap allocation dependency */
4889 				retval += 1;
4890 				if (!wantcount)
4891 					goto out;
4892 			}
4893 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
4894 				/* direct block pointer dependency */
4895 				retval += 1;
4896 				if (!wantcount)
4897 					goto out;
4898 			}
4899 			continue;
4900 
4901 		case D_INDIRDEP:
4902 			indirdep = WK_INDIRDEP(wk);
4903 
4904 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
4905 				/* indirect block pointer dependency */
4906 				retval += 1;
4907 				if (!wantcount)
4908 					goto out;
4909 			}
4910 			continue;
4911 
4912 		case D_PAGEDEP:
4913 			pagedep = WK_PAGEDEP(wk);
4914 			for (i = 0; i < DAHASHSZ; i++) {
4915 
4916 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
4917 					/* directory entry dependency */
4918 					retval += 1;
4919 					if (!wantcount)
4920 						goto out;
4921 				}
4922 			}
4923 			continue;
4924 
4925 		case D_BMSAFEMAP:
4926 		case D_ALLOCDIRECT:
4927 		case D_ALLOCINDIR:
4928 		case D_MKDIR:
4929 			/* never a dependency on these blocks */
4930 			continue;
4931 
4932 		default:
4933 			FREE_LOCK(&lk);
4934 			panic("softdep_check_for_rollback: Unexpected type %s",
4935 			    TYPENAME(wk->wk_type));
4936 			/* NOTREACHED */
4937 		}
4938 	}
4939 out:
4940 	FREE_LOCK(&lk);
4941 	return retval;
4942 }
4943 
4944 /*
4945  * Acquire exclusive access to a buffer.
4946  * Must be called with splbio blocked.
4947  * Return 1 if buffer was acquired.
4948  */
4949 static int
4950 getdirtybuf(bpp, waitfor)
4951 	struct buf **bpp;
4952 	int waitfor;
4953 {
4954 	struct buf *bp;
4955 	int error;
4956 
4957 	for (;;) {
4958 		if ((bp = *bpp) == NULL)
4959 			return (0);
4960 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
4961 			if ((bp->b_xflags & BX_BKGRDINPROG) == 0)
4962 				break;
4963 			BUF_UNLOCK(bp);
4964 			if (waitfor != MNT_WAIT)
4965 				return (0);
4966 			bp->b_xflags |= BX_BKGRDWAIT;
4967 			interlocked_sleep(&lk, SLEEP, &bp->b_xflags, 0,
4968 			    "getbuf", 0);
4969 			continue;
4970 		}
4971 		if (waitfor != MNT_WAIT)
4972 			return (0);
4973 		error = interlocked_sleep(&lk, LOCKBUF, bp,
4974 		    LK_EXCLUSIVE | LK_SLEEPFAIL, 0, 0);
4975 		if (error != ENOLCK) {
4976 			FREE_LOCK(&lk);
4977 			panic("getdirtybuf: inconsistent lock");
4978 		}
4979 	}
4980 	if ((bp->b_flags & B_DELWRI) == 0) {
4981 		BUF_UNLOCK(bp);
4982 		return (0);
4983 	}
4984 	bremfree(bp);
4985 	return (1);
4986 }
4987 
4988 /*
4989  * Wait for pending output on a vnode to complete.
4990  * Must be called with vnode locked.
4991  */
4992 static void
4993 drain_output(vp, islocked)
4994 	struct vnode *vp;
4995 	int islocked;
4996 {
4997 
4998 	if (!islocked)
4999 		ACQUIRE_LOCK(&lk);
5000 	while (vp->v_numoutput) {
5001 		vp->v_flag |= VBWAIT;
5002 		interlocked_sleep(&lk, SLEEP, (caddr_t)&vp->v_numoutput,
5003 		    0, "drainvp", 0);
5004 	}
5005 	if (!islocked)
5006 		FREE_LOCK(&lk);
5007 }
5008 
5009 /*
5010  * Called whenever a buffer that is being invalidated or reallocated
5011  * contains dependencies. This should only happen if an I/O error has
5012  * occurred. The routine is called with the buffer locked.
5013  */
5014 static void
5015 softdep_deallocate_dependencies(bp)
5016 	struct buf *bp;
5017 {
5018 
5019 	if ((bp->b_flags & B_ERROR) == 0)
5020 		panic("softdep_deallocate_dependencies: dangling deps");
5021 	softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntfromname, bp->b_error);
5022 	panic("softdep_deallocate_dependencies: unrecovered I/O error");
5023 }
5024 
5025 /*
5026  * Function to handle asynchronous write errors in the filesystem.
5027  */
5028 void
5029 softdep_error(func, error)
5030 	char *func;
5031 	int error;
5032 {
5033 
5034 	/* XXX should do something better! */
5035 	printf("%s: got error %d while accessing filesystem\n", func, error);
5036 }
5037