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