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