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