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