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