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