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