xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision 5b9c547c)
1 /*-
2  * Copyright 1998, 2000 Marshall Kirk McKusick.
3  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
4  * All rights reserved.
5  *
6  * The soft updates code is derived from the appendix of a University
7  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
8  * "Soft Updates: A Solution to the Metadata Update Problem in File
9  * Systems", CSE-TR-254-95, August 1995).
10  *
11  * Further information about soft updates can be obtained from:
12  *
13  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
14  *	1614 Oxford Street		mckusick@mckusick.com
15  *	Berkeley, CA 94709-1608		+1-510-843-9542
16  *	USA
17  *
18  * Redistribution and use in source and binary forms, with or without
19  * modification, are permitted provided that the following conditions
20  * are met:
21  *
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
29  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  *
39  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
40  */
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include "opt_ffs.h"
46 #include "opt_quota.h"
47 #include "opt_ddb.h"
48 
49 /*
50  * For now we want the safety net that the DEBUG flag provides.
51  */
52 #ifndef DEBUG
53 #define DEBUG
54 #endif
55 
56 #include <sys/param.h>
57 #include <sys/kernel.h>
58 #include <sys/systm.h>
59 #include <sys/bio.h>
60 #include <sys/buf.h>
61 #include <sys/kdb.h>
62 #include <sys/kthread.h>
63 #include <sys/ktr.h>
64 #include <sys/limits.h>
65 #include <sys/lock.h>
66 #include <sys/malloc.h>
67 #include <sys/mount.h>
68 #include <sys/mutex.h>
69 #include <sys/namei.h>
70 #include <sys/priv.h>
71 #include <sys/proc.h>
72 #include <sys/rwlock.h>
73 #include <sys/stat.h>
74 #include <sys/sysctl.h>
75 #include <sys/syslog.h>
76 #include <sys/vnode.h>
77 #include <sys/conf.h>
78 
79 #include <ufs/ufs/dir.h>
80 #include <ufs/ufs/extattr.h>
81 #include <ufs/ufs/quota.h>
82 #include <ufs/ufs/inode.h>
83 #include <ufs/ufs/ufsmount.h>
84 #include <ufs/ffs/fs.h>
85 #include <ufs/ffs/softdep.h>
86 #include <ufs/ffs/ffs_extern.h>
87 #include <ufs/ufs/ufs_extern.h>
88 
89 #include <vm/vm.h>
90 #include <vm/vm_extern.h>
91 #include <vm/vm_object.h>
92 
93 #include <geom/geom.h>
94 
95 #include <ddb/ddb.h>
96 
97 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
98 
99 #ifndef SOFTUPDATES
100 
101 int
102 softdep_flushfiles(oldmnt, flags, td)
103 	struct mount *oldmnt;
104 	int flags;
105 	struct thread *td;
106 {
107 
108 	panic("softdep_flushfiles called");
109 }
110 
111 int
112 softdep_mount(devvp, mp, fs, cred)
113 	struct vnode *devvp;
114 	struct mount *mp;
115 	struct fs *fs;
116 	struct ucred *cred;
117 {
118 
119 	return (0);
120 }
121 
122 void
123 softdep_initialize()
124 {
125 
126 	return;
127 }
128 
129 void
130 softdep_uninitialize()
131 {
132 
133 	return;
134 }
135 
136 void
137 softdep_unmount(mp)
138 	struct mount *mp;
139 {
140 
141 	panic("softdep_unmount called");
142 }
143 
144 void
145 softdep_setup_sbupdate(ump, fs, bp)
146 	struct ufsmount *ump;
147 	struct fs *fs;
148 	struct buf *bp;
149 {
150 
151 	panic("softdep_setup_sbupdate called");
152 }
153 
154 void
155 softdep_setup_inomapdep(bp, ip, newinum, mode)
156 	struct buf *bp;
157 	struct inode *ip;
158 	ino_t newinum;
159 	int mode;
160 {
161 
162 	panic("softdep_setup_inomapdep called");
163 }
164 
165 void
166 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
167 	struct buf *bp;
168 	struct mount *mp;
169 	ufs2_daddr_t newblkno;
170 	int frags;
171 	int oldfrags;
172 {
173 
174 	panic("softdep_setup_blkmapdep called");
175 }
176 
177 void
178 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
179 	struct inode *ip;
180 	ufs_lbn_t lbn;
181 	ufs2_daddr_t newblkno;
182 	ufs2_daddr_t oldblkno;
183 	long newsize;
184 	long oldsize;
185 	struct buf *bp;
186 {
187 
188 	panic("softdep_setup_allocdirect called");
189 }
190 
191 void
192 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
193 	struct inode *ip;
194 	ufs_lbn_t lbn;
195 	ufs2_daddr_t newblkno;
196 	ufs2_daddr_t oldblkno;
197 	long newsize;
198 	long oldsize;
199 	struct buf *bp;
200 {
201 
202 	panic("softdep_setup_allocext called");
203 }
204 
205 void
206 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
207 	struct inode *ip;
208 	ufs_lbn_t lbn;
209 	struct buf *bp;
210 	int ptrno;
211 	ufs2_daddr_t newblkno;
212 	ufs2_daddr_t oldblkno;
213 	struct buf *nbp;
214 {
215 
216 	panic("softdep_setup_allocindir_page called");
217 }
218 
219 void
220 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
221 	struct buf *nbp;
222 	struct inode *ip;
223 	struct buf *bp;
224 	int ptrno;
225 	ufs2_daddr_t newblkno;
226 {
227 
228 	panic("softdep_setup_allocindir_meta called");
229 }
230 
231 void
232 softdep_journal_freeblocks(ip, cred, length, flags)
233 	struct inode *ip;
234 	struct ucred *cred;
235 	off_t length;
236 	int flags;
237 {
238 
239 	panic("softdep_journal_freeblocks called");
240 }
241 
242 void
243 softdep_journal_fsync(ip)
244 	struct inode *ip;
245 {
246 
247 	panic("softdep_journal_fsync called");
248 }
249 
250 void
251 softdep_setup_freeblocks(ip, length, flags)
252 	struct inode *ip;
253 	off_t length;
254 	int flags;
255 {
256 
257 	panic("softdep_setup_freeblocks called");
258 }
259 
260 void
261 softdep_freefile(pvp, ino, mode)
262 		struct vnode *pvp;
263 		ino_t ino;
264 		int mode;
265 {
266 
267 	panic("softdep_freefile called");
268 }
269 
270 int
271 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
272 	struct buf *bp;
273 	struct inode *dp;
274 	off_t diroffset;
275 	ino_t newinum;
276 	struct buf *newdirbp;
277 	int isnewblk;
278 {
279 
280 	panic("softdep_setup_directory_add called");
281 }
282 
283 void
284 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
285 	struct buf *bp;
286 	struct inode *dp;
287 	caddr_t base;
288 	caddr_t oldloc;
289 	caddr_t newloc;
290 	int entrysize;
291 {
292 
293 	panic("softdep_change_directoryentry_offset called");
294 }
295 
296 void
297 softdep_setup_remove(bp, dp, ip, isrmdir)
298 	struct buf *bp;
299 	struct inode *dp;
300 	struct inode *ip;
301 	int isrmdir;
302 {
303 
304 	panic("softdep_setup_remove called");
305 }
306 
307 void
308 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
309 	struct buf *bp;
310 	struct inode *dp;
311 	struct inode *ip;
312 	ino_t newinum;
313 	int isrmdir;
314 {
315 
316 	panic("softdep_setup_directory_change called");
317 }
318 
319 void
320 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
321 	struct mount *mp;
322 	struct buf *bp;
323 	ufs2_daddr_t blkno;
324 	int frags;
325 	struct workhead *wkhd;
326 {
327 
328 	panic("%s called", __FUNCTION__);
329 }
330 
331 void
332 softdep_setup_inofree(mp, bp, ino, wkhd)
333 	struct mount *mp;
334 	struct buf *bp;
335 	ino_t ino;
336 	struct workhead *wkhd;
337 {
338 
339 	panic("%s called", __FUNCTION__);
340 }
341 
342 void
343 softdep_setup_unlink(dp, ip)
344 	struct inode *dp;
345 	struct inode *ip;
346 {
347 
348 	panic("%s called", __FUNCTION__);
349 }
350 
351 void
352 softdep_setup_link(dp, ip)
353 	struct inode *dp;
354 	struct inode *ip;
355 {
356 
357 	panic("%s called", __FUNCTION__);
358 }
359 
360 void
361 softdep_revert_link(dp, ip)
362 	struct inode *dp;
363 	struct inode *ip;
364 {
365 
366 	panic("%s called", __FUNCTION__);
367 }
368 
369 void
370 softdep_setup_rmdir(dp, ip)
371 	struct inode *dp;
372 	struct inode *ip;
373 {
374 
375 	panic("%s called", __FUNCTION__);
376 }
377 
378 void
379 softdep_revert_rmdir(dp, ip)
380 	struct inode *dp;
381 	struct inode *ip;
382 {
383 
384 	panic("%s called", __FUNCTION__);
385 }
386 
387 void
388 softdep_setup_create(dp, ip)
389 	struct inode *dp;
390 	struct inode *ip;
391 {
392 
393 	panic("%s called", __FUNCTION__);
394 }
395 
396 void
397 softdep_revert_create(dp, ip)
398 	struct inode *dp;
399 	struct inode *ip;
400 {
401 
402 	panic("%s called", __FUNCTION__);
403 }
404 
405 void
406 softdep_setup_mkdir(dp, ip)
407 	struct inode *dp;
408 	struct inode *ip;
409 {
410 
411 	panic("%s called", __FUNCTION__);
412 }
413 
414 void
415 softdep_revert_mkdir(dp, ip)
416 	struct inode *dp;
417 	struct inode *ip;
418 {
419 
420 	panic("%s called", __FUNCTION__);
421 }
422 
423 void
424 softdep_setup_dotdot_link(dp, ip)
425 	struct inode *dp;
426 	struct inode *ip;
427 {
428 
429 	panic("%s called", __FUNCTION__);
430 }
431 
432 int
433 softdep_prealloc(vp, waitok)
434 	struct vnode *vp;
435 	int waitok;
436 {
437 
438 	panic("%s called", __FUNCTION__);
439 }
440 
441 int
442 softdep_journal_lookup(mp, vpp)
443 	struct mount *mp;
444 	struct vnode **vpp;
445 {
446 
447 	return (ENOENT);
448 }
449 
450 void
451 softdep_change_linkcnt(ip)
452 	struct inode *ip;
453 {
454 
455 	panic("softdep_change_linkcnt called");
456 }
457 
458 void
459 softdep_load_inodeblock(ip)
460 	struct inode *ip;
461 {
462 
463 	panic("softdep_load_inodeblock called");
464 }
465 
466 void
467 softdep_update_inodeblock(ip, bp, waitfor)
468 	struct inode *ip;
469 	struct buf *bp;
470 	int waitfor;
471 {
472 
473 	panic("softdep_update_inodeblock called");
474 }
475 
476 int
477 softdep_fsync(vp)
478 	struct vnode *vp;	/* the "in_core" copy of the inode */
479 {
480 
481 	return (0);
482 }
483 
484 void
485 softdep_fsync_mountdev(vp)
486 	struct vnode *vp;
487 {
488 
489 	return;
490 }
491 
492 int
493 softdep_flushworklist(oldmnt, countp, td)
494 	struct mount *oldmnt;
495 	int *countp;
496 	struct thread *td;
497 {
498 
499 	*countp = 0;
500 	return (0);
501 }
502 
503 int
504 softdep_sync_metadata(struct vnode *vp)
505 {
506 
507 	panic("softdep_sync_metadata called");
508 }
509 
510 int
511 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
512 {
513 
514 	panic("softdep_sync_buf called");
515 }
516 
517 int
518 softdep_slowdown(vp)
519 	struct vnode *vp;
520 {
521 
522 	panic("softdep_slowdown called");
523 }
524 
525 int
526 softdep_request_cleanup(fs, vp, cred, resource)
527 	struct fs *fs;
528 	struct vnode *vp;
529 	struct ucred *cred;
530 	int resource;
531 {
532 
533 	return (0);
534 }
535 
536 int
537 softdep_check_suspend(struct mount *mp,
538 		      struct vnode *devvp,
539 		      int softdep_depcnt,
540 		      int softdep_accdepcnt,
541 		      int secondary_writes,
542 		      int secondary_accwrites)
543 {
544 	struct bufobj *bo;
545 	int error;
546 
547 	(void) softdep_depcnt,
548 	(void) softdep_accdepcnt;
549 
550 	bo = &devvp->v_bufobj;
551 	ASSERT_BO_WLOCKED(bo);
552 
553 	MNT_ILOCK(mp);
554 	while (mp->mnt_secondary_writes != 0) {
555 		BO_UNLOCK(bo);
556 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
557 		    (PUSER - 1) | PDROP, "secwr", 0);
558 		BO_LOCK(bo);
559 		MNT_ILOCK(mp);
560 	}
561 
562 	/*
563 	 * Reasons for needing more work before suspend:
564 	 * - Dirty buffers on devvp.
565 	 * - Secondary writes occurred after start of vnode sync loop
566 	 */
567 	error = 0;
568 	if (bo->bo_numoutput > 0 ||
569 	    bo->bo_dirty.bv_cnt > 0 ||
570 	    secondary_writes != 0 ||
571 	    mp->mnt_secondary_writes != 0 ||
572 	    secondary_accwrites != mp->mnt_secondary_accwrites)
573 		error = EAGAIN;
574 	BO_UNLOCK(bo);
575 	return (error);
576 }
577 
578 void
579 softdep_get_depcounts(struct mount *mp,
580 		      int *softdepactivep,
581 		      int *softdepactiveaccp)
582 {
583 	(void) mp;
584 	*softdepactivep = 0;
585 	*softdepactiveaccp = 0;
586 }
587 
588 void
589 softdep_buf_append(bp, wkhd)
590 	struct buf *bp;
591 	struct workhead *wkhd;
592 {
593 
594 	panic("softdep_buf_appendwork called");
595 }
596 
597 void
598 softdep_inode_append(ip, cred, wkhd)
599 	struct inode *ip;
600 	struct ucred *cred;
601 	struct workhead *wkhd;
602 {
603 
604 	panic("softdep_inode_appendwork called");
605 }
606 
607 void
608 softdep_freework(wkhd)
609 	struct workhead *wkhd;
610 {
611 
612 	panic("softdep_freework called");
613 }
614 
615 #else
616 
617 FEATURE(softupdates, "FFS soft-updates support");
618 
619 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW, 0,
620     "soft updates stats");
621 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total, CTLFLAG_RW, 0,
622     "total dependencies allocated");
623 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse, CTLFLAG_RW, 0,
624     "high use dependencies allocated");
625 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current, CTLFLAG_RW, 0,
626     "current dependencies allocated");
627 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write, CTLFLAG_RW, 0,
628     "current dependencies written");
629 
630 unsigned long dep_current[D_LAST + 1];
631 unsigned long dep_highuse[D_LAST + 1];
632 unsigned long dep_total[D_LAST + 1];
633 unsigned long dep_write[D_LAST + 1];
634 
635 #define	SOFTDEP_TYPE(type, str, long)					\
636     static MALLOC_DEFINE(M_ ## type, #str, long);			\
637     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
638 	&dep_total[D_ ## type], 0, "");					\
639     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
640 	&dep_current[D_ ## type], 0, "");				\
641     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
642 	&dep_highuse[D_ ## type], 0, "");				\
643     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
644 	&dep_write[D_ ## type], 0, "");
645 
646 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
647 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
648 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
649     "Block or frag allocated from cyl group map");
650 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
651 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
652 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
653 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
654 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
655 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
656 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
657 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
658 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
659 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
660 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
661 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
662 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
663 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
664 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
665 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
666 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
667 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
668 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
669 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
670 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
671 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
672 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
673 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
674 
675 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
676 
677 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
678 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
679 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
680 
681 #define M_SOFTDEP_FLAGS	(M_WAITOK)
682 
683 /*
684  * translate from workitem type to memory type
685  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
686  */
687 static struct malloc_type *memtype[] = {
688 	M_PAGEDEP,
689 	M_INODEDEP,
690 	M_BMSAFEMAP,
691 	M_NEWBLK,
692 	M_ALLOCDIRECT,
693 	M_INDIRDEP,
694 	M_ALLOCINDIR,
695 	M_FREEFRAG,
696 	M_FREEBLKS,
697 	M_FREEFILE,
698 	M_DIRADD,
699 	M_MKDIR,
700 	M_DIRREM,
701 	M_NEWDIRBLK,
702 	M_FREEWORK,
703 	M_FREEDEP,
704 	M_JADDREF,
705 	M_JREMREF,
706 	M_JMVREF,
707 	M_JNEWBLK,
708 	M_JFREEBLK,
709 	M_JFREEFRAG,
710 	M_JSEG,
711 	M_JSEGDEP,
712 	M_SBDEP,
713 	M_JTRUNC,
714 	M_JFSYNC,
715 	M_SENTINEL
716 };
717 
718 #define DtoM(type) (memtype[type])
719 
720 /*
721  * Names of malloc types.
722  */
723 #define TYPENAME(type)  \
724 	((unsigned)(type) <= D_LAST ? memtype[type]->ks_shortdesc : "???")
725 /*
726  * End system adaptation definitions.
727  */
728 
729 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
730 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
731 
732 /*
733  * Internal function prototypes.
734  */
735 static	void check_clear_deps(struct mount *);
736 static	void softdep_error(char *, int);
737 static	int softdep_process_worklist(struct mount *, int);
738 static	int softdep_waitidle(struct mount *, int);
739 static	void drain_output(struct vnode *);
740 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
741 static	int check_inodedep_free(struct inodedep *);
742 static	void clear_remove(struct mount *);
743 static	void clear_inodedeps(struct mount *);
744 static	void unlinked_inodedep(struct mount *, struct inodedep *);
745 static	void clear_unlinked_inodedep(struct inodedep *);
746 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
747 static	int flush_pagedep_deps(struct vnode *, struct mount *,
748 	    struct diraddhd *);
749 static	int free_pagedep(struct pagedep *);
750 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
751 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
752 static	int flush_deplist(struct allocdirectlst *, int, int *);
753 static	int sync_cgs(struct mount *, int);
754 static	int handle_written_filepage(struct pagedep *, struct buf *);
755 static	int handle_written_sbdep(struct sbdep *, struct buf *);
756 static	void initiate_write_sbdep(struct sbdep *);
757 static	void diradd_inode_written(struct diradd *, struct inodedep *);
758 static	int handle_written_indirdep(struct indirdep *, struct buf *,
759 	    struct buf**);
760 static	int handle_written_inodeblock(struct inodedep *, struct buf *);
761 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
762 	    uint8_t *);
763 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *);
764 static	void handle_written_jaddref(struct jaddref *);
765 static	void handle_written_jremref(struct jremref *);
766 static	void handle_written_jseg(struct jseg *, struct buf *);
767 static	void handle_written_jnewblk(struct jnewblk *);
768 static	void handle_written_jblkdep(struct jblkdep *);
769 static	void handle_written_jfreefrag(struct jfreefrag *);
770 static	void complete_jseg(struct jseg *);
771 static	void complete_jsegs(struct jseg *);
772 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
773 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
774 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
775 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
776 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
777 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
778 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
779 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
780 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
781 static	inline void inoref_write(struct inoref *, struct jseg *,
782 	    struct jrefrec *);
783 static	void handle_allocdirect_partdone(struct allocdirect *,
784 	    struct workhead *);
785 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
786 	    struct workhead *);
787 static	void indirdep_complete(struct indirdep *);
788 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
789 static	void indirblk_insert(struct freework *);
790 static	void indirblk_remove(struct freework *);
791 static	void handle_allocindir_partdone(struct allocindir *);
792 static	void initiate_write_filepage(struct pagedep *, struct buf *);
793 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
794 static	void handle_written_mkdir(struct mkdir *, int);
795 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
796 	    uint8_t *);
797 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
798 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
799 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
800 static	void handle_workitem_freefile(struct freefile *);
801 static	int handle_workitem_remove(struct dirrem *, int);
802 static	struct dirrem *newdirrem(struct buf *, struct inode *,
803 	    struct inode *, int, struct dirrem **);
804 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
805 	    struct buf *);
806 static	void cancel_indirdep(struct indirdep *, struct buf *,
807 	    struct freeblks *);
808 static	void free_indirdep(struct indirdep *);
809 static	void free_diradd(struct diradd *, struct workhead *);
810 static	void merge_diradd(struct inodedep *, struct diradd *);
811 static	void complete_diradd(struct diradd *);
812 static	struct diradd *diradd_lookup(struct pagedep *, int);
813 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
814 	    struct jremref *);
815 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
816 	    struct jremref *);
817 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
818 	    struct jremref *, struct jremref *);
819 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
820 	    struct jremref *);
821 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
822 	    struct freeblks *, int);
823 static	int setup_trunc_indir(struct freeblks *, struct inode *,
824 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
825 static	void complete_trunc_indir(struct freework *);
826 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
827 	    int);
828 static	void complete_mkdir(struct mkdir *);
829 static	void free_newdirblk(struct newdirblk *);
830 static	void free_jremref(struct jremref *);
831 static	void free_jaddref(struct jaddref *);
832 static	void free_jsegdep(struct jsegdep *);
833 static	void free_jsegs(struct jblocks *);
834 static	void rele_jseg(struct jseg *);
835 static	void free_jseg(struct jseg *, struct jblocks *);
836 static	void free_jnewblk(struct jnewblk *);
837 static	void free_jblkdep(struct jblkdep *);
838 static	void free_jfreefrag(struct jfreefrag *);
839 static	void free_freedep(struct freedep *);
840 static	void journal_jremref(struct dirrem *, struct jremref *,
841 	    struct inodedep *);
842 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
843 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
844 	    struct workhead *);
845 static	void cancel_jfreefrag(struct jfreefrag *);
846 static	inline void setup_freedirect(struct freeblks *, struct inode *,
847 	    int, int);
848 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
849 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
850 	    ufs_lbn_t, int);
851 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
852 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
853 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
854 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
855 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
856 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
857 	    int, int);
858 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
859 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
860 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
861 static	void newblk_freefrag(struct newblk*);
862 static	void free_newblk(struct newblk *);
863 static	void cancel_allocdirect(struct allocdirectlst *,
864 	    struct allocdirect *, struct freeblks *);
865 static	int check_inode_unwritten(struct inodedep *);
866 static	int free_inodedep(struct inodedep *);
867 static	void freework_freeblock(struct freework *);
868 static	void freework_enqueue(struct freework *);
869 static	int handle_workitem_freeblocks(struct freeblks *, int);
870 static	int handle_complete_freeblocks(struct freeblks *, int);
871 static	void handle_workitem_indirblk(struct freework *);
872 static	void handle_written_freework(struct freework *);
873 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
874 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
875 	    struct workhead *);
876 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
877 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
878 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
879 	    ufs2_daddr_t, ufs_lbn_t);
880 static	void handle_workitem_freefrag(struct freefrag *);
881 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
882 	    ufs_lbn_t);
883 static	void allocdirect_merge(struct allocdirectlst *,
884 	    struct allocdirect *, struct allocdirect *);
885 static	struct freefrag *allocindir_merge(struct allocindir *,
886 	    struct allocindir *);
887 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
888 	    struct bmsafemap **);
889 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
890 	    int cg, struct bmsafemap *);
891 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
892 	    struct newblk **);
893 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
894 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
895 	    struct inodedep **);
896 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
897 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
898 	    int, struct pagedep **);
899 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
900 	    struct pagedep **);
901 static	void pause_timer(void *);
902 static	int request_cleanup(struct mount *, int);
903 static	int process_worklist_item(struct mount *, int, int);
904 static	void process_removes(struct vnode *);
905 static	void process_truncates(struct vnode *);
906 static	void jwork_move(struct workhead *, struct workhead *);
907 static	void jwork_insert(struct workhead *, struct jsegdep *);
908 static	void add_to_worklist(struct worklist *, int);
909 static	void wake_worklist(struct worklist *);
910 static	void wait_worklist(struct worklist *, char *);
911 static	void remove_from_worklist(struct worklist *);
912 static	void softdep_flush(void *);
913 static	void softdep_flushjournal(struct mount *);
914 static	int softdep_speedup(struct ufsmount *);
915 static	void worklist_speedup(struct mount *);
916 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
917 static	void journal_unmount(struct ufsmount *);
918 static	int journal_space(struct ufsmount *, int);
919 static	void journal_suspend(struct ufsmount *);
920 static	int journal_unsuspend(struct ufsmount *ump);
921 static	void softdep_prelink(struct vnode *, struct vnode *);
922 static	void add_to_journal(struct worklist *);
923 static	void remove_from_journal(struct worklist *);
924 static	void softdep_process_journal(struct mount *, struct worklist *, int);
925 static	struct jremref *newjremref(struct dirrem *, struct inode *,
926 	    struct inode *ip, off_t, nlink_t);
927 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
928 	    uint16_t);
929 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
930 	    uint16_t);
931 static	inline struct jsegdep *inoref_jseg(struct inoref *);
932 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
933 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
934 	    ufs2_daddr_t, int);
935 static	void adjust_newfreework(struct freeblks *, int);
936 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
937 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
938 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
939 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
940 	    ufs2_daddr_t, long, ufs_lbn_t);
941 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
942 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
943 static	int jwait(struct worklist *, int);
944 static	struct inodedep *inodedep_lookup_ip(struct inode *);
945 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
946 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
947 static	void handle_jwork(struct workhead *);
948 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
949 	    struct mkdir **);
950 static	struct jblocks *jblocks_create(void);
951 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
952 static	void jblocks_free(struct jblocks *, struct mount *, int);
953 static	void jblocks_destroy(struct jblocks *);
954 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
955 
956 /*
957  * Exported softdep operations.
958  */
959 static	void softdep_disk_io_initiation(struct buf *);
960 static	void softdep_disk_write_complete(struct buf *);
961 static	void softdep_deallocate_dependencies(struct buf *);
962 static	int softdep_count_dependencies(struct buf *bp, int);
963 
964 /*
965  * Global lock over all of soft updates.
966  */
967 static struct mtx lk;
968 MTX_SYSINIT(softdep_lock, &lk, "Global Softdep Lock", MTX_DEF);
969 
970 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
971 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
972 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
973 
974 /*
975  * Per-filesystem soft-updates locking.
976  */
977 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
978 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
979 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
980 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
981 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
982 				    RA_WLOCKED)
983 
984 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
985 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
986 
987 /*
988  * Worklist queue management.
989  * These routines require that the lock be held.
990  */
991 #ifndef /* NOT */ DEBUG
992 #define WORKLIST_INSERT(head, item) do {	\
993 	(item)->wk_state |= ONWORKLIST;		\
994 	LIST_INSERT_HEAD(head, item, wk_list);	\
995 } while (0)
996 #define WORKLIST_REMOVE(item) do {		\
997 	(item)->wk_state &= ~ONWORKLIST;	\
998 	LIST_REMOVE(item, wk_list);		\
999 } while (0)
1000 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1001 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1002 
1003 #else /* DEBUG */
1004 static	void worklist_insert(struct workhead *, struct worklist *, int);
1005 static	void worklist_remove(struct worklist *, int);
1006 
1007 #define WORKLIST_INSERT(head, item) worklist_insert(head, item, 1)
1008 #define WORKLIST_INSERT_UNLOCKED(head, item) worklist_insert(head, item, 0)
1009 #define WORKLIST_REMOVE(item) worklist_remove(item, 1)
1010 #define WORKLIST_REMOVE_UNLOCKED(item) worklist_remove(item, 0)
1011 
1012 static void
1013 worklist_insert(head, item, locked)
1014 	struct workhead *head;
1015 	struct worklist *item;
1016 	int locked;
1017 {
1018 
1019 	if (locked)
1020 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1021 	if (item->wk_state & ONWORKLIST)
1022 		panic("worklist_insert: %p %s(0x%X) already on list",
1023 		    item, TYPENAME(item->wk_type), item->wk_state);
1024 	item->wk_state |= ONWORKLIST;
1025 	LIST_INSERT_HEAD(head, item, wk_list);
1026 }
1027 
1028 static void
1029 worklist_remove(item, locked)
1030 	struct worklist *item;
1031 	int locked;
1032 {
1033 
1034 	if (locked)
1035 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1036 	if ((item->wk_state & ONWORKLIST) == 0)
1037 		panic("worklist_remove: %p %s(0x%X) not on list",
1038 		    item, TYPENAME(item->wk_type), item->wk_state);
1039 	item->wk_state &= ~ONWORKLIST;
1040 	LIST_REMOVE(item, wk_list);
1041 }
1042 #endif /* DEBUG */
1043 
1044 /*
1045  * Merge two jsegdeps keeping only the oldest one as newer references
1046  * can't be discarded until after older references.
1047  */
1048 static inline struct jsegdep *
1049 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1050 {
1051 	struct jsegdep *swp;
1052 
1053 	if (two == NULL)
1054 		return (one);
1055 
1056 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1057 		swp = one;
1058 		one = two;
1059 		two = swp;
1060 	}
1061 	WORKLIST_REMOVE(&two->jd_list);
1062 	free_jsegdep(two);
1063 
1064 	return (one);
1065 }
1066 
1067 /*
1068  * If two freedeps are compatible free one to reduce list size.
1069  */
1070 static inline struct freedep *
1071 freedep_merge(struct freedep *one, struct freedep *two)
1072 {
1073 	if (two == NULL)
1074 		return (one);
1075 
1076 	if (one->fd_freework == two->fd_freework) {
1077 		WORKLIST_REMOVE(&two->fd_list);
1078 		free_freedep(two);
1079 	}
1080 	return (one);
1081 }
1082 
1083 /*
1084  * Move journal work from one list to another.  Duplicate freedeps and
1085  * jsegdeps are coalesced to keep the lists as small as possible.
1086  */
1087 static void
1088 jwork_move(dst, src)
1089 	struct workhead *dst;
1090 	struct workhead *src;
1091 {
1092 	struct freedep *freedep;
1093 	struct jsegdep *jsegdep;
1094 	struct worklist *wkn;
1095 	struct worklist *wk;
1096 
1097 	KASSERT(dst != src,
1098 	    ("jwork_move: dst == src"));
1099 	freedep = NULL;
1100 	jsegdep = NULL;
1101 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1102 		if (wk->wk_type == D_JSEGDEP)
1103 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1104 		else if (wk->wk_type == D_FREEDEP)
1105 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1106 	}
1107 
1108 	while ((wk = LIST_FIRST(src)) != NULL) {
1109 		WORKLIST_REMOVE(wk);
1110 		WORKLIST_INSERT(dst, wk);
1111 		if (wk->wk_type == D_JSEGDEP) {
1112 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1113 			continue;
1114 		}
1115 		if (wk->wk_type == D_FREEDEP)
1116 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1117 	}
1118 }
1119 
1120 static void
1121 jwork_insert(dst, jsegdep)
1122 	struct workhead *dst;
1123 	struct jsegdep *jsegdep;
1124 {
1125 	struct jsegdep *jsegdepn;
1126 	struct worklist *wk;
1127 
1128 	LIST_FOREACH(wk, dst, wk_list)
1129 		if (wk->wk_type == D_JSEGDEP)
1130 			break;
1131 	if (wk == NULL) {
1132 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1133 		return;
1134 	}
1135 	jsegdepn = WK_JSEGDEP(wk);
1136 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1137 		WORKLIST_REMOVE(wk);
1138 		free_jsegdep(jsegdepn);
1139 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1140 	} else
1141 		free_jsegdep(jsegdep);
1142 }
1143 
1144 /*
1145  * Routines for tracking and managing workitems.
1146  */
1147 static	void workitem_free(struct worklist *, int);
1148 static	void workitem_alloc(struct worklist *, int, struct mount *);
1149 static	void workitem_reassign(struct worklist *, int);
1150 
1151 #define	WORKITEM_FREE(item, type) \
1152 	workitem_free((struct worklist *)(item), (type))
1153 #define	WORKITEM_REASSIGN(item, type) \
1154 	workitem_reassign((struct worklist *)(item), (type))
1155 
1156 static void
1157 workitem_free(item, type)
1158 	struct worklist *item;
1159 	int type;
1160 {
1161 	struct ufsmount *ump;
1162 
1163 #ifdef DEBUG
1164 	if (item->wk_state & ONWORKLIST)
1165 		panic("workitem_free: %s(0x%X) still on list",
1166 		    TYPENAME(item->wk_type), item->wk_state);
1167 	if (item->wk_type != type && type != D_NEWBLK)
1168 		panic("workitem_free: type mismatch %s != %s",
1169 		    TYPENAME(item->wk_type), TYPENAME(type));
1170 #endif
1171 	if (item->wk_state & IOWAITING)
1172 		wakeup(item);
1173 	ump = VFSTOUFS(item->wk_mp);
1174 	LOCK_OWNED(ump);
1175 	KASSERT(ump->softdep_deps > 0,
1176 	    ("workitem_free: %s: softdep_deps going negative",
1177 	    ump->um_fs->fs_fsmnt));
1178 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1179 		wakeup(&ump->softdep_deps);
1180 	KASSERT(dep_current[item->wk_type] > 0,
1181 	    ("workitem_free: %s: dep_current[%s] going negative",
1182 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1183 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1184 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1185 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1186 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1187 	ump->softdep_curdeps[item->wk_type] -= 1;
1188 	free(item, DtoM(type));
1189 }
1190 
1191 static void
1192 workitem_alloc(item, type, mp)
1193 	struct worklist *item;
1194 	int type;
1195 	struct mount *mp;
1196 {
1197 	struct ufsmount *ump;
1198 
1199 	item->wk_type = type;
1200 	item->wk_mp = mp;
1201 	item->wk_state = 0;
1202 
1203 	ump = VFSTOUFS(mp);
1204 	ACQUIRE_GBLLOCK(&lk);
1205 	dep_current[type]++;
1206 	if (dep_current[type] > dep_highuse[type])
1207 		dep_highuse[type] = dep_current[type];
1208 	dep_total[type]++;
1209 	FREE_GBLLOCK(&lk);
1210 	ACQUIRE_LOCK(ump);
1211 	ump->softdep_curdeps[type] += 1;
1212 	ump->softdep_deps++;
1213 	ump->softdep_accdeps++;
1214 	FREE_LOCK(ump);
1215 }
1216 
1217 static void
1218 workitem_reassign(item, newtype)
1219 	struct worklist *item;
1220 	int newtype;
1221 {
1222 	struct ufsmount *ump;
1223 
1224 	ump = VFSTOUFS(item->wk_mp);
1225 	LOCK_OWNED(ump);
1226 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1227 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1228 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1229 	ump->softdep_curdeps[item->wk_type] -= 1;
1230 	ump->softdep_curdeps[newtype] += 1;
1231 	KASSERT(dep_current[item->wk_type] > 0,
1232 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1233 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1234 	ACQUIRE_GBLLOCK(&lk);
1235 	dep_current[newtype]++;
1236 	dep_current[item->wk_type]--;
1237 	if (dep_current[newtype] > dep_highuse[newtype])
1238 		dep_highuse[newtype] = dep_current[newtype];
1239 	dep_total[newtype]++;
1240 	FREE_GBLLOCK(&lk);
1241 	item->wk_type = newtype;
1242 }
1243 
1244 /*
1245  * Workitem queue management
1246  */
1247 static int max_softdeps;	/* maximum number of structs before slowdown */
1248 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1249 static int proc_waiting;	/* tracks whether we have a timeout posted */
1250 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1251 static struct callout softdep_callout;
1252 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1253 static int req_clear_remove;	/* syncer process flush some freeblks */
1254 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1255 
1256 /*
1257  * runtime statistics
1258  */
1259 static int stat_flush_threads;	/* number of softdep flushing threads */
1260 static int stat_worklist_push;	/* number of worklist cleanups */
1261 static int stat_blk_limit_push;	/* number of times block limit neared */
1262 static int stat_ino_limit_push;	/* number of times inode limit neared */
1263 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1264 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1265 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1266 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1267 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1268 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1269 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1270 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1271 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1272 static int stat_journal_min;	/* Times hit journal min threshold */
1273 static int stat_journal_low;	/* Times hit journal low threshold */
1274 static int stat_journal_wait;	/* Times blocked in jwait(). */
1275 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1276 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1277 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1278 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1279 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1280 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1281 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1282 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1283 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1284 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1285 
1286 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1287     &max_softdeps, 0, "");
1288 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1289     &tickdelay, 0, "");
1290 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1291     &stat_flush_threads, 0, "");
1292 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push, CTLFLAG_RW,
1293     &stat_worklist_push, 0,"");
1294 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push, CTLFLAG_RW,
1295     &stat_blk_limit_push, 0,"");
1296 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push, CTLFLAG_RW,
1297     &stat_ino_limit_push, 0,"");
1298 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit, CTLFLAG_RW,
1299     &stat_blk_limit_hit, 0, "");
1300 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit, CTLFLAG_RW,
1301     &stat_ino_limit_hit, 0, "");
1302 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit, CTLFLAG_RW,
1303     &stat_sync_limit_hit, 0, "");
1304 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs, CTLFLAG_RW,
1305     &stat_indir_blk_ptrs, 0, "");
1306 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap, CTLFLAG_RW,
1307     &stat_inode_bitmap, 0, "");
1308 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs, CTLFLAG_RW,
1309     &stat_direct_blk_ptrs, 0, "");
1310 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry, CTLFLAG_RW,
1311     &stat_dir_entry, 0, "");
1312 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback, CTLFLAG_RW,
1313     &stat_jaddref, 0, "");
1314 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback, CTLFLAG_RW,
1315     &stat_jnewblk, 0, "");
1316 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low, CTLFLAG_RW,
1317     &stat_journal_low, 0, "");
1318 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min, CTLFLAG_RW,
1319     &stat_journal_min, 0, "");
1320 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait, CTLFLAG_RW,
1321     &stat_journal_wait, 0, "");
1322 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage, CTLFLAG_RW,
1323     &stat_jwait_filepage, 0, "");
1324 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks, CTLFLAG_RW,
1325     &stat_jwait_freeblks, 0, "");
1326 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode, CTLFLAG_RW,
1327     &stat_jwait_inode, 0, "");
1328 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk, CTLFLAG_RW,
1329     &stat_jwait_newblk, 0, "");
1330 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests, CTLFLAG_RW,
1331     &stat_cleanup_blkrequests, 0, "");
1332 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests, CTLFLAG_RW,
1333     &stat_cleanup_inorequests, 0, "");
1334 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay, CTLFLAG_RW,
1335     &stat_cleanup_high_delay, 0, "");
1336 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries, CTLFLAG_RW,
1337     &stat_cleanup_retries, 0, "");
1338 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures, CTLFLAG_RW,
1339     &stat_cleanup_failures, 0, "");
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1341     &softdep_flushcache, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1343     &stat_emptyjblocks, 0, "");
1344 
1345 SYSCTL_DECL(_vfs_ffs);
1346 
1347 /* Whether to recompute the summary at mount time */
1348 static int compute_summary_at_mount = 0;
1349 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1350 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1351 static int print_threads = 0;
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1353     &print_threads, 0, "Notify flusher thread start/stop");
1354 
1355 /* List of all filesystems mounted with soft updates */
1356 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1357 
1358 /*
1359  * This function cleans the worklist for a filesystem.
1360  * Each filesystem running with soft dependencies gets its own
1361  * thread to run in this function. The thread is started up in
1362  * softdep_mount and shutdown in softdep_unmount. They show up
1363  * as part of the kernel "bufdaemon" process whose process
1364  * entry is available in bufdaemonproc.
1365  */
1366 static int searchfailed;
1367 extern struct proc *bufdaemonproc;
1368 static void
1369 softdep_flush(addr)
1370 	void *addr;
1371 {
1372 	struct mount *mp;
1373 	struct thread *td;
1374 	struct ufsmount *ump;
1375 
1376 	td = curthread;
1377 	td->td_pflags |= TDP_NORUNNINGBUF;
1378 	mp = (struct mount *)addr;
1379 	ump = VFSTOUFS(mp);
1380 	atomic_add_int(&stat_flush_threads, 1);
1381 	ACQUIRE_LOCK(ump);
1382 	ump->softdep_flags &= ~FLUSH_STARTING;
1383 	wakeup(&ump->softdep_flushtd);
1384 	FREE_LOCK(ump);
1385 	if (print_threads) {
1386 		if (stat_flush_threads == 1)
1387 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1388 			    bufdaemonproc->p_pid);
1389 		printf("Start thread %s\n", td->td_name);
1390 	}
1391 	for (;;) {
1392 		while (softdep_process_worklist(mp, 0) > 0 ||
1393 		    (MOUNTEDSUJ(mp) &&
1394 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1395 			kthread_suspend_check();
1396 		ACQUIRE_LOCK(ump);
1397 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1398 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1399 			    "sdflush", hz / 2);
1400 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1401 		/*
1402 		 * Check to see if we are done and need to exit.
1403 		 */
1404 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1405 			FREE_LOCK(ump);
1406 			continue;
1407 		}
1408 		ump->softdep_flags &= ~FLUSH_EXIT;
1409 		FREE_LOCK(ump);
1410 		wakeup(&ump->softdep_flags);
1411 		if (print_threads)
1412 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1413 		atomic_subtract_int(&stat_flush_threads, 1);
1414 		kthread_exit();
1415 		panic("kthread_exit failed\n");
1416 	}
1417 }
1418 
1419 static void
1420 worklist_speedup(mp)
1421 	struct mount *mp;
1422 {
1423 	struct ufsmount *ump;
1424 
1425 	ump = VFSTOUFS(mp);
1426 	LOCK_OWNED(ump);
1427 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1428 		ump->softdep_flags |= FLUSH_CLEANUP;
1429 	wakeup(&ump->softdep_flushtd);
1430 }
1431 
1432 static int
1433 softdep_speedup(ump)
1434 	struct ufsmount *ump;
1435 {
1436 	struct ufsmount *altump;
1437 	struct mount_softdeps *sdp;
1438 
1439 	LOCK_OWNED(ump);
1440 	worklist_speedup(ump->um_mountp);
1441 	bd_speedup();
1442 	/*
1443 	 * If we have global shortages, then we need other
1444 	 * filesystems to help with the cleanup. Here we wakeup a
1445 	 * flusher thread for a filesystem that is over its fair
1446 	 * share of resources.
1447 	 */
1448 	if (req_clear_inodedeps || req_clear_remove) {
1449 		ACQUIRE_GBLLOCK(&lk);
1450 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1451 			if ((altump = sdp->sd_ump) == ump)
1452 				continue;
1453 			if (((req_clear_inodedeps &&
1454 			    altump->softdep_curdeps[D_INODEDEP] >
1455 			    max_softdeps / stat_flush_threads) ||
1456 			    (req_clear_remove &&
1457 			    altump->softdep_curdeps[D_DIRREM] >
1458 			    (max_softdeps / 2) / stat_flush_threads)) &&
1459 			    TRY_ACQUIRE_LOCK(altump))
1460 				break;
1461 		}
1462 		if (sdp == NULL) {
1463 			searchfailed++;
1464 			FREE_GBLLOCK(&lk);
1465 		} else {
1466 			/*
1467 			 * Move to the end of the list so we pick a
1468 			 * different one on out next try.
1469 			 */
1470 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1471 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1472 			FREE_GBLLOCK(&lk);
1473 			if ((altump->softdep_flags &
1474 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1475 				altump->softdep_flags |= FLUSH_CLEANUP;
1476 			altump->um_softdep->sd_cleanups++;
1477 			wakeup(&altump->softdep_flushtd);
1478 			FREE_LOCK(altump);
1479 		}
1480 	}
1481 	return (speedup_syncer());
1482 }
1483 
1484 /*
1485  * Add an item to the end of the work queue.
1486  * This routine requires that the lock be held.
1487  * This is the only routine that adds items to the list.
1488  * The following routine is the only one that removes items
1489  * and does so in order from first to last.
1490  */
1491 
1492 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1493 #define	WK_NODELAY	0x0002	/* Process immediately. */
1494 
1495 static void
1496 add_to_worklist(wk, flags)
1497 	struct worklist *wk;
1498 	int flags;
1499 {
1500 	struct ufsmount *ump;
1501 
1502 	ump = VFSTOUFS(wk->wk_mp);
1503 	LOCK_OWNED(ump);
1504 	if (wk->wk_state & ONWORKLIST)
1505 		panic("add_to_worklist: %s(0x%X) already on list",
1506 		    TYPENAME(wk->wk_type), wk->wk_state);
1507 	wk->wk_state |= ONWORKLIST;
1508 	if (ump->softdep_on_worklist == 0) {
1509 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1510 		ump->softdep_worklist_tail = wk;
1511 	} else if (flags & WK_HEAD) {
1512 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1513 	} else {
1514 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1515 		ump->softdep_worklist_tail = wk;
1516 	}
1517 	ump->softdep_on_worklist += 1;
1518 	if (flags & WK_NODELAY)
1519 		worklist_speedup(wk->wk_mp);
1520 }
1521 
1522 /*
1523  * Remove the item to be processed. If we are removing the last
1524  * item on the list, we need to recalculate the tail pointer.
1525  */
1526 static void
1527 remove_from_worklist(wk)
1528 	struct worklist *wk;
1529 {
1530 	struct ufsmount *ump;
1531 
1532 	ump = VFSTOUFS(wk->wk_mp);
1533 	WORKLIST_REMOVE(wk);
1534 	if (ump->softdep_worklist_tail == wk)
1535 		ump->softdep_worklist_tail =
1536 		    (struct worklist *)wk->wk_list.le_prev;
1537 	ump->softdep_on_worklist -= 1;
1538 }
1539 
1540 static void
1541 wake_worklist(wk)
1542 	struct worklist *wk;
1543 {
1544 	if (wk->wk_state & IOWAITING) {
1545 		wk->wk_state &= ~IOWAITING;
1546 		wakeup(wk);
1547 	}
1548 }
1549 
1550 static void
1551 wait_worklist(wk, wmesg)
1552 	struct worklist *wk;
1553 	char *wmesg;
1554 {
1555 	struct ufsmount *ump;
1556 
1557 	ump = VFSTOUFS(wk->wk_mp);
1558 	wk->wk_state |= IOWAITING;
1559 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1560 }
1561 
1562 /*
1563  * Process that runs once per second to handle items in the background queue.
1564  *
1565  * Note that we ensure that everything is done in the order in which they
1566  * appear in the queue. The code below depends on this property to ensure
1567  * that blocks of a file are freed before the inode itself is freed. This
1568  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1569  * until all the old ones have been purged from the dependency lists.
1570  */
1571 static int
1572 softdep_process_worklist(mp, full)
1573 	struct mount *mp;
1574 	int full;
1575 {
1576 	int cnt, matchcnt;
1577 	struct ufsmount *ump;
1578 	long starttime;
1579 
1580 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1581 	if (MOUNTEDSOFTDEP(mp) == 0)
1582 		return (0);
1583 	matchcnt = 0;
1584 	ump = VFSTOUFS(mp);
1585 	ACQUIRE_LOCK(ump);
1586 	starttime = time_second;
1587 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1588 	check_clear_deps(mp);
1589 	while (ump->softdep_on_worklist > 0) {
1590 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1591 			break;
1592 		else
1593 			matchcnt += cnt;
1594 		check_clear_deps(mp);
1595 		/*
1596 		 * We do not generally want to stop for buffer space, but if
1597 		 * we are really being a buffer hog, we will stop and wait.
1598 		 */
1599 		if (should_yield()) {
1600 			FREE_LOCK(ump);
1601 			kern_yield(PRI_USER);
1602 			bwillwrite();
1603 			ACQUIRE_LOCK(ump);
1604 		}
1605 		/*
1606 		 * Never allow processing to run for more than one
1607 		 * second. This gives the syncer thread the opportunity
1608 		 * to pause if appropriate.
1609 		 */
1610 		if (!full && starttime != time_second)
1611 			break;
1612 	}
1613 	if (full == 0)
1614 		journal_unsuspend(ump);
1615 	FREE_LOCK(ump);
1616 	return (matchcnt);
1617 }
1618 
1619 /*
1620  * Process all removes associated with a vnode if we are running out of
1621  * journal space.  Any other process which attempts to flush these will
1622  * be unable as we have the vnodes locked.
1623  */
1624 static void
1625 process_removes(vp)
1626 	struct vnode *vp;
1627 {
1628 	struct inodedep *inodedep;
1629 	struct dirrem *dirrem;
1630 	struct ufsmount *ump;
1631 	struct mount *mp;
1632 	ino_t inum;
1633 
1634 	mp = vp->v_mount;
1635 	ump = VFSTOUFS(mp);
1636 	LOCK_OWNED(ump);
1637 	inum = VTOI(vp)->i_number;
1638 	for (;;) {
1639 top:
1640 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1641 			return;
1642 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1643 			/*
1644 			 * If another thread is trying to lock this vnode
1645 			 * it will fail but we must wait for it to do so
1646 			 * before we can proceed.
1647 			 */
1648 			if (dirrem->dm_state & INPROGRESS) {
1649 				wait_worklist(&dirrem->dm_list, "pwrwait");
1650 				goto top;
1651 			}
1652 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1653 			    (COMPLETE | ONWORKLIST))
1654 				break;
1655 		}
1656 		if (dirrem == NULL)
1657 			return;
1658 		remove_from_worklist(&dirrem->dm_list);
1659 		FREE_LOCK(ump);
1660 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1661 			panic("process_removes: suspended filesystem");
1662 		handle_workitem_remove(dirrem, 0);
1663 		vn_finished_secondary_write(mp);
1664 		ACQUIRE_LOCK(ump);
1665 	}
1666 }
1667 
1668 /*
1669  * Process all truncations associated with a vnode if we are running out
1670  * of journal space.  This is called when the vnode lock is already held
1671  * and no other process can clear the truncation.  This function returns
1672  * a value greater than zero if it did any work.
1673  */
1674 static void
1675 process_truncates(vp)
1676 	struct vnode *vp;
1677 {
1678 	struct inodedep *inodedep;
1679 	struct freeblks *freeblks;
1680 	struct ufsmount *ump;
1681 	struct mount *mp;
1682 	ino_t inum;
1683 	int cgwait;
1684 
1685 	mp = vp->v_mount;
1686 	ump = VFSTOUFS(mp);
1687 	LOCK_OWNED(ump);
1688 	inum = VTOI(vp)->i_number;
1689 	for (;;) {
1690 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1691 			return;
1692 		cgwait = 0;
1693 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1694 			/* Journal entries not yet written.  */
1695 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1696 				jwait(&LIST_FIRST(
1697 				    &freeblks->fb_jblkdephd)->jb_list,
1698 				    MNT_WAIT);
1699 				break;
1700 			}
1701 			/* Another thread is executing this item. */
1702 			if (freeblks->fb_state & INPROGRESS) {
1703 				wait_worklist(&freeblks->fb_list, "ptrwait");
1704 				break;
1705 			}
1706 			/* Freeblks is waiting on a inode write. */
1707 			if ((freeblks->fb_state & COMPLETE) == 0) {
1708 				FREE_LOCK(ump);
1709 				ffs_update(vp, 1);
1710 				ACQUIRE_LOCK(ump);
1711 				break;
1712 			}
1713 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1714 			    (ALLCOMPLETE | ONWORKLIST)) {
1715 				remove_from_worklist(&freeblks->fb_list);
1716 				freeblks->fb_state |= INPROGRESS;
1717 				FREE_LOCK(ump);
1718 				if (vn_start_secondary_write(NULL, &mp,
1719 				    V_NOWAIT))
1720 					panic("process_truncates: "
1721 					    "suspended filesystem");
1722 				handle_workitem_freeblocks(freeblks, 0);
1723 				vn_finished_secondary_write(mp);
1724 				ACQUIRE_LOCK(ump);
1725 				break;
1726 			}
1727 			if (freeblks->fb_cgwait)
1728 				cgwait++;
1729 		}
1730 		if (cgwait) {
1731 			FREE_LOCK(ump);
1732 			sync_cgs(mp, MNT_WAIT);
1733 			ffs_sync_snap(mp, MNT_WAIT);
1734 			ACQUIRE_LOCK(ump);
1735 			continue;
1736 		}
1737 		if (freeblks == NULL)
1738 			break;
1739 	}
1740 	return;
1741 }
1742 
1743 /*
1744  * Process one item on the worklist.
1745  */
1746 static int
1747 process_worklist_item(mp, target, flags)
1748 	struct mount *mp;
1749 	int target;
1750 	int flags;
1751 {
1752 	struct worklist sentinel;
1753 	struct worklist *wk;
1754 	struct ufsmount *ump;
1755 	int matchcnt;
1756 	int error;
1757 
1758 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1759 	/*
1760 	 * If we are being called because of a process doing a
1761 	 * copy-on-write, then it is not safe to write as we may
1762 	 * recurse into the copy-on-write routine.
1763 	 */
1764 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1765 		return (-1);
1766 	PHOLD(curproc);	/* Don't let the stack go away. */
1767 	ump = VFSTOUFS(mp);
1768 	LOCK_OWNED(ump);
1769 	matchcnt = 0;
1770 	sentinel.wk_mp = NULL;
1771 	sentinel.wk_type = D_SENTINEL;
1772 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1773 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1774 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1775 		if (wk->wk_type == D_SENTINEL) {
1776 			LIST_REMOVE(&sentinel, wk_list);
1777 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1778 			continue;
1779 		}
1780 		if (wk->wk_state & INPROGRESS)
1781 			panic("process_worklist_item: %p already in progress.",
1782 			    wk);
1783 		wk->wk_state |= INPROGRESS;
1784 		remove_from_worklist(wk);
1785 		FREE_LOCK(ump);
1786 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1787 			panic("process_worklist_item: suspended filesystem");
1788 		switch (wk->wk_type) {
1789 		case D_DIRREM:
1790 			/* removal of a directory entry */
1791 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
1792 			break;
1793 
1794 		case D_FREEBLKS:
1795 			/* releasing blocks and/or fragments from a file */
1796 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
1797 			    flags);
1798 			break;
1799 
1800 		case D_FREEFRAG:
1801 			/* releasing a fragment when replaced as a file grows */
1802 			handle_workitem_freefrag(WK_FREEFRAG(wk));
1803 			error = 0;
1804 			break;
1805 
1806 		case D_FREEFILE:
1807 			/* releasing an inode when its link count drops to 0 */
1808 			handle_workitem_freefile(WK_FREEFILE(wk));
1809 			error = 0;
1810 			break;
1811 
1812 		default:
1813 			panic("%s_process_worklist: Unknown type %s",
1814 			    "softdep", TYPENAME(wk->wk_type));
1815 			/* NOTREACHED */
1816 		}
1817 		vn_finished_secondary_write(mp);
1818 		ACQUIRE_LOCK(ump);
1819 		if (error == 0) {
1820 			if (++matchcnt == target)
1821 				break;
1822 			continue;
1823 		}
1824 		/*
1825 		 * We have to retry the worklist item later.  Wake up any
1826 		 * waiters who may be able to complete it immediately and
1827 		 * add the item back to the head so we don't try to execute
1828 		 * it again.
1829 		 */
1830 		wk->wk_state &= ~INPROGRESS;
1831 		wake_worklist(wk);
1832 		add_to_worklist(wk, WK_HEAD);
1833 	}
1834 	LIST_REMOVE(&sentinel, wk_list);
1835 	/* Sentinal could've become the tail from remove_from_worklist. */
1836 	if (ump->softdep_worklist_tail == &sentinel)
1837 		ump->softdep_worklist_tail =
1838 		    (struct worklist *)sentinel.wk_list.le_prev;
1839 	PRELE(curproc);
1840 	return (matchcnt);
1841 }
1842 
1843 /*
1844  * Move dependencies from one buffer to another.
1845  */
1846 int
1847 softdep_move_dependencies(oldbp, newbp)
1848 	struct buf *oldbp;
1849 	struct buf *newbp;
1850 {
1851 	struct worklist *wk, *wktail;
1852 	struct ufsmount *ump;
1853 	int dirty;
1854 
1855 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
1856 		return (0);
1857 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
1858 	    ("softdep_move_dependencies called on non-softdep filesystem"));
1859 	dirty = 0;
1860 	wktail = NULL;
1861 	ump = VFSTOUFS(wk->wk_mp);
1862 	ACQUIRE_LOCK(ump);
1863 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
1864 		LIST_REMOVE(wk, wk_list);
1865 		if (wk->wk_type == D_BMSAFEMAP &&
1866 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
1867 			dirty = 1;
1868 		if (wktail == 0)
1869 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
1870 		else
1871 			LIST_INSERT_AFTER(wktail, wk, wk_list);
1872 		wktail = wk;
1873 	}
1874 	FREE_LOCK(ump);
1875 
1876 	return (dirty);
1877 }
1878 
1879 /*
1880  * Purge the work list of all items associated with a particular mount point.
1881  */
1882 int
1883 softdep_flushworklist(oldmnt, countp, td)
1884 	struct mount *oldmnt;
1885 	int *countp;
1886 	struct thread *td;
1887 {
1888 	struct vnode *devvp;
1889 	struct ufsmount *ump;
1890 	int count, error;
1891 
1892 	/*
1893 	 * Alternately flush the block device associated with the mount
1894 	 * point and process any dependencies that the flushing
1895 	 * creates. We continue until no more worklist dependencies
1896 	 * are found.
1897 	 */
1898 	*countp = 0;
1899 	error = 0;
1900 	ump = VFSTOUFS(oldmnt);
1901 	devvp = ump->um_devvp;
1902 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
1903 		*countp += count;
1904 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1905 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1906 		VOP_UNLOCK(devvp, 0);
1907 		if (error != 0)
1908 			break;
1909 	}
1910 	return (error);
1911 }
1912 
1913 #define	SU_WAITIDLE_RETRIES	20
1914 static int
1915 softdep_waitidle(struct mount *mp, int flags __unused)
1916 {
1917 	struct ufsmount *ump;
1918 	struct vnode *devvp;
1919 	struct thread *td;
1920 	int error, i;
1921 
1922 	ump = VFSTOUFS(mp);
1923 	devvp = ump->um_devvp;
1924 	td = curthread;
1925 	error = 0;
1926 	ACQUIRE_LOCK(ump);
1927 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
1928 		ump->softdep_req = 1;
1929 		KASSERT((flags & FORCECLOSE) == 0 ||
1930 		    ump->softdep_on_worklist == 0,
1931 		    ("softdep_waitidle: work added after flush"));
1932 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
1933 		    "softdeps", 10 * hz);
1934 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
1935 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
1936 		VOP_UNLOCK(devvp, 0);
1937 		if (error != 0)
1938 			break;
1939 		ACQUIRE_LOCK(ump);
1940 	}
1941 	ump->softdep_req = 0;
1942 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
1943 		error = EBUSY;
1944 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
1945 		    mp);
1946 	}
1947 	FREE_LOCK(ump);
1948 	return (error);
1949 }
1950 
1951 /*
1952  * Flush all vnodes and worklist items associated with a specified mount point.
1953  */
1954 int
1955 softdep_flushfiles(oldmnt, flags, td)
1956 	struct mount *oldmnt;
1957 	int flags;
1958 	struct thread *td;
1959 {
1960 #ifdef QUOTA
1961 	struct ufsmount *ump;
1962 	int i;
1963 #endif
1964 	int error, early, depcount, loopcnt, retry_flush_count, retry;
1965 	int morework;
1966 
1967 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
1968 	    ("softdep_flushfiles called on non-softdep filesystem"));
1969 	loopcnt = 10;
1970 	retry_flush_count = 3;
1971 retry_flush:
1972 	error = 0;
1973 
1974 	/*
1975 	 * Alternately flush the vnodes associated with the mount
1976 	 * point and process any dependencies that the flushing
1977 	 * creates. In theory, this loop can happen at most twice,
1978 	 * but we give it a few extra just to be sure.
1979 	 */
1980 	for (; loopcnt > 0; loopcnt--) {
1981 		/*
1982 		 * Do another flush in case any vnodes were brought in
1983 		 * as part of the cleanup operations.
1984 		 */
1985 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
1986 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
1987 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
1988 			break;
1989 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
1990 		    depcount == 0)
1991 			break;
1992 	}
1993 	/*
1994 	 * If we are unmounting then it is an error to fail. If we
1995 	 * are simply trying to downgrade to read-only, then filesystem
1996 	 * activity can keep us busy forever, so we just fail with EBUSY.
1997 	 */
1998 	if (loopcnt == 0) {
1999 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2000 			panic("softdep_flushfiles: looping");
2001 		error = EBUSY;
2002 	}
2003 	if (!error)
2004 		error = softdep_waitidle(oldmnt, flags);
2005 	if (!error) {
2006 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2007 			retry = 0;
2008 			MNT_ILOCK(oldmnt);
2009 			KASSERT((oldmnt->mnt_kern_flag & MNTK_NOINSMNTQ) != 0,
2010 			    ("softdep_flushfiles: !MNTK_NOINSMNTQ"));
2011 			morework = oldmnt->mnt_nvnodelistsize > 0;
2012 #ifdef QUOTA
2013 			ump = VFSTOUFS(oldmnt);
2014 			UFS_LOCK(ump);
2015 			for (i = 0; i < MAXQUOTAS; i++) {
2016 				if (ump->um_quotas[i] != NULLVP)
2017 					morework = 1;
2018 			}
2019 			UFS_UNLOCK(ump);
2020 #endif
2021 			if (morework) {
2022 				if (--retry_flush_count > 0) {
2023 					retry = 1;
2024 					loopcnt = 3;
2025 				} else
2026 					error = EBUSY;
2027 			}
2028 			MNT_IUNLOCK(oldmnt);
2029 			if (retry)
2030 				goto retry_flush;
2031 		}
2032 	}
2033 	return (error);
2034 }
2035 
2036 /*
2037  * Structure hashing.
2038  *
2039  * There are four types of structures that can be looked up:
2040  *	1) pagedep structures identified by mount point, inode number,
2041  *	   and logical block.
2042  *	2) inodedep structures identified by mount point and inode number.
2043  *	3) newblk structures identified by mount point and
2044  *	   physical block number.
2045  *	4) bmsafemap structures identified by mount point and
2046  *	   cylinder group number.
2047  *
2048  * The "pagedep" and "inodedep" dependency structures are hashed
2049  * separately from the file blocks and inodes to which they correspond.
2050  * This separation helps when the in-memory copy of an inode or
2051  * file block must be replaced. It also obviates the need to access
2052  * an inode or file page when simply updating (or de-allocating)
2053  * dependency structures. Lookup of newblk structures is needed to
2054  * find newly allocated blocks when trying to associate them with
2055  * their allocdirect or allocindir structure.
2056  *
2057  * The lookup routines optionally create and hash a new instance when
2058  * an existing entry is not found. The bmsafemap lookup routine always
2059  * allocates a new structure if an existing one is not found.
2060  */
2061 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2062 #define NODELAY		0x0002	/* cannot do background work */
2063 
2064 /*
2065  * Structures and routines associated with pagedep caching.
2066  */
2067 #define	PAGEDEP_HASH(ump, inum, lbn) \
2068 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2069 
2070 static int
2071 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2072 	struct pagedep_hashhead *pagedephd;
2073 	ino_t ino;
2074 	ufs_lbn_t lbn;
2075 	struct pagedep **pagedeppp;
2076 {
2077 	struct pagedep *pagedep;
2078 
2079 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2080 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2081 			*pagedeppp = pagedep;
2082 			return (1);
2083 		}
2084 	}
2085 	*pagedeppp = NULL;
2086 	return (0);
2087 }
2088 /*
2089  * Look up a pagedep. Return 1 if found, 0 otherwise.
2090  * If not found, allocate if DEPALLOC flag is passed.
2091  * Found or allocated entry is returned in pagedeppp.
2092  * This routine must be called with splbio interrupts blocked.
2093  */
2094 static int
2095 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2096 	struct mount *mp;
2097 	struct buf *bp;
2098 	ino_t ino;
2099 	ufs_lbn_t lbn;
2100 	int flags;
2101 	struct pagedep **pagedeppp;
2102 {
2103 	struct pagedep *pagedep;
2104 	struct pagedep_hashhead *pagedephd;
2105 	struct worklist *wk;
2106 	struct ufsmount *ump;
2107 	int ret;
2108 	int i;
2109 
2110 	ump = VFSTOUFS(mp);
2111 	LOCK_OWNED(ump);
2112 	if (bp) {
2113 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2114 			if (wk->wk_type == D_PAGEDEP) {
2115 				*pagedeppp = WK_PAGEDEP(wk);
2116 				return (1);
2117 			}
2118 		}
2119 	}
2120 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2121 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2122 	if (ret) {
2123 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2124 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2125 		return (1);
2126 	}
2127 	if ((flags & DEPALLOC) == 0)
2128 		return (0);
2129 	FREE_LOCK(ump);
2130 	pagedep = malloc(sizeof(struct pagedep),
2131 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2132 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2133 	ACQUIRE_LOCK(ump);
2134 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2135 	if (*pagedeppp) {
2136 		/*
2137 		 * This should never happen since we only create pagedeps
2138 		 * with the vnode lock held.  Could be an assert.
2139 		 */
2140 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2141 		return (ret);
2142 	}
2143 	pagedep->pd_ino = ino;
2144 	pagedep->pd_lbn = lbn;
2145 	LIST_INIT(&pagedep->pd_dirremhd);
2146 	LIST_INIT(&pagedep->pd_pendinghd);
2147 	for (i = 0; i < DAHASHSZ; i++)
2148 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2149 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2150 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2151 	*pagedeppp = pagedep;
2152 	return (0);
2153 }
2154 
2155 /*
2156  * Structures and routines associated with inodedep caching.
2157  */
2158 #define	INODEDEP_HASH(ump, inum) \
2159       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2160 
2161 static int
2162 inodedep_find(inodedephd, inum, inodedeppp)
2163 	struct inodedep_hashhead *inodedephd;
2164 	ino_t inum;
2165 	struct inodedep **inodedeppp;
2166 {
2167 	struct inodedep *inodedep;
2168 
2169 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2170 		if (inum == inodedep->id_ino)
2171 			break;
2172 	if (inodedep) {
2173 		*inodedeppp = inodedep;
2174 		return (1);
2175 	}
2176 	*inodedeppp = NULL;
2177 
2178 	return (0);
2179 }
2180 /*
2181  * Look up an inodedep. Return 1 if found, 0 if not found.
2182  * If not found, allocate if DEPALLOC flag is passed.
2183  * Found or allocated entry is returned in inodedeppp.
2184  * This routine must be called with splbio interrupts blocked.
2185  */
2186 static int
2187 inodedep_lookup(mp, inum, flags, inodedeppp)
2188 	struct mount *mp;
2189 	ino_t inum;
2190 	int flags;
2191 	struct inodedep **inodedeppp;
2192 {
2193 	struct inodedep *inodedep;
2194 	struct inodedep_hashhead *inodedephd;
2195 	struct ufsmount *ump;
2196 	struct fs *fs;
2197 
2198 	ump = VFSTOUFS(mp);
2199 	LOCK_OWNED(ump);
2200 	fs = ump->um_fs;
2201 	inodedephd = INODEDEP_HASH(ump, inum);
2202 
2203 	if (inodedep_find(inodedephd, inum, inodedeppp))
2204 		return (1);
2205 	if ((flags & DEPALLOC) == 0)
2206 		return (0);
2207 	/*
2208 	 * If the system is over its limit and our filesystem is
2209 	 * responsible for more than our share of that usage and
2210 	 * we are not in a rush, request some inodedep cleanup.
2211 	 */
2212 	while (dep_current[D_INODEDEP] > max_softdeps &&
2213 	    (flags & NODELAY) == 0 &&
2214 	    ump->softdep_curdeps[D_INODEDEP] >
2215 	    max_softdeps / stat_flush_threads)
2216 		request_cleanup(mp, FLUSH_INODES);
2217 	FREE_LOCK(ump);
2218 	inodedep = malloc(sizeof(struct inodedep),
2219 		M_INODEDEP, M_SOFTDEP_FLAGS);
2220 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2221 	ACQUIRE_LOCK(ump);
2222 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2223 		WORKITEM_FREE(inodedep, D_INODEDEP);
2224 		return (1);
2225 	}
2226 	inodedep->id_fs = fs;
2227 	inodedep->id_ino = inum;
2228 	inodedep->id_state = ALLCOMPLETE;
2229 	inodedep->id_nlinkdelta = 0;
2230 	inodedep->id_savedino1 = NULL;
2231 	inodedep->id_savedsize = -1;
2232 	inodedep->id_savedextsize = -1;
2233 	inodedep->id_savednlink = -1;
2234 	inodedep->id_bmsafemap = NULL;
2235 	inodedep->id_mkdiradd = NULL;
2236 	LIST_INIT(&inodedep->id_dirremhd);
2237 	LIST_INIT(&inodedep->id_pendinghd);
2238 	LIST_INIT(&inodedep->id_inowait);
2239 	LIST_INIT(&inodedep->id_bufwait);
2240 	TAILQ_INIT(&inodedep->id_inoreflst);
2241 	TAILQ_INIT(&inodedep->id_inoupdt);
2242 	TAILQ_INIT(&inodedep->id_newinoupdt);
2243 	TAILQ_INIT(&inodedep->id_extupdt);
2244 	TAILQ_INIT(&inodedep->id_newextupdt);
2245 	TAILQ_INIT(&inodedep->id_freeblklst);
2246 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2247 	*inodedeppp = inodedep;
2248 	return (0);
2249 }
2250 
2251 /*
2252  * Structures and routines associated with newblk caching.
2253  */
2254 #define	NEWBLK_HASH(ump, inum) \
2255 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2256 
2257 static int
2258 newblk_find(newblkhd, newblkno, flags, newblkpp)
2259 	struct newblk_hashhead *newblkhd;
2260 	ufs2_daddr_t newblkno;
2261 	int flags;
2262 	struct newblk **newblkpp;
2263 {
2264 	struct newblk *newblk;
2265 
2266 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2267 		if (newblkno != newblk->nb_newblkno)
2268 			continue;
2269 		/*
2270 		 * If we're creating a new dependency don't match those that
2271 		 * have already been converted to allocdirects.  This is for
2272 		 * a frag extend.
2273 		 */
2274 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2275 			continue;
2276 		break;
2277 	}
2278 	if (newblk) {
2279 		*newblkpp = newblk;
2280 		return (1);
2281 	}
2282 	*newblkpp = NULL;
2283 	return (0);
2284 }
2285 
2286 /*
2287  * Look up a newblk. Return 1 if found, 0 if not found.
2288  * If not found, allocate if DEPALLOC flag is passed.
2289  * Found or allocated entry is returned in newblkpp.
2290  */
2291 static int
2292 newblk_lookup(mp, newblkno, flags, newblkpp)
2293 	struct mount *mp;
2294 	ufs2_daddr_t newblkno;
2295 	int flags;
2296 	struct newblk **newblkpp;
2297 {
2298 	struct newblk *newblk;
2299 	struct newblk_hashhead *newblkhd;
2300 	struct ufsmount *ump;
2301 
2302 	ump = VFSTOUFS(mp);
2303 	LOCK_OWNED(ump);
2304 	newblkhd = NEWBLK_HASH(ump, newblkno);
2305 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2306 		return (1);
2307 	if ((flags & DEPALLOC) == 0)
2308 		return (0);
2309 	FREE_LOCK(ump);
2310 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2311 	    M_SOFTDEP_FLAGS | M_ZERO);
2312 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2313 	ACQUIRE_LOCK(ump);
2314 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2315 		WORKITEM_FREE(newblk, D_NEWBLK);
2316 		return (1);
2317 	}
2318 	newblk->nb_freefrag = NULL;
2319 	LIST_INIT(&newblk->nb_indirdeps);
2320 	LIST_INIT(&newblk->nb_newdirblk);
2321 	LIST_INIT(&newblk->nb_jwork);
2322 	newblk->nb_state = ATTACHED;
2323 	newblk->nb_newblkno = newblkno;
2324 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2325 	*newblkpp = newblk;
2326 	return (0);
2327 }
2328 
2329 /*
2330  * Structures and routines associated with freed indirect block caching.
2331  */
2332 #define	INDIR_HASH(ump, blkno) \
2333 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2334 
2335 /*
2336  * Lookup an indirect block in the indir hash table.  The freework is
2337  * removed and potentially freed.  The caller must do a blocking journal
2338  * write before writing to the blkno.
2339  */
2340 static int
2341 indirblk_lookup(mp, blkno)
2342 	struct mount *mp;
2343 	ufs2_daddr_t blkno;
2344 {
2345 	struct freework *freework;
2346 	struct indir_hashhead *wkhd;
2347 	struct ufsmount *ump;
2348 
2349 	ump = VFSTOUFS(mp);
2350 	wkhd = INDIR_HASH(ump, blkno);
2351 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2352 		if (freework->fw_blkno != blkno)
2353 			continue;
2354 		indirblk_remove(freework);
2355 		return (1);
2356 	}
2357 	return (0);
2358 }
2359 
2360 /*
2361  * Insert an indirect block represented by freework into the indirblk
2362  * hash table so that it may prevent the block from being re-used prior
2363  * to the journal being written.
2364  */
2365 static void
2366 indirblk_insert(freework)
2367 	struct freework *freework;
2368 {
2369 	struct jblocks *jblocks;
2370 	struct jseg *jseg;
2371 	struct ufsmount *ump;
2372 
2373 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2374 	jblocks = ump->softdep_jblocks;
2375 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2376 	if (jseg == NULL)
2377 		return;
2378 
2379 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2380 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2381 	    fw_next);
2382 	freework->fw_state &= ~DEPCOMPLETE;
2383 }
2384 
2385 static void
2386 indirblk_remove(freework)
2387 	struct freework *freework;
2388 {
2389 	struct ufsmount *ump;
2390 
2391 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2392 	LIST_REMOVE(freework, fw_segs);
2393 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2394 	freework->fw_state |= DEPCOMPLETE;
2395 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2396 		WORKITEM_FREE(freework, D_FREEWORK);
2397 }
2398 
2399 /*
2400  * Executed during filesystem system initialization before
2401  * mounting any filesystems.
2402  */
2403 void
2404 softdep_initialize()
2405 {
2406 
2407 	TAILQ_INIT(&softdepmounts);
2408 	max_softdeps = desiredvnodes * 4;
2409 
2410 	/* initialise bioops hack */
2411 	bioops.io_start = softdep_disk_io_initiation;
2412 	bioops.io_complete = softdep_disk_write_complete;
2413 	bioops.io_deallocate = softdep_deallocate_dependencies;
2414 	bioops.io_countdeps = softdep_count_dependencies;
2415 
2416 	/* Initialize the callout with an mtx. */
2417 	callout_init_mtx(&softdep_callout, &lk, 0);
2418 }
2419 
2420 /*
2421  * Executed after all filesystems have been unmounted during
2422  * filesystem module unload.
2423  */
2424 void
2425 softdep_uninitialize()
2426 {
2427 
2428 	/* clear bioops hack */
2429 	bioops.io_start = NULL;
2430 	bioops.io_complete = NULL;
2431 	bioops.io_deallocate = NULL;
2432 	bioops.io_countdeps = NULL;
2433 
2434 	callout_drain(&softdep_callout);
2435 }
2436 
2437 /*
2438  * Called at mount time to notify the dependency code that a
2439  * filesystem wishes to use it.
2440  */
2441 int
2442 softdep_mount(devvp, mp, fs, cred)
2443 	struct vnode *devvp;
2444 	struct mount *mp;
2445 	struct fs *fs;
2446 	struct ucred *cred;
2447 {
2448 	struct csum_total cstotal;
2449 	struct mount_softdeps *sdp;
2450 	struct ufsmount *ump;
2451 	struct cg *cgp;
2452 	struct buf *bp;
2453 	int i, error, cyl;
2454 
2455 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2456 	    M_WAITOK | M_ZERO);
2457 	MNT_ILOCK(mp);
2458 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2459 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2460 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2461 			MNTK_SOFTDEP | MNTK_NOASYNC;
2462 	}
2463 	ump = VFSTOUFS(mp);
2464 	ump->um_softdep = sdp;
2465 	MNT_IUNLOCK(mp);
2466 	rw_init(LOCK_PTR(ump), "Per-Filesystem Softdep Lock");
2467 	sdp->sd_ump = ump;
2468 	LIST_INIT(&ump->softdep_workitem_pending);
2469 	LIST_INIT(&ump->softdep_journal_pending);
2470 	TAILQ_INIT(&ump->softdep_unlinked);
2471 	LIST_INIT(&ump->softdep_dirtycg);
2472 	ump->softdep_worklist_tail = NULL;
2473 	ump->softdep_on_worklist = 0;
2474 	ump->softdep_deps = 0;
2475 	LIST_INIT(&ump->softdep_mkdirlisthd);
2476 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2477 	    &ump->pagedep_hash_size);
2478 	ump->pagedep_nextclean = 0;
2479 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2480 	    &ump->inodedep_hash_size);
2481 	ump->inodedep_nextclean = 0;
2482 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2483 	    &ump->newblk_hash_size);
2484 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2485 	    &ump->bmsafemap_hash_size);
2486 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2487 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2488 	    M_FREEWORK, M_WAITOK);
2489 	ump->indir_hash_size = i - 1;
2490 	for (i = 0; i <= ump->indir_hash_size; i++)
2491 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2492 	ACQUIRE_GBLLOCK(&lk);
2493 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2494 	FREE_GBLLOCK(&lk);
2495 	if ((fs->fs_flags & FS_SUJ) &&
2496 	    (error = journal_mount(mp, fs, cred)) != 0) {
2497 		printf("Failed to start journal: %d\n", error);
2498 		softdep_unmount(mp);
2499 		return (error);
2500 	}
2501 	/*
2502 	 * Start our flushing thread in the bufdaemon process.
2503 	 */
2504 	ACQUIRE_LOCK(ump);
2505 	ump->softdep_flags |= FLUSH_STARTING;
2506 	FREE_LOCK(ump);
2507 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2508 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2509 	    mp->mnt_stat.f_mntonname);
2510 	ACQUIRE_LOCK(ump);
2511 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2512 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2513 		    hz / 2);
2514 	}
2515 	FREE_LOCK(ump);
2516 	/*
2517 	 * When doing soft updates, the counters in the
2518 	 * superblock may have gotten out of sync. Recomputation
2519 	 * can take a long time and can be deferred for background
2520 	 * fsck.  However, the old behavior of scanning the cylinder
2521 	 * groups and recalculating them at mount time is available
2522 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2523 	 */
2524 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2525 		return (0);
2526 	bzero(&cstotal, sizeof cstotal);
2527 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2528 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2529 		    fs->fs_cgsize, cred, &bp)) != 0) {
2530 			brelse(bp);
2531 			softdep_unmount(mp);
2532 			return (error);
2533 		}
2534 		cgp = (struct cg *)bp->b_data;
2535 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2536 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2537 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2538 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2539 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2540 		brelse(bp);
2541 	}
2542 #ifdef DEBUG
2543 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2544 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2545 #endif
2546 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2547 	return (0);
2548 }
2549 
2550 void
2551 softdep_unmount(mp)
2552 	struct mount *mp;
2553 {
2554 	struct ufsmount *ump;
2555 #ifdef INVARIANTS
2556 	int i;
2557 #endif
2558 
2559 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2560 	    ("softdep_unmount called on non-softdep filesystem"));
2561 	ump = VFSTOUFS(mp);
2562 	MNT_ILOCK(mp);
2563 	mp->mnt_flag &= ~MNT_SOFTDEP;
2564 	if (MOUNTEDSUJ(mp) == 0) {
2565 		MNT_IUNLOCK(mp);
2566 	} else {
2567 		mp->mnt_flag &= ~MNT_SUJ;
2568 		MNT_IUNLOCK(mp);
2569 		journal_unmount(ump);
2570 	}
2571 	/*
2572 	 * Shut down our flushing thread. Check for NULL is if
2573 	 * softdep_mount errors out before the thread has been created.
2574 	 */
2575 	if (ump->softdep_flushtd != NULL) {
2576 		ACQUIRE_LOCK(ump);
2577 		ump->softdep_flags |= FLUSH_EXIT;
2578 		wakeup(&ump->softdep_flushtd);
2579 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2580 		    "sdwait", 0);
2581 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2582 		    ("Thread shutdown failed"));
2583 	}
2584 	/*
2585 	 * Free up our resources.
2586 	 */
2587 	ACQUIRE_GBLLOCK(&lk);
2588 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2589 	FREE_GBLLOCK(&lk);
2590 	rw_destroy(LOCK_PTR(ump));
2591 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2592 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2593 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2594 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2595 	    ump->bmsafemap_hash_size);
2596 	free(ump->indir_hashtbl, M_FREEWORK);
2597 #ifdef INVARIANTS
2598 	for (i = 0; i <= D_LAST; i++)
2599 		KASSERT(ump->softdep_curdeps[i] == 0,
2600 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2601 		    TYPENAME(i), ump->softdep_curdeps[i]));
2602 #endif
2603 	free(ump->um_softdep, M_MOUNTDATA);
2604 }
2605 
2606 static struct jblocks *
2607 jblocks_create(void)
2608 {
2609 	struct jblocks *jblocks;
2610 
2611 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2612 	TAILQ_INIT(&jblocks->jb_segs);
2613 	jblocks->jb_avail = 10;
2614 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2615 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2616 
2617 	return (jblocks);
2618 }
2619 
2620 static ufs2_daddr_t
2621 jblocks_alloc(jblocks, bytes, actual)
2622 	struct jblocks *jblocks;
2623 	int bytes;
2624 	int *actual;
2625 {
2626 	ufs2_daddr_t daddr;
2627 	struct jextent *jext;
2628 	int freecnt;
2629 	int blocks;
2630 
2631 	blocks = bytes / DEV_BSIZE;
2632 	jext = &jblocks->jb_extent[jblocks->jb_head];
2633 	freecnt = jext->je_blocks - jblocks->jb_off;
2634 	if (freecnt == 0) {
2635 		jblocks->jb_off = 0;
2636 		if (++jblocks->jb_head > jblocks->jb_used)
2637 			jblocks->jb_head = 0;
2638 		jext = &jblocks->jb_extent[jblocks->jb_head];
2639 		freecnt = jext->je_blocks;
2640 	}
2641 	if (freecnt > blocks)
2642 		freecnt = blocks;
2643 	*actual = freecnt * DEV_BSIZE;
2644 	daddr = jext->je_daddr + jblocks->jb_off;
2645 	jblocks->jb_off += freecnt;
2646 	jblocks->jb_free -= freecnt;
2647 
2648 	return (daddr);
2649 }
2650 
2651 static void
2652 jblocks_free(jblocks, mp, bytes)
2653 	struct jblocks *jblocks;
2654 	struct mount *mp;
2655 	int bytes;
2656 {
2657 
2658 	LOCK_OWNED(VFSTOUFS(mp));
2659 	jblocks->jb_free += bytes / DEV_BSIZE;
2660 	if (jblocks->jb_suspended)
2661 		worklist_speedup(mp);
2662 	wakeup(jblocks);
2663 }
2664 
2665 static void
2666 jblocks_destroy(jblocks)
2667 	struct jblocks *jblocks;
2668 {
2669 
2670 	if (jblocks->jb_extent)
2671 		free(jblocks->jb_extent, M_JBLOCKS);
2672 	free(jblocks, M_JBLOCKS);
2673 }
2674 
2675 static void
2676 jblocks_add(jblocks, daddr, blocks)
2677 	struct jblocks *jblocks;
2678 	ufs2_daddr_t daddr;
2679 	int blocks;
2680 {
2681 	struct jextent *jext;
2682 
2683 	jblocks->jb_blocks += blocks;
2684 	jblocks->jb_free += blocks;
2685 	jext = &jblocks->jb_extent[jblocks->jb_used];
2686 	/* Adding the first block. */
2687 	if (jext->je_daddr == 0) {
2688 		jext->je_daddr = daddr;
2689 		jext->je_blocks = blocks;
2690 		return;
2691 	}
2692 	/* Extending the last extent. */
2693 	if (jext->je_daddr + jext->je_blocks == daddr) {
2694 		jext->je_blocks += blocks;
2695 		return;
2696 	}
2697 	/* Adding a new extent. */
2698 	if (++jblocks->jb_used == jblocks->jb_avail) {
2699 		jblocks->jb_avail *= 2;
2700 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2701 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2702 		memcpy(jext, jblocks->jb_extent,
2703 		    sizeof(struct jextent) * jblocks->jb_used);
2704 		free(jblocks->jb_extent, M_JBLOCKS);
2705 		jblocks->jb_extent = jext;
2706 	}
2707 	jext = &jblocks->jb_extent[jblocks->jb_used];
2708 	jext->je_daddr = daddr;
2709 	jext->je_blocks = blocks;
2710 	return;
2711 }
2712 
2713 int
2714 softdep_journal_lookup(mp, vpp)
2715 	struct mount *mp;
2716 	struct vnode **vpp;
2717 {
2718 	struct componentname cnp;
2719 	struct vnode *dvp;
2720 	ino_t sujournal;
2721 	int error;
2722 
2723 	error = VFS_VGET(mp, ROOTINO, LK_EXCLUSIVE, &dvp);
2724 	if (error)
2725 		return (error);
2726 	bzero(&cnp, sizeof(cnp));
2727 	cnp.cn_nameiop = LOOKUP;
2728 	cnp.cn_flags = ISLASTCN;
2729 	cnp.cn_thread = curthread;
2730 	cnp.cn_cred = curthread->td_ucred;
2731 	cnp.cn_pnbuf = SUJ_FILE;
2732 	cnp.cn_nameptr = SUJ_FILE;
2733 	cnp.cn_namelen = strlen(SUJ_FILE);
2734 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2735 	vput(dvp);
2736 	if (error != 0)
2737 		return (error);
2738 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2739 	return (error);
2740 }
2741 
2742 /*
2743  * Open and verify the journal file.
2744  */
2745 static int
2746 journal_mount(mp, fs, cred)
2747 	struct mount *mp;
2748 	struct fs *fs;
2749 	struct ucred *cred;
2750 {
2751 	struct jblocks *jblocks;
2752 	struct ufsmount *ump;
2753 	struct vnode *vp;
2754 	struct inode *ip;
2755 	ufs2_daddr_t blkno;
2756 	int bcount;
2757 	int error;
2758 	int i;
2759 
2760 	ump = VFSTOUFS(mp);
2761 	ump->softdep_journal_tail = NULL;
2762 	ump->softdep_on_journal = 0;
2763 	ump->softdep_accdeps = 0;
2764 	ump->softdep_req = 0;
2765 	ump->softdep_jblocks = NULL;
2766 	error = softdep_journal_lookup(mp, &vp);
2767 	if (error != 0) {
2768 		printf("Failed to find journal.  Use tunefs to create one\n");
2769 		return (error);
2770 	}
2771 	ip = VTOI(vp);
2772 	if (ip->i_size < SUJ_MIN) {
2773 		error = ENOSPC;
2774 		goto out;
2775 	}
2776 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
2777 	jblocks = jblocks_create();
2778 	for (i = 0; i < bcount; i++) {
2779 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
2780 		if (error)
2781 			break;
2782 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
2783 	}
2784 	if (error) {
2785 		jblocks_destroy(jblocks);
2786 		goto out;
2787 	}
2788 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
2789 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
2790 	ump->softdep_jblocks = jblocks;
2791 out:
2792 	if (error == 0) {
2793 		MNT_ILOCK(mp);
2794 		mp->mnt_flag |= MNT_SUJ;
2795 		mp->mnt_flag &= ~MNT_SOFTDEP;
2796 		MNT_IUNLOCK(mp);
2797 		/*
2798 		 * Only validate the journal contents if the
2799 		 * filesystem is clean, otherwise we write the logs
2800 		 * but they'll never be used.  If the filesystem was
2801 		 * still dirty when we mounted it the journal is
2802 		 * invalid and a new journal can only be valid if it
2803 		 * starts from a clean mount.
2804 		 */
2805 		if (fs->fs_clean) {
2806 			DIP_SET(ip, i_modrev, fs->fs_mtime);
2807 			ip->i_flags |= IN_MODIFIED;
2808 			ffs_update(vp, 1);
2809 		}
2810 	}
2811 	vput(vp);
2812 	return (error);
2813 }
2814 
2815 static void
2816 journal_unmount(ump)
2817 	struct ufsmount *ump;
2818 {
2819 
2820 	if (ump->softdep_jblocks)
2821 		jblocks_destroy(ump->softdep_jblocks);
2822 	ump->softdep_jblocks = NULL;
2823 }
2824 
2825 /*
2826  * Called when a journal record is ready to be written.  Space is allocated
2827  * and the journal entry is created when the journal is flushed to stable
2828  * store.
2829  */
2830 static void
2831 add_to_journal(wk)
2832 	struct worklist *wk;
2833 {
2834 	struct ufsmount *ump;
2835 
2836 	ump = VFSTOUFS(wk->wk_mp);
2837 	LOCK_OWNED(ump);
2838 	if (wk->wk_state & ONWORKLIST)
2839 		panic("add_to_journal: %s(0x%X) already on list",
2840 		    TYPENAME(wk->wk_type), wk->wk_state);
2841 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
2842 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
2843 		ump->softdep_jblocks->jb_age = ticks;
2844 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
2845 	} else
2846 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
2847 	ump->softdep_journal_tail = wk;
2848 	ump->softdep_on_journal += 1;
2849 }
2850 
2851 /*
2852  * Remove an arbitrary item for the journal worklist maintain the tail
2853  * pointer.  This happens when a new operation obviates the need to
2854  * journal an old operation.
2855  */
2856 static void
2857 remove_from_journal(wk)
2858 	struct worklist *wk;
2859 {
2860 	struct ufsmount *ump;
2861 
2862 	ump = VFSTOUFS(wk->wk_mp);
2863 	LOCK_OWNED(ump);
2864 #ifdef SUJ_DEBUG
2865 	{
2866 		struct worklist *wkn;
2867 
2868 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
2869 			if (wkn == wk)
2870 				break;
2871 		if (wkn == NULL)
2872 			panic("remove_from_journal: %p is not in journal", wk);
2873 	}
2874 #endif
2875 	/*
2876 	 * We emulate a TAILQ to save space in most structures which do not
2877 	 * require TAILQ semantics.  Here we must update the tail position
2878 	 * when removing the tail which is not the final entry. This works
2879 	 * only if the worklist linkage are at the beginning of the structure.
2880 	 */
2881 	if (ump->softdep_journal_tail == wk)
2882 		ump->softdep_journal_tail =
2883 		    (struct worklist *)wk->wk_list.le_prev;
2884 
2885 	WORKLIST_REMOVE(wk);
2886 	ump->softdep_on_journal -= 1;
2887 }
2888 
2889 /*
2890  * Check for journal space as well as dependency limits so the prelink
2891  * code can throttle both journaled and non-journaled filesystems.
2892  * Threshold is 0 for low and 1 for min.
2893  */
2894 static int
2895 journal_space(ump, thresh)
2896 	struct ufsmount *ump;
2897 	int thresh;
2898 {
2899 	struct jblocks *jblocks;
2900 	int limit, avail;
2901 
2902 	jblocks = ump->softdep_jblocks;
2903 	if (jblocks == NULL)
2904 		return (1);
2905 	/*
2906 	 * We use a tighter restriction here to prevent request_cleanup()
2907 	 * running in threads from running into locks we currently hold.
2908 	 * We have to be over the limit and our filesystem has to be
2909 	 * responsible for more than our share of that usage.
2910 	 */
2911 	limit = (max_softdeps / 10) * 9;
2912 	if (dep_current[D_INODEDEP] > limit &&
2913 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
2914 		return (0);
2915 	if (thresh)
2916 		thresh = jblocks->jb_min;
2917 	else
2918 		thresh = jblocks->jb_low;
2919 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
2920 	avail = jblocks->jb_free - avail;
2921 
2922 	return (avail > thresh);
2923 }
2924 
2925 static void
2926 journal_suspend(ump)
2927 	struct ufsmount *ump;
2928 {
2929 	struct jblocks *jblocks;
2930 	struct mount *mp;
2931 
2932 	mp = UFSTOVFS(ump);
2933 	jblocks = ump->softdep_jblocks;
2934 	MNT_ILOCK(mp);
2935 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
2936 		stat_journal_min++;
2937 		mp->mnt_kern_flag |= MNTK_SUSPEND;
2938 		mp->mnt_susp_owner = ump->softdep_flushtd;
2939 	}
2940 	jblocks->jb_suspended = 1;
2941 	MNT_IUNLOCK(mp);
2942 }
2943 
2944 static int
2945 journal_unsuspend(struct ufsmount *ump)
2946 {
2947 	struct jblocks *jblocks;
2948 	struct mount *mp;
2949 
2950 	mp = UFSTOVFS(ump);
2951 	jblocks = ump->softdep_jblocks;
2952 
2953 	if (jblocks != NULL && jblocks->jb_suspended &&
2954 	    journal_space(ump, jblocks->jb_min)) {
2955 		jblocks->jb_suspended = 0;
2956 		FREE_LOCK(ump);
2957 		mp->mnt_susp_owner = curthread;
2958 		vfs_write_resume(mp, 0);
2959 		ACQUIRE_LOCK(ump);
2960 		return (1);
2961 	}
2962 	return (0);
2963 }
2964 
2965 /*
2966  * Called before any allocation function to be certain that there is
2967  * sufficient space in the journal prior to creating any new records.
2968  * Since in the case of block allocation we may have multiple locked
2969  * buffers at the time of the actual allocation we can not block
2970  * when the journal records are created.  Doing so would create a deadlock
2971  * if any of these buffers needed to be flushed to reclaim space.  Instead
2972  * we require a sufficiently large amount of available space such that
2973  * each thread in the system could have passed this allocation check and
2974  * still have sufficient free space.  With 20% of a minimum journal size
2975  * of 1MB we have 6553 records available.
2976  */
2977 int
2978 softdep_prealloc(vp, waitok)
2979 	struct vnode *vp;
2980 	int waitok;
2981 {
2982 	struct ufsmount *ump;
2983 
2984 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
2985 	    ("softdep_prealloc called on non-softdep filesystem"));
2986 	/*
2987 	 * Nothing to do if we are not running journaled soft updates.
2988 	 * If we currently hold the snapshot lock, we must avoid handling
2989 	 * other resources that could cause deadlock.
2990 	 */
2991 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)))
2992 		return (0);
2993 	ump = VFSTOUFS(vp->v_mount);
2994 	ACQUIRE_LOCK(ump);
2995 	if (journal_space(ump, 0)) {
2996 		FREE_LOCK(ump);
2997 		return (0);
2998 	}
2999 	stat_journal_low++;
3000 	FREE_LOCK(ump);
3001 	if (waitok == MNT_NOWAIT)
3002 		return (ENOSPC);
3003 	/*
3004 	 * Attempt to sync this vnode once to flush any journal
3005 	 * work attached to it.
3006 	 */
3007 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3008 		ffs_syncvnode(vp, waitok, 0);
3009 	ACQUIRE_LOCK(ump);
3010 	process_removes(vp);
3011 	process_truncates(vp);
3012 	if (journal_space(ump, 0) == 0) {
3013 		softdep_speedup(ump);
3014 		if (journal_space(ump, 1) == 0)
3015 			journal_suspend(ump);
3016 	}
3017 	FREE_LOCK(ump);
3018 
3019 	return (0);
3020 }
3021 
3022 /*
3023  * Before adjusting a link count on a vnode verify that we have sufficient
3024  * journal space.  If not, process operations that depend on the currently
3025  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3026  * and softdep flush threads can not acquire these locks to reclaim space.
3027  */
3028 static void
3029 softdep_prelink(dvp, vp)
3030 	struct vnode *dvp;
3031 	struct vnode *vp;
3032 {
3033 	struct ufsmount *ump;
3034 
3035 	ump = VFSTOUFS(dvp->v_mount);
3036 	LOCK_OWNED(ump);
3037 	/*
3038 	 * Nothing to do if we have sufficient journal space.
3039 	 * If we currently hold the snapshot lock, we must avoid
3040 	 * handling other resources that could cause deadlock.
3041 	 */
3042 	if (journal_space(ump, 0) || (vp && IS_SNAPSHOT(VTOI(vp))))
3043 		return;
3044 	stat_journal_low++;
3045 	FREE_LOCK(ump);
3046 	if (vp)
3047 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3048 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3049 	ACQUIRE_LOCK(ump);
3050 	/* Process vp before dvp as it may create .. removes. */
3051 	if (vp) {
3052 		process_removes(vp);
3053 		process_truncates(vp);
3054 	}
3055 	process_removes(dvp);
3056 	process_truncates(dvp);
3057 	softdep_speedup(ump);
3058 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3059 	if (journal_space(ump, 0) == 0) {
3060 		softdep_speedup(ump);
3061 		if (journal_space(ump, 1) == 0)
3062 			journal_suspend(ump);
3063 	}
3064 }
3065 
3066 static void
3067 jseg_write(ump, jseg, data)
3068 	struct ufsmount *ump;
3069 	struct jseg *jseg;
3070 	uint8_t *data;
3071 {
3072 	struct jsegrec *rec;
3073 
3074 	rec = (struct jsegrec *)data;
3075 	rec->jsr_seq = jseg->js_seq;
3076 	rec->jsr_oldest = jseg->js_oldseq;
3077 	rec->jsr_cnt = jseg->js_cnt;
3078 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3079 	rec->jsr_crc = 0;
3080 	rec->jsr_time = ump->um_fs->fs_mtime;
3081 }
3082 
3083 static inline void
3084 inoref_write(inoref, jseg, rec)
3085 	struct inoref *inoref;
3086 	struct jseg *jseg;
3087 	struct jrefrec *rec;
3088 {
3089 
3090 	inoref->if_jsegdep->jd_seg = jseg;
3091 	rec->jr_ino = inoref->if_ino;
3092 	rec->jr_parent = inoref->if_parent;
3093 	rec->jr_nlink = inoref->if_nlink;
3094 	rec->jr_mode = inoref->if_mode;
3095 	rec->jr_diroff = inoref->if_diroff;
3096 }
3097 
3098 static void
3099 jaddref_write(jaddref, jseg, data)
3100 	struct jaddref *jaddref;
3101 	struct jseg *jseg;
3102 	uint8_t *data;
3103 {
3104 	struct jrefrec *rec;
3105 
3106 	rec = (struct jrefrec *)data;
3107 	rec->jr_op = JOP_ADDREF;
3108 	inoref_write(&jaddref->ja_ref, jseg, rec);
3109 }
3110 
3111 static void
3112 jremref_write(jremref, jseg, data)
3113 	struct jremref *jremref;
3114 	struct jseg *jseg;
3115 	uint8_t *data;
3116 {
3117 	struct jrefrec *rec;
3118 
3119 	rec = (struct jrefrec *)data;
3120 	rec->jr_op = JOP_REMREF;
3121 	inoref_write(&jremref->jr_ref, jseg, rec);
3122 }
3123 
3124 static void
3125 jmvref_write(jmvref, jseg, data)
3126 	struct jmvref *jmvref;
3127 	struct jseg *jseg;
3128 	uint8_t *data;
3129 {
3130 	struct jmvrec *rec;
3131 
3132 	rec = (struct jmvrec *)data;
3133 	rec->jm_op = JOP_MVREF;
3134 	rec->jm_ino = jmvref->jm_ino;
3135 	rec->jm_parent = jmvref->jm_parent;
3136 	rec->jm_oldoff = jmvref->jm_oldoff;
3137 	rec->jm_newoff = jmvref->jm_newoff;
3138 }
3139 
3140 static void
3141 jnewblk_write(jnewblk, jseg, data)
3142 	struct jnewblk *jnewblk;
3143 	struct jseg *jseg;
3144 	uint8_t *data;
3145 {
3146 	struct jblkrec *rec;
3147 
3148 	jnewblk->jn_jsegdep->jd_seg = jseg;
3149 	rec = (struct jblkrec *)data;
3150 	rec->jb_op = JOP_NEWBLK;
3151 	rec->jb_ino = jnewblk->jn_ino;
3152 	rec->jb_blkno = jnewblk->jn_blkno;
3153 	rec->jb_lbn = jnewblk->jn_lbn;
3154 	rec->jb_frags = jnewblk->jn_frags;
3155 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3156 }
3157 
3158 static void
3159 jfreeblk_write(jfreeblk, jseg, data)
3160 	struct jfreeblk *jfreeblk;
3161 	struct jseg *jseg;
3162 	uint8_t *data;
3163 {
3164 	struct jblkrec *rec;
3165 
3166 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3167 	rec = (struct jblkrec *)data;
3168 	rec->jb_op = JOP_FREEBLK;
3169 	rec->jb_ino = jfreeblk->jf_ino;
3170 	rec->jb_blkno = jfreeblk->jf_blkno;
3171 	rec->jb_lbn = jfreeblk->jf_lbn;
3172 	rec->jb_frags = jfreeblk->jf_frags;
3173 	rec->jb_oldfrags = 0;
3174 }
3175 
3176 static void
3177 jfreefrag_write(jfreefrag, jseg, data)
3178 	struct jfreefrag *jfreefrag;
3179 	struct jseg *jseg;
3180 	uint8_t *data;
3181 {
3182 	struct jblkrec *rec;
3183 
3184 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3185 	rec = (struct jblkrec *)data;
3186 	rec->jb_op = JOP_FREEBLK;
3187 	rec->jb_ino = jfreefrag->fr_ino;
3188 	rec->jb_blkno = jfreefrag->fr_blkno;
3189 	rec->jb_lbn = jfreefrag->fr_lbn;
3190 	rec->jb_frags = jfreefrag->fr_frags;
3191 	rec->jb_oldfrags = 0;
3192 }
3193 
3194 static void
3195 jtrunc_write(jtrunc, jseg, data)
3196 	struct jtrunc *jtrunc;
3197 	struct jseg *jseg;
3198 	uint8_t *data;
3199 {
3200 	struct jtrncrec *rec;
3201 
3202 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3203 	rec = (struct jtrncrec *)data;
3204 	rec->jt_op = JOP_TRUNC;
3205 	rec->jt_ino = jtrunc->jt_ino;
3206 	rec->jt_size = jtrunc->jt_size;
3207 	rec->jt_extsize = jtrunc->jt_extsize;
3208 }
3209 
3210 static void
3211 jfsync_write(jfsync, jseg, data)
3212 	struct jfsync *jfsync;
3213 	struct jseg *jseg;
3214 	uint8_t *data;
3215 {
3216 	struct jtrncrec *rec;
3217 
3218 	rec = (struct jtrncrec *)data;
3219 	rec->jt_op = JOP_SYNC;
3220 	rec->jt_ino = jfsync->jfs_ino;
3221 	rec->jt_size = jfsync->jfs_size;
3222 	rec->jt_extsize = jfsync->jfs_extsize;
3223 }
3224 
3225 static void
3226 softdep_flushjournal(mp)
3227 	struct mount *mp;
3228 {
3229 	struct jblocks *jblocks;
3230 	struct ufsmount *ump;
3231 
3232 	if (MOUNTEDSUJ(mp) == 0)
3233 		return;
3234 	ump = VFSTOUFS(mp);
3235 	jblocks = ump->softdep_jblocks;
3236 	ACQUIRE_LOCK(ump);
3237 	while (ump->softdep_on_journal) {
3238 		jblocks->jb_needseg = 1;
3239 		softdep_process_journal(mp, NULL, MNT_WAIT);
3240 	}
3241 	FREE_LOCK(ump);
3242 }
3243 
3244 static void softdep_synchronize_completed(struct bio *);
3245 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3246 
3247 static void
3248 softdep_synchronize_completed(bp)
3249         struct bio *bp;
3250 {
3251 	struct jseg *oldest;
3252 	struct jseg *jseg;
3253 	struct ufsmount *ump;
3254 
3255 	/*
3256 	 * caller1 marks the last segment written before we issued the
3257 	 * synchronize cache.
3258 	 */
3259 	jseg = bp->bio_caller1;
3260 	if (jseg == NULL) {
3261 		g_destroy_bio(bp);
3262 		return;
3263 	}
3264 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3265 	ACQUIRE_LOCK(ump);
3266 	oldest = NULL;
3267 	/*
3268 	 * Mark all the journal entries waiting on the synchronize cache
3269 	 * as completed so they may continue on.
3270 	 */
3271 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3272 		jseg->js_state |= COMPLETE;
3273 		oldest = jseg;
3274 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3275 	}
3276 	/*
3277 	 * Restart deferred journal entry processing from the oldest
3278 	 * completed jseg.
3279 	 */
3280 	if (oldest)
3281 		complete_jsegs(oldest);
3282 
3283 	FREE_LOCK(ump);
3284 	g_destroy_bio(bp);
3285 }
3286 
3287 /*
3288  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3289  * barriers.  The journal must be written prior to any blocks that depend
3290  * on it and the journal can not be released until the blocks have be
3291  * written.  This code handles both barriers simultaneously.
3292  */
3293 static void
3294 softdep_synchronize(bp, ump, caller1)
3295 	struct bio *bp;
3296 	struct ufsmount *ump;
3297 	void *caller1;
3298 {
3299 
3300 	bp->bio_cmd = BIO_FLUSH;
3301 	bp->bio_flags |= BIO_ORDERED;
3302 	bp->bio_data = NULL;
3303 	bp->bio_offset = ump->um_cp->provider->mediasize;
3304 	bp->bio_length = 0;
3305 	bp->bio_done = softdep_synchronize_completed;
3306 	bp->bio_caller1 = caller1;
3307 	g_io_request(bp,
3308 	    (struct g_consumer *)ump->um_devvp->v_bufobj.bo_private);
3309 }
3310 
3311 /*
3312  * Flush some journal records to disk.
3313  */
3314 static void
3315 softdep_process_journal(mp, needwk, flags)
3316 	struct mount *mp;
3317 	struct worklist *needwk;
3318 	int flags;
3319 {
3320 	struct jblocks *jblocks;
3321 	struct ufsmount *ump;
3322 	struct worklist *wk;
3323 	struct jseg *jseg;
3324 	struct buf *bp;
3325 	struct bio *bio;
3326 	uint8_t *data;
3327 	struct fs *fs;
3328 	int shouldflush;
3329 	int segwritten;
3330 	int jrecmin;	/* Minimum records per block. */
3331 	int jrecmax;	/* Maximum records per block. */
3332 	int size;
3333 	int cnt;
3334 	int off;
3335 	int devbsize;
3336 
3337 	if (MOUNTEDSUJ(mp) == 0)
3338 		return;
3339 	shouldflush = softdep_flushcache;
3340 	bio = NULL;
3341 	jseg = NULL;
3342 	ump = VFSTOUFS(mp);
3343 	LOCK_OWNED(ump);
3344 	fs = ump->um_fs;
3345 	jblocks = ump->softdep_jblocks;
3346 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3347 	/*
3348 	 * We write anywhere between a disk block and fs block.  The upper
3349 	 * bound is picked to prevent buffer cache fragmentation and limit
3350 	 * processing time per I/O.
3351 	 */
3352 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3353 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3354 	segwritten = 0;
3355 	for (;;) {
3356 		cnt = ump->softdep_on_journal;
3357 		/*
3358 		 * Criteria for writing a segment:
3359 		 * 1) We have a full block.
3360 		 * 2) We're called from jwait() and haven't found the
3361 		 *    journal item yet.
3362 		 * 3) Always write if needseg is set.
3363 		 * 4) If we are called from process_worklist and have
3364 		 *    not yet written anything we write a partial block
3365 		 *    to enforce a 1 second maximum latency on journal
3366 		 *    entries.
3367 		 */
3368 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3369 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3370 			break;
3371 		cnt++;
3372 		/*
3373 		 * Verify some free journal space.  softdep_prealloc() should
3374 		 * guarantee that we don't run out so this is indicative of
3375 		 * a problem with the flow control.  Try to recover
3376 		 * gracefully in any event.
3377 		 */
3378 		while (jblocks->jb_free == 0) {
3379 			if (flags != MNT_WAIT)
3380 				break;
3381 			printf("softdep: Out of journal space!\n");
3382 			softdep_speedup(ump);
3383 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3384 		}
3385 		FREE_LOCK(ump);
3386 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3387 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3388 		LIST_INIT(&jseg->js_entries);
3389 		LIST_INIT(&jseg->js_indirs);
3390 		jseg->js_state = ATTACHED;
3391 		if (shouldflush == 0)
3392 			jseg->js_state |= COMPLETE;
3393 		else if (bio == NULL)
3394 			bio = g_alloc_bio();
3395 		jseg->js_jblocks = jblocks;
3396 		bp = geteblk(fs->fs_bsize, 0);
3397 		ACQUIRE_LOCK(ump);
3398 		/*
3399 		 * If there was a race while we were allocating the block
3400 		 * and jseg the entry we care about was likely written.
3401 		 * We bail out in both the WAIT and NOWAIT case and assume
3402 		 * the caller will loop if the entry it cares about is
3403 		 * not written.
3404 		 */
3405 		cnt = ump->softdep_on_journal;
3406 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3407 			bp->b_flags |= B_INVAL | B_NOCACHE;
3408 			WORKITEM_FREE(jseg, D_JSEG);
3409 			FREE_LOCK(ump);
3410 			brelse(bp);
3411 			ACQUIRE_LOCK(ump);
3412 			break;
3413 		}
3414 		/*
3415 		 * Calculate the disk block size required for the available
3416 		 * records rounded to the min size.
3417 		 */
3418 		if (cnt == 0)
3419 			size = devbsize;
3420 		else if (cnt < jrecmax)
3421 			size = howmany(cnt, jrecmin) * devbsize;
3422 		else
3423 			size = fs->fs_bsize;
3424 		/*
3425 		 * Allocate a disk block for this journal data and account
3426 		 * for truncation of the requested size if enough contiguous
3427 		 * space was not available.
3428 		 */
3429 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3430 		bp->b_lblkno = bp->b_blkno;
3431 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3432 		bp->b_bcount = size;
3433 		bp->b_flags &= ~B_INVAL;
3434 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3435 		/*
3436 		 * Initialize our jseg with cnt records.  Assign the next
3437 		 * sequence number to it and link it in-order.
3438 		 */
3439 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3440 		jseg->js_buf = bp;
3441 		jseg->js_cnt = cnt;
3442 		jseg->js_refs = cnt + 1;	/* Self ref. */
3443 		jseg->js_size = size;
3444 		jseg->js_seq = jblocks->jb_nextseq++;
3445 		if (jblocks->jb_oldestseg == NULL)
3446 			jblocks->jb_oldestseg = jseg;
3447 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3448 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3449 		if (jblocks->jb_writeseg == NULL)
3450 			jblocks->jb_writeseg = jseg;
3451 		/*
3452 		 * Start filling in records from the pending list.
3453 		 */
3454 		data = bp->b_data;
3455 		off = 0;
3456 
3457 		/*
3458 		 * Always put a header on the first block.
3459 		 * XXX As with below, there might not be a chance to get
3460 		 * into the loop.  Ensure that something valid is written.
3461 		 */
3462 		jseg_write(ump, jseg, data);
3463 		off += JREC_SIZE;
3464 		data = bp->b_data + off;
3465 
3466 		/*
3467 		 * XXX Something is wrong here.  There's no work to do,
3468 		 * but we need to perform and I/O and allow it to complete
3469 		 * anyways.
3470 		 */
3471 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3472 			stat_emptyjblocks++;
3473 
3474 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3475 		    != NULL) {
3476 			if (cnt == 0)
3477 				break;
3478 			/* Place a segment header on every device block. */
3479 			if ((off % devbsize) == 0) {
3480 				jseg_write(ump, jseg, data);
3481 				off += JREC_SIZE;
3482 				data = bp->b_data + off;
3483 			}
3484 			if (wk == needwk)
3485 				needwk = NULL;
3486 			remove_from_journal(wk);
3487 			wk->wk_state |= INPROGRESS;
3488 			WORKLIST_INSERT(&jseg->js_entries, wk);
3489 			switch (wk->wk_type) {
3490 			case D_JADDREF:
3491 				jaddref_write(WK_JADDREF(wk), jseg, data);
3492 				break;
3493 			case D_JREMREF:
3494 				jremref_write(WK_JREMREF(wk), jseg, data);
3495 				break;
3496 			case D_JMVREF:
3497 				jmvref_write(WK_JMVREF(wk), jseg, data);
3498 				break;
3499 			case D_JNEWBLK:
3500 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3501 				break;
3502 			case D_JFREEBLK:
3503 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3504 				break;
3505 			case D_JFREEFRAG:
3506 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3507 				break;
3508 			case D_JTRUNC:
3509 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3510 				break;
3511 			case D_JFSYNC:
3512 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3513 				break;
3514 			default:
3515 				panic("process_journal: Unknown type %s",
3516 				    TYPENAME(wk->wk_type));
3517 				/* NOTREACHED */
3518 			}
3519 			off += JREC_SIZE;
3520 			data = bp->b_data + off;
3521 			cnt--;
3522 		}
3523 
3524 		/* Clear any remaining space so we don't leak kernel data */
3525 		if (size > off)
3526 			bzero(data, size - off);
3527 
3528 		/*
3529 		 * Write this one buffer and continue.
3530 		 */
3531 		segwritten = 1;
3532 		jblocks->jb_needseg = 0;
3533 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3534 		FREE_LOCK(ump);
3535 		pbgetvp(ump->um_devvp, bp);
3536 		/*
3537 		 * We only do the blocking wait once we find the journal
3538 		 * entry we're looking for.
3539 		 */
3540 		if (needwk == NULL && flags == MNT_WAIT)
3541 			bwrite(bp);
3542 		else
3543 			bawrite(bp);
3544 		ACQUIRE_LOCK(ump);
3545 	}
3546 	/*
3547 	 * If we wrote a segment issue a synchronize cache so the journal
3548 	 * is reflected on disk before the data is written.  Since reclaiming
3549 	 * journal space also requires writing a journal record this
3550 	 * process also enforces a barrier before reclamation.
3551 	 */
3552 	if (segwritten && shouldflush) {
3553 		softdep_synchronize(bio, ump,
3554 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3555 	} else if (bio)
3556 		g_destroy_bio(bio);
3557 	/*
3558 	 * If we've suspended the filesystem because we ran out of journal
3559 	 * space either try to sync it here to make some progress or
3560 	 * unsuspend it if we already have.
3561 	 */
3562 	if (flags == 0 && jblocks->jb_suspended) {
3563 		if (journal_unsuspend(ump))
3564 			return;
3565 		FREE_LOCK(ump);
3566 		VFS_SYNC(mp, MNT_NOWAIT);
3567 		ffs_sbupdate(ump, MNT_WAIT, 0);
3568 		ACQUIRE_LOCK(ump);
3569 	}
3570 }
3571 
3572 /*
3573  * Complete a jseg, allowing all dependencies awaiting journal writes
3574  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3575  * structures so that the journal segment can be freed to reclaim space.
3576  */
3577 static void
3578 complete_jseg(jseg)
3579 	struct jseg *jseg;
3580 {
3581 	struct worklist *wk;
3582 	struct jmvref *jmvref;
3583 	int waiting;
3584 #ifdef INVARIANTS
3585 	int i = 0;
3586 #endif
3587 
3588 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3589 		WORKLIST_REMOVE(wk);
3590 		waiting = wk->wk_state & IOWAITING;
3591 		wk->wk_state &= ~(INPROGRESS | IOWAITING);
3592 		wk->wk_state |= COMPLETE;
3593 		KASSERT(i++ < jseg->js_cnt,
3594 		    ("handle_written_jseg: overflow %d >= %d",
3595 		    i - 1, jseg->js_cnt));
3596 		switch (wk->wk_type) {
3597 		case D_JADDREF:
3598 			handle_written_jaddref(WK_JADDREF(wk));
3599 			break;
3600 		case D_JREMREF:
3601 			handle_written_jremref(WK_JREMREF(wk));
3602 			break;
3603 		case D_JMVREF:
3604 			rele_jseg(jseg);	/* No jsegdep. */
3605 			jmvref = WK_JMVREF(wk);
3606 			LIST_REMOVE(jmvref, jm_deps);
3607 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
3608 				free_pagedep(jmvref->jm_pagedep);
3609 			WORKITEM_FREE(jmvref, D_JMVREF);
3610 			break;
3611 		case D_JNEWBLK:
3612 			handle_written_jnewblk(WK_JNEWBLK(wk));
3613 			break;
3614 		case D_JFREEBLK:
3615 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
3616 			break;
3617 		case D_JTRUNC:
3618 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
3619 			break;
3620 		case D_JFSYNC:
3621 			rele_jseg(jseg);	/* No jsegdep. */
3622 			WORKITEM_FREE(wk, D_JFSYNC);
3623 			break;
3624 		case D_JFREEFRAG:
3625 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
3626 			break;
3627 		default:
3628 			panic("handle_written_jseg: Unknown type %s",
3629 			    TYPENAME(wk->wk_type));
3630 			/* NOTREACHED */
3631 		}
3632 		if (waiting)
3633 			wakeup(wk);
3634 	}
3635 	/* Release the self reference so the structure may be freed. */
3636 	rele_jseg(jseg);
3637 }
3638 
3639 /*
3640  * Determine which jsegs are ready for completion processing.  Waits for
3641  * synchronize cache to complete as well as forcing in-order completion
3642  * of journal entries.
3643  */
3644 static void
3645 complete_jsegs(jseg)
3646 	struct jseg *jseg;
3647 {
3648 	struct jblocks *jblocks;
3649 	struct jseg *jsegn;
3650 
3651 	jblocks = jseg->js_jblocks;
3652 	/*
3653 	 * Don't allow out of order completions.  If this isn't the first
3654 	 * block wait for it to write before we're done.
3655 	 */
3656 	if (jseg != jblocks->jb_writeseg)
3657 		return;
3658 	/* Iterate through available jsegs processing their entries. */
3659 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
3660 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
3661 		jsegn = TAILQ_NEXT(jseg, js_next);
3662 		complete_jseg(jseg);
3663 		jseg = jsegn;
3664 	}
3665 	jblocks->jb_writeseg = jseg;
3666 	/*
3667 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
3668 	 */
3669 	free_jsegs(jblocks);
3670 }
3671 
3672 /*
3673  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
3674  * the final completions.
3675  */
3676 static void
3677 handle_written_jseg(jseg, bp)
3678 	struct jseg *jseg;
3679 	struct buf *bp;
3680 {
3681 
3682 	if (jseg->js_refs == 0)
3683 		panic("handle_written_jseg: No self-reference on %p", jseg);
3684 	jseg->js_state |= DEPCOMPLETE;
3685 	/*
3686 	 * We'll never need this buffer again, set flags so it will be
3687 	 * discarded.
3688 	 */
3689 	bp->b_flags |= B_INVAL | B_NOCACHE;
3690 	pbrelvp(bp);
3691 	complete_jsegs(jseg);
3692 }
3693 
3694 static inline struct jsegdep *
3695 inoref_jseg(inoref)
3696 	struct inoref *inoref;
3697 {
3698 	struct jsegdep *jsegdep;
3699 
3700 	jsegdep = inoref->if_jsegdep;
3701 	inoref->if_jsegdep = NULL;
3702 
3703 	return (jsegdep);
3704 }
3705 
3706 /*
3707  * Called once a jremref has made it to stable store.  The jremref is marked
3708  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
3709  * for the jremref to complete will be awoken by free_jremref.
3710  */
3711 static void
3712 handle_written_jremref(jremref)
3713 	struct jremref *jremref;
3714 {
3715 	struct inodedep *inodedep;
3716 	struct jsegdep *jsegdep;
3717 	struct dirrem *dirrem;
3718 
3719 	/* Grab the jsegdep. */
3720 	jsegdep = inoref_jseg(&jremref->jr_ref);
3721 	/*
3722 	 * Remove us from the inoref list.
3723 	 */
3724 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
3725 	    0, &inodedep) == 0)
3726 		panic("handle_written_jremref: Lost inodedep");
3727 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
3728 	/*
3729 	 * Complete the dirrem.
3730 	 */
3731 	dirrem = jremref->jr_dirrem;
3732 	jremref->jr_dirrem = NULL;
3733 	LIST_REMOVE(jremref, jr_deps);
3734 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
3735 	jwork_insert(&dirrem->dm_jwork, jsegdep);
3736 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
3737 	    (dirrem->dm_state & COMPLETE) != 0)
3738 		add_to_worklist(&dirrem->dm_list, 0);
3739 	free_jremref(jremref);
3740 }
3741 
3742 /*
3743  * Called once a jaddref has made it to stable store.  The dependency is
3744  * marked complete and any dependent structures are added to the inode
3745  * bufwait list to be completed as soon as it is written.  If a bitmap write
3746  * depends on this entry we move the inode into the inodedephd of the
3747  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
3748  */
3749 static void
3750 handle_written_jaddref(jaddref)
3751 	struct jaddref *jaddref;
3752 {
3753 	struct jsegdep *jsegdep;
3754 	struct inodedep *inodedep;
3755 	struct diradd *diradd;
3756 	struct mkdir *mkdir;
3757 
3758 	/* Grab the jsegdep. */
3759 	jsegdep = inoref_jseg(&jaddref->ja_ref);
3760 	mkdir = NULL;
3761 	diradd = NULL;
3762 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
3763 	    0, &inodedep) == 0)
3764 		panic("handle_written_jaddref: Lost inodedep.");
3765 	if (jaddref->ja_diradd == NULL)
3766 		panic("handle_written_jaddref: No dependency");
3767 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
3768 		diradd = jaddref->ja_diradd;
3769 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
3770 	} else if (jaddref->ja_state & MKDIR_PARENT) {
3771 		mkdir = jaddref->ja_mkdir;
3772 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
3773 	} else if (jaddref->ja_state & MKDIR_BODY)
3774 		mkdir = jaddref->ja_mkdir;
3775 	else
3776 		panic("handle_written_jaddref: Unknown dependency %p",
3777 		    jaddref->ja_diradd);
3778 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
3779 	/*
3780 	 * Remove us from the inode list.
3781 	 */
3782 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
3783 	/*
3784 	 * The mkdir may be waiting on the jaddref to clear before freeing.
3785 	 */
3786 	if (mkdir) {
3787 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
3788 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
3789 		    TYPENAME(mkdir->md_list.wk_type)));
3790 		mkdir->md_jaddref = NULL;
3791 		diradd = mkdir->md_diradd;
3792 		mkdir->md_state |= DEPCOMPLETE;
3793 		complete_mkdir(mkdir);
3794 	}
3795 	jwork_insert(&diradd->da_jwork, jsegdep);
3796 	if (jaddref->ja_state & NEWBLOCK) {
3797 		inodedep->id_state |= ONDEPLIST;
3798 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
3799 		    inodedep, id_deps);
3800 	}
3801 	free_jaddref(jaddref);
3802 }
3803 
3804 /*
3805  * Called once a jnewblk journal is written.  The allocdirect or allocindir
3806  * is placed in the bmsafemap to await notification of a written bitmap.  If
3807  * the operation was canceled we add the segdep to the appropriate
3808  * dependency to free the journal space once the canceling operation
3809  * completes.
3810  */
3811 static void
3812 handle_written_jnewblk(jnewblk)
3813 	struct jnewblk *jnewblk;
3814 {
3815 	struct bmsafemap *bmsafemap;
3816 	struct freefrag *freefrag;
3817 	struct freework *freework;
3818 	struct jsegdep *jsegdep;
3819 	struct newblk *newblk;
3820 
3821 	/* Grab the jsegdep. */
3822 	jsegdep = jnewblk->jn_jsegdep;
3823 	jnewblk->jn_jsegdep = NULL;
3824 	if (jnewblk->jn_dep == NULL)
3825 		panic("handle_written_jnewblk: No dependency for the segdep.");
3826 	switch (jnewblk->jn_dep->wk_type) {
3827 	case D_NEWBLK:
3828 	case D_ALLOCDIRECT:
3829 	case D_ALLOCINDIR:
3830 		/*
3831 		 * Add the written block to the bmsafemap so it can
3832 		 * be notified when the bitmap is on disk.
3833 		 */
3834 		newblk = WK_NEWBLK(jnewblk->jn_dep);
3835 		newblk->nb_jnewblk = NULL;
3836 		if ((newblk->nb_state & GOINGAWAY) == 0) {
3837 			bmsafemap = newblk->nb_bmsafemap;
3838 			newblk->nb_state |= ONDEPLIST;
3839 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
3840 			    nb_deps);
3841 		}
3842 		jwork_insert(&newblk->nb_jwork, jsegdep);
3843 		break;
3844 	case D_FREEFRAG:
3845 		/*
3846 		 * A newblock being removed by a freefrag when replaced by
3847 		 * frag extension.
3848 		 */
3849 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
3850 		freefrag->ff_jdep = NULL;
3851 		jwork_insert(&freefrag->ff_jwork, jsegdep);
3852 		break;
3853 	case D_FREEWORK:
3854 		/*
3855 		 * A direct block was removed by truncate.
3856 		 */
3857 		freework = WK_FREEWORK(jnewblk->jn_dep);
3858 		freework->fw_jnewblk = NULL;
3859 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
3860 		break;
3861 	default:
3862 		panic("handle_written_jnewblk: Unknown type %d.",
3863 		    jnewblk->jn_dep->wk_type);
3864 	}
3865 	jnewblk->jn_dep = NULL;
3866 	free_jnewblk(jnewblk);
3867 }
3868 
3869 /*
3870  * Cancel a jfreefrag that won't be needed, probably due to colliding with
3871  * an in-flight allocation that has not yet been committed.  Divorce us
3872  * from the freefrag and mark it DEPCOMPLETE so that it may be added
3873  * to the worklist.
3874  */
3875 static void
3876 cancel_jfreefrag(jfreefrag)
3877 	struct jfreefrag *jfreefrag;
3878 {
3879 	struct freefrag *freefrag;
3880 
3881 	if (jfreefrag->fr_jsegdep) {
3882 		free_jsegdep(jfreefrag->fr_jsegdep);
3883 		jfreefrag->fr_jsegdep = NULL;
3884 	}
3885 	freefrag = jfreefrag->fr_freefrag;
3886 	jfreefrag->fr_freefrag = NULL;
3887 	free_jfreefrag(jfreefrag);
3888 	freefrag->ff_state |= DEPCOMPLETE;
3889 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
3890 }
3891 
3892 /*
3893  * Free a jfreefrag when the parent freefrag is rendered obsolete.
3894  */
3895 static void
3896 free_jfreefrag(jfreefrag)
3897 	struct jfreefrag *jfreefrag;
3898 {
3899 
3900 	if (jfreefrag->fr_state & INPROGRESS)
3901 		WORKLIST_REMOVE(&jfreefrag->fr_list);
3902 	else if (jfreefrag->fr_state & ONWORKLIST)
3903 		remove_from_journal(&jfreefrag->fr_list);
3904 	if (jfreefrag->fr_freefrag != NULL)
3905 		panic("free_jfreefrag:  Still attached to a freefrag.");
3906 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
3907 }
3908 
3909 /*
3910  * Called when the journal write for a jfreefrag completes.  The parent
3911  * freefrag is added to the worklist if this completes its dependencies.
3912  */
3913 static void
3914 handle_written_jfreefrag(jfreefrag)
3915 	struct jfreefrag *jfreefrag;
3916 {
3917 	struct jsegdep *jsegdep;
3918 	struct freefrag *freefrag;
3919 
3920 	/* Grab the jsegdep. */
3921 	jsegdep = jfreefrag->fr_jsegdep;
3922 	jfreefrag->fr_jsegdep = NULL;
3923 	freefrag = jfreefrag->fr_freefrag;
3924 	if (freefrag == NULL)
3925 		panic("handle_written_jfreefrag: No freefrag.");
3926 	freefrag->ff_state |= DEPCOMPLETE;
3927 	freefrag->ff_jdep = NULL;
3928 	jwork_insert(&freefrag->ff_jwork, jsegdep);
3929 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
3930 		add_to_worklist(&freefrag->ff_list, 0);
3931 	jfreefrag->fr_freefrag = NULL;
3932 	free_jfreefrag(jfreefrag);
3933 }
3934 
3935 /*
3936  * Called when the journal write for a jfreeblk completes.  The jfreeblk
3937  * is removed from the freeblks list of pending journal writes and the
3938  * jsegdep is moved to the freeblks jwork to be completed when all blocks
3939  * have been reclaimed.
3940  */
3941 static void
3942 handle_written_jblkdep(jblkdep)
3943 	struct jblkdep *jblkdep;
3944 {
3945 	struct freeblks *freeblks;
3946 	struct jsegdep *jsegdep;
3947 
3948 	/* Grab the jsegdep. */
3949 	jsegdep = jblkdep->jb_jsegdep;
3950 	jblkdep->jb_jsegdep = NULL;
3951 	freeblks = jblkdep->jb_freeblks;
3952 	LIST_REMOVE(jblkdep, jb_deps);
3953 	jwork_insert(&freeblks->fb_jwork, jsegdep);
3954 	/*
3955 	 * If the freeblks is all journaled, we can add it to the worklist.
3956 	 */
3957 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
3958 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
3959 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
3960 
3961 	free_jblkdep(jblkdep);
3962 }
3963 
3964 static struct jsegdep *
3965 newjsegdep(struct worklist *wk)
3966 {
3967 	struct jsegdep *jsegdep;
3968 
3969 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
3970 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
3971 	jsegdep->jd_seg = NULL;
3972 
3973 	return (jsegdep);
3974 }
3975 
3976 static struct jmvref *
3977 newjmvref(dp, ino, oldoff, newoff)
3978 	struct inode *dp;
3979 	ino_t ino;
3980 	off_t oldoff;
3981 	off_t newoff;
3982 {
3983 	struct jmvref *jmvref;
3984 
3985 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
3986 	workitem_alloc(&jmvref->jm_list, D_JMVREF, UFSTOVFS(dp->i_ump));
3987 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
3988 	jmvref->jm_parent = dp->i_number;
3989 	jmvref->jm_ino = ino;
3990 	jmvref->jm_oldoff = oldoff;
3991 	jmvref->jm_newoff = newoff;
3992 
3993 	return (jmvref);
3994 }
3995 
3996 /*
3997  * Allocate a new jremref that tracks the removal of ip from dp with the
3998  * directory entry offset of diroff.  Mark the entry as ATTACHED and
3999  * DEPCOMPLETE as we have all the information required for the journal write
4000  * and the directory has already been removed from the buffer.  The caller
4001  * is responsible for linking the jremref into the pagedep and adding it
4002  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4003  * a DOTDOT addition so handle_workitem_remove() can properly assign
4004  * the jsegdep when we're done.
4005  */
4006 static struct jremref *
4007 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4008     off_t diroff, nlink_t nlink)
4009 {
4010 	struct jremref *jremref;
4011 
4012 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4013 	workitem_alloc(&jremref->jr_list, D_JREMREF, UFSTOVFS(dp->i_ump));
4014 	jremref->jr_state = ATTACHED;
4015 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4016 	   nlink, ip->i_mode);
4017 	jremref->jr_dirrem = dirrem;
4018 
4019 	return (jremref);
4020 }
4021 
4022 static inline void
4023 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4024     nlink_t nlink, uint16_t mode)
4025 {
4026 
4027 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4028 	inoref->if_diroff = diroff;
4029 	inoref->if_ino = ino;
4030 	inoref->if_parent = parent;
4031 	inoref->if_nlink = nlink;
4032 	inoref->if_mode = mode;
4033 }
4034 
4035 /*
4036  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4037  * directory offset may not be known until later.  The caller is responsible
4038  * adding the entry to the journal when this information is available.  nlink
4039  * should be the link count prior to the addition and mode is only required
4040  * to have the correct FMT.
4041  */
4042 static struct jaddref *
4043 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4044     uint16_t mode)
4045 {
4046 	struct jaddref *jaddref;
4047 
4048 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4049 	workitem_alloc(&jaddref->ja_list, D_JADDREF, UFSTOVFS(dp->i_ump));
4050 	jaddref->ja_state = ATTACHED;
4051 	jaddref->ja_mkdir = NULL;
4052 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4053 
4054 	return (jaddref);
4055 }
4056 
4057 /*
4058  * Create a new free dependency for a freework.  The caller is responsible
4059  * for adjusting the reference count when it has the lock held.  The freedep
4060  * will track an outstanding bitmap write that will ultimately clear the
4061  * freework to continue.
4062  */
4063 static struct freedep *
4064 newfreedep(struct freework *freework)
4065 {
4066 	struct freedep *freedep;
4067 
4068 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4069 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4070 	freedep->fd_freework = freework;
4071 
4072 	return (freedep);
4073 }
4074 
4075 /*
4076  * Free a freedep structure once the buffer it is linked to is written.  If
4077  * this is the last reference to the freework schedule it for completion.
4078  */
4079 static void
4080 free_freedep(freedep)
4081 	struct freedep *freedep;
4082 {
4083 	struct freework *freework;
4084 
4085 	freework = freedep->fd_freework;
4086 	freework->fw_freeblks->fb_cgwait--;
4087 	if (--freework->fw_ref == 0)
4088 		freework_enqueue(freework);
4089 	WORKITEM_FREE(freedep, D_FREEDEP);
4090 }
4091 
4092 /*
4093  * Allocate a new freework structure that may be a level in an indirect
4094  * when parent is not NULL or a top level block when it is.  The top level
4095  * freework structures are allocated without the per-filesystem lock held
4096  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4097  */
4098 static struct freework *
4099 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4100 	struct ufsmount *ump;
4101 	struct freeblks *freeblks;
4102 	struct freework *parent;
4103 	ufs_lbn_t lbn;
4104 	ufs2_daddr_t nb;
4105 	int frags;
4106 	int off;
4107 	int journal;
4108 {
4109 	struct freework *freework;
4110 
4111 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4112 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4113 	freework->fw_state = ATTACHED;
4114 	freework->fw_jnewblk = NULL;
4115 	freework->fw_freeblks = freeblks;
4116 	freework->fw_parent = parent;
4117 	freework->fw_lbn = lbn;
4118 	freework->fw_blkno = nb;
4119 	freework->fw_frags = frags;
4120 	freework->fw_indir = NULL;
4121 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 || lbn >= -NXADDR)
4122 		? 0 : NINDIR(ump->um_fs) + 1;
4123 	freework->fw_start = freework->fw_off = off;
4124 	if (journal)
4125 		newjfreeblk(freeblks, lbn, nb, frags);
4126 	if (parent == NULL) {
4127 		ACQUIRE_LOCK(ump);
4128 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4129 		freeblks->fb_ref++;
4130 		FREE_LOCK(ump);
4131 	}
4132 
4133 	return (freework);
4134 }
4135 
4136 /*
4137  * Eliminate a jfreeblk for a block that does not need journaling.
4138  */
4139 static void
4140 cancel_jfreeblk(freeblks, blkno)
4141 	struct freeblks *freeblks;
4142 	ufs2_daddr_t blkno;
4143 {
4144 	struct jfreeblk *jfreeblk;
4145 	struct jblkdep *jblkdep;
4146 
4147 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4148 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4149 			continue;
4150 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4151 		if (jfreeblk->jf_blkno == blkno)
4152 			break;
4153 	}
4154 	if (jblkdep == NULL)
4155 		return;
4156 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4157 	free_jsegdep(jblkdep->jb_jsegdep);
4158 	LIST_REMOVE(jblkdep, jb_deps);
4159 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4160 }
4161 
4162 /*
4163  * Allocate a new jfreeblk to journal top level block pointer when truncating
4164  * a file.  The caller must add this to the worklist when the per-filesystem
4165  * lock is held.
4166  */
4167 static struct jfreeblk *
4168 newjfreeblk(freeblks, lbn, blkno, frags)
4169 	struct freeblks *freeblks;
4170 	ufs_lbn_t lbn;
4171 	ufs2_daddr_t blkno;
4172 	int frags;
4173 {
4174 	struct jfreeblk *jfreeblk;
4175 
4176 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4177 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4178 	    freeblks->fb_list.wk_mp);
4179 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4180 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4181 	jfreeblk->jf_ino = freeblks->fb_inum;
4182 	jfreeblk->jf_lbn = lbn;
4183 	jfreeblk->jf_blkno = blkno;
4184 	jfreeblk->jf_frags = frags;
4185 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4186 
4187 	return (jfreeblk);
4188 }
4189 
4190 /*
4191  * The journal is only prepared to handle full-size block numbers, so we
4192  * have to adjust the record to reflect the change to a full-size block.
4193  * For example, suppose we have a block made up of fragments 8-15 and
4194  * want to free its last two fragments. We are given a request that says:
4195  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4196  * where frags are the number of fragments to free and oldfrags are the
4197  * number of fragments to keep. To block align it, we have to change it to
4198  * have a valid full-size blkno, so it becomes:
4199  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4200  */
4201 static void
4202 adjust_newfreework(freeblks, frag_offset)
4203 	struct freeblks *freeblks;
4204 	int frag_offset;
4205 {
4206 	struct jfreeblk *jfreeblk;
4207 
4208 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4209 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4210 	    ("adjust_newfreework: Missing freeblks dependency"));
4211 
4212 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4213 	jfreeblk->jf_blkno -= frag_offset;
4214 	jfreeblk->jf_frags += frag_offset;
4215 }
4216 
4217 /*
4218  * Allocate a new jtrunc to track a partial truncation.
4219  */
4220 static struct jtrunc *
4221 newjtrunc(freeblks, size, extsize)
4222 	struct freeblks *freeblks;
4223 	off_t size;
4224 	int extsize;
4225 {
4226 	struct jtrunc *jtrunc;
4227 
4228 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4229 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4230 	    freeblks->fb_list.wk_mp);
4231 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4232 	jtrunc->jt_dep.jb_freeblks = freeblks;
4233 	jtrunc->jt_ino = freeblks->fb_inum;
4234 	jtrunc->jt_size = size;
4235 	jtrunc->jt_extsize = extsize;
4236 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4237 
4238 	return (jtrunc);
4239 }
4240 
4241 /*
4242  * If we're canceling a new bitmap we have to search for another ref
4243  * to move into the bmsafemap dep.  This might be better expressed
4244  * with another structure.
4245  */
4246 static void
4247 move_newblock_dep(jaddref, inodedep)
4248 	struct jaddref *jaddref;
4249 	struct inodedep *inodedep;
4250 {
4251 	struct inoref *inoref;
4252 	struct jaddref *jaddrefn;
4253 
4254 	jaddrefn = NULL;
4255 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4256 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4257 		if ((jaddref->ja_state & NEWBLOCK) &&
4258 		    inoref->if_list.wk_type == D_JADDREF) {
4259 			jaddrefn = (struct jaddref *)inoref;
4260 			break;
4261 		}
4262 	}
4263 	if (jaddrefn == NULL)
4264 		return;
4265 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4266 	jaddrefn->ja_state |= jaddref->ja_state &
4267 	    (ATTACHED | UNDONE | NEWBLOCK);
4268 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4269 	jaddref->ja_state |= ATTACHED;
4270 	LIST_REMOVE(jaddref, ja_bmdeps);
4271 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4272 	    ja_bmdeps);
4273 }
4274 
4275 /*
4276  * Cancel a jaddref either before it has been written or while it is being
4277  * written.  This happens when a link is removed before the add reaches
4278  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4279  * and inode to prevent the link count or bitmap from reaching the disk
4280  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4281  * required.
4282  *
4283  * Returns 1 if the canceled addref requires journaling of the remove and
4284  * 0 otherwise.
4285  */
4286 static int
4287 cancel_jaddref(jaddref, inodedep, wkhd)
4288 	struct jaddref *jaddref;
4289 	struct inodedep *inodedep;
4290 	struct workhead *wkhd;
4291 {
4292 	struct inoref *inoref;
4293 	struct jsegdep *jsegdep;
4294 	int needsj;
4295 
4296 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4297 	    ("cancel_jaddref: Canceling complete jaddref"));
4298 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4299 		needsj = 1;
4300 	else
4301 		needsj = 0;
4302 	if (inodedep == NULL)
4303 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4304 		    0, &inodedep) == 0)
4305 			panic("cancel_jaddref: Lost inodedep");
4306 	/*
4307 	 * We must adjust the nlink of any reference operation that follows
4308 	 * us so that it is consistent with the in-memory reference.  This
4309 	 * ensures that inode nlink rollbacks always have the correct link.
4310 	 */
4311 	if (needsj == 0) {
4312 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4313 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4314 			if (inoref->if_state & GOINGAWAY)
4315 				break;
4316 			inoref->if_nlink--;
4317 		}
4318 	}
4319 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4320 	if (jaddref->ja_state & NEWBLOCK)
4321 		move_newblock_dep(jaddref, inodedep);
4322 	wake_worklist(&jaddref->ja_list);
4323 	jaddref->ja_mkdir = NULL;
4324 	if (jaddref->ja_state & INPROGRESS) {
4325 		jaddref->ja_state &= ~INPROGRESS;
4326 		WORKLIST_REMOVE(&jaddref->ja_list);
4327 		jwork_insert(wkhd, jsegdep);
4328 	} else {
4329 		free_jsegdep(jsegdep);
4330 		if (jaddref->ja_state & DEPCOMPLETE)
4331 			remove_from_journal(&jaddref->ja_list);
4332 	}
4333 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4334 	/*
4335 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4336 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4337 	 * no longer need this addref attached to the inoreflst and it
4338 	 * will incorrectly adjust nlink if we leave it.
4339 	 */
4340 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4341 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4342 		    if_deps);
4343 		jaddref->ja_state |= COMPLETE;
4344 		free_jaddref(jaddref);
4345 		return (needsj);
4346 	}
4347 	/*
4348 	 * Leave the head of the list for jsegdeps for fast merging.
4349 	 */
4350 	if (LIST_FIRST(wkhd) != NULL) {
4351 		jaddref->ja_state |= ONWORKLIST;
4352 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4353 	} else
4354 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4355 
4356 	return (needsj);
4357 }
4358 
4359 /*
4360  * Attempt to free a jaddref structure when some work completes.  This
4361  * should only succeed once the entry is written and all dependencies have
4362  * been notified.
4363  */
4364 static void
4365 free_jaddref(jaddref)
4366 	struct jaddref *jaddref;
4367 {
4368 
4369 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4370 		return;
4371 	if (jaddref->ja_ref.if_jsegdep)
4372 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4373 		    jaddref, jaddref->ja_state);
4374 	if (jaddref->ja_state & NEWBLOCK)
4375 		LIST_REMOVE(jaddref, ja_bmdeps);
4376 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4377 		panic("free_jaddref: Bad state %p(0x%X)",
4378 		    jaddref, jaddref->ja_state);
4379 	if (jaddref->ja_mkdir != NULL)
4380 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4381 	WORKITEM_FREE(jaddref, D_JADDREF);
4382 }
4383 
4384 /*
4385  * Free a jremref structure once it has been written or discarded.
4386  */
4387 static void
4388 free_jremref(jremref)
4389 	struct jremref *jremref;
4390 {
4391 
4392 	if (jremref->jr_ref.if_jsegdep)
4393 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4394 	if (jremref->jr_state & INPROGRESS)
4395 		panic("free_jremref: IO still pending");
4396 	WORKITEM_FREE(jremref, D_JREMREF);
4397 }
4398 
4399 /*
4400  * Free a jnewblk structure.
4401  */
4402 static void
4403 free_jnewblk(jnewblk)
4404 	struct jnewblk *jnewblk;
4405 {
4406 
4407 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4408 		return;
4409 	LIST_REMOVE(jnewblk, jn_deps);
4410 	if (jnewblk->jn_dep != NULL)
4411 		panic("free_jnewblk: Dependency still attached.");
4412 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4413 }
4414 
4415 /*
4416  * Cancel a jnewblk which has been been made redundant by frag extension.
4417  */
4418 static void
4419 cancel_jnewblk(jnewblk, wkhd)
4420 	struct jnewblk *jnewblk;
4421 	struct workhead *wkhd;
4422 {
4423 	struct jsegdep *jsegdep;
4424 
4425 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4426 	jsegdep = jnewblk->jn_jsegdep;
4427 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4428 		panic("cancel_jnewblk: Invalid state");
4429 	jnewblk->jn_jsegdep  = NULL;
4430 	jnewblk->jn_dep = NULL;
4431 	jnewblk->jn_state |= GOINGAWAY;
4432 	if (jnewblk->jn_state & INPROGRESS) {
4433 		jnewblk->jn_state &= ~INPROGRESS;
4434 		WORKLIST_REMOVE(&jnewblk->jn_list);
4435 		jwork_insert(wkhd, jsegdep);
4436 	} else {
4437 		free_jsegdep(jsegdep);
4438 		remove_from_journal(&jnewblk->jn_list);
4439 	}
4440 	wake_worklist(&jnewblk->jn_list);
4441 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4442 }
4443 
4444 static void
4445 free_jblkdep(jblkdep)
4446 	struct jblkdep *jblkdep;
4447 {
4448 
4449 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4450 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4451 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4452 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4453 	else
4454 		panic("free_jblkdep: Unexpected type %s",
4455 		    TYPENAME(jblkdep->jb_list.wk_type));
4456 }
4457 
4458 /*
4459  * Free a single jseg once it is no longer referenced in memory or on
4460  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4461  * to disappear.
4462  */
4463 static void
4464 free_jseg(jseg, jblocks)
4465 	struct jseg *jseg;
4466 	struct jblocks *jblocks;
4467 {
4468 	struct freework *freework;
4469 
4470 	/*
4471 	 * Free freework structures that were lingering to indicate freed
4472 	 * indirect blocks that forced journal write ordering on reallocate.
4473 	 */
4474 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4475 		indirblk_remove(freework);
4476 	if (jblocks->jb_oldestseg == jseg)
4477 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4478 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4479 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4480 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4481 	    ("free_jseg: Freed jseg has valid entries."));
4482 	WORKITEM_FREE(jseg, D_JSEG);
4483 }
4484 
4485 /*
4486  * Free all jsegs that meet the criteria for being reclaimed and update
4487  * oldestseg.
4488  */
4489 static void
4490 free_jsegs(jblocks)
4491 	struct jblocks *jblocks;
4492 {
4493 	struct jseg *jseg;
4494 
4495 	/*
4496 	 * Free only those jsegs which have none allocated before them to
4497 	 * preserve the journal space ordering.
4498 	 */
4499 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4500 		/*
4501 		 * Only reclaim space when nothing depends on this journal
4502 		 * set and another set has written that it is no longer
4503 		 * valid.
4504 		 */
4505 		if (jseg->js_refs != 0) {
4506 			jblocks->jb_oldestseg = jseg;
4507 			return;
4508 		}
4509 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4510 			break;
4511 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4512 			break;
4513 		/*
4514 		 * We can free jsegs that didn't write entries when
4515 		 * oldestwrseq == js_seq.
4516 		 */
4517 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4518 		    jseg->js_cnt != 0)
4519 			break;
4520 		free_jseg(jseg, jblocks);
4521 	}
4522 	/*
4523 	 * If we exited the loop above we still must discover the
4524 	 * oldest valid segment.
4525 	 */
4526 	if (jseg)
4527 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4528 		     jseg = TAILQ_NEXT(jseg, js_next))
4529 			if (jseg->js_refs != 0)
4530 				break;
4531 	jblocks->jb_oldestseg = jseg;
4532 	/*
4533 	 * The journal has no valid records but some jsegs may still be
4534 	 * waiting on oldestwrseq to advance.  We force a small record
4535 	 * out to permit these lingering records to be reclaimed.
4536 	 */
4537 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4538 		jblocks->jb_needseg = 1;
4539 }
4540 
4541 /*
4542  * Release one reference to a jseg and free it if the count reaches 0.  This
4543  * should eventually reclaim journal space as well.
4544  */
4545 static void
4546 rele_jseg(jseg)
4547 	struct jseg *jseg;
4548 {
4549 
4550 	KASSERT(jseg->js_refs > 0,
4551 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4552 	if (--jseg->js_refs != 0)
4553 		return;
4554 	free_jsegs(jseg->js_jblocks);
4555 }
4556 
4557 /*
4558  * Release a jsegdep and decrement the jseg count.
4559  */
4560 static void
4561 free_jsegdep(jsegdep)
4562 	struct jsegdep *jsegdep;
4563 {
4564 
4565 	if (jsegdep->jd_seg)
4566 		rele_jseg(jsegdep->jd_seg);
4567 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4568 }
4569 
4570 /*
4571  * Wait for a journal item to make it to disk.  Initiate journal processing
4572  * if required.
4573  */
4574 static int
4575 jwait(wk, waitfor)
4576 	struct worklist *wk;
4577 	int waitfor;
4578 {
4579 
4580 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4581 	/*
4582 	 * Blocking journal waits cause slow synchronous behavior.  Record
4583 	 * stats on the frequency of these blocking operations.
4584 	 */
4585 	if (waitfor == MNT_WAIT) {
4586 		stat_journal_wait++;
4587 		switch (wk->wk_type) {
4588 		case D_JREMREF:
4589 		case D_JMVREF:
4590 			stat_jwait_filepage++;
4591 			break;
4592 		case D_JTRUNC:
4593 		case D_JFREEBLK:
4594 			stat_jwait_freeblks++;
4595 			break;
4596 		case D_JNEWBLK:
4597 			stat_jwait_newblk++;
4598 			break;
4599 		case D_JADDREF:
4600 			stat_jwait_inode++;
4601 			break;
4602 		default:
4603 			break;
4604 		}
4605 	}
4606 	/*
4607 	 * If IO has not started we process the journal.  We can't mark the
4608 	 * worklist item as IOWAITING because we drop the lock while
4609 	 * processing the journal and the worklist entry may be freed after
4610 	 * this point.  The caller may call back in and re-issue the request.
4611 	 */
4612 	if ((wk->wk_state & INPROGRESS) == 0) {
4613 		softdep_process_journal(wk->wk_mp, wk, waitfor);
4614 		if (waitfor != MNT_WAIT)
4615 			return (EBUSY);
4616 		return (0);
4617 	}
4618 	if (waitfor != MNT_WAIT)
4619 		return (EBUSY);
4620 	wait_worklist(wk, "jwait");
4621 	return (0);
4622 }
4623 
4624 /*
4625  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
4626  * appropriate.  This is a convenience function to reduce duplicate code
4627  * for the setup and revert functions below.
4628  */
4629 static struct inodedep *
4630 inodedep_lookup_ip(ip)
4631 	struct inode *ip;
4632 {
4633 	struct inodedep *inodedep;
4634 	int dflags;
4635 
4636 	KASSERT(ip->i_nlink >= ip->i_effnlink,
4637 	    ("inodedep_lookup_ip: bad delta"));
4638 	dflags = DEPALLOC;
4639 	if (IS_SNAPSHOT(ip))
4640 		dflags |= NODELAY;
4641 	(void) inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags,
4642 	    &inodedep);
4643 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
4644 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
4645 
4646 	return (inodedep);
4647 }
4648 
4649 /*
4650  * Called prior to creating a new inode and linking it to a directory.  The
4651  * jaddref structure must already be allocated by softdep_setup_inomapdep
4652  * and it is discovered here so we can initialize the mode and update
4653  * nlinkdelta.
4654  */
4655 void
4656 softdep_setup_create(dp, ip)
4657 	struct inode *dp;
4658 	struct inode *ip;
4659 {
4660 	struct inodedep *inodedep;
4661 	struct jaddref *jaddref;
4662 	struct vnode *dvp;
4663 
4664 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4665 	    ("softdep_setup_create called on non-softdep filesystem"));
4666 	KASSERT(ip->i_nlink == 1,
4667 	    ("softdep_setup_create: Invalid link count."));
4668 	dvp = ITOV(dp);
4669 	ACQUIRE_LOCK(dp->i_ump);
4670 	inodedep = inodedep_lookup_ip(ip);
4671 	if (DOINGSUJ(dvp)) {
4672 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4673 		    inoreflst);
4674 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
4675 		    ("softdep_setup_create: No addref structure present."));
4676 	}
4677 	softdep_prelink(dvp, NULL);
4678 	FREE_LOCK(dp->i_ump);
4679 }
4680 
4681 /*
4682  * Create a jaddref structure to track the addition of a DOTDOT link when
4683  * we are reparenting an inode as part of a rename.  This jaddref will be
4684  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
4685  * non-journaling softdep.
4686  */
4687 void
4688 softdep_setup_dotdot_link(dp, ip)
4689 	struct inode *dp;
4690 	struct inode *ip;
4691 {
4692 	struct inodedep *inodedep;
4693 	struct jaddref *jaddref;
4694 	struct vnode *dvp;
4695 	struct vnode *vp;
4696 
4697 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4698 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
4699 	dvp = ITOV(dp);
4700 	vp = ITOV(ip);
4701 	jaddref = NULL;
4702 	/*
4703 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
4704 	 * is used as a normal link would be.
4705 	 */
4706 	if (DOINGSUJ(dvp))
4707 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4708 		    dp->i_effnlink - 1, dp->i_mode);
4709 	ACQUIRE_LOCK(dp->i_ump);
4710 	inodedep = inodedep_lookup_ip(dp);
4711 	if (jaddref)
4712 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4713 		    if_deps);
4714 	softdep_prelink(dvp, ITOV(ip));
4715 	FREE_LOCK(dp->i_ump);
4716 }
4717 
4718 /*
4719  * Create a jaddref structure to track a new link to an inode.  The directory
4720  * offset is not known until softdep_setup_directory_add or
4721  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
4722  * softdep.
4723  */
4724 void
4725 softdep_setup_link(dp, ip)
4726 	struct inode *dp;
4727 	struct inode *ip;
4728 {
4729 	struct inodedep *inodedep;
4730 	struct jaddref *jaddref;
4731 	struct vnode *dvp;
4732 
4733 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4734 	    ("softdep_setup_link called on non-softdep filesystem"));
4735 	dvp = ITOV(dp);
4736 	jaddref = NULL;
4737 	if (DOINGSUJ(dvp))
4738 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
4739 		    ip->i_mode);
4740 	ACQUIRE_LOCK(dp->i_ump);
4741 	inodedep = inodedep_lookup_ip(ip);
4742 	if (jaddref)
4743 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
4744 		    if_deps);
4745 	softdep_prelink(dvp, ITOV(ip));
4746 	FREE_LOCK(dp->i_ump);
4747 }
4748 
4749 /*
4750  * Called to create the jaddref structures to track . and .. references as
4751  * well as lookup and further initialize the incomplete jaddref created
4752  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
4753  * nlinkdelta for non-journaling softdep.
4754  */
4755 void
4756 softdep_setup_mkdir(dp, ip)
4757 	struct inode *dp;
4758 	struct inode *ip;
4759 {
4760 	struct inodedep *inodedep;
4761 	struct jaddref *dotdotaddref;
4762 	struct jaddref *dotaddref;
4763 	struct jaddref *jaddref;
4764 	struct vnode *dvp;
4765 
4766 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4767 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
4768 	dvp = ITOV(dp);
4769 	dotaddref = dotdotaddref = NULL;
4770 	if (DOINGSUJ(dvp)) {
4771 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
4772 		    ip->i_mode);
4773 		dotaddref->ja_state |= MKDIR_BODY;
4774 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
4775 		    dp->i_effnlink - 1, dp->i_mode);
4776 		dotdotaddref->ja_state |= MKDIR_PARENT;
4777 	}
4778 	ACQUIRE_LOCK(dp->i_ump);
4779 	inodedep = inodedep_lookup_ip(ip);
4780 	if (DOINGSUJ(dvp)) {
4781 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4782 		    inoreflst);
4783 		KASSERT(jaddref != NULL,
4784 		    ("softdep_setup_mkdir: No addref structure present."));
4785 		KASSERT(jaddref->ja_parent == dp->i_number,
4786 		    ("softdep_setup_mkdir: bad parent %ju",
4787 		    (uintmax_t)jaddref->ja_parent));
4788 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
4789 		    if_deps);
4790 	}
4791 	inodedep = inodedep_lookup_ip(dp);
4792 	if (DOINGSUJ(dvp))
4793 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
4794 		    &dotdotaddref->ja_ref, if_deps);
4795 	softdep_prelink(ITOV(dp), NULL);
4796 	FREE_LOCK(dp->i_ump);
4797 }
4798 
4799 /*
4800  * Called to track nlinkdelta of the inode and parent directories prior to
4801  * unlinking a directory.
4802  */
4803 void
4804 softdep_setup_rmdir(dp, ip)
4805 	struct inode *dp;
4806 	struct inode *ip;
4807 {
4808 	struct vnode *dvp;
4809 
4810 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4811 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
4812 	dvp = ITOV(dp);
4813 	ACQUIRE_LOCK(dp->i_ump);
4814 	(void) inodedep_lookup_ip(ip);
4815 	(void) inodedep_lookup_ip(dp);
4816 	softdep_prelink(dvp, ITOV(ip));
4817 	FREE_LOCK(dp->i_ump);
4818 }
4819 
4820 /*
4821  * Called to track nlinkdelta of the inode and parent directories prior to
4822  * unlink.
4823  */
4824 void
4825 softdep_setup_unlink(dp, ip)
4826 	struct inode *dp;
4827 	struct inode *ip;
4828 {
4829 	struct vnode *dvp;
4830 
4831 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4832 	    ("softdep_setup_unlink called on non-softdep filesystem"));
4833 	dvp = ITOV(dp);
4834 	ACQUIRE_LOCK(dp->i_ump);
4835 	(void) inodedep_lookup_ip(ip);
4836 	(void) inodedep_lookup_ip(dp);
4837 	softdep_prelink(dvp, ITOV(ip));
4838 	FREE_LOCK(dp->i_ump);
4839 }
4840 
4841 /*
4842  * Called to release the journal structures created by a failed non-directory
4843  * creation.  Adjusts nlinkdelta for non-journaling softdep.
4844  */
4845 void
4846 softdep_revert_create(dp, ip)
4847 	struct inode *dp;
4848 	struct inode *ip;
4849 {
4850 	struct inodedep *inodedep;
4851 	struct jaddref *jaddref;
4852 	struct vnode *dvp;
4853 
4854 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4855 	    ("softdep_revert_create called on non-softdep filesystem"));
4856 	dvp = ITOV(dp);
4857 	ACQUIRE_LOCK(dp->i_ump);
4858 	inodedep = inodedep_lookup_ip(ip);
4859 	if (DOINGSUJ(dvp)) {
4860 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4861 		    inoreflst);
4862 		KASSERT(jaddref->ja_parent == dp->i_number,
4863 		    ("softdep_revert_create: addref parent mismatch"));
4864 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4865 	}
4866 	FREE_LOCK(dp->i_ump);
4867 }
4868 
4869 /*
4870  * Called to release the journal structures created by a failed link
4871  * addition.  Adjusts nlinkdelta for non-journaling softdep.
4872  */
4873 void
4874 softdep_revert_link(dp, ip)
4875 	struct inode *dp;
4876 	struct inode *ip;
4877 {
4878 	struct inodedep *inodedep;
4879 	struct jaddref *jaddref;
4880 	struct vnode *dvp;
4881 
4882 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4883 	    ("softdep_revert_link called on non-softdep filesystem"));
4884 	dvp = ITOV(dp);
4885 	ACQUIRE_LOCK(dp->i_ump);
4886 	inodedep = inodedep_lookup_ip(ip);
4887 	if (DOINGSUJ(dvp)) {
4888 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4889 		    inoreflst);
4890 		KASSERT(jaddref->ja_parent == dp->i_number,
4891 		    ("softdep_revert_link: addref parent mismatch"));
4892 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4893 	}
4894 	FREE_LOCK(dp->i_ump);
4895 }
4896 
4897 /*
4898  * Called to release the journal structures created by a failed mkdir
4899  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
4900  */
4901 void
4902 softdep_revert_mkdir(dp, ip)
4903 	struct inode *dp;
4904 	struct inode *ip;
4905 {
4906 	struct inodedep *inodedep;
4907 	struct jaddref *jaddref;
4908 	struct jaddref *dotaddref;
4909 	struct vnode *dvp;
4910 
4911 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4912 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
4913 	dvp = ITOV(dp);
4914 
4915 	ACQUIRE_LOCK(dp->i_ump);
4916 	inodedep = inodedep_lookup_ip(dp);
4917 	if (DOINGSUJ(dvp)) {
4918 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4919 		    inoreflst);
4920 		KASSERT(jaddref->ja_parent == ip->i_number,
4921 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
4922 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4923 	}
4924 	inodedep = inodedep_lookup_ip(ip);
4925 	if (DOINGSUJ(dvp)) {
4926 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
4927 		    inoreflst);
4928 		KASSERT(jaddref->ja_parent == dp->i_number,
4929 		    ("softdep_revert_mkdir: addref parent mismatch"));
4930 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
4931 		    inoreflst, if_deps);
4932 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
4933 		KASSERT(dotaddref->ja_parent == ip->i_number,
4934 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
4935 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
4936 	}
4937 	FREE_LOCK(dp->i_ump);
4938 }
4939 
4940 /*
4941  * Called to correct nlinkdelta after a failed rmdir.
4942  */
4943 void
4944 softdep_revert_rmdir(dp, ip)
4945 	struct inode *dp;
4946 	struct inode *ip;
4947 {
4948 
4949 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(dp->i_ump)) != 0,
4950 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
4951 	ACQUIRE_LOCK(dp->i_ump);
4952 	(void) inodedep_lookup_ip(ip);
4953 	(void) inodedep_lookup_ip(dp);
4954 	FREE_LOCK(dp->i_ump);
4955 }
4956 
4957 /*
4958  * Protecting the freemaps (or bitmaps).
4959  *
4960  * To eliminate the need to execute fsck before mounting a filesystem
4961  * after a power failure, one must (conservatively) guarantee that the
4962  * on-disk copy of the bitmaps never indicate that a live inode or block is
4963  * free.  So, when a block or inode is allocated, the bitmap should be
4964  * updated (on disk) before any new pointers.  When a block or inode is
4965  * freed, the bitmap should not be updated until all pointers have been
4966  * reset.  The latter dependency is handled by the delayed de-allocation
4967  * approach described below for block and inode de-allocation.  The former
4968  * dependency is handled by calling the following procedure when a block or
4969  * inode is allocated. When an inode is allocated an "inodedep" is created
4970  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
4971  * Each "inodedep" is also inserted into the hash indexing structure so
4972  * that any additional link additions can be made dependent on the inode
4973  * allocation.
4974  *
4975  * The ufs filesystem maintains a number of free block counts (e.g., per
4976  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
4977  * in addition to the bitmaps.  These counts are used to improve efficiency
4978  * during allocation and therefore must be consistent with the bitmaps.
4979  * There is no convenient way to guarantee post-crash consistency of these
4980  * counts with simple update ordering, for two main reasons: (1) The counts
4981  * and bitmaps for a single cylinder group block are not in the same disk
4982  * sector.  If a disk write is interrupted (e.g., by power failure), one may
4983  * be written and the other not.  (2) Some of the counts are located in the
4984  * superblock rather than the cylinder group block. So, we focus our soft
4985  * updates implementation on protecting the bitmaps. When mounting a
4986  * filesystem, we recompute the auxiliary counts from the bitmaps.
4987  */
4988 
4989 /*
4990  * Called just after updating the cylinder group block to allocate an inode.
4991  */
4992 void
4993 softdep_setup_inomapdep(bp, ip, newinum, mode)
4994 	struct buf *bp;		/* buffer for cylgroup block with inode map */
4995 	struct inode *ip;	/* inode related to allocation */
4996 	ino_t newinum;		/* new inode number being allocated */
4997 	int mode;
4998 {
4999 	struct inodedep *inodedep;
5000 	struct bmsafemap *bmsafemap;
5001 	struct jaddref *jaddref;
5002 	struct mount *mp;
5003 	struct fs *fs;
5004 
5005 	mp = UFSTOVFS(ip->i_ump);
5006 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5007 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5008 	fs = ip->i_ump->um_fs;
5009 	jaddref = NULL;
5010 
5011 	/*
5012 	 * Allocate the journal reference add structure so that the bitmap
5013 	 * can be dependent on it.
5014 	 */
5015 	if (MOUNTEDSUJ(mp)) {
5016 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5017 		jaddref->ja_state |= NEWBLOCK;
5018 	}
5019 
5020 	/*
5021 	 * Create a dependency for the newly allocated inode.
5022 	 * Panic if it already exists as something is seriously wrong.
5023 	 * Otherwise add it to the dependency list for the buffer holding
5024 	 * the cylinder group map from which it was allocated.
5025 	 *
5026 	 * We have to preallocate a bmsafemap entry in case it is needed
5027 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5028 	 * have to finish initializing it before we can FREE_LOCK().
5029 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5030 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5031 	 * creating the inodedep as it can be freed during the time
5032 	 * that we FREE_LOCK() while allocating the inodedep. We must
5033 	 * call workitem_alloc() before entering the locked section as
5034 	 * it also acquires the lock and we must avoid trying doing so
5035 	 * recursively.
5036 	 */
5037 	bmsafemap = malloc(sizeof(struct bmsafemap),
5038 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5039 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5040 	ACQUIRE_LOCK(ip->i_ump);
5041 	if ((inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep)))
5042 		panic("softdep_setup_inomapdep: dependency %p for new"
5043 		    "inode already exists", inodedep);
5044 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5045 	if (jaddref) {
5046 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5047 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5048 		    if_deps);
5049 	} else {
5050 		inodedep->id_state |= ONDEPLIST;
5051 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5052 	}
5053 	inodedep->id_bmsafemap = bmsafemap;
5054 	inodedep->id_state &= ~DEPCOMPLETE;
5055 	FREE_LOCK(ip->i_ump);
5056 }
5057 
5058 /*
5059  * Called just after updating the cylinder group block to
5060  * allocate block or fragment.
5061  */
5062 void
5063 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5064 	struct buf *bp;		/* buffer for cylgroup block with block map */
5065 	struct mount *mp;	/* filesystem doing allocation */
5066 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5067 	int frags;		/* Number of fragments. */
5068 	int oldfrags;		/* Previous number of fragments for extend. */
5069 {
5070 	struct newblk *newblk;
5071 	struct bmsafemap *bmsafemap;
5072 	struct jnewblk *jnewblk;
5073 	struct ufsmount *ump;
5074 	struct fs *fs;
5075 
5076 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5077 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5078 	ump = VFSTOUFS(mp);
5079 	fs = ump->um_fs;
5080 	jnewblk = NULL;
5081 	/*
5082 	 * Create a dependency for the newly allocated block.
5083 	 * Add it to the dependency list for the buffer holding
5084 	 * the cylinder group map from which it was allocated.
5085 	 */
5086 	if (MOUNTEDSUJ(mp)) {
5087 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5088 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5089 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5090 		jnewblk->jn_state = ATTACHED;
5091 		jnewblk->jn_blkno = newblkno;
5092 		jnewblk->jn_frags = frags;
5093 		jnewblk->jn_oldfrags = oldfrags;
5094 #ifdef SUJ_DEBUG
5095 		{
5096 			struct cg *cgp;
5097 			uint8_t *blksfree;
5098 			long bno;
5099 			int i;
5100 
5101 			cgp = (struct cg *)bp->b_data;
5102 			blksfree = cg_blksfree(cgp);
5103 			bno = dtogd(fs, jnewblk->jn_blkno);
5104 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5105 			    i++) {
5106 				if (isset(blksfree, bno + i))
5107 					panic("softdep_setup_blkmapdep: "
5108 					    "free fragment %d from %d-%d "
5109 					    "state 0x%X dep %p", i,
5110 					    jnewblk->jn_oldfrags,
5111 					    jnewblk->jn_frags,
5112 					    jnewblk->jn_state,
5113 					    jnewblk->jn_dep);
5114 			}
5115 		}
5116 #endif
5117 	}
5118 
5119 	CTR3(KTR_SUJ,
5120 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5121 	    newblkno, frags, oldfrags);
5122 	ACQUIRE_LOCK(ump);
5123 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5124 		panic("softdep_setup_blkmapdep: found block");
5125 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5126 	    dtog(fs, newblkno), NULL);
5127 	if (jnewblk) {
5128 		jnewblk->jn_dep = (struct worklist *)newblk;
5129 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5130 	} else {
5131 		newblk->nb_state |= ONDEPLIST;
5132 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5133 	}
5134 	newblk->nb_bmsafemap = bmsafemap;
5135 	newblk->nb_jnewblk = jnewblk;
5136 	FREE_LOCK(ump);
5137 }
5138 
5139 #define	BMSAFEMAP_HASH(ump, cg) \
5140       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5141 
5142 static int
5143 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5144 	struct bmsafemap_hashhead *bmsafemaphd;
5145 	int cg;
5146 	struct bmsafemap **bmsafemapp;
5147 {
5148 	struct bmsafemap *bmsafemap;
5149 
5150 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5151 		if (bmsafemap->sm_cg == cg)
5152 			break;
5153 	if (bmsafemap) {
5154 		*bmsafemapp = bmsafemap;
5155 		return (1);
5156 	}
5157 	*bmsafemapp = NULL;
5158 
5159 	return (0);
5160 }
5161 
5162 /*
5163  * Find the bmsafemap associated with a cylinder group buffer.
5164  * If none exists, create one. The buffer must be locked when
5165  * this routine is called and this routine must be called with
5166  * the softdep lock held. To avoid giving up the lock while
5167  * allocating a new bmsafemap, a preallocated bmsafemap may be
5168  * provided. If it is provided but not needed, it is freed.
5169  */
5170 static struct bmsafemap *
5171 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5172 	struct mount *mp;
5173 	struct buf *bp;
5174 	int cg;
5175 	struct bmsafemap *newbmsafemap;
5176 {
5177 	struct bmsafemap_hashhead *bmsafemaphd;
5178 	struct bmsafemap *bmsafemap, *collision;
5179 	struct worklist *wk;
5180 	struct ufsmount *ump;
5181 
5182 	ump = VFSTOUFS(mp);
5183 	LOCK_OWNED(ump);
5184 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5185 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5186 		if (wk->wk_type == D_BMSAFEMAP) {
5187 			if (newbmsafemap)
5188 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5189 			return (WK_BMSAFEMAP(wk));
5190 		}
5191 	}
5192 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5193 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5194 		if (newbmsafemap)
5195 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5196 		return (bmsafemap);
5197 	}
5198 	if (newbmsafemap) {
5199 		bmsafemap = newbmsafemap;
5200 	} else {
5201 		FREE_LOCK(ump);
5202 		bmsafemap = malloc(sizeof(struct bmsafemap),
5203 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5204 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5205 		ACQUIRE_LOCK(ump);
5206 	}
5207 	bmsafemap->sm_buf = bp;
5208 	LIST_INIT(&bmsafemap->sm_inodedephd);
5209 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5210 	LIST_INIT(&bmsafemap->sm_newblkhd);
5211 	LIST_INIT(&bmsafemap->sm_newblkwr);
5212 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5213 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5214 	LIST_INIT(&bmsafemap->sm_freehd);
5215 	LIST_INIT(&bmsafemap->sm_freewr);
5216 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5217 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5218 		return (collision);
5219 	}
5220 	bmsafemap->sm_cg = cg;
5221 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5222 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5223 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5224 	return (bmsafemap);
5225 }
5226 
5227 /*
5228  * Direct block allocation dependencies.
5229  *
5230  * When a new block is allocated, the corresponding disk locations must be
5231  * initialized (with zeros or new data) before the on-disk inode points to
5232  * them.  Also, the freemap from which the block was allocated must be
5233  * updated (on disk) before the inode's pointer. These two dependencies are
5234  * independent of each other and are needed for all file blocks and indirect
5235  * blocks that are pointed to directly by the inode.  Just before the
5236  * "in-core" version of the inode is updated with a newly allocated block
5237  * number, a procedure (below) is called to setup allocation dependency
5238  * structures.  These structures are removed when the corresponding
5239  * dependencies are satisfied or when the block allocation becomes obsolete
5240  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5241  * fragment that gets upgraded).  All of these cases are handled in
5242  * procedures described later.
5243  *
5244  * When a file extension causes a fragment to be upgraded, either to a larger
5245  * fragment or to a full block, the on-disk location may change (if the
5246  * previous fragment could not simply be extended). In this case, the old
5247  * fragment must be de-allocated, but not until after the inode's pointer has
5248  * been updated. In most cases, this is handled by later procedures, which
5249  * will construct a "freefrag" structure to be added to the workitem queue
5250  * when the inode update is complete (or obsolete).  The main exception to
5251  * this is when an allocation occurs while a pending allocation dependency
5252  * (for the same block pointer) remains.  This case is handled in the main
5253  * allocation dependency setup procedure by immediately freeing the
5254  * unreferenced fragments.
5255  */
5256 void
5257 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5258 	struct inode *ip;	/* inode to which block is being added */
5259 	ufs_lbn_t off;		/* block pointer within inode */
5260 	ufs2_daddr_t newblkno;	/* disk block number being added */
5261 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5262 	long newsize;		/* size of new block */
5263 	long oldsize;		/* size of new block */
5264 	struct buf *bp;		/* bp for allocated block */
5265 {
5266 	struct allocdirect *adp, *oldadp;
5267 	struct allocdirectlst *adphead;
5268 	struct freefrag *freefrag;
5269 	struct inodedep *inodedep;
5270 	struct pagedep *pagedep;
5271 	struct jnewblk *jnewblk;
5272 	struct newblk *newblk;
5273 	struct mount *mp;
5274 	ufs_lbn_t lbn;
5275 
5276 	lbn = bp->b_lblkno;
5277 	mp = UFSTOVFS(ip->i_ump);
5278 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5279 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5280 	if (oldblkno && oldblkno != newblkno)
5281 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5282 	else
5283 		freefrag = NULL;
5284 
5285 	CTR6(KTR_SUJ,
5286 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5287 	    "off %jd newsize %ld oldsize %d",
5288 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5289 	ACQUIRE_LOCK(ip->i_ump);
5290 	if (off >= NDADDR) {
5291 		if (lbn > 0)
5292 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5293 			    lbn, off);
5294 		/* allocating an indirect block */
5295 		if (oldblkno != 0)
5296 			panic("softdep_setup_allocdirect: non-zero indir");
5297 	} else {
5298 		if (off != lbn)
5299 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5300 			    lbn, off);
5301 		/*
5302 		 * Allocating a direct block.
5303 		 *
5304 		 * If we are allocating a directory block, then we must
5305 		 * allocate an associated pagedep to track additions and
5306 		 * deletions.
5307 		 */
5308 		if ((ip->i_mode & IFMT) == IFDIR)
5309 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5310 			    &pagedep);
5311 	}
5312 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5313 		panic("softdep_setup_allocdirect: lost block");
5314 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5315 	    ("softdep_setup_allocdirect: newblk already initialized"));
5316 	/*
5317 	 * Convert the newblk to an allocdirect.
5318 	 */
5319 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5320 	adp = (struct allocdirect *)newblk;
5321 	newblk->nb_freefrag = freefrag;
5322 	adp->ad_offset = off;
5323 	adp->ad_oldblkno = oldblkno;
5324 	adp->ad_newsize = newsize;
5325 	adp->ad_oldsize = oldsize;
5326 
5327 	/*
5328 	 * Finish initializing the journal.
5329 	 */
5330 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5331 		jnewblk->jn_ino = ip->i_number;
5332 		jnewblk->jn_lbn = lbn;
5333 		add_to_journal(&jnewblk->jn_list);
5334 	}
5335 	if (freefrag && freefrag->ff_jdep != NULL &&
5336 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5337 		add_to_journal(freefrag->ff_jdep);
5338 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5339 	adp->ad_inodedep = inodedep;
5340 
5341 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5342 	/*
5343 	 * The list of allocdirects must be kept in sorted and ascending
5344 	 * order so that the rollback routines can quickly determine the
5345 	 * first uncommitted block (the size of the file stored on disk
5346 	 * ends at the end of the lowest committed fragment, or if there
5347 	 * are no fragments, at the end of the highest committed block).
5348 	 * Since files generally grow, the typical case is that the new
5349 	 * block is to be added at the end of the list. We speed this
5350 	 * special case by checking against the last allocdirect in the
5351 	 * list before laboriously traversing the list looking for the
5352 	 * insertion point.
5353 	 */
5354 	adphead = &inodedep->id_newinoupdt;
5355 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5356 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5357 		/* insert at end of list */
5358 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5359 		if (oldadp != NULL && oldadp->ad_offset == off)
5360 			allocdirect_merge(adphead, adp, oldadp);
5361 		FREE_LOCK(ip->i_ump);
5362 		return;
5363 	}
5364 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5365 		if (oldadp->ad_offset >= off)
5366 			break;
5367 	}
5368 	if (oldadp == NULL)
5369 		panic("softdep_setup_allocdirect: lost entry");
5370 	/* insert in middle of list */
5371 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5372 	if (oldadp->ad_offset == off)
5373 		allocdirect_merge(adphead, adp, oldadp);
5374 
5375 	FREE_LOCK(ip->i_ump);
5376 }
5377 
5378 /*
5379  * Merge a newer and older journal record to be stored either in a
5380  * newblock or freefrag.  This handles aggregating journal records for
5381  * fragment allocation into a second record as well as replacing a
5382  * journal free with an aborted journal allocation.  A segment for the
5383  * oldest record will be placed on wkhd if it has been written.  If not
5384  * the segment for the newer record will suffice.
5385  */
5386 static struct worklist *
5387 jnewblk_merge(new, old, wkhd)
5388 	struct worklist *new;
5389 	struct worklist *old;
5390 	struct workhead *wkhd;
5391 {
5392 	struct jnewblk *njnewblk;
5393 	struct jnewblk *jnewblk;
5394 
5395 	/* Handle NULLs to simplify callers. */
5396 	if (new == NULL)
5397 		return (old);
5398 	if (old == NULL)
5399 		return (new);
5400 	/* Replace a jfreefrag with a jnewblk. */
5401 	if (new->wk_type == D_JFREEFRAG) {
5402 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5403 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5404 			    old, new);
5405 		cancel_jfreefrag(WK_JFREEFRAG(new));
5406 		return (old);
5407 	}
5408 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5409 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5410 		    old->wk_type, new->wk_type);
5411 	/*
5412 	 * Handle merging of two jnewblk records that describe
5413 	 * different sets of fragments in the same block.
5414 	 */
5415 	jnewblk = WK_JNEWBLK(old);
5416 	njnewblk = WK_JNEWBLK(new);
5417 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5418 		panic("jnewblk_merge: Merging disparate blocks.");
5419 	/*
5420 	 * The record may be rolled back in the cg.
5421 	 */
5422 	if (jnewblk->jn_state & UNDONE) {
5423 		jnewblk->jn_state &= ~UNDONE;
5424 		njnewblk->jn_state |= UNDONE;
5425 		njnewblk->jn_state &= ~ATTACHED;
5426 	}
5427 	/*
5428 	 * We modify the newer addref and free the older so that if neither
5429 	 * has been written the most up-to-date copy will be on disk.  If
5430 	 * both have been written but rolled back we only temporarily need
5431 	 * one of them to fix the bits when the cg write completes.
5432 	 */
5433 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5434 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5435 	cancel_jnewblk(jnewblk, wkhd);
5436 	WORKLIST_REMOVE(&jnewblk->jn_list);
5437 	free_jnewblk(jnewblk);
5438 	return (new);
5439 }
5440 
5441 /*
5442  * Replace an old allocdirect dependency with a newer one.
5443  * This routine must be called with splbio interrupts blocked.
5444  */
5445 static void
5446 allocdirect_merge(adphead, newadp, oldadp)
5447 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5448 	struct allocdirect *newadp;	/* allocdirect being added */
5449 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5450 {
5451 	struct worklist *wk;
5452 	struct freefrag *freefrag;
5453 
5454 	freefrag = NULL;
5455 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5456 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5457 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5458 	    newadp->ad_offset >= NDADDR)
5459 		panic("%s %jd != new %jd || old size %ld != new %ld",
5460 		    "allocdirect_merge: old blkno",
5461 		    (intmax_t)newadp->ad_oldblkno,
5462 		    (intmax_t)oldadp->ad_newblkno,
5463 		    newadp->ad_oldsize, oldadp->ad_newsize);
5464 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5465 	newadp->ad_oldsize = oldadp->ad_oldsize;
5466 	/*
5467 	 * If the old dependency had a fragment to free or had never
5468 	 * previously had a block allocated, then the new dependency
5469 	 * can immediately post its freefrag and adopt the old freefrag.
5470 	 * This action is done by swapping the freefrag dependencies.
5471 	 * The new dependency gains the old one's freefrag, and the
5472 	 * old one gets the new one and then immediately puts it on
5473 	 * the worklist when it is freed by free_newblk. It is
5474 	 * not possible to do this swap when the old dependency had a
5475 	 * non-zero size but no previous fragment to free. This condition
5476 	 * arises when the new block is an extension of the old block.
5477 	 * Here, the first part of the fragment allocated to the new
5478 	 * dependency is part of the block currently claimed on disk by
5479 	 * the old dependency, so cannot legitimately be freed until the
5480 	 * conditions for the new dependency are fulfilled.
5481 	 */
5482 	freefrag = newadp->ad_freefrag;
5483 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5484 		newadp->ad_freefrag = oldadp->ad_freefrag;
5485 		oldadp->ad_freefrag = freefrag;
5486 	}
5487 	/*
5488 	 * If we are tracking a new directory-block allocation,
5489 	 * move it from the old allocdirect to the new allocdirect.
5490 	 */
5491 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5492 		WORKLIST_REMOVE(wk);
5493 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5494 			panic("allocdirect_merge: extra newdirblk");
5495 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5496 	}
5497 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5498 	/*
5499 	 * We need to move any journal dependencies over to the freefrag
5500 	 * that releases this block if it exists.  Otherwise we are
5501 	 * extending an existing block and we'll wait until that is
5502 	 * complete to release the journal space and extend the
5503 	 * new journal to cover this old space as well.
5504 	 */
5505 	if (freefrag == NULL) {
5506 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5507 			panic("allocdirect_merge: %jd != %jd",
5508 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5509 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5510 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5511 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5512 		    &newadp->ad_block.nb_jwork);
5513 		oldadp->ad_block.nb_jnewblk = NULL;
5514 		cancel_newblk(&oldadp->ad_block, NULL,
5515 		    &newadp->ad_block.nb_jwork);
5516 	} else {
5517 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5518 		    &freefrag->ff_list, &freefrag->ff_jwork);
5519 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5520 		    &freefrag->ff_jwork);
5521 	}
5522 	free_newblk(&oldadp->ad_block);
5523 }
5524 
5525 /*
5526  * Allocate a jfreefrag structure to journal a single block free.
5527  */
5528 static struct jfreefrag *
5529 newjfreefrag(freefrag, ip, blkno, size, lbn)
5530 	struct freefrag *freefrag;
5531 	struct inode *ip;
5532 	ufs2_daddr_t blkno;
5533 	long size;
5534 	ufs_lbn_t lbn;
5535 {
5536 	struct jfreefrag *jfreefrag;
5537 	struct fs *fs;
5538 
5539 	fs = ip->i_fs;
5540 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5541 	    M_SOFTDEP_FLAGS);
5542 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, UFSTOVFS(ip->i_ump));
5543 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5544 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5545 	jfreefrag->fr_ino = ip->i_number;
5546 	jfreefrag->fr_lbn = lbn;
5547 	jfreefrag->fr_blkno = blkno;
5548 	jfreefrag->fr_frags = numfrags(fs, size);
5549 	jfreefrag->fr_freefrag = freefrag;
5550 
5551 	return (jfreefrag);
5552 }
5553 
5554 /*
5555  * Allocate a new freefrag structure.
5556  */
5557 static struct freefrag *
5558 newfreefrag(ip, blkno, size, lbn)
5559 	struct inode *ip;
5560 	ufs2_daddr_t blkno;
5561 	long size;
5562 	ufs_lbn_t lbn;
5563 {
5564 	struct freefrag *freefrag;
5565 	struct fs *fs;
5566 
5567 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5568 	    ip->i_number, blkno, size, lbn);
5569 	fs = ip->i_fs;
5570 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5571 		panic("newfreefrag: frag size");
5572 	freefrag = malloc(sizeof(struct freefrag),
5573 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5574 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ip->i_ump));
5575 	freefrag->ff_state = ATTACHED;
5576 	LIST_INIT(&freefrag->ff_jwork);
5577 	freefrag->ff_inum = ip->i_number;
5578 	freefrag->ff_vtype = ITOV(ip)->v_type;
5579 	freefrag->ff_blkno = blkno;
5580 	freefrag->ff_fragsize = size;
5581 
5582 	if (MOUNTEDSUJ(UFSTOVFS(ip->i_ump))) {
5583 		freefrag->ff_jdep = (struct worklist *)
5584 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5585 	} else {
5586 		freefrag->ff_state |= DEPCOMPLETE;
5587 		freefrag->ff_jdep = NULL;
5588 	}
5589 
5590 	return (freefrag);
5591 }
5592 
5593 /*
5594  * This workitem de-allocates fragments that were replaced during
5595  * file block allocation.
5596  */
5597 static void
5598 handle_workitem_freefrag(freefrag)
5599 	struct freefrag *freefrag;
5600 {
5601 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5602 	struct workhead wkhd;
5603 
5604 	CTR3(KTR_SUJ,
5605 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
5606 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
5607 	/*
5608 	 * It would be illegal to add new completion items to the
5609 	 * freefrag after it was schedule to be done so it must be
5610 	 * safe to modify the list head here.
5611 	 */
5612 	LIST_INIT(&wkhd);
5613 	ACQUIRE_LOCK(ump);
5614 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
5615 	/*
5616 	 * If the journal has not been written we must cancel it here.
5617 	 */
5618 	if (freefrag->ff_jdep) {
5619 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
5620 			panic("handle_workitem_freefrag: Unexpected type %d\n",
5621 			    freefrag->ff_jdep->wk_type);
5622 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
5623 	}
5624 	FREE_LOCK(ump);
5625 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
5626 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype, &wkhd);
5627 	ACQUIRE_LOCK(ump);
5628 	WORKITEM_FREE(freefrag, D_FREEFRAG);
5629 	FREE_LOCK(ump);
5630 }
5631 
5632 /*
5633  * Set up a dependency structure for an external attributes data block.
5634  * This routine follows much of the structure of softdep_setup_allocdirect.
5635  * See the description of softdep_setup_allocdirect above for details.
5636  */
5637 void
5638 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5639 	struct inode *ip;
5640 	ufs_lbn_t off;
5641 	ufs2_daddr_t newblkno;
5642 	ufs2_daddr_t oldblkno;
5643 	long newsize;
5644 	long oldsize;
5645 	struct buf *bp;
5646 {
5647 	struct allocdirect *adp, *oldadp;
5648 	struct allocdirectlst *adphead;
5649 	struct freefrag *freefrag;
5650 	struct inodedep *inodedep;
5651 	struct jnewblk *jnewblk;
5652 	struct newblk *newblk;
5653 	struct mount *mp;
5654 	ufs_lbn_t lbn;
5655 
5656 	mp = UFSTOVFS(ip->i_ump);
5657 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5658 	    ("softdep_setup_allocext called on non-softdep filesystem"));
5659 	KASSERT(off < NXADDR, ("softdep_setup_allocext: lbn %lld > NXADDR",
5660 		    (long long)off));
5661 
5662 	lbn = bp->b_lblkno;
5663 	if (oldblkno && oldblkno != newblkno)
5664 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn);
5665 	else
5666 		freefrag = NULL;
5667 
5668 	ACQUIRE_LOCK(ip->i_ump);
5669 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5670 		panic("softdep_setup_allocext: lost block");
5671 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5672 	    ("softdep_setup_allocext: newblk already initialized"));
5673 	/*
5674 	 * Convert the newblk to an allocdirect.
5675 	 */
5676 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5677 	adp = (struct allocdirect *)newblk;
5678 	newblk->nb_freefrag = freefrag;
5679 	adp->ad_offset = off;
5680 	adp->ad_oldblkno = oldblkno;
5681 	adp->ad_newsize = newsize;
5682 	adp->ad_oldsize = oldsize;
5683 	adp->ad_state |=  EXTDATA;
5684 
5685 	/*
5686 	 * Finish initializing the journal.
5687 	 */
5688 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5689 		jnewblk->jn_ino = ip->i_number;
5690 		jnewblk->jn_lbn = lbn;
5691 		add_to_journal(&jnewblk->jn_list);
5692 	}
5693 	if (freefrag && freefrag->ff_jdep != NULL &&
5694 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5695 		add_to_journal(freefrag->ff_jdep);
5696 	inodedep_lookup(mp, ip->i_number, DEPALLOC | NODELAY, &inodedep);
5697 	adp->ad_inodedep = inodedep;
5698 
5699 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5700 	/*
5701 	 * The list of allocdirects must be kept in sorted and ascending
5702 	 * order so that the rollback routines can quickly determine the
5703 	 * first uncommitted block (the size of the file stored on disk
5704 	 * ends at the end of the lowest committed fragment, or if there
5705 	 * are no fragments, at the end of the highest committed block).
5706 	 * Since files generally grow, the typical case is that the new
5707 	 * block is to be added at the end of the list. We speed this
5708 	 * special case by checking against the last allocdirect in the
5709 	 * list before laboriously traversing the list looking for the
5710 	 * insertion point.
5711 	 */
5712 	adphead = &inodedep->id_newextupdt;
5713 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5714 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5715 		/* insert at end of list */
5716 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5717 		if (oldadp != NULL && oldadp->ad_offset == off)
5718 			allocdirect_merge(adphead, adp, oldadp);
5719 		FREE_LOCK(ip->i_ump);
5720 		return;
5721 	}
5722 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5723 		if (oldadp->ad_offset >= off)
5724 			break;
5725 	}
5726 	if (oldadp == NULL)
5727 		panic("softdep_setup_allocext: lost entry");
5728 	/* insert in middle of list */
5729 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5730 	if (oldadp->ad_offset == off)
5731 		allocdirect_merge(adphead, adp, oldadp);
5732 	FREE_LOCK(ip->i_ump);
5733 }
5734 
5735 /*
5736  * Indirect block allocation dependencies.
5737  *
5738  * The same dependencies that exist for a direct block also exist when
5739  * a new block is allocated and pointed to by an entry in a block of
5740  * indirect pointers. The undo/redo states described above are also
5741  * used here. Because an indirect block contains many pointers that
5742  * may have dependencies, a second copy of the entire in-memory indirect
5743  * block is kept. The buffer cache copy is always completely up-to-date.
5744  * The second copy, which is used only as a source for disk writes,
5745  * contains only the safe pointers (i.e., those that have no remaining
5746  * update dependencies). The second copy is freed when all pointers
5747  * are safe. The cache is not allowed to replace indirect blocks with
5748  * pending update dependencies. If a buffer containing an indirect
5749  * block with dependencies is written, these routines will mark it
5750  * dirty again. It can only be successfully written once all the
5751  * dependencies are removed. The ffs_fsync routine in conjunction with
5752  * softdep_sync_metadata work together to get all the dependencies
5753  * removed so that a file can be successfully written to disk. Three
5754  * procedures are used when setting up indirect block pointer
5755  * dependencies. The division is necessary because of the organization
5756  * of the "balloc" routine and because of the distinction between file
5757  * pages and file metadata blocks.
5758  */
5759 
5760 /*
5761  * Allocate a new allocindir structure.
5762  */
5763 static struct allocindir *
5764 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
5765 	struct inode *ip;	/* inode for file being extended */
5766 	int ptrno;		/* offset of pointer in indirect block */
5767 	ufs2_daddr_t newblkno;	/* disk block number being added */
5768 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5769 	ufs_lbn_t lbn;
5770 {
5771 	struct newblk *newblk;
5772 	struct allocindir *aip;
5773 	struct freefrag *freefrag;
5774 	struct jnewblk *jnewblk;
5775 
5776 	if (oldblkno)
5777 		freefrag = newfreefrag(ip, oldblkno, ip->i_fs->fs_bsize, lbn);
5778 	else
5779 		freefrag = NULL;
5780 	ACQUIRE_LOCK(ip->i_ump);
5781 	if (newblk_lookup(UFSTOVFS(ip->i_ump), newblkno, 0, &newblk) == 0)
5782 		panic("new_allocindir: lost block");
5783 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5784 	    ("newallocindir: newblk already initialized"));
5785 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
5786 	newblk->nb_freefrag = freefrag;
5787 	aip = (struct allocindir *)newblk;
5788 	aip->ai_offset = ptrno;
5789 	aip->ai_oldblkno = oldblkno;
5790 	aip->ai_lbn = lbn;
5791 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5792 		jnewblk->jn_ino = ip->i_number;
5793 		jnewblk->jn_lbn = lbn;
5794 		add_to_journal(&jnewblk->jn_list);
5795 	}
5796 	if (freefrag && freefrag->ff_jdep != NULL &&
5797 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5798 		add_to_journal(freefrag->ff_jdep);
5799 	return (aip);
5800 }
5801 
5802 /*
5803  * Called just before setting an indirect block pointer
5804  * to a newly allocated file page.
5805  */
5806 void
5807 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
5808 	struct inode *ip;	/* inode for file being extended */
5809 	ufs_lbn_t lbn;		/* allocated block number within file */
5810 	struct buf *bp;		/* buffer with indirect blk referencing page */
5811 	int ptrno;		/* offset of pointer in indirect block */
5812 	ufs2_daddr_t newblkno;	/* disk block number being added */
5813 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
5814 	struct buf *nbp;	/* buffer holding allocated page */
5815 {
5816 	struct inodedep *inodedep;
5817 	struct freefrag *freefrag;
5818 	struct allocindir *aip;
5819 	struct pagedep *pagedep;
5820 	struct mount *mp;
5821 	int dflags;
5822 
5823 	mp = UFSTOVFS(ip->i_ump);
5824 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5825 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
5826 	KASSERT(lbn == nbp->b_lblkno,
5827 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
5828 	    lbn, bp->b_lblkno));
5829 	CTR4(KTR_SUJ,
5830 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
5831 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
5832 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
5833 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
5834 	dflags = DEPALLOC;
5835 	if (IS_SNAPSHOT(ip))
5836 		dflags |= NODELAY;
5837 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
5838 	/*
5839 	 * If we are allocating a directory page, then we must
5840 	 * allocate an associated pagedep to track additions and
5841 	 * deletions.
5842 	 */
5843 	if ((ip->i_mode & IFMT) == IFDIR)
5844 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
5845 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5846 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
5847 	FREE_LOCK(ip->i_ump);
5848 	if (freefrag)
5849 		handle_workitem_freefrag(freefrag);
5850 }
5851 
5852 /*
5853  * Called just before setting an indirect block pointer to a
5854  * newly allocated indirect block.
5855  */
5856 void
5857 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
5858 	struct buf *nbp;	/* newly allocated indirect block */
5859 	struct inode *ip;	/* inode for file being extended */
5860 	struct buf *bp;		/* indirect block referencing allocated block */
5861 	int ptrno;		/* offset of pointer in indirect block */
5862 	ufs2_daddr_t newblkno;	/* disk block number being added */
5863 {
5864 	struct inodedep *inodedep;
5865 	struct allocindir *aip;
5866 	ufs_lbn_t lbn;
5867 	int dflags;
5868 
5869 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
5870 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
5871 	CTR3(KTR_SUJ,
5872 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
5873 	    ip->i_number, newblkno, ptrno);
5874 	lbn = nbp->b_lblkno;
5875 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
5876 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
5877 	dflags = DEPALLOC;
5878 	if (IS_SNAPSHOT(ip))
5879 		dflags |= NODELAY;
5880 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
5881 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
5882 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
5883 		panic("softdep_setup_allocindir_meta: Block already existed");
5884 	FREE_LOCK(ip->i_ump);
5885 }
5886 
5887 static void
5888 indirdep_complete(indirdep)
5889 	struct indirdep *indirdep;
5890 {
5891 	struct allocindir *aip;
5892 
5893 	LIST_REMOVE(indirdep, ir_next);
5894 	indirdep->ir_state |= DEPCOMPLETE;
5895 
5896 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
5897 		LIST_REMOVE(aip, ai_next);
5898 		free_newblk(&aip->ai_block);
5899 	}
5900 	/*
5901 	 * If this indirdep is not attached to a buf it was simply waiting
5902 	 * on completion to clear completehd.  free_indirdep() asserts
5903 	 * that nothing is dangling.
5904 	 */
5905 	if ((indirdep->ir_state & ONWORKLIST) == 0)
5906 		free_indirdep(indirdep);
5907 }
5908 
5909 static struct indirdep *
5910 indirdep_lookup(mp, ip, bp)
5911 	struct mount *mp;
5912 	struct inode *ip;
5913 	struct buf *bp;
5914 {
5915 	struct indirdep *indirdep, *newindirdep;
5916 	struct newblk *newblk;
5917 	struct ufsmount *ump;
5918 	struct worklist *wk;
5919 	struct fs *fs;
5920 	ufs2_daddr_t blkno;
5921 
5922 	ump = VFSTOUFS(mp);
5923 	LOCK_OWNED(ump);
5924 	indirdep = NULL;
5925 	newindirdep = NULL;
5926 	fs = ip->i_fs;
5927 	for (;;) {
5928 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5929 			if (wk->wk_type != D_INDIRDEP)
5930 				continue;
5931 			indirdep = WK_INDIRDEP(wk);
5932 			break;
5933 		}
5934 		/* Found on the buffer worklist, no new structure to free. */
5935 		if (indirdep != NULL && newindirdep == NULL)
5936 			return (indirdep);
5937 		if (indirdep != NULL && newindirdep != NULL)
5938 			panic("indirdep_lookup: simultaneous create");
5939 		/* None found on the buffer and a new structure is ready. */
5940 		if (indirdep == NULL && newindirdep != NULL)
5941 			break;
5942 		/* None found and no new structure available. */
5943 		FREE_LOCK(ump);
5944 		newindirdep = malloc(sizeof(struct indirdep),
5945 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
5946 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
5947 		newindirdep->ir_state = ATTACHED;
5948 		if (ip->i_ump->um_fstype == UFS1)
5949 			newindirdep->ir_state |= UFS1FMT;
5950 		TAILQ_INIT(&newindirdep->ir_trunc);
5951 		newindirdep->ir_saveddata = NULL;
5952 		LIST_INIT(&newindirdep->ir_deplisthd);
5953 		LIST_INIT(&newindirdep->ir_donehd);
5954 		LIST_INIT(&newindirdep->ir_writehd);
5955 		LIST_INIT(&newindirdep->ir_completehd);
5956 		if (bp->b_blkno == bp->b_lblkno) {
5957 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
5958 			    NULL, NULL);
5959 			bp->b_blkno = blkno;
5960 		}
5961 		newindirdep->ir_freeblks = NULL;
5962 		newindirdep->ir_savebp =
5963 		    getblk(ip->i_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
5964 		newindirdep->ir_bp = bp;
5965 		BUF_KERNPROC(newindirdep->ir_savebp);
5966 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
5967 		ACQUIRE_LOCK(ump);
5968 	}
5969 	indirdep = newindirdep;
5970 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
5971 	/*
5972 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
5973 	 * that we don't free dependencies until the pointers are valid.
5974 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
5975 	 * than using the hash.
5976 	 */
5977 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
5978 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
5979 	else
5980 		indirdep->ir_state |= DEPCOMPLETE;
5981 	return (indirdep);
5982 }
5983 
5984 /*
5985  * Called to finish the allocation of the "aip" allocated
5986  * by one of the two routines above.
5987  */
5988 static struct freefrag *
5989 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
5990 	struct buf *bp;		/* in-memory copy of the indirect block */
5991 	struct inode *ip;	/* inode for file being extended */
5992 	struct inodedep *inodedep; /* Inodedep for ip */
5993 	struct allocindir *aip;	/* allocindir allocated by the above routines */
5994 	ufs_lbn_t lbn;		/* Logical block number for this block. */
5995 {
5996 	struct fs *fs;
5997 	struct indirdep *indirdep;
5998 	struct allocindir *oldaip;
5999 	struct freefrag *freefrag;
6000 	struct mount *mp;
6001 
6002 	LOCK_OWNED(ip->i_ump);
6003 	mp = UFSTOVFS(ip->i_ump);
6004 	fs = ip->i_fs;
6005 	if (bp->b_lblkno >= 0)
6006 		panic("setup_allocindir_phase2: not indir blk");
6007 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6008 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6009 	indirdep = indirdep_lookup(mp, ip, bp);
6010 	KASSERT(indirdep->ir_savebp != NULL,
6011 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6012 	aip->ai_indirdep = indirdep;
6013 	/*
6014 	 * Check for an unwritten dependency for this indirect offset.  If
6015 	 * there is, merge the old dependency into the new one.  This happens
6016 	 * as a result of reallocblk only.
6017 	 */
6018 	freefrag = NULL;
6019 	if (aip->ai_oldblkno != 0) {
6020 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6021 			if (oldaip->ai_offset == aip->ai_offset) {
6022 				freefrag = allocindir_merge(aip, oldaip);
6023 				goto done;
6024 			}
6025 		}
6026 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6027 			if (oldaip->ai_offset == aip->ai_offset) {
6028 				freefrag = allocindir_merge(aip, oldaip);
6029 				goto done;
6030 			}
6031 		}
6032 	}
6033 done:
6034 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6035 	return (freefrag);
6036 }
6037 
6038 /*
6039  * Merge two allocindirs which refer to the same block.  Move newblock
6040  * dependencies and setup the freefrags appropriately.
6041  */
6042 static struct freefrag *
6043 allocindir_merge(aip, oldaip)
6044 	struct allocindir *aip;
6045 	struct allocindir *oldaip;
6046 {
6047 	struct freefrag *freefrag;
6048 	struct worklist *wk;
6049 
6050 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6051 		panic("allocindir_merge: blkno");
6052 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6053 	freefrag = aip->ai_freefrag;
6054 	aip->ai_freefrag = oldaip->ai_freefrag;
6055 	oldaip->ai_freefrag = NULL;
6056 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6057 	/*
6058 	 * If we are tracking a new directory-block allocation,
6059 	 * move it from the old allocindir to the new allocindir.
6060 	 */
6061 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6062 		WORKLIST_REMOVE(wk);
6063 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6064 			panic("allocindir_merge: extra newdirblk");
6065 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6066 	}
6067 	/*
6068 	 * We can skip journaling for this freefrag and just complete
6069 	 * any pending journal work for the allocindir that is being
6070 	 * removed after the freefrag completes.
6071 	 */
6072 	if (freefrag->ff_jdep)
6073 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6074 	LIST_REMOVE(oldaip, ai_next);
6075 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6076 	    &freefrag->ff_list, &freefrag->ff_jwork);
6077 	free_newblk(&oldaip->ai_block);
6078 
6079 	return (freefrag);
6080 }
6081 
6082 static inline void
6083 setup_freedirect(freeblks, ip, i, needj)
6084 	struct freeblks *freeblks;
6085 	struct inode *ip;
6086 	int i;
6087 	int needj;
6088 {
6089 	ufs2_daddr_t blkno;
6090 	int frags;
6091 
6092 	blkno = DIP(ip, i_db[i]);
6093 	if (blkno == 0)
6094 		return;
6095 	DIP_SET(ip, i_db[i], 0);
6096 	frags = sblksize(ip->i_fs, ip->i_size, i);
6097 	frags = numfrags(ip->i_fs, frags);
6098 	newfreework(ip->i_ump, freeblks, NULL, i, blkno, frags, 0, needj);
6099 }
6100 
6101 static inline void
6102 setup_freeext(freeblks, ip, i, needj)
6103 	struct freeblks *freeblks;
6104 	struct inode *ip;
6105 	int i;
6106 	int needj;
6107 {
6108 	ufs2_daddr_t blkno;
6109 	int frags;
6110 
6111 	blkno = ip->i_din2->di_extb[i];
6112 	if (blkno == 0)
6113 		return;
6114 	ip->i_din2->di_extb[i] = 0;
6115 	frags = sblksize(ip->i_fs, ip->i_din2->di_extsize, i);
6116 	frags = numfrags(ip->i_fs, frags);
6117 	newfreework(ip->i_ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6118 }
6119 
6120 static inline void
6121 setup_freeindir(freeblks, ip, i, lbn, needj)
6122 	struct freeblks *freeblks;
6123 	struct inode *ip;
6124 	int i;
6125 	ufs_lbn_t lbn;
6126 	int needj;
6127 {
6128 	ufs2_daddr_t blkno;
6129 
6130 	blkno = DIP(ip, i_ib[i]);
6131 	if (blkno == 0)
6132 		return;
6133 	DIP_SET(ip, i_ib[i], 0);
6134 	newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, ip->i_fs->fs_frag,
6135 	    0, needj);
6136 }
6137 
6138 static inline struct freeblks *
6139 newfreeblks(mp, ip)
6140 	struct mount *mp;
6141 	struct inode *ip;
6142 {
6143 	struct freeblks *freeblks;
6144 
6145 	freeblks = malloc(sizeof(struct freeblks),
6146 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6147 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6148 	LIST_INIT(&freeblks->fb_jblkdephd);
6149 	LIST_INIT(&freeblks->fb_jwork);
6150 	freeblks->fb_ref = 0;
6151 	freeblks->fb_cgwait = 0;
6152 	freeblks->fb_state = ATTACHED;
6153 	freeblks->fb_uid = ip->i_uid;
6154 	freeblks->fb_inum = ip->i_number;
6155 	freeblks->fb_vtype = ITOV(ip)->v_type;
6156 	freeblks->fb_modrev = DIP(ip, i_modrev);
6157 	freeblks->fb_devvp = ip->i_devvp;
6158 	freeblks->fb_chkcnt = 0;
6159 	freeblks->fb_len = 0;
6160 
6161 	return (freeblks);
6162 }
6163 
6164 static void
6165 trunc_indirdep(indirdep, freeblks, bp, off)
6166 	struct indirdep *indirdep;
6167 	struct freeblks *freeblks;
6168 	struct buf *bp;
6169 	int off;
6170 {
6171 	struct allocindir *aip, *aipn;
6172 
6173 	/*
6174 	 * The first set of allocindirs won't be in savedbp.
6175 	 */
6176 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6177 		if (aip->ai_offset > off)
6178 			cancel_allocindir(aip, bp, freeblks, 1);
6179 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6180 		if (aip->ai_offset > off)
6181 			cancel_allocindir(aip, bp, freeblks, 1);
6182 	/*
6183 	 * These will exist in savedbp.
6184 	 */
6185 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6186 		if (aip->ai_offset > off)
6187 			cancel_allocindir(aip, NULL, freeblks, 0);
6188 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6189 		if (aip->ai_offset > off)
6190 			cancel_allocindir(aip, NULL, freeblks, 0);
6191 }
6192 
6193 /*
6194  * Follow the chain of indirects down to lastlbn creating a freework
6195  * structure for each.  This will be used to start indir_trunc() at
6196  * the right offset and create the journal records for the parrtial
6197  * truncation.  A second step will handle the truncated dependencies.
6198  */
6199 static int
6200 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6201 	struct freeblks *freeblks;
6202 	struct inode *ip;
6203 	ufs_lbn_t lbn;
6204 	ufs_lbn_t lastlbn;
6205 	ufs2_daddr_t blkno;
6206 {
6207 	struct indirdep *indirdep;
6208 	struct indirdep *indirn;
6209 	struct freework *freework;
6210 	struct newblk *newblk;
6211 	struct mount *mp;
6212 	struct buf *bp;
6213 	uint8_t *start;
6214 	uint8_t *end;
6215 	ufs_lbn_t lbnadd;
6216 	int level;
6217 	int error;
6218 	int off;
6219 
6220 
6221 	freework = NULL;
6222 	if (blkno == 0)
6223 		return (0);
6224 	mp = freeblks->fb_list.wk_mp;
6225 	bp = getblk(ITOV(ip), lbn, mp->mnt_stat.f_iosize, 0, 0, 0);
6226 	if ((bp->b_flags & B_CACHE) == 0) {
6227 		bp->b_blkno = blkptrtodb(VFSTOUFS(mp), blkno);
6228 		bp->b_iocmd = BIO_READ;
6229 		bp->b_flags &= ~B_INVAL;
6230 		bp->b_ioflags &= ~BIO_ERROR;
6231 		vfs_busy_pages(bp, 0);
6232 		bp->b_iooffset = dbtob(bp->b_blkno);
6233 		bstrategy(bp);
6234 		curthread->td_ru.ru_inblock++;
6235 		error = bufwait(bp);
6236 		if (error) {
6237 			brelse(bp);
6238 			return (error);
6239 		}
6240 	}
6241 	level = lbn_level(lbn);
6242 	lbnadd = lbn_offset(ip->i_fs, level);
6243 	/*
6244 	 * Compute the offset of the last block we want to keep.  Store
6245 	 * in the freework the first block we want to completely free.
6246 	 */
6247 	off = (lastlbn - -(lbn + level)) / lbnadd;
6248 	if (off + 1 == NINDIR(ip->i_fs))
6249 		goto nowork;
6250 	freework = newfreework(ip->i_ump, freeblks, NULL, lbn, blkno, 0, off+1,
6251 	    0);
6252 	/*
6253 	 * Link the freework into the indirdep.  This will prevent any new
6254 	 * allocations from proceeding until we are finished with the
6255 	 * truncate and the block is written.
6256 	 */
6257 	ACQUIRE_LOCK(ip->i_ump);
6258 	indirdep = indirdep_lookup(mp, ip, bp);
6259 	if (indirdep->ir_freeblks)
6260 		panic("setup_trunc_indir: indirdep already truncated.");
6261 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6262 	freework->fw_indir = indirdep;
6263 	/*
6264 	 * Cancel any allocindirs that will not make it to disk.
6265 	 * We have to do this for all copies of the indirdep that
6266 	 * live on this newblk.
6267 	 */
6268 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6269 		newblk_lookup(mp, dbtofsb(ip->i_fs, bp->b_blkno), 0, &newblk);
6270 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6271 			trunc_indirdep(indirn, freeblks, bp, off);
6272 	} else
6273 		trunc_indirdep(indirdep, freeblks, bp, off);
6274 	FREE_LOCK(ip->i_ump);
6275 	/*
6276 	 * Creation is protected by the buf lock. The saveddata is only
6277 	 * needed if a full truncation follows a partial truncation but it
6278 	 * is difficult to allocate in that case so we fetch it anyway.
6279 	 */
6280 	if (indirdep->ir_saveddata == NULL)
6281 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6282 		    M_SOFTDEP_FLAGS);
6283 nowork:
6284 	/* Fetch the blkno of the child and the zero start offset. */
6285 	if (ip->i_ump->um_fstype == UFS1) {
6286 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6287 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6288 	} else {
6289 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6290 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6291 	}
6292 	if (freework) {
6293 		/* Zero the truncated pointers. */
6294 		end = bp->b_data + bp->b_bcount;
6295 		bzero(start, end - start);
6296 		bdwrite(bp);
6297 	} else
6298 		bqrelse(bp);
6299 	if (level == 0)
6300 		return (0);
6301 	lbn++; /* adjust level */
6302 	lbn -= (off * lbnadd);
6303 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6304 }
6305 
6306 /*
6307  * Complete the partial truncation of an indirect block setup by
6308  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6309  * copy and writes them to disk before the freeblks is allowed to complete.
6310  */
6311 static void
6312 complete_trunc_indir(freework)
6313 	struct freework *freework;
6314 {
6315 	struct freework *fwn;
6316 	struct indirdep *indirdep;
6317 	struct ufsmount *ump;
6318 	struct buf *bp;
6319 	uintptr_t start;
6320 	int count;
6321 
6322 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6323 	LOCK_OWNED(ump);
6324 	indirdep = freework->fw_indir;
6325 	for (;;) {
6326 		bp = indirdep->ir_bp;
6327 		/* See if the block was discarded. */
6328 		if (bp == NULL)
6329 			break;
6330 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6331 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6332 			break;
6333 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6334 		    LOCK_PTR(ump)) == 0)
6335 			BUF_UNLOCK(bp);
6336 		ACQUIRE_LOCK(ump);
6337 	}
6338 	freework->fw_state |= DEPCOMPLETE;
6339 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6340 	/*
6341 	 * Zero the pointers in the saved copy.
6342 	 */
6343 	if (indirdep->ir_state & UFS1FMT)
6344 		start = sizeof(ufs1_daddr_t);
6345 	else
6346 		start = sizeof(ufs2_daddr_t);
6347 	start *= freework->fw_start;
6348 	count = indirdep->ir_savebp->b_bcount - start;
6349 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6350 	bzero((char *)start, count);
6351 	/*
6352 	 * We need to start the next truncation in the list if it has not
6353 	 * been started yet.
6354 	 */
6355 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6356 	if (fwn != NULL) {
6357 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6358 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6359 		if ((fwn->fw_state & ONWORKLIST) == 0)
6360 			freework_enqueue(fwn);
6361 	}
6362 	/*
6363 	 * If bp is NULL the block was fully truncated, restore
6364 	 * the saved block list otherwise free it if it is no
6365 	 * longer needed.
6366 	 */
6367 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6368 		if (bp == NULL)
6369 			bcopy(indirdep->ir_saveddata,
6370 			    indirdep->ir_savebp->b_data,
6371 			    indirdep->ir_savebp->b_bcount);
6372 		free(indirdep->ir_saveddata, M_INDIRDEP);
6373 		indirdep->ir_saveddata = NULL;
6374 	}
6375 	/*
6376 	 * When bp is NULL there is a full truncation pending.  We
6377 	 * must wait for this full truncation to be journaled before
6378 	 * we can release this freework because the disk pointers will
6379 	 * never be written as zero.
6380 	 */
6381 	if (bp == NULL)  {
6382 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6383 			handle_written_freework(freework);
6384 		else
6385 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6386 			   &freework->fw_list);
6387 	} else {
6388 		/* Complete when the real copy is written. */
6389 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6390 		BUF_UNLOCK(bp);
6391 	}
6392 }
6393 
6394 /*
6395  * Calculate the number of blocks we are going to release where datablocks
6396  * is the current total and length is the new file size.
6397  */
6398 static ufs2_daddr_t
6399 blkcount(fs, datablocks, length)
6400 	struct fs *fs;
6401 	ufs2_daddr_t datablocks;
6402 	off_t length;
6403 {
6404 	off_t totblks, numblks;
6405 
6406 	totblks = 0;
6407 	numblks = howmany(length, fs->fs_bsize);
6408 	if (numblks <= NDADDR) {
6409 		totblks = howmany(length, fs->fs_fsize);
6410 		goto out;
6411 	}
6412         totblks = blkstofrags(fs, numblks);
6413 	numblks -= NDADDR;
6414 	/*
6415 	 * Count all single, then double, then triple indirects required.
6416 	 * Subtracting one indirects worth of blocks for each pass
6417 	 * acknowledges one of each pointed to by the inode.
6418 	 */
6419 	for (;;) {
6420 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6421 		numblks -= NINDIR(fs);
6422 		if (numblks <= 0)
6423 			break;
6424 		numblks = howmany(numblks, NINDIR(fs));
6425 	}
6426 out:
6427 	totblks = fsbtodb(fs, totblks);
6428 	/*
6429 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6430 	 * references.  We will correct it later in handle_complete_freeblks()
6431 	 * when we know the real count.
6432 	 */
6433 	if (totblks > datablocks)
6434 		return (0);
6435 	return (datablocks - totblks);
6436 }
6437 
6438 /*
6439  * Handle freeblocks for journaled softupdate filesystems.
6440  *
6441  * Contrary to normal softupdates, we must preserve the block pointers in
6442  * indirects until their subordinates are free.  This is to avoid journaling
6443  * every block that is freed which may consume more space than the journal
6444  * itself.  The recovery program will see the free block journals at the
6445  * base of the truncated area and traverse them to reclaim space.  The
6446  * pointers in the inode may be cleared immediately after the journal
6447  * records are written because each direct and indirect pointer in the
6448  * inode is recorded in a journal.  This permits full truncation to proceed
6449  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6450  *
6451  * The algorithm is as follows:
6452  * 1) Traverse the in-memory state and create journal entries to release
6453  *    the relevant blocks and full indirect trees.
6454  * 2) Traverse the indirect block chain adding partial truncation freework
6455  *    records to indirects in the path to lastlbn.  The freework will
6456  *    prevent new allocation dependencies from being satisfied in this
6457  *    indirect until the truncation completes.
6458  * 3) Read and lock the inode block, performing an update with the new size
6459  *    and pointers.  This prevents truncated data from becoming valid on
6460  *    disk through step 4.
6461  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6462  *    eliminate journal work for those records that do not require it.
6463  * 5) Schedule the journal records to be written followed by the inode block.
6464  * 6) Allocate any necessary frags for the end of file.
6465  * 7) Zero any partially truncated blocks.
6466  *
6467  * From this truncation proceeds asynchronously using the freework and
6468  * indir_trunc machinery.  The file will not be extended again into a
6469  * partially truncated indirect block until all work is completed but
6470  * the normal dependency mechanism ensures that it is rolled back/forward
6471  * as appropriate.  Further truncation may occur without delay and is
6472  * serialized in indir_trunc().
6473  */
6474 void
6475 softdep_journal_freeblocks(ip, cred, length, flags)
6476 	struct inode *ip;	/* The inode whose length is to be reduced */
6477 	struct ucred *cred;
6478 	off_t length;		/* The new length for the file */
6479 	int flags;		/* IO_EXT and/or IO_NORMAL */
6480 {
6481 	struct freeblks *freeblks, *fbn;
6482 	struct worklist *wk, *wkn;
6483 	struct inodedep *inodedep;
6484 	struct jblkdep *jblkdep;
6485 	struct allocdirect *adp, *adpn;
6486 	struct ufsmount *ump;
6487 	struct fs *fs;
6488 	struct buf *bp;
6489 	struct vnode *vp;
6490 	struct mount *mp;
6491 	ufs2_daddr_t extblocks, datablocks;
6492 	ufs_lbn_t tmpval, lbn, lastlbn;
6493 	int frags, lastoff, iboff, allocblock, needj, dflags, error, i;
6494 
6495 	fs = ip->i_fs;
6496 	ump = ip->i_ump;
6497 	mp = UFSTOVFS(ump);
6498 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6499 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6500 	vp = ITOV(ip);
6501 	needj = 1;
6502 	iboff = -1;
6503 	allocblock = 0;
6504 	extblocks = 0;
6505 	datablocks = 0;
6506 	frags = 0;
6507 	freeblks = newfreeblks(mp, ip);
6508 	ACQUIRE_LOCK(ump);
6509 	/*
6510 	 * If we're truncating a removed file that will never be written
6511 	 * we don't need to journal the block frees.  The canceled journals
6512 	 * for the allocations will suffice.
6513 	 */
6514 	dflags = DEPALLOC;
6515 	if (IS_SNAPSHOT(ip))
6516 		dflags |= NODELAY;
6517 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6518 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6519 	    length == 0)
6520 		needj = 0;
6521 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6522 	    ip->i_number, length, needj);
6523 	FREE_LOCK(ump);
6524 	/*
6525 	 * Calculate the lbn that we are truncating to.  This results in -1
6526 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6527 	 * to keep, not the first lbn we want to truncate.
6528 	 */
6529 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6530 	lastoff = blkoff(fs, length);
6531 	/*
6532 	 * Compute frags we are keeping in lastlbn.  0 means all.
6533 	 */
6534 	if (lastlbn >= 0 && lastlbn < NDADDR) {
6535 		frags = fragroundup(fs, lastoff);
6536 		/* adp offset of last valid allocdirect. */
6537 		iboff = lastlbn;
6538 	} else if (lastlbn > 0)
6539 		iboff = NDADDR;
6540 	if (fs->fs_magic == FS_UFS2_MAGIC)
6541 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6542 	/*
6543 	 * Handle normal data blocks and indirects.  This section saves
6544 	 * values used after the inode update to complete frag and indirect
6545 	 * truncation.
6546 	 */
6547 	if ((flags & IO_NORMAL) != 0) {
6548 		/*
6549 		 * Handle truncation of whole direct and indirect blocks.
6550 		 */
6551 		for (i = iboff + 1; i < NDADDR; i++)
6552 			setup_freedirect(freeblks, ip, i, needj);
6553 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6554 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6555 			/* Release a whole indirect tree. */
6556 			if (lbn > lastlbn) {
6557 				setup_freeindir(freeblks, ip, i, -lbn -i,
6558 				    needj);
6559 				continue;
6560 			}
6561 			iboff = i + NDADDR;
6562 			/*
6563 			 * Traverse partially truncated indirect tree.
6564 			 */
6565 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6566 				setup_trunc_indir(freeblks, ip, -lbn - i,
6567 				    lastlbn, DIP(ip, i_ib[i]));
6568 		}
6569 		/*
6570 		 * Handle partial truncation to a frag boundary.
6571 		 */
6572 		if (frags) {
6573 			ufs2_daddr_t blkno;
6574 			long oldfrags;
6575 
6576 			oldfrags = blksize(fs, ip, lastlbn);
6577 			blkno = DIP(ip, i_db[lastlbn]);
6578 			if (blkno && oldfrags != frags) {
6579 				oldfrags -= frags;
6580 				oldfrags = numfrags(ip->i_fs, oldfrags);
6581 				blkno += numfrags(ip->i_fs, frags);
6582 				newfreework(ump, freeblks, NULL, lastlbn,
6583 				    blkno, oldfrags, 0, needj);
6584 				if (needj)
6585 					adjust_newfreework(freeblks,
6586 					    numfrags(ip->i_fs, frags));
6587 			} else if (blkno == 0)
6588 				allocblock = 1;
6589 		}
6590 		/*
6591 		 * Add a journal record for partial truncate if we are
6592 		 * handling indirect blocks.  Non-indirects need no extra
6593 		 * journaling.
6594 		 */
6595 		if (length != 0 && lastlbn >= NDADDR) {
6596 			ip->i_flag |= IN_TRUNCATED;
6597 			newjtrunc(freeblks, length, 0);
6598 		}
6599 		ip->i_size = length;
6600 		DIP_SET(ip, i_size, ip->i_size);
6601 		datablocks = DIP(ip, i_blocks) - extblocks;
6602 		if (length != 0)
6603 			datablocks = blkcount(ip->i_fs, datablocks, length);
6604 		freeblks->fb_len = length;
6605 	}
6606 	if ((flags & IO_EXT) != 0) {
6607 		for (i = 0; i < NXADDR; i++)
6608 			setup_freeext(freeblks, ip, i, needj);
6609 		ip->i_din2->di_extsize = 0;
6610 		datablocks += extblocks;
6611 	}
6612 #ifdef QUOTA
6613 	/* Reference the quotas in case the block count is wrong in the end. */
6614 	quotaref(vp, freeblks->fb_quota);
6615 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6616 #endif
6617 	freeblks->fb_chkcnt = -datablocks;
6618 	UFS_LOCK(ump);
6619 	fs->fs_pendingblocks += datablocks;
6620 	UFS_UNLOCK(ump);
6621 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6622 	/*
6623 	 * Handle truncation of incomplete alloc direct dependencies.  We
6624 	 * hold the inode block locked to prevent incomplete dependencies
6625 	 * from reaching the disk while we are eliminating those that
6626 	 * have been truncated.  This is a partially inlined ffs_update().
6627 	 */
6628 	ufs_itimes(vp);
6629 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
6630 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6631 	    (int)fs->fs_bsize, cred, &bp);
6632 	if (error) {
6633 		brelse(bp);
6634 		softdep_error("softdep_journal_freeblocks", error);
6635 		return;
6636 	}
6637 	if (bp->b_bufsize == fs->fs_bsize)
6638 		bp->b_flags |= B_CLUSTEROK;
6639 	softdep_update_inodeblock(ip, bp, 0);
6640 	if (ump->um_fstype == UFS1)
6641 		*((struct ufs1_dinode *)bp->b_data +
6642 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
6643 	else
6644 		*((struct ufs2_dinode *)bp->b_data +
6645 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
6646 	ACQUIRE_LOCK(ump);
6647 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6648 	if ((inodedep->id_state & IOSTARTED) != 0)
6649 		panic("softdep_setup_freeblocks: inode busy");
6650 	/*
6651 	 * Add the freeblks structure to the list of operations that
6652 	 * must await the zero'ed inode being written to disk. If we
6653 	 * still have a bitmap dependency (needj), then the inode
6654 	 * has never been written to disk, so we can process the
6655 	 * freeblks below once we have deleted the dependencies.
6656 	 */
6657 	if (needj)
6658 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6659 	else
6660 		freeblks->fb_state |= COMPLETE;
6661 	if ((flags & IO_NORMAL) != 0) {
6662 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
6663 			if (adp->ad_offset > iboff)
6664 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
6665 				    freeblks);
6666 			/*
6667 			 * Truncate the allocdirect.  We could eliminate
6668 			 * or modify journal records as well.
6669 			 */
6670 			else if (adp->ad_offset == iboff && frags)
6671 				adp->ad_newsize = frags;
6672 		}
6673 	}
6674 	if ((flags & IO_EXT) != 0)
6675 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6676 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6677 			    freeblks);
6678 	/*
6679 	 * Scan the bufwait list for newblock dependencies that will never
6680 	 * make it to disk.
6681 	 */
6682 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
6683 		if (wk->wk_type != D_ALLOCDIRECT)
6684 			continue;
6685 		adp = WK_ALLOCDIRECT(wk);
6686 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
6687 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
6688 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
6689 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
6690 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
6691 		}
6692 	}
6693 	/*
6694 	 * Add journal work.
6695 	 */
6696 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
6697 		add_to_journal(&jblkdep->jb_list);
6698 	FREE_LOCK(ump);
6699 	bdwrite(bp);
6700 	/*
6701 	 * Truncate dependency structures beyond length.
6702 	 */
6703 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
6704 	/*
6705 	 * This is only set when we need to allocate a fragment because
6706 	 * none existed at the end of a frag-sized file.  It handles only
6707 	 * allocating a new, zero filled block.
6708 	 */
6709 	if (allocblock) {
6710 		ip->i_size = length - lastoff;
6711 		DIP_SET(ip, i_size, ip->i_size);
6712 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
6713 		if (error != 0) {
6714 			softdep_error("softdep_journal_freeblks", error);
6715 			return;
6716 		}
6717 		ip->i_size = length;
6718 		DIP_SET(ip, i_size, length);
6719 		ip->i_flag |= IN_CHANGE | IN_UPDATE;
6720 		allocbuf(bp, frags);
6721 		ffs_update(vp, 0);
6722 		bawrite(bp);
6723 	} else if (lastoff != 0 && vp->v_type != VDIR) {
6724 		int size;
6725 
6726 		/*
6727 		 * Zero the end of a truncated frag or block.
6728 		 */
6729 		size = sblksize(fs, length, lastlbn);
6730 		error = bread(vp, lastlbn, size, cred, &bp);
6731 		if (error) {
6732 			softdep_error("softdep_journal_freeblks", error);
6733 			return;
6734 		}
6735 		bzero((char *)bp->b_data + lastoff, size - lastoff);
6736 		bawrite(bp);
6737 
6738 	}
6739 	ACQUIRE_LOCK(ump);
6740 	inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6741 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
6742 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
6743 	/*
6744 	 * We zero earlier truncations so they don't erroneously
6745 	 * update i_blocks.
6746 	 */
6747 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
6748 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
6749 			fbn->fb_len = 0;
6750 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
6751 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
6752 		freeblks->fb_state |= INPROGRESS;
6753 	else
6754 		freeblks = NULL;
6755 	FREE_LOCK(ump);
6756 	if (freeblks)
6757 		handle_workitem_freeblocks(freeblks, 0);
6758 	trunc_pages(ip, length, extblocks, flags);
6759 
6760 }
6761 
6762 /*
6763  * Flush a JOP_SYNC to the journal.
6764  */
6765 void
6766 softdep_journal_fsync(ip)
6767 	struct inode *ip;
6768 {
6769 	struct jfsync *jfsync;
6770 
6771 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
6772 	    ("softdep_journal_fsync called on non-softdep filesystem"));
6773 	if ((ip->i_flag & IN_TRUNCATED) == 0)
6774 		return;
6775 	ip->i_flag &= ~IN_TRUNCATED;
6776 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
6777 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ip->i_ump));
6778 	jfsync->jfs_size = ip->i_size;
6779 	jfsync->jfs_ino = ip->i_number;
6780 	ACQUIRE_LOCK(ip->i_ump);
6781 	add_to_journal(&jfsync->jfs_list);
6782 	jwait(&jfsync->jfs_list, MNT_WAIT);
6783 	FREE_LOCK(ip->i_ump);
6784 }
6785 
6786 /*
6787  * Block de-allocation dependencies.
6788  *
6789  * When blocks are de-allocated, the on-disk pointers must be nullified before
6790  * the blocks are made available for use by other files.  (The true
6791  * requirement is that old pointers must be nullified before new on-disk
6792  * pointers are set.  We chose this slightly more stringent requirement to
6793  * reduce complexity.) Our implementation handles this dependency by updating
6794  * the inode (or indirect block) appropriately but delaying the actual block
6795  * de-allocation (i.e., freemap and free space count manipulation) until
6796  * after the updated versions reach stable storage.  After the disk is
6797  * updated, the blocks can be safely de-allocated whenever it is convenient.
6798  * This implementation handles only the common case of reducing a file's
6799  * length to zero. Other cases are handled by the conventional synchronous
6800  * write approach.
6801  *
6802  * The ffs implementation with which we worked double-checks
6803  * the state of the block pointers and file size as it reduces
6804  * a file's length.  Some of this code is replicated here in our
6805  * soft updates implementation.  The freeblks->fb_chkcnt field is
6806  * used to transfer a part of this information to the procedure
6807  * that eventually de-allocates the blocks.
6808  *
6809  * This routine should be called from the routine that shortens
6810  * a file's length, before the inode's size or block pointers
6811  * are modified. It will save the block pointer information for
6812  * later release and zero the inode so that the calling routine
6813  * can release it.
6814  */
6815 void
6816 softdep_setup_freeblocks(ip, length, flags)
6817 	struct inode *ip;	/* The inode whose length is to be reduced */
6818 	off_t length;		/* The new length for the file */
6819 	int flags;		/* IO_EXT and/or IO_NORMAL */
6820 {
6821 	struct ufs1_dinode *dp1;
6822 	struct ufs2_dinode *dp2;
6823 	struct freeblks *freeblks;
6824 	struct inodedep *inodedep;
6825 	struct allocdirect *adp;
6826 	struct ufsmount *ump;
6827 	struct buf *bp;
6828 	struct fs *fs;
6829 	ufs2_daddr_t extblocks, datablocks;
6830 	struct mount *mp;
6831 	int i, delay, error, dflags;
6832 	ufs_lbn_t tmpval;
6833 	ufs_lbn_t lbn;
6834 
6835 	ump = ip->i_ump;
6836 	mp = UFSTOVFS(ump);
6837 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6838 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
6839 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
6840 	    ip->i_number, length);
6841 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
6842 	fs = ip->i_fs;
6843 	freeblks = newfreeblks(mp, ip);
6844 	extblocks = 0;
6845 	datablocks = 0;
6846 	if (fs->fs_magic == FS_UFS2_MAGIC)
6847 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6848 	if ((flags & IO_NORMAL) != 0) {
6849 		for (i = 0; i < NDADDR; i++)
6850 			setup_freedirect(freeblks, ip, i, 0);
6851 		for (i = 0, tmpval = NINDIR(fs), lbn = NDADDR; i < NIADDR;
6852 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
6853 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
6854 		ip->i_size = 0;
6855 		DIP_SET(ip, i_size, 0);
6856 		datablocks = DIP(ip, i_blocks) - extblocks;
6857 	}
6858 	if ((flags & IO_EXT) != 0) {
6859 		for (i = 0; i < NXADDR; i++)
6860 			setup_freeext(freeblks, ip, i, 0);
6861 		ip->i_din2->di_extsize = 0;
6862 		datablocks += extblocks;
6863 	}
6864 #ifdef QUOTA
6865 	/* Reference the quotas in case the block count is wrong in the end. */
6866 	quotaref(ITOV(ip), freeblks->fb_quota);
6867 	(void) chkdq(ip, -datablocks, NOCRED, 0);
6868 #endif
6869 	freeblks->fb_chkcnt = -datablocks;
6870 	UFS_LOCK(ump);
6871 	fs->fs_pendingblocks += datablocks;
6872 	UFS_UNLOCK(ump);
6873 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
6874 	/*
6875 	 * Push the zero'ed inode to to its disk buffer so that we are free
6876 	 * to delete its dependencies below. Once the dependencies are gone
6877 	 * the buffer can be safely released.
6878 	 */
6879 	if ((error = bread(ip->i_devvp,
6880 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
6881 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
6882 		brelse(bp);
6883 		softdep_error("softdep_setup_freeblocks", error);
6884 	}
6885 	if (ump->um_fstype == UFS1) {
6886 		dp1 = ((struct ufs1_dinode *)bp->b_data +
6887 		    ino_to_fsbo(fs, ip->i_number));
6888 		ip->i_din1->di_freelink = dp1->di_freelink;
6889 		*dp1 = *ip->i_din1;
6890 	} else {
6891 		dp2 = ((struct ufs2_dinode *)bp->b_data +
6892 		    ino_to_fsbo(fs, ip->i_number));
6893 		ip->i_din2->di_freelink = dp2->di_freelink;
6894 		*dp2 = *ip->i_din2;
6895 	}
6896 	/*
6897 	 * Find and eliminate any inode dependencies.
6898 	 */
6899 	ACQUIRE_LOCK(ump);
6900 	dflags = DEPALLOC;
6901 	if (IS_SNAPSHOT(ip))
6902 		dflags |= NODELAY;
6903 	(void) inodedep_lookup(mp, ip->i_number, dflags, &inodedep);
6904 	if ((inodedep->id_state & IOSTARTED) != 0)
6905 		panic("softdep_setup_freeblocks: inode busy");
6906 	/*
6907 	 * Add the freeblks structure to the list of operations that
6908 	 * must await the zero'ed inode being written to disk. If we
6909 	 * still have a bitmap dependency (delay == 0), then the inode
6910 	 * has never been written to disk, so we can process the
6911 	 * freeblks below once we have deleted the dependencies.
6912 	 */
6913 	delay = (inodedep->id_state & DEPCOMPLETE);
6914 	if (delay)
6915 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
6916 	else
6917 		freeblks->fb_state |= COMPLETE;
6918 	/*
6919 	 * Because the file length has been truncated to zero, any
6920 	 * pending block allocation dependency structures associated
6921 	 * with this inode are obsolete and can simply be de-allocated.
6922 	 * We must first merge the two dependency lists to get rid of
6923 	 * any duplicate freefrag structures, then purge the merged list.
6924 	 * If we still have a bitmap dependency, then the inode has never
6925 	 * been written to disk, so we can free any fragments without delay.
6926 	 */
6927 	if (flags & IO_NORMAL) {
6928 		merge_inode_lists(&inodedep->id_newinoupdt,
6929 		    &inodedep->id_inoupdt);
6930 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != 0)
6931 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
6932 			    freeblks);
6933 	}
6934 	if (flags & IO_EXT) {
6935 		merge_inode_lists(&inodedep->id_newextupdt,
6936 		    &inodedep->id_extupdt);
6937 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != 0)
6938 			cancel_allocdirect(&inodedep->id_extupdt, adp,
6939 			    freeblks);
6940 	}
6941 	FREE_LOCK(ump);
6942 	bdwrite(bp);
6943 	trunc_dependencies(ip, freeblks, -1, 0, flags);
6944 	ACQUIRE_LOCK(ump);
6945 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
6946 		(void) free_inodedep(inodedep);
6947 	freeblks->fb_state |= DEPCOMPLETE;
6948 	/*
6949 	 * If the inode with zeroed block pointers is now on disk
6950 	 * we can start freeing blocks.
6951 	 */
6952 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
6953 		freeblks->fb_state |= INPROGRESS;
6954 	else
6955 		freeblks = NULL;
6956 	FREE_LOCK(ump);
6957 	if (freeblks)
6958 		handle_workitem_freeblocks(freeblks, 0);
6959 	trunc_pages(ip, length, extblocks, flags);
6960 }
6961 
6962 /*
6963  * Eliminate pages from the page cache that back parts of this inode and
6964  * adjust the vnode pager's idea of our size.  This prevents stale data
6965  * from hanging around in the page cache.
6966  */
6967 static void
6968 trunc_pages(ip, length, extblocks, flags)
6969 	struct inode *ip;
6970 	off_t length;
6971 	ufs2_daddr_t extblocks;
6972 	int flags;
6973 {
6974 	struct vnode *vp;
6975 	struct fs *fs;
6976 	ufs_lbn_t lbn;
6977 	off_t end, extend;
6978 
6979 	vp = ITOV(ip);
6980 	fs = ip->i_fs;
6981 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
6982 	if ((flags & IO_EXT) != 0)
6983 		vn_pages_remove(vp, extend, 0);
6984 	if ((flags & IO_NORMAL) == 0)
6985 		return;
6986 	BO_LOCK(&vp->v_bufobj);
6987 	drain_output(vp);
6988 	BO_UNLOCK(&vp->v_bufobj);
6989 	/*
6990 	 * The vnode pager eliminates file pages we eliminate indirects
6991 	 * below.
6992 	 */
6993 	vnode_pager_setsize(vp, length);
6994 	/*
6995 	 * Calculate the end based on the last indirect we want to keep.  If
6996 	 * the block extends into indirects we can just use the negative of
6997 	 * its lbn.  Doubles and triples exist at lower numbers so we must
6998 	 * be careful not to remove those, if they exist.  double and triple
6999 	 * indirect lbns do not overlap with others so it is not important
7000 	 * to verify how many levels are required.
7001 	 */
7002 	lbn = lblkno(fs, length);
7003 	if (lbn >= NDADDR) {
7004 		/* Calculate the virtual lbn of the triple indirect. */
7005 		lbn = -lbn - (NIADDR - 1);
7006 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7007 	} else
7008 		end = extend;
7009 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7010 }
7011 
7012 /*
7013  * See if the buf bp is in the range eliminated by truncation.
7014  */
7015 static int
7016 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7017 	struct buf *bp;
7018 	int *blkoffp;
7019 	ufs_lbn_t lastlbn;
7020 	int lastoff;
7021 	int flags;
7022 {
7023 	ufs_lbn_t lbn;
7024 
7025 	*blkoffp = 0;
7026 	/* Only match ext/normal blocks as appropriate. */
7027 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7028 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7029 		return (0);
7030 	/* ALTDATA is always a full truncation. */
7031 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7032 		return (1);
7033 	/* -1 is full truncation. */
7034 	if (lastlbn == -1)
7035 		return (1);
7036 	/*
7037 	 * If this is a partial truncate we only want those
7038 	 * blocks and indirect blocks that cover the range
7039 	 * we're after.
7040 	 */
7041 	lbn = bp->b_lblkno;
7042 	if (lbn < 0)
7043 		lbn = -(lbn + lbn_level(lbn));
7044 	if (lbn < lastlbn)
7045 		return (0);
7046 	/* Here we only truncate lblkno if it's partial. */
7047 	if (lbn == lastlbn) {
7048 		if (lastoff == 0)
7049 			return (0);
7050 		*blkoffp = lastoff;
7051 	}
7052 	return (1);
7053 }
7054 
7055 /*
7056  * Eliminate any dependencies that exist in memory beyond lblkno:off
7057  */
7058 static void
7059 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7060 	struct inode *ip;
7061 	struct freeblks *freeblks;
7062 	ufs_lbn_t lastlbn;
7063 	int lastoff;
7064 	int flags;
7065 {
7066 	struct bufobj *bo;
7067 	struct vnode *vp;
7068 	struct buf *bp;
7069 	struct fs *fs;
7070 	int blkoff;
7071 
7072 	/*
7073 	 * We must wait for any I/O in progress to finish so that
7074 	 * all potential buffers on the dirty list will be visible.
7075 	 * Once they are all there, walk the list and get rid of
7076 	 * any dependencies.
7077 	 */
7078 	fs = ip->i_fs;
7079 	vp = ITOV(ip);
7080 	bo = &vp->v_bufobj;
7081 	BO_LOCK(bo);
7082 	drain_output(vp);
7083 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7084 		bp->b_vflags &= ~BV_SCANNED;
7085 restart:
7086 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7087 		if (bp->b_vflags & BV_SCANNED)
7088 			continue;
7089 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7090 			bp->b_vflags |= BV_SCANNED;
7091 			continue;
7092 		}
7093 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7094 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7095 			goto restart;
7096 		BO_UNLOCK(bo);
7097 		if (deallocate_dependencies(bp, freeblks, blkoff))
7098 			bqrelse(bp);
7099 		else
7100 			brelse(bp);
7101 		BO_LOCK(bo);
7102 		goto restart;
7103 	}
7104 	/*
7105 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7106 	 */
7107 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7108 		bp->b_vflags &= ~BV_SCANNED;
7109 cleanrestart:
7110 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7111 		if (bp->b_vflags & BV_SCANNED)
7112 			continue;
7113 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7114 			bp->b_vflags |= BV_SCANNED;
7115 			continue;
7116 		}
7117 		if (BUF_LOCK(bp,
7118 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7119 		    BO_LOCKPTR(bo)) == ENOLCK) {
7120 			BO_LOCK(bo);
7121 			goto cleanrestart;
7122 		}
7123 		bp->b_vflags |= BV_SCANNED;
7124 		bremfree(bp);
7125 		if (blkoff != 0) {
7126 			allocbuf(bp, blkoff);
7127 			bqrelse(bp);
7128 		} else {
7129 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7130 			brelse(bp);
7131 		}
7132 		BO_LOCK(bo);
7133 		goto cleanrestart;
7134 	}
7135 	drain_output(vp);
7136 	BO_UNLOCK(bo);
7137 }
7138 
7139 static int
7140 cancel_pagedep(pagedep, freeblks, blkoff)
7141 	struct pagedep *pagedep;
7142 	struct freeblks *freeblks;
7143 	int blkoff;
7144 {
7145 	struct jremref *jremref;
7146 	struct jmvref *jmvref;
7147 	struct dirrem *dirrem, *tmp;
7148 	int i;
7149 
7150 	/*
7151 	 * Copy any directory remove dependencies to the list
7152 	 * to be processed after the freeblks proceeds.  If
7153 	 * directory entry never made it to disk they
7154 	 * can be dumped directly onto the work list.
7155 	 */
7156 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7157 		/* Skip this directory removal if it is intended to remain. */
7158 		if (dirrem->dm_offset < blkoff)
7159 			continue;
7160 		/*
7161 		 * If there are any dirrems we wait for the journal write
7162 		 * to complete and then restart the buf scan as the lock
7163 		 * has been dropped.
7164 		 */
7165 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7166 			jwait(&jremref->jr_list, MNT_WAIT);
7167 			return (ERESTART);
7168 		}
7169 		LIST_REMOVE(dirrem, dm_next);
7170 		dirrem->dm_dirinum = pagedep->pd_ino;
7171 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7172 	}
7173 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7174 		jwait(&jmvref->jm_list, MNT_WAIT);
7175 		return (ERESTART);
7176 	}
7177 	/*
7178 	 * When we're partially truncating a pagedep we just want to flush
7179 	 * journal entries and return.  There can not be any adds in the
7180 	 * truncated portion of the directory and newblk must remain if
7181 	 * part of the block remains.
7182 	 */
7183 	if (blkoff != 0) {
7184 		struct diradd *dap;
7185 
7186 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7187 			if (dap->da_offset > blkoff)
7188 				panic("cancel_pagedep: diradd %p off %d > %d",
7189 				    dap, dap->da_offset, blkoff);
7190 		for (i = 0; i < DAHASHSZ; i++)
7191 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7192 				if (dap->da_offset > blkoff)
7193 					panic("cancel_pagedep: diradd %p off %d > %d",
7194 					    dap, dap->da_offset, blkoff);
7195 		return (0);
7196 	}
7197 	/*
7198 	 * There should be no directory add dependencies present
7199 	 * as the directory could not be truncated until all
7200 	 * children were removed.
7201 	 */
7202 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7203 	    ("deallocate_dependencies: pendinghd != NULL"));
7204 	for (i = 0; i < DAHASHSZ; i++)
7205 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7206 		    ("deallocate_dependencies: diraddhd != NULL"));
7207 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7208 		free_newdirblk(pagedep->pd_newdirblk);
7209 	if (free_pagedep(pagedep) == 0)
7210 		panic("Failed to free pagedep %p", pagedep);
7211 	return (0);
7212 }
7213 
7214 /*
7215  * Reclaim any dependency structures from a buffer that is about to
7216  * be reallocated to a new vnode. The buffer must be locked, thus,
7217  * no I/O completion operations can occur while we are manipulating
7218  * its associated dependencies. The mutex is held so that other I/O's
7219  * associated with related dependencies do not occur.
7220  */
7221 static int
7222 deallocate_dependencies(bp, freeblks, off)
7223 	struct buf *bp;
7224 	struct freeblks *freeblks;
7225 	int off;
7226 {
7227 	struct indirdep *indirdep;
7228 	struct pagedep *pagedep;
7229 	struct allocdirect *adp;
7230 	struct worklist *wk, *wkn;
7231 	struct ufsmount *ump;
7232 
7233 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
7234 		goto done;
7235 	ump = VFSTOUFS(wk->wk_mp);
7236 	ACQUIRE_LOCK(ump);
7237 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7238 		switch (wk->wk_type) {
7239 		case D_INDIRDEP:
7240 			indirdep = WK_INDIRDEP(wk);
7241 			if (bp->b_lblkno >= 0 ||
7242 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7243 				panic("deallocate_dependencies: not indir");
7244 			cancel_indirdep(indirdep, bp, freeblks);
7245 			continue;
7246 
7247 		case D_PAGEDEP:
7248 			pagedep = WK_PAGEDEP(wk);
7249 			if (cancel_pagedep(pagedep, freeblks, off)) {
7250 				FREE_LOCK(ump);
7251 				return (ERESTART);
7252 			}
7253 			continue;
7254 
7255 		case D_ALLOCINDIR:
7256 			/*
7257 			 * Simply remove the allocindir, we'll find it via
7258 			 * the indirdep where we can clear pointers if
7259 			 * needed.
7260 			 */
7261 			WORKLIST_REMOVE(wk);
7262 			continue;
7263 
7264 		case D_FREEWORK:
7265 			/*
7266 			 * A truncation is waiting for the zero'd pointers
7267 			 * to be written.  It can be freed when the freeblks
7268 			 * is journaled.
7269 			 */
7270 			WORKLIST_REMOVE(wk);
7271 			wk->wk_state |= ONDEPLIST;
7272 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7273 			break;
7274 
7275 		case D_ALLOCDIRECT:
7276 			adp = WK_ALLOCDIRECT(wk);
7277 			if (off != 0)
7278 				continue;
7279 			/* FALLTHROUGH */
7280 		default:
7281 			panic("deallocate_dependencies: Unexpected type %s",
7282 			    TYPENAME(wk->wk_type));
7283 			/* NOTREACHED */
7284 		}
7285 	}
7286 	FREE_LOCK(ump);
7287 done:
7288 	/*
7289 	 * Don't throw away this buf, we were partially truncating and
7290 	 * some deps may always remain.
7291 	 */
7292 	if (off) {
7293 		allocbuf(bp, off);
7294 		bp->b_vflags |= BV_SCANNED;
7295 		return (EBUSY);
7296 	}
7297 	bp->b_flags |= B_INVAL | B_NOCACHE;
7298 
7299 	return (0);
7300 }
7301 
7302 /*
7303  * An allocdirect is being canceled due to a truncate.  We must make sure
7304  * the journal entry is released in concert with the blkfree that releases
7305  * the storage.  Completed journal entries must not be released until the
7306  * space is no longer pointed to by the inode or in the bitmap.
7307  */
7308 static void
7309 cancel_allocdirect(adphead, adp, freeblks)
7310 	struct allocdirectlst *adphead;
7311 	struct allocdirect *adp;
7312 	struct freeblks *freeblks;
7313 {
7314 	struct freework *freework;
7315 	struct newblk *newblk;
7316 	struct worklist *wk;
7317 
7318 	TAILQ_REMOVE(adphead, adp, ad_next);
7319 	newblk = (struct newblk *)adp;
7320 	freework = NULL;
7321 	/*
7322 	 * Find the correct freework structure.
7323 	 */
7324 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7325 		if (wk->wk_type != D_FREEWORK)
7326 			continue;
7327 		freework = WK_FREEWORK(wk);
7328 		if (freework->fw_blkno == newblk->nb_newblkno)
7329 			break;
7330 	}
7331 	if (freework == NULL)
7332 		panic("cancel_allocdirect: Freework not found");
7333 	/*
7334 	 * If a newblk exists at all we still have the journal entry that
7335 	 * initiated the allocation so we do not need to journal the free.
7336 	 */
7337 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7338 	/*
7339 	 * If the journal hasn't been written the jnewblk must be passed
7340 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7341 	 * this by linking the journal dependency into the freework to be
7342 	 * freed when freework_freeblock() is called.  If the journal has
7343 	 * been written we can simply reclaim the journal space when the
7344 	 * freeblks work is complete.
7345 	 */
7346 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7347 	    &freeblks->fb_jwork);
7348 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7349 }
7350 
7351 
7352 /*
7353  * Cancel a new block allocation.  May be an indirect or direct block.  We
7354  * remove it from various lists and return any journal record that needs to
7355  * be resolved by the caller.
7356  *
7357  * A special consideration is made for indirects which were never pointed
7358  * at on disk and will never be found once this block is released.
7359  */
7360 static struct jnewblk *
7361 cancel_newblk(newblk, wk, wkhd)
7362 	struct newblk *newblk;
7363 	struct worklist *wk;
7364 	struct workhead *wkhd;
7365 {
7366 	struct jnewblk *jnewblk;
7367 
7368 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7369 
7370 	newblk->nb_state |= GOINGAWAY;
7371 	/*
7372 	 * Previously we traversed the completedhd on each indirdep
7373 	 * attached to this newblk to cancel them and gather journal
7374 	 * work.  Since we need only the oldest journal segment and
7375 	 * the lowest point on the tree will always have the oldest
7376 	 * journal segment we are free to release the segments
7377 	 * of any subordinates and may leave the indirdep list to
7378 	 * indirdep_complete() when this newblk is freed.
7379 	 */
7380 	if (newblk->nb_state & ONDEPLIST) {
7381 		newblk->nb_state &= ~ONDEPLIST;
7382 		LIST_REMOVE(newblk, nb_deps);
7383 	}
7384 	if (newblk->nb_state & ONWORKLIST)
7385 		WORKLIST_REMOVE(&newblk->nb_list);
7386 	/*
7387 	 * If the journal entry hasn't been written we save a pointer to
7388 	 * the dependency that frees it until it is written or the
7389 	 * superseding operation completes.
7390 	 */
7391 	jnewblk = newblk->nb_jnewblk;
7392 	if (jnewblk != NULL && wk != NULL) {
7393 		newblk->nb_jnewblk = NULL;
7394 		jnewblk->jn_dep = wk;
7395 	}
7396 	if (!LIST_EMPTY(&newblk->nb_jwork))
7397 		jwork_move(wkhd, &newblk->nb_jwork);
7398 	/*
7399 	 * When truncating we must free the newdirblk early to remove
7400 	 * the pagedep from the hash before returning.
7401 	 */
7402 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7403 		free_newdirblk(WK_NEWDIRBLK(wk));
7404 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7405 		panic("cancel_newblk: extra newdirblk");
7406 
7407 	return (jnewblk);
7408 }
7409 
7410 /*
7411  * Schedule the freefrag associated with a newblk to be released once
7412  * the pointers are written and the previous block is no longer needed.
7413  */
7414 static void
7415 newblk_freefrag(newblk)
7416 	struct newblk *newblk;
7417 {
7418 	struct freefrag *freefrag;
7419 
7420 	if (newblk->nb_freefrag == NULL)
7421 		return;
7422 	freefrag = newblk->nb_freefrag;
7423 	newblk->nb_freefrag = NULL;
7424 	freefrag->ff_state |= COMPLETE;
7425 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7426 		add_to_worklist(&freefrag->ff_list, 0);
7427 }
7428 
7429 /*
7430  * Free a newblk. Generate a new freefrag work request if appropriate.
7431  * This must be called after the inode pointer and any direct block pointers
7432  * are valid or fully removed via truncate or frag extension.
7433  */
7434 static void
7435 free_newblk(newblk)
7436 	struct newblk *newblk;
7437 {
7438 	struct indirdep *indirdep;
7439 	struct worklist *wk;
7440 
7441 	KASSERT(newblk->nb_jnewblk == NULL,
7442 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7443 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7444 	    ("free_newblk: unclaimed newblk"));
7445 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7446 	newblk_freefrag(newblk);
7447 	if (newblk->nb_state & ONDEPLIST)
7448 		LIST_REMOVE(newblk, nb_deps);
7449 	if (newblk->nb_state & ONWORKLIST)
7450 		WORKLIST_REMOVE(&newblk->nb_list);
7451 	LIST_REMOVE(newblk, nb_hash);
7452 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7453 		free_newdirblk(WK_NEWDIRBLK(wk));
7454 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7455 		panic("free_newblk: extra newdirblk");
7456 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7457 		indirdep_complete(indirdep);
7458 	handle_jwork(&newblk->nb_jwork);
7459 	WORKITEM_FREE(newblk, D_NEWBLK);
7460 }
7461 
7462 /*
7463  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7464  * This routine must be called with splbio interrupts blocked.
7465  */
7466 static void
7467 free_newdirblk(newdirblk)
7468 	struct newdirblk *newdirblk;
7469 {
7470 	struct pagedep *pagedep;
7471 	struct diradd *dap;
7472 	struct worklist *wk;
7473 
7474 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7475 	WORKLIST_REMOVE(&newdirblk->db_list);
7476 	/*
7477 	 * If the pagedep is still linked onto the directory buffer
7478 	 * dependency chain, then some of the entries on the
7479 	 * pd_pendinghd list may not be committed to disk yet. In
7480 	 * this case, we will simply clear the NEWBLOCK flag and
7481 	 * let the pd_pendinghd list be processed when the pagedep
7482 	 * is next written. If the pagedep is no longer on the buffer
7483 	 * dependency chain, then all the entries on the pd_pending
7484 	 * list are committed to disk and we can free them here.
7485 	 */
7486 	pagedep = newdirblk->db_pagedep;
7487 	pagedep->pd_state &= ~NEWBLOCK;
7488 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7489 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7490 			free_diradd(dap, NULL);
7491 		/*
7492 		 * If no dependencies remain, the pagedep will be freed.
7493 		 */
7494 		free_pagedep(pagedep);
7495 	}
7496 	/* Should only ever be one item in the list. */
7497 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7498 		WORKLIST_REMOVE(wk);
7499 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7500 	}
7501 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7502 }
7503 
7504 /*
7505  * Prepare an inode to be freed. The actual free operation is not
7506  * done until the zero'ed inode has been written to disk.
7507  */
7508 void
7509 softdep_freefile(pvp, ino, mode)
7510 	struct vnode *pvp;
7511 	ino_t ino;
7512 	int mode;
7513 {
7514 	struct inode *ip = VTOI(pvp);
7515 	struct inodedep *inodedep;
7516 	struct freefile *freefile;
7517 	struct freeblks *freeblks;
7518 	struct ufsmount *ump;
7519 
7520 	ump = ip->i_ump;
7521 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7522 	    ("softdep_freefile called on non-softdep filesystem"));
7523 	/*
7524 	 * This sets up the inode de-allocation dependency.
7525 	 */
7526 	freefile = malloc(sizeof(struct freefile),
7527 		M_FREEFILE, M_SOFTDEP_FLAGS);
7528 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7529 	freefile->fx_mode = mode;
7530 	freefile->fx_oldinum = ino;
7531 	freefile->fx_devvp = ip->i_devvp;
7532 	LIST_INIT(&freefile->fx_jwork);
7533 	UFS_LOCK(ump);
7534 	ip->i_fs->fs_pendinginodes += 1;
7535 	UFS_UNLOCK(ump);
7536 
7537 	/*
7538 	 * If the inodedep does not exist, then the zero'ed inode has
7539 	 * been written to disk. If the allocated inode has never been
7540 	 * written to disk, then the on-disk inode is zero'ed. In either
7541 	 * case we can free the file immediately.  If the journal was
7542 	 * canceled before being written the inode will never make it to
7543 	 * disk and we must send the canceled journal entrys to
7544 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7545 	 * Any blocks waiting on the inode to write can be safely freed
7546 	 * here as it will never been written.
7547 	 */
7548 	ACQUIRE_LOCK(ump);
7549 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7550 	if (inodedep) {
7551 		/*
7552 		 * Clear out freeblks that no longer need to reference
7553 		 * this inode.
7554 		 */
7555 		while ((freeblks =
7556 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7557 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7558 			    fb_next);
7559 			freeblks->fb_state &= ~ONDEPLIST;
7560 		}
7561 		/*
7562 		 * Remove this inode from the unlinked list.
7563 		 */
7564 		if (inodedep->id_state & UNLINKED) {
7565 			/*
7566 			 * Save the journal work to be freed with the bitmap
7567 			 * before we clear UNLINKED.  Otherwise it can be lost
7568 			 * if the inode block is written.
7569 			 */
7570 			handle_bufwait(inodedep, &freefile->fx_jwork);
7571 			clear_unlinked_inodedep(inodedep);
7572 			/*
7573 			 * Re-acquire inodedep as we've dropped the
7574 			 * per-filesystem lock in clear_unlinked_inodedep().
7575 			 */
7576 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7577 		}
7578 	}
7579 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
7580 		FREE_LOCK(ump);
7581 		handle_workitem_freefile(freefile);
7582 		return;
7583 	}
7584 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
7585 		inodedep->id_state |= GOINGAWAY;
7586 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
7587 	FREE_LOCK(ump);
7588 	if (ip->i_number == ino)
7589 		ip->i_flag |= IN_MODIFIED;
7590 }
7591 
7592 /*
7593  * Check to see if an inode has never been written to disk. If
7594  * so free the inodedep and return success, otherwise return failure.
7595  * This routine must be called with splbio interrupts blocked.
7596  *
7597  * If we still have a bitmap dependency, then the inode has never
7598  * been written to disk. Drop the dependency as it is no longer
7599  * necessary since the inode is being deallocated. We set the
7600  * ALLCOMPLETE flags since the bitmap now properly shows that the
7601  * inode is not allocated. Even if the inode is actively being
7602  * written, it has been rolled back to its zero'ed state, so we
7603  * are ensured that a zero inode is what is on the disk. For short
7604  * lived files, this change will usually result in removing all the
7605  * dependencies from the inode so that it can be freed immediately.
7606  */
7607 static int
7608 check_inode_unwritten(inodedep)
7609 	struct inodedep *inodedep;
7610 {
7611 
7612 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7613 
7614 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
7615 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7616 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7617 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7618 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7619 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7620 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7621 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7622 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7623 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7624 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7625 	    inodedep->id_mkdiradd != NULL ||
7626 	    inodedep->id_nlinkdelta != 0)
7627 		return (0);
7628 	/*
7629 	 * Another process might be in initiate_write_inodeblock_ufs[12]
7630 	 * trying to allocate memory without holding "Softdep Lock".
7631 	 */
7632 	if ((inodedep->id_state & IOSTARTED) != 0 &&
7633 	    inodedep->id_savedino1 == NULL)
7634 		return (0);
7635 
7636 	if (inodedep->id_state & ONDEPLIST)
7637 		LIST_REMOVE(inodedep, id_deps);
7638 	inodedep->id_state &= ~ONDEPLIST;
7639 	inodedep->id_state |= ALLCOMPLETE;
7640 	inodedep->id_bmsafemap = NULL;
7641 	if (inodedep->id_state & ONWORKLIST)
7642 		WORKLIST_REMOVE(&inodedep->id_list);
7643 	if (inodedep->id_savedino1 != NULL) {
7644 		free(inodedep->id_savedino1, M_SAVEDINO);
7645 		inodedep->id_savedino1 = NULL;
7646 	}
7647 	if (free_inodedep(inodedep) == 0)
7648 		panic("check_inode_unwritten: busy inode");
7649 	return (1);
7650 }
7651 
7652 static int
7653 check_inodedep_free(inodedep)
7654 	struct inodedep *inodedep;
7655 {
7656 
7657 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7658 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
7659 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
7660 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
7661 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
7662 	    !LIST_EMPTY(&inodedep->id_inowait) ||
7663 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
7664 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
7665 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
7666 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
7667 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
7668 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
7669 	    inodedep->id_mkdiradd != NULL ||
7670 	    inodedep->id_nlinkdelta != 0 ||
7671 	    inodedep->id_savedino1 != NULL)
7672 		return (0);
7673 	return (1);
7674 }
7675 
7676 /*
7677  * Try to free an inodedep structure. Return 1 if it could be freed.
7678  */
7679 static int
7680 free_inodedep(inodedep)
7681 	struct inodedep *inodedep;
7682 {
7683 
7684 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
7685 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
7686 	    !check_inodedep_free(inodedep))
7687 		return (0);
7688 	if (inodedep->id_state & ONDEPLIST)
7689 		LIST_REMOVE(inodedep, id_deps);
7690 	LIST_REMOVE(inodedep, id_hash);
7691 	WORKITEM_FREE(inodedep, D_INODEDEP);
7692 	return (1);
7693 }
7694 
7695 /*
7696  * Free the block referenced by a freework structure.  The parent freeblks
7697  * structure is released and completed when the final cg bitmap reaches
7698  * the disk.  This routine may be freeing a jnewblk which never made it to
7699  * disk in which case we do not have to wait as the operation is undone
7700  * in memory immediately.
7701  */
7702 static void
7703 freework_freeblock(freework)
7704 	struct freework *freework;
7705 {
7706 	struct freeblks *freeblks;
7707 	struct jnewblk *jnewblk;
7708 	struct ufsmount *ump;
7709 	struct workhead wkhd;
7710 	struct fs *fs;
7711 	int bsize;
7712 	int needj;
7713 
7714 	ump = VFSTOUFS(freework->fw_list.wk_mp);
7715 	LOCK_OWNED(ump);
7716 	/*
7717 	 * Handle partial truncate separately.
7718 	 */
7719 	if (freework->fw_indir) {
7720 		complete_trunc_indir(freework);
7721 		return;
7722 	}
7723 	freeblks = freework->fw_freeblks;
7724 	fs = ump->um_fs;
7725 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
7726 	bsize = lfragtosize(fs, freework->fw_frags);
7727 	LIST_INIT(&wkhd);
7728 	/*
7729 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
7730 	 * on the indirblk hashtable and prevents premature freeing.
7731 	 */
7732 	freework->fw_state |= DEPCOMPLETE;
7733 	/*
7734 	 * SUJ needs to wait for the segment referencing freed indirect
7735 	 * blocks to expire so that we know the checker will not confuse
7736 	 * a re-allocated indirect block with its old contents.
7737 	 */
7738 	if (needj && freework->fw_lbn <= -NDADDR)
7739 		indirblk_insert(freework);
7740 	/*
7741 	 * If we are canceling an existing jnewblk pass it to the free
7742 	 * routine, otherwise pass the freeblk which will ultimately
7743 	 * release the freeblks.  If we're not journaling, we can just
7744 	 * free the freeblks immediately.
7745 	 */
7746 	jnewblk = freework->fw_jnewblk;
7747 	if (jnewblk != NULL) {
7748 		cancel_jnewblk(jnewblk, &wkhd);
7749 		needj = 0;
7750 	} else if (needj) {
7751 		freework->fw_state |= DELAYEDFREE;
7752 		freeblks->fb_cgwait++;
7753 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
7754 	}
7755 	FREE_LOCK(ump);
7756 	freeblks_free(ump, freeblks, btodb(bsize));
7757 	CTR4(KTR_SUJ,
7758 	    "freework_freeblock: ino %d blkno %jd lbn %jd size %ld",
7759 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
7760 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
7761 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd);
7762 	ACQUIRE_LOCK(ump);
7763 	/*
7764 	 * The jnewblk will be discarded and the bits in the map never
7765 	 * made it to disk.  We can immediately free the freeblk.
7766 	 */
7767 	if (needj == 0)
7768 		handle_written_freework(freework);
7769 }
7770 
7771 /*
7772  * We enqueue freework items that need processing back on the freeblks and
7773  * add the freeblks to the worklist.  This makes it easier to find all work
7774  * required to flush a truncation in process_truncates().
7775  */
7776 static void
7777 freework_enqueue(freework)
7778 	struct freework *freework;
7779 {
7780 	struct freeblks *freeblks;
7781 
7782 	freeblks = freework->fw_freeblks;
7783 	if ((freework->fw_state & INPROGRESS) == 0)
7784 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
7785 	if ((freeblks->fb_state &
7786 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
7787 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7788 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7789 }
7790 
7791 /*
7792  * Start, continue, or finish the process of freeing an indirect block tree.
7793  * The free operation may be paused at any point with fw_off containing the
7794  * offset to restart from.  This enables us to implement some flow control
7795  * for large truncates which may fan out and generate a huge number of
7796  * dependencies.
7797  */
7798 static void
7799 handle_workitem_indirblk(freework)
7800 	struct freework *freework;
7801 {
7802 	struct freeblks *freeblks;
7803 	struct ufsmount *ump;
7804 	struct fs *fs;
7805 
7806 	freeblks = freework->fw_freeblks;
7807 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7808 	fs = ump->um_fs;
7809 	if (freework->fw_state & DEPCOMPLETE) {
7810 		handle_written_freework(freework);
7811 		return;
7812 	}
7813 	if (freework->fw_off == NINDIR(fs)) {
7814 		freework_freeblock(freework);
7815 		return;
7816 	}
7817 	freework->fw_state |= INPROGRESS;
7818 	FREE_LOCK(ump);
7819 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
7820 	    freework->fw_lbn);
7821 	ACQUIRE_LOCK(ump);
7822 }
7823 
7824 /*
7825  * Called when a freework structure attached to a cg buf is written.  The
7826  * ref on either the parent or the freeblks structure is released and
7827  * the freeblks is added back to the worklist if there is more work to do.
7828  */
7829 static void
7830 handle_written_freework(freework)
7831 	struct freework *freework;
7832 {
7833 	struct freeblks *freeblks;
7834 	struct freework *parent;
7835 
7836 	freeblks = freework->fw_freeblks;
7837 	parent = freework->fw_parent;
7838 	if (freework->fw_state & DELAYEDFREE)
7839 		freeblks->fb_cgwait--;
7840 	freework->fw_state |= COMPLETE;
7841 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
7842 		WORKITEM_FREE(freework, D_FREEWORK);
7843 	if (parent) {
7844 		if (--parent->fw_ref == 0)
7845 			freework_enqueue(parent);
7846 		return;
7847 	}
7848 	if (--freeblks->fb_ref != 0)
7849 		return;
7850 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
7851 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
7852 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
7853 }
7854 
7855 /*
7856  * This workitem routine performs the block de-allocation.
7857  * The workitem is added to the pending list after the updated
7858  * inode block has been written to disk.  As mentioned above,
7859  * checks regarding the number of blocks de-allocated (compared
7860  * to the number of blocks allocated for the file) are also
7861  * performed in this function.
7862  */
7863 static int
7864 handle_workitem_freeblocks(freeblks, flags)
7865 	struct freeblks *freeblks;
7866 	int flags;
7867 {
7868 	struct freework *freework;
7869 	struct newblk *newblk;
7870 	struct allocindir *aip;
7871 	struct ufsmount *ump;
7872 	struct worklist *wk;
7873 
7874 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
7875 	    ("handle_workitem_freeblocks: Journal entries not written."));
7876 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7877 	ACQUIRE_LOCK(ump);
7878 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
7879 		WORKLIST_REMOVE(wk);
7880 		switch (wk->wk_type) {
7881 		case D_DIRREM:
7882 			wk->wk_state |= COMPLETE;
7883 			add_to_worklist(wk, 0);
7884 			continue;
7885 
7886 		case D_ALLOCDIRECT:
7887 			free_newblk(WK_NEWBLK(wk));
7888 			continue;
7889 
7890 		case D_ALLOCINDIR:
7891 			aip = WK_ALLOCINDIR(wk);
7892 			freework = NULL;
7893 			if (aip->ai_state & DELAYEDFREE) {
7894 				FREE_LOCK(ump);
7895 				freework = newfreework(ump, freeblks, NULL,
7896 				    aip->ai_lbn, aip->ai_newblkno,
7897 				    ump->um_fs->fs_frag, 0, 0);
7898 				ACQUIRE_LOCK(ump);
7899 			}
7900 			newblk = WK_NEWBLK(wk);
7901 			if (newblk->nb_jnewblk) {
7902 				freework->fw_jnewblk = newblk->nb_jnewblk;
7903 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
7904 				newblk->nb_jnewblk = NULL;
7905 			}
7906 			free_newblk(newblk);
7907 			continue;
7908 
7909 		case D_FREEWORK:
7910 			freework = WK_FREEWORK(wk);
7911 			if (freework->fw_lbn <= -NDADDR)
7912 				handle_workitem_indirblk(freework);
7913 			else
7914 				freework_freeblock(freework);
7915 			continue;
7916 		default:
7917 			panic("handle_workitem_freeblocks: Unknown type %s",
7918 			    TYPENAME(wk->wk_type));
7919 		}
7920 	}
7921 	if (freeblks->fb_ref != 0) {
7922 		freeblks->fb_state &= ~INPROGRESS;
7923 		wake_worklist(&freeblks->fb_list);
7924 		freeblks = NULL;
7925 	}
7926 	FREE_LOCK(ump);
7927 	if (freeblks)
7928 		return handle_complete_freeblocks(freeblks, flags);
7929 	return (0);
7930 }
7931 
7932 /*
7933  * Handle completion of block free via truncate.  This allows fs_pending
7934  * to track the actual free block count more closely than if we only updated
7935  * it at the end.  We must be careful to handle cases where the block count
7936  * on free was incorrect.
7937  */
7938 static void
7939 freeblks_free(ump, freeblks, blocks)
7940 	struct ufsmount *ump;
7941 	struct freeblks *freeblks;
7942 	int blocks;
7943 {
7944 	struct fs *fs;
7945 	ufs2_daddr_t remain;
7946 
7947 	UFS_LOCK(ump);
7948 	remain = -freeblks->fb_chkcnt;
7949 	freeblks->fb_chkcnt += blocks;
7950 	if (remain > 0) {
7951 		if (remain < blocks)
7952 			blocks = remain;
7953 		fs = ump->um_fs;
7954 		fs->fs_pendingblocks -= blocks;
7955 	}
7956 	UFS_UNLOCK(ump);
7957 }
7958 
7959 /*
7960  * Once all of the freework workitems are complete we can retire the
7961  * freeblocks dependency and any journal work awaiting completion.  This
7962  * can not be called until all other dependencies are stable on disk.
7963  */
7964 static int
7965 handle_complete_freeblocks(freeblks, flags)
7966 	struct freeblks *freeblks;
7967 	int flags;
7968 {
7969 	struct inodedep *inodedep;
7970 	struct inode *ip;
7971 	struct vnode *vp;
7972 	struct fs *fs;
7973 	struct ufsmount *ump;
7974 	ufs2_daddr_t spare;
7975 
7976 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
7977 	fs = ump->um_fs;
7978 	flags = LK_EXCLUSIVE | flags;
7979 	spare = freeblks->fb_chkcnt;
7980 
7981 	/*
7982 	 * If we did not release the expected number of blocks we may have
7983 	 * to adjust the inode block count here.  Only do so if it wasn't
7984 	 * a truncation to zero and the modrev still matches.
7985 	 */
7986 	if (spare && freeblks->fb_len != 0) {
7987 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
7988 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
7989 			return (EBUSY);
7990 		ip = VTOI(vp);
7991 		if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
7992 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
7993 			ip->i_flag |= IN_CHANGE;
7994 			/*
7995 			 * We must wait so this happens before the
7996 			 * journal is reclaimed.
7997 			 */
7998 			ffs_update(vp, 1);
7999 		}
8000 		vput(vp);
8001 	}
8002 	if (spare < 0) {
8003 		UFS_LOCK(ump);
8004 		fs->fs_pendingblocks += spare;
8005 		UFS_UNLOCK(ump);
8006 	}
8007 #ifdef QUOTA
8008 	/* Handle spare. */
8009 	if (spare)
8010 		quotaadj(freeblks->fb_quota, ump, -spare);
8011 	quotarele(freeblks->fb_quota);
8012 #endif
8013 	ACQUIRE_LOCK(ump);
8014 	if (freeblks->fb_state & ONDEPLIST) {
8015 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8016 		    0, &inodedep);
8017 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8018 		freeblks->fb_state &= ~ONDEPLIST;
8019 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8020 			free_inodedep(inodedep);
8021 	}
8022 	/*
8023 	 * All of the freeblock deps must be complete prior to this call
8024 	 * so it's now safe to complete earlier outstanding journal entries.
8025 	 */
8026 	handle_jwork(&freeblks->fb_jwork);
8027 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8028 	FREE_LOCK(ump);
8029 	return (0);
8030 }
8031 
8032 /*
8033  * Release blocks associated with the freeblks and stored in the indirect
8034  * block dbn. If level is greater than SINGLE, the block is an indirect block
8035  * and recursive calls to indirtrunc must be used to cleanse other indirect
8036  * blocks.
8037  *
8038  * This handles partial and complete truncation of blocks.  Partial is noted
8039  * with goingaway == 0.  In this case the freework is completed after the
8040  * zero'd indirects are written to disk.  For full truncation the freework
8041  * is completed after the block is freed.
8042  */
8043 static void
8044 indir_trunc(freework, dbn, lbn)
8045 	struct freework *freework;
8046 	ufs2_daddr_t dbn;
8047 	ufs_lbn_t lbn;
8048 {
8049 	struct freework *nfreework;
8050 	struct workhead wkhd;
8051 	struct freeblks *freeblks;
8052 	struct buf *bp;
8053 	struct fs *fs;
8054 	struct indirdep *indirdep;
8055 	struct ufsmount *ump;
8056 	ufs1_daddr_t *bap1 = 0;
8057 	ufs2_daddr_t nb, nnb, *bap2 = 0;
8058 	ufs_lbn_t lbnadd, nlbn;
8059 	int i, nblocks, ufs1fmt;
8060 	int freedblocks;
8061 	int goingaway;
8062 	int freedeps;
8063 	int needj;
8064 	int level;
8065 	int cnt;
8066 
8067 	freeblks = freework->fw_freeblks;
8068 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8069 	fs = ump->um_fs;
8070 	/*
8071 	 * Get buffer of block pointers to be freed.  There are three cases:
8072 	 *
8073 	 * 1) Partial truncate caches the indirdep pointer in the freework
8074 	 *    which provides us a back copy to the save bp which holds the
8075 	 *    pointers we want to clear.  When this completes the zero
8076 	 *    pointers are written to the real copy.
8077 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8078 	 *    eliminated the real copy and placed the indirdep on the saved
8079 	 *    copy.  The indirdep and buf are discarded when this completes.
8080 	 * 3) The indirect was not in memory, we read a copy off of the disk
8081 	 *    using the devvp and drop and invalidate the buffer when we're
8082 	 *    done.
8083 	 */
8084 	goingaway = 1;
8085 	indirdep = NULL;
8086 	if (freework->fw_indir != NULL) {
8087 		goingaway = 0;
8088 		indirdep = freework->fw_indir;
8089 		bp = indirdep->ir_savebp;
8090 		if (bp == NULL || bp->b_blkno != dbn)
8091 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8092 			    bp, (intmax_t)dbn);
8093 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8094 		/*
8095 		 * The lock prevents the buf dep list from changing and
8096 	 	 * indirects on devvp should only ever have one dependency.
8097 		 */
8098 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8099 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8100 			panic("indir_trunc: Bad indirdep %p from buf %p",
8101 			    indirdep, bp);
8102 	} else if (bread(freeblks->fb_devvp, dbn, (int)fs->fs_bsize,
8103 	    NOCRED, &bp) != 0) {
8104 		brelse(bp);
8105 		return;
8106 	}
8107 	ACQUIRE_LOCK(ump);
8108 	/* Protects against a race with complete_trunc_indir(). */
8109 	freework->fw_state &= ~INPROGRESS;
8110 	/*
8111 	 * If we have an indirdep we need to enforce the truncation order
8112 	 * and discard it when it is complete.
8113 	 */
8114 	if (indirdep) {
8115 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8116 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8117 			/*
8118 			 * Add the complete truncate to the list on the
8119 			 * indirdep to enforce in-order processing.
8120 			 */
8121 			if (freework->fw_indir == NULL)
8122 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8123 				    freework, fw_next);
8124 			FREE_LOCK(ump);
8125 			return;
8126 		}
8127 		/*
8128 		 * If we're goingaway, free the indirdep.  Otherwise it will
8129 		 * linger until the write completes.
8130 		 */
8131 		if (goingaway)
8132 			free_indirdep(indirdep);
8133 	}
8134 	FREE_LOCK(ump);
8135 	/* Initialize pointers depending on block size. */
8136 	if (ump->um_fstype == UFS1) {
8137 		bap1 = (ufs1_daddr_t *)bp->b_data;
8138 		nb = bap1[freework->fw_off];
8139 		ufs1fmt = 1;
8140 	} else {
8141 		bap2 = (ufs2_daddr_t *)bp->b_data;
8142 		nb = bap2[freework->fw_off];
8143 		ufs1fmt = 0;
8144 	}
8145 	level = lbn_level(lbn);
8146 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8147 	lbnadd = lbn_offset(fs, level);
8148 	nblocks = btodb(fs->fs_bsize);
8149 	nfreework = freework;
8150 	freedeps = 0;
8151 	cnt = 0;
8152 	/*
8153 	 * Reclaim blocks.  Traverses into nested indirect levels and
8154 	 * arranges for the current level to be freed when subordinates
8155 	 * are free when journaling.
8156 	 */
8157 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8158 		if (i != NINDIR(fs) - 1) {
8159 			if (ufs1fmt)
8160 				nnb = bap1[i+1];
8161 			else
8162 				nnb = bap2[i+1];
8163 		} else
8164 			nnb = 0;
8165 		if (nb == 0)
8166 			continue;
8167 		cnt++;
8168 		if (level != 0) {
8169 			nlbn = (lbn + 1) - (i * lbnadd);
8170 			if (needj != 0) {
8171 				nfreework = newfreework(ump, freeblks, freework,
8172 				    nlbn, nb, fs->fs_frag, 0, 0);
8173 				freedeps++;
8174 			}
8175 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8176 		} else {
8177 			struct freedep *freedep;
8178 
8179 			/*
8180 			 * Attempt to aggregate freedep dependencies for
8181 			 * all blocks being released to the same CG.
8182 			 */
8183 			LIST_INIT(&wkhd);
8184 			if (needj != 0 &&
8185 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8186 				freedep = newfreedep(freework);
8187 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8188 				    &freedep->fd_list);
8189 				freedeps++;
8190 			}
8191 			CTR3(KTR_SUJ,
8192 			    "indir_trunc: ino %d blkno %jd size %ld",
8193 			    freeblks->fb_inum, nb, fs->fs_bsize);
8194 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8195 			    fs->fs_bsize, freeblks->fb_inum,
8196 			    freeblks->fb_vtype, &wkhd);
8197 		}
8198 	}
8199 	if (goingaway) {
8200 		bp->b_flags |= B_INVAL | B_NOCACHE;
8201 		brelse(bp);
8202 	}
8203 	freedblocks = 0;
8204 	if (level == 0)
8205 		freedblocks = (nblocks * cnt);
8206 	if (needj == 0)
8207 		freedblocks += nblocks;
8208 	freeblks_free(ump, freeblks, freedblocks);
8209 	/*
8210 	 * If we are journaling set up the ref counts and offset so this
8211 	 * indirect can be completed when its children are free.
8212 	 */
8213 	if (needj) {
8214 		ACQUIRE_LOCK(ump);
8215 		freework->fw_off = i;
8216 		freework->fw_ref += freedeps;
8217 		freework->fw_ref -= NINDIR(fs) + 1;
8218 		if (level == 0)
8219 			freeblks->fb_cgwait += freedeps;
8220 		if (freework->fw_ref == 0)
8221 			freework_freeblock(freework);
8222 		FREE_LOCK(ump);
8223 		return;
8224 	}
8225 	/*
8226 	 * If we're not journaling we can free the indirect now.
8227 	 */
8228 	dbn = dbtofsb(fs, dbn);
8229 	CTR3(KTR_SUJ,
8230 	    "indir_trunc 2: ino %d blkno %jd size %ld",
8231 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8232 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8233 	    freeblks->fb_inum, freeblks->fb_vtype, NULL);
8234 	/* Non SUJ softdep does single-threaded truncations. */
8235 	if (freework->fw_blkno == dbn) {
8236 		freework->fw_state |= ALLCOMPLETE;
8237 		ACQUIRE_LOCK(ump);
8238 		handle_written_freework(freework);
8239 		FREE_LOCK(ump);
8240 	}
8241 	return;
8242 }
8243 
8244 /*
8245  * Cancel an allocindir when it is removed via truncation.  When bp is not
8246  * NULL the indirect never appeared on disk and is scheduled to be freed
8247  * independently of the indir so we can more easily track journal work.
8248  */
8249 static void
8250 cancel_allocindir(aip, bp, freeblks, trunc)
8251 	struct allocindir *aip;
8252 	struct buf *bp;
8253 	struct freeblks *freeblks;
8254 	int trunc;
8255 {
8256 	struct indirdep *indirdep;
8257 	struct freefrag *freefrag;
8258 	struct newblk *newblk;
8259 
8260 	newblk = (struct newblk *)aip;
8261 	LIST_REMOVE(aip, ai_next);
8262 	/*
8263 	 * We must eliminate the pointer in bp if it must be freed on its
8264 	 * own due to partial truncate or pending journal work.
8265 	 */
8266 	if (bp && (trunc || newblk->nb_jnewblk)) {
8267 		/*
8268 		 * Clear the pointer and mark the aip to be freed
8269 		 * directly if it never existed on disk.
8270 		 */
8271 		aip->ai_state |= DELAYEDFREE;
8272 		indirdep = aip->ai_indirdep;
8273 		if (indirdep->ir_state & UFS1FMT)
8274 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8275 		else
8276 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8277 	}
8278 	/*
8279 	 * When truncating the previous pointer will be freed via
8280 	 * savedbp.  Eliminate the freefrag which would dup free.
8281 	 */
8282 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8283 		newblk->nb_freefrag = NULL;
8284 		if (freefrag->ff_jdep)
8285 			cancel_jfreefrag(
8286 			    WK_JFREEFRAG(freefrag->ff_jdep));
8287 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8288 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8289 	}
8290 	/*
8291 	 * If the journal hasn't been written the jnewblk must be passed
8292 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8293 	 * this by leaving the journal dependency on the newblk to be freed
8294 	 * when a freework is created in handle_workitem_freeblocks().
8295 	 */
8296 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8297 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8298 }
8299 
8300 /*
8301  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8302  * in to a newdirblk so any subsequent additions are tracked properly.  The
8303  * caller is responsible for adding the mkdir1 dependency to the journal
8304  * and updating id_mkdiradd.  This function returns with the per-filesystem
8305  * lock held.
8306  */
8307 static struct mkdir *
8308 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8309 	struct diradd *dap;
8310 	ino_t newinum;
8311 	ino_t dinum;
8312 	struct buf *newdirbp;
8313 	struct mkdir **mkdirp;
8314 {
8315 	struct newblk *newblk;
8316 	struct pagedep *pagedep;
8317 	struct inodedep *inodedep;
8318 	struct newdirblk *newdirblk = 0;
8319 	struct mkdir *mkdir1, *mkdir2;
8320 	struct worklist *wk;
8321 	struct jaddref *jaddref;
8322 	struct ufsmount *ump;
8323 	struct mount *mp;
8324 
8325 	mp = dap->da_list.wk_mp;
8326 	ump = VFSTOUFS(mp);
8327 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8328 	    M_SOFTDEP_FLAGS);
8329 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8330 	LIST_INIT(&newdirblk->db_mkdir);
8331 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8332 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8333 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8334 	mkdir1->md_diradd = dap;
8335 	mkdir1->md_jaddref = NULL;
8336 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8337 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8338 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8339 	mkdir2->md_diradd = dap;
8340 	mkdir2->md_jaddref = NULL;
8341 	if (MOUNTEDSUJ(mp) == 0) {
8342 		mkdir1->md_state |= DEPCOMPLETE;
8343 		mkdir2->md_state |= DEPCOMPLETE;
8344 	}
8345 	/*
8346 	 * Dependency on "." and ".." being written to disk.
8347 	 */
8348 	mkdir1->md_buf = newdirbp;
8349 	ACQUIRE_LOCK(VFSTOUFS(mp));
8350 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8351 	/*
8352 	 * We must link the pagedep, allocdirect, and newdirblk for
8353 	 * the initial file page so the pointer to the new directory
8354 	 * is not written until the directory contents are live and
8355 	 * any subsequent additions are not marked live until the
8356 	 * block is reachable via the inode.
8357 	 */
8358 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8359 		panic("setup_newdir: lost pagedep");
8360 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8361 		if (wk->wk_type == D_ALLOCDIRECT)
8362 			break;
8363 	if (wk == NULL)
8364 		panic("setup_newdir: lost allocdirect");
8365 	if (pagedep->pd_state & NEWBLOCK)
8366 		panic("setup_newdir: NEWBLOCK already set");
8367 	newblk = WK_NEWBLK(wk);
8368 	pagedep->pd_state |= NEWBLOCK;
8369 	pagedep->pd_newdirblk = newdirblk;
8370 	newdirblk->db_pagedep = pagedep;
8371 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8372 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8373 	/*
8374 	 * Look up the inodedep for the parent directory so that we
8375 	 * can link mkdir2 into the pending dotdot jaddref or
8376 	 * the inode write if there is none.  If the inode is
8377 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8378 	 * been satisfied and mkdir2 can be freed.
8379 	 */
8380 	inodedep_lookup(mp, dinum, 0, &inodedep);
8381 	if (MOUNTEDSUJ(mp)) {
8382 		if (inodedep == NULL)
8383 			panic("setup_newdir: Lost parent.");
8384 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8385 		    inoreflst);
8386 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8387 		    (jaddref->ja_state & MKDIR_PARENT),
8388 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8389 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8390 		mkdir2->md_jaddref = jaddref;
8391 		jaddref->ja_mkdir = mkdir2;
8392 	} else if (inodedep == NULL ||
8393 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8394 		dap->da_state &= ~MKDIR_PARENT;
8395 		WORKITEM_FREE(mkdir2, D_MKDIR);
8396 		mkdir2 = NULL;
8397 	} else {
8398 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8399 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8400 	}
8401 	*mkdirp = mkdir2;
8402 
8403 	return (mkdir1);
8404 }
8405 
8406 /*
8407  * Directory entry addition dependencies.
8408  *
8409  * When adding a new directory entry, the inode (with its incremented link
8410  * count) must be written to disk before the directory entry's pointer to it.
8411  * Also, if the inode is newly allocated, the corresponding freemap must be
8412  * updated (on disk) before the directory entry's pointer. These requirements
8413  * are met via undo/redo on the directory entry's pointer, which consists
8414  * simply of the inode number.
8415  *
8416  * As directory entries are added and deleted, the free space within a
8417  * directory block can become fragmented.  The ufs filesystem will compact
8418  * a fragmented directory block to make space for a new entry. When this
8419  * occurs, the offsets of previously added entries change. Any "diradd"
8420  * dependency structures corresponding to these entries must be updated with
8421  * the new offsets.
8422  */
8423 
8424 /*
8425  * This routine is called after the in-memory inode's link
8426  * count has been incremented, but before the directory entry's
8427  * pointer to the inode has been set.
8428  */
8429 int
8430 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8431 	struct buf *bp;		/* buffer containing directory block */
8432 	struct inode *dp;	/* inode for directory */
8433 	off_t diroffset;	/* offset of new entry in directory */
8434 	ino_t newinum;		/* inode referenced by new directory entry */
8435 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8436 	int isnewblk;		/* entry is in a newly allocated block */
8437 {
8438 	int offset;		/* offset of new entry within directory block */
8439 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8440 	struct fs *fs;
8441 	struct diradd *dap;
8442 	struct newblk *newblk;
8443 	struct pagedep *pagedep;
8444 	struct inodedep *inodedep;
8445 	struct newdirblk *newdirblk = 0;
8446 	struct mkdir *mkdir1, *mkdir2;
8447 	struct jaddref *jaddref;
8448 	struct ufsmount *ump;
8449 	struct mount *mp;
8450 	int isindir;
8451 
8452 	ump = dp->i_ump;
8453 	mp = UFSTOVFS(ump);
8454 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8455 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8456 	/*
8457 	 * Whiteouts have no dependencies.
8458 	 */
8459 	if (newinum == WINO) {
8460 		if (newdirbp != NULL)
8461 			bdwrite(newdirbp);
8462 		return (0);
8463 	}
8464 	jaddref = NULL;
8465 	mkdir1 = mkdir2 = NULL;
8466 	fs = dp->i_fs;
8467 	lbn = lblkno(fs, diroffset);
8468 	offset = blkoff(fs, diroffset);
8469 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8470 		M_SOFTDEP_FLAGS|M_ZERO);
8471 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8472 	dap->da_offset = offset;
8473 	dap->da_newinum = newinum;
8474 	dap->da_state = ATTACHED;
8475 	LIST_INIT(&dap->da_jwork);
8476 	isindir = bp->b_lblkno >= NDADDR;
8477 	if (isnewblk &&
8478 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8479 		newdirblk = malloc(sizeof(struct newdirblk),
8480 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8481 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8482 		LIST_INIT(&newdirblk->db_mkdir);
8483 	}
8484 	/*
8485 	 * If we're creating a new directory setup the dependencies and set
8486 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8487 	 * we can move on.
8488 	 */
8489 	if (newdirbp == NULL) {
8490 		dap->da_state |= DEPCOMPLETE;
8491 		ACQUIRE_LOCK(ump);
8492 	} else {
8493 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8494 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8495 		    &mkdir2);
8496 	}
8497 	/*
8498 	 * Link into parent directory pagedep to await its being written.
8499 	 */
8500 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8501 #ifdef DEBUG
8502 	if (diradd_lookup(pagedep, offset) != NULL)
8503 		panic("softdep_setup_directory_add: %p already at off %d\n",
8504 		    diradd_lookup(pagedep, offset), offset);
8505 #endif
8506 	dap->da_pagedep = pagedep;
8507 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8508 	    da_pdlist);
8509 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
8510 	/*
8511 	 * If we're journaling, link the diradd into the jaddref so it
8512 	 * may be completed after the journal entry is written.  Otherwise,
8513 	 * link the diradd into its inodedep.  If the inode is not yet
8514 	 * written place it on the bufwait list, otherwise do the post-inode
8515 	 * write processing to put it on the id_pendinghd list.
8516 	 */
8517 	if (MOUNTEDSUJ(mp)) {
8518 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8519 		    inoreflst);
8520 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8521 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8522 		jaddref->ja_diroff = diroffset;
8523 		jaddref->ja_diradd = dap;
8524 		add_to_journal(&jaddref->ja_list);
8525 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8526 		diradd_inode_written(dap, inodedep);
8527 	else
8528 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8529 	/*
8530 	 * Add the journal entries for . and .. links now that the primary
8531 	 * link is written.
8532 	 */
8533 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8534 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8535 		    inoreflst, if_deps);
8536 		KASSERT(jaddref != NULL &&
8537 		    jaddref->ja_ino == jaddref->ja_parent &&
8538 		    (jaddref->ja_state & MKDIR_BODY),
8539 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8540 		    jaddref));
8541 		mkdir1->md_jaddref = jaddref;
8542 		jaddref->ja_mkdir = mkdir1;
8543 		/*
8544 		 * It is important that the dotdot journal entry
8545 		 * is added prior to the dot entry since dot writes
8546 		 * both the dot and dotdot links.  These both must
8547 		 * be added after the primary link for the journal
8548 		 * to remain consistent.
8549 		 */
8550 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8551 		add_to_journal(&jaddref->ja_list);
8552 	}
8553 	/*
8554 	 * If we are adding a new directory remember this diradd so that if
8555 	 * we rename it we can keep the dot and dotdot dependencies.  If
8556 	 * we are adding a new name for an inode that has a mkdiradd we
8557 	 * must be in rename and we have to move the dot and dotdot
8558 	 * dependencies to this new name.  The old name is being orphaned
8559 	 * soon.
8560 	 */
8561 	if (mkdir1 != NULL) {
8562 		if (inodedep->id_mkdiradd != NULL)
8563 			panic("softdep_setup_directory_add: Existing mkdir");
8564 		inodedep->id_mkdiradd = dap;
8565 	} else if (inodedep->id_mkdiradd)
8566 		merge_diradd(inodedep, dap);
8567 	if (newdirblk) {
8568 		/*
8569 		 * There is nothing to do if we are already tracking
8570 		 * this block.
8571 		 */
8572 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
8573 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
8574 			FREE_LOCK(ump);
8575 			return (0);
8576 		}
8577 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
8578 		    == 0)
8579 			panic("softdep_setup_directory_add: lost entry");
8580 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8581 		pagedep->pd_state |= NEWBLOCK;
8582 		pagedep->pd_newdirblk = newdirblk;
8583 		newdirblk->db_pagedep = pagedep;
8584 		FREE_LOCK(ump);
8585 		/*
8586 		 * If we extended into an indirect signal direnter to sync.
8587 		 */
8588 		if (isindir)
8589 			return (1);
8590 		return (0);
8591 	}
8592 	FREE_LOCK(ump);
8593 	return (0);
8594 }
8595 
8596 /*
8597  * This procedure is called to change the offset of a directory
8598  * entry when compacting a directory block which must be owned
8599  * exclusively by the caller. Note that the actual entry movement
8600  * must be done in this procedure to ensure that no I/O completions
8601  * occur while the move is in progress.
8602  */
8603 void
8604 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
8605 	struct buf *bp;		/* Buffer holding directory block. */
8606 	struct inode *dp;	/* inode for directory */
8607 	caddr_t base;		/* address of dp->i_offset */
8608 	caddr_t oldloc;		/* address of old directory location */
8609 	caddr_t newloc;		/* address of new directory location */
8610 	int entrysize;		/* size of directory entry */
8611 {
8612 	int offset, oldoffset, newoffset;
8613 	struct pagedep *pagedep;
8614 	struct jmvref *jmvref;
8615 	struct diradd *dap;
8616 	struct direct *de;
8617 	struct mount *mp;
8618 	ufs_lbn_t lbn;
8619 	int flags;
8620 
8621 	mp = UFSTOVFS(dp->i_ump);
8622 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8623 	    ("softdep_change_directoryentry_offset called on "
8624 	     "non-softdep filesystem"));
8625 	de = (struct direct *)oldloc;
8626 	jmvref = NULL;
8627 	flags = 0;
8628 	/*
8629 	 * Moves are always journaled as it would be too complex to
8630 	 * determine if any affected adds or removes are present in the
8631 	 * journal.
8632 	 */
8633 	if (MOUNTEDSUJ(mp)) {
8634 		flags = DEPALLOC;
8635 		jmvref = newjmvref(dp, de->d_ino,
8636 		    dp->i_offset + (oldloc - base),
8637 		    dp->i_offset + (newloc - base));
8638 	}
8639 	lbn = lblkno(dp->i_fs, dp->i_offset);
8640 	offset = blkoff(dp->i_fs, dp->i_offset);
8641 	oldoffset = offset + (oldloc - base);
8642 	newoffset = offset + (newloc - base);
8643 	ACQUIRE_LOCK(dp->i_ump);
8644 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
8645 		goto done;
8646 	dap = diradd_lookup(pagedep, oldoffset);
8647 	if (dap) {
8648 		dap->da_offset = newoffset;
8649 		newoffset = DIRADDHASH(newoffset);
8650 		oldoffset = DIRADDHASH(oldoffset);
8651 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
8652 		    newoffset != oldoffset) {
8653 			LIST_REMOVE(dap, da_pdlist);
8654 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
8655 			    dap, da_pdlist);
8656 		}
8657 	}
8658 done:
8659 	if (jmvref) {
8660 		jmvref->jm_pagedep = pagedep;
8661 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
8662 		add_to_journal(&jmvref->jm_list);
8663 	}
8664 	bcopy(oldloc, newloc, entrysize);
8665 	FREE_LOCK(dp->i_ump);
8666 }
8667 
8668 /*
8669  * Move the mkdir dependencies and journal work from one diradd to another
8670  * when renaming a directory.  The new name must depend on the mkdir deps
8671  * completing as the old name did.  Directories can only have one valid link
8672  * at a time so one must be canonical.
8673  */
8674 static void
8675 merge_diradd(inodedep, newdap)
8676 	struct inodedep *inodedep;
8677 	struct diradd *newdap;
8678 {
8679 	struct diradd *olddap;
8680 	struct mkdir *mkdir, *nextmd;
8681 	struct ufsmount *ump;
8682 	short state;
8683 
8684 	olddap = inodedep->id_mkdiradd;
8685 	inodedep->id_mkdiradd = newdap;
8686 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8687 		newdap->da_state &= ~DEPCOMPLETE;
8688 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
8689 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8690 		     mkdir = nextmd) {
8691 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8692 			if (mkdir->md_diradd != olddap)
8693 				continue;
8694 			mkdir->md_diradd = newdap;
8695 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
8696 			newdap->da_state |= state;
8697 			olddap->da_state &= ~state;
8698 			if ((olddap->da_state &
8699 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
8700 				break;
8701 		}
8702 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8703 			panic("merge_diradd: unfound ref");
8704 	}
8705 	/*
8706 	 * Any mkdir related journal items are not safe to be freed until
8707 	 * the new name is stable.
8708 	 */
8709 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
8710 	olddap->da_state |= DEPCOMPLETE;
8711 	complete_diradd(olddap);
8712 }
8713 
8714 /*
8715  * Move the diradd to the pending list when all diradd dependencies are
8716  * complete.
8717  */
8718 static void
8719 complete_diradd(dap)
8720 	struct diradd *dap;
8721 {
8722 	struct pagedep *pagedep;
8723 
8724 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
8725 		if (dap->da_state & DIRCHG)
8726 			pagedep = dap->da_previous->dm_pagedep;
8727 		else
8728 			pagedep = dap->da_pagedep;
8729 		LIST_REMOVE(dap, da_pdlist);
8730 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
8731 	}
8732 }
8733 
8734 /*
8735  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
8736  * add entries and conditonally journal the remove.
8737  */
8738 static void
8739 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
8740 	struct diradd *dap;
8741 	struct dirrem *dirrem;
8742 	struct jremref *jremref;
8743 	struct jremref *dotremref;
8744 	struct jremref *dotdotremref;
8745 {
8746 	struct inodedep *inodedep;
8747 	struct jaddref *jaddref;
8748 	struct inoref *inoref;
8749 	struct ufsmount *ump;
8750 	struct mkdir *mkdir;
8751 
8752 	/*
8753 	 * If no remove references were allocated we're on a non-journaled
8754 	 * filesystem and can skip the cancel step.
8755 	 */
8756 	if (jremref == NULL) {
8757 		free_diradd(dap, NULL);
8758 		return;
8759 	}
8760 	/*
8761 	 * Cancel the primary name an free it if it does not require
8762 	 * journaling.
8763 	 */
8764 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
8765 	    0, &inodedep) != 0) {
8766 		/* Abort the addref that reference this diradd.  */
8767 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
8768 			if (inoref->if_list.wk_type != D_JADDREF)
8769 				continue;
8770 			jaddref = (struct jaddref *)inoref;
8771 			if (jaddref->ja_diradd != dap)
8772 				continue;
8773 			if (cancel_jaddref(jaddref, inodedep,
8774 			    &dirrem->dm_jwork) == 0) {
8775 				free_jremref(jremref);
8776 				jremref = NULL;
8777 			}
8778 			break;
8779 		}
8780 	}
8781 	/*
8782 	 * Cancel subordinate names and free them if they do not require
8783 	 * journaling.
8784 	 */
8785 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8786 		ump = VFSTOUFS(dap->da_list.wk_mp);
8787 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
8788 			if (mkdir->md_diradd != dap)
8789 				continue;
8790 			if ((jaddref = mkdir->md_jaddref) == NULL)
8791 				continue;
8792 			mkdir->md_jaddref = NULL;
8793 			if (mkdir->md_state & MKDIR_PARENT) {
8794 				if (cancel_jaddref(jaddref, NULL,
8795 				    &dirrem->dm_jwork) == 0) {
8796 					free_jremref(dotdotremref);
8797 					dotdotremref = NULL;
8798 				}
8799 			} else {
8800 				if (cancel_jaddref(jaddref, inodedep,
8801 				    &dirrem->dm_jwork) == 0) {
8802 					free_jremref(dotremref);
8803 					dotremref = NULL;
8804 				}
8805 			}
8806 		}
8807 	}
8808 
8809 	if (jremref)
8810 		journal_jremref(dirrem, jremref, inodedep);
8811 	if (dotremref)
8812 		journal_jremref(dirrem, dotremref, inodedep);
8813 	if (dotdotremref)
8814 		journal_jremref(dirrem, dotdotremref, NULL);
8815 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
8816 	free_diradd(dap, &dirrem->dm_jwork);
8817 }
8818 
8819 /*
8820  * Free a diradd dependency structure. This routine must be called
8821  * with splbio interrupts blocked.
8822  */
8823 static void
8824 free_diradd(dap, wkhd)
8825 	struct diradd *dap;
8826 	struct workhead *wkhd;
8827 {
8828 	struct dirrem *dirrem;
8829 	struct pagedep *pagedep;
8830 	struct inodedep *inodedep;
8831 	struct mkdir *mkdir, *nextmd;
8832 	struct ufsmount *ump;
8833 
8834 	ump = VFSTOUFS(dap->da_list.wk_mp);
8835 	LOCK_OWNED(ump);
8836 	LIST_REMOVE(dap, da_pdlist);
8837 	if (dap->da_state & ONWORKLIST)
8838 		WORKLIST_REMOVE(&dap->da_list);
8839 	if ((dap->da_state & DIRCHG) == 0) {
8840 		pagedep = dap->da_pagedep;
8841 	} else {
8842 		dirrem = dap->da_previous;
8843 		pagedep = dirrem->dm_pagedep;
8844 		dirrem->dm_dirinum = pagedep->pd_ino;
8845 		dirrem->dm_state |= COMPLETE;
8846 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
8847 			add_to_worklist(&dirrem->dm_list, 0);
8848 	}
8849 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
8850 	    0, &inodedep) != 0)
8851 		if (inodedep->id_mkdiradd == dap)
8852 			inodedep->id_mkdiradd = NULL;
8853 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
8854 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
8855 		     mkdir = nextmd) {
8856 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
8857 			if (mkdir->md_diradd != dap)
8858 				continue;
8859 			dap->da_state &=
8860 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
8861 			LIST_REMOVE(mkdir, md_mkdirs);
8862 			if (mkdir->md_state & ONWORKLIST)
8863 				WORKLIST_REMOVE(&mkdir->md_list);
8864 			if (mkdir->md_jaddref != NULL)
8865 				panic("free_diradd: Unexpected jaddref");
8866 			WORKITEM_FREE(mkdir, D_MKDIR);
8867 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
8868 				break;
8869 		}
8870 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
8871 			panic("free_diradd: unfound ref");
8872 	}
8873 	if (inodedep)
8874 		free_inodedep(inodedep);
8875 	/*
8876 	 * Free any journal segments waiting for the directory write.
8877 	 */
8878 	handle_jwork(&dap->da_jwork);
8879 	WORKITEM_FREE(dap, D_DIRADD);
8880 }
8881 
8882 /*
8883  * Directory entry removal dependencies.
8884  *
8885  * When removing a directory entry, the entry's inode pointer must be
8886  * zero'ed on disk before the corresponding inode's link count is decremented
8887  * (possibly freeing the inode for re-use). This dependency is handled by
8888  * updating the directory entry but delaying the inode count reduction until
8889  * after the directory block has been written to disk. After this point, the
8890  * inode count can be decremented whenever it is convenient.
8891  */
8892 
8893 /*
8894  * This routine should be called immediately after removing
8895  * a directory entry.  The inode's link count should not be
8896  * decremented by the calling procedure -- the soft updates
8897  * code will do this task when it is safe.
8898  */
8899 void
8900 softdep_setup_remove(bp, dp, ip, isrmdir)
8901 	struct buf *bp;		/* buffer containing directory block */
8902 	struct inode *dp;	/* inode for the directory being modified */
8903 	struct inode *ip;	/* inode for directory entry being removed */
8904 	int isrmdir;		/* indicates if doing RMDIR */
8905 {
8906 	struct dirrem *dirrem, *prevdirrem;
8907 	struct inodedep *inodedep;
8908 	int direct;
8909 
8910 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
8911 	    ("softdep_setup_remove called on non-softdep filesystem"));
8912 	/*
8913 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
8914 	 * newdirrem() to setup the full directory remove which requires
8915 	 * isrmdir > 1.
8916 	 */
8917 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
8918 	/*
8919 	 * Add the dirrem to the inodedep's pending remove list for quick
8920 	 * discovery later.
8921 	 */
8922 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
8923 	    &inodedep) == 0)
8924 		panic("softdep_setup_remove: Lost inodedep.");
8925 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
8926 	dirrem->dm_state |= ONDEPLIST;
8927 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
8928 
8929 	/*
8930 	 * If the COMPLETE flag is clear, then there were no active
8931 	 * entries and we want to roll back to a zeroed entry until
8932 	 * the new inode is committed to disk. If the COMPLETE flag is
8933 	 * set then we have deleted an entry that never made it to
8934 	 * disk. If the entry we deleted resulted from a name change,
8935 	 * then the old name still resides on disk. We cannot delete
8936 	 * its inode (returned to us in prevdirrem) until the zeroed
8937 	 * directory entry gets to disk. The new inode has never been
8938 	 * referenced on the disk, so can be deleted immediately.
8939 	 */
8940 	if ((dirrem->dm_state & COMPLETE) == 0) {
8941 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
8942 		    dm_next);
8943 		FREE_LOCK(ip->i_ump);
8944 	} else {
8945 		if (prevdirrem != NULL)
8946 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
8947 			    prevdirrem, dm_next);
8948 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
8949 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
8950 		FREE_LOCK(ip->i_ump);
8951 		if (direct)
8952 			handle_workitem_remove(dirrem, 0);
8953 	}
8954 }
8955 
8956 /*
8957  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
8958  * pd_pendinghd list of a pagedep.
8959  */
8960 static struct diradd *
8961 diradd_lookup(pagedep, offset)
8962 	struct pagedep *pagedep;
8963 	int offset;
8964 {
8965 	struct diradd *dap;
8966 
8967 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
8968 		if (dap->da_offset == offset)
8969 			return (dap);
8970 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
8971 		if (dap->da_offset == offset)
8972 			return (dap);
8973 	return (NULL);
8974 }
8975 
8976 /*
8977  * Search for a .. diradd dependency in a directory that is being removed.
8978  * If the directory was renamed to a new parent we have a diradd rather
8979  * than a mkdir for the .. entry.  We need to cancel it now before
8980  * it is found in truncate().
8981  */
8982 static struct jremref *
8983 cancel_diradd_dotdot(ip, dirrem, jremref)
8984 	struct inode *ip;
8985 	struct dirrem *dirrem;
8986 	struct jremref *jremref;
8987 {
8988 	struct pagedep *pagedep;
8989 	struct diradd *dap;
8990 	struct worklist *wk;
8991 
8992 	if (pagedep_lookup(UFSTOVFS(ip->i_ump), NULL, ip->i_number, 0, 0,
8993 	    &pagedep) == 0)
8994 		return (jremref);
8995 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
8996 	if (dap == NULL)
8997 		return (jremref);
8998 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
8999 	/*
9000 	 * Mark any journal work as belonging to the parent so it is freed
9001 	 * with the .. reference.
9002 	 */
9003 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9004 		wk->wk_state |= MKDIR_PARENT;
9005 	return (NULL);
9006 }
9007 
9008 /*
9009  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9010  * replace it with a dirrem/diradd pair as a result of re-parenting a
9011  * directory.  This ensures that we don't simultaneously have a mkdir and
9012  * a diradd for the same .. entry.
9013  */
9014 static struct jremref *
9015 cancel_mkdir_dotdot(ip, dirrem, jremref)
9016 	struct inode *ip;
9017 	struct dirrem *dirrem;
9018 	struct jremref *jremref;
9019 {
9020 	struct inodedep *inodedep;
9021 	struct jaddref *jaddref;
9022 	struct ufsmount *ump;
9023 	struct mkdir *mkdir;
9024 	struct diradd *dap;
9025 
9026 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
9027 	    &inodedep) == 0)
9028 		return (jremref);
9029 	dap = inodedep->id_mkdiradd;
9030 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9031 		return (jremref);
9032 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9033 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9034 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9035 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9036 			break;
9037 	if (mkdir == NULL)
9038 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9039 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9040 		mkdir->md_jaddref = NULL;
9041 		jaddref->ja_state &= ~MKDIR_PARENT;
9042 		if (inodedep_lookup(UFSTOVFS(ip->i_ump), jaddref->ja_ino, 0,
9043 		    &inodedep) == 0)
9044 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9045 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9046 			journal_jremref(dirrem, jremref, inodedep);
9047 			jremref = NULL;
9048 		}
9049 	}
9050 	if (mkdir->md_state & ONWORKLIST)
9051 		WORKLIST_REMOVE(&mkdir->md_list);
9052 	mkdir->md_state |= ALLCOMPLETE;
9053 	complete_mkdir(mkdir);
9054 	return (jremref);
9055 }
9056 
9057 static void
9058 journal_jremref(dirrem, jremref, inodedep)
9059 	struct dirrem *dirrem;
9060 	struct jremref *jremref;
9061 	struct inodedep *inodedep;
9062 {
9063 
9064 	if (inodedep == NULL)
9065 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9066 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9067 			panic("journal_jremref: Lost inodedep");
9068 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9069 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9070 	add_to_journal(&jremref->jr_list);
9071 }
9072 
9073 static void
9074 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9075 	struct dirrem *dirrem;
9076 	struct jremref *jremref;
9077 	struct jremref *dotremref;
9078 	struct jremref *dotdotremref;
9079 {
9080 	struct inodedep *inodedep;
9081 
9082 
9083 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9084 	    &inodedep) == 0)
9085 		panic("dirrem_journal: Lost inodedep");
9086 	journal_jremref(dirrem, jremref, inodedep);
9087 	if (dotremref)
9088 		journal_jremref(dirrem, dotremref, inodedep);
9089 	if (dotdotremref)
9090 		journal_jremref(dirrem, dotdotremref, NULL);
9091 }
9092 
9093 /*
9094  * Allocate a new dirrem if appropriate and return it along with
9095  * its associated pagedep. Called without a lock, returns with lock.
9096  */
9097 static struct dirrem *
9098 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9099 	struct buf *bp;		/* buffer containing directory block */
9100 	struct inode *dp;	/* inode for the directory being modified */
9101 	struct inode *ip;	/* inode for directory entry being removed */
9102 	int isrmdir;		/* indicates if doing RMDIR */
9103 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9104 {
9105 	int offset;
9106 	ufs_lbn_t lbn;
9107 	struct diradd *dap;
9108 	struct dirrem *dirrem;
9109 	struct pagedep *pagedep;
9110 	struct jremref *jremref;
9111 	struct jremref *dotremref;
9112 	struct jremref *dotdotremref;
9113 	struct vnode *dvp;
9114 
9115 	/*
9116 	 * Whiteouts have no deletion dependencies.
9117 	 */
9118 	if (ip == NULL)
9119 		panic("newdirrem: whiteout");
9120 	dvp = ITOV(dp);
9121 	/*
9122 	 * If the system is over its limit and our filesystem is
9123 	 * responsible for more than our share of that usage and
9124 	 * we are not a snapshot, request some inodedep cleanup.
9125 	 * Limiting the number of dirrem structures will also limit
9126 	 * the number of freefile and freeblks structures.
9127 	 */
9128 	ACQUIRE_LOCK(ip->i_ump);
9129 	while (!IS_SNAPSHOT(ip) && dep_current[D_DIRREM] > max_softdeps / 2 &&
9130 	    ip->i_ump->softdep_curdeps[D_DIRREM] >
9131 	    (max_softdeps / 2) / stat_flush_threads)
9132 		(void) request_cleanup(ITOV(dp)->v_mount, FLUSH_BLOCKS);
9133 	FREE_LOCK(ip->i_ump);
9134 	dirrem = malloc(sizeof(struct dirrem),
9135 		M_DIRREM, M_SOFTDEP_FLAGS|M_ZERO);
9136 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9137 	LIST_INIT(&dirrem->dm_jremrefhd);
9138 	LIST_INIT(&dirrem->dm_jwork);
9139 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9140 	dirrem->dm_oldinum = ip->i_number;
9141 	*prevdirremp = NULL;
9142 	/*
9143 	 * Allocate remove reference structures to track journal write
9144 	 * dependencies.  We will always have one for the link and
9145 	 * when doing directories we will always have one more for dot.
9146 	 * When renaming a directory we skip the dotdot link change so
9147 	 * this is not needed.
9148 	 */
9149 	jremref = dotremref = dotdotremref = NULL;
9150 	if (DOINGSUJ(dvp)) {
9151 		if (isrmdir) {
9152 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9153 			    ip->i_effnlink + 2);
9154 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9155 			    ip->i_effnlink + 1);
9156 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9157 			    dp->i_effnlink + 1);
9158 			dotdotremref->jr_state |= MKDIR_PARENT;
9159 		} else
9160 			jremref = newjremref(dirrem, dp, ip, dp->i_offset,
9161 			    ip->i_effnlink + 1);
9162 	}
9163 	ACQUIRE_LOCK(ip->i_ump);
9164 	lbn = lblkno(dp->i_fs, dp->i_offset);
9165 	offset = blkoff(dp->i_fs, dp->i_offset);
9166 	pagedep_lookup(UFSTOVFS(dp->i_ump), bp, dp->i_number, lbn, DEPALLOC,
9167 	    &pagedep);
9168 	dirrem->dm_pagedep = pagedep;
9169 	dirrem->dm_offset = offset;
9170 	/*
9171 	 * If we're renaming a .. link to a new directory, cancel any
9172 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9173 	 * the jremref is preserved for any potential diradd in this
9174 	 * location.  This can not coincide with a rmdir.
9175 	 */
9176 	if (dp->i_offset == DOTDOT_OFFSET) {
9177 		if (isrmdir)
9178 			panic("newdirrem: .. directory change during remove?");
9179 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9180 	}
9181 	/*
9182 	 * If we're removing a directory search for the .. dependency now and
9183 	 * cancel it.  Any pending journal work will be added to the dirrem
9184 	 * to be completed when the workitem remove completes.
9185 	 */
9186 	if (isrmdir)
9187 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9188 	/*
9189 	 * Check for a diradd dependency for the same directory entry.
9190 	 * If present, then both dependencies become obsolete and can
9191 	 * be de-allocated.
9192 	 */
9193 	dap = diradd_lookup(pagedep, offset);
9194 	if (dap == NULL) {
9195 		/*
9196 		 * Link the jremref structures into the dirrem so they are
9197 		 * written prior to the pagedep.
9198 		 */
9199 		if (jremref)
9200 			dirrem_journal(dirrem, jremref, dotremref,
9201 			    dotdotremref);
9202 		return (dirrem);
9203 	}
9204 	/*
9205 	 * Must be ATTACHED at this point.
9206 	 */
9207 	if ((dap->da_state & ATTACHED) == 0)
9208 		panic("newdirrem: not ATTACHED");
9209 	if (dap->da_newinum != ip->i_number)
9210 		panic("newdirrem: inum %ju should be %ju",
9211 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9212 	/*
9213 	 * If we are deleting a changed name that never made it to disk,
9214 	 * then return the dirrem describing the previous inode (which
9215 	 * represents the inode currently referenced from this entry on disk).
9216 	 */
9217 	if ((dap->da_state & DIRCHG) != 0) {
9218 		*prevdirremp = dap->da_previous;
9219 		dap->da_state &= ~DIRCHG;
9220 		dap->da_pagedep = pagedep;
9221 	}
9222 	/*
9223 	 * We are deleting an entry that never made it to disk.
9224 	 * Mark it COMPLETE so we can delete its inode immediately.
9225 	 */
9226 	dirrem->dm_state |= COMPLETE;
9227 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9228 #ifdef SUJ_DEBUG
9229 	if (isrmdir == 0) {
9230 		struct worklist *wk;
9231 
9232 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9233 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9234 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9235 	}
9236 #endif
9237 
9238 	return (dirrem);
9239 }
9240 
9241 /*
9242  * Directory entry change dependencies.
9243  *
9244  * Changing an existing directory entry requires that an add operation
9245  * be completed first followed by a deletion. The semantics for the addition
9246  * are identical to the description of adding a new entry above except
9247  * that the rollback is to the old inode number rather than zero. Once
9248  * the addition dependency is completed, the removal is done as described
9249  * in the removal routine above.
9250  */
9251 
9252 /*
9253  * This routine should be called immediately after changing
9254  * a directory entry.  The inode's link count should not be
9255  * decremented by the calling procedure -- the soft updates
9256  * code will perform this task when it is safe.
9257  */
9258 void
9259 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9260 	struct buf *bp;		/* buffer containing directory block */
9261 	struct inode *dp;	/* inode for the directory being modified */
9262 	struct inode *ip;	/* inode for directory entry being removed */
9263 	ino_t newinum;		/* new inode number for changed entry */
9264 	int isrmdir;		/* indicates if doing RMDIR */
9265 {
9266 	int offset;
9267 	struct diradd *dap = NULL;
9268 	struct dirrem *dirrem, *prevdirrem;
9269 	struct pagedep *pagedep;
9270 	struct inodedep *inodedep;
9271 	struct jaddref *jaddref;
9272 	struct mount *mp;
9273 
9274 	offset = blkoff(dp->i_fs, dp->i_offset);
9275 	mp = UFSTOVFS(dp->i_ump);
9276 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9277 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9278 
9279 	/*
9280 	 * Whiteouts do not need diradd dependencies.
9281 	 */
9282 	if (newinum != WINO) {
9283 		dap = malloc(sizeof(struct diradd),
9284 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9285 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9286 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9287 		dap->da_offset = offset;
9288 		dap->da_newinum = newinum;
9289 		LIST_INIT(&dap->da_jwork);
9290 	}
9291 
9292 	/*
9293 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9294 	 */
9295 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9296 	pagedep = dirrem->dm_pagedep;
9297 	/*
9298 	 * The possible values for isrmdir:
9299 	 *	0 - non-directory file rename
9300 	 *	1 - directory rename within same directory
9301 	 *   inum - directory rename to new directory of given inode number
9302 	 * When renaming to a new directory, we are both deleting and
9303 	 * creating a new directory entry, so the link count on the new
9304 	 * directory should not change. Thus we do not need the followup
9305 	 * dirrem which is usually done in handle_workitem_remove. We set
9306 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9307 	 * followup dirrem.
9308 	 */
9309 	if (isrmdir > 1)
9310 		dirrem->dm_state |= DIRCHG;
9311 
9312 	/*
9313 	 * Whiteouts have no additional dependencies,
9314 	 * so just put the dirrem on the correct list.
9315 	 */
9316 	if (newinum == WINO) {
9317 		if ((dirrem->dm_state & COMPLETE) == 0) {
9318 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9319 			    dm_next);
9320 		} else {
9321 			dirrem->dm_dirinum = pagedep->pd_ino;
9322 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9323 				add_to_worklist(&dirrem->dm_list, 0);
9324 		}
9325 		FREE_LOCK(dp->i_ump);
9326 		return;
9327 	}
9328 	/*
9329 	 * Add the dirrem to the inodedep's pending remove list for quick
9330 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9331 	 * will not fail.
9332 	 */
9333 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9334 		panic("softdep_setup_directory_change: Lost inodedep.");
9335 	dirrem->dm_state |= ONDEPLIST;
9336 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9337 
9338 	/*
9339 	 * If the COMPLETE flag is clear, then there were no active
9340 	 * entries and we want to roll back to the previous inode until
9341 	 * the new inode is committed to disk. If the COMPLETE flag is
9342 	 * set, then we have deleted an entry that never made it to disk.
9343 	 * If the entry we deleted resulted from a name change, then the old
9344 	 * inode reference still resides on disk. Any rollback that we do
9345 	 * needs to be to that old inode (returned to us in prevdirrem). If
9346 	 * the entry we deleted resulted from a create, then there is
9347 	 * no entry on the disk, so we want to roll back to zero rather
9348 	 * than the uncommitted inode. In either of the COMPLETE cases we
9349 	 * want to immediately free the unwritten and unreferenced inode.
9350 	 */
9351 	if ((dirrem->dm_state & COMPLETE) == 0) {
9352 		dap->da_previous = dirrem;
9353 	} else {
9354 		if (prevdirrem != NULL) {
9355 			dap->da_previous = prevdirrem;
9356 		} else {
9357 			dap->da_state &= ~DIRCHG;
9358 			dap->da_pagedep = pagedep;
9359 		}
9360 		dirrem->dm_dirinum = pagedep->pd_ino;
9361 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9362 			add_to_worklist(&dirrem->dm_list, 0);
9363 	}
9364 	/*
9365 	 * Lookup the jaddref for this journal entry.  We must finish
9366 	 * initializing it and make the diradd write dependent on it.
9367 	 * If we're not journaling, put it on the id_bufwait list if the
9368 	 * inode is not yet written. If it is written, do the post-inode
9369 	 * write processing to put it on the id_pendinghd list.
9370 	 */
9371 	inodedep_lookup(mp, newinum, DEPALLOC | NODELAY, &inodedep);
9372 	if (MOUNTEDSUJ(mp)) {
9373 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9374 		    inoreflst);
9375 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9376 		    ("softdep_setup_directory_change: bad jaddref %p",
9377 		    jaddref));
9378 		jaddref->ja_diroff = dp->i_offset;
9379 		jaddref->ja_diradd = dap;
9380 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9381 		    dap, da_pdlist);
9382 		add_to_journal(&jaddref->ja_list);
9383 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9384 		dap->da_state |= COMPLETE;
9385 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9386 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9387 	} else {
9388 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9389 		    dap, da_pdlist);
9390 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9391 	}
9392 	/*
9393 	 * If we're making a new name for a directory that has not been
9394 	 * committed when need to move the dot and dotdot references to
9395 	 * this new name.
9396 	 */
9397 	if (inodedep->id_mkdiradd && dp->i_offset != DOTDOT_OFFSET)
9398 		merge_diradd(inodedep, dap);
9399 	FREE_LOCK(dp->i_ump);
9400 }
9401 
9402 /*
9403  * Called whenever the link count on an inode is changed.
9404  * It creates an inode dependency so that the new reference(s)
9405  * to the inode cannot be committed to disk until the updated
9406  * inode has been written.
9407  */
9408 void
9409 softdep_change_linkcnt(ip)
9410 	struct inode *ip;	/* the inode with the increased link count */
9411 {
9412 	struct inodedep *inodedep;
9413 	int dflags;
9414 
9415 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
9416 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9417 	ACQUIRE_LOCK(ip->i_ump);
9418 	dflags = DEPALLOC;
9419 	if (IS_SNAPSHOT(ip))
9420 		dflags |= NODELAY;
9421 	inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, dflags, &inodedep);
9422 	if (ip->i_nlink < ip->i_effnlink)
9423 		panic("softdep_change_linkcnt: bad delta");
9424 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9425 	FREE_LOCK(ip->i_ump);
9426 }
9427 
9428 /*
9429  * Attach a sbdep dependency to the superblock buf so that we can keep
9430  * track of the head of the linked list of referenced but unlinked inodes.
9431  */
9432 void
9433 softdep_setup_sbupdate(ump, fs, bp)
9434 	struct ufsmount *ump;
9435 	struct fs *fs;
9436 	struct buf *bp;
9437 {
9438 	struct sbdep *sbdep;
9439 	struct worklist *wk;
9440 
9441 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9442 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9443 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9444 		if (wk->wk_type == D_SBDEP)
9445 			break;
9446 	if (wk != NULL)
9447 		return;
9448 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9449 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9450 	sbdep->sb_fs = fs;
9451 	sbdep->sb_ump = ump;
9452 	ACQUIRE_LOCK(ump);
9453 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9454 	FREE_LOCK(ump);
9455 }
9456 
9457 /*
9458  * Return the first unlinked inodedep which is ready to be the head of the
9459  * list.  The inodedep and all those after it must have valid next pointers.
9460  */
9461 static struct inodedep *
9462 first_unlinked_inodedep(ump)
9463 	struct ufsmount *ump;
9464 {
9465 	struct inodedep *inodedep;
9466 	struct inodedep *idp;
9467 
9468 	LOCK_OWNED(ump);
9469 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9470 	    inodedep; inodedep = idp) {
9471 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9472 			return (NULL);
9473 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9474 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9475 			break;
9476 		if ((inodedep->id_state & UNLINKPREV) == 0)
9477 			break;
9478 	}
9479 	return (inodedep);
9480 }
9481 
9482 /*
9483  * Set the sujfree unlinked head pointer prior to writing a superblock.
9484  */
9485 static void
9486 initiate_write_sbdep(sbdep)
9487 	struct sbdep *sbdep;
9488 {
9489 	struct inodedep *inodedep;
9490 	struct fs *bpfs;
9491 	struct fs *fs;
9492 
9493 	bpfs = sbdep->sb_fs;
9494 	fs = sbdep->sb_ump->um_fs;
9495 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9496 	if (inodedep) {
9497 		fs->fs_sujfree = inodedep->id_ino;
9498 		inodedep->id_state |= UNLINKPREV;
9499 	} else
9500 		fs->fs_sujfree = 0;
9501 	bpfs->fs_sujfree = fs->fs_sujfree;
9502 }
9503 
9504 /*
9505  * After a superblock is written determine whether it must be written again
9506  * due to a changing unlinked list head.
9507  */
9508 static int
9509 handle_written_sbdep(sbdep, bp)
9510 	struct sbdep *sbdep;
9511 	struct buf *bp;
9512 {
9513 	struct inodedep *inodedep;
9514 	struct mount *mp;
9515 	struct fs *fs;
9516 
9517 	LOCK_OWNED(sbdep->sb_ump);
9518 	fs = sbdep->sb_fs;
9519 	mp = UFSTOVFS(sbdep->sb_ump);
9520 	/*
9521 	 * If the superblock doesn't match the in-memory list start over.
9522 	 */
9523 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9524 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9525 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9526 		bdirty(bp);
9527 		return (1);
9528 	}
9529 	WORKITEM_FREE(sbdep, D_SBDEP);
9530 	if (fs->fs_sujfree == 0)
9531 		return (0);
9532 	/*
9533 	 * Now that we have a record of this inode in stable store allow it
9534 	 * to be written to free up pending work.  Inodes may see a lot of
9535 	 * write activity after they are unlinked which we must not hold up.
9536 	 */
9537 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9538 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9539 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9540 			    inodedep, inodedep->id_state);
9541 		if (inodedep->id_state & UNLINKONLIST)
9542 			break;
9543 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9544 	}
9545 
9546 	return (0);
9547 }
9548 
9549 /*
9550  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9551  */
9552 static void
9553 unlinked_inodedep(mp, inodedep)
9554 	struct mount *mp;
9555 	struct inodedep *inodedep;
9556 {
9557 	struct ufsmount *ump;
9558 
9559 	ump = VFSTOUFS(mp);
9560 	LOCK_OWNED(ump);
9561 	if (MOUNTEDSUJ(mp) == 0)
9562 		return;
9563 	ump->um_fs->fs_fmod = 1;
9564 	if (inodedep->id_state & UNLINKED)
9565 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
9566 	inodedep->id_state |= UNLINKED;
9567 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
9568 }
9569 
9570 /*
9571  * Remove an inodedep from the unlinked inodedep list.  This may require
9572  * disk writes if the inode has made it that far.
9573  */
9574 static void
9575 clear_unlinked_inodedep(inodedep)
9576 	struct inodedep *inodedep;
9577 {
9578 	struct ufsmount *ump;
9579 	struct inodedep *idp;
9580 	struct inodedep *idn;
9581 	struct fs *fs;
9582 	struct buf *bp;
9583 	ino_t ino;
9584 	ino_t nino;
9585 	ino_t pino;
9586 	int error;
9587 
9588 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9589 	fs = ump->um_fs;
9590 	ino = inodedep->id_ino;
9591 	error = 0;
9592 	for (;;) {
9593 		LOCK_OWNED(ump);
9594 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9595 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9596 		    inodedep));
9597 		/*
9598 		 * If nothing has yet been written simply remove us from
9599 		 * the in memory list and return.  This is the most common
9600 		 * case where handle_workitem_remove() loses the final
9601 		 * reference.
9602 		 */
9603 		if ((inodedep->id_state & UNLINKLINKS) == 0)
9604 			break;
9605 		/*
9606 		 * If we have a NEXT pointer and no PREV pointer we can simply
9607 		 * clear NEXT's PREV and remove ourselves from the list.  Be
9608 		 * careful not to clear PREV if the superblock points at
9609 		 * next as well.
9610 		 */
9611 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9612 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
9613 			if (idn && fs->fs_sujfree != idn->id_ino)
9614 				idn->id_state &= ~UNLINKPREV;
9615 			break;
9616 		}
9617 		/*
9618 		 * Here we have an inodedep which is actually linked into
9619 		 * the list.  We must remove it by forcing a write to the
9620 		 * link before us, whether it be the superblock or an inode.
9621 		 * Unfortunately the list may change while we're waiting
9622 		 * on the buf lock for either resource so we must loop until
9623 		 * we lock the right one.  If both the superblock and an
9624 		 * inode point to this inode we must clear the inode first
9625 		 * followed by the superblock.
9626 		 */
9627 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9628 		pino = 0;
9629 		if (idp && (idp->id_state & UNLINKNEXT))
9630 			pino = idp->id_ino;
9631 		FREE_LOCK(ump);
9632 		if (pino == 0) {
9633 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9634 			    (int)fs->fs_sbsize, 0, 0, 0);
9635 		} else {
9636 			error = bread(ump->um_devvp,
9637 			    fsbtodb(fs, ino_to_fsba(fs, pino)),
9638 			    (int)fs->fs_bsize, NOCRED, &bp);
9639 			if (error)
9640 				brelse(bp);
9641 		}
9642 		ACQUIRE_LOCK(ump);
9643 		if (error)
9644 			break;
9645 		/* If the list has changed restart the loop. */
9646 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9647 		nino = 0;
9648 		if (idp && (idp->id_state & UNLINKNEXT))
9649 			nino = idp->id_ino;
9650 		if (nino != pino ||
9651 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
9652 			FREE_LOCK(ump);
9653 			brelse(bp);
9654 			ACQUIRE_LOCK(ump);
9655 			continue;
9656 		}
9657 		nino = 0;
9658 		idn = TAILQ_NEXT(inodedep, id_unlinked);
9659 		if (idn)
9660 			nino = idn->id_ino;
9661 		/*
9662 		 * Remove us from the in memory list.  After this we cannot
9663 		 * access the inodedep.
9664 		 */
9665 		KASSERT((inodedep->id_state & UNLINKED) != 0,
9666 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
9667 		    inodedep));
9668 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9669 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9670 		FREE_LOCK(ump);
9671 		/*
9672 		 * The predecessor's next pointer is manually updated here
9673 		 * so that the NEXT flag is never cleared for an element
9674 		 * that is in the list.
9675 		 */
9676 		if (pino == 0) {
9677 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9678 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9679 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9680 			    bp);
9681 		} else if (fs->fs_magic == FS_UFS1_MAGIC)
9682 			((struct ufs1_dinode *)bp->b_data +
9683 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9684 		else
9685 			((struct ufs2_dinode *)bp->b_data +
9686 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
9687 		/*
9688 		 * If the bwrite fails we have no recourse to recover.  The
9689 		 * filesystem is corrupted already.
9690 		 */
9691 		bwrite(bp);
9692 		ACQUIRE_LOCK(ump);
9693 		/*
9694 		 * If the superblock pointer still needs to be cleared force
9695 		 * a write here.
9696 		 */
9697 		if (fs->fs_sujfree == ino) {
9698 			FREE_LOCK(ump);
9699 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
9700 			    (int)fs->fs_sbsize, 0, 0, 0);
9701 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
9702 			ffs_oldfscompat_write((struct fs *)bp->b_data, ump);
9703 			softdep_setup_sbupdate(ump, (struct fs *)bp->b_data,
9704 			    bp);
9705 			bwrite(bp);
9706 			ACQUIRE_LOCK(ump);
9707 		}
9708 
9709 		if (fs->fs_sujfree != ino)
9710 			return;
9711 		panic("clear_unlinked_inodedep: Failed to clear free head");
9712 	}
9713 	if (inodedep->id_ino == fs->fs_sujfree)
9714 		panic("clear_unlinked_inodedep: Freeing head of free list");
9715 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
9716 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
9717 	return;
9718 }
9719 
9720 /*
9721  * This workitem decrements the inode's link count.
9722  * If the link count reaches zero, the file is removed.
9723  */
9724 static int
9725 handle_workitem_remove(dirrem, flags)
9726 	struct dirrem *dirrem;
9727 	int flags;
9728 {
9729 	struct inodedep *inodedep;
9730 	struct workhead dotdotwk;
9731 	struct worklist *wk;
9732 	struct ufsmount *ump;
9733 	struct mount *mp;
9734 	struct vnode *vp;
9735 	struct inode *ip;
9736 	ino_t oldinum;
9737 
9738 	if (dirrem->dm_state & ONWORKLIST)
9739 		panic("handle_workitem_remove: dirrem %p still on worklist",
9740 		    dirrem);
9741 	oldinum = dirrem->dm_oldinum;
9742 	mp = dirrem->dm_list.wk_mp;
9743 	ump = VFSTOUFS(mp);
9744 	flags |= LK_EXCLUSIVE;
9745 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
9746 		return (EBUSY);
9747 	ip = VTOI(vp);
9748 	ACQUIRE_LOCK(ump);
9749 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
9750 		panic("handle_workitem_remove: lost inodedep");
9751 	if (dirrem->dm_state & ONDEPLIST)
9752 		LIST_REMOVE(dirrem, dm_inonext);
9753 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
9754 	    ("handle_workitem_remove:  Journal entries not written."));
9755 
9756 	/*
9757 	 * Move all dependencies waiting on the remove to complete
9758 	 * from the dirrem to the inode inowait list to be completed
9759 	 * after the inode has been updated and written to disk.  Any
9760 	 * marked MKDIR_PARENT are saved to be completed when the .. ref
9761 	 * is removed.
9762 	 */
9763 	LIST_INIT(&dotdotwk);
9764 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
9765 		WORKLIST_REMOVE(wk);
9766 		if (wk->wk_state & MKDIR_PARENT) {
9767 			wk->wk_state &= ~MKDIR_PARENT;
9768 			WORKLIST_INSERT(&dotdotwk, wk);
9769 			continue;
9770 		}
9771 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
9772 	}
9773 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
9774 	/*
9775 	 * Normal file deletion.
9776 	 */
9777 	if ((dirrem->dm_state & RMDIR) == 0) {
9778 		ip->i_nlink--;
9779 		DIP_SET(ip, i_nlink, ip->i_nlink);
9780 		ip->i_flag |= IN_CHANGE;
9781 		if (ip->i_nlink < ip->i_effnlink)
9782 			panic("handle_workitem_remove: bad file delta");
9783 		if (ip->i_nlink == 0)
9784 			unlinked_inodedep(mp, inodedep);
9785 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9786 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9787 		    ("handle_workitem_remove: worklist not empty. %s",
9788 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
9789 		WORKITEM_FREE(dirrem, D_DIRREM);
9790 		FREE_LOCK(ump);
9791 		goto out;
9792 	}
9793 	/*
9794 	 * Directory deletion. Decrement reference count for both the
9795 	 * just deleted parent directory entry and the reference for ".".
9796 	 * Arrange to have the reference count on the parent decremented
9797 	 * to account for the loss of "..".
9798 	 */
9799 	ip->i_nlink -= 2;
9800 	DIP_SET(ip, i_nlink, ip->i_nlink);
9801 	ip->i_flag |= IN_CHANGE;
9802 	if (ip->i_nlink < ip->i_effnlink)
9803 		panic("handle_workitem_remove: bad dir delta");
9804 	if (ip->i_nlink == 0)
9805 		unlinked_inodedep(mp, inodedep);
9806 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9807 	/*
9808 	 * Rename a directory to a new parent. Since, we are both deleting
9809 	 * and creating a new directory entry, the link count on the new
9810 	 * directory should not change. Thus we skip the followup dirrem.
9811 	 */
9812 	if (dirrem->dm_state & DIRCHG) {
9813 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
9814 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
9815 		WORKITEM_FREE(dirrem, D_DIRREM);
9816 		FREE_LOCK(ump);
9817 		goto out;
9818 	}
9819 	dirrem->dm_state = ONDEPLIST;
9820 	dirrem->dm_oldinum = dirrem->dm_dirinum;
9821 	/*
9822 	 * Place the dirrem on the parent's diremhd list.
9823 	 */
9824 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
9825 		panic("handle_workitem_remove: lost dir inodedep");
9826 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9827 	/*
9828 	 * If the allocated inode has never been written to disk, then
9829 	 * the on-disk inode is zero'ed and we can remove the file
9830 	 * immediately.  When journaling if the inode has been marked
9831 	 * unlinked and not DEPCOMPLETE we know it can never be written.
9832 	 */
9833 	inodedep_lookup(mp, oldinum, 0, &inodedep);
9834 	if (inodedep == NULL ||
9835 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
9836 	    check_inode_unwritten(inodedep)) {
9837 		FREE_LOCK(ump);
9838 		vput(vp);
9839 		return handle_workitem_remove(dirrem, flags);
9840 	}
9841 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
9842 	FREE_LOCK(ump);
9843 	ip->i_flag |= IN_CHANGE;
9844 out:
9845 	ffs_update(vp, 0);
9846 	vput(vp);
9847 	return (0);
9848 }
9849 
9850 /*
9851  * Inode de-allocation dependencies.
9852  *
9853  * When an inode's link count is reduced to zero, it can be de-allocated. We
9854  * found it convenient to postpone de-allocation until after the inode is
9855  * written to disk with its new link count (zero).  At this point, all of the
9856  * on-disk inode's block pointers are nullified and, with careful dependency
9857  * list ordering, all dependencies related to the inode will be satisfied and
9858  * the corresponding dependency structures de-allocated.  So, if/when the
9859  * inode is reused, there will be no mixing of old dependencies with new
9860  * ones.  This artificial dependency is set up by the block de-allocation
9861  * procedure above (softdep_setup_freeblocks) and completed by the
9862  * following procedure.
9863  */
9864 static void
9865 handle_workitem_freefile(freefile)
9866 	struct freefile *freefile;
9867 {
9868 	struct workhead wkhd;
9869 	struct fs *fs;
9870 	struct inodedep *idp;
9871 	struct ufsmount *ump;
9872 	int error;
9873 
9874 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
9875 	fs = ump->um_fs;
9876 #ifdef DEBUG
9877 	ACQUIRE_LOCK(ump);
9878 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
9879 	FREE_LOCK(ump);
9880 	if (error)
9881 		panic("handle_workitem_freefile: inodedep %p survived", idp);
9882 #endif
9883 	UFS_LOCK(ump);
9884 	fs->fs_pendinginodes -= 1;
9885 	UFS_UNLOCK(ump);
9886 	LIST_INIT(&wkhd);
9887 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
9888 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
9889 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
9890 		softdep_error("handle_workitem_freefile", error);
9891 	ACQUIRE_LOCK(ump);
9892 	WORKITEM_FREE(freefile, D_FREEFILE);
9893 	FREE_LOCK(ump);
9894 }
9895 
9896 
9897 /*
9898  * Helper function which unlinks marker element from work list and returns
9899  * the next element on the list.
9900  */
9901 static __inline struct worklist *
9902 markernext(struct worklist *marker)
9903 {
9904 	struct worklist *next;
9905 
9906 	next = LIST_NEXT(marker, wk_list);
9907 	LIST_REMOVE(marker, wk_list);
9908 	return next;
9909 }
9910 
9911 /*
9912  * Disk writes.
9913  *
9914  * The dependency structures constructed above are most actively used when file
9915  * system blocks are written to disk.  No constraints are placed on when a
9916  * block can be written, but unsatisfied update dependencies are made safe by
9917  * modifying (or replacing) the source memory for the duration of the disk
9918  * write.  When the disk write completes, the memory block is again brought
9919  * up-to-date.
9920  *
9921  * In-core inode structure reclamation.
9922  *
9923  * Because there are a finite number of "in-core" inode structures, they are
9924  * reused regularly.  By transferring all inode-related dependencies to the
9925  * in-memory inode block and indexing them separately (via "inodedep"s), we
9926  * can allow "in-core" inode structures to be reused at any time and avoid
9927  * any increase in contention.
9928  *
9929  * Called just before entering the device driver to initiate a new disk I/O.
9930  * The buffer must be locked, thus, no I/O completion operations can occur
9931  * while we are manipulating its associated dependencies.
9932  */
9933 static void
9934 softdep_disk_io_initiation(bp)
9935 	struct buf *bp;		/* structure describing disk write to occur */
9936 {
9937 	struct worklist *wk;
9938 	struct worklist marker;
9939 	struct inodedep *inodedep;
9940 	struct freeblks *freeblks;
9941 	struct jblkdep *jblkdep;
9942 	struct newblk *newblk;
9943 	struct ufsmount *ump;
9944 
9945 	/*
9946 	 * We only care about write operations. There should never
9947 	 * be dependencies for reads.
9948 	 */
9949 	if (bp->b_iocmd != BIO_WRITE)
9950 		panic("softdep_disk_io_initiation: not write");
9951 
9952 	if (bp->b_vflags & BV_BKGRDINPROG)
9953 		panic("softdep_disk_io_initiation: Writing buffer with "
9954 		    "background write in progress: %p", bp);
9955 
9956 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
9957 		return;
9958 	ump = VFSTOUFS(wk->wk_mp);
9959 
9960 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
9961 	PHOLD(curproc);			/* Don't swap out kernel stack */
9962 	ACQUIRE_LOCK(ump);
9963 	/*
9964 	 * Do any necessary pre-I/O processing.
9965 	 */
9966 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
9967 	     wk = markernext(&marker)) {
9968 		LIST_INSERT_AFTER(wk, &marker, wk_list);
9969 		switch (wk->wk_type) {
9970 
9971 		case D_PAGEDEP:
9972 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
9973 			continue;
9974 
9975 		case D_INODEDEP:
9976 			inodedep = WK_INODEDEP(wk);
9977 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
9978 				initiate_write_inodeblock_ufs1(inodedep, bp);
9979 			else
9980 				initiate_write_inodeblock_ufs2(inodedep, bp);
9981 			continue;
9982 
9983 		case D_INDIRDEP:
9984 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
9985 			continue;
9986 
9987 		case D_BMSAFEMAP:
9988 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
9989 			continue;
9990 
9991 		case D_JSEG:
9992 			WK_JSEG(wk)->js_buf = NULL;
9993 			continue;
9994 
9995 		case D_FREEBLKS:
9996 			freeblks = WK_FREEBLKS(wk);
9997 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
9998 			/*
9999 			 * We have to wait for the freeblks to be journaled
10000 			 * before we can write an inodeblock with updated
10001 			 * pointers.  Be careful to arrange the marker so
10002 			 * we revisit the freeblks if it's not removed by
10003 			 * the first jwait().
10004 			 */
10005 			if (jblkdep != NULL) {
10006 				LIST_REMOVE(&marker, wk_list);
10007 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10008 				jwait(&jblkdep->jb_list, MNT_WAIT);
10009 			}
10010 			continue;
10011 		case D_ALLOCDIRECT:
10012 		case D_ALLOCINDIR:
10013 			/*
10014 			 * We have to wait for the jnewblk to be journaled
10015 			 * before we can write to a block if the contents
10016 			 * may be confused with an earlier file's indirect
10017 			 * at recovery time.  Handle the marker as described
10018 			 * above.
10019 			 */
10020 			newblk = WK_NEWBLK(wk);
10021 			if (newblk->nb_jnewblk != NULL &&
10022 			    indirblk_lookup(newblk->nb_list.wk_mp,
10023 			    newblk->nb_newblkno)) {
10024 				LIST_REMOVE(&marker, wk_list);
10025 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10026 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10027 			}
10028 			continue;
10029 
10030 		case D_SBDEP:
10031 			initiate_write_sbdep(WK_SBDEP(wk));
10032 			continue;
10033 
10034 		case D_MKDIR:
10035 		case D_FREEWORK:
10036 		case D_FREEDEP:
10037 		case D_JSEGDEP:
10038 			continue;
10039 
10040 		default:
10041 			panic("handle_disk_io_initiation: Unexpected type %s",
10042 			    TYPENAME(wk->wk_type));
10043 			/* NOTREACHED */
10044 		}
10045 	}
10046 	FREE_LOCK(ump);
10047 	PRELE(curproc);			/* Allow swapout of kernel stack */
10048 }
10049 
10050 /*
10051  * Called from within the procedure above to deal with unsatisfied
10052  * allocation dependencies in a directory. The buffer must be locked,
10053  * thus, no I/O completion operations can occur while we are
10054  * manipulating its associated dependencies.
10055  */
10056 static void
10057 initiate_write_filepage(pagedep, bp)
10058 	struct pagedep *pagedep;
10059 	struct buf *bp;
10060 {
10061 	struct jremref *jremref;
10062 	struct jmvref *jmvref;
10063 	struct dirrem *dirrem;
10064 	struct diradd *dap;
10065 	struct direct *ep;
10066 	int i;
10067 
10068 	if (pagedep->pd_state & IOSTARTED) {
10069 		/*
10070 		 * This can only happen if there is a driver that does not
10071 		 * understand chaining. Here biodone will reissue the call
10072 		 * to strategy for the incomplete buffers.
10073 		 */
10074 		printf("initiate_write_filepage: already started\n");
10075 		return;
10076 	}
10077 	pagedep->pd_state |= IOSTARTED;
10078 	/*
10079 	 * Wait for all journal remove dependencies to hit the disk.
10080 	 * We can not allow any potentially conflicting directory adds
10081 	 * to be visible before removes and rollback is too difficult.
10082 	 * The per-filesystem lock may be dropped and re-acquired, however
10083 	 * we hold the buf locked so the dependency can not go away.
10084 	 */
10085 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10086 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10087 			jwait(&jremref->jr_list, MNT_WAIT);
10088 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10089 		jwait(&jmvref->jm_list, MNT_WAIT);
10090 	for (i = 0; i < DAHASHSZ; i++) {
10091 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10092 			ep = (struct direct *)
10093 			    ((char *)bp->b_data + dap->da_offset);
10094 			if (ep->d_ino != dap->da_newinum)
10095 				panic("%s: dir inum %ju != new %ju",
10096 				    "initiate_write_filepage",
10097 				    (uintmax_t)ep->d_ino,
10098 				    (uintmax_t)dap->da_newinum);
10099 			if (dap->da_state & DIRCHG)
10100 				ep->d_ino = dap->da_previous->dm_oldinum;
10101 			else
10102 				ep->d_ino = 0;
10103 			dap->da_state &= ~ATTACHED;
10104 			dap->da_state |= UNDONE;
10105 		}
10106 	}
10107 }
10108 
10109 /*
10110  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10111  * Note that any bug fixes made to this routine must be done in the
10112  * version found below.
10113  *
10114  * Called from within the procedure above to deal with unsatisfied
10115  * allocation dependencies in an inodeblock. The buffer must be
10116  * locked, thus, no I/O completion operations can occur while we
10117  * are manipulating its associated dependencies.
10118  */
10119 static void
10120 initiate_write_inodeblock_ufs1(inodedep, bp)
10121 	struct inodedep *inodedep;
10122 	struct buf *bp;			/* The inode block */
10123 {
10124 	struct allocdirect *adp, *lastadp;
10125 	struct ufs1_dinode *dp;
10126 	struct ufs1_dinode *sip;
10127 	struct inoref *inoref;
10128 	struct ufsmount *ump;
10129 	struct fs *fs;
10130 	ufs_lbn_t i;
10131 #ifdef INVARIANTS
10132 	ufs_lbn_t prevlbn = 0;
10133 #endif
10134 	int deplist;
10135 
10136 	if (inodedep->id_state & IOSTARTED)
10137 		panic("initiate_write_inodeblock_ufs1: already started");
10138 	inodedep->id_state |= IOSTARTED;
10139 	fs = inodedep->id_fs;
10140 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10141 	LOCK_OWNED(ump);
10142 	dp = (struct ufs1_dinode *)bp->b_data +
10143 	    ino_to_fsbo(fs, inodedep->id_ino);
10144 
10145 	/*
10146 	 * If we're on the unlinked list but have not yet written our
10147 	 * next pointer initialize it here.
10148 	 */
10149 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10150 		struct inodedep *inon;
10151 
10152 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10153 		dp->di_freelink = inon ? inon->id_ino : 0;
10154 	}
10155 	/*
10156 	 * If the bitmap is not yet written, then the allocated
10157 	 * inode cannot be written to disk.
10158 	 */
10159 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10160 		if (inodedep->id_savedino1 != NULL)
10161 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10162 		FREE_LOCK(ump);
10163 		sip = malloc(sizeof(struct ufs1_dinode),
10164 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10165 		ACQUIRE_LOCK(ump);
10166 		inodedep->id_savedino1 = sip;
10167 		*inodedep->id_savedino1 = *dp;
10168 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10169 		dp->di_gen = inodedep->id_savedino1->di_gen;
10170 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10171 		return;
10172 	}
10173 	/*
10174 	 * If no dependencies, then there is nothing to roll back.
10175 	 */
10176 	inodedep->id_savedsize = dp->di_size;
10177 	inodedep->id_savedextsize = 0;
10178 	inodedep->id_savednlink = dp->di_nlink;
10179 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10180 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10181 		return;
10182 	/*
10183 	 * Revert the link count to that of the first unwritten journal entry.
10184 	 */
10185 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10186 	if (inoref)
10187 		dp->di_nlink = inoref->if_nlink;
10188 	/*
10189 	 * Set the dependencies to busy.
10190 	 */
10191 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10192 	     adp = TAILQ_NEXT(adp, ad_next)) {
10193 #ifdef INVARIANTS
10194 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10195 			panic("softdep_write_inodeblock: lbn order");
10196 		prevlbn = adp->ad_offset;
10197 		if (adp->ad_offset < NDADDR &&
10198 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10199 			panic("%s: direct pointer #%jd mismatch %d != %jd",
10200 			    "softdep_write_inodeblock",
10201 			    (intmax_t)adp->ad_offset,
10202 			    dp->di_db[adp->ad_offset],
10203 			    (intmax_t)adp->ad_newblkno);
10204 		if (adp->ad_offset >= NDADDR &&
10205 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10206 			panic("%s: indirect pointer #%jd mismatch %d != %jd",
10207 			    "softdep_write_inodeblock",
10208 			    (intmax_t)adp->ad_offset - NDADDR,
10209 			    dp->di_ib[adp->ad_offset - NDADDR],
10210 			    (intmax_t)adp->ad_newblkno);
10211 		deplist |= 1 << adp->ad_offset;
10212 		if ((adp->ad_state & ATTACHED) == 0)
10213 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10214 			    adp->ad_state);
10215 #endif /* INVARIANTS */
10216 		adp->ad_state &= ~ATTACHED;
10217 		adp->ad_state |= UNDONE;
10218 	}
10219 	/*
10220 	 * The on-disk inode cannot claim to be any larger than the last
10221 	 * fragment that has been written. Otherwise, the on-disk inode
10222 	 * might have fragments that were not the last block in the file
10223 	 * which would corrupt the filesystem.
10224 	 */
10225 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10226 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10227 		if (adp->ad_offset >= NDADDR)
10228 			break;
10229 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10230 		/* keep going until hitting a rollback to a frag */
10231 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10232 			continue;
10233 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10234 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10235 #ifdef INVARIANTS
10236 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10237 				panic("softdep_write_inodeblock: lost dep1");
10238 #endif /* INVARIANTS */
10239 			dp->di_db[i] = 0;
10240 		}
10241 		for (i = 0; i < NIADDR; i++) {
10242 #ifdef INVARIANTS
10243 			if (dp->di_ib[i] != 0 &&
10244 			    (deplist & ((1 << NDADDR) << i)) == 0)
10245 				panic("softdep_write_inodeblock: lost dep2");
10246 #endif /* INVARIANTS */
10247 			dp->di_ib[i] = 0;
10248 		}
10249 		return;
10250 	}
10251 	/*
10252 	 * If we have zero'ed out the last allocated block of the file,
10253 	 * roll back the size to the last currently allocated block.
10254 	 * We know that this last allocated block is a full-sized as
10255 	 * we already checked for fragments in the loop above.
10256 	 */
10257 	if (lastadp != NULL &&
10258 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10259 		for (i = lastadp->ad_offset; i >= 0; i--)
10260 			if (dp->di_db[i] != 0)
10261 				break;
10262 		dp->di_size = (i + 1) * fs->fs_bsize;
10263 	}
10264 	/*
10265 	 * The only dependencies are for indirect blocks.
10266 	 *
10267 	 * The file size for indirect block additions is not guaranteed.
10268 	 * Such a guarantee would be non-trivial to achieve. The conventional
10269 	 * synchronous write implementation also does not make this guarantee.
10270 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10271 	 * can be over-estimated without destroying integrity when the file
10272 	 * moves into the indirect blocks (i.e., is large). If we want to
10273 	 * postpone fsck, we are stuck with this argument.
10274 	 */
10275 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10276 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10277 }
10278 
10279 /*
10280  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10281  * Note that any bug fixes made to this routine must be done in the
10282  * version found above.
10283  *
10284  * Called from within the procedure above to deal with unsatisfied
10285  * allocation dependencies in an inodeblock. The buffer must be
10286  * locked, thus, no I/O completion operations can occur while we
10287  * are manipulating its associated dependencies.
10288  */
10289 static void
10290 initiate_write_inodeblock_ufs2(inodedep, bp)
10291 	struct inodedep *inodedep;
10292 	struct buf *bp;			/* The inode block */
10293 {
10294 	struct allocdirect *adp, *lastadp;
10295 	struct ufs2_dinode *dp;
10296 	struct ufs2_dinode *sip;
10297 	struct inoref *inoref;
10298 	struct ufsmount *ump;
10299 	struct fs *fs;
10300 	ufs_lbn_t i;
10301 #ifdef INVARIANTS
10302 	ufs_lbn_t prevlbn = 0;
10303 #endif
10304 	int deplist;
10305 
10306 	if (inodedep->id_state & IOSTARTED)
10307 		panic("initiate_write_inodeblock_ufs2: already started");
10308 	inodedep->id_state |= IOSTARTED;
10309 	fs = inodedep->id_fs;
10310 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10311 	LOCK_OWNED(ump);
10312 	dp = (struct ufs2_dinode *)bp->b_data +
10313 	    ino_to_fsbo(fs, inodedep->id_ino);
10314 
10315 	/*
10316 	 * If we're on the unlinked list but have not yet written our
10317 	 * next pointer initialize it here.
10318 	 */
10319 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10320 		struct inodedep *inon;
10321 
10322 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10323 		dp->di_freelink = inon ? inon->id_ino : 0;
10324 	}
10325 	/*
10326 	 * If the bitmap is not yet written, then the allocated
10327 	 * inode cannot be written to disk.
10328 	 */
10329 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10330 		if (inodedep->id_savedino2 != NULL)
10331 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10332 		FREE_LOCK(ump);
10333 		sip = malloc(sizeof(struct ufs2_dinode),
10334 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10335 		ACQUIRE_LOCK(ump);
10336 		inodedep->id_savedino2 = sip;
10337 		*inodedep->id_savedino2 = *dp;
10338 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10339 		dp->di_gen = inodedep->id_savedino2->di_gen;
10340 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10341 		return;
10342 	}
10343 	/*
10344 	 * If no dependencies, then there is nothing to roll back.
10345 	 */
10346 	inodedep->id_savedsize = dp->di_size;
10347 	inodedep->id_savedextsize = dp->di_extsize;
10348 	inodedep->id_savednlink = dp->di_nlink;
10349 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10350 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10351 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10352 		return;
10353 	/*
10354 	 * Revert the link count to that of the first unwritten journal entry.
10355 	 */
10356 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10357 	if (inoref)
10358 		dp->di_nlink = inoref->if_nlink;
10359 
10360 	/*
10361 	 * Set the ext data dependencies to busy.
10362 	 */
10363 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10364 	     adp = TAILQ_NEXT(adp, ad_next)) {
10365 #ifdef INVARIANTS
10366 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10367 			panic("softdep_write_inodeblock: lbn order");
10368 		prevlbn = adp->ad_offset;
10369 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10370 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10371 			    "softdep_write_inodeblock",
10372 			    (intmax_t)adp->ad_offset,
10373 			    (intmax_t)dp->di_extb[adp->ad_offset],
10374 			    (intmax_t)adp->ad_newblkno);
10375 		deplist |= 1 << adp->ad_offset;
10376 		if ((adp->ad_state & ATTACHED) == 0)
10377 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10378 			    adp->ad_state);
10379 #endif /* INVARIANTS */
10380 		adp->ad_state &= ~ATTACHED;
10381 		adp->ad_state |= UNDONE;
10382 	}
10383 	/*
10384 	 * The on-disk inode cannot claim to be any larger than the last
10385 	 * fragment that has been written. Otherwise, the on-disk inode
10386 	 * might have fragments that were not the last block in the ext
10387 	 * data which would corrupt the filesystem.
10388 	 */
10389 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10390 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10391 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10392 		/* keep going until hitting a rollback to a frag */
10393 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10394 			continue;
10395 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10396 		for (i = adp->ad_offset + 1; i < NXADDR; i++) {
10397 #ifdef INVARIANTS
10398 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10399 				panic("softdep_write_inodeblock: lost dep1");
10400 #endif /* INVARIANTS */
10401 			dp->di_extb[i] = 0;
10402 		}
10403 		lastadp = NULL;
10404 		break;
10405 	}
10406 	/*
10407 	 * If we have zero'ed out the last allocated block of the ext
10408 	 * data, roll back the size to the last currently allocated block.
10409 	 * We know that this last allocated block is a full-sized as
10410 	 * we already checked for fragments in the loop above.
10411 	 */
10412 	if (lastadp != NULL &&
10413 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10414 		for (i = lastadp->ad_offset; i >= 0; i--)
10415 			if (dp->di_extb[i] != 0)
10416 				break;
10417 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10418 	}
10419 	/*
10420 	 * Set the file data dependencies to busy.
10421 	 */
10422 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10423 	     adp = TAILQ_NEXT(adp, ad_next)) {
10424 #ifdef INVARIANTS
10425 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10426 			panic("softdep_write_inodeblock: lbn order");
10427 		if ((adp->ad_state & ATTACHED) == 0)
10428 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10429 		prevlbn = adp->ad_offset;
10430 		if (adp->ad_offset < NDADDR &&
10431 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10432 			panic("%s: direct pointer #%jd mismatch %jd != %jd",
10433 			    "softdep_write_inodeblock",
10434 			    (intmax_t)adp->ad_offset,
10435 			    (intmax_t)dp->di_db[adp->ad_offset],
10436 			    (intmax_t)adp->ad_newblkno);
10437 		if (adp->ad_offset >= NDADDR &&
10438 		    dp->di_ib[adp->ad_offset - NDADDR] != adp->ad_newblkno)
10439 			panic("%s indirect pointer #%jd mismatch %jd != %jd",
10440 			    "softdep_write_inodeblock:",
10441 			    (intmax_t)adp->ad_offset - NDADDR,
10442 			    (intmax_t)dp->di_ib[adp->ad_offset - NDADDR],
10443 			    (intmax_t)adp->ad_newblkno);
10444 		deplist |= 1 << adp->ad_offset;
10445 		if ((adp->ad_state & ATTACHED) == 0)
10446 			panic("softdep_write_inodeblock: Unknown state 0x%x",
10447 			    adp->ad_state);
10448 #endif /* INVARIANTS */
10449 		adp->ad_state &= ~ATTACHED;
10450 		adp->ad_state |= UNDONE;
10451 	}
10452 	/*
10453 	 * The on-disk inode cannot claim to be any larger than the last
10454 	 * fragment that has been written. Otherwise, the on-disk inode
10455 	 * might have fragments that were not the last block in the file
10456 	 * which would corrupt the filesystem.
10457 	 */
10458 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10459 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10460 		if (adp->ad_offset >= NDADDR)
10461 			break;
10462 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10463 		/* keep going until hitting a rollback to a frag */
10464 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10465 			continue;
10466 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10467 		for (i = adp->ad_offset + 1; i < NDADDR; i++) {
10468 #ifdef INVARIANTS
10469 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10470 				panic("softdep_write_inodeblock: lost dep2");
10471 #endif /* INVARIANTS */
10472 			dp->di_db[i] = 0;
10473 		}
10474 		for (i = 0; i < NIADDR; i++) {
10475 #ifdef INVARIANTS
10476 			if (dp->di_ib[i] != 0 &&
10477 			    (deplist & ((1 << NDADDR) << i)) == 0)
10478 				panic("softdep_write_inodeblock: lost dep3");
10479 #endif /* INVARIANTS */
10480 			dp->di_ib[i] = 0;
10481 		}
10482 		return;
10483 	}
10484 	/*
10485 	 * If we have zero'ed out the last allocated block of the file,
10486 	 * roll back the size to the last currently allocated block.
10487 	 * We know that this last allocated block is a full-sized as
10488 	 * we already checked for fragments in the loop above.
10489 	 */
10490 	if (lastadp != NULL &&
10491 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10492 		for (i = lastadp->ad_offset; i >= 0; i--)
10493 			if (dp->di_db[i] != 0)
10494 				break;
10495 		dp->di_size = (i + 1) * fs->fs_bsize;
10496 	}
10497 	/*
10498 	 * The only dependencies are for indirect blocks.
10499 	 *
10500 	 * The file size for indirect block additions is not guaranteed.
10501 	 * Such a guarantee would be non-trivial to achieve. The conventional
10502 	 * synchronous write implementation also does not make this guarantee.
10503 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10504 	 * can be over-estimated without destroying integrity when the file
10505 	 * moves into the indirect blocks (i.e., is large). If we want to
10506 	 * postpone fsck, we are stuck with this argument.
10507 	 */
10508 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10509 		dp->di_ib[adp->ad_offset - NDADDR] = 0;
10510 }
10511 
10512 /*
10513  * Cancel an indirdep as a result of truncation.  Release all of the
10514  * children allocindirs and place their journal work on the appropriate
10515  * list.
10516  */
10517 static void
10518 cancel_indirdep(indirdep, bp, freeblks)
10519 	struct indirdep *indirdep;
10520 	struct buf *bp;
10521 	struct freeblks *freeblks;
10522 {
10523 	struct allocindir *aip;
10524 
10525 	/*
10526 	 * None of the indirect pointers will ever be visible,
10527 	 * so they can simply be tossed. GOINGAWAY ensures
10528 	 * that allocated pointers will be saved in the buffer
10529 	 * cache until they are freed. Note that they will
10530 	 * only be able to be found by their physical address
10531 	 * since the inode mapping the logical address will
10532 	 * be gone. The save buffer used for the safe copy
10533 	 * was allocated in setup_allocindir_phase2 using
10534 	 * the physical address so it could be used for this
10535 	 * purpose. Hence we swap the safe copy with the real
10536 	 * copy, allowing the safe copy to be freed and holding
10537 	 * on to the real copy for later use in indir_trunc.
10538 	 */
10539 	if (indirdep->ir_state & GOINGAWAY)
10540 		panic("cancel_indirdep: already gone");
10541 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
10542 		indirdep->ir_state |= DEPCOMPLETE;
10543 		LIST_REMOVE(indirdep, ir_next);
10544 	}
10545 	indirdep->ir_state |= GOINGAWAY;
10546 	/*
10547 	 * Pass in bp for blocks still have journal writes
10548 	 * pending so we can cancel them on their own.
10549 	 */
10550 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != 0)
10551 		cancel_allocindir(aip, bp, freeblks, 0);
10552 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0)
10553 		cancel_allocindir(aip, NULL, freeblks, 0);
10554 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0)
10555 		cancel_allocindir(aip, NULL, freeblks, 0);
10556 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != 0)
10557 		cancel_allocindir(aip, NULL, freeblks, 0);
10558 	/*
10559 	 * If there are pending partial truncations we need to keep the
10560 	 * old block copy around until they complete.  This is because
10561 	 * the current b_data is not a perfect superset of the available
10562 	 * blocks.
10563 	 */
10564 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
10565 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
10566 	else
10567 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10568 	WORKLIST_REMOVE(&indirdep->ir_list);
10569 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
10570 	indirdep->ir_bp = NULL;
10571 	indirdep->ir_freeblks = freeblks;
10572 }
10573 
10574 /*
10575  * Free an indirdep once it no longer has new pointers to track.
10576  */
10577 static void
10578 free_indirdep(indirdep)
10579 	struct indirdep *indirdep;
10580 {
10581 
10582 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
10583 	    ("free_indirdep: Indir trunc list not empty."));
10584 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
10585 	    ("free_indirdep: Complete head not empty."));
10586 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
10587 	    ("free_indirdep: write head not empty."));
10588 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
10589 	    ("free_indirdep: done head not empty."));
10590 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
10591 	    ("free_indirdep: deplist head not empty."));
10592 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
10593 	    ("free_indirdep: %p still on newblk list.", indirdep));
10594 	KASSERT(indirdep->ir_saveddata == NULL,
10595 	    ("free_indirdep: %p still has saved data.", indirdep));
10596 	if (indirdep->ir_state & ONWORKLIST)
10597 		WORKLIST_REMOVE(&indirdep->ir_list);
10598 	WORKITEM_FREE(indirdep, D_INDIRDEP);
10599 }
10600 
10601 /*
10602  * Called before a write to an indirdep.  This routine is responsible for
10603  * rolling back pointers to a safe state which includes only those
10604  * allocindirs which have been completed.
10605  */
10606 static void
10607 initiate_write_indirdep(indirdep, bp)
10608 	struct indirdep *indirdep;
10609 	struct buf *bp;
10610 {
10611 	struct ufsmount *ump;
10612 
10613 	indirdep->ir_state |= IOSTARTED;
10614 	if (indirdep->ir_state & GOINGAWAY)
10615 		panic("disk_io_initiation: indirdep gone");
10616 	/*
10617 	 * If there are no remaining dependencies, this will be writing
10618 	 * the real pointers.
10619 	 */
10620 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
10621 	    TAILQ_EMPTY(&indirdep->ir_trunc))
10622 		return;
10623 	/*
10624 	 * Replace up-to-date version with safe version.
10625 	 */
10626 	if (indirdep->ir_saveddata == NULL) {
10627 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
10628 		LOCK_OWNED(ump);
10629 		FREE_LOCK(ump);
10630 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
10631 		    M_SOFTDEP_FLAGS);
10632 		ACQUIRE_LOCK(ump);
10633 	}
10634 	indirdep->ir_state &= ~ATTACHED;
10635 	indirdep->ir_state |= UNDONE;
10636 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
10637 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
10638 	    bp->b_bcount);
10639 }
10640 
10641 /*
10642  * Called when an inode has been cleared in a cg bitmap.  This finally
10643  * eliminates any canceled jaddrefs
10644  */
10645 void
10646 softdep_setup_inofree(mp, bp, ino, wkhd)
10647 	struct mount *mp;
10648 	struct buf *bp;
10649 	ino_t ino;
10650 	struct workhead *wkhd;
10651 {
10652 	struct worklist *wk, *wkn;
10653 	struct inodedep *inodedep;
10654 	struct ufsmount *ump;
10655 	uint8_t *inosused;
10656 	struct cg *cgp;
10657 	struct fs *fs;
10658 
10659 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
10660 	    ("softdep_setup_inofree called on non-softdep filesystem"));
10661 	ump = VFSTOUFS(mp);
10662 	ACQUIRE_LOCK(ump);
10663 	fs = ump->um_fs;
10664 	cgp = (struct cg *)bp->b_data;
10665 	inosused = cg_inosused(cgp);
10666 	if (isset(inosused, ino % fs->fs_ipg))
10667 		panic("softdep_setup_inofree: inode %ju not freed.",
10668 		    (uintmax_t)ino);
10669 	if (inodedep_lookup(mp, ino, 0, &inodedep))
10670 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
10671 		    (uintmax_t)ino, inodedep);
10672 	if (wkhd) {
10673 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
10674 			if (wk->wk_type != D_JADDREF)
10675 				continue;
10676 			WORKLIST_REMOVE(wk);
10677 			/*
10678 			 * We can free immediately even if the jaddref
10679 			 * isn't attached in a background write as now
10680 			 * the bitmaps are reconciled.
10681 			 */
10682 			wk->wk_state |= COMPLETE | ATTACHED;
10683 			free_jaddref(WK_JADDREF(wk));
10684 		}
10685 		jwork_move(&bp->b_dep, wkhd);
10686 	}
10687 	FREE_LOCK(ump);
10688 }
10689 
10690 
10691 /*
10692  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
10693  * map.  Any dependencies waiting for the write to clear are added to the
10694  * buf's list and any jnewblks that are being canceled are discarded
10695  * immediately.
10696  */
10697 void
10698 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
10699 	struct mount *mp;
10700 	struct buf *bp;
10701 	ufs2_daddr_t blkno;
10702 	int frags;
10703 	struct workhead *wkhd;
10704 {
10705 	struct bmsafemap *bmsafemap;
10706 	struct jnewblk *jnewblk;
10707 	struct ufsmount *ump;
10708 	struct worklist *wk;
10709 	struct fs *fs;
10710 #ifdef SUJ_DEBUG
10711 	uint8_t *blksfree;
10712 	struct cg *cgp;
10713 	ufs2_daddr_t jstart;
10714 	ufs2_daddr_t jend;
10715 	ufs2_daddr_t end;
10716 	long bno;
10717 	int i;
10718 #endif
10719 
10720 	CTR3(KTR_SUJ,
10721 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
10722 	    blkno, frags, wkhd);
10723 
10724 	ump = VFSTOUFS(mp);
10725 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
10726 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
10727 	ACQUIRE_LOCK(ump);
10728 	/* Lookup the bmsafemap so we track when it is dirty. */
10729 	fs = ump->um_fs;
10730 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10731 	/*
10732 	 * Detach any jnewblks which have been canceled.  They must linger
10733 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
10734 	 * an unjournaled allocation from hitting the disk.
10735 	 */
10736 	if (wkhd) {
10737 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
10738 			CTR2(KTR_SUJ,
10739 			    "softdep_setup_blkfree: blkno %jd wk type %d",
10740 			    blkno, wk->wk_type);
10741 			WORKLIST_REMOVE(wk);
10742 			if (wk->wk_type != D_JNEWBLK) {
10743 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
10744 				continue;
10745 			}
10746 			jnewblk = WK_JNEWBLK(wk);
10747 			KASSERT(jnewblk->jn_state & GOINGAWAY,
10748 			    ("softdep_setup_blkfree: jnewblk not canceled."));
10749 #ifdef SUJ_DEBUG
10750 			/*
10751 			 * Assert that this block is free in the bitmap
10752 			 * before we discard the jnewblk.
10753 			 */
10754 			cgp = (struct cg *)bp->b_data;
10755 			blksfree = cg_blksfree(cgp);
10756 			bno = dtogd(fs, jnewblk->jn_blkno);
10757 			for (i = jnewblk->jn_oldfrags;
10758 			    i < jnewblk->jn_frags; i++) {
10759 				if (isset(blksfree, bno + i))
10760 					continue;
10761 				panic("softdep_setup_blkfree: not free");
10762 			}
10763 #endif
10764 			/*
10765 			 * Even if it's not attached we can free immediately
10766 			 * as the new bitmap is correct.
10767 			 */
10768 			wk->wk_state |= COMPLETE | ATTACHED;
10769 			free_jnewblk(jnewblk);
10770 		}
10771 	}
10772 
10773 #ifdef SUJ_DEBUG
10774 	/*
10775 	 * Assert that we are not freeing a block which has an outstanding
10776 	 * allocation dependency.
10777 	 */
10778 	fs = VFSTOUFS(mp)->um_fs;
10779 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
10780 	end = blkno + frags;
10781 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10782 		/*
10783 		 * Don't match against blocks that will be freed when the
10784 		 * background write is done.
10785 		 */
10786 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
10787 		    (COMPLETE | DEPCOMPLETE))
10788 			continue;
10789 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
10790 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
10791 		if ((blkno >= jstart && blkno < jend) ||
10792 		    (end > jstart && end <= jend)) {
10793 			printf("state 0x%X %jd - %d %d dep %p\n",
10794 			    jnewblk->jn_state, jnewblk->jn_blkno,
10795 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
10796 			    jnewblk->jn_dep);
10797 			panic("softdep_setup_blkfree: "
10798 			    "%jd-%jd(%d) overlaps with %jd-%jd",
10799 			    blkno, end, frags, jstart, jend);
10800 		}
10801 	}
10802 #endif
10803 	FREE_LOCK(ump);
10804 }
10805 
10806 /*
10807  * Revert a block allocation when the journal record that describes it
10808  * is not yet written.
10809  */
10810 static int
10811 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
10812 	struct jnewblk *jnewblk;
10813 	struct fs *fs;
10814 	struct cg *cgp;
10815 	uint8_t *blksfree;
10816 {
10817 	ufs1_daddr_t fragno;
10818 	long cgbno, bbase;
10819 	int frags, blk;
10820 	int i;
10821 
10822 	frags = 0;
10823 	cgbno = dtogd(fs, jnewblk->jn_blkno);
10824 	/*
10825 	 * We have to test which frags need to be rolled back.  We may
10826 	 * be operating on a stale copy when doing background writes.
10827 	 */
10828 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
10829 		if (isclr(blksfree, cgbno + i))
10830 			frags++;
10831 	if (frags == 0)
10832 		return (0);
10833 	/*
10834 	 * This is mostly ffs_blkfree() sans some validation and
10835 	 * superblock updates.
10836 	 */
10837 	if (frags == fs->fs_frag) {
10838 		fragno = fragstoblks(fs, cgbno);
10839 		ffs_setblock(fs, blksfree, fragno);
10840 		ffs_clusteracct(fs, cgp, fragno, 1);
10841 		cgp->cg_cs.cs_nbfree++;
10842 	} else {
10843 		cgbno += jnewblk->jn_oldfrags;
10844 		bbase = cgbno - fragnum(fs, cgbno);
10845 		/* Decrement the old frags.  */
10846 		blk = blkmap(fs, blksfree, bbase);
10847 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
10848 		/* Deallocate the fragment */
10849 		for (i = 0; i < frags; i++)
10850 			setbit(blksfree, cgbno + i);
10851 		cgp->cg_cs.cs_nffree += frags;
10852 		/* Add back in counts associated with the new frags */
10853 		blk = blkmap(fs, blksfree, bbase);
10854 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
10855 		/* If a complete block has been reassembled, account for it. */
10856 		fragno = fragstoblks(fs, bbase);
10857 		if (ffs_isblock(fs, blksfree, fragno)) {
10858 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
10859 			ffs_clusteracct(fs, cgp, fragno, 1);
10860 			cgp->cg_cs.cs_nbfree++;
10861 		}
10862 	}
10863 	stat_jnewblk++;
10864 	jnewblk->jn_state &= ~ATTACHED;
10865 	jnewblk->jn_state |= UNDONE;
10866 
10867 	return (frags);
10868 }
10869 
10870 static void
10871 initiate_write_bmsafemap(bmsafemap, bp)
10872 	struct bmsafemap *bmsafemap;
10873 	struct buf *bp;			/* The cg block. */
10874 {
10875 	struct jaddref *jaddref;
10876 	struct jnewblk *jnewblk;
10877 	uint8_t *inosused;
10878 	uint8_t *blksfree;
10879 	struct cg *cgp;
10880 	struct fs *fs;
10881 	ino_t ino;
10882 
10883 	if (bmsafemap->sm_state & IOSTARTED)
10884 		return;
10885 	bmsafemap->sm_state |= IOSTARTED;
10886 	/*
10887 	 * Clear any inode allocations which are pending journal writes.
10888 	 */
10889 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
10890 		cgp = (struct cg *)bp->b_data;
10891 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10892 		inosused = cg_inosused(cgp);
10893 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
10894 			ino = jaddref->ja_ino % fs->fs_ipg;
10895 			if (isset(inosused, ino)) {
10896 				if ((jaddref->ja_mode & IFMT) == IFDIR)
10897 					cgp->cg_cs.cs_ndir--;
10898 				cgp->cg_cs.cs_nifree++;
10899 				clrbit(inosused, ino);
10900 				jaddref->ja_state &= ~ATTACHED;
10901 				jaddref->ja_state |= UNDONE;
10902 				stat_jaddref++;
10903 			} else
10904 				panic("initiate_write_bmsafemap: inode %ju "
10905 				    "marked free", (uintmax_t)jaddref->ja_ino);
10906 		}
10907 	}
10908 	/*
10909 	 * Clear any block allocations which are pending journal writes.
10910 	 */
10911 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
10912 		cgp = (struct cg *)bp->b_data;
10913 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
10914 		blksfree = cg_blksfree(cgp);
10915 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
10916 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
10917 				continue;
10918 			panic("initiate_write_bmsafemap: block %jd "
10919 			    "marked free", jnewblk->jn_blkno);
10920 		}
10921 	}
10922 	/*
10923 	 * Move allocation lists to the written lists so they can be
10924 	 * cleared once the block write is complete.
10925 	 */
10926 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
10927 	    inodedep, id_deps);
10928 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
10929 	    newblk, nb_deps);
10930 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
10931 	    wk_list);
10932 }
10933 
10934 /*
10935  * This routine is called during the completion interrupt
10936  * service routine for a disk write (from the procedure called
10937  * by the device driver to inform the filesystem caches of
10938  * a request completion).  It should be called early in this
10939  * procedure, before the block is made available to other
10940  * processes or other routines are called.
10941  *
10942  */
10943 static void
10944 softdep_disk_write_complete(bp)
10945 	struct buf *bp;		/* describes the completed disk write */
10946 {
10947 	struct worklist *wk;
10948 	struct worklist *owk;
10949 	struct ufsmount *ump;
10950 	struct workhead reattach;
10951 	struct freeblks *freeblks;
10952 	struct buf *sbp;
10953 
10954 	/*
10955 	 * If an error occurred while doing the write, then the data
10956 	 * has not hit the disk and the dependencies cannot be unrolled.
10957 	 */
10958 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0)
10959 		return;
10960 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
10961 		return;
10962 	ump = VFSTOUFS(wk->wk_mp);
10963 	LIST_INIT(&reattach);
10964 	/*
10965 	 * This lock must not be released anywhere in this code segment.
10966 	 */
10967 	sbp = NULL;
10968 	owk = NULL;
10969 	ACQUIRE_LOCK(ump);
10970 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
10971 		WORKLIST_REMOVE(wk);
10972 		atomic_add_long(&dep_write[wk->wk_type], 1);
10973 		if (wk == owk)
10974 			panic("duplicate worklist: %p\n", wk);
10975 		owk = wk;
10976 		switch (wk->wk_type) {
10977 
10978 		case D_PAGEDEP:
10979 			if (handle_written_filepage(WK_PAGEDEP(wk), bp))
10980 				WORKLIST_INSERT(&reattach, wk);
10981 			continue;
10982 
10983 		case D_INODEDEP:
10984 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp))
10985 				WORKLIST_INSERT(&reattach, wk);
10986 			continue;
10987 
10988 		case D_BMSAFEMAP:
10989 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp))
10990 				WORKLIST_INSERT(&reattach, wk);
10991 			continue;
10992 
10993 		case D_MKDIR:
10994 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
10995 			continue;
10996 
10997 		case D_ALLOCDIRECT:
10998 			wk->wk_state |= COMPLETE;
10999 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11000 			continue;
11001 
11002 		case D_ALLOCINDIR:
11003 			wk->wk_state |= COMPLETE;
11004 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11005 			continue;
11006 
11007 		case D_INDIRDEP:
11008 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp))
11009 				WORKLIST_INSERT(&reattach, wk);
11010 			continue;
11011 
11012 		case D_FREEBLKS:
11013 			wk->wk_state |= COMPLETE;
11014 			freeblks = WK_FREEBLKS(wk);
11015 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11016 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11017 				add_to_worklist(wk, WK_NODELAY);
11018 			continue;
11019 
11020 		case D_FREEWORK:
11021 			handle_written_freework(WK_FREEWORK(wk));
11022 			break;
11023 
11024 		case D_JSEGDEP:
11025 			free_jsegdep(WK_JSEGDEP(wk));
11026 			continue;
11027 
11028 		case D_JSEG:
11029 			handle_written_jseg(WK_JSEG(wk), bp);
11030 			continue;
11031 
11032 		case D_SBDEP:
11033 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11034 				WORKLIST_INSERT(&reattach, wk);
11035 			continue;
11036 
11037 		case D_FREEDEP:
11038 			free_freedep(WK_FREEDEP(wk));
11039 			continue;
11040 
11041 		default:
11042 			panic("handle_disk_write_complete: Unknown type %s",
11043 			    TYPENAME(wk->wk_type));
11044 			/* NOTREACHED */
11045 		}
11046 	}
11047 	/*
11048 	 * Reattach any requests that must be redone.
11049 	 */
11050 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11051 		WORKLIST_REMOVE(wk);
11052 		WORKLIST_INSERT(&bp->b_dep, wk);
11053 	}
11054 	FREE_LOCK(ump);
11055 	if (sbp)
11056 		brelse(sbp);
11057 }
11058 
11059 /*
11060  * Called from within softdep_disk_write_complete above. Note that
11061  * this routine is always called from interrupt level with further
11062  * splbio interrupts blocked.
11063  */
11064 static void
11065 handle_allocdirect_partdone(adp, wkhd)
11066 	struct allocdirect *adp;	/* the completed allocdirect */
11067 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11068 {
11069 	struct allocdirectlst *listhead;
11070 	struct allocdirect *listadp;
11071 	struct inodedep *inodedep;
11072 	long bsize;
11073 
11074 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11075 		return;
11076 	/*
11077 	 * The on-disk inode cannot claim to be any larger than the last
11078 	 * fragment that has been written. Otherwise, the on-disk inode
11079 	 * might have fragments that were not the last block in the file
11080 	 * which would corrupt the filesystem. Thus, we cannot free any
11081 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11082 	 * these blocks must be rolled back to zero before writing the inode.
11083 	 * We check the currently active set of allocdirects in id_inoupdt
11084 	 * or id_extupdt as appropriate.
11085 	 */
11086 	inodedep = adp->ad_inodedep;
11087 	bsize = inodedep->id_fs->fs_bsize;
11088 	if (adp->ad_state & EXTDATA)
11089 		listhead = &inodedep->id_extupdt;
11090 	else
11091 		listhead = &inodedep->id_inoupdt;
11092 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11093 		/* found our block */
11094 		if (listadp == adp)
11095 			break;
11096 		/* continue if ad_oldlbn is not a fragment */
11097 		if (listadp->ad_oldsize == 0 ||
11098 		    listadp->ad_oldsize == bsize)
11099 			continue;
11100 		/* hit a fragment */
11101 		return;
11102 	}
11103 	/*
11104 	 * If we have reached the end of the current list without
11105 	 * finding the just finished dependency, then it must be
11106 	 * on the future dependency list. Future dependencies cannot
11107 	 * be freed until they are moved to the current list.
11108 	 */
11109 	if (listadp == NULL) {
11110 #ifdef DEBUG
11111 		if (adp->ad_state & EXTDATA)
11112 			listhead = &inodedep->id_newextupdt;
11113 		else
11114 			listhead = &inodedep->id_newinoupdt;
11115 		TAILQ_FOREACH(listadp, listhead, ad_next)
11116 			/* found our block */
11117 			if (listadp == adp)
11118 				break;
11119 		if (listadp == NULL)
11120 			panic("handle_allocdirect_partdone: lost dep");
11121 #endif /* DEBUG */
11122 		return;
11123 	}
11124 	/*
11125 	 * If we have found the just finished dependency, then queue
11126 	 * it along with anything that follows it that is complete.
11127 	 * Since the pointer has not yet been written in the inode
11128 	 * as the dependency prevents it, place the allocdirect on the
11129 	 * bufwait list where it will be freed once the pointer is
11130 	 * valid.
11131 	 */
11132 	if (wkhd == NULL)
11133 		wkhd = &inodedep->id_bufwait;
11134 	for (; adp; adp = listadp) {
11135 		listadp = TAILQ_NEXT(adp, ad_next);
11136 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11137 			return;
11138 		TAILQ_REMOVE(listhead, adp, ad_next);
11139 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11140 	}
11141 }
11142 
11143 /*
11144  * Called from within softdep_disk_write_complete above.  This routine
11145  * completes successfully written allocindirs.
11146  */
11147 static void
11148 handle_allocindir_partdone(aip)
11149 	struct allocindir *aip;		/* the completed allocindir */
11150 {
11151 	struct indirdep *indirdep;
11152 
11153 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11154 		return;
11155 	indirdep = aip->ai_indirdep;
11156 	LIST_REMOVE(aip, ai_next);
11157 	/*
11158 	 * Don't set a pointer while the buffer is undergoing IO or while
11159 	 * we have active truncations.
11160 	 */
11161 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11162 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11163 		return;
11164 	}
11165 	if (indirdep->ir_state & UFS1FMT)
11166 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11167 		    aip->ai_newblkno;
11168 	else
11169 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11170 		    aip->ai_newblkno;
11171 	/*
11172 	 * Await the pointer write before freeing the allocindir.
11173 	 */
11174 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11175 }
11176 
11177 /*
11178  * Release segments held on a jwork list.
11179  */
11180 static void
11181 handle_jwork(wkhd)
11182 	struct workhead *wkhd;
11183 {
11184 	struct worklist *wk;
11185 
11186 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11187 		WORKLIST_REMOVE(wk);
11188 		switch (wk->wk_type) {
11189 		case D_JSEGDEP:
11190 			free_jsegdep(WK_JSEGDEP(wk));
11191 			continue;
11192 		case D_FREEDEP:
11193 			free_freedep(WK_FREEDEP(wk));
11194 			continue;
11195 		case D_FREEFRAG:
11196 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11197 			WORKITEM_FREE(wk, D_FREEFRAG);
11198 			continue;
11199 		case D_FREEWORK:
11200 			handle_written_freework(WK_FREEWORK(wk));
11201 			continue;
11202 		default:
11203 			panic("handle_jwork: Unknown type %s\n",
11204 			    TYPENAME(wk->wk_type));
11205 		}
11206 	}
11207 }
11208 
11209 /*
11210  * Handle the bufwait list on an inode when it is safe to release items
11211  * held there.  This normally happens after an inode block is written but
11212  * may be delayed and handled later if there are pending journal items that
11213  * are not yet safe to be released.
11214  */
11215 static struct freefile *
11216 handle_bufwait(inodedep, refhd)
11217 	struct inodedep *inodedep;
11218 	struct workhead *refhd;
11219 {
11220 	struct jaddref *jaddref;
11221 	struct freefile *freefile;
11222 	struct worklist *wk;
11223 
11224 	freefile = NULL;
11225 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11226 		WORKLIST_REMOVE(wk);
11227 		switch (wk->wk_type) {
11228 		case D_FREEFILE:
11229 			/*
11230 			 * We defer adding freefile to the worklist
11231 			 * until all other additions have been made to
11232 			 * ensure that it will be done after all the
11233 			 * old blocks have been freed.
11234 			 */
11235 			if (freefile != NULL)
11236 				panic("handle_bufwait: freefile");
11237 			freefile = WK_FREEFILE(wk);
11238 			continue;
11239 
11240 		case D_MKDIR:
11241 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11242 			continue;
11243 
11244 		case D_DIRADD:
11245 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11246 			continue;
11247 
11248 		case D_FREEFRAG:
11249 			wk->wk_state |= COMPLETE;
11250 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11251 				add_to_worklist(wk, 0);
11252 			continue;
11253 
11254 		case D_DIRREM:
11255 			wk->wk_state |= COMPLETE;
11256 			add_to_worklist(wk, 0);
11257 			continue;
11258 
11259 		case D_ALLOCDIRECT:
11260 		case D_ALLOCINDIR:
11261 			free_newblk(WK_NEWBLK(wk));
11262 			continue;
11263 
11264 		case D_JNEWBLK:
11265 			wk->wk_state |= COMPLETE;
11266 			free_jnewblk(WK_JNEWBLK(wk));
11267 			continue;
11268 
11269 		/*
11270 		 * Save freed journal segments and add references on
11271 		 * the supplied list which will delay their release
11272 		 * until the cg bitmap is cleared on disk.
11273 		 */
11274 		case D_JSEGDEP:
11275 			if (refhd == NULL)
11276 				free_jsegdep(WK_JSEGDEP(wk));
11277 			else
11278 				WORKLIST_INSERT(refhd, wk);
11279 			continue;
11280 
11281 		case D_JADDREF:
11282 			jaddref = WK_JADDREF(wk);
11283 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11284 			    if_deps);
11285 			/*
11286 			 * Transfer any jaddrefs to the list to be freed with
11287 			 * the bitmap if we're handling a removed file.
11288 			 */
11289 			if (refhd == NULL) {
11290 				wk->wk_state |= COMPLETE;
11291 				free_jaddref(jaddref);
11292 			} else
11293 				WORKLIST_INSERT(refhd, wk);
11294 			continue;
11295 
11296 		default:
11297 			panic("handle_bufwait: Unknown type %p(%s)",
11298 			    wk, TYPENAME(wk->wk_type));
11299 			/* NOTREACHED */
11300 		}
11301 	}
11302 	return (freefile);
11303 }
11304 /*
11305  * Called from within softdep_disk_write_complete above to restore
11306  * in-memory inode block contents to their most up-to-date state. Note
11307  * that this routine is always called from interrupt level with further
11308  * splbio interrupts blocked.
11309  */
11310 static int
11311 handle_written_inodeblock(inodedep, bp)
11312 	struct inodedep *inodedep;
11313 	struct buf *bp;		/* buffer containing the inode block */
11314 {
11315 	struct freefile *freefile;
11316 	struct allocdirect *adp, *nextadp;
11317 	struct ufs1_dinode *dp1 = NULL;
11318 	struct ufs2_dinode *dp2 = NULL;
11319 	struct workhead wkhd;
11320 	int hadchanges, fstype;
11321 	ino_t freelink;
11322 
11323 	LIST_INIT(&wkhd);
11324 	hadchanges = 0;
11325 	freefile = NULL;
11326 	if ((inodedep->id_state & IOSTARTED) == 0)
11327 		panic("handle_written_inodeblock: not started");
11328 	inodedep->id_state &= ~IOSTARTED;
11329 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11330 		fstype = UFS1;
11331 		dp1 = (struct ufs1_dinode *)bp->b_data +
11332 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11333 		freelink = dp1->di_freelink;
11334 	} else {
11335 		fstype = UFS2;
11336 		dp2 = (struct ufs2_dinode *)bp->b_data +
11337 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11338 		freelink = dp2->di_freelink;
11339 	}
11340 	/*
11341 	 * Leave this inodeblock dirty until it's in the list.
11342 	 */
11343 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED) {
11344 		struct inodedep *inon;
11345 
11346 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11347 		if ((inon == NULL && freelink == 0) ||
11348 		    (inon && inon->id_ino == freelink)) {
11349 			if (inon)
11350 				inon->id_state |= UNLINKPREV;
11351 			inodedep->id_state |= UNLINKNEXT;
11352 		}
11353 		hadchanges = 1;
11354 	}
11355 	/*
11356 	 * If we had to rollback the inode allocation because of
11357 	 * bitmaps being incomplete, then simply restore it.
11358 	 * Keep the block dirty so that it will not be reclaimed until
11359 	 * all associated dependencies have been cleared and the
11360 	 * corresponding updates written to disk.
11361 	 */
11362 	if (inodedep->id_savedino1 != NULL) {
11363 		hadchanges = 1;
11364 		if (fstype == UFS1)
11365 			*dp1 = *inodedep->id_savedino1;
11366 		else
11367 			*dp2 = *inodedep->id_savedino2;
11368 		free(inodedep->id_savedino1, M_SAVEDINO);
11369 		inodedep->id_savedino1 = NULL;
11370 		if ((bp->b_flags & B_DELWRI) == 0)
11371 			stat_inode_bitmap++;
11372 		bdirty(bp);
11373 		/*
11374 		 * If the inode is clear here and GOINGAWAY it will never
11375 		 * be written.  Process the bufwait and clear any pending
11376 		 * work which may include the freefile.
11377 		 */
11378 		if (inodedep->id_state & GOINGAWAY)
11379 			goto bufwait;
11380 		return (1);
11381 	}
11382 	inodedep->id_state |= COMPLETE;
11383 	/*
11384 	 * Roll forward anything that had to be rolled back before
11385 	 * the inode could be updated.
11386 	 */
11387 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11388 		nextadp = TAILQ_NEXT(adp, ad_next);
11389 		if (adp->ad_state & ATTACHED)
11390 			panic("handle_written_inodeblock: new entry");
11391 		if (fstype == UFS1) {
11392 			if (adp->ad_offset < NDADDR) {
11393 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11394 					panic("%s %s #%jd mismatch %d != %jd",
11395 					    "handle_written_inodeblock:",
11396 					    "direct pointer",
11397 					    (intmax_t)adp->ad_offset,
11398 					    dp1->di_db[adp->ad_offset],
11399 					    (intmax_t)adp->ad_oldblkno);
11400 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11401 			} else {
11402 				if (dp1->di_ib[adp->ad_offset - NDADDR] != 0)
11403 					panic("%s: %s #%jd allocated as %d",
11404 					    "handle_written_inodeblock",
11405 					    "indirect pointer",
11406 					    (intmax_t)adp->ad_offset - NDADDR,
11407 					    dp1->di_ib[adp->ad_offset - NDADDR]);
11408 				dp1->di_ib[adp->ad_offset - NDADDR] =
11409 				    adp->ad_newblkno;
11410 			}
11411 		} else {
11412 			if (adp->ad_offset < NDADDR) {
11413 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11414 					panic("%s: %s #%jd %s %jd != %jd",
11415 					    "handle_written_inodeblock",
11416 					    "direct pointer",
11417 					    (intmax_t)adp->ad_offset, "mismatch",
11418 					    (intmax_t)dp2->di_db[adp->ad_offset],
11419 					    (intmax_t)adp->ad_oldblkno);
11420 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11421 			} else {
11422 				if (dp2->di_ib[adp->ad_offset - NDADDR] != 0)
11423 					panic("%s: %s #%jd allocated as %jd",
11424 					    "handle_written_inodeblock",
11425 					    "indirect pointer",
11426 					    (intmax_t)adp->ad_offset - NDADDR,
11427 					    (intmax_t)
11428 					    dp2->di_ib[adp->ad_offset - NDADDR]);
11429 				dp2->di_ib[adp->ad_offset - NDADDR] =
11430 				    adp->ad_newblkno;
11431 			}
11432 		}
11433 		adp->ad_state &= ~UNDONE;
11434 		adp->ad_state |= ATTACHED;
11435 		hadchanges = 1;
11436 	}
11437 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
11438 		nextadp = TAILQ_NEXT(adp, ad_next);
11439 		if (adp->ad_state & ATTACHED)
11440 			panic("handle_written_inodeblock: new entry");
11441 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
11442 			panic("%s: direct pointers #%jd %s %jd != %jd",
11443 			    "handle_written_inodeblock",
11444 			    (intmax_t)adp->ad_offset, "mismatch",
11445 			    (intmax_t)dp2->di_extb[adp->ad_offset],
11446 			    (intmax_t)adp->ad_oldblkno);
11447 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
11448 		adp->ad_state &= ~UNDONE;
11449 		adp->ad_state |= ATTACHED;
11450 		hadchanges = 1;
11451 	}
11452 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
11453 		stat_direct_blk_ptrs++;
11454 	/*
11455 	 * Reset the file size to its most up-to-date value.
11456 	 */
11457 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
11458 		panic("handle_written_inodeblock: bad size");
11459 	if (inodedep->id_savednlink > LINK_MAX)
11460 		panic("handle_written_inodeblock: Invalid link count "
11461 		    "%d for inodedep %p", inodedep->id_savednlink, inodedep);
11462 	if (fstype == UFS1) {
11463 		if (dp1->di_nlink != inodedep->id_savednlink) {
11464 			dp1->di_nlink = inodedep->id_savednlink;
11465 			hadchanges = 1;
11466 		}
11467 		if (dp1->di_size != inodedep->id_savedsize) {
11468 			dp1->di_size = inodedep->id_savedsize;
11469 			hadchanges = 1;
11470 		}
11471 	} else {
11472 		if (dp2->di_nlink != inodedep->id_savednlink) {
11473 			dp2->di_nlink = inodedep->id_savednlink;
11474 			hadchanges = 1;
11475 		}
11476 		if (dp2->di_size != inodedep->id_savedsize) {
11477 			dp2->di_size = inodedep->id_savedsize;
11478 			hadchanges = 1;
11479 		}
11480 		if (dp2->di_extsize != inodedep->id_savedextsize) {
11481 			dp2->di_extsize = inodedep->id_savedextsize;
11482 			hadchanges = 1;
11483 		}
11484 	}
11485 	inodedep->id_savedsize = -1;
11486 	inodedep->id_savedextsize = -1;
11487 	inodedep->id_savednlink = -1;
11488 	/*
11489 	 * If there were any rollbacks in the inode block, then it must be
11490 	 * marked dirty so that its will eventually get written back in
11491 	 * its correct form.
11492 	 */
11493 	if (hadchanges)
11494 		bdirty(bp);
11495 bufwait:
11496 	/*
11497 	 * Process any allocdirects that completed during the update.
11498 	 */
11499 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
11500 		handle_allocdirect_partdone(adp, &wkhd);
11501 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
11502 		handle_allocdirect_partdone(adp, &wkhd);
11503 	/*
11504 	 * Process deallocations that were held pending until the
11505 	 * inode had been written to disk. Freeing of the inode
11506 	 * is delayed until after all blocks have been freed to
11507 	 * avoid creation of new <vfsid, inum, lbn> triples
11508 	 * before the old ones have been deleted.  Completely
11509 	 * unlinked inodes are not processed until the unlinked
11510 	 * inode list is written or the last reference is removed.
11511 	 */
11512 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
11513 		freefile = handle_bufwait(inodedep, NULL);
11514 		if (freefile && !LIST_EMPTY(&wkhd)) {
11515 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
11516 			freefile = NULL;
11517 		}
11518 	}
11519 	/*
11520 	 * Move rolled forward dependency completions to the bufwait list
11521 	 * now that those that were already written have been processed.
11522 	 */
11523 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
11524 		panic("handle_written_inodeblock: bufwait but no changes");
11525 	jwork_move(&inodedep->id_bufwait, &wkhd);
11526 
11527 	if (freefile != NULL) {
11528 		/*
11529 		 * If the inode is goingaway it was never written.  Fake up
11530 		 * the state here so free_inodedep() can succeed.
11531 		 */
11532 		if (inodedep->id_state & GOINGAWAY)
11533 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
11534 		if (free_inodedep(inodedep) == 0)
11535 			panic("handle_written_inodeblock: live inodedep %p",
11536 			    inodedep);
11537 		add_to_worklist(&freefile->fx_list, 0);
11538 		return (0);
11539 	}
11540 
11541 	/*
11542 	 * If no outstanding dependencies, free it.
11543 	 */
11544 	if (free_inodedep(inodedep) ||
11545 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
11546 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
11547 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
11548 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
11549 		return (0);
11550 	return (hadchanges);
11551 }
11552 
11553 static int
11554 handle_written_indirdep(indirdep, bp, bpp)
11555 	struct indirdep *indirdep;
11556 	struct buf *bp;
11557 	struct buf **bpp;
11558 {
11559 	struct allocindir *aip;
11560 	struct buf *sbp;
11561 	int chgs;
11562 
11563 	if (indirdep->ir_state & GOINGAWAY)
11564 		panic("handle_written_indirdep: indirdep gone");
11565 	if ((indirdep->ir_state & IOSTARTED) == 0)
11566 		panic("handle_written_indirdep: IO not started");
11567 	chgs = 0;
11568 	/*
11569 	 * If there were rollbacks revert them here.
11570 	 */
11571 	if (indirdep->ir_saveddata) {
11572 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
11573 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11574 			free(indirdep->ir_saveddata, M_INDIRDEP);
11575 			indirdep->ir_saveddata = NULL;
11576 		}
11577 		chgs = 1;
11578 	}
11579 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
11580 	indirdep->ir_state |= ATTACHED;
11581 	/*
11582 	 * Move allocindirs with written pointers to the completehd if
11583 	 * the indirdep's pointer is not yet written.  Otherwise
11584 	 * free them here.
11585 	 */
11586 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != 0) {
11587 		LIST_REMOVE(aip, ai_next);
11588 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11589 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
11590 			    ai_next);
11591 			newblk_freefrag(&aip->ai_block);
11592 			continue;
11593 		}
11594 		free_newblk(&aip->ai_block);
11595 	}
11596 	/*
11597 	 * Move allocindirs that have finished dependency processing from
11598 	 * the done list to the write list after updating the pointers.
11599 	 */
11600 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
11601 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != 0) {
11602 			handle_allocindir_partdone(aip);
11603 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
11604 				panic("disk_write_complete: not gone");
11605 			chgs = 1;
11606 		}
11607 	}
11608 	/*
11609 	 * Preserve the indirdep if there were any changes or if it is not
11610 	 * yet valid on disk.
11611 	 */
11612 	if (chgs) {
11613 		stat_indir_blk_ptrs++;
11614 		bdirty(bp);
11615 		return (1);
11616 	}
11617 	/*
11618 	 * If there were no changes we can discard the savedbp and detach
11619 	 * ourselves from the buf.  We are only carrying completed pointers
11620 	 * in this case.
11621 	 */
11622 	sbp = indirdep->ir_savebp;
11623 	sbp->b_flags |= B_INVAL | B_NOCACHE;
11624 	indirdep->ir_savebp = NULL;
11625 	indirdep->ir_bp = NULL;
11626 	if (*bpp != NULL)
11627 		panic("handle_written_indirdep: bp already exists.");
11628 	*bpp = sbp;
11629 	/*
11630 	 * The indirdep may not be freed until its parent points at it.
11631 	 */
11632 	if (indirdep->ir_state & DEPCOMPLETE)
11633 		free_indirdep(indirdep);
11634 
11635 	return (0);
11636 }
11637 
11638 /*
11639  * Process a diradd entry after its dependent inode has been written.
11640  * This routine must be called with splbio interrupts blocked.
11641  */
11642 static void
11643 diradd_inode_written(dap, inodedep)
11644 	struct diradd *dap;
11645 	struct inodedep *inodedep;
11646 {
11647 
11648 	dap->da_state |= COMPLETE;
11649 	complete_diradd(dap);
11650 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
11651 }
11652 
11653 /*
11654  * Returns true if the bmsafemap will have rollbacks when written.  Must only
11655  * be called with the per-filesystem lock and the buf lock on the cg held.
11656  */
11657 static int
11658 bmsafemap_backgroundwrite(bmsafemap, bp)
11659 	struct bmsafemap *bmsafemap;
11660 	struct buf *bp;
11661 {
11662 	int dirty;
11663 
11664 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
11665 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
11666 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
11667 	/*
11668 	 * If we're initiating a background write we need to process the
11669 	 * rollbacks as they exist now, not as they exist when IO starts.
11670 	 * No other consumers will look at the contents of the shadowed
11671 	 * buf so this is safe to do here.
11672 	 */
11673 	if (bp->b_xflags & BX_BKGRDMARKER)
11674 		initiate_write_bmsafemap(bmsafemap, bp);
11675 
11676 	return (dirty);
11677 }
11678 
11679 /*
11680  * Re-apply an allocation when a cg write is complete.
11681  */
11682 static int
11683 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
11684 	struct jnewblk *jnewblk;
11685 	struct fs *fs;
11686 	struct cg *cgp;
11687 	uint8_t *blksfree;
11688 {
11689 	ufs1_daddr_t fragno;
11690 	ufs2_daddr_t blkno;
11691 	long cgbno, bbase;
11692 	int frags, blk;
11693 	int i;
11694 
11695 	frags = 0;
11696 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11697 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
11698 		if (isclr(blksfree, cgbno + i))
11699 			panic("jnewblk_rollforward: re-allocated fragment");
11700 		frags++;
11701 	}
11702 	if (frags == fs->fs_frag) {
11703 		blkno = fragstoblks(fs, cgbno);
11704 		ffs_clrblock(fs, blksfree, (long)blkno);
11705 		ffs_clusteracct(fs, cgp, blkno, -1);
11706 		cgp->cg_cs.cs_nbfree--;
11707 	} else {
11708 		bbase = cgbno - fragnum(fs, cgbno);
11709 		cgbno += jnewblk->jn_oldfrags;
11710                 /* If a complete block had been reassembled, account for it. */
11711 		fragno = fragstoblks(fs, bbase);
11712 		if (ffs_isblock(fs, blksfree, fragno)) {
11713 			cgp->cg_cs.cs_nffree += fs->fs_frag;
11714 			ffs_clusteracct(fs, cgp, fragno, -1);
11715 			cgp->cg_cs.cs_nbfree--;
11716 		}
11717 		/* Decrement the old frags.  */
11718 		blk = blkmap(fs, blksfree, bbase);
11719 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11720 		/* Allocate the fragment */
11721 		for (i = 0; i < frags; i++)
11722 			clrbit(blksfree, cgbno + i);
11723 		cgp->cg_cs.cs_nffree -= frags;
11724 		/* Add back in counts associated with the new frags */
11725 		blk = blkmap(fs, blksfree, bbase);
11726 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11727 	}
11728 	return (frags);
11729 }
11730 
11731 /*
11732  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
11733  * changes if it's not a background write.  Set all written dependencies
11734  * to DEPCOMPLETE and free the structure if possible.
11735  */
11736 static int
11737 handle_written_bmsafemap(bmsafemap, bp)
11738 	struct bmsafemap *bmsafemap;
11739 	struct buf *bp;
11740 {
11741 	struct newblk *newblk;
11742 	struct inodedep *inodedep;
11743 	struct jaddref *jaddref, *jatmp;
11744 	struct jnewblk *jnewblk, *jntmp;
11745 	struct ufsmount *ump;
11746 	uint8_t *inosused;
11747 	uint8_t *blksfree;
11748 	struct cg *cgp;
11749 	struct fs *fs;
11750 	ino_t ino;
11751 	int foreground;
11752 	int chgs;
11753 
11754 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
11755 		panic("initiate_write_bmsafemap: Not started\n");
11756 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
11757 	chgs = 0;
11758 	bmsafemap->sm_state &= ~IOSTARTED;
11759 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
11760 	/*
11761 	 * Release journal work that was waiting on the write.
11762 	 */
11763 	handle_jwork(&bmsafemap->sm_freewr);
11764 
11765 	/*
11766 	 * Restore unwritten inode allocation pending jaddref writes.
11767 	 */
11768 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
11769 		cgp = (struct cg *)bp->b_data;
11770 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11771 		inosused = cg_inosused(cgp);
11772 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
11773 		    ja_bmdeps, jatmp) {
11774 			if ((jaddref->ja_state & UNDONE) == 0)
11775 				continue;
11776 			ino = jaddref->ja_ino % fs->fs_ipg;
11777 			if (isset(inosused, ino))
11778 				panic("handle_written_bmsafemap: "
11779 				    "re-allocated inode");
11780 			/* Do the roll-forward only if it's a real copy. */
11781 			if (foreground) {
11782 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11783 					cgp->cg_cs.cs_ndir++;
11784 				cgp->cg_cs.cs_nifree--;
11785 				setbit(inosused, ino);
11786 				chgs = 1;
11787 			}
11788 			jaddref->ja_state &= ~UNDONE;
11789 			jaddref->ja_state |= ATTACHED;
11790 			free_jaddref(jaddref);
11791 		}
11792 	}
11793 	/*
11794 	 * Restore any block allocations which are pending journal writes.
11795 	 */
11796 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11797 		cgp = (struct cg *)bp->b_data;
11798 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11799 		blksfree = cg_blksfree(cgp);
11800 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
11801 		    jntmp) {
11802 			if ((jnewblk->jn_state & UNDONE) == 0)
11803 				continue;
11804 			/* Do the roll-forward only if it's a real copy. */
11805 			if (foreground &&
11806 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
11807 				chgs = 1;
11808 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
11809 			jnewblk->jn_state |= ATTACHED;
11810 			free_jnewblk(jnewblk);
11811 		}
11812 	}
11813 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
11814 		newblk->nb_state |= DEPCOMPLETE;
11815 		newblk->nb_state &= ~ONDEPLIST;
11816 		newblk->nb_bmsafemap = NULL;
11817 		LIST_REMOVE(newblk, nb_deps);
11818 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
11819 			handle_allocdirect_partdone(
11820 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
11821 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
11822 			handle_allocindir_partdone(
11823 			    WK_ALLOCINDIR(&newblk->nb_list));
11824 		else if (newblk->nb_list.wk_type != D_NEWBLK)
11825 			panic("handle_written_bmsafemap: Unexpected type: %s",
11826 			    TYPENAME(newblk->nb_list.wk_type));
11827 	}
11828 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
11829 		inodedep->id_state |= DEPCOMPLETE;
11830 		inodedep->id_state &= ~ONDEPLIST;
11831 		LIST_REMOVE(inodedep, id_deps);
11832 		inodedep->id_bmsafemap = NULL;
11833 	}
11834 	LIST_REMOVE(bmsafemap, sm_next);
11835 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
11836 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
11837 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
11838 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
11839 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
11840 		LIST_REMOVE(bmsafemap, sm_hash);
11841 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
11842 		return (0);
11843 	}
11844 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
11845 	if (foreground)
11846 		bdirty(bp);
11847 	return (1);
11848 }
11849 
11850 /*
11851  * Try to free a mkdir dependency.
11852  */
11853 static void
11854 complete_mkdir(mkdir)
11855 	struct mkdir *mkdir;
11856 {
11857 	struct diradd *dap;
11858 
11859 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
11860 		return;
11861 	LIST_REMOVE(mkdir, md_mkdirs);
11862 	dap = mkdir->md_diradd;
11863 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
11864 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
11865 		dap->da_state |= DEPCOMPLETE;
11866 		complete_diradd(dap);
11867 	}
11868 	WORKITEM_FREE(mkdir, D_MKDIR);
11869 }
11870 
11871 /*
11872  * Handle the completion of a mkdir dependency.
11873  */
11874 static void
11875 handle_written_mkdir(mkdir, type)
11876 	struct mkdir *mkdir;
11877 	int type;
11878 {
11879 
11880 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
11881 		panic("handle_written_mkdir: bad type");
11882 	mkdir->md_state |= COMPLETE;
11883 	complete_mkdir(mkdir);
11884 }
11885 
11886 static int
11887 free_pagedep(pagedep)
11888 	struct pagedep *pagedep;
11889 {
11890 	int i;
11891 
11892 	if (pagedep->pd_state & NEWBLOCK)
11893 		return (0);
11894 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
11895 		return (0);
11896 	for (i = 0; i < DAHASHSZ; i++)
11897 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
11898 			return (0);
11899 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
11900 		return (0);
11901 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
11902 		return (0);
11903 	if (pagedep->pd_state & ONWORKLIST)
11904 		WORKLIST_REMOVE(&pagedep->pd_list);
11905 	LIST_REMOVE(pagedep, pd_hash);
11906 	WORKITEM_FREE(pagedep, D_PAGEDEP);
11907 
11908 	return (1);
11909 }
11910 
11911 /*
11912  * Called from within softdep_disk_write_complete above.
11913  * A write operation was just completed. Removed inodes can
11914  * now be freed and associated block pointers may be committed.
11915  * Note that this routine is always called from interrupt level
11916  * with further splbio interrupts blocked.
11917  */
11918 static int
11919 handle_written_filepage(pagedep, bp)
11920 	struct pagedep *pagedep;
11921 	struct buf *bp;		/* buffer containing the written page */
11922 {
11923 	struct dirrem *dirrem;
11924 	struct diradd *dap, *nextdap;
11925 	struct direct *ep;
11926 	int i, chgs;
11927 
11928 	if ((pagedep->pd_state & IOSTARTED) == 0)
11929 		panic("handle_written_filepage: not started");
11930 	pagedep->pd_state &= ~IOSTARTED;
11931 	/*
11932 	 * Process any directory removals that have been committed.
11933 	 */
11934 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
11935 		LIST_REMOVE(dirrem, dm_next);
11936 		dirrem->dm_state |= COMPLETE;
11937 		dirrem->dm_dirinum = pagedep->pd_ino;
11938 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
11939 		    ("handle_written_filepage: Journal entries not written."));
11940 		add_to_worklist(&dirrem->dm_list, 0);
11941 	}
11942 	/*
11943 	 * Free any directory additions that have been committed.
11944 	 * If it is a newly allocated block, we have to wait until
11945 	 * the on-disk directory inode claims the new block.
11946 	 */
11947 	if ((pagedep->pd_state & NEWBLOCK) == 0)
11948 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
11949 			free_diradd(dap, NULL);
11950 	/*
11951 	 * Uncommitted directory entries must be restored.
11952 	 */
11953 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
11954 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
11955 		     dap = nextdap) {
11956 			nextdap = LIST_NEXT(dap, da_pdlist);
11957 			if (dap->da_state & ATTACHED)
11958 				panic("handle_written_filepage: attached");
11959 			ep = (struct direct *)
11960 			    ((char *)bp->b_data + dap->da_offset);
11961 			ep->d_ino = dap->da_newinum;
11962 			dap->da_state &= ~UNDONE;
11963 			dap->da_state |= ATTACHED;
11964 			chgs = 1;
11965 			/*
11966 			 * If the inode referenced by the directory has
11967 			 * been written out, then the dependency can be
11968 			 * moved to the pending list.
11969 			 */
11970 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
11971 				LIST_REMOVE(dap, da_pdlist);
11972 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
11973 				    da_pdlist);
11974 			}
11975 		}
11976 	}
11977 	/*
11978 	 * If there were any rollbacks in the directory, then it must be
11979 	 * marked dirty so that its will eventually get written back in
11980 	 * its correct form.
11981 	 */
11982 	if (chgs) {
11983 		if ((bp->b_flags & B_DELWRI) == 0)
11984 			stat_dir_entry++;
11985 		bdirty(bp);
11986 		return (1);
11987 	}
11988 	/*
11989 	 * If we are not waiting for a new directory block to be
11990 	 * claimed by its inode, then the pagedep will be freed.
11991 	 * Otherwise it will remain to track any new entries on
11992 	 * the page in case they are fsync'ed.
11993 	 */
11994 	free_pagedep(pagedep);
11995 	return (0);
11996 }
11997 
11998 /*
11999  * Writing back in-core inode structures.
12000  *
12001  * The filesystem only accesses an inode's contents when it occupies an
12002  * "in-core" inode structure.  These "in-core" structures are separate from
12003  * the page frames used to cache inode blocks.  Only the latter are
12004  * transferred to/from the disk.  So, when the updated contents of the
12005  * "in-core" inode structure are copied to the corresponding in-memory inode
12006  * block, the dependencies are also transferred.  The following procedure is
12007  * called when copying a dirty "in-core" inode to a cached inode block.
12008  */
12009 
12010 /*
12011  * Called when an inode is loaded from disk. If the effective link count
12012  * differed from the actual link count when it was last flushed, then we
12013  * need to ensure that the correct effective link count is put back.
12014  */
12015 void
12016 softdep_load_inodeblock(ip)
12017 	struct inode *ip;	/* the "in_core" copy of the inode */
12018 {
12019 	struct inodedep *inodedep;
12020 
12021 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
12022 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12023 	/*
12024 	 * Check for alternate nlink count.
12025 	 */
12026 	ip->i_effnlink = ip->i_nlink;
12027 	ACQUIRE_LOCK(ip->i_ump);
12028 	if (inodedep_lookup(UFSTOVFS(ip->i_ump), ip->i_number, 0,
12029 	    &inodedep) == 0) {
12030 		FREE_LOCK(ip->i_ump);
12031 		return;
12032 	}
12033 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12034 	FREE_LOCK(ip->i_ump);
12035 }
12036 
12037 /*
12038  * This routine is called just before the "in-core" inode
12039  * information is to be copied to the in-memory inode block.
12040  * Recall that an inode block contains several inodes. If
12041  * the force flag is set, then the dependencies will be
12042  * cleared so that the update can always be made. Note that
12043  * the buffer is locked when this routine is called, so we
12044  * will never be in the middle of writing the inode block
12045  * to disk.
12046  */
12047 void
12048 softdep_update_inodeblock(ip, bp, waitfor)
12049 	struct inode *ip;	/* the "in_core" copy of the inode */
12050 	struct buf *bp;		/* the buffer containing the inode block */
12051 	int waitfor;		/* nonzero => update must be allowed */
12052 {
12053 	struct inodedep *inodedep;
12054 	struct inoref *inoref;
12055 	struct ufsmount *ump;
12056 	struct worklist *wk;
12057 	struct mount *mp;
12058 	struct buf *ibp;
12059 	struct fs *fs;
12060 	int error;
12061 
12062 	ump = ip->i_ump;
12063 	mp = UFSTOVFS(ump);
12064 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12065 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12066 	fs = ip->i_fs;
12067 	/*
12068 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12069 	 * does not have access to the in-core ip so must write directly into
12070 	 * the inode block buffer when setting freelink.
12071 	 */
12072 	if (fs->fs_magic == FS_UFS1_MAGIC)
12073 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12074 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12075 	else
12076 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12077 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12078 	/*
12079 	 * If the effective link count is not equal to the actual link
12080 	 * count, then we must track the difference in an inodedep while
12081 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12082 	 * if there is no existing inodedep, then there are no dependencies
12083 	 * to track.
12084 	 */
12085 	ACQUIRE_LOCK(ump);
12086 again:
12087 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12088 		FREE_LOCK(ump);
12089 		if (ip->i_effnlink != ip->i_nlink)
12090 			panic("softdep_update_inodeblock: bad link count");
12091 		return;
12092 	}
12093 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12094 		panic("softdep_update_inodeblock: bad delta");
12095 	/*
12096 	 * If we're flushing all dependencies we must also move any waiting
12097 	 * for journal writes onto the bufwait list prior to I/O.
12098 	 */
12099 	if (waitfor) {
12100 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12101 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12102 			    == DEPCOMPLETE) {
12103 				jwait(&inoref->if_list, MNT_WAIT);
12104 				goto again;
12105 			}
12106 		}
12107 	}
12108 	/*
12109 	 * Changes have been initiated. Anything depending on these
12110 	 * changes cannot occur until this inode has been written.
12111 	 */
12112 	inodedep->id_state &= ~COMPLETE;
12113 	if ((inodedep->id_state & ONWORKLIST) == 0)
12114 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12115 	/*
12116 	 * Any new dependencies associated with the incore inode must
12117 	 * now be moved to the list associated with the buffer holding
12118 	 * the in-memory copy of the inode. Once merged process any
12119 	 * allocdirects that are completed by the merger.
12120 	 */
12121 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12122 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12123 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12124 		    NULL);
12125 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12126 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12127 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12128 		    NULL);
12129 	/*
12130 	 * Now that the inode has been pushed into the buffer, the
12131 	 * operations dependent on the inode being written to disk
12132 	 * can be moved to the id_bufwait so that they will be
12133 	 * processed when the buffer I/O completes.
12134 	 */
12135 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12136 		WORKLIST_REMOVE(wk);
12137 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12138 	}
12139 	/*
12140 	 * Newly allocated inodes cannot be written until the bitmap
12141 	 * that allocates them have been written (indicated by
12142 	 * DEPCOMPLETE being set in id_state). If we are doing a
12143 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12144 	 * to be written so that the update can be done.
12145 	 */
12146 	if (waitfor == 0) {
12147 		FREE_LOCK(ump);
12148 		return;
12149 	}
12150 retry:
12151 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12152 		FREE_LOCK(ump);
12153 		return;
12154 	}
12155 	ibp = inodedep->id_bmsafemap->sm_buf;
12156 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12157 	if (ibp == NULL) {
12158 		/*
12159 		 * If ibp came back as NULL, the dependency could have been
12160 		 * freed while we slept.  Look it up again, and check to see
12161 		 * that it has completed.
12162 		 */
12163 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12164 			goto retry;
12165 		FREE_LOCK(ump);
12166 		return;
12167 	}
12168 	FREE_LOCK(ump);
12169 	if ((error = bwrite(ibp)) != 0)
12170 		softdep_error("softdep_update_inodeblock: bwrite", error);
12171 }
12172 
12173 /*
12174  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12175  * old inode dependency list (such as id_inoupdt). This routine must be
12176  * called with splbio interrupts blocked.
12177  */
12178 static void
12179 merge_inode_lists(newlisthead, oldlisthead)
12180 	struct allocdirectlst *newlisthead;
12181 	struct allocdirectlst *oldlisthead;
12182 {
12183 	struct allocdirect *listadp, *newadp;
12184 
12185 	newadp = TAILQ_FIRST(newlisthead);
12186 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12187 		if (listadp->ad_offset < newadp->ad_offset) {
12188 			listadp = TAILQ_NEXT(listadp, ad_next);
12189 			continue;
12190 		}
12191 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12192 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12193 		if (listadp->ad_offset == newadp->ad_offset) {
12194 			allocdirect_merge(oldlisthead, newadp,
12195 			    listadp);
12196 			listadp = newadp;
12197 		}
12198 		newadp = TAILQ_FIRST(newlisthead);
12199 	}
12200 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12201 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12202 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12203 	}
12204 }
12205 
12206 /*
12207  * If we are doing an fsync, then we must ensure that any directory
12208  * entries for the inode have been written after the inode gets to disk.
12209  */
12210 int
12211 softdep_fsync(vp)
12212 	struct vnode *vp;	/* the "in_core" copy of the inode */
12213 {
12214 	struct inodedep *inodedep;
12215 	struct pagedep *pagedep;
12216 	struct inoref *inoref;
12217 	struct ufsmount *ump;
12218 	struct worklist *wk;
12219 	struct diradd *dap;
12220 	struct mount *mp;
12221 	struct vnode *pvp;
12222 	struct inode *ip;
12223 	struct buf *bp;
12224 	struct fs *fs;
12225 	struct thread *td = curthread;
12226 	int error, flushparent, pagedep_new_block;
12227 	ino_t parentino;
12228 	ufs_lbn_t lbn;
12229 
12230 	ip = VTOI(vp);
12231 	fs = ip->i_fs;
12232 	ump = ip->i_ump;
12233 	mp = vp->v_mount;
12234 	if (MOUNTEDSOFTDEP(mp) == 0)
12235 		return (0);
12236 	ACQUIRE_LOCK(ump);
12237 restart:
12238 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12239 		FREE_LOCK(ump);
12240 		return (0);
12241 	}
12242 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12243 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12244 		    == DEPCOMPLETE) {
12245 			jwait(&inoref->if_list, MNT_WAIT);
12246 			goto restart;
12247 		}
12248 	}
12249 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12250 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12251 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12252 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12253 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12254 		panic("softdep_fsync: pending ops %p", inodedep);
12255 	for (error = 0, flushparent = 0; ; ) {
12256 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12257 			break;
12258 		if (wk->wk_type != D_DIRADD)
12259 			panic("softdep_fsync: Unexpected type %s",
12260 			    TYPENAME(wk->wk_type));
12261 		dap = WK_DIRADD(wk);
12262 		/*
12263 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12264 		 * dependency or is contained in a newly allocated block.
12265 		 */
12266 		if (dap->da_state & DIRCHG)
12267 			pagedep = dap->da_previous->dm_pagedep;
12268 		else
12269 			pagedep = dap->da_pagedep;
12270 		parentino = pagedep->pd_ino;
12271 		lbn = pagedep->pd_lbn;
12272 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12273 			panic("softdep_fsync: dirty");
12274 		if ((dap->da_state & MKDIR_PARENT) ||
12275 		    (pagedep->pd_state & NEWBLOCK))
12276 			flushparent = 1;
12277 		else
12278 			flushparent = 0;
12279 		/*
12280 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12281 		 * then we will not be able to release and recover the
12282 		 * vnode below, so we just have to give up on writing its
12283 		 * directory entry out. It will eventually be written, just
12284 		 * not now, but then the user was not asking to have it
12285 		 * written, so we are not breaking any promises.
12286 		 */
12287 		if (vp->v_iflag & VI_DOOMED)
12288 			break;
12289 		/*
12290 		 * We prevent deadlock by always fetching inodes from the
12291 		 * root, moving down the directory tree. Thus, when fetching
12292 		 * our parent directory, we first try to get the lock. If
12293 		 * that fails, we must unlock ourselves before requesting
12294 		 * the lock on our parent. See the comment in ufs_lookup
12295 		 * for details on possible races.
12296 		 */
12297 		FREE_LOCK(ump);
12298 		if (ffs_vgetf(mp, parentino, LK_NOWAIT | LK_EXCLUSIVE, &pvp,
12299 		    FFSV_FORCEINSMQ)) {
12300 			error = vfs_busy(mp, MBF_NOWAIT);
12301 			if (error != 0) {
12302 				vfs_ref(mp);
12303 				VOP_UNLOCK(vp, 0);
12304 				error = vfs_busy(mp, 0);
12305 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12306 				vfs_rel(mp);
12307 				if (error != 0)
12308 					return (ENOENT);
12309 				if (vp->v_iflag & VI_DOOMED) {
12310 					vfs_unbusy(mp);
12311 					return (ENOENT);
12312 				}
12313 			}
12314 			VOP_UNLOCK(vp, 0);
12315 			error = ffs_vgetf(mp, parentino, LK_EXCLUSIVE,
12316 			    &pvp, FFSV_FORCEINSMQ);
12317 			vfs_unbusy(mp);
12318 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
12319 			if (vp->v_iflag & VI_DOOMED) {
12320 				if (error == 0)
12321 					vput(pvp);
12322 				error = ENOENT;
12323 			}
12324 			if (error != 0)
12325 				return (error);
12326 		}
12327 		/*
12328 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12329 		 * that are contained in direct blocks will be resolved by
12330 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12331 		 * may require a complete sync'ing of the directory. So, we
12332 		 * try the cheap and fast ffs_update first, and if that fails,
12333 		 * then we do the slower ffs_syncvnode of the directory.
12334 		 */
12335 		if (flushparent) {
12336 			int locked;
12337 
12338 			if ((error = ffs_update(pvp, 1)) != 0) {
12339 				vput(pvp);
12340 				return (error);
12341 			}
12342 			ACQUIRE_LOCK(ump);
12343 			locked = 1;
12344 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12345 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12346 					if (wk->wk_type != D_DIRADD)
12347 						panic("softdep_fsync: Unexpected type %s",
12348 						      TYPENAME(wk->wk_type));
12349 					dap = WK_DIRADD(wk);
12350 					if (dap->da_state & DIRCHG)
12351 						pagedep = dap->da_previous->dm_pagedep;
12352 					else
12353 						pagedep = dap->da_pagedep;
12354 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12355 					FREE_LOCK(ump);
12356 					locked = 0;
12357 					if (pagedep_new_block && (error =
12358 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12359 						vput(pvp);
12360 						return (error);
12361 					}
12362 				}
12363 			}
12364 			if (locked)
12365 				FREE_LOCK(ump);
12366 		}
12367 		/*
12368 		 * Flush directory page containing the inode's name.
12369 		 */
12370 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12371 		    &bp);
12372 		if (error == 0)
12373 			error = bwrite(bp);
12374 		else
12375 			brelse(bp);
12376 		vput(pvp);
12377 		if (error != 0)
12378 			return (error);
12379 		ACQUIRE_LOCK(ump);
12380 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12381 			break;
12382 	}
12383 	FREE_LOCK(ump);
12384 	return (0);
12385 }
12386 
12387 /*
12388  * Flush all the dirty bitmaps associated with the block device
12389  * before flushing the rest of the dirty blocks so as to reduce
12390  * the number of dependencies that will have to be rolled back.
12391  *
12392  * XXX Unused?
12393  */
12394 void
12395 softdep_fsync_mountdev(vp)
12396 	struct vnode *vp;
12397 {
12398 	struct buf *bp, *nbp;
12399 	struct worklist *wk;
12400 	struct bufobj *bo;
12401 
12402 	if (!vn_isdisk(vp, NULL))
12403 		panic("softdep_fsync_mountdev: vnode not a disk");
12404 	bo = &vp->v_bufobj;
12405 restart:
12406 	BO_LOCK(bo);
12407 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
12408 		/*
12409 		 * If it is already scheduled, skip to the next buffer.
12410 		 */
12411 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
12412 			continue;
12413 
12414 		if ((bp->b_flags & B_DELWRI) == 0)
12415 			panic("softdep_fsync_mountdev: not dirty");
12416 		/*
12417 		 * We are only interested in bitmaps with outstanding
12418 		 * dependencies.
12419 		 */
12420 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
12421 		    wk->wk_type != D_BMSAFEMAP ||
12422 		    (bp->b_vflags & BV_BKGRDINPROG)) {
12423 			BUF_UNLOCK(bp);
12424 			continue;
12425 		}
12426 		BO_UNLOCK(bo);
12427 		bremfree(bp);
12428 		(void) bawrite(bp);
12429 		goto restart;
12430 	}
12431 	drain_output(vp);
12432 	BO_UNLOCK(bo);
12433 }
12434 
12435 /*
12436  * Sync all cylinder groups that were dirty at the time this function is
12437  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
12438  * is used to flush freedep activity that may be holding up writes to a
12439  * indirect block.
12440  */
12441 static int
12442 sync_cgs(mp, waitfor)
12443 	struct mount *mp;
12444 	int waitfor;
12445 {
12446 	struct bmsafemap *bmsafemap;
12447 	struct bmsafemap *sentinel;
12448 	struct ufsmount *ump;
12449 	struct buf *bp;
12450 	int error;
12451 
12452 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
12453 	sentinel->sm_cg = -1;
12454 	ump = VFSTOUFS(mp);
12455 	error = 0;
12456 	ACQUIRE_LOCK(ump);
12457 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
12458 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
12459 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
12460 		/* Skip sentinels and cgs with no work to release. */
12461 		if (bmsafemap->sm_cg == -1 ||
12462 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
12463 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
12464 			LIST_REMOVE(sentinel, sm_next);
12465 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12466 			continue;
12467 		}
12468 		/*
12469 		 * If we don't get the lock and we're waiting try again, if
12470 		 * not move on to the next buf and try to sync it.
12471 		 */
12472 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
12473 		if (bp == NULL && waitfor == MNT_WAIT)
12474 			continue;
12475 		LIST_REMOVE(sentinel, sm_next);
12476 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
12477 		if (bp == NULL)
12478 			continue;
12479 		FREE_LOCK(ump);
12480 		if (waitfor == MNT_NOWAIT)
12481 			bawrite(bp);
12482 		else
12483 			error = bwrite(bp);
12484 		ACQUIRE_LOCK(ump);
12485 		if (error)
12486 			break;
12487 	}
12488 	LIST_REMOVE(sentinel, sm_next);
12489 	FREE_LOCK(ump);
12490 	free(sentinel, M_BMSAFEMAP);
12491 	return (error);
12492 }
12493 
12494 /*
12495  * This routine is called when we are trying to synchronously flush a
12496  * file. This routine must eliminate any filesystem metadata dependencies
12497  * so that the syncing routine can succeed.
12498  */
12499 int
12500 softdep_sync_metadata(struct vnode *vp)
12501 {
12502 	struct inode *ip;
12503 	int error;
12504 
12505 	ip = VTOI(vp);
12506 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
12507 	    ("softdep_sync_metadata called on non-softdep filesystem"));
12508 	/*
12509 	 * Ensure that any direct block dependencies have been cleared,
12510 	 * truncations are started, and inode references are journaled.
12511 	 */
12512 	ACQUIRE_LOCK(ip->i_ump);
12513 	/*
12514 	 * Write all journal records to prevent rollbacks on devvp.
12515 	 */
12516 	if (vp->v_type == VCHR)
12517 		softdep_flushjournal(vp->v_mount);
12518 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
12519 	/*
12520 	 * Ensure that all truncates are written so we won't find deps on
12521 	 * indirect blocks.
12522 	 */
12523 	process_truncates(vp);
12524 	FREE_LOCK(ip->i_ump);
12525 
12526 	return (error);
12527 }
12528 
12529 /*
12530  * This routine is called when we are attempting to sync a buf with
12531  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
12532  * other IO it can but returns EBUSY if the buffer is not yet able to
12533  * be written.  Dependencies which will not cause rollbacks will always
12534  * return 0.
12535  */
12536 int
12537 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
12538 {
12539 	struct indirdep *indirdep;
12540 	struct pagedep *pagedep;
12541 	struct allocindir *aip;
12542 	struct newblk *newblk;
12543 	struct ufsmount *ump;
12544 	struct buf *nbp;
12545 	struct worklist *wk;
12546 	int i, error;
12547 
12548 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
12549 	    ("softdep_sync_buf called on non-softdep filesystem"));
12550 	/*
12551 	 * For VCHR we just don't want to force flush any dependencies that
12552 	 * will cause rollbacks.
12553 	 */
12554 	if (vp->v_type == VCHR) {
12555 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
12556 			return (EBUSY);
12557 		return (0);
12558 	}
12559 	ump = VTOI(vp)->i_ump;
12560 	ACQUIRE_LOCK(ump);
12561 	/*
12562 	 * As we hold the buffer locked, none of its dependencies
12563 	 * will disappear.
12564 	 */
12565 	error = 0;
12566 top:
12567 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
12568 		switch (wk->wk_type) {
12569 
12570 		case D_ALLOCDIRECT:
12571 		case D_ALLOCINDIR:
12572 			newblk = WK_NEWBLK(wk);
12573 			if (newblk->nb_jnewblk != NULL) {
12574 				if (waitfor == MNT_NOWAIT) {
12575 					error = EBUSY;
12576 					goto out_unlock;
12577 				}
12578 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
12579 				goto top;
12580 			}
12581 			if (newblk->nb_state & DEPCOMPLETE ||
12582 			    waitfor == MNT_NOWAIT)
12583 				continue;
12584 			nbp = newblk->nb_bmsafemap->sm_buf;
12585 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12586 			if (nbp == NULL)
12587 				goto top;
12588 			FREE_LOCK(ump);
12589 			if ((error = bwrite(nbp)) != 0)
12590 				goto out;
12591 			ACQUIRE_LOCK(ump);
12592 			continue;
12593 
12594 		case D_INDIRDEP:
12595 			indirdep = WK_INDIRDEP(wk);
12596 			if (waitfor == MNT_NOWAIT) {
12597 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
12598 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
12599 					error = EBUSY;
12600 					goto out_unlock;
12601 				}
12602 			}
12603 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
12604 				panic("softdep_sync_buf: truncation pending.");
12605 		restart:
12606 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
12607 				newblk = (struct newblk *)aip;
12608 				if (newblk->nb_jnewblk != NULL) {
12609 					jwait(&newblk->nb_jnewblk->jn_list,
12610 					    waitfor);
12611 					goto restart;
12612 				}
12613 				if (newblk->nb_state & DEPCOMPLETE)
12614 					continue;
12615 				nbp = newblk->nb_bmsafemap->sm_buf;
12616 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
12617 				if (nbp == NULL)
12618 					goto restart;
12619 				FREE_LOCK(ump);
12620 				if ((error = bwrite(nbp)) != 0)
12621 					goto out;
12622 				ACQUIRE_LOCK(ump);
12623 				goto restart;
12624 			}
12625 			continue;
12626 
12627 		case D_PAGEDEP:
12628 			/*
12629 			 * Only flush directory entries in synchronous passes.
12630 			 */
12631 			if (waitfor != MNT_WAIT) {
12632 				error = EBUSY;
12633 				goto out_unlock;
12634 			}
12635 			/*
12636 			 * While syncing snapshots, we must allow recursive
12637 			 * lookups.
12638 			 */
12639 			BUF_AREC(bp);
12640 			/*
12641 			 * We are trying to sync a directory that may
12642 			 * have dependencies on both its own metadata
12643 			 * and/or dependencies on the inodes of any
12644 			 * recently allocated files. We walk its diradd
12645 			 * lists pushing out the associated inode.
12646 			 */
12647 			pagedep = WK_PAGEDEP(wk);
12648 			for (i = 0; i < DAHASHSZ; i++) {
12649 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
12650 					continue;
12651 				if ((error = flush_pagedep_deps(vp, wk->wk_mp,
12652 				    &pagedep->pd_diraddhd[i]))) {
12653 					BUF_NOREC(bp);
12654 					goto out_unlock;
12655 				}
12656 			}
12657 			BUF_NOREC(bp);
12658 			continue;
12659 
12660 		case D_FREEWORK:
12661 		case D_FREEDEP:
12662 		case D_JSEGDEP:
12663 		case D_JNEWBLK:
12664 			continue;
12665 
12666 		default:
12667 			panic("softdep_sync_buf: Unknown type %s",
12668 			    TYPENAME(wk->wk_type));
12669 			/* NOTREACHED */
12670 		}
12671 	}
12672 out_unlock:
12673 	FREE_LOCK(ump);
12674 out:
12675 	return (error);
12676 }
12677 
12678 /*
12679  * Flush the dependencies associated with an inodedep.
12680  * Called with splbio blocked.
12681  */
12682 static int
12683 flush_inodedep_deps(vp, mp, ino)
12684 	struct vnode *vp;
12685 	struct mount *mp;
12686 	ino_t ino;
12687 {
12688 	struct inodedep *inodedep;
12689 	struct inoref *inoref;
12690 	struct ufsmount *ump;
12691 	int error, waitfor;
12692 
12693 	/*
12694 	 * This work is done in two passes. The first pass grabs most
12695 	 * of the buffers and begins asynchronously writing them. The
12696 	 * only way to wait for these asynchronous writes is to sleep
12697 	 * on the filesystem vnode which may stay busy for a long time
12698 	 * if the filesystem is active. So, instead, we make a second
12699 	 * pass over the dependencies blocking on each write. In the
12700 	 * usual case we will be blocking against a write that we
12701 	 * initiated, so when it is done the dependency will have been
12702 	 * resolved. Thus the second pass is expected to end quickly.
12703 	 * We give a brief window at the top of the loop to allow
12704 	 * any pending I/O to complete.
12705 	 */
12706 	ump = VFSTOUFS(mp);
12707 	LOCK_OWNED(ump);
12708 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
12709 		if (error)
12710 			return (error);
12711 		FREE_LOCK(ump);
12712 		ACQUIRE_LOCK(ump);
12713 restart:
12714 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
12715 			return (0);
12716 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12717 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12718 			    == DEPCOMPLETE) {
12719 				jwait(&inoref->if_list, MNT_WAIT);
12720 				goto restart;
12721 			}
12722 		}
12723 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
12724 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
12725 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
12726 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
12727 			continue;
12728 		/*
12729 		 * If pass2, we are done, otherwise do pass 2.
12730 		 */
12731 		if (waitfor == MNT_WAIT)
12732 			break;
12733 		waitfor = MNT_WAIT;
12734 	}
12735 	/*
12736 	 * Try freeing inodedep in case all dependencies have been removed.
12737 	 */
12738 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
12739 		(void) free_inodedep(inodedep);
12740 	return (0);
12741 }
12742 
12743 /*
12744  * Flush an inode dependency list.
12745  * Called with splbio blocked.
12746  */
12747 static int
12748 flush_deplist(listhead, waitfor, errorp)
12749 	struct allocdirectlst *listhead;
12750 	int waitfor;
12751 	int *errorp;
12752 {
12753 	struct allocdirect *adp;
12754 	struct newblk *newblk;
12755 	struct ufsmount *ump;
12756 	struct buf *bp;
12757 
12758 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
12759 		return (0);
12760 	ump = VFSTOUFS(adp->ad_list.wk_mp);
12761 	LOCK_OWNED(ump);
12762 	TAILQ_FOREACH(adp, listhead, ad_next) {
12763 		newblk = (struct newblk *)adp;
12764 		if (newblk->nb_jnewblk != NULL) {
12765 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12766 			return (1);
12767 		}
12768 		if (newblk->nb_state & DEPCOMPLETE)
12769 			continue;
12770 		bp = newblk->nb_bmsafemap->sm_buf;
12771 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
12772 		if (bp == NULL) {
12773 			if (waitfor == MNT_NOWAIT)
12774 				continue;
12775 			return (1);
12776 		}
12777 		FREE_LOCK(ump);
12778 		if (waitfor == MNT_NOWAIT)
12779 			bawrite(bp);
12780 		else
12781 			*errorp = bwrite(bp);
12782 		ACQUIRE_LOCK(ump);
12783 		return (1);
12784 	}
12785 	return (0);
12786 }
12787 
12788 /*
12789  * Flush dependencies associated with an allocdirect block.
12790  */
12791 static int
12792 flush_newblk_dep(vp, mp, lbn)
12793 	struct vnode *vp;
12794 	struct mount *mp;
12795 	ufs_lbn_t lbn;
12796 {
12797 	struct newblk *newblk;
12798 	struct ufsmount *ump;
12799 	struct bufobj *bo;
12800 	struct inode *ip;
12801 	struct buf *bp;
12802 	ufs2_daddr_t blkno;
12803 	int error;
12804 
12805 	error = 0;
12806 	bo = &vp->v_bufobj;
12807 	ip = VTOI(vp);
12808 	blkno = DIP(ip, i_db[lbn]);
12809 	if (blkno == 0)
12810 		panic("flush_newblk_dep: Missing block");
12811 	ump = VFSTOUFS(mp);
12812 	ACQUIRE_LOCK(ump);
12813 	/*
12814 	 * Loop until all dependencies related to this block are satisfied.
12815 	 * We must be careful to restart after each sleep in case a write
12816 	 * completes some part of this process for us.
12817 	 */
12818 	for (;;) {
12819 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
12820 			FREE_LOCK(ump);
12821 			break;
12822 		}
12823 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
12824 			panic("flush_newblk_deps: Bad newblk %p", newblk);
12825 		/*
12826 		 * Flush the journal.
12827 		 */
12828 		if (newblk->nb_jnewblk != NULL) {
12829 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
12830 			continue;
12831 		}
12832 		/*
12833 		 * Write the bitmap dependency.
12834 		 */
12835 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
12836 			bp = newblk->nb_bmsafemap->sm_buf;
12837 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
12838 			if (bp == NULL)
12839 				continue;
12840 			FREE_LOCK(ump);
12841 			error = bwrite(bp);
12842 			if (error)
12843 				break;
12844 			ACQUIRE_LOCK(ump);
12845 			continue;
12846 		}
12847 		/*
12848 		 * Write the buffer.
12849 		 */
12850 		FREE_LOCK(ump);
12851 		BO_LOCK(bo);
12852 		bp = gbincore(bo, lbn);
12853 		if (bp != NULL) {
12854 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
12855 			    LK_INTERLOCK, BO_LOCKPTR(bo));
12856 			if (error == ENOLCK) {
12857 				ACQUIRE_LOCK(ump);
12858 				continue; /* Slept, retry */
12859 			}
12860 			if (error != 0)
12861 				break;	/* Failed */
12862 			if (bp->b_flags & B_DELWRI) {
12863 				bremfree(bp);
12864 				error = bwrite(bp);
12865 				if (error)
12866 					break;
12867 			} else
12868 				BUF_UNLOCK(bp);
12869 		} else
12870 			BO_UNLOCK(bo);
12871 		/*
12872 		 * We have to wait for the direct pointers to
12873 		 * point at the newdirblk before the dependency
12874 		 * will go away.
12875 		 */
12876 		error = ffs_update(vp, 1);
12877 		if (error)
12878 			break;
12879 		ACQUIRE_LOCK(ump);
12880 	}
12881 	return (error);
12882 }
12883 
12884 /*
12885  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
12886  * Called with splbio blocked.
12887  */
12888 static int
12889 flush_pagedep_deps(pvp, mp, diraddhdp)
12890 	struct vnode *pvp;
12891 	struct mount *mp;
12892 	struct diraddhd *diraddhdp;
12893 {
12894 	struct inodedep *inodedep;
12895 	struct inoref *inoref;
12896 	struct ufsmount *ump;
12897 	struct diradd *dap;
12898 	struct vnode *vp;
12899 	int error = 0;
12900 	struct buf *bp;
12901 	ino_t inum;
12902 	struct diraddhd unfinished;
12903 
12904 	LIST_INIT(&unfinished);
12905 	ump = VFSTOUFS(mp);
12906 	LOCK_OWNED(ump);
12907 restart:
12908 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
12909 		/*
12910 		 * Flush ourselves if this directory entry
12911 		 * has a MKDIR_PARENT dependency.
12912 		 */
12913 		if (dap->da_state & MKDIR_PARENT) {
12914 			FREE_LOCK(ump);
12915 			if ((error = ffs_update(pvp, 1)) != 0)
12916 				break;
12917 			ACQUIRE_LOCK(ump);
12918 			/*
12919 			 * If that cleared dependencies, go on to next.
12920 			 */
12921 			if (dap != LIST_FIRST(diraddhdp))
12922 				continue;
12923 			/*
12924 			 * All MKDIR_PARENT dependencies and all the
12925 			 * NEWBLOCK pagedeps that are contained in direct
12926 			 * blocks were resolved by doing above ffs_update.
12927 			 * Pagedeps contained in indirect blocks may
12928 			 * require a complete sync'ing of the directory.
12929 			 * We are in the midst of doing a complete sync,
12930 			 * so if they are not resolved in this pass we
12931 			 * defer them for now as they will be sync'ed by
12932 			 * our caller shortly.
12933 			 */
12934 			LIST_REMOVE(dap, da_pdlist);
12935 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
12936 			continue;
12937 		}
12938 		/*
12939 		 * A newly allocated directory must have its "." and
12940 		 * ".." entries written out before its name can be
12941 		 * committed in its parent.
12942 		 */
12943 		inum = dap->da_newinum;
12944 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12945 			panic("flush_pagedep_deps: lost inode1");
12946 		/*
12947 		 * Wait for any pending journal adds to complete so we don't
12948 		 * cause rollbacks while syncing.
12949 		 */
12950 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12951 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12952 			    == DEPCOMPLETE) {
12953 				jwait(&inoref->if_list, MNT_WAIT);
12954 				goto restart;
12955 			}
12956 		}
12957 		if (dap->da_state & MKDIR_BODY) {
12958 			FREE_LOCK(ump);
12959 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
12960 			    FFSV_FORCEINSMQ)))
12961 				break;
12962 			error = flush_newblk_dep(vp, mp, 0);
12963 			/*
12964 			 * If we still have the dependency we might need to
12965 			 * update the vnode to sync the new link count to
12966 			 * disk.
12967 			 */
12968 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
12969 				error = ffs_update(vp, 1);
12970 			vput(vp);
12971 			if (error != 0)
12972 				break;
12973 			ACQUIRE_LOCK(ump);
12974 			/*
12975 			 * If that cleared dependencies, go on to next.
12976 			 */
12977 			if (dap != LIST_FIRST(diraddhdp))
12978 				continue;
12979 			if (dap->da_state & MKDIR_BODY) {
12980 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
12981 				    &inodedep);
12982 				panic("flush_pagedep_deps: MKDIR_BODY "
12983 				    "inodedep %p dap %p vp %p",
12984 				    inodedep, dap, vp);
12985 			}
12986 		}
12987 		/*
12988 		 * Flush the inode on which the directory entry depends.
12989 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
12990 		 * the only remaining dependency is that the updated inode
12991 		 * count must get pushed to disk. The inode has already
12992 		 * been pushed into its inode buffer (via VOP_UPDATE) at
12993 		 * the time of the reference count change. So we need only
12994 		 * locate that buffer, ensure that there will be no rollback
12995 		 * caused by a bitmap dependency, then write the inode buffer.
12996 		 */
12997 retry:
12998 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
12999 			panic("flush_pagedep_deps: lost inode");
13000 		/*
13001 		 * If the inode still has bitmap dependencies,
13002 		 * push them to disk.
13003 		 */
13004 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13005 			bp = inodedep->id_bmsafemap->sm_buf;
13006 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13007 			if (bp == NULL)
13008 				goto retry;
13009 			FREE_LOCK(ump);
13010 			if ((error = bwrite(bp)) != 0)
13011 				break;
13012 			ACQUIRE_LOCK(ump);
13013 			if (dap != LIST_FIRST(diraddhdp))
13014 				continue;
13015 		}
13016 		/*
13017 		 * If the inode is still sitting in a buffer waiting
13018 		 * to be written or waiting for the link count to be
13019 		 * adjusted update it here to flush it to disk.
13020 		 */
13021 		if (dap == LIST_FIRST(diraddhdp)) {
13022 			FREE_LOCK(ump);
13023 			if ((error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &vp,
13024 			    FFSV_FORCEINSMQ)))
13025 				break;
13026 			error = ffs_update(vp, 1);
13027 			vput(vp);
13028 			if (error)
13029 				break;
13030 			ACQUIRE_LOCK(ump);
13031 		}
13032 		/*
13033 		 * If we have failed to get rid of all the dependencies
13034 		 * then something is seriously wrong.
13035 		 */
13036 		if (dap == LIST_FIRST(diraddhdp)) {
13037 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13038 			panic("flush_pagedep_deps: failed to flush "
13039 			    "inodedep %p ino %ju dap %p",
13040 			    inodedep, (uintmax_t)inum, dap);
13041 		}
13042 	}
13043 	if (error)
13044 		ACQUIRE_LOCK(ump);
13045 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13046 		LIST_REMOVE(dap, da_pdlist);
13047 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13048 	}
13049 	return (error);
13050 }
13051 
13052 /*
13053  * A large burst of file addition or deletion activity can drive the
13054  * memory load excessively high. First attempt to slow things down
13055  * using the techniques below. If that fails, this routine requests
13056  * the offending operations to fall back to running synchronously
13057  * until the memory load returns to a reasonable level.
13058  */
13059 int
13060 softdep_slowdown(vp)
13061 	struct vnode *vp;
13062 {
13063 	struct ufsmount *ump;
13064 	int jlow;
13065 	int max_softdeps_hard;
13066 
13067 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13068 	    ("softdep_slowdown called on non-softdep filesystem"));
13069 	ump = VFSTOUFS(vp->v_mount);
13070 	ACQUIRE_LOCK(ump);
13071 	jlow = 0;
13072 	/*
13073 	 * Check for journal space if needed.
13074 	 */
13075 	if (DOINGSUJ(vp)) {
13076 		if (journal_space(ump, 0) == 0)
13077 			jlow = 1;
13078 	}
13079 	/*
13080 	 * If the system is under its limits and our filesystem is
13081 	 * not responsible for more than our share of the usage and
13082 	 * we are not low on journal space, then no need to slow down.
13083 	 */
13084 	max_softdeps_hard = max_softdeps * 11 / 10;
13085 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13086 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13087 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13088 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13089 	    ump->softdep_curdeps[D_DIRREM] <
13090 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13091 	    ump->softdep_curdeps[D_INODEDEP] <
13092 	    max_softdeps_hard / stat_flush_threads &&
13093 	    ump->softdep_curdeps[D_INDIRDEP] <
13094 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13095 	    ump->softdep_curdeps[D_FREEBLKS] <
13096 	    max_softdeps_hard / stat_flush_threads) {
13097 		FREE_LOCK(ump);
13098   		return (0);
13099 	}
13100 	/*
13101 	 * If the journal is low or our filesystem is over its limit
13102 	 * then speedup the cleanup.
13103 	 */
13104 	if (ump->softdep_curdeps[D_INDIRDEP] <
13105 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13106 		softdep_speedup(ump);
13107 	stat_sync_limit_hit += 1;
13108 	FREE_LOCK(ump);
13109 	/*
13110 	 * We only slow down the rate at which new dependencies are
13111 	 * generated if we are not using journaling. With journaling,
13112 	 * the cleanup should always be sufficient to keep things
13113 	 * under control.
13114 	 */
13115 	if (DOINGSUJ(vp))
13116 		return (0);
13117 	return (1);
13118 }
13119 
13120 /*
13121  * Called by the allocation routines when they are about to fail
13122  * in the hope that we can free up the requested resource (inodes
13123  * or disk space).
13124  *
13125  * First check to see if the work list has anything on it. If it has,
13126  * clean up entries until we successfully free the requested resource.
13127  * Because this process holds inodes locked, we cannot handle any remove
13128  * requests that might block on a locked inode as that could lead to
13129  * deadlock. If the worklist yields none of the requested resource,
13130  * start syncing out vnodes to free up the needed space.
13131  */
13132 int
13133 softdep_request_cleanup(fs, vp, cred, resource)
13134 	struct fs *fs;
13135 	struct vnode *vp;
13136 	struct ucred *cred;
13137 	int resource;
13138 {
13139 	struct ufsmount *ump;
13140 	struct mount *mp;
13141 	struct vnode *lvp, *mvp;
13142 	long starttime;
13143 	ufs2_daddr_t needed;
13144 	int error;
13145 
13146 	/*
13147 	 * If we are being called because of a process doing a
13148 	 * copy-on-write, then it is not safe to process any
13149 	 * worklist items as we will recurse into the copyonwrite
13150 	 * routine.  This will result in an incoherent snapshot.
13151 	 * If the vnode that we hold is a snapshot, we must avoid
13152 	 * handling other resources that could cause deadlock.
13153 	 */
13154 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13155 		return (0);
13156 
13157 	if (resource == FLUSH_BLOCKS_WAIT)
13158 		stat_cleanup_blkrequests += 1;
13159 	else
13160 		stat_cleanup_inorequests += 1;
13161 
13162 	mp = vp->v_mount;
13163 	ump = VFSTOUFS(mp);
13164 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13165 	UFS_UNLOCK(ump);
13166 	error = ffs_update(vp, 1);
13167 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13168 		UFS_LOCK(ump);
13169 		return (0);
13170 	}
13171 	/*
13172 	 * If we are in need of resources, start by cleaning up
13173 	 * any block removals associated with our inode.
13174 	 */
13175 	ACQUIRE_LOCK(ump);
13176 	process_removes(vp);
13177 	process_truncates(vp);
13178 	FREE_LOCK(ump);
13179 	/*
13180 	 * Now clean up at least as many resources as we will need.
13181 	 *
13182 	 * When requested to clean up inodes, the number that are needed
13183 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13184 	 * plus a bit of slop (2) in case some more writers show up while
13185 	 * we are cleaning.
13186 	 *
13187 	 * When requested to free up space, the amount of space that
13188 	 * we need is enough blocks to allocate a full-sized segment
13189 	 * (fs_contigsumsize). The number of such segments that will
13190 	 * be needed is set by the number of simultaneous writers
13191 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13192 	 * writers show up while we are cleaning.
13193 	 *
13194 	 * Additionally, if we are unpriviledged and allocating space,
13195 	 * we need to ensure that we clean up enough blocks to get the
13196 	 * needed number of blocks over the threshhold of the minimum
13197 	 * number of blocks required to be kept free by the filesystem
13198 	 * (fs_minfree).
13199 	 */
13200 	if (resource == FLUSH_INODES_WAIT) {
13201 		needed = vp->v_mount->mnt_writeopcount + 2;
13202 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13203 		needed = (vp->v_mount->mnt_writeopcount + 2) *
13204 		    fs->fs_contigsumsize;
13205 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE, 0))
13206 			needed += fragstoblks(fs,
13207 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13208 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13209 	} else {
13210 		UFS_LOCK(ump);
13211 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13212 		    resource);
13213 		return (0);
13214 	}
13215 	starttime = time_second;
13216 retry:
13217 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13218 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13219 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13220 	    fs->fs_cstotal.cs_nifree <= needed)) {
13221 		ACQUIRE_LOCK(ump);
13222 		if (ump->softdep_on_worklist > 0 &&
13223 		    process_worklist_item(UFSTOVFS(ump),
13224 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13225 			stat_worklist_push += 1;
13226 		FREE_LOCK(ump);
13227 	}
13228 	/*
13229 	 * If we still need resources and there are no more worklist
13230 	 * entries to process to obtain them, we have to start flushing
13231 	 * the dirty vnodes to force the release of additional requests
13232 	 * to the worklist that we can then process to reap addition
13233 	 * resources. We walk the vnodes associated with the mount point
13234 	 * until we get the needed worklist requests that we can reap.
13235 	 */
13236 	if ((resource == FLUSH_BLOCKS_WAIT &&
13237 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13238 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13239 	     fs->fs_cstotal.cs_nifree <= needed)) {
13240 		MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13241 			if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13242 				VI_UNLOCK(lvp);
13243 				continue;
13244 			}
13245 			if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT,
13246 			    curthread))
13247 				continue;
13248 			if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13249 				vput(lvp);
13250 				continue;
13251 			}
13252 			(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13253 			vput(lvp);
13254 		}
13255 		lvp = ump->um_devvp;
13256 		if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13257 			VOP_FSYNC(lvp, MNT_NOWAIT, curthread);
13258 			VOP_UNLOCK(lvp, 0);
13259 		}
13260 		if (ump->softdep_on_worklist > 0) {
13261 			stat_cleanup_retries += 1;
13262 			goto retry;
13263 		}
13264 		stat_cleanup_failures += 1;
13265 	}
13266 	if (time_second - starttime > stat_cleanup_high_delay)
13267 		stat_cleanup_high_delay = time_second - starttime;
13268 	UFS_LOCK(ump);
13269 	return (1);
13270 }
13271 
13272 /*
13273  * If memory utilization has gotten too high, deliberately slow things
13274  * down and speed up the I/O processing.
13275  */
13276 static int
13277 request_cleanup(mp, resource)
13278 	struct mount *mp;
13279 	int resource;
13280 {
13281 	struct thread *td = curthread;
13282 	struct ufsmount *ump;
13283 
13284 	ump = VFSTOUFS(mp);
13285 	LOCK_OWNED(ump);
13286 	/*
13287 	 * We never hold up the filesystem syncer or buf daemon.
13288 	 */
13289 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
13290 		return (0);
13291 	/*
13292 	 * First check to see if the work list has gotten backlogged.
13293 	 * If it has, co-opt this process to help clean up two entries.
13294 	 * Because this process may hold inodes locked, we cannot
13295 	 * handle any remove requests that might block on a locked
13296 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
13297 	 * to avoid recursively processing the worklist.
13298 	 */
13299 	if (ump->softdep_on_worklist > max_softdeps / 10) {
13300 		td->td_pflags |= TDP_SOFTDEP;
13301 		process_worklist_item(mp, 2, LK_NOWAIT);
13302 		td->td_pflags &= ~TDP_SOFTDEP;
13303 		stat_worklist_push += 2;
13304 		return(1);
13305 	}
13306 	/*
13307 	 * Next, we attempt to speed up the syncer process. If that
13308 	 * is successful, then we allow the process to continue.
13309 	 */
13310 	if (softdep_speedup(ump) &&
13311 	    resource != FLUSH_BLOCKS_WAIT &&
13312 	    resource != FLUSH_INODES_WAIT)
13313 		return(0);
13314 	/*
13315 	 * If we are resource constrained on inode dependencies, try
13316 	 * flushing some dirty inodes. Otherwise, we are constrained
13317 	 * by file deletions, so try accelerating flushes of directories
13318 	 * with removal dependencies. We would like to do the cleanup
13319 	 * here, but we probably hold an inode locked at this point and
13320 	 * that might deadlock against one that we try to clean. So,
13321 	 * the best that we can do is request the syncer daemon to do
13322 	 * the cleanup for us.
13323 	 */
13324 	switch (resource) {
13325 
13326 	case FLUSH_INODES:
13327 	case FLUSH_INODES_WAIT:
13328 		ACQUIRE_GBLLOCK(&lk);
13329 		stat_ino_limit_push += 1;
13330 		req_clear_inodedeps += 1;
13331 		FREE_GBLLOCK(&lk);
13332 		stat_countp = &stat_ino_limit_hit;
13333 		break;
13334 
13335 	case FLUSH_BLOCKS:
13336 	case FLUSH_BLOCKS_WAIT:
13337 		ACQUIRE_GBLLOCK(&lk);
13338 		stat_blk_limit_push += 1;
13339 		req_clear_remove += 1;
13340 		FREE_GBLLOCK(&lk);
13341 		stat_countp = &stat_blk_limit_hit;
13342 		break;
13343 
13344 	default:
13345 		panic("request_cleanup: unknown type");
13346 	}
13347 	/*
13348 	 * Hopefully the syncer daemon will catch up and awaken us.
13349 	 * We wait at most tickdelay before proceeding in any case.
13350 	 */
13351 	ACQUIRE_GBLLOCK(&lk);
13352 	FREE_LOCK(ump);
13353 	proc_waiting += 1;
13354 	if (callout_pending(&softdep_callout) == FALSE)
13355 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
13356 		    pause_timer, 0);
13357 
13358 	msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
13359 	proc_waiting -= 1;
13360 	FREE_GBLLOCK(&lk);
13361 	ACQUIRE_LOCK(ump);
13362 	return (1);
13363 }
13364 
13365 /*
13366  * Awaken processes pausing in request_cleanup and clear proc_waiting
13367  * to indicate that there is no longer a timer running. Pause_timer
13368  * will be called with the global softdep mutex (&lk) locked.
13369  */
13370 static void
13371 pause_timer(arg)
13372 	void *arg;
13373 {
13374 
13375 	GBLLOCK_OWNED(&lk);
13376 	/*
13377 	 * The callout_ API has acquired mtx and will hold it around this
13378 	 * function call.
13379 	 */
13380 	*stat_countp += proc_waiting;
13381 	wakeup(&proc_waiting);
13382 }
13383 
13384 /*
13385  * If requested, try removing inode or removal dependencies.
13386  */
13387 static void
13388 check_clear_deps(mp)
13389 	struct mount *mp;
13390 {
13391 
13392 	/*
13393 	 * If we are suspended, it may be because of our using
13394 	 * too many inodedeps, so help clear them out.
13395 	 */
13396 	if (MOUNTEDSUJ(mp) && VFSTOUFS(mp)->softdep_jblocks->jb_suspended)
13397 		clear_inodedeps(mp);
13398 	/*
13399 	 * General requests for cleanup of backed up dependencies
13400 	 */
13401 	ACQUIRE_GBLLOCK(&lk);
13402 	if (req_clear_inodedeps) {
13403 		req_clear_inodedeps -= 1;
13404 		FREE_GBLLOCK(&lk);
13405 		clear_inodedeps(mp);
13406 		ACQUIRE_GBLLOCK(&lk);
13407 		wakeup(&proc_waiting);
13408 	}
13409 	if (req_clear_remove) {
13410 		req_clear_remove -= 1;
13411 		FREE_GBLLOCK(&lk);
13412 		clear_remove(mp);
13413 		ACQUIRE_GBLLOCK(&lk);
13414 		wakeup(&proc_waiting);
13415 	}
13416 	FREE_GBLLOCK(&lk);
13417 }
13418 
13419 /*
13420  * Flush out a directory with at least one removal dependency in an effort to
13421  * reduce the number of dirrem, freefile, and freeblks dependency structures.
13422  */
13423 static void
13424 clear_remove(mp)
13425 	struct mount *mp;
13426 {
13427 	struct pagedep_hashhead *pagedephd;
13428 	struct pagedep *pagedep;
13429 	struct ufsmount *ump;
13430 	struct vnode *vp;
13431 	struct bufobj *bo;
13432 	int error, cnt;
13433 	ino_t ino;
13434 
13435 	ump = VFSTOUFS(mp);
13436 	LOCK_OWNED(ump);
13437 
13438 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
13439 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
13440 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
13441 			ump->pagedep_nextclean = 0;
13442 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
13443 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
13444 				continue;
13445 			ino = pagedep->pd_ino;
13446 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13447 				continue;
13448 			FREE_LOCK(ump);
13449 
13450 			/*
13451 			 * Let unmount clear deps
13452 			 */
13453 			error = vfs_busy(mp, MBF_NOWAIT);
13454 			if (error != 0)
13455 				goto finish_write;
13456 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13457 			     FFSV_FORCEINSMQ);
13458 			vfs_unbusy(mp);
13459 			if (error != 0) {
13460 				softdep_error("clear_remove: vget", error);
13461 				goto finish_write;
13462 			}
13463 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13464 				softdep_error("clear_remove: fsync", error);
13465 			bo = &vp->v_bufobj;
13466 			BO_LOCK(bo);
13467 			drain_output(vp);
13468 			BO_UNLOCK(bo);
13469 			vput(vp);
13470 		finish_write:
13471 			vn_finished_write(mp);
13472 			ACQUIRE_LOCK(ump);
13473 			return;
13474 		}
13475 	}
13476 }
13477 
13478 /*
13479  * Clear out a block of dirty inodes in an effort to reduce
13480  * the number of inodedep dependency structures.
13481  */
13482 static void
13483 clear_inodedeps(mp)
13484 	struct mount *mp;
13485 {
13486 	struct inodedep_hashhead *inodedephd;
13487 	struct inodedep *inodedep;
13488 	struct ufsmount *ump;
13489 	struct vnode *vp;
13490 	struct fs *fs;
13491 	int error, cnt;
13492 	ino_t firstino, lastino, ino;
13493 
13494 	ump = VFSTOUFS(mp);
13495 	fs = ump->um_fs;
13496 	LOCK_OWNED(ump);
13497 	/*
13498 	 * Pick a random inode dependency to be cleared.
13499 	 * We will then gather up all the inodes in its block
13500 	 * that have dependencies and flush them out.
13501 	 */
13502 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
13503 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
13504 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
13505 			ump->inodedep_nextclean = 0;
13506 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
13507 			break;
13508 	}
13509 	if (inodedep == NULL)
13510 		return;
13511 	/*
13512 	 * Find the last inode in the block with dependencies.
13513 	 */
13514 	firstino = inodedep->id_ino & ~(INOPB(fs) - 1);
13515 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
13516 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
13517 			break;
13518 	/*
13519 	 * Asynchronously push all but the last inode with dependencies.
13520 	 * Synchronously push the last inode with dependencies to ensure
13521 	 * that the inode block gets written to free up the inodedeps.
13522 	 */
13523 	for (ino = firstino; ino <= lastino; ino++) {
13524 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13525 			continue;
13526 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
13527 			continue;
13528 		FREE_LOCK(ump);
13529 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
13530 		if (error != 0) {
13531 			vn_finished_write(mp);
13532 			ACQUIRE_LOCK(ump);
13533 			return;
13534 		}
13535 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
13536 		    FFSV_FORCEINSMQ)) != 0) {
13537 			softdep_error("clear_inodedeps: vget", error);
13538 			vfs_unbusy(mp);
13539 			vn_finished_write(mp);
13540 			ACQUIRE_LOCK(ump);
13541 			return;
13542 		}
13543 		vfs_unbusy(mp);
13544 		if (ino == lastino) {
13545 			if ((error = ffs_syncvnode(vp, MNT_WAIT, 0)))
13546 				softdep_error("clear_inodedeps: fsync1", error);
13547 		} else {
13548 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
13549 				softdep_error("clear_inodedeps: fsync2", error);
13550 			BO_LOCK(&vp->v_bufobj);
13551 			drain_output(vp);
13552 			BO_UNLOCK(&vp->v_bufobj);
13553 		}
13554 		vput(vp);
13555 		vn_finished_write(mp);
13556 		ACQUIRE_LOCK(ump);
13557 	}
13558 }
13559 
13560 void
13561 softdep_buf_append(bp, wkhd)
13562 	struct buf *bp;
13563 	struct workhead *wkhd;
13564 {
13565 	struct worklist *wk;
13566 	struct ufsmount *ump;
13567 
13568 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13569 		return;
13570 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13571 	    ("softdep_buf_append called on non-softdep filesystem"));
13572 	ump = VFSTOUFS(wk->wk_mp);
13573 	ACQUIRE_LOCK(ump);
13574 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
13575 		WORKLIST_REMOVE(wk);
13576 		WORKLIST_INSERT(&bp->b_dep, wk);
13577 	}
13578 	FREE_LOCK(ump);
13579 
13580 }
13581 
13582 void
13583 softdep_inode_append(ip, cred, wkhd)
13584 	struct inode *ip;
13585 	struct ucred *cred;
13586 	struct workhead *wkhd;
13587 {
13588 	struct buf *bp;
13589 	struct fs *fs;
13590 	int error;
13591 
13592 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ip->i_ump)) != 0,
13593 	    ("softdep_inode_append called on non-softdep filesystem"));
13594 	fs = ip->i_fs;
13595 	error = bread(ip->i_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
13596 	    (int)fs->fs_bsize, cred, &bp);
13597 	if (error) {
13598 		bqrelse(bp);
13599 		softdep_freework(wkhd);
13600 		return;
13601 	}
13602 	softdep_buf_append(bp, wkhd);
13603 	bqrelse(bp);
13604 }
13605 
13606 void
13607 softdep_freework(wkhd)
13608 	struct workhead *wkhd;
13609 {
13610 	struct worklist *wk;
13611 	struct ufsmount *ump;
13612 
13613 	if ((wk = LIST_FIRST(wkhd)) == NULL)
13614 		return;
13615 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
13616 	    ("softdep_freework called on non-softdep filesystem"));
13617 	ump = VFSTOUFS(wk->wk_mp);
13618 	ACQUIRE_LOCK(ump);
13619 	handle_jwork(wkhd);
13620 	FREE_LOCK(ump);
13621 }
13622 
13623 /*
13624  * Function to determine if the buffer has outstanding dependencies
13625  * that will cause a roll-back if the buffer is written. If wantcount
13626  * is set, return number of dependencies, otherwise just yes or no.
13627  */
13628 static int
13629 softdep_count_dependencies(bp, wantcount)
13630 	struct buf *bp;
13631 	int wantcount;
13632 {
13633 	struct worklist *wk;
13634 	struct ufsmount *ump;
13635 	struct bmsafemap *bmsafemap;
13636 	struct freework *freework;
13637 	struct inodedep *inodedep;
13638 	struct indirdep *indirdep;
13639 	struct freeblks *freeblks;
13640 	struct allocindir *aip;
13641 	struct pagedep *pagedep;
13642 	struct dirrem *dirrem;
13643 	struct newblk *newblk;
13644 	struct mkdir *mkdir;
13645 	struct diradd *dap;
13646 	int i, retval;
13647 
13648 	retval = 0;
13649 	if ((wk = LIST_FIRST(&bp->b_dep)) == NULL)
13650 		return (0);
13651 	ump = VFSTOUFS(wk->wk_mp);
13652 	ACQUIRE_LOCK(ump);
13653 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13654 		switch (wk->wk_type) {
13655 
13656 		case D_INODEDEP:
13657 			inodedep = WK_INODEDEP(wk);
13658 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
13659 				/* bitmap allocation dependency */
13660 				retval += 1;
13661 				if (!wantcount)
13662 					goto out;
13663 			}
13664 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
13665 				/* direct block pointer dependency */
13666 				retval += 1;
13667 				if (!wantcount)
13668 					goto out;
13669 			}
13670 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
13671 				/* direct block pointer dependency */
13672 				retval += 1;
13673 				if (!wantcount)
13674 					goto out;
13675 			}
13676 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
13677 				/* Add reference dependency. */
13678 				retval += 1;
13679 				if (!wantcount)
13680 					goto out;
13681 			}
13682 			continue;
13683 
13684 		case D_INDIRDEP:
13685 			indirdep = WK_INDIRDEP(wk);
13686 
13687 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
13688 				/* indirect truncation dependency */
13689 				retval += 1;
13690 				if (!wantcount)
13691 					goto out;
13692 			}
13693 
13694 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13695 				/* indirect block pointer dependency */
13696 				retval += 1;
13697 				if (!wantcount)
13698 					goto out;
13699 			}
13700 			continue;
13701 
13702 		case D_PAGEDEP:
13703 			pagedep = WK_PAGEDEP(wk);
13704 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
13705 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
13706 					/* Journal remove ref dependency. */
13707 					retval += 1;
13708 					if (!wantcount)
13709 						goto out;
13710 				}
13711 			}
13712 			for (i = 0; i < DAHASHSZ; i++) {
13713 
13714 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
13715 					/* directory entry dependency */
13716 					retval += 1;
13717 					if (!wantcount)
13718 						goto out;
13719 				}
13720 			}
13721 			continue;
13722 
13723 		case D_BMSAFEMAP:
13724 			bmsafemap = WK_BMSAFEMAP(wk);
13725 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
13726 				/* Add reference dependency. */
13727 				retval += 1;
13728 				if (!wantcount)
13729 					goto out;
13730 			}
13731 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
13732 				/* Allocate block dependency. */
13733 				retval += 1;
13734 				if (!wantcount)
13735 					goto out;
13736 			}
13737 			continue;
13738 
13739 		case D_FREEBLKS:
13740 			freeblks = WK_FREEBLKS(wk);
13741 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
13742 				/* Freeblk journal dependency. */
13743 				retval += 1;
13744 				if (!wantcount)
13745 					goto out;
13746 			}
13747 			continue;
13748 
13749 		case D_ALLOCDIRECT:
13750 		case D_ALLOCINDIR:
13751 			newblk = WK_NEWBLK(wk);
13752 			if (newblk->nb_jnewblk) {
13753 				/* Journal allocate dependency. */
13754 				retval += 1;
13755 				if (!wantcount)
13756 					goto out;
13757 			}
13758 			continue;
13759 
13760 		case D_MKDIR:
13761 			mkdir = WK_MKDIR(wk);
13762 			if (mkdir->md_jaddref) {
13763 				/* Journal reference dependency. */
13764 				retval += 1;
13765 				if (!wantcount)
13766 					goto out;
13767 			}
13768 			continue;
13769 
13770 		case D_FREEWORK:
13771 		case D_FREEDEP:
13772 		case D_JSEGDEP:
13773 		case D_JSEG:
13774 		case D_SBDEP:
13775 			/* never a dependency on these blocks */
13776 			continue;
13777 
13778 		default:
13779 			panic("softdep_count_dependencies: Unexpected type %s",
13780 			    TYPENAME(wk->wk_type));
13781 			/* NOTREACHED */
13782 		}
13783 	}
13784 out:
13785 	FREE_LOCK(ump);
13786 	return retval;
13787 }
13788 
13789 /*
13790  * Acquire exclusive access to a buffer.
13791  * Must be called with a locked mtx parameter.
13792  * Return acquired buffer or NULL on failure.
13793  */
13794 static struct buf *
13795 getdirtybuf(bp, lock, waitfor)
13796 	struct buf *bp;
13797 	struct rwlock *lock;
13798 	int waitfor;
13799 {
13800 	int error;
13801 
13802 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
13803 		if (waitfor != MNT_WAIT)
13804 			return (NULL);
13805 		error = BUF_LOCK(bp,
13806 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
13807 		/*
13808 		 * Even if we sucessfully acquire bp here, we have dropped
13809 		 * lock, which may violates our guarantee.
13810 		 */
13811 		if (error == 0)
13812 			BUF_UNLOCK(bp);
13813 		else if (error != ENOLCK)
13814 			panic("getdirtybuf: inconsistent lock: %d", error);
13815 		rw_wlock(lock);
13816 		return (NULL);
13817 	}
13818 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13819 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
13820 			rw_wunlock(lock);
13821 			BO_LOCK(bp->b_bufobj);
13822 			BUF_UNLOCK(bp);
13823 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
13824 				bp->b_vflags |= BV_BKGRDWAIT;
13825 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
13826 				       PRIBIO | PDROP, "getbuf", 0);
13827 			} else
13828 				BO_UNLOCK(bp->b_bufobj);
13829 			rw_wlock(lock);
13830 			return (NULL);
13831 		}
13832 		BUF_UNLOCK(bp);
13833 		if (waitfor != MNT_WAIT)
13834 			return (NULL);
13835 		/*
13836 		 * The lock argument must be bp->b_vp's mutex in
13837 		 * this case.
13838 		 */
13839 #ifdef	DEBUG_VFS_LOCKS
13840 		if (bp->b_vp->v_type != VCHR)
13841 			ASSERT_BO_WLOCKED(bp->b_bufobj);
13842 #endif
13843 		bp->b_vflags |= BV_BKGRDWAIT;
13844 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
13845 		return (NULL);
13846 	}
13847 	if ((bp->b_flags & B_DELWRI) == 0) {
13848 		BUF_UNLOCK(bp);
13849 		return (NULL);
13850 	}
13851 	bremfree(bp);
13852 	return (bp);
13853 }
13854 
13855 
13856 /*
13857  * Check if it is safe to suspend the file system now.  On entry,
13858  * the vnode interlock for devvp should be held.  Return 0 with
13859  * the mount interlock held if the file system can be suspended now,
13860  * otherwise return EAGAIN with the mount interlock held.
13861  */
13862 int
13863 softdep_check_suspend(struct mount *mp,
13864 		      struct vnode *devvp,
13865 		      int softdep_depcnt,
13866 		      int softdep_accdepcnt,
13867 		      int secondary_writes,
13868 		      int secondary_accwrites)
13869 {
13870 	struct bufobj *bo;
13871 	struct ufsmount *ump;
13872 	struct inodedep *inodedep;
13873 	int error, unlinked;
13874 
13875 	bo = &devvp->v_bufobj;
13876 	ASSERT_BO_WLOCKED(bo);
13877 
13878 	/*
13879 	 * If we are not running with soft updates, then we need only
13880 	 * deal with secondary writes as we try to suspend.
13881 	 */
13882 	if (MOUNTEDSOFTDEP(mp) == 0) {
13883 		MNT_ILOCK(mp);
13884 		while (mp->mnt_secondary_writes != 0) {
13885 			BO_UNLOCK(bo);
13886 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
13887 			    (PUSER - 1) | PDROP, "secwr", 0);
13888 			BO_LOCK(bo);
13889 			MNT_ILOCK(mp);
13890 		}
13891 
13892 		/*
13893 		 * Reasons for needing more work before suspend:
13894 		 * - Dirty buffers on devvp.
13895 		 * - Secondary writes occurred after start of vnode sync loop
13896 		 */
13897 		error = 0;
13898 		if (bo->bo_numoutput > 0 ||
13899 		    bo->bo_dirty.bv_cnt > 0 ||
13900 		    secondary_writes != 0 ||
13901 		    mp->mnt_secondary_writes != 0 ||
13902 		    secondary_accwrites != mp->mnt_secondary_accwrites)
13903 			error = EAGAIN;
13904 		BO_UNLOCK(bo);
13905 		return (error);
13906 	}
13907 
13908 	/*
13909 	 * If we are running with soft updates, then we need to coordinate
13910 	 * with them as we try to suspend.
13911 	 */
13912 	ump = VFSTOUFS(mp);
13913 	for (;;) {
13914 		if (!TRY_ACQUIRE_LOCK(ump)) {
13915 			BO_UNLOCK(bo);
13916 			ACQUIRE_LOCK(ump);
13917 			FREE_LOCK(ump);
13918 			BO_LOCK(bo);
13919 			continue;
13920 		}
13921 		MNT_ILOCK(mp);
13922 		if (mp->mnt_secondary_writes != 0) {
13923 			FREE_LOCK(ump);
13924 			BO_UNLOCK(bo);
13925 			msleep(&mp->mnt_secondary_writes,
13926 			       MNT_MTX(mp),
13927 			       (PUSER - 1) | PDROP, "secwr", 0);
13928 			BO_LOCK(bo);
13929 			continue;
13930 		}
13931 		break;
13932 	}
13933 
13934 	unlinked = 0;
13935 	if (MOUNTEDSUJ(mp)) {
13936 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
13937 		    inodedep != NULL;
13938 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
13939 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
13940 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
13941 			    UNLINKONLIST) ||
13942 			    !check_inodedep_free(inodedep))
13943 				continue;
13944 			unlinked++;
13945 		}
13946 	}
13947 
13948 	/*
13949 	 * Reasons for needing more work before suspend:
13950 	 * - Dirty buffers on devvp.
13951 	 * - Softdep activity occurred after start of vnode sync loop
13952 	 * - Secondary writes occurred after start of vnode sync loop
13953 	 */
13954 	error = 0;
13955 	if (bo->bo_numoutput > 0 ||
13956 	    bo->bo_dirty.bv_cnt > 0 ||
13957 	    softdep_depcnt != unlinked ||
13958 	    ump->softdep_deps != unlinked ||
13959 	    softdep_accdepcnt != ump->softdep_accdeps ||
13960 	    secondary_writes != 0 ||
13961 	    mp->mnt_secondary_writes != 0 ||
13962 	    secondary_accwrites != mp->mnt_secondary_accwrites)
13963 		error = EAGAIN;
13964 	FREE_LOCK(ump);
13965 	BO_UNLOCK(bo);
13966 	return (error);
13967 }
13968 
13969 
13970 /*
13971  * Get the number of dependency structures for the file system, both
13972  * the current number and the total number allocated.  These will
13973  * later be used to detect that softdep processing has occurred.
13974  */
13975 void
13976 softdep_get_depcounts(struct mount *mp,
13977 		      int *softdep_depsp,
13978 		      int *softdep_accdepsp)
13979 {
13980 	struct ufsmount *ump;
13981 
13982 	if (MOUNTEDSOFTDEP(mp) == 0) {
13983 		*softdep_depsp = 0;
13984 		*softdep_accdepsp = 0;
13985 		return;
13986 	}
13987 	ump = VFSTOUFS(mp);
13988 	ACQUIRE_LOCK(ump);
13989 	*softdep_depsp = ump->softdep_deps;
13990 	*softdep_accdepsp = ump->softdep_accdeps;
13991 	FREE_LOCK(ump);
13992 }
13993 
13994 /*
13995  * Wait for pending output on a vnode to complete.
13996  * Must be called with vnode lock and interlock locked.
13997  *
13998  * XXX: Should just be a call to bufobj_wwait().
13999  */
14000 static void
14001 drain_output(vp)
14002 	struct vnode *vp;
14003 {
14004 	struct bufobj *bo;
14005 
14006 	bo = &vp->v_bufobj;
14007 	ASSERT_VOP_LOCKED(vp, "drain_output");
14008 	ASSERT_BO_WLOCKED(bo);
14009 
14010 	while (bo->bo_numoutput) {
14011 		bo->bo_flag |= BO_WWAIT;
14012 		msleep((caddr_t)&bo->bo_numoutput,
14013 		    BO_LOCKPTR(bo), PRIBIO + 1, "drainvp", 0);
14014 	}
14015 }
14016 
14017 /*
14018  * Called whenever a buffer that is being invalidated or reallocated
14019  * contains dependencies. This should only happen if an I/O error has
14020  * occurred. The routine is called with the buffer locked.
14021  */
14022 static void
14023 softdep_deallocate_dependencies(bp)
14024 	struct buf *bp;
14025 {
14026 
14027 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14028 		panic("softdep_deallocate_dependencies: dangling deps");
14029 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14030 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14031 	else
14032 		printf("softdep_deallocate_dependencies: "
14033 		    "got error %d while accessing filesystem\n", bp->b_error);
14034 	if (bp->b_error != ENXIO)
14035 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14036 }
14037 
14038 /*
14039  * Function to handle asynchronous write errors in the filesystem.
14040  */
14041 static void
14042 softdep_error(func, error)
14043 	char *func;
14044 	int error;
14045 {
14046 
14047 	/* XXX should do something better! */
14048 	printf("%s: got error %d while accessing filesystem\n", func, error);
14049 }
14050 
14051 #ifdef DDB
14052 
14053 static void
14054 inodedep_print(struct inodedep *inodedep, int verbose)
14055 {
14056 	db_printf("%p fs %p st %x ino %jd inoblk %jd delta %d nlink %d"
14057 	    " saveino %p\n",
14058 	    inodedep, inodedep->id_fs, inodedep->id_state,
14059 	    (intmax_t)inodedep->id_ino,
14060 	    (intmax_t)fsbtodb(inodedep->id_fs,
14061 	    ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14062 	    inodedep->id_nlinkdelta, inodedep->id_savednlink,
14063 	    inodedep->id_savedino1);
14064 
14065 	if (verbose == 0)
14066 		return;
14067 
14068 	db_printf("\tpendinghd %p, bufwait %p, inowait %p, inoreflst %p, "
14069 	    "mkdiradd %p\n",
14070 	    LIST_FIRST(&inodedep->id_pendinghd),
14071 	    LIST_FIRST(&inodedep->id_bufwait),
14072 	    LIST_FIRST(&inodedep->id_inowait),
14073 	    TAILQ_FIRST(&inodedep->id_inoreflst),
14074 	    inodedep->id_mkdiradd);
14075 	db_printf("\tinoupdt %p, newinoupdt %p, extupdt %p, newextupdt %p\n",
14076 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14077 	    TAILQ_FIRST(&inodedep->id_newinoupdt),
14078 	    TAILQ_FIRST(&inodedep->id_extupdt),
14079 	    TAILQ_FIRST(&inodedep->id_newextupdt));
14080 }
14081 
14082 DB_SHOW_COMMAND(inodedep, db_show_inodedep)
14083 {
14084 
14085 	if (have_addr == 0) {
14086 		db_printf("Address required\n");
14087 		return;
14088 	}
14089 	inodedep_print((struct inodedep*)addr, 1);
14090 }
14091 
14092 DB_SHOW_COMMAND(inodedeps, db_show_inodedeps)
14093 {
14094 	struct inodedep_hashhead *inodedephd;
14095 	struct inodedep *inodedep;
14096 	struct ufsmount *ump;
14097 	int cnt;
14098 
14099 	if (have_addr == 0) {
14100 		db_printf("Address required\n");
14101 		return;
14102 	}
14103 	ump = (struct ufsmount *)addr;
14104 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
14105 		inodedephd = &ump->inodedep_hashtbl[cnt];
14106 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
14107 			inodedep_print(inodedep, 0);
14108 		}
14109 	}
14110 }
14111 
14112 DB_SHOW_COMMAND(worklist, db_show_worklist)
14113 {
14114 	struct worklist *wk;
14115 
14116 	if (have_addr == 0) {
14117 		db_printf("Address required\n");
14118 		return;
14119 	}
14120 	wk = (struct worklist *)addr;
14121 	printf("worklist: %p type %s state 0x%X\n",
14122 	    wk, TYPENAME(wk->wk_type), wk->wk_state);
14123 }
14124 
14125 DB_SHOW_COMMAND(workhead, db_show_workhead)
14126 {
14127 	struct workhead *wkhd;
14128 	struct worklist *wk;
14129 	int i;
14130 
14131 	if (have_addr == 0) {
14132 		db_printf("Address required\n");
14133 		return;
14134 	}
14135 	wkhd = (struct workhead *)addr;
14136 	wk = LIST_FIRST(wkhd);
14137 	for (i = 0; i < 100 && wk != NULL; i++, wk = LIST_NEXT(wk, wk_list))
14138 		db_printf("worklist: %p type %s state 0x%X",
14139 		    wk, TYPENAME(wk->wk_type), wk->wk_state);
14140 	if (i == 100)
14141 		db_printf("workhead overflow");
14142 	printf("\n");
14143 }
14144 
14145 
14146 DB_SHOW_COMMAND(mkdirs, db_show_mkdirs)
14147 {
14148 	struct mkdirlist *mkdirlisthd;
14149 	struct jaddref *jaddref;
14150 	struct diradd *diradd;
14151 	struct mkdir *mkdir;
14152 
14153 	if (have_addr == 0) {
14154 		db_printf("Address required\n");
14155 		return;
14156 	}
14157 	mkdirlisthd = (struct mkdirlist *)addr;
14158 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
14159 		diradd = mkdir->md_diradd;
14160 		db_printf("mkdir: %p state 0x%X dap %p state 0x%X",
14161 		    mkdir, mkdir->md_state, diradd, diradd->da_state);
14162 		if ((jaddref = mkdir->md_jaddref) != NULL)
14163 			db_printf(" jaddref %p jaddref state 0x%X",
14164 			    jaddref, jaddref->ja_state);
14165 		db_printf("\n");
14166 	}
14167 }
14168 
14169 /* exported to ffs_vfsops.c */
14170 extern void db_print_ffs(struct ufsmount *ump);
14171 void
14172 db_print_ffs(struct ufsmount *ump)
14173 {
14174 	db_printf("mp %p %s devvp %p fs %p su_wl %d su_deps %d su_req %d\n",
14175 	    ump->um_mountp, ump->um_mountp->mnt_stat.f_mntonname,
14176 	    ump->um_devvp, ump->um_fs, ump->softdep_on_worklist,
14177 	    ump->softdep_deps, ump->softdep_req);
14178 }
14179 
14180 #endif /* DDB */
14181 
14182 #endif /* SOFTUPDATES */
14183