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