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