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