xref: /freebsd/sys/ufs/ffs/ffs_softdep.c (revision c66ec88fed842fbaad62c30d510644ceb7bd2d71)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright 1998, 2000 Marshall Kirk McKusick.
5  * Copyright 2009, 2010 Jeffrey W. Roberson <jeff@FreeBSD.org>
6  * All rights reserved.
7  *
8  * The soft updates code is derived from the appendix of a University
9  * of Michigan technical report (Gregory R. Ganger and Yale N. Patt,
10  * "Soft Updates: A Solution to the Metadata Update Problem in File
11  * Systems", CSE-TR-254-95, August 1995).
12  *
13  * Further information about soft updates can be obtained from:
14  *
15  *	Marshall Kirk McKusick		http://www.mckusick.com/softdep/
16  *	1614 Oxford Street		mckusick@mckusick.com
17  *	Berkeley, CA 94709-1608		+1-510-843-9542
18  *	USA
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  *
24  * 1. Redistributions of source code must retain the above copyright
25  *    notice, this list of conditions and the following disclaimer.
26  * 2. Redistributions in binary form must reproduce the above copyright
27  *    notice, this list of conditions and the following disclaimer in the
28  *    documentation and/or other materials provided with the distribution.
29  *
30  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
31  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33  * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY DIRECT, INDIRECT,
34  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
35  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
36  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
37  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
38  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
39  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  *	from: @(#)ffs_softdep.c	9.59 (McKusick) 6/21/00
42  */
43 
44 #include <sys/cdefs.h>
45 __FBSDID("$FreeBSD$");
46 
47 #include "opt_ffs.h"
48 #include "opt_quota.h"
49 #include "opt_ddb.h"
50 
51 #include <sys/param.h>
52 #include <sys/kernel.h>
53 #include <sys/systm.h>
54 #include <sys/bio.h>
55 #include <sys/buf.h>
56 #include <sys/kdb.h>
57 #include <sys/kthread.h>
58 #include <sys/ktr.h>
59 #include <sys/limits.h>
60 #include <sys/lock.h>
61 #include <sys/malloc.h>
62 #include <sys/mount.h>
63 #include <sys/mutex.h>
64 #include <sys/namei.h>
65 #include <sys/priv.h>
66 #include <sys/proc.h>
67 #include <sys/racct.h>
68 #include <sys/rwlock.h>
69 #include <sys/stat.h>
70 #include <sys/sysctl.h>
71 #include <sys/syslog.h>
72 #include <sys/vnode.h>
73 #include <sys/conf.h>
74 
75 #include <ufs/ufs/dir.h>
76 #include <ufs/ufs/extattr.h>
77 #include <ufs/ufs/quota.h>
78 #include <ufs/ufs/inode.h>
79 #include <ufs/ufs/ufsmount.h>
80 #include <ufs/ffs/fs.h>
81 #include <ufs/ffs/softdep.h>
82 #include <ufs/ffs/ffs_extern.h>
83 #include <ufs/ufs/ufs_extern.h>
84 
85 #include <vm/vm.h>
86 #include <vm/vm_extern.h>
87 #include <vm/vm_object.h>
88 
89 #include <geom/geom.h>
90 #include <geom/geom_vfs.h>
91 
92 #include <ddb/ddb.h>
93 
94 #define	KTR_SUJ	0	/* Define to KTR_SPARE. */
95 
96 #ifndef SOFTUPDATES
97 
98 int
99 softdep_flushfiles(oldmnt, flags, td)
100 	struct mount *oldmnt;
101 	int flags;
102 	struct thread *td;
103 {
104 
105 	panic("softdep_flushfiles called");
106 }
107 
108 int
109 softdep_mount(devvp, mp, fs, cred)
110 	struct vnode *devvp;
111 	struct mount *mp;
112 	struct fs *fs;
113 	struct ucred *cred;
114 {
115 
116 	return (0);
117 }
118 
119 void
120 softdep_initialize()
121 {
122 
123 	return;
124 }
125 
126 void
127 softdep_uninitialize()
128 {
129 
130 	return;
131 }
132 
133 void
134 softdep_unmount(mp)
135 	struct mount *mp;
136 {
137 
138 	panic("softdep_unmount called");
139 }
140 
141 void
142 softdep_setup_sbupdate(ump, fs, bp)
143 	struct ufsmount *ump;
144 	struct fs *fs;
145 	struct buf *bp;
146 {
147 
148 	panic("softdep_setup_sbupdate called");
149 }
150 
151 void
152 softdep_setup_inomapdep(bp, ip, newinum, mode)
153 	struct buf *bp;
154 	struct inode *ip;
155 	ino_t newinum;
156 	int mode;
157 {
158 
159 	panic("softdep_setup_inomapdep called");
160 }
161 
162 void
163 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
164 	struct buf *bp;
165 	struct mount *mp;
166 	ufs2_daddr_t newblkno;
167 	int frags;
168 	int oldfrags;
169 {
170 
171 	panic("softdep_setup_blkmapdep called");
172 }
173 
174 void
175 softdep_setup_allocdirect(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
176 	struct inode *ip;
177 	ufs_lbn_t lbn;
178 	ufs2_daddr_t newblkno;
179 	ufs2_daddr_t oldblkno;
180 	long newsize;
181 	long oldsize;
182 	struct buf *bp;
183 {
184 
185 	panic("softdep_setup_allocdirect called");
186 }
187 
188 void
189 softdep_setup_allocext(ip, lbn, newblkno, oldblkno, newsize, oldsize, bp)
190 	struct inode *ip;
191 	ufs_lbn_t lbn;
192 	ufs2_daddr_t newblkno;
193 	ufs2_daddr_t oldblkno;
194 	long newsize;
195 	long oldsize;
196 	struct buf *bp;
197 {
198 
199 	panic("softdep_setup_allocext called");
200 }
201 
202 void
203 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
204 	struct inode *ip;
205 	ufs_lbn_t lbn;
206 	struct buf *bp;
207 	int ptrno;
208 	ufs2_daddr_t newblkno;
209 	ufs2_daddr_t oldblkno;
210 	struct buf *nbp;
211 {
212 
213 	panic("softdep_setup_allocindir_page called");
214 }
215 
216 void
217 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
218 	struct buf *nbp;
219 	struct inode *ip;
220 	struct buf *bp;
221 	int ptrno;
222 	ufs2_daddr_t newblkno;
223 {
224 
225 	panic("softdep_setup_allocindir_meta called");
226 }
227 
228 void
229 softdep_journal_freeblocks(ip, cred, length, flags)
230 	struct inode *ip;
231 	struct ucred *cred;
232 	off_t length;
233 	int flags;
234 {
235 
236 	panic("softdep_journal_freeblocks called");
237 }
238 
239 void
240 softdep_journal_fsync(ip)
241 	struct inode *ip;
242 {
243 
244 	panic("softdep_journal_fsync called");
245 }
246 
247 void
248 softdep_setup_freeblocks(ip, length, flags)
249 	struct inode *ip;
250 	off_t length;
251 	int flags;
252 {
253 
254 	panic("softdep_setup_freeblocks called");
255 }
256 
257 void
258 softdep_freefile(pvp, ino, mode)
259 		struct vnode *pvp;
260 		ino_t ino;
261 		int mode;
262 {
263 
264 	panic("softdep_freefile called");
265 }
266 
267 int
268 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
269 	struct buf *bp;
270 	struct inode *dp;
271 	off_t diroffset;
272 	ino_t newinum;
273 	struct buf *newdirbp;
274 	int isnewblk;
275 {
276 
277 	panic("softdep_setup_directory_add called");
278 }
279 
280 void
281 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
282 	struct buf *bp;
283 	struct inode *dp;
284 	caddr_t base;
285 	caddr_t oldloc;
286 	caddr_t newloc;
287 	int entrysize;
288 {
289 
290 	panic("softdep_change_directoryentry_offset called");
291 }
292 
293 void
294 softdep_setup_remove(bp, dp, ip, isrmdir)
295 	struct buf *bp;
296 	struct inode *dp;
297 	struct inode *ip;
298 	int isrmdir;
299 {
300 
301 	panic("softdep_setup_remove called");
302 }
303 
304 void
305 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
306 	struct buf *bp;
307 	struct inode *dp;
308 	struct inode *ip;
309 	ino_t newinum;
310 	int isrmdir;
311 {
312 
313 	panic("softdep_setup_directory_change called");
314 }
315 
316 void
317 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
318 	struct mount *mp;
319 	struct buf *bp;
320 	ufs2_daddr_t blkno;
321 	int frags;
322 	struct workhead *wkhd;
323 {
324 
325 	panic("%s called", __FUNCTION__);
326 }
327 
328 void
329 softdep_setup_inofree(mp, bp, ino, wkhd)
330 	struct mount *mp;
331 	struct buf *bp;
332 	ino_t ino;
333 	struct workhead *wkhd;
334 {
335 
336 	panic("%s called", __FUNCTION__);
337 }
338 
339 void
340 softdep_setup_unlink(dp, ip)
341 	struct inode *dp;
342 	struct inode *ip;
343 {
344 
345 	panic("%s called", __FUNCTION__);
346 }
347 
348 void
349 softdep_setup_link(dp, ip)
350 	struct inode *dp;
351 	struct inode *ip;
352 {
353 
354 	panic("%s called", __FUNCTION__);
355 }
356 
357 void
358 softdep_revert_link(dp, ip)
359 	struct inode *dp;
360 	struct inode *ip;
361 {
362 
363 	panic("%s called", __FUNCTION__);
364 }
365 
366 void
367 softdep_setup_rmdir(dp, ip)
368 	struct inode *dp;
369 	struct inode *ip;
370 {
371 
372 	panic("%s called", __FUNCTION__);
373 }
374 
375 void
376 softdep_revert_rmdir(dp, ip)
377 	struct inode *dp;
378 	struct inode *ip;
379 {
380 
381 	panic("%s called", __FUNCTION__);
382 }
383 
384 void
385 softdep_setup_create(dp, ip)
386 	struct inode *dp;
387 	struct inode *ip;
388 {
389 
390 	panic("%s called", __FUNCTION__);
391 }
392 
393 void
394 softdep_revert_create(dp, ip)
395 	struct inode *dp;
396 	struct inode *ip;
397 {
398 
399 	panic("%s called", __FUNCTION__);
400 }
401 
402 void
403 softdep_setup_mkdir(dp, ip)
404 	struct inode *dp;
405 	struct inode *ip;
406 {
407 
408 	panic("%s called", __FUNCTION__);
409 }
410 
411 void
412 softdep_revert_mkdir(dp, ip)
413 	struct inode *dp;
414 	struct inode *ip;
415 {
416 
417 	panic("%s called", __FUNCTION__);
418 }
419 
420 void
421 softdep_setup_dotdot_link(dp, ip)
422 	struct inode *dp;
423 	struct inode *ip;
424 {
425 
426 	panic("%s called", __FUNCTION__);
427 }
428 
429 int
430 softdep_prealloc(vp, waitok)
431 	struct vnode *vp;
432 	int waitok;
433 {
434 
435 	panic("%s called", __FUNCTION__);
436 }
437 
438 int
439 softdep_journal_lookup(mp, vpp)
440 	struct mount *mp;
441 	struct vnode **vpp;
442 {
443 
444 	return (ENOENT);
445 }
446 
447 void
448 softdep_change_linkcnt(ip)
449 	struct inode *ip;
450 {
451 
452 	panic("softdep_change_linkcnt called");
453 }
454 
455 void
456 softdep_load_inodeblock(ip)
457 	struct inode *ip;
458 {
459 
460 	panic("softdep_load_inodeblock called");
461 }
462 
463 void
464 softdep_update_inodeblock(ip, bp, waitfor)
465 	struct inode *ip;
466 	struct buf *bp;
467 	int waitfor;
468 {
469 
470 	panic("softdep_update_inodeblock called");
471 }
472 
473 int
474 softdep_fsync(vp)
475 	struct vnode *vp;	/* the "in_core" copy of the inode */
476 {
477 
478 	return (0);
479 }
480 
481 void
482 softdep_fsync_mountdev(vp)
483 	struct vnode *vp;
484 {
485 
486 	return;
487 }
488 
489 int
490 softdep_flushworklist(oldmnt, countp, td)
491 	struct mount *oldmnt;
492 	int *countp;
493 	struct thread *td;
494 {
495 
496 	*countp = 0;
497 	return (0);
498 }
499 
500 int
501 softdep_sync_metadata(struct vnode *vp)
502 {
503 
504 	panic("softdep_sync_metadata called");
505 }
506 
507 int
508 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
509 {
510 
511 	panic("softdep_sync_buf called");
512 }
513 
514 int
515 softdep_slowdown(vp)
516 	struct vnode *vp;
517 {
518 
519 	panic("softdep_slowdown called");
520 }
521 
522 int
523 softdep_request_cleanup(fs, vp, cred, resource)
524 	struct fs *fs;
525 	struct vnode *vp;
526 	struct ucred *cred;
527 	int resource;
528 {
529 
530 	return (0);
531 }
532 
533 int
534 softdep_check_suspend(struct mount *mp,
535 		      struct vnode *devvp,
536 		      int softdep_depcnt,
537 		      int softdep_accdepcnt,
538 		      int secondary_writes,
539 		      int secondary_accwrites)
540 {
541 	struct bufobj *bo;
542 	int error;
543 
544 	(void) softdep_depcnt,
545 	(void) softdep_accdepcnt;
546 
547 	bo = &devvp->v_bufobj;
548 	ASSERT_BO_WLOCKED(bo);
549 
550 	MNT_ILOCK(mp);
551 	while (mp->mnt_secondary_writes != 0) {
552 		BO_UNLOCK(bo);
553 		msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
554 		    (PUSER - 1) | PDROP, "secwr", 0);
555 		BO_LOCK(bo);
556 		MNT_ILOCK(mp);
557 	}
558 
559 	/*
560 	 * Reasons for needing more work before suspend:
561 	 * - Dirty buffers on devvp.
562 	 * - Secondary writes occurred after start of vnode sync loop
563 	 */
564 	error = 0;
565 	if (bo->bo_numoutput > 0 ||
566 	    bo->bo_dirty.bv_cnt > 0 ||
567 	    secondary_writes != 0 ||
568 	    mp->mnt_secondary_writes != 0 ||
569 	    secondary_accwrites != mp->mnt_secondary_accwrites)
570 		error = EAGAIN;
571 	BO_UNLOCK(bo);
572 	return (error);
573 }
574 
575 void
576 softdep_get_depcounts(struct mount *mp,
577 		      int *softdepactivep,
578 		      int *softdepactiveaccp)
579 {
580 	(void) mp;
581 	*softdepactivep = 0;
582 	*softdepactiveaccp = 0;
583 }
584 
585 void
586 softdep_buf_append(bp, wkhd)
587 	struct buf *bp;
588 	struct workhead *wkhd;
589 {
590 
591 	panic("softdep_buf_appendwork called");
592 }
593 
594 void
595 softdep_inode_append(ip, cred, wkhd)
596 	struct inode *ip;
597 	struct ucred *cred;
598 	struct workhead *wkhd;
599 {
600 
601 	panic("softdep_inode_appendwork called");
602 }
603 
604 void
605 softdep_freework(wkhd)
606 	struct workhead *wkhd;
607 {
608 
609 	panic("softdep_freework called");
610 }
611 
612 int
613 softdep_prerename(fdvp, fvp, tdvp, tvp)
614 	struct vnode *fdvp;
615 	struct vnode *fvp;
616 	struct vnode *tdvp;
617 	struct vnode *tvp;
618 {
619 
620 	panic("softdep_prerename called");
621 }
622 
623 int
624 softdep_prelink(dvp, vp, will_direnter)
625 	struct vnode *dvp;
626 	struct vnode *vp;
627 	int will_direnter;
628 {
629 
630 	panic("softdep_prelink called");
631 }
632 
633 #else
634 
635 FEATURE(softupdates, "FFS soft-updates support");
636 
637 static SYSCTL_NODE(_debug, OID_AUTO, softdep, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
638     "soft updates stats");
639 static SYSCTL_NODE(_debug_softdep, OID_AUTO, total,
640     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
641     "total dependencies allocated");
642 static SYSCTL_NODE(_debug_softdep, OID_AUTO, highuse,
643     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
644     "high use dependencies allocated");
645 static SYSCTL_NODE(_debug_softdep, OID_AUTO, current,
646     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
647     "current dependencies allocated");
648 static SYSCTL_NODE(_debug_softdep, OID_AUTO, write,
649     CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
650     "current dependencies written");
651 
652 unsigned long dep_current[D_LAST + 1];
653 unsigned long dep_highuse[D_LAST + 1];
654 unsigned long dep_total[D_LAST + 1];
655 unsigned long dep_write[D_LAST + 1];
656 
657 #define	SOFTDEP_TYPE(type, str, long)					\
658     static MALLOC_DEFINE(M_ ## type, #str, long);			\
659     SYSCTL_ULONG(_debug_softdep_total, OID_AUTO, str, CTLFLAG_RD,	\
660 	&dep_total[D_ ## type], 0, "");					\
661     SYSCTL_ULONG(_debug_softdep_current, OID_AUTO, str, CTLFLAG_RD, 	\
662 	&dep_current[D_ ## type], 0, "");				\
663     SYSCTL_ULONG(_debug_softdep_highuse, OID_AUTO, str, CTLFLAG_RD, 	\
664 	&dep_highuse[D_ ## type], 0, "");				\
665     SYSCTL_ULONG(_debug_softdep_write, OID_AUTO, str, CTLFLAG_RD, 	\
666 	&dep_write[D_ ## type], 0, "");
667 
668 SOFTDEP_TYPE(PAGEDEP, pagedep, "File page dependencies");
669 SOFTDEP_TYPE(INODEDEP, inodedep, "Inode dependencies");
670 SOFTDEP_TYPE(BMSAFEMAP, bmsafemap,
671     "Block or frag allocated from cyl group map");
672 SOFTDEP_TYPE(NEWBLK, newblk, "New block or frag allocation dependency");
673 SOFTDEP_TYPE(ALLOCDIRECT, allocdirect, "Block or frag dependency for an inode");
674 SOFTDEP_TYPE(INDIRDEP, indirdep, "Indirect block dependencies");
675 SOFTDEP_TYPE(ALLOCINDIR, allocindir, "Block dependency for an indirect block");
676 SOFTDEP_TYPE(FREEFRAG, freefrag, "Previously used frag for an inode");
677 SOFTDEP_TYPE(FREEBLKS, freeblks, "Blocks freed from an inode");
678 SOFTDEP_TYPE(FREEFILE, freefile, "Inode deallocated");
679 SOFTDEP_TYPE(DIRADD, diradd, "New directory entry");
680 SOFTDEP_TYPE(MKDIR, mkdir, "New directory");
681 SOFTDEP_TYPE(DIRREM, dirrem, "Directory entry deleted");
682 SOFTDEP_TYPE(NEWDIRBLK, newdirblk, "Unclaimed new directory block");
683 SOFTDEP_TYPE(FREEWORK, freework, "free an inode block");
684 SOFTDEP_TYPE(FREEDEP, freedep, "track a block free");
685 SOFTDEP_TYPE(JADDREF, jaddref, "Journal inode ref add");
686 SOFTDEP_TYPE(JREMREF, jremref, "Journal inode ref remove");
687 SOFTDEP_TYPE(JMVREF, jmvref, "Journal inode ref move");
688 SOFTDEP_TYPE(JNEWBLK, jnewblk, "Journal new block");
689 SOFTDEP_TYPE(JFREEBLK, jfreeblk, "Journal free block");
690 SOFTDEP_TYPE(JFREEFRAG, jfreefrag, "Journal free frag");
691 SOFTDEP_TYPE(JSEG, jseg, "Journal segment");
692 SOFTDEP_TYPE(JSEGDEP, jsegdep, "Journal segment complete");
693 SOFTDEP_TYPE(SBDEP, sbdep, "Superblock write dependency");
694 SOFTDEP_TYPE(JTRUNC, jtrunc, "Journal inode truncation");
695 SOFTDEP_TYPE(JFSYNC, jfsync, "Journal fsync complete");
696 
697 static MALLOC_DEFINE(M_SENTINEL, "sentinel", "Worklist sentinel");
698 
699 static MALLOC_DEFINE(M_SAVEDINO, "savedino", "Saved inodes");
700 static MALLOC_DEFINE(M_JBLOCKS, "jblocks", "Journal block locations");
701 static MALLOC_DEFINE(M_MOUNTDATA, "softdep", "Softdep per-mount data");
702 
703 #define M_SOFTDEP_FLAGS	(M_WAITOK)
704 
705 /*
706  * translate from workitem type to memory type
707  * MUST match the defines above, such that memtype[D_XXX] == M_XXX
708  */
709 static struct malloc_type *memtype[] = {
710 	NULL,
711 	M_PAGEDEP,
712 	M_INODEDEP,
713 	M_BMSAFEMAP,
714 	M_NEWBLK,
715 	M_ALLOCDIRECT,
716 	M_INDIRDEP,
717 	M_ALLOCINDIR,
718 	M_FREEFRAG,
719 	M_FREEBLKS,
720 	M_FREEFILE,
721 	M_DIRADD,
722 	M_MKDIR,
723 	M_DIRREM,
724 	M_NEWDIRBLK,
725 	M_FREEWORK,
726 	M_FREEDEP,
727 	M_JADDREF,
728 	M_JREMREF,
729 	M_JMVREF,
730 	M_JNEWBLK,
731 	M_JFREEBLK,
732 	M_JFREEFRAG,
733 	M_JSEG,
734 	M_JSEGDEP,
735 	M_SBDEP,
736 	M_JTRUNC,
737 	M_JFSYNC,
738 	M_SENTINEL
739 };
740 
741 #define DtoM(type) (memtype[type])
742 
743 /*
744  * Names of malloc types.
745  */
746 #define TYPENAME(type)  \
747 	((unsigned)(type) <= D_LAST && (unsigned)(type) >= D_FIRST ? \
748 	memtype[type]->ks_shortdesc : "???")
749 /*
750  * End system adaptation definitions.
751  */
752 
753 #define	DOTDOT_OFFSET	offsetof(struct dirtemplate, dotdot_ino)
754 #define	DOT_OFFSET	offsetof(struct dirtemplate, dot_ino)
755 
756 /*
757  * Internal function prototypes.
758  */
759 static	void check_clear_deps(struct mount *);
760 static	void softdep_error(char *, int);
761 static	int softdep_prerename_vnode(struct ufsmount *, struct vnode *);
762 static	int softdep_process_worklist(struct mount *, int);
763 static	int softdep_waitidle(struct mount *, int);
764 static	void drain_output(struct vnode *);
765 static	struct buf *getdirtybuf(struct buf *, struct rwlock *, int);
766 static	int check_inodedep_free(struct inodedep *);
767 static	void clear_remove(struct mount *);
768 static	void clear_inodedeps(struct mount *);
769 static	void unlinked_inodedep(struct mount *, struct inodedep *);
770 static	void clear_unlinked_inodedep(struct inodedep *);
771 static	struct inodedep *first_unlinked_inodedep(struct ufsmount *);
772 static	int flush_pagedep_deps(struct vnode *, struct mount *,
773 	    struct diraddhd *, struct buf *);
774 static	int free_pagedep(struct pagedep *);
775 static	int flush_newblk_dep(struct vnode *, struct mount *, ufs_lbn_t);
776 static	int flush_inodedep_deps(struct vnode *, struct mount *, ino_t);
777 static	int flush_deplist(struct allocdirectlst *, int, int *);
778 static	int sync_cgs(struct mount *, int);
779 static	int handle_written_filepage(struct pagedep *, struct buf *, int);
780 static	int handle_written_sbdep(struct sbdep *, struct buf *);
781 static	void initiate_write_sbdep(struct sbdep *);
782 static	void diradd_inode_written(struct diradd *, struct inodedep *);
783 static	int handle_written_indirdep(struct indirdep *, struct buf *,
784 	    struct buf**, int);
785 static	int handle_written_inodeblock(struct inodedep *, struct buf *, int);
786 static	int jnewblk_rollforward(struct jnewblk *, struct fs *, struct cg *,
787 	    uint8_t *);
788 static	int handle_written_bmsafemap(struct bmsafemap *, struct buf *, int);
789 static	void handle_written_jaddref(struct jaddref *);
790 static	void handle_written_jremref(struct jremref *);
791 static	void handle_written_jseg(struct jseg *, struct buf *);
792 static	void handle_written_jnewblk(struct jnewblk *);
793 static	void handle_written_jblkdep(struct jblkdep *);
794 static	void handle_written_jfreefrag(struct jfreefrag *);
795 static	void complete_jseg(struct jseg *);
796 static	void complete_jsegs(struct jseg *);
797 static	void jseg_write(struct ufsmount *ump, struct jseg *, uint8_t *);
798 static	void jaddref_write(struct jaddref *, struct jseg *, uint8_t *);
799 static	void jremref_write(struct jremref *, struct jseg *, uint8_t *);
800 static	void jmvref_write(struct jmvref *, struct jseg *, uint8_t *);
801 static	void jtrunc_write(struct jtrunc *, struct jseg *, uint8_t *);
802 static	void jfsync_write(struct jfsync *, struct jseg *, uint8_t *data);
803 static	void jnewblk_write(struct jnewblk *, struct jseg *, uint8_t *);
804 static	void jfreeblk_write(struct jfreeblk *, struct jseg *, uint8_t *);
805 static	void jfreefrag_write(struct jfreefrag *, struct jseg *, uint8_t *);
806 static	inline void inoref_write(struct inoref *, struct jseg *,
807 	    struct jrefrec *);
808 static	void handle_allocdirect_partdone(struct allocdirect *,
809 	    struct workhead *);
810 static	struct jnewblk *cancel_newblk(struct newblk *, struct worklist *,
811 	    struct workhead *);
812 static	void indirdep_complete(struct indirdep *);
813 static	int indirblk_lookup(struct mount *, ufs2_daddr_t);
814 static	void indirblk_insert(struct freework *);
815 static	void indirblk_remove(struct freework *);
816 static	void handle_allocindir_partdone(struct allocindir *);
817 static	void initiate_write_filepage(struct pagedep *, struct buf *);
818 static	void initiate_write_indirdep(struct indirdep*, struct buf *);
819 static	void handle_written_mkdir(struct mkdir *, int);
820 static	int jnewblk_rollback(struct jnewblk *, struct fs *, struct cg *,
821 	    uint8_t *);
822 static	void initiate_write_bmsafemap(struct bmsafemap *, struct buf *);
823 static	void initiate_write_inodeblock_ufs1(struct inodedep *, struct buf *);
824 static	void initiate_write_inodeblock_ufs2(struct inodedep *, struct buf *);
825 static	void handle_workitem_freefile(struct freefile *);
826 static	int handle_workitem_remove(struct dirrem *, int);
827 static	struct dirrem *newdirrem(struct buf *, struct inode *,
828 	    struct inode *, int, struct dirrem **);
829 static	struct indirdep *indirdep_lookup(struct mount *, struct inode *,
830 	    struct buf *);
831 static	void cancel_indirdep(struct indirdep *, struct buf *,
832 	    struct freeblks *);
833 static	void free_indirdep(struct indirdep *);
834 static	void free_diradd(struct diradd *, struct workhead *);
835 static	void merge_diradd(struct inodedep *, struct diradd *);
836 static	void complete_diradd(struct diradd *);
837 static	struct diradd *diradd_lookup(struct pagedep *, int);
838 static	struct jremref *cancel_diradd_dotdot(struct inode *, struct dirrem *,
839 	    struct jremref *);
840 static	struct jremref *cancel_mkdir_dotdot(struct inode *, struct dirrem *,
841 	    struct jremref *);
842 static	void cancel_diradd(struct diradd *, struct dirrem *, struct jremref *,
843 	    struct jremref *, struct jremref *);
844 static	void dirrem_journal(struct dirrem *, struct jremref *, struct jremref *,
845 	    struct jremref *);
846 static	void cancel_allocindir(struct allocindir *, struct buf *bp,
847 	    struct freeblks *, int);
848 static	int setup_trunc_indir(struct freeblks *, struct inode *,
849 	    ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t);
850 static	void complete_trunc_indir(struct freework *);
851 static	void trunc_indirdep(struct indirdep *, struct freeblks *, struct buf *,
852 	    int);
853 static	void complete_mkdir(struct mkdir *);
854 static	void free_newdirblk(struct newdirblk *);
855 static	void free_jremref(struct jremref *);
856 static	void free_jaddref(struct jaddref *);
857 static	void free_jsegdep(struct jsegdep *);
858 static	void free_jsegs(struct jblocks *);
859 static	void rele_jseg(struct jseg *);
860 static	void free_jseg(struct jseg *, struct jblocks *);
861 static	void free_jnewblk(struct jnewblk *);
862 static	void free_jblkdep(struct jblkdep *);
863 static	void free_jfreefrag(struct jfreefrag *);
864 static	void free_freedep(struct freedep *);
865 static	void journal_jremref(struct dirrem *, struct jremref *,
866 	    struct inodedep *);
867 static	void cancel_jnewblk(struct jnewblk *, struct workhead *);
868 static	int cancel_jaddref(struct jaddref *, struct inodedep *,
869 	    struct workhead *);
870 static	void cancel_jfreefrag(struct jfreefrag *);
871 static	inline void setup_freedirect(struct freeblks *, struct inode *,
872 	    int, int);
873 static	inline void setup_freeext(struct freeblks *, struct inode *, int, int);
874 static	inline void setup_freeindir(struct freeblks *, struct inode *, int,
875 	    ufs_lbn_t, int);
876 static	inline struct freeblks *newfreeblks(struct mount *, struct inode *);
877 static	void freeblks_free(struct ufsmount *, struct freeblks *, int);
878 static	void indir_trunc(struct freework *, ufs2_daddr_t, ufs_lbn_t);
879 static	ufs2_daddr_t blkcount(struct fs *, ufs2_daddr_t, off_t);
880 static	int trunc_check_buf(struct buf *, int *, ufs_lbn_t, int, int);
881 static	void trunc_dependencies(struct inode *, struct freeblks *, ufs_lbn_t,
882 	    int, int);
883 static	void trunc_pages(struct inode *, off_t, ufs2_daddr_t, int);
884 static 	int cancel_pagedep(struct pagedep *, struct freeblks *, int);
885 static	int deallocate_dependencies(struct buf *, struct freeblks *, int);
886 static	void newblk_freefrag(struct newblk*);
887 static	void free_newblk(struct newblk *);
888 static	void cancel_allocdirect(struct allocdirectlst *,
889 	    struct allocdirect *, struct freeblks *);
890 static	int check_inode_unwritten(struct inodedep *);
891 static	int free_inodedep(struct inodedep *);
892 static	void freework_freeblock(struct freework *, u_long);
893 static	void freework_enqueue(struct freework *);
894 static	int handle_workitem_freeblocks(struct freeblks *, int);
895 static	int handle_complete_freeblocks(struct freeblks *, int);
896 static	void handle_workitem_indirblk(struct freework *);
897 static	void handle_written_freework(struct freework *);
898 static	void merge_inode_lists(struct allocdirectlst *,struct allocdirectlst *);
899 static	struct worklist *jnewblk_merge(struct worklist *, struct worklist *,
900 	    struct workhead *);
901 static	struct freefrag *setup_allocindir_phase2(struct buf *, struct inode *,
902 	    struct inodedep *, struct allocindir *, ufs_lbn_t);
903 static	struct allocindir *newallocindir(struct inode *, int, ufs2_daddr_t,
904 	    ufs2_daddr_t, ufs_lbn_t);
905 static	void handle_workitem_freefrag(struct freefrag *);
906 static	struct freefrag *newfreefrag(struct inode *, ufs2_daddr_t, long,
907 	    ufs_lbn_t, u_long);
908 static	void allocdirect_merge(struct allocdirectlst *,
909 	    struct allocdirect *, struct allocdirect *);
910 static	struct freefrag *allocindir_merge(struct allocindir *,
911 	    struct allocindir *);
912 static	int bmsafemap_find(struct bmsafemap_hashhead *, int,
913 	    struct bmsafemap **);
914 static	struct bmsafemap *bmsafemap_lookup(struct mount *, struct buf *,
915 	    int cg, struct bmsafemap *);
916 static	int newblk_find(struct newblk_hashhead *, ufs2_daddr_t, int,
917 	    struct newblk **);
918 static	int newblk_lookup(struct mount *, ufs2_daddr_t, int, struct newblk **);
919 static	int inodedep_find(struct inodedep_hashhead *, ino_t,
920 	    struct inodedep **);
921 static	int inodedep_lookup(struct mount *, ino_t, int, struct inodedep **);
922 static	int pagedep_lookup(struct mount *, struct buf *bp, ino_t, ufs_lbn_t,
923 	    int, struct pagedep **);
924 static	int pagedep_find(struct pagedep_hashhead *, ino_t, ufs_lbn_t,
925 	    struct pagedep **);
926 static	void pause_timer(void *);
927 static	int request_cleanup(struct mount *, int);
928 static	int softdep_request_cleanup_flush(struct mount *, struct ufsmount *);
929 static	void schedule_cleanup(struct mount *);
930 static void softdep_ast_cleanup_proc(struct thread *);
931 static struct ufsmount *softdep_bp_to_mp(struct buf *bp);
932 static	int process_worklist_item(struct mount *, int, int);
933 static	void process_removes(struct vnode *);
934 static	void process_truncates(struct vnode *);
935 static	void jwork_move(struct workhead *, struct workhead *);
936 static	void jwork_insert(struct workhead *, struct jsegdep *);
937 static	void add_to_worklist(struct worklist *, int);
938 static	void wake_worklist(struct worklist *);
939 static	void wait_worklist(struct worklist *, char *);
940 static	void remove_from_worklist(struct worklist *);
941 static	void softdep_flush(void *);
942 static	void softdep_flushjournal(struct mount *);
943 static	int softdep_speedup(struct ufsmount *);
944 static	void worklist_speedup(struct mount *);
945 static	int journal_mount(struct mount *, struct fs *, struct ucred *);
946 static	void journal_unmount(struct ufsmount *);
947 static	int journal_space(struct ufsmount *, int);
948 static	void journal_suspend(struct ufsmount *);
949 static	int journal_unsuspend(struct ufsmount *ump);
950 static	void add_to_journal(struct worklist *);
951 static	void remove_from_journal(struct worklist *);
952 static	bool softdep_excess_items(struct ufsmount *, int);
953 static	void softdep_process_journal(struct mount *, struct worklist *, int);
954 static	struct jremref *newjremref(struct dirrem *, struct inode *,
955 	    struct inode *ip, off_t, nlink_t);
956 static	struct jaddref *newjaddref(struct inode *, ino_t, off_t, int16_t,
957 	    uint16_t);
958 static	inline void newinoref(struct inoref *, ino_t, ino_t, off_t, nlink_t,
959 	    uint16_t);
960 static	inline struct jsegdep *inoref_jseg(struct inoref *);
961 static	struct jmvref *newjmvref(struct inode *, ino_t, off_t, off_t);
962 static	struct jfreeblk *newjfreeblk(struct freeblks *, ufs_lbn_t,
963 	    ufs2_daddr_t, int);
964 static	void adjust_newfreework(struct freeblks *, int);
965 static	struct jtrunc *newjtrunc(struct freeblks *, off_t, int);
966 static	void move_newblock_dep(struct jaddref *, struct inodedep *);
967 static	void cancel_jfreeblk(struct freeblks *, ufs2_daddr_t);
968 static	struct jfreefrag *newjfreefrag(struct freefrag *, struct inode *,
969 	    ufs2_daddr_t, long, ufs_lbn_t);
970 static	struct freework *newfreework(struct ufsmount *, struct freeblks *,
971 	    struct freework *, ufs_lbn_t, ufs2_daddr_t, int, int, int);
972 static	int jwait(struct worklist *, int);
973 static	struct inodedep *inodedep_lookup_ip(struct inode *);
974 static	int bmsafemap_backgroundwrite(struct bmsafemap *, struct buf *);
975 static	struct freefile *handle_bufwait(struct inodedep *, struct workhead *);
976 static	void handle_jwork(struct workhead *);
977 static	struct mkdir *setup_newdir(struct diradd *, ino_t, ino_t, struct buf *,
978 	    struct mkdir **);
979 static	struct jblocks *jblocks_create(void);
980 static	ufs2_daddr_t jblocks_alloc(struct jblocks *, int, int *);
981 static	void jblocks_free(struct jblocks *, struct mount *, int);
982 static	void jblocks_destroy(struct jblocks *);
983 static	void jblocks_add(struct jblocks *, ufs2_daddr_t, int);
984 
985 /*
986  * Exported softdep operations.
987  */
988 static	void softdep_disk_io_initiation(struct buf *);
989 static	void softdep_disk_write_complete(struct buf *);
990 static	void softdep_deallocate_dependencies(struct buf *);
991 static	int softdep_count_dependencies(struct buf *bp, int);
992 
993 /*
994  * Global lock over all of soft updates.
995  */
996 static struct mtx lk;
997 MTX_SYSINIT(softdep_lock, &lk, "global softdep", MTX_DEF);
998 
999 #define ACQUIRE_GBLLOCK(lk)	mtx_lock(lk)
1000 #define FREE_GBLLOCK(lk)	mtx_unlock(lk)
1001 #define GBLLOCK_OWNED(lk)	mtx_assert((lk), MA_OWNED)
1002 
1003 /*
1004  * Per-filesystem soft-updates locking.
1005  */
1006 #define LOCK_PTR(ump)		(&(ump)->um_softdep->sd_fslock)
1007 #define TRY_ACQUIRE_LOCK(ump)	rw_try_wlock(&(ump)->um_softdep->sd_fslock)
1008 #define ACQUIRE_LOCK(ump)	rw_wlock(&(ump)->um_softdep->sd_fslock)
1009 #define FREE_LOCK(ump)		rw_wunlock(&(ump)->um_softdep->sd_fslock)
1010 #define LOCK_OWNED(ump)		rw_assert(&(ump)->um_softdep->sd_fslock, \
1011 				    RA_WLOCKED)
1012 
1013 #define	BUF_AREC(bp)		lockallowrecurse(&(bp)->b_lock)
1014 #define	BUF_NOREC(bp)		lockdisablerecurse(&(bp)->b_lock)
1015 
1016 /*
1017  * Worklist queue management.
1018  * These routines require that the lock be held.
1019  */
1020 #ifndef /* NOT */ INVARIANTS
1021 #define WORKLIST_INSERT(head, item) do {	\
1022 	(item)->wk_state |= ONWORKLIST;		\
1023 	LIST_INSERT_HEAD(head, item, wk_list);	\
1024 } while (0)
1025 #define WORKLIST_REMOVE(item) do {		\
1026 	(item)->wk_state &= ~ONWORKLIST;	\
1027 	LIST_REMOVE(item, wk_list);		\
1028 } while (0)
1029 #define WORKLIST_INSERT_UNLOCKED	WORKLIST_INSERT
1030 #define WORKLIST_REMOVE_UNLOCKED	WORKLIST_REMOVE
1031 
1032 #else /* INVARIANTS */
1033 static	void worklist_insert(struct workhead *, struct worklist *, int,
1034 	const char *, int);
1035 static	void worklist_remove(struct worklist *, int, const char *, int);
1036 
1037 #define WORKLIST_INSERT(head, item) \
1038 	worklist_insert(head, item, 1, __func__, __LINE__)
1039 #define WORKLIST_INSERT_UNLOCKED(head, item)\
1040 	worklist_insert(head, item, 0, __func__, __LINE__)
1041 #define WORKLIST_REMOVE(item)\
1042 	worklist_remove(item, 1, __func__, __LINE__)
1043 #define WORKLIST_REMOVE_UNLOCKED(item)\
1044 	worklist_remove(item, 0, __func__, __LINE__)
1045 
1046 static void
1047 worklist_insert(head, item, locked, func, line)
1048 	struct workhead *head;
1049 	struct worklist *item;
1050 	int locked;
1051 	const char *func;
1052 	int line;
1053 {
1054 
1055 	if (locked)
1056 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1057 	if (item->wk_state & ONWORKLIST)
1058 		panic("worklist_insert: %p %s(0x%X) already on list, "
1059 		    "added in function %s at line %d",
1060 		    item, TYPENAME(item->wk_type), item->wk_state,
1061 		    item->wk_func, item->wk_line);
1062 	item->wk_state |= ONWORKLIST;
1063 	item->wk_func = func;
1064 	item->wk_line = line;
1065 	LIST_INSERT_HEAD(head, item, wk_list);
1066 }
1067 
1068 static void
1069 worklist_remove(item, locked, func, line)
1070 	struct worklist *item;
1071 	int locked;
1072 	const char *func;
1073 	int line;
1074 {
1075 
1076 	if (locked)
1077 		LOCK_OWNED(VFSTOUFS(item->wk_mp));
1078 	if ((item->wk_state & ONWORKLIST) == 0)
1079 		panic("worklist_remove: %p %s(0x%X) not on list, "
1080 		    "removed in function %s at line %d",
1081 		    item, TYPENAME(item->wk_type), item->wk_state,
1082 		    item->wk_func, item->wk_line);
1083 	item->wk_state &= ~ONWORKLIST;
1084 	item->wk_func = func;
1085 	item->wk_line = line;
1086 	LIST_REMOVE(item, wk_list);
1087 }
1088 #endif /* INVARIANTS */
1089 
1090 /*
1091  * Merge two jsegdeps keeping only the oldest one as newer references
1092  * can't be discarded until after older references.
1093  */
1094 static inline struct jsegdep *
1095 jsegdep_merge(struct jsegdep *one, struct jsegdep *two)
1096 {
1097 	struct jsegdep *swp;
1098 
1099 	if (two == NULL)
1100 		return (one);
1101 
1102 	if (one->jd_seg->js_seq > two->jd_seg->js_seq) {
1103 		swp = one;
1104 		one = two;
1105 		two = swp;
1106 	}
1107 	WORKLIST_REMOVE(&two->jd_list);
1108 	free_jsegdep(two);
1109 
1110 	return (one);
1111 }
1112 
1113 /*
1114  * If two freedeps are compatible free one to reduce list size.
1115  */
1116 static inline struct freedep *
1117 freedep_merge(struct freedep *one, struct freedep *two)
1118 {
1119 	if (two == NULL)
1120 		return (one);
1121 
1122 	if (one->fd_freework == two->fd_freework) {
1123 		WORKLIST_REMOVE(&two->fd_list);
1124 		free_freedep(two);
1125 	}
1126 	return (one);
1127 }
1128 
1129 /*
1130  * Move journal work from one list to another.  Duplicate freedeps and
1131  * jsegdeps are coalesced to keep the lists as small as possible.
1132  */
1133 static void
1134 jwork_move(dst, src)
1135 	struct workhead *dst;
1136 	struct workhead *src;
1137 {
1138 	struct freedep *freedep;
1139 	struct jsegdep *jsegdep;
1140 	struct worklist *wkn;
1141 	struct worklist *wk;
1142 
1143 	KASSERT(dst != src,
1144 	    ("jwork_move: dst == src"));
1145 	freedep = NULL;
1146 	jsegdep = NULL;
1147 	LIST_FOREACH_SAFE(wk, dst, wk_list, wkn) {
1148 		if (wk->wk_type == D_JSEGDEP)
1149 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1150 		else if (wk->wk_type == D_FREEDEP)
1151 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1152 	}
1153 
1154 	while ((wk = LIST_FIRST(src)) != NULL) {
1155 		WORKLIST_REMOVE(wk);
1156 		WORKLIST_INSERT(dst, wk);
1157 		if (wk->wk_type == D_JSEGDEP) {
1158 			jsegdep = jsegdep_merge(WK_JSEGDEP(wk), jsegdep);
1159 			continue;
1160 		}
1161 		if (wk->wk_type == D_FREEDEP)
1162 			freedep = freedep_merge(WK_FREEDEP(wk), freedep);
1163 	}
1164 }
1165 
1166 static void
1167 jwork_insert(dst, jsegdep)
1168 	struct workhead *dst;
1169 	struct jsegdep *jsegdep;
1170 {
1171 	struct jsegdep *jsegdepn;
1172 	struct worklist *wk;
1173 
1174 	LIST_FOREACH(wk, dst, wk_list)
1175 		if (wk->wk_type == D_JSEGDEP)
1176 			break;
1177 	if (wk == NULL) {
1178 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1179 		return;
1180 	}
1181 	jsegdepn = WK_JSEGDEP(wk);
1182 	if (jsegdep->jd_seg->js_seq < jsegdepn->jd_seg->js_seq) {
1183 		WORKLIST_REMOVE(wk);
1184 		free_jsegdep(jsegdepn);
1185 		WORKLIST_INSERT(dst, &jsegdep->jd_list);
1186 	} else
1187 		free_jsegdep(jsegdep);
1188 }
1189 
1190 /*
1191  * Routines for tracking and managing workitems.
1192  */
1193 static	void workitem_free(struct worklist *, int);
1194 static	void workitem_alloc(struct worklist *, int, struct mount *);
1195 static	void workitem_reassign(struct worklist *, int);
1196 
1197 #define	WORKITEM_FREE(item, type) \
1198 	workitem_free((struct worklist *)(item), (type))
1199 #define	WORKITEM_REASSIGN(item, type) \
1200 	workitem_reassign((struct worklist *)(item), (type))
1201 
1202 static void
1203 workitem_free(item, type)
1204 	struct worklist *item;
1205 	int type;
1206 {
1207 	struct ufsmount *ump;
1208 
1209 #ifdef INVARIANTS
1210 	if (item->wk_state & ONWORKLIST)
1211 		panic("workitem_free: %s(0x%X) still on list, "
1212 		    "added in function %s at line %d",
1213 		    TYPENAME(item->wk_type), item->wk_state,
1214 		    item->wk_func, item->wk_line);
1215 	if (item->wk_type != type && type != D_NEWBLK)
1216 		panic("workitem_free: type mismatch %s != %s",
1217 		    TYPENAME(item->wk_type), TYPENAME(type));
1218 #endif
1219 	if (item->wk_state & IOWAITING)
1220 		wakeup(item);
1221 	ump = VFSTOUFS(item->wk_mp);
1222 	LOCK_OWNED(ump);
1223 	KASSERT(ump->softdep_deps > 0,
1224 	    ("workitem_free: %s: softdep_deps going negative",
1225 	    ump->um_fs->fs_fsmnt));
1226 	if (--ump->softdep_deps == 0 && ump->softdep_req)
1227 		wakeup(&ump->softdep_deps);
1228 	KASSERT(dep_current[item->wk_type] > 0,
1229 	    ("workitem_free: %s: dep_current[%s] going negative",
1230 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1231 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1232 	    ("workitem_free: %s: softdep_curdeps[%s] going negative",
1233 	    ump->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1234 	atomic_subtract_long(&dep_current[item->wk_type], 1);
1235 	ump->softdep_curdeps[item->wk_type] -= 1;
1236 #ifdef INVARIANTS
1237 	LIST_REMOVE(item, wk_all);
1238 #endif
1239 	free(item, DtoM(type));
1240 }
1241 
1242 static void
1243 workitem_alloc(item, type, mp)
1244 	struct worklist *item;
1245 	int type;
1246 	struct mount *mp;
1247 {
1248 	struct ufsmount *ump;
1249 
1250 	item->wk_type = type;
1251 	item->wk_mp = mp;
1252 	item->wk_state = 0;
1253 
1254 	ump = VFSTOUFS(mp);
1255 	ACQUIRE_GBLLOCK(&lk);
1256 	dep_current[type]++;
1257 	if (dep_current[type] > dep_highuse[type])
1258 		dep_highuse[type] = dep_current[type];
1259 	dep_total[type]++;
1260 	FREE_GBLLOCK(&lk);
1261 	ACQUIRE_LOCK(ump);
1262 	ump->softdep_curdeps[type] += 1;
1263 	ump->softdep_deps++;
1264 	ump->softdep_accdeps++;
1265 #ifdef INVARIANTS
1266 	LIST_INSERT_HEAD(&ump->softdep_alldeps[type], item, wk_all);
1267 #endif
1268 	FREE_LOCK(ump);
1269 }
1270 
1271 static void
1272 workitem_reassign(item, newtype)
1273 	struct worklist *item;
1274 	int newtype;
1275 {
1276 	struct ufsmount *ump;
1277 
1278 	ump = VFSTOUFS(item->wk_mp);
1279 	LOCK_OWNED(ump);
1280 	KASSERT(ump->softdep_curdeps[item->wk_type] > 0,
1281 	    ("workitem_reassign: %s: softdep_curdeps[%s] going negative",
1282 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1283 	ump->softdep_curdeps[item->wk_type] -= 1;
1284 	ump->softdep_curdeps[newtype] += 1;
1285 	KASSERT(dep_current[item->wk_type] > 0,
1286 	    ("workitem_reassign: %s: dep_current[%s] going negative",
1287 	    VFSTOUFS(item->wk_mp)->um_fs->fs_fsmnt, TYPENAME(item->wk_type)));
1288 	ACQUIRE_GBLLOCK(&lk);
1289 	dep_current[newtype]++;
1290 	dep_current[item->wk_type]--;
1291 	if (dep_current[newtype] > dep_highuse[newtype])
1292 		dep_highuse[newtype] = dep_current[newtype];
1293 	dep_total[newtype]++;
1294 	FREE_GBLLOCK(&lk);
1295 	item->wk_type = newtype;
1296 }
1297 
1298 /*
1299  * Workitem queue management
1300  */
1301 static int max_softdeps;	/* maximum number of structs before slowdown */
1302 static int tickdelay = 2;	/* number of ticks to pause during slowdown */
1303 static int proc_waiting;	/* tracks whether we have a timeout posted */
1304 static int *stat_countp;	/* statistic to count in proc_waiting timeout */
1305 static struct callout softdep_callout;
1306 static int req_clear_inodedeps;	/* syncer process flush some inodedeps */
1307 static int req_clear_remove;	/* syncer process flush some freeblks */
1308 static int softdep_flushcache = 0; /* Should we do BIO_FLUSH? */
1309 
1310 /*
1311  * runtime statistics
1312  */
1313 static int stat_flush_threads;	/* number of softdep flushing threads */
1314 static int stat_worklist_push;	/* number of worklist cleanups */
1315 static int stat_blk_limit_push;	/* number of times block limit neared */
1316 static int stat_ino_limit_push;	/* number of times inode limit neared */
1317 static int stat_blk_limit_hit;	/* number of times block slowdown imposed */
1318 static int stat_ino_limit_hit;	/* number of times inode slowdown imposed */
1319 static int stat_sync_limit_hit;	/* number of synchronous slowdowns imposed */
1320 static int stat_indir_blk_ptrs;	/* bufs redirtied as indir ptrs not written */
1321 static int stat_inode_bitmap;	/* bufs redirtied as inode bitmap not written */
1322 static int stat_direct_blk_ptrs;/* bufs redirtied as direct ptrs not written */
1323 static int stat_dir_entry;	/* bufs redirtied as dir entry cannot write */
1324 static int stat_jaddref;	/* bufs redirtied as ino bitmap can not write */
1325 static int stat_jnewblk;	/* bufs redirtied as blk bitmap can not write */
1326 static int stat_journal_min;	/* Times hit journal min threshold */
1327 static int stat_journal_low;	/* Times hit journal low threshold */
1328 static int stat_journal_wait;	/* Times blocked in jwait(). */
1329 static int stat_jwait_filepage;	/* Times blocked in jwait() for filepage. */
1330 static int stat_jwait_freeblks;	/* Times blocked in jwait() for freeblks. */
1331 static int stat_jwait_inode;	/* Times blocked in jwait() for inodes. */
1332 static int stat_jwait_newblk;	/* Times blocked in jwait() for newblks. */
1333 static int stat_cleanup_high_delay; /* Maximum cleanup delay (in ticks) */
1334 static int stat_cleanup_blkrequests; /* Number of block cleanup requests */
1335 static int stat_cleanup_inorequests; /* Number of inode cleanup requests */
1336 static int stat_cleanup_retries; /* Number of cleanups that needed to flush */
1337 static int stat_cleanup_failures; /* Number of cleanup requests that failed */
1338 static int stat_emptyjblocks; /* Number of potentially empty journal blocks */
1339 
1340 SYSCTL_INT(_debug_softdep, OID_AUTO, max_softdeps, CTLFLAG_RW,
1341     &max_softdeps, 0, "");
1342 SYSCTL_INT(_debug_softdep, OID_AUTO, tickdelay, CTLFLAG_RW,
1343     &tickdelay, 0, "");
1344 SYSCTL_INT(_debug_softdep, OID_AUTO, flush_threads, CTLFLAG_RD,
1345     &stat_flush_threads, 0, "");
1346 SYSCTL_INT(_debug_softdep, OID_AUTO, worklist_push,
1347     CTLFLAG_RW | CTLFLAG_STATS, &stat_worklist_push, 0,"");
1348 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_push,
1349     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_push, 0,"");
1350 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_push,
1351     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_push, 0,"");
1352 SYSCTL_INT(_debug_softdep, OID_AUTO, blk_limit_hit,
1353     CTLFLAG_RW | CTLFLAG_STATS, &stat_blk_limit_hit, 0, "");
1354 SYSCTL_INT(_debug_softdep, OID_AUTO, ino_limit_hit,
1355     CTLFLAG_RW | CTLFLAG_STATS, &stat_ino_limit_hit, 0, "");
1356 SYSCTL_INT(_debug_softdep, OID_AUTO, sync_limit_hit,
1357     CTLFLAG_RW | CTLFLAG_STATS, &stat_sync_limit_hit, 0, "");
1358 SYSCTL_INT(_debug_softdep, OID_AUTO, indir_blk_ptrs,
1359     CTLFLAG_RW | CTLFLAG_STATS, &stat_indir_blk_ptrs, 0, "");
1360 SYSCTL_INT(_debug_softdep, OID_AUTO, inode_bitmap,
1361     CTLFLAG_RW | CTLFLAG_STATS, &stat_inode_bitmap, 0, "");
1362 SYSCTL_INT(_debug_softdep, OID_AUTO, direct_blk_ptrs,
1363     CTLFLAG_RW | CTLFLAG_STATS, &stat_direct_blk_ptrs, 0, "");
1364 SYSCTL_INT(_debug_softdep, OID_AUTO, dir_entry,
1365     CTLFLAG_RW | CTLFLAG_STATS, &stat_dir_entry, 0, "");
1366 SYSCTL_INT(_debug_softdep, OID_AUTO, jaddref_rollback,
1367     CTLFLAG_RW | CTLFLAG_STATS, &stat_jaddref, 0, "");
1368 SYSCTL_INT(_debug_softdep, OID_AUTO, jnewblk_rollback,
1369     CTLFLAG_RW | CTLFLAG_STATS, &stat_jnewblk, 0, "");
1370 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_low,
1371     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_low, 0, "");
1372 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_min,
1373     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_min, 0, "");
1374 SYSCTL_INT(_debug_softdep, OID_AUTO, journal_wait,
1375     CTLFLAG_RW | CTLFLAG_STATS, &stat_journal_wait, 0, "");
1376 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_filepage,
1377     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_filepage, 0, "");
1378 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_freeblks,
1379     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_freeblks, 0, "");
1380 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_inode,
1381     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_inode, 0, "");
1382 SYSCTL_INT(_debug_softdep, OID_AUTO, jwait_newblk,
1383     CTLFLAG_RW | CTLFLAG_STATS, &stat_jwait_newblk, 0, "");
1384 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_blkrequests,
1385     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_blkrequests, 0, "");
1386 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_inorequests,
1387     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_inorequests, 0, "");
1388 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_high_delay,
1389     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_high_delay, 0, "");
1390 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_retries,
1391     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_retries, 0, "");
1392 SYSCTL_INT(_debug_softdep, OID_AUTO, cleanup_failures,
1393     CTLFLAG_RW | CTLFLAG_STATS, &stat_cleanup_failures, 0, "");
1394 
1395 SYSCTL_INT(_debug_softdep, OID_AUTO, flushcache, CTLFLAG_RW,
1396     &softdep_flushcache, 0, "");
1397 SYSCTL_INT(_debug_softdep, OID_AUTO, emptyjblocks, CTLFLAG_RD,
1398     &stat_emptyjblocks, 0, "");
1399 
1400 SYSCTL_DECL(_vfs_ffs);
1401 
1402 /* Whether to recompute the summary at mount time */
1403 static int compute_summary_at_mount = 0;
1404 SYSCTL_INT(_vfs_ffs, OID_AUTO, compute_summary_at_mount, CTLFLAG_RW,
1405 	   &compute_summary_at_mount, 0, "Recompute summary at mount");
1406 static int print_threads = 0;
1407 SYSCTL_INT(_debug_softdep, OID_AUTO, print_threads, CTLFLAG_RW,
1408     &print_threads, 0, "Notify flusher thread start/stop");
1409 
1410 /* List of all filesystems mounted with soft updates */
1411 static TAILQ_HEAD(, mount_softdeps) softdepmounts;
1412 
1413 static void
1414 get_parent_vp_unlock_bp(struct mount *mp, struct buf *bp,
1415     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp)
1416 {
1417 	struct diradd *dap;
1418 
1419 	/*
1420 	 * Requeue unfinished dependencies before
1421 	 * unlocking buffer, which could make
1422 	 * diraddhdp invalid.
1423 	 */
1424 	ACQUIRE_LOCK(VFSTOUFS(mp));
1425 	while ((dap = LIST_FIRST(unfinishedp)) != NULL) {
1426 		LIST_REMOVE(dap, da_pdlist);
1427 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
1428 	}
1429 	FREE_LOCK(VFSTOUFS(mp));
1430 
1431 	bp->b_vflags &= ~BV_SCANNED;
1432 	BUF_NOREC(bp);
1433 	BUF_UNLOCK(bp);
1434 }
1435 
1436 /*
1437  * This function fetches inode inum on mount point mp.  We already
1438  * hold a locked vnode vp, and might have a locked buffer bp belonging
1439  * to vp.
1440 
1441  * We must not block on acquiring the new inode lock as we will get
1442  * into a lock-order reversal with the buffer lock and possibly get a
1443  * deadlock.  Thus if we cannot instantiate the requested vnode
1444  * without sleeping on its lock, we must unlock the vnode and the
1445  * buffer before doing a blocking on the vnode lock.  We return
1446  * ERELOOKUP if we have had to unlock either the vnode or the buffer so
1447  * that the caller can reassess its state.
1448  *
1449  * Top-level VFS code (for syscalls and other consumers, e.g. callers
1450  * of VOP_FSYNC() in syncer) check for ERELOOKUP and restart at safe
1451  * point.
1452  *
1453  * Since callers expect to operate on fully constructed vnode, we also
1454  * recheck v_data after relock, and return ENOENT if NULL.
1455  *
1456  * If unlocking bp, we must unroll dequeueing its unfinished
1457  * dependencies, and clear scan flag, before unlocking.  If unlocking
1458  * vp while it is under deactivation, we re-queue deactivation.
1459  */
1460 static int
1461 get_parent_vp(struct vnode *vp, struct mount *mp, ino_t inum, struct buf *bp,
1462     struct diraddhd *diraddhdp, struct diraddhd *unfinishedp,
1463     struct vnode **rvp)
1464 {
1465 	struct vnode *pvp;
1466 	int error;
1467 	bool bplocked;
1468 
1469 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked");
1470 	for (bplocked = true, pvp = NULL;;) {
1471 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE | LK_NOWAIT, &pvp,
1472 		    FFSV_FORCEINSMQ);
1473 		if (error == 0) {
1474 			/*
1475 			 * Since we could have unlocked vp, the inode
1476 			 * number could no longer indicate a
1477 			 * constructed node.  In this case, we must
1478 			 * restart the syscall.
1479 			 */
1480 			if (VTOI(pvp)->i_mode == 0 || !bplocked) {
1481 				if (bp != NULL && bplocked)
1482 					get_parent_vp_unlock_bp(mp, bp,
1483 					    diraddhdp, unfinishedp);
1484 				if (VTOI(pvp)->i_mode == 0)
1485 					vgone(pvp);
1486 				error = ERELOOKUP;
1487 				goto out2;
1488 			}
1489 			goto out1;
1490 		}
1491 		if (bp != NULL && bplocked) {
1492 			get_parent_vp_unlock_bp(mp, bp, diraddhdp, unfinishedp);
1493 			bplocked = false;
1494 		}
1495 
1496 		/*
1497 		 * Do not drop vnode lock while inactivating.  This
1498 		 * would result in leaks of the VI flags and
1499 		 * reclaiming of non-truncated vnode.  Instead,
1500 		 * re-schedule inactivation hoping that we would be
1501 		 * able to sync inode later.
1502 		 */
1503 		if ((vp->v_iflag & VI_DOINGINACT) != 0) {
1504 			VI_LOCK(vp);
1505 			vp->v_iflag |= VI_OWEINACT;
1506 			VI_UNLOCK(vp);
1507 			return (ERELOOKUP);
1508 		}
1509 
1510 		VOP_UNLOCK(vp);
1511 		error = ffs_vgetf(mp, inum, LK_EXCLUSIVE, &pvp,
1512 		    FFSV_FORCEINSMQ);
1513 		if (error != 0) {
1514 			MPASS(error != ERELOOKUP);
1515 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1516 			break;
1517 		}
1518 		if (VTOI(pvp)->i_mode == 0) {
1519 			vgone(pvp);
1520 			vput(pvp);
1521 			pvp = NULL;
1522 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1523 			error = ERELOOKUP;
1524 			break;
1525 		}
1526 		error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
1527 		if (error == 0)
1528 			break;
1529 		vput(pvp);
1530 		pvp = NULL;
1531 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1532 		if (vp->v_data == NULL) {
1533 			error = ENOENT;
1534 			break;
1535 		}
1536 	}
1537 	if (bp != NULL) {
1538 		MPASS(!bplocked);
1539 		error = ERELOOKUP;
1540 	}
1541 out2:
1542 	if (error != 0 && pvp != NULL) {
1543 		vput(pvp);
1544 		pvp = NULL;
1545 	}
1546 out1:
1547 	*rvp = pvp;
1548 	ASSERT_VOP_ELOCKED(vp, "child vnode must be locked on return");
1549 	return (error);
1550 }
1551 
1552 /*
1553  * This function cleans the worklist for a filesystem.
1554  * Each filesystem running with soft dependencies gets its own
1555  * thread to run in this function. The thread is started up in
1556  * softdep_mount and shutdown in softdep_unmount. They show up
1557  * as part of the kernel "bufdaemon" process whose process
1558  * entry is available in bufdaemonproc.
1559  */
1560 static int searchfailed;
1561 extern struct proc *bufdaemonproc;
1562 static void
1563 softdep_flush(addr)
1564 	void *addr;
1565 {
1566 	struct mount *mp;
1567 	struct thread *td;
1568 	struct ufsmount *ump;
1569 
1570 	td = curthread;
1571 	td->td_pflags |= TDP_NORUNNINGBUF;
1572 	mp = (struct mount *)addr;
1573 	ump = VFSTOUFS(mp);
1574 	atomic_add_int(&stat_flush_threads, 1);
1575 	ACQUIRE_LOCK(ump);
1576 	ump->softdep_flags &= ~FLUSH_STARTING;
1577 	wakeup(&ump->softdep_flushtd);
1578 	FREE_LOCK(ump);
1579 	if (print_threads) {
1580 		if (stat_flush_threads == 1)
1581 			printf("Running %s at pid %d\n", bufdaemonproc->p_comm,
1582 			    bufdaemonproc->p_pid);
1583 		printf("Start thread %s\n", td->td_name);
1584 	}
1585 	for (;;) {
1586 		while (softdep_process_worklist(mp, 0) > 0 ||
1587 		    (MOUNTEDSUJ(mp) &&
1588 		    VFSTOUFS(mp)->softdep_jblocks->jb_suspended))
1589 			kthread_suspend_check();
1590 		ACQUIRE_LOCK(ump);
1591 		if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1592 			msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM,
1593 			    "sdflush", hz / 2);
1594 		ump->softdep_flags &= ~FLUSH_CLEANUP;
1595 		/*
1596 		 * Check to see if we are done and need to exit.
1597 		 */
1598 		if ((ump->softdep_flags & FLUSH_EXIT) == 0) {
1599 			FREE_LOCK(ump);
1600 			continue;
1601 		}
1602 		ump->softdep_flags &= ~FLUSH_EXIT;
1603 		FREE_LOCK(ump);
1604 		wakeup(&ump->softdep_flags);
1605 		if (print_threads)
1606 			printf("Stop thread %s: searchfailed %d, did cleanups %d\n", td->td_name, searchfailed, ump->um_softdep->sd_cleanups);
1607 		atomic_subtract_int(&stat_flush_threads, 1);
1608 		kthread_exit();
1609 		panic("kthread_exit failed\n");
1610 	}
1611 }
1612 
1613 static void
1614 worklist_speedup(mp)
1615 	struct mount *mp;
1616 {
1617 	struct ufsmount *ump;
1618 
1619 	ump = VFSTOUFS(mp);
1620 	LOCK_OWNED(ump);
1621 	if ((ump->softdep_flags & (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1622 		ump->softdep_flags |= FLUSH_CLEANUP;
1623 	wakeup(&ump->softdep_flushtd);
1624 }
1625 
1626 static void
1627 softdep_send_speedup(struct ufsmount *ump, off_t shortage, u_int flags)
1628 {
1629 	struct buf *bp;
1630 
1631 	if ((ump->um_flags & UM_CANSPEEDUP) == 0)
1632 		return;
1633 
1634 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
1635 	bp->b_iocmd = BIO_SPEEDUP;
1636 	bp->b_ioflags = flags;
1637 	bp->b_bcount = omin(shortage, LONG_MAX);
1638 	g_vfs_strategy(ump->um_bo, bp);
1639 	bufwait(bp);
1640 	free(bp, M_TRIM);
1641 }
1642 
1643 static int
1644 softdep_speedup(ump)
1645 	struct ufsmount *ump;
1646 {
1647 	struct ufsmount *altump;
1648 	struct mount_softdeps *sdp;
1649 
1650 	LOCK_OWNED(ump);
1651 	worklist_speedup(ump->um_mountp);
1652 	bd_speedup();
1653 	/*
1654 	 * If we have global shortages, then we need other
1655 	 * filesystems to help with the cleanup. Here we wakeup a
1656 	 * flusher thread for a filesystem that is over its fair
1657 	 * share of resources.
1658 	 */
1659 	if (req_clear_inodedeps || req_clear_remove) {
1660 		ACQUIRE_GBLLOCK(&lk);
1661 		TAILQ_FOREACH(sdp, &softdepmounts, sd_next) {
1662 			if ((altump = sdp->sd_ump) == ump)
1663 				continue;
1664 			if (((req_clear_inodedeps &&
1665 			    altump->softdep_curdeps[D_INODEDEP] >
1666 			    max_softdeps / stat_flush_threads) ||
1667 			    (req_clear_remove &&
1668 			    altump->softdep_curdeps[D_DIRREM] >
1669 			    (max_softdeps / 2) / stat_flush_threads)) &&
1670 			    TRY_ACQUIRE_LOCK(altump))
1671 				break;
1672 		}
1673 		if (sdp == NULL) {
1674 			searchfailed++;
1675 			FREE_GBLLOCK(&lk);
1676 		} else {
1677 			/*
1678 			 * Move to the end of the list so we pick a
1679 			 * different one on out next try.
1680 			 */
1681 			TAILQ_REMOVE(&softdepmounts, sdp, sd_next);
1682 			TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
1683 			FREE_GBLLOCK(&lk);
1684 			if ((altump->softdep_flags &
1685 			    (FLUSH_CLEANUP | FLUSH_EXIT)) == 0)
1686 				altump->softdep_flags |= FLUSH_CLEANUP;
1687 			altump->um_softdep->sd_cleanups++;
1688 			wakeup(&altump->softdep_flushtd);
1689 			FREE_LOCK(altump);
1690 		}
1691 	}
1692 	return (speedup_syncer());
1693 }
1694 
1695 /*
1696  * Add an item to the end of the work queue.
1697  * This routine requires that the lock be held.
1698  * This is the only routine that adds items to the list.
1699  * The following routine is the only one that removes items
1700  * and does so in order from first to last.
1701  */
1702 
1703 #define	WK_HEAD		0x0001	/* Add to HEAD. */
1704 #define	WK_NODELAY	0x0002	/* Process immediately. */
1705 
1706 static void
1707 add_to_worklist(wk, flags)
1708 	struct worklist *wk;
1709 	int flags;
1710 {
1711 	struct ufsmount *ump;
1712 
1713 	ump = VFSTOUFS(wk->wk_mp);
1714 	LOCK_OWNED(ump);
1715 	if (wk->wk_state & ONWORKLIST)
1716 		panic("add_to_worklist: %s(0x%X) already on list",
1717 		    TYPENAME(wk->wk_type), wk->wk_state);
1718 	wk->wk_state |= ONWORKLIST;
1719 	if (ump->softdep_on_worklist == 0) {
1720 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1721 		ump->softdep_worklist_tail = wk;
1722 	} else if (flags & WK_HEAD) {
1723 		LIST_INSERT_HEAD(&ump->softdep_workitem_pending, wk, wk_list);
1724 	} else {
1725 		LIST_INSERT_AFTER(ump->softdep_worklist_tail, wk, wk_list);
1726 		ump->softdep_worklist_tail = wk;
1727 	}
1728 	ump->softdep_on_worklist += 1;
1729 	if (flags & WK_NODELAY)
1730 		worklist_speedup(wk->wk_mp);
1731 }
1732 
1733 /*
1734  * Remove the item to be processed. If we are removing the last
1735  * item on the list, we need to recalculate the tail pointer.
1736  */
1737 static void
1738 remove_from_worklist(wk)
1739 	struct worklist *wk;
1740 {
1741 	struct ufsmount *ump;
1742 
1743 	ump = VFSTOUFS(wk->wk_mp);
1744 	if (ump->softdep_worklist_tail == wk)
1745 		ump->softdep_worklist_tail =
1746 		    (struct worklist *)wk->wk_list.le_prev;
1747 	WORKLIST_REMOVE(wk);
1748 	ump->softdep_on_worklist -= 1;
1749 }
1750 
1751 static void
1752 wake_worklist(wk)
1753 	struct worklist *wk;
1754 {
1755 	if (wk->wk_state & IOWAITING) {
1756 		wk->wk_state &= ~IOWAITING;
1757 		wakeup(wk);
1758 	}
1759 }
1760 
1761 static void
1762 wait_worklist(wk, wmesg)
1763 	struct worklist *wk;
1764 	char *wmesg;
1765 {
1766 	struct ufsmount *ump;
1767 
1768 	ump = VFSTOUFS(wk->wk_mp);
1769 	wk->wk_state |= IOWAITING;
1770 	msleep(wk, LOCK_PTR(ump), PVM, wmesg, 0);
1771 }
1772 
1773 /*
1774  * Process that runs once per second to handle items in the background queue.
1775  *
1776  * Note that we ensure that everything is done in the order in which they
1777  * appear in the queue. The code below depends on this property to ensure
1778  * that blocks of a file are freed before the inode itself is freed. This
1779  * ordering ensures that no new <vfsid, inum, lbn> triples will be generated
1780  * until all the old ones have been purged from the dependency lists.
1781  */
1782 static int
1783 softdep_process_worklist(mp, full)
1784 	struct mount *mp;
1785 	int full;
1786 {
1787 	int cnt, matchcnt;
1788 	struct ufsmount *ump;
1789 	long starttime;
1790 
1791 	KASSERT(mp != NULL, ("softdep_process_worklist: NULL mp"));
1792 	if (MOUNTEDSOFTDEP(mp) == 0)
1793 		return (0);
1794 	matchcnt = 0;
1795 	ump = VFSTOUFS(mp);
1796 	ACQUIRE_LOCK(ump);
1797 	starttime = time_second;
1798 	softdep_process_journal(mp, NULL, full ? MNT_WAIT : 0);
1799 	check_clear_deps(mp);
1800 	while (ump->softdep_on_worklist > 0) {
1801 		if ((cnt = process_worklist_item(mp, 10, LK_NOWAIT)) == 0)
1802 			break;
1803 		else
1804 			matchcnt += cnt;
1805 		check_clear_deps(mp);
1806 		/*
1807 		 * We do not generally want to stop for buffer space, but if
1808 		 * we are really being a buffer hog, we will stop and wait.
1809 		 */
1810 		if (should_yield()) {
1811 			FREE_LOCK(ump);
1812 			kern_yield(PRI_USER);
1813 			bwillwrite();
1814 			ACQUIRE_LOCK(ump);
1815 		}
1816 		/*
1817 		 * Never allow processing to run for more than one
1818 		 * second. This gives the syncer thread the opportunity
1819 		 * to pause if appropriate.
1820 		 */
1821 		if (!full && starttime != time_second)
1822 			break;
1823 	}
1824 	if (full == 0)
1825 		journal_unsuspend(ump);
1826 	FREE_LOCK(ump);
1827 	return (matchcnt);
1828 }
1829 
1830 /*
1831  * Process all removes associated with a vnode if we are running out of
1832  * journal space.  Any other process which attempts to flush these will
1833  * be unable as we have the vnodes locked.
1834  */
1835 static void
1836 process_removes(vp)
1837 	struct vnode *vp;
1838 {
1839 	struct inodedep *inodedep;
1840 	struct dirrem *dirrem;
1841 	struct ufsmount *ump;
1842 	struct mount *mp;
1843 	ino_t inum;
1844 
1845 	mp = vp->v_mount;
1846 	ump = VFSTOUFS(mp);
1847 	LOCK_OWNED(ump);
1848 	inum = VTOI(vp)->i_number;
1849 	for (;;) {
1850 top:
1851 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1852 			return;
1853 		LIST_FOREACH(dirrem, &inodedep->id_dirremhd, dm_inonext) {
1854 			/*
1855 			 * If another thread is trying to lock this vnode
1856 			 * it will fail but we must wait for it to do so
1857 			 * before we can proceed.
1858 			 */
1859 			if (dirrem->dm_state & INPROGRESS) {
1860 				wait_worklist(&dirrem->dm_list, "pwrwait");
1861 				goto top;
1862 			}
1863 			if ((dirrem->dm_state & (COMPLETE | ONWORKLIST)) ==
1864 			    (COMPLETE | ONWORKLIST))
1865 				break;
1866 		}
1867 		if (dirrem == NULL)
1868 			return;
1869 		remove_from_worklist(&dirrem->dm_list);
1870 		FREE_LOCK(ump);
1871 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1872 			panic("process_removes: suspended filesystem");
1873 		handle_workitem_remove(dirrem, 0);
1874 		vn_finished_secondary_write(mp);
1875 		ACQUIRE_LOCK(ump);
1876 	}
1877 }
1878 
1879 /*
1880  * Process all truncations associated with a vnode if we are running out
1881  * of journal space.  This is called when the vnode lock is already held
1882  * and no other process can clear the truncation.  This function returns
1883  * a value greater than zero if it did any work.
1884  */
1885 static void
1886 process_truncates(vp)
1887 	struct vnode *vp;
1888 {
1889 	struct inodedep *inodedep;
1890 	struct freeblks *freeblks;
1891 	struct ufsmount *ump;
1892 	struct mount *mp;
1893 	ino_t inum;
1894 	int cgwait;
1895 
1896 	mp = vp->v_mount;
1897 	ump = VFSTOUFS(mp);
1898 	LOCK_OWNED(ump);
1899 	inum = VTOI(vp)->i_number;
1900 	for (;;) {
1901 		if (inodedep_lookup(mp, inum, 0, &inodedep) == 0)
1902 			return;
1903 		cgwait = 0;
1904 		TAILQ_FOREACH(freeblks, &inodedep->id_freeblklst, fb_next) {
1905 			/* Journal entries not yet written.  */
1906 			if (!LIST_EMPTY(&freeblks->fb_jblkdephd)) {
1907 				jwait(&LIST_FIRST(
1908 				    &freeblks->fb_jblkdephd)->jb_list,
1909 				    MNT_WAIT);
1910 				break;
1911 			}
1912 			/* Another thread is executing this item. */
1913 			if (freeblks->fb_state & INPROGRESS) {
1914 				wait_worklist(&freeblks->fb_list, "ptrwait");
1915 				break;
1916 			}
1917 			/* Freeblks is waiting on a inode write. */
1918 			if ((freeblks->fb_state & COMPLETE) == 0) {
1919 				FREE_LOCK(ump);
1920 				ffs_update(vp, 1);
1921 				ACQUIRE_LOCK(ump);
1922 				break;
1923 			}
1924 			if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST)) ==
1925 			    (ALLCOMPLETE | ONWORKLIST)) {
1926 				remove_from_worklist(&freeblks->fb_list);
1927 				freeblks->fb_state |= INPROGRESS;
1928 				FREE_LOCK(ump);
1929 				if (vn_start_secondary_write(NULL, &mp,
1930 				    V_NOWAIT))
1931 					panic("process_truncates: "
1932 					    "suspended filesystem");
1933 				handle_workitem_freeblocks(freeblks, 0);
1934 				vn_finished_secondary_write(mp);
1935 				ACQUIRE_LOCK(ump);
1936 				break;
1937 			}
1938 			if (freeblks->fb_cgwait)
1939 				cgwait++;
1940 		}
1941 		if (cgwait) {
1942 			FREE_LOCK(ump);
1943 			sync_cgs(mp, MNT_WAIT);
1944 			ffs_sync_snap(mp, MNT_WAIT);
1945 			ACQUIRE_LOCK(ump);
1946 			continue;
1947 		}
1948 		if (freeblks == NULL)
1949 			break;
1950 	}
1951 	return;
1952 }
1953 
1954 /*
1955  * Process one item on the worklist.
1956  */
1957 static int
1958 process_worklist_item(mp, target, flags)
1959 	struct mount *mp;
1960 	int target;
1961 	int flags;
1962 {
1963 	struct worklist sentinel;
1964 	struct worklist *wk;
1965 	struct ufsmount *ump;
1966 	int matchcnt;
1967 	int error;
1968 
1969 	KASSERT(mp != NULL, ("process_worklist_item: NULL mp"));
1970 	/*
1971 	 * If we are being called because of a process doing a
1972 	 * copy-on-write, then it is not safe to write as we may
1973 	 * recurse into the copy-on-write routine.
1974 	 */
1975 	if (curthread->td_pflags & TDP_COWINPROGRESS)
1976 		return (-1);
1977 	PHOLD(curproc);	/* Don't let the stack go away. */
1978 	ump = VFSTOUFS(mp);
1979 	LOCK_OWNED(ump);
1980 	matchcnt = 0;
1981 	sentinel.wk_mp = NULL;
1982 	sentinel.wk_type = D_SENTINEL;
1983 	LIST_INSERT_HEAD(&ump->softdep_workitem_pending, &sentinel, wk_list);
1984 	for (wk = LIST_NEXT(&sentinel, wk_list); wk != NULL;
1985 	    wk = LIST_NEXT(&sentinel, wk_list)) {
1986 		if (wk->wk_type == D_SENTINEL) {
1987 			LIST_REMOVE(&sentinel, wk_list);
1988 			LIST_INSERT_AFTER(wk, &sentinel, wk_list);
1989 			continue;
1990 		}
1991 		if (wk->wk_state & INPROGRESS)
1992 			panic("process_worklist_item: %p already in progress.",
1993 			    wk);
1994 		wk->wk_state |= INPROGRESS;
1995 		remove_from_worklist(wk);
1996 		FREE_LOCK(ump);
1997 		if (vn_start_secondary_write(NULL, &mp, V_NOWAIT))
1998 			panic("process_worklist_item: suspended filesystem");
1999 		switch (wk->wk_type) {
2000 		case D_DIRREM:
2001 			/* removal of a directory entry */
2002 			error = handle_workitem_remove(WK_DIRREM(wk), flags);
2003 			break;
2004 
2005 		case D_FREEBLKS:
2006 			/* releasing blocks and/or fragments from a file */
2007 			error = handle_workitem_freeblocks(WK_FREEBLKS(wk),
2008 			    flags);
2009 			break;
2010 
2011 		case D_FREEFRAG:
2012 			/* releasing a fragment when replaced as a file grows */
2013 			handle_workitem_freefrag(WK_FREEFRAG(wk));
2014 			error = 0;
2015 			break;
2016 
2017 		case D_FREEFILE:
2018 			/* releasing an inode when its link count drops to 0 */
2019 			handle_workitem_freefile(WK_FREEFILE(wk));
2020 			error = 0;
2021 			break;
2022 
2023 		default:
2024 			panic("%s_process_worklist: Unknown type %s",
2025 			    "softdep", TYPENAME(wk->wk_type));
2026 			/* NOTREACHED */
2027 		}
2028 		vn_finished_secondary_write(mp);
2029 		ACQUIRE_LOCK(ump);
2030 		if (error == 0) {
2031 			if (++matchcnt == target)
2032 				break;
2033 			continue;
2034 		}
2035 		/*
2036 		 * We have to retry the worklist item later.  Wake up any
2037 		 * waiters who may be able to complete it immediately and
2038 		 * add the item back to the head so we don't try to execute
2039 		 * it again.
2040 		 */
2041 		wk->wk_state &= ~INPROGRESS;
2042 		wake_worklist(wk);
2043 		add_to_worklist(wk, WK_HEAD);
2044 	}
2045 	/* Sentinal could've become the tail from remove_from_worklist. */
2046 	if (ump->softdep_worklist_tail == &sentinel)
2047 		ump->softdep_worklist_tail =
2048 		    (struct worklist *)sentinel.wk_list.le_prev;
2049 	LIST_REMOVE(&sentinel, wk_list);
2050 	PRELE(curproc);
2051 	return (matchcnt);
2052 }
2053 
2054 /*
2055  * Move dependencies from one buffer to another.
2056  */
2057 int
2058 softdep_move_dependencies(oldbp, newbp)
2059 	struct buf *oldbp;
2060 	struct buf *newbp;
2061 {
2062 	struct worklist *wk, *wktail;
2063 	struct ufsmount *ump;
2064 	int dirty;
2065 
2066 	if ((wk = LIST_FIRST(&oldbp->b_dep)) == NULL)
2067 		return (0);
2068 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
2069 	    ("softdep_move_dependencies called on non-softdep filesystem"));
2070 	dirty = 0;
2071 	wktail = NULL;
2072 	ump = VFSTOUFS(wk->wk_mp);
2073 	ACQUIRE_LOCK(ump);
2074 	while ((wk = LIST_FIRST(&oldbp->b_dep)) != NULL) {
2075 		LIST_REMOVE(wk, wk_list);
2076 		if (wk->wk_type == D_BMSAFEMAP &&
2077 		    bmsafemap_backgroundwrite(WK_BMSAFEMAP(wk), newbp))
2078 			dirty = 1;
2079 		if (wktail == NULL)
2080 			LIST_INSERT_HEAD(&newbp->b_dep, wk, wk_list);
2081 		else
2082 			LIST_INSERT_AFTER(wktail, wk, wk_list);
2083 		wktail = wk;
2084 	}
2085 	FREE_LOCK(ump);
2086 
2087 	return (dirty);
2088 }
2089 
2090 /*
2091  * Purge the work list of all items associated with a particular mount point.
2092  */
2093 int
2094 softdep_flushworklist(oldmnt, countp, td)
2095 	struct mount *oldmnt;
2096 	int *countp;
2097 	struct thread *td;
2098 {
2099 	struct vnode *devvp;
2100 	struct ufsmount *ump;
2101 	int count, error;
2102 
2103 	/*
2104 	 * Alternately flush the block device associated with the mount
2105 	 * point and process any dependencies that the flushing
2106 	 * creates. We continue until no more worklist dependencies
2107 	 * are found.
2108 	 */
2109 	*countp = 0;
2110 	error = 0;
2111 	ump = VFSTOUFS(oldmnt);
2112 	devvp = ump->um_devvp;
2113 	while ((count = softdep_process_worklist(oldmnt, 1)) > 0) {
2114 		*countp += count;
2115 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2116 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2117 		VOP_UNLOCK(devvp);
2118 		if (error != 0)
2119 			break;
2120 	}
2121 	return (error);
2122 }
2123 
2124 #define	SU_WAITIDLE_RETRIES	20
2125 static int
2126 softdep_waitidle(struct mount *mp, int flags __unused)
2127 {
2128 	struct ufsmount *ump;
2129 	struct vnode *devvp;
2130 	struct thread *td;
2131 	int error, i;
2132 
2133 	ump = VFSTOUFS(mp);
2134 	devvp = ump->um_devvp;
2135 	td = curthread;
2136 	error = 0;
2137 	ACQUIRE_LOCK(ump);
2138 	for (i = 0; i < SU_WAITIDLE_RETRIES && ump->softdep_deps != 0; i++) {
2139 		ump->softdep_req = 1;
2140 		KASSERT((flags & FORCECLOSE) == 0 ||
2141 		    ump->softdep_on_worklist == 0,
2142 		    ("softdep_waitidle: work added after flush"));
2143 		msleep(&ump->softdep_deps, LOCK_PTR(ump), PVM | PDROP,
2144 		    "softdeps", 10 * hz);
2145 		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
2146 		error = VOP_FSYNC(devvp, MNT_WAIT, td);
2147 		VOP_UNLOCK(devvp);
2148 		ACQUIRE_LOCK(ump);
2149 		if (error != 0)
2150 			break;
2151 	}
2152 	ump->softdep_req = 0;
2153 	if (i == SU_WAITIDLE_RETRIES && error == 0 && ump->softdep_deps != 0) {
2154 		error = EBUSY;
2155 		printf("softdep_waitidle: Failed to flush worklist for %p\n",
2156 		    mp);
2157 	}
2158 	FREE_LOCK(ump);
2159 	return (error);
2160 }
2161 
2162 /*
2163  * Flush all vnodes and worklist items associated with a specified mount point.
2164  */
2165 int
2166 softdep_flushfiles(oldmnt, flags, td)
2167 	struct mount *oldmnt;
2168 	int flags;
2169 	struct thread *td;
2170 {
2171 #ifdef QUOTA
2172 	struct ufsmount *ump;
2173 	int i;
2174 #endif
2175 	int error, early, depcount, loopcnt, retry_flush_count, retry;
2176 	int morework;
2177 
2178 	KASSERT(MOUNTEDSOFTDEP(oldmnt) != 0,
2179 	    ("softdep_flushfiles called on non-softdep filesystem"));
2180 	loopcnt = 10;
2181 	retry_flush_count = 3;
2182 retry_flush:
2183 	error = 0;
2184 
2185 	/*
2186 	 * Alternately flush the vnodes associated with the mount
2187 	 * point and process any dependencies that the flushing
2188 	 * creates. In theory, this loop can happen at most twice,
2189 	 * but we give it a few extra just to be sure.
2190 	 */
2191 	for (; loopcnt > 0; loopcnt--) {
2192 		/*
2193 		 * Do another flush in case any vnodes were brought in
2194 		 * as part of the cleanup operations.
2195 		 */
2196 		early = retry_flush_count == 1 || (oldmnt->mnt_kern_flag &
2197 		    MNTK_UNMOUNT) == 0 ? 0 : EARLYFLUSH;
2198 		if ((error = ffs_flushfiles(oldmnt, flags | early, td)) != 0)
2199 			break;
2200 		if ((error = softdep_flushworklist(oldmnt, &depcount, td)) != 0 ||
2201 		    depcount == 0)
2202 			break;
2203 	}
2204 	/*
2205 	 * If we are unmounting then it is an error to fail. If we
2206 	 * are simply trying to downgrade to read-only, then filesystem
2207 	 * activity can keep us busy forever, so we just fail with EBUSY.
2208 	 */
2209 	if (loopcnt == 0) {
2210 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT)
2211 			panic("softdep_flushfiles: looping");
2212 		error = EBUSY;
2213 	}
2214 	if (!error)
2215 		error = softdep_waitidle(oldmnt, flags);
2216 	if (!error) {
2217 		if (oldmnt->mnt_kern_flag & MNTK_UNMOUNT) {
2218 			retry = 0;
2219 			MNT_ILOCK(oldmnt);
2220 			morework = oldmnt->mnt_nvnodelistsize > 0;
2221 #ifdef QUOTA
2222 			ump = VFSTOUFS(oldmnt);
2223 			UFS_LOCK(ump);
2224 			for (i = 0; i < MAXQUOTAS; i++) {
2225 				if (ump->um_quotas[i] != NULLVP)
2226 					morework = 1;
2227 			}
2228 			UFS_UNLOCK(ump);
2229 #endif
2230 			if (morework) {
2231 				if (--retry_flush_count > 0) {
2232 					retry = 1;
2233 					loopcnt = 3;
2234 				} else
2235 					error = EBUSY;
2236 			}
2237 			MNT_IUNLOCK(oldmnt);
2238 			if (retry)
2239 				goto retry_flush;
2240 		}
2241 	}
2242 	return (error);
2243 }
2244 
2245 /*
2246  * Structure hashing.
2247  *
2248  * There are four types of structures that can be looked up:
2249  *	1) pagedep structures identified by mount point, inode number,
2250  *	   and logical block.
2251  *	2) inodedep structures identified by mount point and inode number.
2252  *	3) newblk structures identified by mount point and
2253  *	   physical block number.
2254  *	4) bmsafemap structures identified by mount point and
2255  *	   cylinder group number.
2256  *
2257  * The "pagedep" and "inodedep" dependency structures are hashed
2258  * separately from the file blocks and inodes to which they correspond.
2259  * This separation helps when the in-memory copy of an inode or
2260  * file block must be replaced. It also obviates the need to access
2261  * an inode or file page when simply updating (or de-allocating)
2262  * dependency structures. Lookup of newblk structures is needed to
2263  * find newly allocated blocks when trying to associate them with
2264  * their allocdirect or allocindir structure.
2265  *
2266  * The lookup routines optionally create and hash a new instance when
2267  * an existing entry is not found. The bmsafemap lookup routine always
2268  * allocates a new structure if an existing one is not found.
2269  */
2270 #define DEPALLOC	0x0001	/* allocate structure if lookup fails */
2271 
2272 /*
2273  * Structures and routines associated with pagedep caching.
2274  */
2275 #define	PAGEDEP_HASH(ump, inum, lbn) \
2276 	(&(ump)->pagedep_hashtbl[((inum) + (lbn)) & (ump)->pagedep_hash_size])
2277 
2278 static int
2279 pagedep_find(pagedephd, ino, lbn, pagedeppp)
2280 	struct pagedep_hashhead *pagedephd;
2281 	ino_t ino;
2282 	ufs_lbn_t lbn;
2283 	struct pagedep **pagedeppp;
2284 {
2285 	struct pagedep *pagedep;
2286 
2287 	LIST_FOREACH(pagedep, pagedephd, pd_hash) {
2288 		if (ino == pagedep->pd_ino && lbn == pagedep->pd_lbn) {
2289 			*pagedeppp = pagedep;
2290 			return (1);
2291 		}
2292 	}
2293 	*pagedeppp = NULL;
2294 	return (0);
2295 }
2296 /*
2297  * Look up a pagedep. Return 1 if found, 0 otherwise.
2298  * If not found, allocate if DEPALLOC flag is passed.
2299  * Found or allocated entry is returned in pagedeppp.
2300  */
2301 static int
2302 pagedep_lookup(mp, bp, ino, lbn, flags, pagedeppp)
2303 	struct mount *mp;
2304 	struct buf *bp;
2305 	ino_t ino;
2306 	ufs_lbn_t lbn;
2307 	int flags;
2308 	struct pagedep **pagedeppp;
2309 {
2310 	struct pagedep *pagedep;
2311 	struct pagedep_hashhead *pagedephd;
2312 	struct worklist *wk;
2313 	struct ufsmount *ump;
2314 	int ret;
2315 	int i;
2316 
2317 	ump = VFSTOUFS(mp);
2318 	LOCK_OWNED(ump);
2319 	if (bp) {
2320 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
2321 			if (wk->wk_type == D_PAGEDEP) {
2322 				*pagedeppp = WK_PAGEDEP(wk);
2323 				return (1);
2324 			}
2325 		}
2326 	}
2327 	pagedephd = PAGEDEP_HASH(ump, ino, lbn);
2328 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2329 	if (ret) {
2330 		if (((*pagedeppp)->pd_state & ONWORKLIST) == 0 && bp)
2331 			WORKLIST_INSERT(&bp->b_dep, &(*pagedeppp)->pd_list);
2332 		return (1);
2333 	}
2334 	if ((flags & DEPALLOC) == 0)
2335 		return (0);
2336 	FREE_LOCK(ump);
2337 	pagedep = malloc(sizeof(struct pagedep),
2338 	    M_PAGEDEP, M_SOFTDEP_FLAGS|M_ZERO);
2339 	workitem_alloc(&pagedep->pd_list, D_PAGEDEP, mp);
2340 	ACQUIRE_LOCK(ump);
2341 	ret = pagedep_find(pagedephd, ino, lbn, pagedeppp);
2342 	if (*pagedeppp) {
2343 		/*
2344 		 * This should never happen since we only create pagedeps
2345 		 * with the vnode lock held.  Could be an assert.
2346 		 */
2347 		WORKITEM_FREE(pagedep, D_PAGEDEP);
2348 		return (ret);
2349 	}
2350 	pagedep->pd_ino = ino;
2351 	pagedep->pd_lbn = lbn;
2352 	LIST_INIT(&pagedep->pd_dirremhd);
2353 	LIST_INIT(&pagedep->pd_pendinghd);
2354 	for (i = 0; i < DAHASHSZ; i++)
2355 		LIST_INIT(&pagedep->pd_diraddhd[i]);
2356 	LIST_INSERT_HEAD(pagedephd, pagedep, pd_hash);
2357 	WORKLIST_INSERT(&bp->b_dep, &pagedep->pd_list);
2358 	*pagedeppp = pagedep;
2359 	return (0);
2360 }
2361 
2362 /*
2363  * Structures and routines associated with inodedep caching.
2364  */
2365 #define	INODEDEP_HASH(ump, inum) \
2366       (&(ump)->inodedep_hashtbl[(inum) & (ump)->inodedep_hash_size])
2367 
2368 static int
2369 inodedep_find(inodedephd, inum, inodedeppp)
2370 	struct inodedep_hashhead *inodedephd;
2371 	ino_t inum;
2372 	struct inodedep **inodedeppp;
2373 {
2374 	struct inodedep *inodedep;
2375 
2376 	LIST_FOREACH(inodedep, inodedephd, id_hash)
2377 		if (inum == inodedep->id_ino)
2378 			break;
2379 	if (inodedep) {
2380 		*inodedeppp = inodedep;
2381 		return (1);
2382 	}
2383 	*inodedeppp = NULL;
2384 
2385 	return (0);
2386 }
2387 /*
2388  * Look up an inodedep. Return 1 if found, 0 if not found.
2389  * If not found, allocate if DEPALLOC flag is passed.
2390  * Found or allocated entry is returned in inodedeppp.
2391  */
2392 static int
2393 inodedep_lookup(mp, inum, flags, inodedeppp)
2394 	struct mount *mp;
2395 	ino_t inum;
2396 	int flags;
2397 	struct inodedep **inodedeppp;
2398 {
2399 	struct inodedep *inodedep;
2400 	struct inodedep_hashhead *inodedephd;
2401 	struct ufsmount *ump;
2402 	struct fs *fs;
2403 
2404 	ump = VFSTOUFS(mp);
2405 	LOCK_OWNED(ump);
2406 	fs = ump->um_fs;
2407 	inodedephd = INODEDEP_HASH(ump, inum);
2408 
2409 	if (inodedep_find(inodedephd, inum, inodedeppp))
2410 		return (1);
2411 	if ((flags & DEPALLOC) == 0)
2412 		return (0);
2413 	/*
2414 	 * If the system is over its limit and our filesystem is
2415 	 * responsible for more than our share of that usage and
2416 	 * we are not in a rush, request some inodedep cleanup.
2417 	 */
2418 	if (softdep_excess_items(ump, D_INODEDEP))
2419 		schedule_cleanup(mp);
2420 	else
2421 		FREE_LOCK(ump);
2422 	inodedep = malloc(sizeof(struct inodedep),
2423 		M_INODEDEP, M_SOFTDEP_FLAGS);
2424 	workitem_alloc(&inodedep->id_list, D_INODEDEP, mp);
2425 	ACQUIRE_LOCK(ump);
2426 	if (inodedep_find(inodedephd, inum, inodedeppp)) {
2427 		WORKITEM_FREE(inodedep, D_INODEDEP);
2428 		return (1);
2429 	}
2430 	inodedep->id_fs = fs;
2431 	inodedep->id_ino = inum;
2432 	inodedep->id_state = ALLCOMPLETE;
2433 	inodedep->id_nlinkdelta = 0;
2434 	inodedep->id_nlinkwrote = -1;
2435 	inodedep->id_savedino1 = NULL;
2436 	inodedep->id_savedsize = -1;
2437 	inodedep->id_savedextsize = -1;
2438 	inodedep->id_savednlink = -1;
2439 	inodedep->id_bmsafemap = NULL;
2440 	inodedep->id_mkdiradd = NULL;
2441 	LIST_INIT(&inodedep->id_dirremhd);
2442 	LIST_INIT(&inodedep->id_pendinghd);
2443 	LIST_INIT(&inodedep->id_inowait);
2444 	LIST_INIT(&inodedep->id_bufwait);
2445 	TAILQ_INIT(&inodedep->id_inoreflst);
2446 	TAILQ_INIT(&inodedep->id_inoupdt);
2447 	TAILQ_INIT(&inodedep->id_newinoupdt);
2448 	TAILQ_INIT(&inodedep->id_extupdt);
2449 	TAILQ_INIT(&inodedep->id_newextupdt);
2450 	TAILQ_INIT(&inodedep->id_freeblklst);
2451 	LIST_INSERT_HEAD(inodedephd, inodedep, id_hash);
2452 	*inodedeppp = inodedep;
2453 	return (0);
2454 }
2455 
2456 /*
2457  * Structures and routines associated with newblk caching.
2458  */
2459 #define	NEWBLK_HASH(ump, inum) \
2460 	(&(ump)->newblk_hashtbl[(inum) & (ump)->newblk_hash_size])
2461 
2462 static int
2463 newblk_find(newblkhd, newblkno, flags, newblkpp)
2464 	struct newblk_hashhead *newblkhd;
2465 	ufs2_daddr_t newblkno;
2466 	int flags;
2467 	struct newblk **newblkpp;
2468 {
2469 	struct newblk *newblk;
2470 
2471 	LIST_FOREACH(newblk, newblkhd, nb_hash) {
2472 		if (newblkno != newblk->nb_newblkno)
2473 			continue;
2474 		/*
2475 		 * If we're creating a new dependency don't match those that
2476 		 * have already been converted to allocdirects.  This is for
2477 		 * a frag extend.
2478 		 */
2479 		if ((flags & DEPALLOC) && newblk->nb_list.wk_type != D_NEWBLK)
2480 			continue;
2481 		break;
2482 	}
2483 	if (newblk) {
2484 		*newblkpp = newblk;
2485 		return (1);
2486 	}
2487 	*newblkpp = NULL;
2488 	return (0);
2489 }
2490 
2491 /*
2492  * Look up a newblk. Return 1 if found, 0 if not found.
2493  * If not found, allocate if DEPALLOC flag is passed.
2494  * Found or allocated entry is returned in newblkpp.
2495  */
2496 static int
2497 newblk_lookup(mp, newblkno, flags, newblkpp)
2498 	struct mount *mp;
2499 	ufs2_daddr_t newblkno;
2500 	int flags;
2501 	struct newblk **newblkpp;
2502 {
2503 	struct newblk *newblk;
2504 	struct newblk_hashhead *newblkhd;
2505 	struct ufsmount *ump;
2506 
2507 	ump = VFSTOUFS(mp);
2508 	LOCK_OWNED(ump);
2509 	newblkhd = NEWBLK_HASH(ump, newblkno);
2510 	if (newblk_find(newblkhd, newblkno, flags, newblkpp))
2511 		return (1);
2512 	if ((flags & DEPALLOC) == 0)
2513 		return (0);
2514 	if (softdep_excess_items(ump, D_NEWBLK) ||
2515 	    softdep_excess_items(ump, D_ALLOCDIRECT) ||
2516 	    softdep_excess_items(ump, D_ALLOCINDIR))
2517 		schedule_cleanup(mp);
2518 	else
2519 		FREE_LOCK(ump);
2520 	newblk = malloc(sizeof(union allblk), M_NEWBLK,
2521 	    M_SOFTDEP_FLAGS | M_ZERO);
2522 	workitem_alloc(&newblk->nb_list, D_NEWBLK, mp);
2523 	ACQUIRE_LOCK(ump);
2524 	if (newblk_find(newblkhd, newblkno, flags, newblkpp)) {
2525 		WORKITEM_FREE(newblk, D_NEWBLK);
2526 		return (1);
2527 	}
2528 	newblk->nb_freefrag = NULL;
2529 	LIST_INIT(&newblk->nb_indirdeps);
2530 	LIST_INIT(&newblk->nb_newdirblk);
2531 	LIST_INIT(&newblk->nb_jwork);
2532 	newblk->nb_state = ATTACHED;
2533 	newblk->nb_newblkno = newblkno;
2534 	LIST_INSERT_HEAD(newblkhd, newblk, nb_hash);
2535 	*newblkpp = newblk;
2536 	return (0);
2537 }
2538 
2539 /*
2540  * Structures and routines associated with freed indirect block caching.
2541  */
2542 #define	INDIR_HASH(ump, blkno) \
2543 	(&(ump)->indir_hashtbl[(blkno) & (ump)->indir_hash_size])
2544 
2545 /*
2546  * Lookup an indirect block in the indir hash table.  The freework is
2547  * removed and potentially freed.  The caller must do a blocking journal
2548  * write before writing to the blkno.
2549  */
2550 static int
2551 indirblk_lookup(mp, blkno)
2552 	struct mount *mp;
2553 	ufs2_daddr_t blkno;
2554 {
2555 	struct freework *freework;
2556 	struct indir_hashhead *wkhd;
2557 	struct ufsmount *ump;
2558 
2559 	ump = VFSTOUFS(mp);
2560 	wkhd = INDIR_HASH(ump, blkno);
2561 	TAILQ_FOREACH(freework, wkhd, fw_next) {
2562 		if (freework->fw_blkno != blkno)
2563 			continue;
2564 		indirblk_remove(freework);
2565 		return (1);
2566 	}
2567 	return (0);
2568 }
2569 
2570 /*
2571  * Insert an indirect block represented by freework into the indirblk
2572  * hash table so that it may prevent the block from being re-used prior
2573  * to the journal being written.
2574  */
2575 static void
2576 indirblk_insert(freework)
2577 	struct freework *freework;
2578 {
2579 	struct jblocks *jblocks;
2580 	struct jseg *jseg;
2581 	struct ufsmount *ump;
2582 
2583 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2584 	jblocks = ump->softdep_jblocks;
2585 	jseg = TAILQ_LAST(&jblocks->jb_segs, jseglst);
2586 	if (jseg == NULL)
2587 		return;
2588 
2589 	LIST_INSERT_HEAD(&jseg->js_indirs, freework, fw_segs);
2590 	TAILQ_INSERT_HEAD(INDIR_HASH(ump, freework->fw_blkno), freework,
2591 	    fw_next);
2592 	freework->fw_state &= ~DEPCOMPLETE;
2593 }
2594 
2595 static void
2596 indirblk_remove(freework)
2597 	struct freework *freework;
2598 {
2599 	struct ufsmount *ump;
2600 
2601 	ump = VFSTOUFS(freework->fw_list.wk_mp);
2602 	LIST_REMOVE(freework, fw_segs);
2603 	TAILQ_REMOVE(INDIR_HASH(ump, freework->fw_blkno), freework, fw_next);
2604 	freework->fw_state |= DEPCOMPLETE;
2605 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
2606 		WORKITEM_FREE(freework, D_FREEWORK);
2607 }
2608 
2609 /*
2610  * Executed during filesystem system initialization before
2611  * mounting any filesystems.
2612  */
2613 void
2614 softdep_initialize()
2615 {
2616 
2617 	TAILQ_INIT(&softdepmounts);
2618 #ifdef __LP64__
2619 	max_softdeps = desiredvnodes * 4;
2620 #else
2621 	max_softdeps = desiredvnodes * 2;
2622 #endif
2623 
2624 	/* initialise bioops hack */
2625 	bioops.io_start = softdep_disk_io_initiation;
2626 	bioops.io_complete = softdep_disk_write_complete;
2627 	bioops.io_deallocate = softdep_deallocate_dependencies;
2628 	bioops.io_countdeps = softdep_count_dependencies;
2629 	softdep_ast_cleanup = softdep_ast_cleanup_proc;
2630 
2631 	/* Initialize the callout with an mtx. */
2632 	callout_init_mtx(&softdep_callout, &lk, 0);
2633 }
2634 
2635 /*
2636  * Executed after all filesystems have been unmounted during
2637  * filesystem module unload.
2638  */
2639 void
2640 softdep_uninitialize()
2641 {
2642 
2643 	/* clear bioops hack */
2644 	bioops.io_start = NULL;
2645 	bioops.io_complete = NULL;
2646 	bioops.io_deallocate = NULL;
2647 	bioops.io_countdeps = NULL;
2648 	softdep_ast_cleanup = NULL;
2649 
2650 	callout_drain(&softdep_callout);
2651 }
2652 
2653 /*
2654  * Called at mount time to notify the dependency code that a
2655  * filesystem wishes to use it.
2656  */
2657 int
2658 softdep_mount(devvp, mp, fs, cred)
2659 	struct vnode *devvp;
2660 	struct mount *mp;
2661 	struct fs *fs;
2662 	struct ucred *cred;
2663 {
2664 	struct csum_total cstotal;
2665 	struct mount_softdeps *sdp;
2666 	struct ufsmount *ump;
2667 	struct cg *cgp;
2668 	struct buf *bp;
2669 	u_int cyl, i;
2670 	int error;
2671 
2672 	sdp = malloc(sizeof(struct mount_softdeps), M_MOUNTDATA,
2673 	    M_WAITOK | M_ZERO);
2674 	MNT_ILOCK(mp);
2675 	mp->mnt_flag = (mp->mnt_flag & ~MNT_ASYNC) | MNT_SOFTDEP;
2676 	if ((mp->mnt_kern_flag & MNTK_SOFTDEP) == 0) {
2677 		mp->mnt_kern_flag = (mp->mnt_kern_flag & ~MNTK_ASYNC) |
2678 			MNTK_SOFTDEP | MNTK_NOASYNC;
2679 	}
2680 	ump = VFSTOUFS(mp);
2681 	ump->um_softdep = sdp;
2682 	MNT_IUNLOCK(mp);
2683 	rw_init(LOCK_PTR(ump), "per-fs softdep");
2684 	sdp->sd_ump = ump;
2685 	LIST_INIT(&ump->softdep_workitem_pending);
2686 	LIST_INIT(&ump->softdep_journal_pending);
2687 	TAILQ_INIT(&ump->softdep_unlinked);
2688 	LIST_INIT(&ump->softdep_dirtycg);
2689 	ump->softdep_worklist_tail = NULL;
2690 	ump->softdep_on_worklist = 0;
2691 	ump->softdep_deps = 0;
2692 	LIST_INIT(&ump->softdep_mkdirlisthd);
2693 	ump->pagedep_hashtbl = hashinit(desiredvnodes / 5, M_PAGEDEP,
2694 	    &ump->pagedep_hash_size);
2695 	ump->pagedep_nextclean = 0;
2696 	ump->inodedep_hashtbl = hashinit(desiredvnodes, M_INODEDEP,
2697 	    &ump->inodedep_hash_size);
2698 	ump->inodedep_nextclean = 0;
2699 	ump->newblk_hashtbl = hashinit(max_softdeps / 2,  M_NEWBLK,
2700 	    &ump->newblk_hash_size);
2701 	ump->bmsafemap_hashtbl = hashinit(1024, M_BMSAFEMAP,
2702 	    &ump->bmsafemap_hash_size);
2703 	i = 1 << (ffs(desiredvnodes / 10) - 1);
2704 	ump->indir_hashtbl = malloc(i * sizeof(struct indir_hashhead),
2705 	    M_FREEWORK, M_WAITOK);
2706 	ump->indir_hash_size = i - 1;
2707 	for (i = 0; i <= ump->indir_hash_size; i++)
2708 		TAILQ_INIT(&ump->indir_hashtbl[i]);
2709 #ifdef INVARIANTS
2710 	for (i = 0; i <= D_LAST; i++)
2711 		LIST_INIT(&ump->softdep_alldeps[i]);
2712 #endif
2713 	ACQUIRE_GBLLOCK(&lk);
2714 	TAILQ_INSERT_TAIL(&softdepmounts, sdp, sd_next);
2715 	FREE_GBLLOCK(&lk);
2716 	if ((fs->fs_flags & FS_SUJ) &&
2717 	    (error = journal_mount(mp, fs, cred)) != 0) {
2718 		printf("Failed to start journal: %d\n", error);
2719 		softdep_unmount(mp);
2720 		return (error);
2721 	}
2722 	/*
2723 	 * Start our flushing thread in the bufdaemon process.
2724 	 */
2725 	ACQUIRE_LOCK(ump);
2726 	ump->softdep_flags |= FLUSH_STARTING;
2727 	FREE_LOCK(ump);
2728 	kproc_kthread_add(&softdep_flush, mp, &bufdaemonproc,
2729 	    &ump->softdep_flushtd, 0, 0, "softdepflush", "%s worker",
2730 	    mp->mnt_stat.f_mntonname);
2731 	ACQUIRE_LOCK(ump);
2732 	while ((ump->softdep_flags & FLUSH_STARTING) != 0) {
2733 		msleep(&ump->softdep_flushtd, LOCK_PTR(ump), PVM, "sdstart",
2734 		    hz / 2);
2735 	}
2736 	FREE_LOCK(ump);
2737 	/*
2738 	 * When doing soft updates, the counters in the
2739 	 * superblock may have gotten out of sync. Recomputation
2740 	 * can take a long time and can be deferred for background
2741 	 * fsck.  However, the old behavior of scanning the cylinder
2742 	 * groups and recalculating them at mount time is available
2743 	 * by setting vfs.ffs.compute_summary_at_mount to one.
2744 	 */
2745 	if (compute_summary_at_mount == 0 || fs->fs_clean != 0)
2746 		return (0);
2747 	bzero(&cstotal, sizeof cstotal);
2748 	for (cyl = 0; cyl < fs->fs_ncg; cyl++) {
2749 		if ((error = bread(devvp, fsbtodb(fs, cgtod(fs, cyl)),
2750 		    fs->fs_cgsize, cred, &bp)) != 0) {
2751 			brelse(bp);
2752 			softdep_unmount(mp);
2753 			return (error);
2754 		}
2755 		cgp = (struct cg *)bp->b_data;
2756 		cstotal.cs_nffree += cgp->cg_cs.cs_nffree;
2757 		cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree;
2758 		cstotal.cs_nifree += cgp->cg_cs.cs_nifree;
2759 		cstotal.cs_ndir += cgp->cg_cs.cs_ndir;
2760 		fs->fs_cs(fs, cyl) = cgp->cg_cs;
2761 		brelse(bp);
2762 	}
2763 #ifdef INVARIANTS
2764 	if (bcmp(&cstotal, &fs->fs_cstotal, sizeof cstotal))
2765 		printf("%s: superblock summary recomputed\n", fs->fs_fsmnt);
2766 #endif
2767 	bcopy(&cstotal, &fs->fs_cstotal, sizeof cstotal);
2768 	return (0);
2769 }
2770 
2771 void
2772 softdep_unmount(mp)
2773 	struct mount *mp;
2774 {
2775 	struct ufsmount *ump;
2776 #ifdef INVARIANTS
2777 	int i;
2778 #endif
2779 
2780 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
2781 	    ("softdep_unmount called on non-softdep filesystem"));
2782 	ump = VFSTOUFS(mp);
2783 	MNT_ILOCK(mp);
2784 	mp->mnt_flag &= ~MNT_SOFTDEP;
2785 	if (MOUNTEDSUJ(mp) == 0) {
2786 		MNT_IUNLOCK(mp);
2787 	} else {
2788 		mp->mnt_flag &= ~MNT_SUJ;
2789 		MNT_IUNLOCK(mp);
2790 		journal_unmount(ump);
2791 	}
2792 	/*
2793 	 * Shut down our flushing thread. Check for NULL is if
2794 	 * softdep_mount errors out before the thread has been created.
2795 	 */
2796 	if (ump->softdep_flushtd != NULL) {
2797 		ACQUIRE_LOCK(ump);
2798 		ump->softdep_flags |= FLUSH_EXIT;
2799 		wakeup(&ump->softdep_flushtd);
2800 		msleep(&ump->softdep_flags, LOCK_PTR(ump), PVM | PDROP,
2801 		    "sdwait", 0);
2802 		KASSERT((ump->softdep_flags & FLUSH_EXIT) == 0,
2803 		    ("Thread shutdown failed"));
2804 	}
2805 	/*
2806 	 * Free up our resources.
2807 	 */
2808 	ACQUIRE_GBLLOCK(&lk);
2809 	TAILQ_REMOVE(&softdepmounts, ump->um_softdep, sd_next);
2810 	FREE_GBLLOCK(&lk);
2811 	rw_destroy(LOCK_PTR(ump));
2812 	hashdestroy(ump->pagedep_hashtbl, M_PAGEDEP, ump->pagedep_hash_size);
2813 	hashdestroy(ump->inodedep_hashtbl, M_INODEDEP, ump->inodedep_hash_size);
2814 	hashdestroy(ump->newblk_hashtbl, M_NEWBLK, ump->newblk_hash_size);
2815 	hashdestroy(ump->bmsafemap_hashtbl, M_BMSAFEMAP,
2816 	    ump->bmsafemap_hash_size);
2817 	free(ump->indir_hashtbl, M_FREEWORK);
2818 #ifdef INVARIANTS
2819 	for (i = 0; i <= D_LAST; i++) {
2820 		KASSERT(ump->softdep_curdeps[i] == 0,
2821 		    ("Unmount %s: Dep type %s != 0 (%ld)", ump->um_fs->fs_fsmnt,
2822 		    TYPENAME(i), ump->softdep_curdeps[i]));
2823 		KASSERT(LIST_EMPTY(&ump->softdep_alldeps[i]),
2824 		    ("Unmount %s: Dep type %s not empty (%p)", ump->um_fs->fs_fsmnt,
2825 		    TYPENAME(i), LIST_FIRST(&ump->softdep_alldeps[i])));
2826 	}
2827 #endif
2828 	free(ump->um_softdep, M_MOUNTDATA);
2829 }
2830 
2831 static struct jblocks *
2832 jblocks_create(void)
2833 {
2834 	struct jblocks *jblocks;
2835 
2836 	jblocks = malloc(sizeof(*jblocks), M_JBLOCKS, M_WAITOK | M_ZERO);
2837 	TAILQ_INIT(&jblocks->jb_segs);
2838 	jblocks->jb_avail = 10;
2839 	jblocks->jb_extent = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2840 	    M_JBLOCKS, M_WAITOK | M_ZERO);
2841 
2842 	return (jblocks);
2843 }
2844 
2845 static ufs2_daddr_t
2846 jblocks_alloc(jblocks, bytes, actual)
2847 	struct jblocks *jblocks;
2848 	int bytes;
2849 	int *actual;
2850 {
2851 	ufs2_daddr_t daddr;
2852 	struct jextent *jext;
2853 	int freecnt;
2854 	int blocks;
2855 
2856 	blocks = bytes / DEV_BSIZE;
2857 	jext = &jblocks->jb_extent[jblocks->jb_head];
2858 	freecnt = jext->je_blocks - jblocks->jb_off;
2859 	if (freecnt == 0) {
2860 		jblocks->jb_off = 0;
2861 		if (++jblocks->jb_head > jblocks->jb_used)
2862 			jblocks->jb_head = 0;
2863 		jext = &jblocks->jb_extent[jblocks->jb_head];
2864 		freecnt = jext->je_blocks;
2865 	}
2866 	if (freecnt > blocks)
2867 		freecnt = blocks;
2868 	*actual = freecnt * DEV_BSIZE;
2869 	daddr = jext->je_daddr + jblocks->jb_off;
2870 	jblocks->jb_off += freecnt;
2871 	jblocks->jb_free -= freecnt;
2872 
2873 	return (daddr);
2874 }
2875 
2876 static void
2877 jblocks_free(jblocks, mp, bytes)
2878 	struct jblocks *jblocks;
2879 	struct mount *mp;
2880 	int bytes;
2881 {
2882 
2883 	LOCK_OWNED(VFSTOUFS(mp));
2884 	jblocks->jb_free += bytes / DEV_BSIZE;
2885 	if (jblocks->jb_suspended)
2886 		worklist_speedup(mp);
2887 	wakeup(jblocks);
2888 }
2889 
2890 static void
2891 jblocks_destroy(jblocks)
2892 	struct jblocks *jblocks;
2893 {
2894 
2895 	if (jblocks->jb_extent)
2896 		free(jblocks->jb_extent, M_JBLOCKS);
2897 	free(jblocks, M_JBLOCKS);
2898 }
2899 
2900 static void
2901 jblocks_add(jblocks, daddr, blocks)
2902 	struct jblocks *jblocks;
2903 	ufs2_daddr_t daddr;
2904 	int blocks;
2905 {
2906 	struct jextent *jext;
2907 
2908 	jblocks->jb_blocks += blocks;
2909 	jblocks->jb_free += blocks;
2910 	jext = &jblocks->jb_extent[jblocks->jb_used];
2911 	/* Adding the first block. */
2912 	if (jext->je_daddr == 0) {
2913 		jext->je_daddr = daddr;
2914 		jext->je_blocks = blocks;
2915 		return;
2916 	}
2917 	/* Extending the last extent. */
2918 	if (jext->je_daddr + jext->je_blocks == daddr) {
2919 		jext->je_blocks += blocks;
2920 		return;
2921 	}
2922 	/* Adding a new extent. */
2923 	if (++jblocks->jb_used == jblocks->jb_avail) {
2924 		jblocks->jb_avail *= 2;
2925 		jext = malloc(sizeof(struct jextent) * jblocks->jb_avail,
2926 		    M_JBLOCKS, M_WAITOK | M_ZERO);
2927 		memcpy(jext, jblocks->jb_extent,
2928 		    sizeof(struct jextent) * jblocks->jb_used);
2929 		free(jblocks->jb_extent, M_JBLOCKS);
2930 		jblocks->jb_extent = jext;
2931 	}
2932 	jext = &jblocks->jb_extent[jblocks->jb_used];
2933 	jext->je_daddr = daddr;
2934 	jext->je_blocks = blocks;
2935 	return;
2936 }
2937 
2938 int
2939 softdep_journal_lookup(mp, vpp)
2940 	struct mount *mp;
2941 	struct vnode **vpp;
2942 {
2943 	struct componentname cnp;
2944 	struct vnode *dvp;
2945 	ino_t sujournal;
2946 	int error;
2947 
2948 	error = VFS_VGET(mp, UFS_ROOTINO, LK_EXCLUSIVE, &dvp);
2949 	if (error)
2950 		return (error);
2951 	bzero(&cnp, sizeof(cnp));
2952 	cnp.cn_nameiop = LOOKUP;
2953 	cnp.cn_flags = ISLASTCN;
2954 	cnp.cn_thread = curthread;
2955 	cnp.cn_cred = curthread->td_ucred;
2956 	cnp.cn_pnbuf = SUJ_FILE;
2957 	cnp.cn_nameptr = SUJ_FILE;
2958 	cnp.cn_namelen = strlen(SUJ_FILE);
2959 	error = ufs_lookup_ino(dvp, NULL, &cnp, &sujournal);
2960 	vput(dvp);
2961 	if (error != 0)
2962 		return (error);
2963 	error = VFS_VGET(mp, sujournal, LK_EXCLUSIVE, vpp);
2964 	return (error);
2965 }
2966 
2967 /*
2968  * Open and verify the journal file.
2969  */
2970 static int
2971 journal_mount(mp, fs, cred)
2972 	struct mount *mp;
2973 	struct fs *fs;
2974 	struct ucred *cred;
2975 {
2976 	struct jblocks *jblocks;
2977 	struct ufsmount *ump;
2978 	struct vnode *vp;
2979 	struct inode *ip;
2980 	ufs2_daddr_t blkno;
2981 	int bcount;
2982 	int error;
2983 	int i;
2984 
2985 	ump = VFSTOUFS(mp);
2986 	ump->softdep_journal_tail = NULL;
2987 	ump->softdep_on_journal = 0;
2988 	ump->softdep_accdeps = 0;
2989 	ump->softdep_req = 0;
2990 	ump->softdep_jblocks = NULL;
2991 	error = softdep_journal_lookup(mp, &vp);
2992 	if (error != 0) {
2993 		printf("Failed to find journal.  Use tunefs to create one\n");
2994 		return (error);
2995 	}
2996 	ip = VTOI(vp);
2997 	if (ip->i_size < SUJ_MIN) {
2998 		error = ENOSPC;
2999 		goto out;
3000 	}
3001 	bcount = lblkno(fs, ip->i_size);	/* Only use whole blocks. */
3002 	jblocks = jblocks_create();
3003 	for (i = 0; i < bcount; i++) {
3004 		error = ufs_bmaparray(vp, i, &blkno, NULL, NULL, NULL);
3005 		if (error)
3006 			break;
3007 		jblocks_add(jblocks, blkno, fsbtodb(fs, fs->fs_frag));
3008 	}
3009 	if (error) {
3010 		jblocks_destroy(jblocks);
3011 		goto out;
3012 	}
3013 	jblocks->jb_low = jblocks->jb_free / 3;	/* Reserve 33%. */
3014 	jblocks->jb_min = jblocks->jb_free / 10; /* Suspend at 10%. */
3015 	ump->softdep_jblocks = jblocks;
3016 out:
3017 	if (error == 0) {
3018 		MNT_ILOCK(mp);
3019 		mp->mnt_flag |= MNT_SUJ;
3020 		mp->mnt_flag &= ~MNT_SOFTDEP;
3021 		MNT_IUNLOCK(mp);
3022 		/*
3023 		 * Only validate the journal contents if the
3024 		 * filesystem is clean, otherwise we write the logs
3025 		 * but they'll never be used.  If the filesystem was
3026 		 * still dirty when we mounted it the journal is
3027 		 * invalid and a new journal can only be valid if it
3028 		 * starts from a clean mount.
3029 		 */
3030 		if (fs->fs_clean) {
3031 			DIP_SET(ip, i_modrev, fs->fs_mtime);
3032 			ip->i_flags |= IN_MODIFIED;
3033 			ffs_update(vp, 1);
3034 		}
3035 	}
3036 	vput(vp);
3037 	return (error);
3038 }
3039 
3040 static void
3041 journal_unmount(ump)
3042 	struct ufsmount *ump;
3043 {
3044 
3045 	if (ump->softdep_jblocks)
3046 		jblocks_destroy(ump->softdep_jblocks);
3047 	ump->softdep_jblocks = NULL;
3048 }
3049 
3050 /*
3051  * Called when a journal record is ready to be written.  Space is allocated
3052  * and the journal entry is created when the journal is flushed to stable
3053  * store.
3054  */
3055 static void
3056 add_to_journal(wk)
3057 	struct worklist *wk;
3058 {
3059 	struct ufsmount *ump;
3060 
3061 	ump = VFSTOUFS(wk->wk_mp);
3062 	LOCK_OWNED(ump);
3063 	if (wk->wk_state & ONWORKLIST)
3064 		panic("add_to_journal: %s(0x%X) already on list",
3065 		    TYPENAME(wk->wk_type), wk->wk_state);
3066 	wk->wk_state |= ONWORKLIST | DEPCOMPLETE;
3067 	if (LIST_EMPTY(&ump->softdep_journal_pending)) {
3068 		ump->softdep_jblocks->jb_age = ticks;
3069 		LIST_INSERT_HEAD(&ump->softdep_journal_pending, wk, wk_list);
3070 	} else
3071 		LIST_INSERT_AFTER(ump->softdep_journal_tail, wk, wk_list);
3072 	ump->softdep_journal_tail = wk;
3073 	ump->softdep_on_journal += 1;
3074 }
3075 
3076 /*
3077  * Remove an arbitrary item for the journal worklist maintain the tail
3078  * pointer.  This happens when a new operation obviates the need to
3079  * journal an old operation.
3080  */
3081 static void
3082 remove_from_journal(wk)
3083 	struct worklist *wk;
3084 {
3085 	struct ufsmount *ump;
3086 
3087 	ump = VFSTOUFS(wk->wk_mp);
3088 	LOCK_OWNED(ump);
3089 #ifdef INVARIANTS
3090 	{
3091 		struct worklist *wkn;
3092 
3093 		LIST_FOREACH(wkn, &ump->softdep_journal_pending, wk_list)
3094 			if (wkn == wk)
3095 				break;
3096 		if (wkn == NULL)
3097 			panic("remove_from_journal: %p is not in journal", wk);
3098 	}
3099 #endif
3100 	/*
3101 	 * We emulate a TAILQ to save space in most structures which do not
3102 	 * require TAILQ semantics.  Here we must update the tail position
3103 	 * when removing the tail which is not the final entry. This works
3104 	 * only if the worklist linkage are at the beginning of the structure.
3105 	 */
3106 	if (ump->softdep_journal_tail == wk)
3107 		ump->softdep_journal_tail =
3108 		    (struct worklist *)wk->wk_list.le_prev;
3109 	WORKLIST_REMOVE(wk);
3110 	ump->softdep_on_journal -= 1;
3111 }
3112 
3113 /*
3114  * Check for journal space as well as dependency limits so the prelink
3115  * code can throttle both journaled and non-journaled filesystems.
3116  * Threshold is 0 for low and 1 for min.
3117  */
3118 static int
3119 journal_space(ump, thresh)
3120 	struct ufsmount *ump;
3121 	int thresh;
3122 {
3123 	struct jblocks *jblocks;
3124 	int limit, avail;
3125 
3126 	jblocks = ump->softdep_jblocks;
3127 	if (jblocks == NULL)
3128 		return (1);
3129 	/*
3130 	 * We use a tighter restriction here to prevent request_cleanup()
3131 	 * running in threads from running into locks we currently hold.
3132 	 * We have to be over the limit and our filesystem has to be
3133 	 * responsible for more than our share of that usage.
3134 	 */
3135 	limit = (max_softdeps / 10) * 9;
3136 	if (dep_current[D_INODEDEP] > limit &&
3137 	    ump->softdep_curdeps[D_INODEDEP] > limit / stat_flush_threads)
3138 		return (0);
3139 	if (thresh)
3140 		thresh = jblocks->jb_min;
3141 	else
3142 		thresh = jblocks->jb_low;
3143 	avail = (ump->softdep_on_journal * JREC_SIZE) / DEV_BSIZE;
3144 	avail = jblocks->jb_free - avail;
3145 
3146 	return (avail > thresh);
3147 }
3148 
3149 static void
3150 journal_suspend(ump)
3151 	struct ufsmount *ump;
3152 {
3153 	struct jblocks *jblocks;
3154 	struct mount *mp;
3155 	bool set;
3156 
3157 	mp = UFSTOVFS(ump);
3158 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) != 0)
3159 		return;
3160 
3161 	jblocks = ump->softdep_jblocks;
3162 	vfs_op_enter(mp);
3163 	set = false;
3164 	MNT_ILOCK(mp);
3165 	if ((mp->mnt_kern_flag & MNTK_SUSPEND) == 0) {
3166 		stat_journal_min++;
3167 		mp->mnt_kern_flag |= MNTK_SUSPEND;
3168 		mp->mnt_susp_owner = ump->softdep_flushtd;
3169 		set = true;
3170 	}
3171 	jblocks->jb_suspended = 1;
3172 	MNT_IUNLOCK(mp);
3173 	if (!set)
3174 		vfs_op_exit(mp);
3175 }
3176 
3177 static int
3178 journal_unsuspend(struct ufsmount *ump)
3179 {
3180 	struct jblocks *jblocks;
3181 	struct mount *mp;
3182 
3183 	mp = UFSTOVFS(ump);
3184 	jblocks = ump->softdep_jblocks;
3185 
3186 	if (jblocks != NULL && jblocks->jb_suspended &&
3187 	    journal_space(ump, jblocks->jb_min)) {
3188 		jblocks->jb_suspended = 0;
3189 		FREE_LOCK(ump);
3190 		mp->mnt_susp_owner = curthread;
3191 		vfs_write_resume(mp, 0);
3192 		ACQUIRE_LOCK(ump);
3193 		return (1);
3194 	}
3195 	return (0);
3196 }
3197 
3198 /*
3199  * Called before any allocation function to be certain that there is
3200  * sufficient space in the journal prior to creating any new records.
3201  * Since in the case of block allocation we may have multiple locked
3202  * buffers at the time of the actual allocation we can not block
3203  * when the journal records are created.  Doing so would create a deadlock
3204  * if any of these buffers needed to be flushed to reclaim space.  Instead
3205  * we require a sufficiently large amount of available space such that
3206  * each thread in the system could have passed this allocation check and
3207  * still have sufficient free space.  With 20% of a minimum journal size
3208  * of 1MB we have 6553 records available.
3209  */
3210 int
3211 softdep_prealloc(vp, waitok)
3212 	struct vnode *vp;
3213 	int waitok;
3214 {
3215 	struct ufsmount *ump;
3216 
3217 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
3218 	    ("softdep_prealloc called on non-softdep filesystem"));
3219 	/*
3220 	 * Nothing to do if we are not running journaled soft updates.
3221 	 * If we currently hold the snapshot lock, we must avoid
3222 	 * handling other resources that could cause deadlock.  Do not
3223 	 * touch quotas vnode since it is typically recursed with
3224 	 * other vnode locks held.
3225 	 */
3226 	if (DOINGSUJ(vp) == 0 || IS_SNAPSHOT(VTOI(vp)) ||
3227 	    (vp->v_vflag & VV_SYSTEM) != 0)
3228 		return (0);
3229 	ump = VFSTOUFS(vp->v_mount);
3230 	ACQUIRE_LOCK(ump);
3231 	if (journal_space(ump, 0)) {
3232 		FREE_LOCK(ump);
3233 		return (0);
3234 	}
3235 	stat_journal_low++;
3236 	FREE_LOCK(ump);
3237 	if (waitok == MNT_NOWAIT)
3238 		return (ENOSPC);
3239 	/*
3240 	 * Attempt to sync this vnode once to flush any journal
3241 	 * work attached to it.
3242 	 */
3243 	if ((curthread->td_pflags & TDP_COWINPROGRESS) == 0)
3244 		ffs_syncvnode(vp, waitok, 0);
3245 	ACQUIRE_LOCK(ump);
3246 	process_removes(vp);
3247 	process_truncates(vp);
3248 	if (journal_space(ump, 0) == 0) {
3249 		softdep_speedup(ump);
3250 		if (journal_space(ump, 1) == 0)
3251 			journal_suspend(ump);
3252 	}
3253 	FREE_LOCK(ump);
3254 
3255 	return (0);
3256 }
3257 
3258 /*
3259  * Try hard to sync all data and metadata for the vnode, and workitems
3260  * flushing which might conflict with the vnode lock.  This is a
3261  * helper for softdep_prerename().
3262  */
3263 static int
3264 softdep_prerename_vnode(ump, vp)
3265 	struct ufsmount *ump;
3266 	struct vnode *vp;
3267 {
3268 	int error;
3269 
3270 	ASSERT_VOP_ELOCKED(vp, "prehandle");
3271 	if (vp->v_data == NULL)
3272 		return (0);
3273 	error = VOP_FSYNC(vp, MNT_WAIT, curthread);
3274 	if (error != 0)
3275 		return (error);
3276 	ACQUIRE_LOCK(ump);
3277 	process_removes(vp);
3278 	process_truncates(vp);
3279 	FREE_LOCK(ump);
3280 	return (0);
3281 }
3282 
3283 /*
3284  * Must be called from VOP_RENAME() after all vnodes are locked.
3285  * Ensures that there is enough journal space for rename.  It is
3286  * sufficiently different from softdep_prelink() by having to handle
3287  * four vnodes.
3288  */
3289 int
3290 softdep_prerename(fdvp, fvp, tdvp, tvp)
3291 	struct vnode *fdvp;
3292 	struct vnode *fvp;
3293 	struct vnode *tdvp;
3294 	struct vnode *tvp;
3295 {
3296 	struct ufsmount *ump;
3297 	int error;
3298 
3299 	ump = VFSTOUFS(fdvp->v_mount);
3300 
3301 	if (journal_space(ump, 0))
3302 		return (0);
3303 
3304 	VOP_UNLOCK(tdvp);
3305 	VOP_UNLOCK(fvp);
3306 	if (tvp != NULL && tvp != tdvp)
3307 		VOP_UNLOCK(tvp);
3308 
3309 	error = softdep_prerename_vnode(ump, fdvp);
3310 	VOP_UNLOCK(fdvp);
3311 	if (error != 0)
3312 		return (error);
3313 
3314 	VOP_LOCK(fvp, LK_EXCLUSIVE | LK_RETRY);
3315 	error = softdep_prerename_vnode(ump, fvp);
3316 	VOP_UNLOCK(fvp);
3317 	if (error != 0)
3318 		return (error);
3319 
3320 	if (tdvp != fdvp) {
3321 		VOP_LOCK(tdvp, LK_EXCLUSIVE | LK_RETRY);
3322 		error = softdep_prerename_vnode(ump, tdvp);
3323 		VOP_UNLOCK(tdvp);
3324 		if (error != 0)
3325 			return (error);
3326 	}
3327 
3328 	if (tvp != fvp && tvp != NULL) {
3329 		VOP_LOCK(tvp, LK_EXCLUSIVE | LK_RETRY);
3330 		error = softdep_prerename_vnode(ump, tvp);
3331 		VOP_UNLOCK(tvp);
3332 		if (error != 0)
3333 			return (error);
3334 	}
3335 
3336 	ACQUIRE_LOCK(ump);
3337 	softdep_speedup(ump);
3338 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3339 	if (journal_space(ump, 0) == 0) {
3340 		softdep_speedup(ump);
3341 		if (journal_space(ump, 1) == 0)
3342 			journal_suspend(ump);
3343 	}
3344 	FREE_LOCK(ump);
3345 	return (ERELOOKUP);
3346 }
3347 
3348 /*
3349  * Before adjusting a link count on a vnode verify that we have sufficient
3350  * journal space.  If not, process operations that depend on the currently
3351  * locked pair of vnodes to try to flush space as the syncer, buf daemon,
3352  * and softdep flush threads can not acquire these locks to reclaim space.
3353  *
3354  * Returns 0 if all owned locks are still valid and were not dropped
3355  * in the process, in other case it returns either an error from sync,
3356  * or ERELOOKUP if any of the locks were re-acquired.  In the later
3357  * case, the state of the vnodes cannot be relied upon and our VFS
3358  * syscall must be restarted at top level from the lookup.
3359  */
3360 int
3361 softdep_prelink(dvp, vp, will_direnter)
3362 	struct vnode *dvp;
3363 	struct vnode *vp;
3364 	int will_direnter;
3365 {
3366 	struct ufsmount *ump;
3367 	int error, error1;
3368 
3369 	ASSERT_VOP_ELOCKED(dvp, "prelink dvp");
3370 	if (vp != NULL)
3371 		ASSERT_VOP_ELOCKED(vp, "prelink vp");
3372 	ump = VFSTOUFS(dvp->v_mount);
3373 
3374 	/*
3375 	 * Nothing to do if we have sufficient journal space.
3376 	 * If we currently hold the snapshot lock, we must avoid
3377 	 * handling other resources that could cause deadlock.
3378 	 *
3379 	 * will_direnter == 1: In case allocated a directory block in
3380 	 * an indirect block, we must prevent holes in the directory
3381 	 * created if directory entries are written out of order.  To
3382 	 * accomplish this we fsync when we extend a directory into
3383 	 * indirects.  During rename it's not safe to drop the tvp
3384 	 * lock so sync must be delayed until it is.
3385 	 *
3386 	 * This synchronous step could be removed if fsck and the
3387 	 * kernel were taught to fill in sparse directories rather
3388 	 * than panic.
3389 	 */
3390 	if (journal_space(ump, 0) || (vp != NULL && IS_SNAPSHOT(VTOI(vp)))) {
3391 		error = 0;
3392 		if (will_direnter && (vp == NULL || !IS_SNAPSHOT(VTOI(vp)))) {
3393 			if (vp != NULL)
3394 				VOP_UNLOCK(vp);
3395 			error = ffs_syncvnode(dvp, MNT_WAIT, 0);
3396 			if (vp != NULL) {
3397 				error1 = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT);
3398 				if (error1 != 0) {
3399 					vn_lock_pair(dvp, true, vp, false);
3400 					if (error == 0)
3401 						error = ERELOOKUP;
3402 				} else if (vp->v_data == NULL) {
3403 					error = ERELOOKUP;
3404 				}
3405 			}
3406 		}
3407 		return (error);
3408 	}
3409 
3410 	stat_journal_low++;
3411 	if (vp != NULL) {
3412 		VOP_UNLOCK(dvp);
3413 		ffs_syncvnode(vp, MNT_NOWAIT, 0);
3414 		vn_lock_pair(dvp, false, vp, true);
3415 		if (dvp->v_data == NULL)
3416 			return (ERELOOKUP);
3417 	}
3418 	if (vp != NULL)
3419 		VOP_UNLOCK(vp);
3420 	ffs_syncvnode(dvp, MNT_WAIT, 0);
3421 	VOP_UNLOCK(dvp);
3422 
3423 	/* Process vp before dvp as it may create .. removes. */
3424 	if (vp != NULL) {
3425 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3426 		if (vp->v_data == NULL) {
3427 			vn_lock_pair(dvp, false, vp, true);
3428 			return (ERELOOKUP);
3429 		}
3430 		ACQUIRE_LOCK(ump);
3431 		process_removes(vp);
3432 		process_truncates(vp);
3433 		FREE_LOCK(ump);
3434 		VOP_UNLOCK(vp);
3435 	}
3436 
3437 	vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
3438 	if (dvp->v_data == NULL) {
3439 		vn_lock_pair(dvp, true, vp, false);
3440 		return (ERELOOKUP);
3441 	}
3442 
3443 	ACQUIRE_LOCK(ump);
3444 	process_removes(dvp);
3445 	process_truncates(dvp);
3446 	VOP_UNLOCK(dvp);
3447 	softdep_speedup(ump);
3448 
3449 	process_worklist_item(UFSTOVFS(ump), 2, LK_NOWAIT);
3450 	if (journal_space(ump, 0) == 0) {
3451 		softdep_speedup(ump);
3452 		if (journal_space(ump, 1) == 0)
3453 			journal_suspend(ump);
3454 	}
3455 	FREE_LOCK(ump);
3456 
3457 	vn_lock_pair(dvp, false, vp, false);
3458 	return (ERELOOKUP);
3459 }
3460 
3461 static void
3462 jseg_write(ump, jseg, data)
3463 	struct ufsmount *ump;
3464 	struct jseg *jseg;
3465 	uint8_t *data;
3466 {
3467 	struct jsegrec *rec;
3468 
3469 	rec = (struct jsegrec *)data;
3470 	rec->jsr_seq = jseg->js_seq;
3471 	rec->jsr_oldest = jseg->js_oldseq;
3472 	rec->jsr_cnt = jseg->js_cnt;
3473 	rec->jsr_blocks = jseg->js_size / ump->um_devvp->v_bufobj.bo_bsize;
3474 	rec->jsr_crc = 0;
3475 	rec->jsr_time = ump->um_fs->fs_mtime;
3476 }
3477 
3478 static inline void
3479 inoref_write(inoref, jseg, rec)
3480 	struct inoref *inoref;
3481 	struct jseg *jseg;
3482 	struct jrefrec *rec;
3483 {
3484 
3485 	inoref->if_jsegdep->jd_seg = jseg;
3486 	rec->jr_ino = inoref->if_ino;
3487 	rec->jr_parent = inoref->if_parent;
3488 	rec->jr_nlink = inoref->if_nlink;
3489 	rec->jr_mode = inoref->if_mode;
3490 	rec->jr_diroff = inoref->if_diroff;
3491 }
3492 
3493 static void
3494 jaddref_write(jaddref, jseg, data)
3495 	struct jaddref *jaddref;
3496 	struct jseg *jseg;
3497 	uint8_t *data;
3498 {
3499 	struct jrefrec *rec;
3500 
3501 	rec = (struct jrefrec *)data;
3502 	rec->jr_op = JOP_ADDREF;
3503 	inoref_write(&jaddref->ja_ref, jseg, rec);
3504 }
3505 
3506 static void
3507 jremref_write(jremref, jseg, data)
3508 	struct jremref *jremref;
3509 	struct jseg *jseg;
3510 	uint8_t *data;
3511 {
3512 	struct jrefrec *rec;
3513 
3514 	rec = (struct jrefrec *)data;
3515 	rec->jr_op = JOP_REMREF;
3516 	inoref_write(&jremref->jr_ref, jseg, rec);
3517 }
3518 
3519 static void
3520 jmvref_write(jmvref, jseg, data)
3521 	struct jmvref *jmvref;
3522 	struct jseg *jseg;
3523 	uint8_t *data;
3524 {
3525 	struct jmvrec *rec;
3526 
3527 	rec = (struct jmvrec *)data;
3528 	rec->jm_op = JOP_MVREF;
3529 	rec->jm_ino = jmvref->jm_ino;
3530 	rec->jm_parent = jmvref->jm_parent;
3531 	rec->jm_oldoff = jmvref->jm_oldoff;
3532 	rec->jm_newoff = jmvref->jm_newoff;
3533 }
3534 
3535 static void
3536 jnewblk_write(jnewblk, jseg, data)
3537 	struct jnewblk *jnewblk;
3538 	struct jseg *jseg;
3539 	uint8_t *data;
3540 {
3541 	struct jblkrec *rec;
3542 
3543 	jnewblk->jn_jsegdep->jd_seg = jseg;
3544 	rec = (struct jblkrec *)data;
3545 	rec->jb_op = JOP_NEWBLK;
3546 	rec->jb_ino = jnewblk->jn_ino;
3547 	rec->jb_blkno = jnewblk->jn_blkno;
3548 	rec->jb_lbn = jnewblk->jn_lbn;
3549 	rec->jb_frags = jnewblk->jn_frags;
3550 	rec->jb_oldfrags = jnewblk->jn_oldfrags;
3551 }
3552 
3553 static void
3554 jfreeblk_write(jfreeblk, jseg, data)
3555 	struct jfreeblk *jfreeblk;
3556 	struct jseg *jseg;
3557 	uint8_t *data;
3558 {
3559 	struct jblkrec *rec;
3560 
3561 	jfreeblk->jf_dep.jb_jsegdep->jd_seg = jseg;
3562 	rec = (struct jblkrec *)data;
3563 	rec->jb_op = JOP_FREEBLK;
3564 	rec->jb_ino = jfreeblk->jf_ino;
3565 	rec->jb_blkno = jfreeblk->jf_blkno;
3566 	rec->jb_lbn = jfreeblk->jf_lbn;
3567 	rec->jb_frags = jfreeblk->jf_frags;
3568 	rec->jb_oldfrags = 0;
3569 }
3570 
3571 static void
3572 jfreefrag_write(jfreefrag, jseg, data)
3573 	struct jfreefrag *jfreefrag;
3574 	struct jseg *jseg;
3575 	uint8_t *data;
3576 {
3577 	struct jblkrec *rec;
3578 
3579 	jfreefrag->fr_jsegdep->jd_seg = jseg;
3580 	rec = (struct jblkrec *)data;
3581 	rec->jb_op = JOP_FREEBLK;
3582 	rec->jb_ino = jfreefrag->fr_ino;
3583 	rec->jb_blkno = jfreefrag->fr_blkno;
3584 	rec->jb_lbn = jfreefrag->fr_lbn;
3585 	rec->jb_frags = jfreefrag->fr_frags;
3586 	rec->jb_oldfrags = 0;
3587 }
3588 
3589 static void
3590 jtrunc_write(jtrunc, jseg, data)
3591 	struct jtrunc *jtrunc;
3592 	struct jseg *jseg;
3593 	uint8_t *data;
3594 {
3595 	struct jtrncrec *rec;
3596 
3597 	jtrunc->jt_dep.jb_jsegdep->jd_seg = jseg;
3598 	rec = (struct jtrncrec *)data;
3599 	rec->jt_op = JOP_TRUNC;
3600 	rec->jt_ino = jtrunc->jt_ino;
3601 	rec->jt_size = jtrunc->jt_size;
3602 	rec->jt_extsize = jtrunc->jt_extsize;
3603 }
3604 
3605 static void
3606 jfsync_write(jfsync, jseg, data)
3607 	struct jfsync *jfsync;
3608 	struct jseg *jseg;
3609 	uint8_t *data;
3610 {
3611 	struct jtrncrec *rec;
3612 
3613 	rec = (struct jtrncrec *)data;
3614 	rec->jt_op = JOP_SYNC;
3615 	rec->jt_ino = jfsync->jfs_ino;
3616 	rec->jt_size = jfsync->jfs_size;
3617 	rec->jt_extsize = jfsync->jfs_extsize;
3618 }
3619 
3620 static void
3621 softdep_flushjournal(mp)
3622 	struct mount *mp;
3623 {
3624 	struct jblocks *jblocks;
3625 	struct ufsmount *ump;
3626 
3627 	if (MOUNTEDSUJ(mp) == 0)
3628 		return;
3629 	ump = VFSTOUFS(mp);
3630 	jblocks = ump->softdep_jblocks;
3631 	ACQUIRE_LOCK(ump);
3632 	while (ump->softdep_on_journal) {
3633 		jblocks->jb_needseg = 1;
3634 		softdep_process_journal(mp, NULL, MNT_WAIT);
3635 	}
3636 	FREE_LOCK(ump);
3637 }
3638 
3639 static void softdep_synchronize_completed(struct bio *);
3640 static void softdep_synchronize(struct bio *, struct ufsmount *, void *);
3641 
3642 static void
3643 softdep_synchronize_completed(bp)
3644         struct bio *bp;
3645 {
3646 	struct jseg *oldest;
3647 	struct jseg *jseg;
3648 	struct ufsmount *ump;
3649 
3650 	/*
3651 	 * caller1 marks the last segment written before we issued the
3652 	 * synchronize cache.
3653 	 */
3654 	jseg = bp->bio_caller1;
3655 	if (jseg == NULL) {
3656 		g_destroy_bio(bp);
3657 		return;
3658 	}
3659 	ump = VFSTOUFS(jseg->js_list.wk_mp);
3660 	ACQUIRE_LOCK(ump);
3661 	oldest = NULL;
3662 	/*
3663 	 * Mark all the journal entries waiting on the synchronize cache
3664 	 * as completed so they may continue on.
3665 	 */
3666 	while (jseg != NULL && (jseg->js_state & COMPLETE) == 0) {
3667 		jseg->js_state |= COMPLETE;
3668 		oldest = jseg;
3669 		jseg = TAILQ_PREV(jseg, jseglst, js_next);
3670 	}
3671 	/*
3672 	 * Restart deferred journal entry processing from the oldest
3673 	 * completed jseg.
3674 	 */
3675 	if (oldest)
3676 		complete_jsegs(oldest);
3677 
3678 	FREE_LOCK(ump);
3679 	g_destroy_bio(bp);
3680 }
3681 
3682 /*
3683  * Send BIO_FLUSH/SYNCHRONIZE CACHE to the device to enforce write ordering
3684  * barriers.  The journal must be written prior to any blocks that depend
3685  * on it and the journal can not be released until the blocks have be
3686  * written.  This code handles both barriers simultaneously.
3687  */
3688 static void
3689 softdep_synchronize(bp, ump, caller1)
3690 	struct bio *bp;
3691 	struct ufsmount *ump;
3692 	void *caller1;
3693 {
3694 
3695 	bp->bio_cmd = BIO_FLUSH;
3696 	bp->bio_flags |= BIO_ORDERED;
3697 	bp->bio_data = NULL;
3698 	bp->bio_offset = ump->um_cp->provider->mediasize;
3699 	bp->bio_length = 0;
3700 	bp->bio_done = softdep_synchronize_completed;
3701 	bp->bio_caller1 = caller1;
3702 	g_io_request(bp, ump->um_cp);
3703 }
3704 
3705 /*
3706  * Flush some journal records to disk.
3707  */
3708 static void
3709 softdep_process_journal(mp, needwk, flags)
3710 	struct mount *mp;
3711 	struct worklist *needwk;
3712 	int flags;
3713 {
3714 	struct jblocks *jblocks;
3715 	struct ufsmount *ump;
3716 	struct worklist *wk;
3717 	struct jseg *jseg;
3718 	struct buf *bp;
3719 	struct bio *bio;
3720 	uint8_t *data;
3721 	struct fs *fs;
3722 	int shouldflush;
3723 	int segwritten;
3724 	int jrecmin;	/* Minimum records per block. */
3725 	int jrecmax;	/* Maximum records per block. */
3726 	int size;
3727 	int cnt;
3728 	int off;
3729 	int devbsize;
3730 
3731 	if (MOUNTEDSUJ(mp) == 0)
3732 		return;
3733 	shouldflush = softdep_flushcache;
3734 	bio = NULL;
3735 	jseg = NULL;
3736 	ump = VFSTOUFS(mp);
3737 	LOCK_OWNED(ump);
3738 	fs = ump->um_fs;
3739 	jblocks = ump->softdep_jblocks;
3740 	devbsize = ump->um_devvp->v_bufobj.bo_bsize;
3741 	/*
3742 	 * We write anywhere between a disk block and fs block.  The upper
3743 	 * bound is picked to prevent buffer cache fragmentation and limit
3744 	 * processing time per I/O.
3745 	 */
3746 	jrecmin = (devbsize / JREC_SIZE) - 1; /* -1 for seg header */
3747 	jrecmax = (fs->fs_bsize / devbsize) * jrecmin;
3748 	segwritten = 0;
3749 	for (;;) {
3750 		cnt = ump->softdep_on_journal;
3751 		/*
3752 		 * Criteria for writing a segment:
3753 		 * 1) We have a full block.
3754 		 * 2) We're called from jwait() and haven't found the
3755 		 *    journal item yet.
3756 		 * 3) Always write if needseg is set.
3757 		 * 4) If we are called from process_worklist and have
3758 		 *    not yet written anything we write a partial block
3759 		 *    to enforce a 1 second maximum latency on journal
3760 		 *    entries.
3761 		 */
3762 		if (cnt < (jrecmax - 1) && needwk == NULL &&
3763 		    jblocks->jb_needseg == 0 && (segwritten || cnt == 0))
3764 			break;
3765 		cnt++;
3766 		/*
3767 		 * Verify some free journal space.  softdep_prealloc() should
3768 		 * guarantee that we don't run out so this is indicative of
3769 		 * a problem with the flow control.  Try to recover
3770 		 * gracefully in any event.
3771 		 */
3772 		while (jblocks->jb_free == 0) {
3773 			if (flags != MNT_WAIT)
3774 				break;
3775 			printf("softdep: Out of journal space!\n");
3776 			softdep_speedup(ump);
3777 			msleep(jblocks, LOCK_PTR(ump), PRIBIO, "jblocks", hz);
3778 		}
3779 		FREE_LOCK(ump);
3780 		jseg = malloc(sizeof(*jseg), M_JSEG, M_SOFTDEP_FLAGS);
3781 		workitem_alloc(&jseg->js_list, D_JSEG, mp);
3782 		LIST_INIT(&jseg->js_entries);
3783 		LIST_INIT(&jseg->js_indirs);
3784 		jseg->js_state = ATTACHED;
3785 		if (shouldflush == 0)
3786 			jseg->js_state |= COMPLETE;
3787 		else if (bio == NULL)
3788 			bio = g_alloc_bio();
3789 		jseg->js_jblocks = jblocks;
3790 		bp = geteblk(fs->fs_bsize, 0);
3791 		ACQUIRE_LOCK(ump);
3792 		/*
3793 		 * If there was a race while we were allocating the block
3794 		 * and jseg the entry we care about was likely written.
3795 		 * We bail out in both the WAIT and NOWAIT case and assume
3796 		 * the caller will loop if the entry it cares about is
3797 		 * not written.
3798 		 */
3799 		cnt = ump->softdep_on_journal;
3800 		if (cnt + jblocks->jb_needseg == 0 || jblocks->jb_free == 0) {
3801 			bp->b_flags |= B_INVAL | B_NOCACHE;
3802 			WORKITEM_FREE(jseg, D_JSEG);
3803 			FREE_LOCK(ump);
3804 			brelse(bp);
3805 			ACQUIRE_LOCK(ump);
3806 			break;
3807 		}
3808 		/*
3809 		 * Calculate the disk block size required for the available
3810 		 * records rounded to the min size.
3811 		 */
3812 		if (cnt == 0)
3813 			size = devbsize;
3814 		else if (cnt < jrecmax)
3815 			size = howmany(cnt, jrecmin) * devbsize;
3816 		else
3817 			size = fs->fs_bsize;
3818 		/*
3819 		 * Allocate a disk block for this journal data and account
3820 		 * for truncation of the requested size if enough contiguous
3821 		 * space was not available.
3822 		 */
3823 		bp->b_blkno = jblocks_alloc(jblocks, size, &size);
3824 		bp->b_lblkno = bp->b_blkno;
3825 		bp->b_offset = bp->b_blkno * DEV_BSIZE;
3826 		bp->b_bcount = size;
3827 		bp->b_flags &= ~B_INVAL;
3828 		bp->b_flags |= B_VALIDSUSPWRT | B_NOCOPY;
3829 		/*
3830 		 * Initialize our jseg with cnt records.  Assign the next
3831 		 * sequence number to it and link it in-order.
3832 		 */
3833 		cnt = MIN(cnt, (size / devbsize) * jrecmin);
3834 		jseg->js_buf = bp;
3835 		jseg->js_cnt = cnt;
3836 		jseg->js_refs = cnt + 1;	/* Self ref. */
3837 		jseg->js_size = size;
3838 		jseg->js_seq = jblocks->jb_nextseq++;
3839 		if (jblocks->jb_oldestseg == NULL)
3840 			jblocks->jb_oldestseg = jseg;
3841 		jseg->js_oldseq = jblocks->jb_oldestseg->js_seq;
3842 		TAILQ_INSERT_TAIL(&jblocks->jb_segs, jseg, js_next);
3843 		if (jblocks->jb_writeseg == NULL)
3844 			jblocks->jb_writeseg = jseg;
3845 		/*
3846 		 * Start filling in records from the pending list.
3847 		 */
3848 		data = bp->b_data;
3849 		off = 0;
3850 
3851 		/*
3852 		 * Always put a header on the first block.
3853 		 * XXX As with below, there might not be a chance to get
3854 		 * into the loop.  Ensure that something valid is written.
3855 		 */
3856 		jseg_write(ump, jseg, data);
3857 		off += JREC_SIZE;
3858 		data = bp->b_data + off;
3859 
3860 		/*
3861 		 * XXX Something is wrong here.  There's no work to do,
3862 		 * but we need to perform and I/O and allow it to complete
3863 		 * anyways.
3864 		 */
3865 		if (LIST_EMPTY(&ump->softdep_journal_pending))
3866 			stat_emptyjblocks++;
3867 
3868 		while ((wk = LIST_FIRST(&ump->softdep_journal_pending))
3869 		    != NULL) {
3870 			if (cnt == 0)
3871 				break;
3872 			/* Place a segment header on every device block. */
3873 			if ((off % devbsize) == 0) {
3874 				jseg_write(ump, jseg, data);
3875 				off += JREC_SIZE;
3876 				data = bp->b_data + off;
3877 			}
3878 			if (wk == needwk)
3879 				needwk = NULL;
3880 			remove_from_journal(wk);
3881 			wk->wk_state |= INPROGRESS;
3882 			WORKLIST_INSERT(&jseg->js_entries, wk);
3883 			switch (wk->wk_type) {
3884 			case D_JADDREF:
3885 				jaddref_write(WK_JADDREF(wk), jseg, data);
3886 				break;
3887 			case D_JREMREF:
3888 				jremref_write(WK_JREMREF(wk), jseg, data);
3889 				break;
3890 			case D_JMVREF:
3891 				jmvref_write(WK_JMVREF(wk), jseg, data);
3892 				break;
3893 			case D_JNEWBLK:
3894 				jnewblk_write(WK_JNEWBLK(wk), jseg, data);
3895 				break;
3896 			case D_JFREEBLK:
3897 				jfreeblk_write(WK_JFREEBLK(wk), jseg, data);
3898 				break;
3899 			case D_JFREEFRAG:
3900 				jfreefrag_write(WK_JFREEFRAG(wk), jseg, data);
3901 				break;
3902 			case D_JTRUNC:
3903 				jtrunc_write(WK_JTRUNC(wk), jseg, data);
3904 				break;
3905 			case D_JFSYNC:
3906 				jfsync_write(WK_JFSYNC(wk), jseg, data);
3907 				break;
3908 			default:
3909 				panic("process_journal: Unknown type %s",
3910 				    TYPENAME(wk->wk_type));
3911 				/* NOTREACHED */
3912 			}
3913 			off += JREC_SIZE;
3914 			data = bp->b_data + off;
3915 			cnt--;
3916 		}
3917 
3918 		/* Clear any remaining space so we don't leak kernel data */
3919 		if (size > off)
3920 			bzero(data, size - off);
3921 
3922 		/*
3923 		 * Write this one buffer and continue.
3924 		 */
3925 		segwritten = 1;
3926 		jblocks->jb_needseg = 0;
3927 		WORKLIST_INSERT(&bp->b_dep, &jseg->js_list);
3928 		FREE_LOCK(ump);
3929 		bp->b_xflags |= BX_CVTENXIO;
3930 		pbgetvp(ump->um_devvp, bp);
3931 		/*
3932 		 * We only do the blocking wait once we find the journal
3933 		 * entry we're looking for.
3934 		 */
3935 		if (needwk == NULL && flags == MNT_WAIT)
3936 			bwrite(bp);
3937 		else
3938 			bawrite(bp);
3939 		ACQUIRE_LOCK(ump);
3940 	}
3941 	/*
3942 	 * If we wrote a segment issue a synchronize cache so the journal
3943 	 * is reflected on disk before the data is written.  Since reclaiming
3944 	 * journal space also requires writing a journal record this
3945 	 * process also enforces a barrier before reclamation.
3946 	 */
3947 	if (segwritten && shouldflush) {
3948 		softdep_synchronize(bio, ump,
3949 		    TAILQ_LAST(&jblocks->jb_segs, jseglst));
3950 	} else if (bio)
3951 		g_destroy_bio(bio);
3952 	/*
3953 	 * If we've suspended the filesystem because we ran out of journal
3954 	 * space either try to sync it here to make some progress or
3955 	 * unsuspend it if we already have.
3956 	 */
3957 	if (flags == 0 && jblocks->jb_suspended) {
3958 		if (journal_unsuspend(ump))
3959 			return;
3960 		FREE_LOCK(ump);
3961 		VFS_SYNC(mp, MNT_NOWAIT);
3962 		ffs_sbupdate(ump, MNT_WAIT, 0);
3963 		ACQUIRE_LOCK(ump);
3964 	}
3965 }
3966 
3967 /*
3968  * Complete a jseg, allowing all dependencies awaiting journal writes
3969  * to proceed.  Each journal dependency also attaches a jsegdep to dependent
3970  * structures so that the journal segment can be freed to reclaim space.
3971  */
3972 static void
3973 complete_jseg(jseg)
3974 	struct jseg *jseg;
3975 {
3976 	struct worklist *wk;
3977 	struct jmvref *jmvref;
3978 #ifdef INVARIANTS
3979 	int i = 0;
3980 #endif
3981 
3982 	while ((wk = LIST_FIRST(&jseg->js_entries)) != NULL) {
3983 		WORKLIST_REMOVE(wk);
3984 		wk->wk_state &= ~INPROGRESS;
3985 		wk->wk_state |= COMPLETE;
3986 		KASSERT(i++ < jseg->js_cnt,
3987 		    ("handle_written_jseg: overflow %d >= %d",
3988 		    i - 1, jseg->js_cnt));
3989 		switch (wk->wk_type) {
3990 		case D_JADDREF:
3991 			handle_written_jaddref(WK_JADDREF(wk));
3992 			break;
3993 		case D_JREMREF:
3994 			handle_written_jremref(WK_JREMREF(wk));
3995 			break;
3996 		case D_JMVREF:
3997 			rele_jseg(jseg);	/* No jsegdep. */
3998 			jmvref = WK_JMVREF(wk);
3999 			LIST_REMOVE(jmvref, jm_deps);
4000 			if ((jmvref->jm_pagedep->pd_state & ONWORKLIST) == 0)
4001 				free_pagedep(jmvref->jm_pagedep);
4002 			WORKITEM_FREE(jmvref, D_JMVREF);
4003 			break;
4004 		case D_JNEWBLK:
4005 			handle_written_jnewblk(WK_JNEWBLK(wk));
4006 			break;
4007 		case D_JFREEBLK:
4008 			handle_written_jblkdep(&WK_JFREEBLK(wk)->jf_dep);
4009 			break;
4010 		case D_JTRUNC:
4011 			handle_written_jblkdep(&WK_JTRUNC(wk)->jt_dep);
4012 			break;
4013 		case D_JFSYNC:
4014 			rele_jseg(jseg);	/* No jsegdep. */
4015 			WORKITEM_FREE(wk, D_JFSYNC);
4016 			break;
4017 		case D_JFREEFRAG:
4018 			handle_written_jfreefrag(WK_JFREEFRAG(wk));
4019 			break;
4020 		default:
4021 			panic("handle_written_jseg: Unknown type %s",
4022 			    TYPENAME(wk->wk_type));
4023 			/* NOTREACHED */
4024 		}
4025 	}
4026 	/* Release the self reference so the structure may be freed. */
4027 	rele_jseg(jseg);
4028 }
4029 
4030 /*
4031  * Determine which jsegs are ready for completion processing.  Waits for
4032  * synchronize cache to complete as well as forcing in-order completion
4033  * of journal entries.
4034  */
4035 static void
4036 complete_jsegs(jseg)
4037 	struct jseg *jseg;
4038 {
4039 	struct jblocks *jblocks;
4040 	struct jseg *jsegn;
4041 
4042 	jblocks = jseg->js_jblocks;
4043 	/*
4044 	 * Don't allow out of order completions.  If this isn't the first
4045 	 * block wait for it to write before we're done.
4046 	 */
4047 	if (jseg != jblocks->jb_writeseg)
4048 		return;
4049 	/* Iterate through available jsegs processing their entries. */
4050 	while (jseg && (jseg->js_state & ALLCOMPLETE) == ALLCOMPLETE) {
4051 		jblocks->jb_oldestwrseq = jseg->js_oldseq;
4052 		jsegn = TAILQ_NEXT(jseg, js_next);
4053 		complete_jseg(jseg);
4054 		jseg = jsegn;
4055 	}
4056 	jblocks->jb_writeseg = jseg;
4057 	/*
4058 	 * Attempt to free jsegs now that oldestwrseq may have advanced.
4059 	 */
4060 	free_jsegs(jblocks);
4061 }
4062 
4063 /*
4064  * Mark a jseg as DEPCOMPLETE and throw away the buffer.  Attempt to handle
4065  * the final completions.
4066  */
4067 static void
4068 handle_written_jseg(jseg, bp)
4069 	struct jseg *jseg;
4070 	struct buf *bp;
4071 {
4072 
4073 	if (jseg->js_refs == 0)
4074 		panic("handle_written_jseg: No self-reference on %p", jseg);
4075 	jseg->js_state |= DEPCOMPLETE;
4076 	/*
4077 	 * We'll never need this buffer again, set flags so it will be
4078 	 * discarded.
4079 	 */
4080 	bp->b_flags |= B_INVAL | B_NOCACHE;
4081 	pbrelvp(bp);
4082 	complete_jsegs(jseg);
4083 }
4084 
4085 static inline struct jsegdep *
4086 inoref_jseg(inoref)
4087 	struct inoref *inoref;
4088 {
4089 	struct jsegdep *jsegdep;
4090 
4091 	jsegdep = inoref->if_jsegdep;
4092 	inoref->if_jsegdep = NULL;
4093 
4094 	return (jsegdep);
4095 }
4096 
4097 /*
4098  * Called once a jremref has made it to stable store.  The jremref is marked
4099  * complete and we attempt to free it.  Any pagedeps writes sleeping waiting
4100  * for the jremref to complete will be awoken by free_jremref.
4101  */
4102 static void
4103 handle_written_jremref(jremref)
4104 	struct jremref *jremref;
4105 {
4106 	struct inodedep *inodedep;
4107 	struct jsegdep *jsegdep;
4108 	struct dirrem *dirrem;
4109 
4110 	/* Grab the jsegdep. */
4111 	jsegdep = inoref_jseg(&jremref->jr_ref);
4112 	/*
4113 	 * Remove us from the inoref list.
4114 	 */
4115 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino,
4116 	    0, &inodedep) == 0)
4117 		panic("handle_written_jremref: Lost inodedep");
4118 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
4119 	/*
4120 	 * Complete the dirrem.
4121 	 */
4122 	dirrem = jremref->jr_dirrem;
4123 	jremref->jr_dirrem = NULL;
4124 	LIST_REMOVE(jremref, jr_deps);
4125 	jsegdep->jd_state |= jremref->jr_state & MKDIR_PARENT;
4126 	jwork_insert(&dirrem->dm_jwork, jsegdep);
4127 	if (LIST_EMPTY(&dirrem->dm_jremrefhd) &&
4128 	    (dirrem->dm_state & COMPLETE) != 0)
4129 		add_to_worklist(&dirrem->dm_list, 0);
4130 	free_jremref(jremref);
4131 }
4132 
4133 /*
4134  * Called once a jaddref has made it to stable store.  The dependency is
4135  * marked complete and any dependent structures are added to the inode
4136  * bufwait list to be completed as soon as it is written.  If a bitmap write
4137  * depends on this entry we move the inode into the inodedephd of the
4138  * bmsafemap dependency and attempt to remove the jaddref from the bmsafemap.
4139  */
4140 static void
4141 handle_written_jaddref(jaddref)
4142 	struct jaddref *jaddref;
4143 {
4144 	struct jsegdep *jsegdep;
4145 	struct inodedep *inodedep;
4146 	struct diradd *diradd;
4147 	struct mkdir *mkdir;
4148 
4149 	/* Grab the jsegdep. */
4150 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4151 	mkdir = NULL;
4152 	diradd = NULL;
4153 	if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4154 	    0, &inodedep) == 0)
4155 		panic("handle_written_jaddref: Lost inodedep.");
4156 	if (jaddref->ja_diradd == NULL)
4157 		panic("handle_written_jaddref: No dependency");
4158 	if (jaddref->ja_diradd->da_list.wk_type == D_DIRADD) {
4159 		diradd = jaddref->ja_diradd;
4160 		WORKLIST_INSERT(&inodedep->id_bufwait, &diradd->da_list);
4161 	} else if (jaddref->ja_state & MKDIR_PARENT) {
4162 		mkdir = jaddref->ja_mkdir;
4163 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir->md_list);
4164 	} else if (jaddref->ja_state & MKDIR_BODY)
4165 		mkdir = jaddref->ja_mkdir;
4166 	else
4167 		panic("handle_written_jaddref: Unknown dependency %p",
4168 		    jaddref->ja_diradd);
4169 	jaddref->ja_diradd = NULL;	/* also clears ja_mkdir */
4170 	/*
4171 	 * Remove us from the inode list.
4172 	 */
4173 	TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref, if_deps);
4174 	/*
4175 	 * The mkdir may be waiting on the jaddref to clear before freeing.
4176 	 */
4177 	if (mkdir) {
4178 		KASSERT(mkdir->md_list.wk_type == D_MKDIR,
4179 		    ("handle_written_jaddref: Incorrect type for mkdir %s",
4180 		    TYPENAME(mkdir->md_list.wk_type)));
4181 		mkdir->md_jaddref = NULL;
4182 		diradd = mkdir->md_diradd;
4183 		mkdir->md_state |= DEPCOMPLETE;
4184 		complete_mkdir(mkdir);
4185 	}
4186 	jwork_insert(&diradd->da_jwork, jsegdep);
4187 	if (jaddref->ja_state & NEWBLOCK) {
4188 		inodedep->id_state |= ONDEPLIST;
4189 		LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_inodedephd,
4190 		    inodedep, id_deps);
4191 	}
4192 	free_jaddref(jaddref);
4193 }
4194 
4195 /*
4196  * Called once a jnewblk journal is written.  The allocdirect or allocindir
4197  * is placed in the bmsafemap to await notification of a written bitmap.  If
4198  * the operation was canceled we add the segdep to the appropriate
4199  * dependency to free the journal space once the canceling operation
4200  * completes.
4201  */
4202 static void
4203 handle_written_jnewblk(jnewblk)
4204 	struct jnewblk *jnewblk;
4205 {
4206 	struct bmsafemap *bmsafemap;
4207 	struct freefrag *freefrag;
4208 	struct freework *freework;
4209 	struct jsegdep *jsegdep;
4210 	struct newblk *newblk;
4211 
4212 	/* Grab the jsegdep. */
4213 	jsegdep = jnewblk->jn_jsegdep;
4214 	jnewblk->jn_jsegdep = NULL;
4215 	if (jnewblk->jn_dep == NULL)
4216 		panic("handle_written_jnewblk: No dependency for the segdep.");
4217 	switch (jnewblk->jn_dep->wk_type) {
4218 	case D_NEWBLK:
4219 	case D_ALLOCDIRECT:
4220 	case D_ALLOCINDIR:
4221 		/*
4222 		 * Add the written block to the bmsafemap so it can
4223 		 * be notified when the bitmap is on disk.
4224 		 */
4225 		newblk = WK_NEWBLK(jnewblk->jn_dep);
4226 		newblk->nb_jnewblk = NULL;
4227 		if ((newblk->nb_state & GOINGAWAY) == 0) {
4228 			bmsafemap = newblk->nb_bmsafemap;
4229 			newblk->nb_state |= ONDEPLIST;
4230 			LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk,
4231 			    nb_deps);
4232 		}
4233 		jwork_insert(&newblk->nb_jwork, jsegdep);
4234 		break;
4235 	case D_FREEFRAG:
4236 		/*
4237 		 * A newblock being removed by a freefrag when replaced by
4238 		 * frag extension.
4239 		 */
4240 		freefrag = WK_FREEFRAG(jnewblk->jn_dep);
4241 		freefrag->ff_jdep = NULL;
4242 		jwork_insert(&freefrag->ff_jwork, jsegdep);
4243 		break;
4244 	case D_FREEWORK:
4245 		/*
4246 		 * A direct block was removed by truncate.
4247 		 */
4248 		freework = WK_FREEWORK(jnewblk->jn_dep);
4249 		freework->fw_jnewblk = NULL;
4250 		jwork_insert(&freework->fw_freeblks->fb_jwork, jsegdep);
4251 		break;
4252 	default:
4253 		panic("handle_written_jnewblk: Unknown type %d.",
4254 		    jnewblk->jn_dep->wk_type);
4255 	}
4256 	jnewblk->jn_dep = NULL;
4257 	free_jnewblk(jnewblk);
4258 }
4259 
4260 /*
4261  * Cancel a jfreefrag that won't be needed, probably due to colliding with
4262  * an in-flight allocation that has not yet been committed.  Divorce us
4263  * from the freefrag and mark it DEPCOMPLETE so that it may be added
4264  * to the worklist.
4265  */
4266 static void
4267 cancel_jfreefrag(jfreefrag)
4268 	struct jfreefrag *jfreefrag;
4269 {
4270 	struct freefrag *freefrag;
4271 
4272 	if (jfreefrag->fr_jsegdep) {
4273 		free_jsegdep(jfreefrag->fr_jsegdep);
4274 		jfreefrag->fr_jsegdep = NULL;
4275 	}
4276 	freefrag = jfreefrag->fr_freefrag;
4277 	jfreefrag->fr_freefrag = NULL;
4278 	free_jfreefrag(jfreefrag);
4279 	freefrag->ff_state |= DEPCOMPLETE;
4280 	CTR1(KTR_SUJ, "cancel_jfreefrag: blkno %jd", freefrag->ff_blkno);
4281 }
4282 
4283 /*
4284  * Free a jfreefrag when the parent freefrag is rendered obsolete.
4285  */
4286 static void
4287 free_jfreefrag(jfreefrag)
4288 	struct jfreefrag *jfreefrag;
4289 {
4290 
4291 	if (jfreefrag->fr_state & INPROGRESS)
4292 		WORKLIST_REMOVE(&jfreefrag->fr_list);
4293 	else if (jfreefrag->fr_state & ONWORKLIST)
4294 		remove_from_journal(&jfreefrag->fr_list);
4295 	if (jfreefrag->fr_freefrag != NULL)
4296 		panic("free_jfreefrag:  Still attached to a freefrag.");
4297 	WORKITEM_FREE(jfreefrag, D_JFREEFRAG);
4298 }
4299 
4300 /*
4301  * Called when the journal write for a jfreefrag completes.  The parent
4302  * freefrag is added to the worklist if this completes its dependencies.
4303  */
4304 static void
4305 handle_written_jfreefrag(jfreefrag)
4306 	struct jfreefrag *jfreefrag;
4307 {
4308 	struct jsegdep *jsegdep;
4309 	struct freefrag *freefrag;
4310 
4311 	/* Grab the jsegdep. */
4312 	jsegdep = jfreefrag->fr_jsegdep;
4313 	jfreefrag->fr_jsegdep = NULL;
4314 	freefrag = jfreefrag->fr_freefrag;
4315 	if (freefrag == NULL)
4316 		panic("handle_written_jfreefrag: No freefrag.");
4317 	freefrag->ff_state |= DEPCOMPLETE;
4318 	freefrag->ff_jdep = NULL;
4319 	jwork_insert(&freefrag->ff_jwork, jsegdep);
4320 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
4321 		add_to_worklist(&freefrag->ff_list, 0);
4322 	jfreefrag->fr_freefrag = NULL;
4323 	free_jfreefrag(jfreefrag);
4324 }
4325 
4326 /*
4327  * Called when the journal write for a jfreeblk completes.  The jfreeblk
4328  * is removed from the freeblks list of pending journal writes and the
4329  * jsegdep is moved to the freeblks jwork to be completed when all blocks
4330  * have been reclaimed.
4331  */
4332 static void
4333 handle_written_jblkdep(jblkdep)
4334 	struct jblkdep *jblkdep;
4335 {
4336 	struct freeblks *freeblks;
4337 	struct jsegdep *jsegdep;
4338 
4339 	/* Grab the jsegdep. */
4340 	jsegdep = jblkdep->jb_jsegdep;
4341 	jblkdep->jb_jsegdep = NULL;
4342 	freeblks = jblkdep->jb_freeblks;
4343 	LIST_REMOVE(jblkdep, jb_deps);
4344 	jwork_insert(&freeblks->fb_jwork, jsegdep);
4345 	/*
4346 	 * If the freeblks is all journaled, we can add it to the worklist.
4347 	 */
4348 	if (LIST_EMPTY(&freeblks->fb_jblkdephd) &&
4349 	    (freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
4350 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
4351 
4352 	free_jblkdep(jblkdep);
4353 }
4354 
4355 static struct jsegdep *
4356 newjsegdep(struct worklist *wk)
4357 {
4358 	struct jsegdep *jsegdep;
4359 
4360 	jsegdep = malloc(sizeof(*jsegdep), M_JSEGDEP, M_SOFTDEP_FLAGS);
4361 	workitem_alloc(&jsegdep->jd_list, D_JSEGDEP, wk->wk_mp);
4362 	jsegdep->jd_seg = NULL;
4363 
4364 	return (jsegdep);
4365 }
4366 
4367 static struct jmvref *
4368 newjmvref(dp, ino, oldoff, newoff)
4369 	struct inode *dp;
4370 	ino_t ino;
4371 	off_t oldoff;
4372 	off_t newoff;
4373 {
4374 	struct jmvref *jmvref;
4375 
4376 	jmvref = malloc(sizeof(*jmvref), M_JMVREF, M_SOFTDEP_FLAGS);
4377 	workitem_alloc(&jmvref->jm_list, D_JMVREF, ITOVFS(dp));
4378 	jmvref->jm_list.wk_state = ATTACHED | DEPCOMPLETE;
4379 	jmvref->jm_parent = dp->i_number;
4380 	jmvref->jm_ino = ino;
4381 	jmvref->jm_oldoff = oldoff;
4382 	jmvref->jm_newoff = newoff;
4383 
4384 	return (jmvref);
4385 }
4386 
4387 /*
4388  * Allocate a new jremref that tracks the removal of ip from dp with the
4389  * directory entry offset of diroff.  Mark the entry as ATTACHED and
4390  * DEPCOMPLETE as we have all the information required for the journal write
4391  * and the directory has already been removed from the buffer.  The caller
4392  * is responsible for linking the jremref into the pagedep and adding it
4393  * to the journal to write.  The MKDIR_PARENT flag is set if we're doing
4394  * a DOTDOT addition so handle_workitem_remove() can properly assign
4395  * the jsegdep when we're done.
4396  */
4397 static struct jremref *
4398 newjremref(struct dirrem *dirrem, struct inode *dp, struct inode *ip,
4399     off_t diroff, nlink_t nlink)
4400 {
4401 	struct jremref *jremref;
4402 
4403 	jremref = malloc(sizeof(*jremref), M_JREMREF, M_SOFTDEP_FLAGS);
4404 	workitem_alloc(&jremref->jr_list, D_JREMREF, ITOVFS(dp));
4405 	jremref->jr_state = ATTACHED;
4406 	newinoref(&jremref->jr_ref, ip->i_number, dp->i_number, diroff,
4407 	   nlink, ip->i_mode);
4408 	jremref->jr_dirrem = dirrem;
4409 
4410 	return (jremref);
4411 }
4412 
4413 static inline void
4414 newinoref(struct inoref *inoref, ino_t ino, ino_t parent, off_t diroff,
4415     nlink_t nlink, uint16_t mode)
4416 {
4417 
4418 	inoref->if_jsegdep = newjsegdep(&inoref->if_list);
4419 	inoref->if_diroff = diroff;
4420 	inoref->if_ino = ino;
4421 	inoref->if_parent = parent;
4422 	inoref->if_nlink = nlink;
4423 	inoref->if_mode = mode;
4424 }
4425 
4426 /*
4427  * Allocate a new jaddref to track the addition of ino to dp at diroff.  The
4428  * directory offset may not be known until later.  The caller is responsible
4429  * adding the entry to the journal when this information is available.  nlink
4430  * should be the link count prior to the addition and mode is only required
4431  * to have the correct FMT.
4432  */
4433 static struct jaddref *
4434 newjaddref(struct inode *dp, ino_t ino, off_t diroff, int16_t nlink,
4435     uint16_t mode)
4436 {
4437 	struct jaddref *jaddref;
4438 
4439 	jaddref = malloc(sizeof(*jaddref), M_JADDREF, M_SOFTDEP_FLAGS);
4440 	workitem_alloc(&jaddref->ja_list, D_JADDREF, ITOVFS(dp));
4441 	jaddref->ja_state = ATTACHED;
4442 	jaddref->ja_mkdir = NULL;
4443 	newinoref(&jaddref->ja_ref, ino, dp->i_number, diroff, nlink, mode);
4444 
4445 	return (jaddref);
4446 }
4447 
4448 /*
4449  * Create a new free dependency for a freework.  The caller is responsible
4450  * for adjusting the reference count when it has the lock held.  The freedep
4451  * will track an outstanding bitmap write that will ultimately clear the
4452  * freework to continue.
4453  */
4454 static struct freedep *
4455 newfreedep(struct freework *freework)
4456 {
4457 	struct freedep *freedep;
4458 
4459 	freedep = malloc(sizeof(*freedep), M_FREEDEP, M_SOFTDEP_FLAGS);
4460 	workitem_alloc(&freedep->fd_list, D_FREEDEP, freework->fw_list.wk_mp);
4461 	freedep->fd_freework = freework;
4462 
4463 	return (freedep);
4464 }
4465 
4466 /*
4467  * Free a freedep structure once the buffer it is linked to is written.  If
4468  * this is the last reference to the freework schedule it for completion.
4469  */
4470 static void
4471 free_freedep(freedep)
4472 	struct freedep *freedep;
4473 {
4474 	struct freework *freework;
4475 
4476 	freework = freedep->fd_freework;
4477 	freework->fw_freeblks->fb_cgwait--;
4478 	if (--freework->fw_ref == 0)
4479 		freework_enqueue(freework);
4480 	WORKITEM_FREE(freedep, D_FREEDEP);
4481 }
4482 
4483 /*
4484  * Allocate a new freework structure that may be a level in an indirect
4485  * when parent is not NULL or a top level block when it is.  The top level
4486  * freework structures are allocated without the per-filesystem lock held
4487  * and before the freeblks is visible outside of softdep_setup_freeblocks().
4488  */
4489 static struct freework *
4490 newfreework(ump, freeblks, parent, lbn, nb, frags, off, journal)
4491 	struct ufsmount *ump;
4492 	struct freeblks *freeblks;
4493 	struct freework *parent;
4494 	ufs_lbn_t lbn;
4495 	ufs2_daddr_t nb;
4496 	int frags;
4497 	int off;
4498 	int journal;
4499 {
4500 	struct freework *freework;
4501 
4502 	freework = malloc(sizeof(*freework), M_FREEWORK, M_SOFTDEP_FLAGS);
4503 	workitem_alloc(&freework->fw_list, D_FREEWORK, freeblks->fb_list.wk_mp);
4504 	freework->fw_state = ATTACHED;
4505 	freework->fw_jnewblk = NULL;
4506 	freework->fw_freeblks = freeblks;
4507 	freework->fw_parent = parent;
4508 	freework->fw_lbn = lbn;
4509 	freework->fw_blkno = nb;
4510 	freework->fw_frags = frags;
4511 	freework->fw_indir = NULL;
4512 	freework->fw_ref = (MOUNTEDSUJ(UFSTOVFS(ump)) == 0 ||
4513 	    lbn >= -UFS_NXADDR) ? 0 : NINDIR(ump->um_fs) + 1;
4514 	freework->fw_start = freework->fw_off = off;
4515 	if (journal)
4516 		newjfreeblk(freeblks, lbn, nb, frags);
4517 	if (parent == NULL) {
4518 		ACQUIRE_LOCK(ump);
4519 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
4520 		freeblks->fb_ref++;
4521 		FREE_LOCK(ump);
4522 	}
4523 
4524 	return (freework);
4525 }
4526 
4527 /*
4528  * Eliminate a jfreeblk for a block that does not need journaling.
4529  */
4530 static void
4531 cancel_jfreeblk(freeblks, blkno)
4532 	struct freeblks *freeblks;
4533 	ufs2_daddr_t blkno;
4534 {
4535 	struct jfreeblk *jfreeblk;
4536 	struct jblkdep *jblkdep;
4537 
4538 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps) {
4539 		if (jblkdep->jb_list.wk_type != D_JFREEBLK)
4540 			continue;
4541 		jfreeblk = WK_JFREEBLK(&jblkdep->jb_list);
4542 		if (jfreeblk->jf_blkno == blkno)
4543 			break;
4544 	}
4545 	if (jblkdep == NULL)
4546 		return;
4547 	CTR1(KTR_SUJ, "cancel_jfreeblk: blkno %jd", blkno);
4548 	free_jsegdep(jblkdep->jb_jsegdep);
4549 	LIST_REMOVE(jblkdep, jb_deps);
4550 	WORKITEM_FREE(jfreeblk, D_JFREEBLK);
4551 }
4552 
4553 /*
4554  * Allocate a new jfreeblk to journal top level block pointer when truncating
4555  * a file.  The caller must add this to the worklist when the per-filesystem
4556  * lock is held.
4557  */
4558 static struct jfreeblk *
4559 newjfreeblk(freeblks, lbn, blkno, frags)
4560 	struct freeblks *freeblks;
4561 	ufs_lbn_t lbn;
4562 	ufs2_daddr_t blkno;
4563 	int frags;
4564 {
4565 	struct jfreeblk *jfreeblk;
4566 
4567 	jfreeblk = malloc(sizeof(*jfreeblk), M_JFREEBLK, M_SOFTDEP_FLAGS);
4568 	workitem_alloc(&jfreeblk->jf_dep.jb_list, D_JFREEBLK,
4569 	    freeblks->fb_list.wk_mp);
4570 	jfreeblk->jf_dep.jb_jsegdep = newjsegdep(&jfreeblk->jf_dep.jb_list);
4571 	jfreeblk->jf_dep.jb_freeblks = freeblks;
4572 	jfreeblk->jf_ino = freeblks->fb_inum;
4573 	jfreeblk->jf_lbn = lbn;
4574 	jfreeblk->jf_blkno = blkno;
4575 	jfreeblk->jf_frags = frags;
4576 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jfreeblk->jf_dep, jb_deps);
4577 
4578 	return (jfreeblk);
4579 }
4580 
4581 /*
4582  * The journal is only prepared to handle full-size block numbers, so we
4583  * have to adjust the record to reflect the change to a full-size block.
4584  * For example, suppose we have a block made up of fragments 8-15 and
4585  * want to free its last two fragments. We are given a request that says:
4586  *     FREEBLK ino=5, blkno=14, lbn=0, frags=2, oldfrags=0
4587  * where frags are the number of fragments to free and oldfrags are the
4588  * number of fragments to keep. To block align it, we have to change it to
4589  * have a valid full-size blkno, so it becomes:
4590  *     FREEBLK ino=5, blkno=8, lbn=0, frags=2, oldfrags=6
4591  */
4592 static void
4593 adjust_newfreework(freeblks, frag_offset)
4594 	struct freeblks *freeblks;
4595 	int frag_offset;
4596 {
4597 	struct jfreeblk *jfreeblk;
4598 
4599 	KASSERT((LIST_FIRST(&freeblks->fb_jblkdephd) != NULL &&
4600 	    LIST_FIRST(&freeblks->fb_jblkdephd)->jb_list.wk_type == D_JFREEBLK),
4601 	    ("adjust_newfreework: Missing freeblks dependency"));
4602 
4603 	jfreeblk = WK_JFREEBLK(LIST_FIRST(&freeblks->fb_jblkdephd));
4604 	jfreeblk->jf_blkno -= frag_offset;
4605 	jfreeblk->jf_frags += frag_offset;
4606 }
4607 
4608 /*
4609  * Allocate a new jtrunc to track a partial truncation.
4610  */
4611 static struct jtrunc *
4612 newjtrunc(freeblks, size, extsize)
4613 	struct freeblks *freeblks;
4614 	off_t size;
4615 	int extsize;
4616 {
4617 	struct jtrunc *jtrunc;
4618 
4619 	jtrunc = malloc(sizeof(*jtrunc), M_JTRUNC, M_SOFTDEP_FLAGS);
4620 	workitem_alloc(&jtrunc->jt_dep.jb_list, D_JTRUNC,
4621 	    freeblks->fb_list.wk_mp);
4622 	jtrunc->jt_dep.jb_jsegdep = newjsegdep(&jtrunc->jt_dep.jb_list);
4623 	jtrunc->jt_dep.jb_freeblks = freeblks;
4624 	jtrunc->jt_ino = freeblks->fb_inum;
4625 	jtrunc->jt_size = size;
4626 	jtrunc->jt_extsize = extsize;
4627 	LIST_INSERT_HEAD(&freeblks->fb_jblkdephd, &jtrunc->jt_dep, jb_deps);
4628 
4629 	return (jtrunc);
4630 }
4631 
4632 /*
4633  * If we're canceling a new bitmap we have to search for another ref
4634  * to move into the bmsafemap dep.  This might be better expressed
4635  * with another structure.
4636  */
4637 static void
4638 move_newblock_dep(jaddref, inodedep)
4639 	struct jaddref *jaddref;
4640 	struct inodedep *inodedep;
4641 {
4642 	struct inoref *inoref;
4643 	struct jaddref *jaddrefn;
4644 
4645 	jaddrefn = NULL;
4646 	for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4647 	    inoref = TAILQ_NEXT(inoref, if_deps)) {
4648 		if ((jaddref->ja_state & NEWBLOCK) &&
4649 		    inoref->if_list.wk_type == D_JADDREF) {
4650 			jaddrefn = (struct jaddref *)inoref;
4651 			break;
4652 		}
4653 	}
4654 	if (jaddrefn == NULL)
4655 		return;
4656 	jaddrefn->ja_state &= ~(ATTACHED | UNDONE);
4657 	jaddrefn->ja_state |= jaddref->ja_state &
4658 	    (ATTACHED | UNDONE | NEWBLOCK);
4659 	jaddref->ja_state &= ~(ATTACHED | UNDONE | NEWBLOCK);
4660 	jaddref->ja_state |= ATTACHED;
4661 	LIST_REMOVE(jaddref, ja_bmdeps);
4662 	LIST_INSERT_HEAD(&inodedep->id_bmsafemap->sm_jaddrefhd, jaddrefn,
4663 	    ja_bmdeps);
4664 }
4665 
4666 /*
4667  * Cancel a jaddref either before it has been written or while it is being
4668  * written.  This happens when a link is removed before the add reaches
4669  * the disk.  The jaddref dependency is kept linked into the bmsafemap
4670  * and inode to prevent the link count or bitmap from reaching the disk
4671  * until handle_workitem_remove() re-adjusts the counts and bitmaps as
4672  * required.
4673  *
4674  * Returns 1 if the canceled addref requires journaling of the remove and
4675  * 0 otherwise.
4676  */
4677 static int
4678 cancel_jaddref(jaddref, inodedep, wkhd)
4679 	struct jaddref *jaddref;
4680 	struct inodedep *inodedep;
4681 	struct workhead *wkhd;
4682 {
4683 	struct inoref *inoref;
4684 	struct jsegdep *jsegdep;
4685 	int needsj;
4686 
4687 	KASSERT((jaddref->ja_state & COMPLETE) == 0,
4688 	    ("cancel_jaddref: Canceling complete jaddref"));
4689 	if (jaddref->ja_state & (INPROGRESS | COMPLETE))
4690 		needsj = 1;
4691 	else
4692 		needsj = 0;
4693 	if (inodedep == NULL)
4694 		if (inodedep_lookup(jaddref->ja_list.wk_mp, jaddref->ja_ino,
4695 		    0, &inodedep) == 0)
4696 			panic("cancel_jaddref: Lost inodedep");
4697 	/*
4698 	 * We must adjust the nlink of any reference operation that follows
4699 	 * us so that it is consistent with the in-memory reference.  This
4700 	 * ensures that inode nlink rollbacks always have the correct link.
4701 	 */
4702 	if (needsj == 0) {
4703 		for (inoref = TAILQ_NEXT(&jaddref->ja_ref, if_deps); inoref;
4704 		    inoref = TAILQ_NEXT(inoref, if_deps)) {
4705 			if (inoref->if_state & GOINGAWAY)
4706 				break;
4707 			inoref->if_nlink--;
4708 		}
4709 	}
4710 	jsegdep = inoref_jseg(&jaddref->ja_ref);
4711 	if (jaddref->ja_state & NEWBLOCK)
4712 		move_newblock_dep(jaddref, inodedep);
4713 	wake_worklist(&jaddref->ja_list);
4714 	jaddref->ja_mkdir = NULL;
4715 	if (jaddref->ja_state & INPROGRESS) {
4716 		jaddref->ja_state &= ~INPROGRESS;
4717 		WORKLIST_REMOVE(&jaddref->ja_list);
4718 		jwork_insert(wkhd, jsegdep);
4719 	} else {
4720 		free_jsegdep(jsegdep);
4721 		if (jaddref->ja_state & DEPCOMPLETE)
4722 			remove_from_journal(&jaddref->ja_list);
4723 	}
4724 	jaddref->ja_state |= (GOINGAWAY | DEPCOMPLETE);
4725 	/*
4726 	 * Leave NEWBLOCK jaddrefs on the inodedep so handle_workitem_remove
4727 	 * can arrange for them to be freed with the bitmap.  Otherwise we
4728 	 * no longer need this addref attached to the inoreflst and it
4729 	 * will incorrectly adjust nlink if we leave it.
4730 	 */
4731 	if ((jaddref->ja_state & NEWBLOCK) == 0) {
4732 		TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
4733 		    if_deps);
4734 		jaddref->ja_state |= COMPLETE;
4735 		free_jaddref(jaddref);
4736 		return (needsj);
4737 	}
4738 	/*
4739 	 * Leave the head of the list for jsegdeps for fast merging.
4740 	 */
4741 	if (LIST_FIRST(wkhd) != NULL) {
4742 		jaddref->ja_state |= ONWORKLIST;
4743 		LIST_INSERT_AFTER(LIST_FIRST(wkhd), &jaddref->ja_list, wk_list);
4744 	} else
4745 		WORKLIST_INSERT(wkhd, &jaddref->ja_list);
4746 
4747 	return (needsj);
4748 }
4749 
4750 /*
4751  * Attempt to free a jaddref structure when some work completes.  This
4752  * should only succeed once the entry is written and all dependencies have
4753  * been notified.
4754  */
4755 static void
4756 free_jaddref(jaddref)
4757 	struct jaddref *jaddref;
4758 {
4759 
4760 	if ((jaddref->ja_state & ALLCOMPLETE) != ALLCOMPLETE)
4761 		return;
4762 	if (jaddref->ja_ref.if_jsegdep)
4763 		panic("free_jaddref: segdep attached to jaddref %p(0x%X)\n",
4764 		    jaddref, jaddref->ja_state);
4765 	if (jaddref->ja_state & NEWBLOCK)
4766 		LIST_REMOVE(jaddref, ja_bmdeps);
4767 	if (jaddref->ja_state & (INPROGRESS | ONWORKLIST))
4768 		panic("free_jaddref: Bad state %p(0x%X)",
4769 		    jaddref, jaddref->ja_state);
4770 	if (jaddref->ja_mkdir != NULL)
4771 		panic("free_jaddref: Work pending, 0x%X\n", jaddref->ja_state);
4772 	WORKITEM_FREE(jaddref, D_JADDREF);
4773 }
4774 
4775 /*
4776  * Free a jremref structure once it has been written or discarded.
4777  */
4778 static void
4779 free_jremref(jremref)
4780 	struct jremref *jremref;
4781 {
4782 
4783 	if (jremref->jr_ref.if_jsegdep)
4784 		free_jsegdep(jremref->jr_ref.if_jsegdep);
4785 	if (jremref->jr_state & INPROGRESS)
4786 		panic("free_jremref: IO still pending");
4787 	WORKITEM_FREE(jremref, D_JREMREF);
4788 }
4789 
4790 /*
4791  * Free a jnewblk structure.
4792  */
4793 static void
4794 free_jnewblk(jnewblk)
4795 	struct jnewblk *jnewblk;
4796 {
4797 
4798 	if ((jnewblk->jn_state & ALLCOMPLETE) != ALLCOMPLETE)
4799 		return;
4800 	LIST_REMOVE(jnewblk, jn_deps);
4801 	if (jnewblk->jn_dep != NULL)
4802 		panic("free_jnewblk: Dependency still attached.");
4803 	WORKITEM_FREE(jnewblk, D_JNEWBLK);
4804 }
4805 
4806 /*
4807  * Cancel a jnewblk which has been been made redundant by frag extension.
4808  */
4809 static void
4810 cancel_jnewblk(jnewblk, wkhd)
4811 	struct jnewblk *jnewblk;
4812 	struct workhead *wkhd;
4813 {
4814 	struct jsegdep *jsegdep;
4815 
4816 	CTR1(KTR_SUJ, "cancel_jnewblk: blkno %jd", jnewblk->jn_blkno);
4817 	jsegdep = jnewblk->jn_jsegdep;
4818 	if (jnewblk->jn_jsegdep == NULL || jnewblk->jn_dep == NULL)
4819 		panic("cancel_jnewblk: Invalid state");
4820 	jnewblk->jn_jsegdep  = NULL;
4821 	jnewblk->jn_dep = NULL;
4822 	jnewblk->jn_state |= GOINGAWAY;
4823 	if (jnewblk->jn_state & INPROGRESS) {
4824 		jnewblk->jn_state &= ~INPROGRESS;
4825 		WORKLIST_REMOVE(&jnewblk->jn_list);
4826 		jwork_insert(wkhd, jsegdep);
4827 	} else {
4828 		free_jsegdep(jsegdep);
4829 		remove_from_journal(&jnewblk->jn_list);
4830 	}
4831 	wake_worklist(&jnewblk->jn_list);
4832 	WORKLIST_INSERT(wkhd, &jnewblk->jn_list);
4833 }
4834 
4835 static void
4836 free_jblkdep(jblkdep)
4837 	struct jblkdep *jblkdep;
4838 {
4839 
4840 	if (jblkdep->jb_list.wk_type == D_JFREEBLK)
4841 		WORKITEM_FREE(jblkdep, D_JFREEBLK);
4842 	else if (jblkdep->jb_list.wk_type == D_JTRUNC)
4843 		WORKITEM_FREE(jblkdep, D_JTRUNC);
4844 	else
4845 		panic("free_jblkdep: Unexpected type %s",
4846 		    TYPENAME(jblkdep->jb_list.wk_type));
4847 }
4848 
4849 /*
4850  * Free a single jseg once it is no longer referenced in memory or on
4851  * disk.  Reclaim journal blocks and dependencies waiting for the segment
4852  * to disappear.
4853  */
4854 static void
4855 free_jseg(jseg, jblocks)
4856 	struct jseg *jseg;
4857 	struct jblocks *jblocks;
4858 {
4859 	struct freework *freework;
4860 
4861 	/*
4862 	 * Free freework structures that were lingering to indicate freed
4863 	 * indirect blocks that forced journal write ordering on reallocate.
4864 	 */
4865 	while ((freework = LIST_FIRST(&jseg->js_indirs)) != NULL)
4866 		indirblk_remove(freework);
4867 	if (jblocks->jb_oldestseg == jseg)
4868 		jblocks->jb_oldestseg = TAILQ_NEXT(jseg, js_next);
4869 	TAILQ_REMOVE(&jblocks->jb_segs, jseg, js_next);
4870 	jblocks_free(jblocks, jseg->js_list.wk_mp, jseg->js_size);
4871 	KASSERT(LIST_EMPTY(&jseg->js_entries),
4872 	    ("free_jseg: Freed jseg has valid entries."));
4873 	WORKITEM_FREE(jseg, D_JSEG);
4874 }
4875 
4876 /*
4877  * Free all jsegs that meet the criteria for being reclaimed and update
4878  * oldestseg.
4879  */
4880 static void
4881 free_jsegs(jblocks)
4882 	struct jblocks *jblocks;
4883 {
4884 	struct jseg *jseg;
4885 
4886 	/*
4887 	 * Free only those jsegs which have none allocated before them to
4888 	 * preserve the journal space ordering.
4889 	 */
4890 	while ((jseg = TAILQ_FIRST(&jblocks->jb_segs)) != NULL) {
4891 		/*
4892 		 * Only reclaim space when nothing depends on this journal
4893 		 * set and another set has written that it is no longer
4894 		 * valid.
4895 		 */
4896 		if (jseg->js_refs != 0) {
4897 			jblocks->jb_oldestseg = jseg;
4898 			return;
4899 		}
4900 		if ((jseg->js_state & ALLCOMPLETE) != ALLCOMPLETE)
4901 			break;
4902 		if (jseg->js_seq > jblocks->jb_oldestwrseq)
4903 			break;
4904 		/*
4905 		 * We can free jsegs that didn't write entries when
4906 		 * oldestwrseq == js_seq.
4907 		 */
4908 		if (jseg->js_seq == jblocks->jb_oldestwrseq &&
4909 		    jseg->js_cnt != 0)
4910 			break;
4911 		free_jseg(jseg, jblocks);
4912 	}
4913 	/*
4914 	 * If we exited the loop above we still must discover the
4915 	 * oldest valid segment.
4916 	 */
4917 	if (jseg)
4918 		for (jseg = jblocks->jb_oldestseg; jseg != NULL;
4919 		     jseg = TAILQ_NEXT(jseg, js_next))
4920 			if (jseg->js_refs != 0)
4921 				break;
4922 	jblocks->jb_oldestseg = jseg;
4923 	/*
4924 	 * The journal has no valid records but some jsegs may still be
4925 	 * waiting on oldestwrseq to advance.  We force a small record
4926 	 * out to permit these lingering records to be reclaimed.
4927 	 */
4928 	if (jblocks->jb_oldestseg == NULL && !TAILQ_EMPTY(&jblocks->jb_segs))
4929 		jblocks->jb_needseg = 1;
4930 }
4931 
4932 /*
4933  * Release one reference to a jseg and free it if the count reaches 0.  This
4934  * should eventually reclaim journal space as well.
4935  */
4936 static void
4937 rele_jseg(jseg)
4938 	struct jseg *jseg;
4939 {
4940 
4941 	KASSERT(jseg->js_refs > 0,
4942 	    ("free_jseg: Invalid refcnt %d", jseg->js_refs));
4943 	if (--jseg->js_refs != 0)
4944 		return;
4945 	free_jsegs(jseg->js_jblocks);
4946 }
4947 
4948 /*
4949  * Release a jsegdep and decrement the jseg count.
4950  */
4951 static void
4952 free_jsegdep(jsegdep)
4953 	struct jsegdep *jsegdep;
4954 {
4955 
4956 	if (jsegdep->jd_seg)
4957 		rele_jseg(jsegdep->jd_seg);
4958 	WORKITEM_FREE(jsegdep, D_JSEGDEP);
4959 }
4960 
4961 /*
4962  * Wait for a journal item to make it to disk.  Initiate journal processing
4963  * if required.
4964  */
4965 static int
4966 jwait(wk, waitfor)
4967 	struct worklist *wk;
4968 	int waitfor;
4969 {
4970 
4971 	LOCK_OWNED(VFSTOUFS(wk->wk_mp));
4972 	/*
4973 	 * Blocking journal waits cause slow synchronous behavior.  Record
4974 	 * stats on the frequency of these blocking operations.
4975 	 */
4976 	if (waitfor == MNT_WAIT) {
4977 		stat_journal_wait++;
4978 		switch (wk->wk_type) {
4979 		case D_JREMREF:
4980 		case D_JMVREF:
4981 			stat_jwait_filepage++;
4982 			break;
4983 		case D_JTRUNC:
4984 		case D_JFREEBLK:
4985 			stat_jwait_freeblks++;
4986 			break;
4987 		case D_JNEWBLK:
4988 			stat_jwait_newblk++;
4989 			break;
4990 		case D_JADDREF:
4991 			stat_jwait_inode++;
4992 			break;
4993 		default:
4994 			break;
4995 		}
4996 	}
4997 	/*
4998 	 * If IO has not started we process the journal.  We can't mark the
4999 	 * worklist item as IOWAITING because we drop the lock while
5000 	 * processing the journal and the worklist entry may be freed after
5001 	 * this point.  The caller may call back in and re-issue the request.
5002 	 */
5003 	if ((wk->wk_state & INPROGRESS) == 0) {
5004 		softdep_process_journal(wk->wk_mp, wk, waitfor);
5005 		if (waitfor != MNT_WAIT)
5006 			return (EBUSY);
5007 		return (0);
5008 	}
5009 	if (waitfor != MNT_WAIT)
5010 		return (EBUSY);
5011 	wait_worklist(wk, "jwait");
5012 	return (0);
5013 }
5014 
5015 /*
5016  * Lookup an inodedep based on an inode pointer and set the nlinkdelta as
5017  * appropriate.  This is a convenience function to reduce duplicate code
5018  * for the setup and revert functions below.
5019  */
5020 static struct inodedep *
5021 inodedep_lookup_ip(ip)
5022 	struct inode *ip;
5023 {
5024 	struct inodedep *inodedep;
5025 
5026 	KASSERT(ip->i_nlink >= ip->i_effnlink,
5027 	    ("inodedep_lookup_ip: bad delta"));
5028 	(void) inodedep_lookup(ITOVFS(ip), ip->i_number, DEPALLOC,
5029 	    &inodedep);
5030 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
5031 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
5032 
5033 	return (inodedep);
5034 }
5035 
5036 /*
5037  * Called prior to creating a new inode and linking it to a directory.  The
5038  * jaddref structure must already be allocated by softdep_setup_inomapdep
5039  * and it is discovered here so we can initialize the mode and update
5040  * nlinkdelta.
5041  */
5042 void
5043 softdep_setup_create(dp, ip)
5044 	struct inode *dp;
5045 	struct inode *ip;
5046 {
5047 	struct inodedep *inodedep;
5048 	struct jaddref *jaddref;
5049 	struct vnode *dvp;
5050 
5051 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5052 	    ("softdep_setup_create called on non-softdep filesystem"));
5053 	KASSERT(ip->i_nlink == 1,
5054 	    ("softdep_setup_create: Invalid link count."));
5055 	dvp = ITOV(dp);
5056 	ACQUIRE_LOCK(ITOUMP(dp));
5057 	inodedep = inodedep_lookup_ip(ip);
5058 	if (DOINGSUJ(dvp)) {
5059 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5060 		    inoreflst);
5061 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
5062 		    ("softdep_setup_create: No addref structure present."));
5063 	}
5064 	FREE_LOCK(ITOUMP(dp));
5065 }
5066 
5067 /*
5068  * Create a jaddref structure to track the addition of a DOTDOT link when
5069  * we are reparenting an inode as part of a rename.  This jaddref will be
5070  * found by softdep_setup_directory_change.  Adjusts nlinkdelta for
5071  * non-journaling softdep.
5072  */
5073 void
5074 softdep_setup_dotdot_link(dp, ip)
5075 	struct inode *dp;
5076 	struct inode *ip;
5077 {
5078 	struct inodedep *inodedep;
5079 	struct jaddref *jaddref;
5080 	struct vnode *dvp;
5081 
5082 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5083 	    ("softdep_setup_dotdot_link called on non-softdep filesystem"));
5084 	dvp = ITOV(dp);
5085 	jaddref = NULL;
5086 	/*
5087 	 * We don't set MKDIR_PARENT as this is not tied to a mkdir and
5088 	 * is used as a normal link would be.
5089 	 */
5090 	if (DOINGSUJ(dvp))
5091 		jaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5092 		    dp->i_effnlink - 1, dp->i_mode);
5093 	ACQUIRE_LOCK(ITOUMP(dp));
5094 	inodedep = inodedep_lookup_ip(dp);
5095 	if (jaddref)
5096 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5097 		    if_deps);
5098 	FREE_LOCK(ITOUMP(dp));
5099 }
5100 
5101 /*
5102  * Create a jaddref structure to track a new link to an inode.  The directory
5103  * offset is not known until softdep_setup_directory_add or
5104  * softdep_setup_directory_change.  Adjusts nlinkdelta for non-journaling
5105  * softdep.
5106  */
5107 void
5108 softdep_setup_link(dp, ip)
5109 	struct inode *dp;
5110 	struct inode *ip;
5111 {
5112 	struct inodedep *inodedep;
5113 	struct jaddref *jaddref;
5114 	struct vnode *dvp;
5115 
5116 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5117 	    ("softdep_setup_link called on non-softdep filesystem"));
5118 	dvp = ITOV(dp);
5119 	jaddref = NULL;
5120 	if (DOINGSUJ(dvp))
5121 		jaddref = newjaddref(dp, ip->i_number, 0, ip->i_effnlink - 1,
5122 		    ip->i_mode);
5123 	ACQUIRE_LOCK(ITOUMP(dp));
5124 	inodedep = inodedep_lookup_ip(ip);
5125 	if (jaddref)
5126 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5127 		    if_deps);
5128 	FREE_LOCK(ITOUMP(dp));
5129 }
5130 
5131 /*
5132  * Called to create the jaddref structures to track . and .. references as
5133  * well as lookup and further initialize the incomplete jaddref created
5134  * by softdep_setup_inomapdep when the inode was allocated.  Adjusts
5135  * nlinkdelta for non-journaling softdep.
5136  */
5137 void
5138 softdep_setup_mkdir(dp, ip)
5139 	struct inode *dp;
5140 	struct inode *ip;
5141 {
5142 	struct inodedep *inodedep;
5143 	struct jaddref *dotdotaddref;
5144 	struct jaddref *dotaddref;
5145 	struct jaddref *jaddref;
5146 	struct vnode *dvp;
5147 
5148 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5149 	    ("softdep_setup_mkdir called on non-softdep filesystem"));
5150 	dvp = ITOV(dp);
5151 	dotaddref = dotdotaddref = NULL;
5152 	if (DOINGSUJ(dvp)) {
5153 		dotaddref = newjaddref(ip, ip->i_number, DOT_OFFSET, 1,
5154 		    ip->i_mode);
5155 		dotaddref->ja_state |= MKDIR_BODY;
5156 		dotdotaddref = newjaddref(ip, dp->i_number, DOTDOT_OFFSET,
5157 		    dp->i_effnlink - 1, dp->i_mode);
5158 		dotdotaddref->ja_state |= MKDIR_PARENT;
5159 	}
5160 	ACQUIRE_LOCK(ITOUMP(dp));
5161 	inodedep = inodedep_lookup_ip(ip);
5162 	if (DOINGSUJ(dvp)) {
5163 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5164 		    inoreflst);
5165 		KASSERT(jaddref != NULL,
5166 		    ("softdep_setup_mkdir: No addref structure present."));
5167 		KASSERT(jaddref->ja_parent == dp->i_number,
5168 		    ("softdep_setup_mkdir: bad parent %ju",
5169 		    (uintmax_t)jaddref->ja_parent));
5170 		TAILQ_INSERT_BEFORE(&jaddref->ja_ref, &dotaddref->ja_ref,
5171 		    if_deps);
5172 	}
5173 	inodedep = inodedep_lookup_ip(dp);
5174 	if (DOINGSUJ(dvp))
5175 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst,
5176 		    &dotdotaddref->ja_ref, if_deps);
5177 	FREE_LOCK(ITOUMP(dp));
5178 }
5179 
5180 /*
5181  * Called to track nlinkdelta of the inode and parent directories prior to
5182  * unlinking a directory.
5183  */
5184 void
5185 softdep_setup_rmdir(dp, ip)
5186 	struct inode *dp;
5187 	struct inode *ip;
5188 {
5189 	struct vnode *dvp;
5190 
5191 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5192 	    ("softdep_setup_rmdir called on non-softdep filesystem"));
5193 	dvp = ITOV(dp);
5194 	ACQUIRE_LOCK(ITOUMP(dp));
5195 	(void) inodedep_lookup_ip(ip);
5196 	(void) inodedep_lookup_ip(dp);
5197 	FREE_LOCK(ITOUMP(dp));
5198 }
5199 
5200 /*
5201  * Called to track nlinkdelta of the inode and parent directories prior to
5202  * unlink.
5203  */
5204 void
5205 softdep_setup_unlink(dp, ip)
5206 	struct inode *dp;
5207 	struct inode *ip;
5208 {
5209 	struct vnode *dvp;
5210 
5211 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5212 	    ("softdep_setup_unlink called on non-softdep filesystem"));
5213 	dvp = ITOV(dp);
5214 	ACQUIRE_LOCK(ITOUMP(dp));
5215 	(void) inodedep_lookup_ip(ip);
5216 	(void) inodedep_lookup_ip(dp);
5217 	FREE_LOCK(ITOUMP(dp));
5218 }
5219 
5220 /*
5221  * Called to release the journal structures created by a failed non-directory
5222  * creation.  Adjusts nlinkdelta for non-journaling softdep.
5223  */
5224 void
5225 softdep_revert_create(dp, ip)
5226 	struct inode *dp;
5227 	struct inode *ip;
5228 {
5229 	struct inodedep *inodedep;
5230 	struct jaddref *jaddref;
5231 	struct vnode *dvp;
5232 
5233 	KASSERT(MOUNTEDSOFTDEP(ITOVFS((dp))) != 0,
5234 	    ("softdep_revert_create called on non-softdep filesystem"));
5235 	dvp = ITOV(dp);
5236 	ACQUIRE_LOCK(ITOUMP(dp));
5237 	inodedep = inodedep_lookup_ip(ip);
5238 	if (DOINGSUJ(dvp)) {
5239 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5240 		    inoreflst);
5241 		KASSERT(jaddref->ja_parent == dp->i_number,
5242 		    ("softdep_revert_create: addref parent mismatch"));
5243 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5244 	}
5245 	FREE_LOCK(ITOUMP(dp));
5246 }
5247 
5248 /*
5249  * Called to release the journal structures created by a failed link
5250  * addition.  Adjusts nlinkdelta for non-journaling softdep.
5251  */
5252 void
5253 softdep_revert_link(dp, ip)
5254 	struct inode *dp;
5255 	struct inode *ip;
5256 {
5257 	struct inodedep *inodedep;
5258 	struct jaddref *jaddref;
5259 	struct vnode *dvp;
5260 
5261 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5262 	    ("softdep_revert_link called on non-softdep filesystem"));
5263 	dvp = ITOV(dp);
5264 	ACQUIRE_LOCK(ITOUMP(dp));
5265 	inodedep = inodedep_lookup_ip(ip);
5266 	if (DOINGSUJ(dvp)) {
5267 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5268 		    inoreflst);
5269 		KASSERT(jaddref->ja_parent == dp->i_number,
5270 		    ("softdep_revert_link: addref parent mismatch"));
5271 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5272 	}
5273 	FREE_LOCK(ITOUMP(dp));
5274 }
5275 
5276 /*
5277  * Called to release the journal structures created by a failed mkdir
5278  * attempt.  Adjusts nlinkdelta for non-journaling softdep.
5279  */
5280 void
5281 softdep_revert_mkdir(dp, ip)
5282 	struct inode *dp;
5283 	struct inode *ip;
5284 {
5285 	struct inodedep *inodedep;
5286 	struct jaddref *jaddref;
5287 	struct jaddref *dotaddref;
5288 	struct vnode *dvp;
5289 
5290 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5291 	    ("softdep_revert_mkdir called on non-softdep filesystem"));
5292 	dvp = ITOV(dp);
5293 
5294 	ACQUIRE_LOCK(ITOUMP(dp));
5295 	inodedep = inodedep_lookup_ip(dp);
5296 	if (DOINGSUJ(dvp)) {
5297 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5298 		    inoreflst);
5299 		KASSERT(jaddref->ja_parent == ip->i_number,
5300 		    ("softdep_revert_mkdir: dotdot addref parent mismatch"));
5301 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5302 	}
5303 	inodedep = inodedep_lookup_ip(ip);
5304 	if (DOINGSUJ(dvp)) {
5305 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
5306 		    inoreflst);
5307 		KASSERT(jaddref->ja_parent == dp->i_number,
5308 		    ("softdep_revert_mkdir: addref parent mismatch"));
5309 		dotaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
5310 		    inoreflst, if_deps);
5311 		cancel_jaddref(jaddref, inodedep, &inodedep->id_inowait);
5312 		KASSERT(dotaddref->ja_parent == ip->i_number,
5313 		    ("softdep_revert_mkdir: dot addref parent mismatch"));
5314 		cancel_jaddref(dotaddref, inodedep, &inodedep->id_inowait);
5315 	}
5316 	FREE_LOCK(ITOUMP(dp));
5317 }
5318 
5319 /*
5320  * Called to correct nlinkdelta after a failed rmdir.
5321  */
5322 void
5323 softdep_revert_rmdir(dp, ip)
5324 	struct inode *dp;
5325 	struct inode *ip;
5326 {
5327 
5328 	KASSERT(MOUNTEDSOFTDEP(ITOVFS(dp)) != 0,
5329 	    ("softdep_revert_rmdir called on non-softdep filesystem"));
5330 	ACQUIRE_LOCK(ITOUMP(dp));
5331 	(void) inodedep_lookup_ip(ip);
5332 	(void) inodedep_lookup_ip(dp);
5333 	FREE_LOCK(ITOUMP(dp));
5334 }
5335 
5336 /*
5337  * Protecting the freemaps (or bitmaps).
5338  *
5339  * To eliminate the need to execute fsck before mounting a filesystem
5340  * after a power failure, one must (conservatively) guarantee that the
5341  * on-disk copy of the bitmaps never indicate that a live inode or block is
5342  * free.  So, when a block or inode is allocated, the bitmap should be
5343  * updated (on disk) before any new pointers.  When a block or inode is
5344  * freed, the bitmap should not be updated until all pointers have been
5345  * reset.  The latter dependency is handled by the delayed de-allocation
5346  * approach described below for block and inode de-allocation.  The former
5347  * dependency is handled by calling the following procedure when a block or
5348  * inode is allocated. When an inode is allocated an "inodedep" is created
5349  * with its DEPCOMPLETE flag cleared until its bitmap is written to disk.
5350  * Each "inodedep" is also inserted into the hash indexing structure so
5351  * that any additional link additions can be made dependent on the inode
5352  * allocation.
5353  *
5354  * The ufs filesystem maintains a number of free block counts (e.g., per
5355  * cylinder group, per cylinder and per <cylinder, rotational position> pair)
5356  * in addition to the bitmaps.  These counts are used to improve efficiency
5357  * during allocation and therefore must be consistent with the bitmaps.
5358  * There is no convenient way to guarantee post-crash consistency of these
5359  * counts with simple update ordering, for two main reasons: (1) The counts
5360  * and bitmaps for a single cylinder group block are not in the same disk
5361  * sector.  If a disk write is interrupted (e.g., by power failure), one may
5362  * be written and the other not.  (2) Some of the counts are located in the
5363  * superblock rather than the cylinder group block. So, we focus our soft
5364  * updates implementation on protecting the bitmaps. When mounting a
5365  * filesystem, we recompute the auxiliary counts from the bitmaps.
5366  */
5367 
5368 /*
5369  * Called just after updating the cylinder group block to allocate an inode.
5370  */
5371 void
5372 softdep_setup_inomapdep(bp, ip, newinum, mode)
5373 	struct buf *bp;		/* buffer for cylgroup block with inode map */
5374 	struct inode *ip;	/* inode related to allocation */
5375 	ino_t newinum;		/* new inode number being allocated */
5376 	int mode;
5377 {
5378 	struct inodedep *inodedep;
5379 	struct bmsafemap *bmsafemap;
5380 	struct jaddref *jaddref;
5381 	struct mount *mp;
5382 	struct fs *fs;
5383 
5384 	mp = ITOVFS(ip);
5385 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5386 	    ("softdep_setup_inomapdep called on non-softdep filesystem"));
5387 	fs = VFSTOUFS(mp)->um_fs;
5388 	jaddref = NULL;
5389 
5390 	/*
5391 	 * Allocate the journal reference add structure so that the bitmap
5392 	 * can be dependent on it.
5393 	 */
5394 	if (MOUNTEDSUJ(mp)) {
5395 		jaddref = newjaddref(ip, newinum, 0, 0, mode);
5396 		jaddref->ja_state |= NEWBLOCK;
5397 	}
5398 
5399 	/*
5400 	 * Create a dependency for the newly allocated inode.
5401 	 * Panic if it already exists as something is seriously wrong.
5402 	 * Otherwise add it to the dependency list for the buffer holding
5403 	 * the cylinder group map from which it was allocated.
5404 	 *
5405 	 * We have to preallocate a bmsafemap entry in case it is needed
5406 	 * in bmsafemap_lookup since once we allocate the inodedep, we
5407 	 * have to finish initializing it before we can FREE_LOCK().
5408 	 * By preallocating, we avoid FREE_LOCK() while doing a malloc
5409 	 * in bmsafemap_lookup. We cannot call bmsafemap_lookup before
5410 	 * creating the inodedep as it can be freed during the time
5411 	 * that we FREE_LOCK() while allocating the inodedep. We must
5412 	 * call workitem_alloc() before entering the locked section as
5413 	 * it also acquires the lock and we must avoid trying doing so
5414 	 * recursively.
5415 	 */
5416 	bmsafemap = malloc(sizeof(struct bmsafemap),
5417 	    M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5418 	workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5419 	ACQUIRE_LOCK(ITOUMP(ip));
5420 	if ((inodedep_lookup(mp, newinum, DEPALLOC, &inodedep)))
5421 		panic("softdep_setup_inomapdep: dependency %p for new"
5422 		    "inode already exists", inodedep);
5423 	bmsafemap = bmsafemap_lookup(mp, bp, ino_to_cg(fs, newinum), bmsafemap);
5424 	if (jaddref) {
5425 		LIST_INSERT_HEAD(&bmsafemap->sm_jaddrefhd, jaddref, ja_bmdeps);
5426 		TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jaddref->ja_ref,
5427 		    if_deps);
5428 	} else {
5429 		inodedep->id_state |= ONDEPLIST;
5430 		LIST_INSERT_HEAD(&bmsafemap->sm_inodedephd, inodedep, id_deps);
5431 	}
5432 	inodedep->id_bmsafemap = bmsafemap;
5433 	inodedep->id_state &= ~DEPCOMPLETE;
5434 	FREE_LOCK(ITOUMP(ip));
5435 }
5436 
5437 /*
5438  * Called just after updating the cylinder group block to
5439  * allocate block or fragment.
5440  */
5441 void
5442 softdep_setup_blkmapdep(bp, mp, newblkno, frags, oldfrags)
5443 	struct buf *bp;		/* buffer for cylgroup block with block map */
5444 	struct mount *mp;	/* filesystem doing allocation */
5445 	ufs2_daddr_t newblkno;	/* number of newly allocated block */
5446 	int frags;		/* Number of fragments. */
5447 	int oldfrags;		/* Previous number of fragments for extend. */
5448 {
5449 	struct newblk *newblk;
5450 	struct bmsafemap *bmsafemap;
5451 	struct jnewblk *jnewblk;
5452 	struct ufsmount *ump;
5453 	struct fs *fs;
5454 
5455 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5456 	    ("softdep_setup_blkmapdep called on non-softdep filesystem"));
5457 	ump = VFSTOUFS(mp);
5458 	fs = ump->um_fs;
5459 	jnewblk = NULL;
5460 	/*
5461 	 * Create a dependency for the newly allocated block.
5462 	 * Add it to the dependency list for the buffer holding
5463 	 * the cylinder group map from which it was allocated.
5464 	 */
5465 	if (MOUNTEDSUJ(mp)) {
5466 		jnewblk = malloc(sizeof(*jnewblk), M_JNEWBLK, M_SOFTDEP_FLAGS);
5467 		workitem_alloc(&jnewblk->jn_list, D_JNEWBLK, mp);
5468 		jnewblk->jn_jsegdep = newjsegdep(&jnewblk->jn_list);
5469 		jnewblk->jn_state = ATTACHED;
5470 		jnewblk->jn_blkno = newblkno;
5471 		jnewblk->jn_frags = frags;
5472 		jnewblk->jn_oldfrags = oldfrags;
5473 #ifdef INVARIANTS
5474 		{
5475 			struct cg *cgp;
5476 			uint8_t *blksfree;
5477 			long bno;
5478 			int i;
5479 
5480 			cgp = (struct cg *)bp->b_data;
5481 			blksfree = cg_blksfree(cgp);
5482 			bno = dtogd(fs, jnewblk->jn_blkno);
5483 			for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags;
5484 			    i++) {
5485 				if (isset(blksfree, bno + i))
5486 					panic("softdep_setup_blkmapdep: "
5487 					    "free fragment %d from %d-%d "
5488 					    "state 0x%X dep %p", i,
5489 					    jnewblk->jn_oldfrags,
5490 					    jnewblk->jn_frags,
5491 					    jnewblk->jn_state,
5492 					    jnewblk->jn_dep);
5493 			}
5494 		}
5495 #endif
5496 	}
5497 
5498 	CTR3(KTR_SUJ,
5499 	    "softdep_setup_blkmapdep: blkno %jd frags %d oldfrags %d",
5500 	    newblkno, frags, oldfrags);
5501 	ACQUIRE_LOCK(ump);
5502 	if (newblk_lookup(mp, newblkno, DEPALLOC, &newblk) != 0)
5503 		panic("softdep_setup_blkmapdep: found block");
5504 	newblk->nb_bmsafemap = bmsafemap = bmsafemap_lookup(mp, bp,
5505 	    dtog(fs, newblkno), NULL);
5506 	if (jnewblk) {
5507 		jnewblk->jn_dep = (struct worklist *)newblk;
5508 		LIST_INSERT_HEAD(&bmsafemap->sm_jnewblkhd, jnewblk, jn_deps);
5509 	} else {
5510 		newblk->nb_state |= ONDEPLIST;
5511 		LIST_INSERT_HEAD(&bmsafemap->sm_newblkhd, newblk, nb_deps);
5512 	}
5513 	newblk->nb_bmsafemap = bmsafemap;
5514 	newblk->nb_jnewblk = jnewblk;
5515 	FREE_LOCK(ump);
5516 }
5517 
5518 #define	BMSAFEMAP_HASH(ump, cg) \
5519       (&(ump)->bmsafemap_hashtbl[(cg) & (ump)->bmsafemap_hash_size])
5520 
5521 static int
5522 bmsafemap_find(bmsafemaphd, cg, bmsafemapp)
5523 	struct bmsafemap_hashhead *bmsafemaphd;
5524 	int cg;
5525 	struct bmsafemap **bmsafemapp;
5526 {
5527 	struct bmsafemap *bmsafemap;
5528 
5529 	LIST_FOREACH(bmsafemap, bmsafemaphd, sm_hash)
5530 		if (bmsafemap->sm_cg == cg)
5531 			break;
5532 	if (bmsafemap) {
5533 		*bmsafemapp = bmsafemap;
5534 		return (1);
5535 	}
5536 	*bmsafemapp = NULL;
5537 
5538 	return (0);
5539 }
5540 
5541 /*
5542  * Find the bmsafemap associated with a cylinder group buffer.
5543  * If none exists, create one. The buffer must be locked when
5544  * this routine is called and this routine must be called with
5545  * the softdep lock held. To avoid giving up the lock while
5546  * allocating a new bmsafemap, a preallocated bmsafemap may be
5547  * provided. If it is provided but not needed, it is freed.
5548  */
5549 static struct bmsafemap *
5550 bmsafemap_lookup(mp, bp, cg, newbmsafemap)
5551 	struct mount *mp;
5552 	struct buf *bp;
5553 	int cg;
5554 	struct bmsafemap *newbmsafemap;
5555 {
5556 	struct bmsafemap_hashhead *bmsafemaphd;
5557 	struct bmsafemap *bmsafemap, *collision;
5558 	struct worklist *wk;
5559 	struct ufsmount *ump;
5560 
5561 	ump = VFSTOUFS(mp);
5562 	LOCK_OWNED(ump);
5563 	KASSERT(bp != NULL, ("bmsafemap_lookup: missing buffer"));
5564 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
5565 		if (wk->wk_type == D_BMSAFEMAP) {
5566 			if (newbmsafemap)
5567 				WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5568 			return (WK_BMSAFEMAP(wk));
5569 		}
5570 	}
5571 	bmsafemaphd = BMSAFEMAP_HASH(ump, cg);
5572 	if (bmsafemap_find(bmsafemaphd, cg, &bmsafemap) == 1) {
5573 		if (newbmsafemap)
5574 			WORKITEM_FREE(newbmsafemap, D_BMSAFEMAP);
5575 		return (bmsafemap);
5576 	}
5577 	if (newbmsafemap) {
5578 		bmsafemap = newbmsafemap;
5579 	} else {
5580 		FREE_LOCK(ump);
5581 		bmsafemap = malloc(sizeof(struct bmsafemap),
5582 			M_BMSAFEMAP, M_SOFTDEP_FLAGS);
5583 		workitem_alloc(&bmsafemap->sm_list, D_BMSAFEMAP, mp);
5584 		ACQUIRE_LOCK(ump);
5585 	}
5586 	bmsafemap->sm_buf = bp;
5587 	LIST_INIT(&bmsafemap->sm_inodedephd);
5588 	LIST_INIT(&bmsafemap->sm_inodedepwr);
5589 	LIST_INIT(&bmsafemap->sm_newblkhd);
5590 	LIST_INIT(&bmsafemap->sm_newblkwr);
5591 	LIST_INIT(&bmsafemap->sm_jaddrefhd);
5592 	LIST_INIT(&bmsafemap->sm_jnewblkhd);
5593 	LIST_INIT(&bmsafemap->sm_freehd);
5594 	LIST_INIT(&bmsafemap->sm_freewr);
5595 	if (bmsafemap_find(bmsafemaphd, cg, &collision) == 1) {
5596 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
5597 		return (collision);
5598 	}
5599 	bmsafemap->sm_cg = cg;
5600 	LIST_INSERT_HEAD(bmsafemaphd, bmsafemap, sm_hash);
5601 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
5602 	WORKLIST_INSERT(&bp->b_dep, &bmsafemap->sm_list);
5603 	return (bmsafemap);
5604 }
5605 
5606 /*
5607  * Direct block allocation dependencies.
5608  *
5609  * When a new block is allocated, the corresponding disk locations must be
5610  * initialized (with zeros or new data) before the on-disk inode points to
5611  * them.  Also, the freemap from which the block was allocated must be
5612  * updated (on disk) before the inode's pointer. These two dependencies are
5613  * independent of each other and are needed for all file blocks and indirect
5614  * blocks that are pointed to directly by the inode.  Just before the
5615  * "in-core" version of the inode is updated with a newly allocated block
5616  * number, a procedure (below) is called to setup allocation dependency
5617  * structures.  These structures are removed when the corresponding
5618  * dependencies are satisfied or when the block allocation becomes obsolete
5619  * (i.e., the file is deleted, the block is de-allocated, or the block is a
5620  * fragment that gets upgraded).  All of these cases are handled in
5621  * procedures described later.
5622  *
5623  * When a file extension causes a fragment to be upgraded, either to a larger
5624  * fragment or to a full block, the on-disk location may change (if the
5625  * previous fragment could not simply be extended). In this case, the old
5626  * fragment must be de-allocated, but not until after the inode's pointer has
5627  * been updated. In most cases, this is handled by later procedures, which
5628  * will construct a "freefrag" structure to be added to the workitem queue
5629  * when the inode update is complete (or obsolete).  The main exception to
5630  * this is when an allocation occurs while a pending allocation dependency
5631  * (for the same block pointer) remains.  This case is handled in the main
5632  * allocation dependency setup procedure by immediately freeing the
5633  * unreferenced fragments.
5634  */
5635 void
5636 softdep_setup_allocdirect(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
5637 	struct inode *ip;	/* inode to which block is being added */
5638 	ufs_lbn_t off;		/* block pointer within inode */
5639 	ufs2_daddr_t newblkno;	/* disk block number being added */
5640 	ufs2_daddr_t oldblkno;	/* previous block number, 0 unless frag */
5641 	long newsize;		/* size of new block */
5642 	long oldsize;		/* size of new block */
5643 	struct buf *bp;		/* bp for allocated block */
5644 {
5645 	struct allocdirect *adp, *oldadp;
5646 	struct allocdirectlst *adphead;
5647 	struct freefrag *freefrag;
5648 	struct inodedep *inodedep;
5649 	struct pagedep *pagedep;
5650 	struct jnewblk *jnewblk;
5651 	struct newblk *newblk;
5652 	struct mount *mp;
5653 	ufs_lbn_t lbn;
5654 
5655 	lbn = bp->b_lblkno;
5656 	mp = ITOVFS(ip);
5657 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
5658 	    ("softdep_setup_allocdirect called on non-softdep filesystem"));
5659 	if (oldblkno && oldblkno != newblkno)
5660 		/*
5661 		 * The usual case is that a smaller fragment that
5662 		 * was just allocated has been replaced with a bigger
5663 		 * fragment or a full-size block. If it is marked as
5664 		 * B_DELWRI, the current contents have not been written
5665 		 * to disk. It is possible that the block was written
5666 		 * earlier, but very uncommon. If the block has never
5667 		 * been written, there is no need to send a BIO_DELETE
5668 		 * for it when it is freed. The gain from avoiding the
5669 		 * TRIMs for the common case of unwritten blocks far
5670 		 * exceeds the cost of the write amplification for the
5671 		 * uncommon case of failing to send a TRIM for a block
5672 		 * that had been written.
5673 		 */
5674 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
5675 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
5676 	else
5677 		freefrag = NULL;
5678 
5679 	CTR6(KTR_SUJ,
5680 	    "softdep_setup_allocdirect: ino %d blkno %jd oldblkno %jd "
5681 	    "off %jd newsize %ld oldsize %d",
5682 	    ip->i_number, newblkno, oldblkno, off, newsize, oldsize);
5683 	ACQUIRE_LOCK(ITOUMP(ip));
5684 	if (off >= UFS_NDADDR) {
5685 		if (lbn > 0)
5686 			panic("softdep_setup_allocdirect: bad lbn %jd, off %jd",
5687 			    lbn, off);
5688 		/* allocating an indirect block */
5689 		if (oldblkno != 0)
5690 			panic("softdep_setup_allocdirect: non-zero indir");
5691 	} else {
5692 		if (off != lbn)
5693 			panic("softdep_setup_allocdirect: lbn %jd != off %jd",
5694 			    lbn, off);
5695 		/*
5696 		 * Allocating a direct block.
5697 		 *
5698 		 * If we are allocating a directory block, then we must
5699 		 * allocate an associated pagedep to track additions and
5700 		 * deletions.
5701 		 */
5702 		if ((ip->i_mode & IFMT) == IFDIR)
5703 			pagedep_lookup(mp, bp, ip->i_number, off, DEPALLOC,
5704 			    &pagedep);
5705 	}
5706 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
5707 		panic("softdep_setup_allocdirect: lost block");
5708 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
5709 	    ("softdep_setup_allocdirect: newblk already initialized"));
5710 	/*
5711 	 * Convert the newblk to an allocdirect.
5712 	 */
5713 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
5714 	adp = (struct allocdirect *)newblk;
5715 	newblk->nb_freefrag = freefrag;
5716 	adp->ad_offset = off;
5717 	adp->ad_oldblkno = oldblkno;
5718 	adp->ad_newsize = newsize;
5719 	adp->ad_oldsize = oldsize;
5720 
5721 	/*
5722 	 * Finish initializing the journal.
5723 	 */
5724 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
5725 		jnewblk->jn_ino = ip->i_number;
5726 		jnewblk->jn_lbn = lbn;
5727 		add_to_journal(&jnewblk->jn_list);
5728 	}
5729 	if (freefrag && freefrag->ff_jdep != NULL &&
5730 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
5731 		add_to_journal(freefrag->ff_jdep);
5732 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
5733 	adp->ad_inodedep = inodedep;
5734 
5735 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
5736 	/*
5737 	 * The list of allocdirects must be kept in sorted and ascending
5738 	 * order so that the rollback routines can quickly determine the
5739 	 * first uncommitted block (the size of the file stored on disk
5740 	 * ends at the end of the lowest committed fragment, or if there
5741 	 * are no fragments, at the end of the highest committed block).
5742 	 * Since files generally grow, the typical case is that the new
5743 	 * block is to be added at the end of the list. We speed this
5744 	 * special case by checking against the last allocdirect in the
5745 	 * list before laboriously traversing the list looking for the
5746 	 * insertion point.
5747 	 */
5748 	adphead = &inodedep->id_newinoupdt;
5749 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
5750 	if (oldadp == NULL || oldadp->ad_offset <= off) {
5751 		/* insert at end of list */
5752 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
5753 		if (oldadp != NULL && oldadp->ad_offset == off)
5754 			allocdirect_merge(adphead, adp, oldadp);
5755 		FREE_LOCK(ITOUMP(ip));
5756 		return;
5757 	}
5758 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
5759 		if (oldadp->ad_offset >= off)
5760 			break;
5761 	}
5762 	if (oldadp == NULL)
5763 		panic("softdep_setup_allocdirect: lost entry");
5764 	/* insert in middle of list */
5765 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
5766 	if (oldadp->ad_offset == off)
5767 		allocdirect_merge(adphead, adp, oldadp);
5768 
5769 	FREE_LOCK(ITOUMP(ip));
5770 }
5771 
5772 /*
5773  * Merge a newer and older journal record to be stored either in a
5774  * newblock or freefrag.  This handles aggregating journal records for
5775  * fragment allocation into a second record as well as replacing a
5776  * journal free with an aborted journal allocation.  A segment for the
5777  * oldest record will be placed on wkhd if it has been written.  If not
5778  * the segment for the newer record will suffice.
5779  */
5780 static struct worklist *
5781 jnewblk_merge(new, old, wkhd)
5782 	struct worklist *new;
5783 	struct worklist *old;
5784 	struct workhead *wkhd;
5785 {
5786 	struct jnewblk *njnewblk;
5787 	struct jnewblk *jnewblk;
5788 
5789 	/* Handle NULLs to simplify callers. */
5790 	if (new == NULL)
5791 		return (old);
5792 	if (old == NULL)
5793 		return (new);
5794 	/* Replace a jfreefrag with a jnewblk. */
5795 	if (new->wk_type == D_JFREEFRAG) {
5796 		if (WK_JNEWBLK(old)->jn_blkno != WK_JFREEFRAG(new)->fr_blkno)
5797 			panic("jnewblk_merge: blkno mismatch: %p, %p",
5798 			    old, new);
5799 		cancel_jfreefrag(WK_JFREEFRAG(new));
5800 		return (old);
5801 	}
5802 	if (old->wk_type != D_JNEWBLK || new->wk_type != D_JNEWBLK)
5803 		panic("jnewblk_merge: Bad type: old %d new %d\n",
5804 		    old->wk_type, new->wk_type);
5805 	/*
5806 	 * Handle merging of two jnewblk records that describe
5807 	 * different sets of fragments in the same block.
5808 	 */
5809 	jnewblk = WK_JNEWBLK(old);
5810 	njnewblk = WK_JNEWBLK(new);
5811 	if (jnewblk->jn_blkno != njnewblk->jn_blkno)
5812 		panic("jnewblk_merge: Merging disparate blocks.");
5813 	/*
5814 	 * The record may be rolled back in the cg.
5815 	 */
5816 	if (jnewblk->jn_state & UNDONE) {
5817 		jnewblk->jn_state &= ~UNDONE;
5818 		njnewblk->jn_state |= UNDONE;
5819 		njnewblk->jn_state &= ~ATTACHED;
5820 	}
5821 	/*
5822 	 * We modify the newer addref and free the older so that if neither
5823 	 * has been written the most up-to-date copy will be on disk.  If
5824 	 * both have been written but rolled back we only temporarily need
5825 	 * one of them to fix the bits when the cg write completes.
5826 	 */
5827 	jnewblk->jn_state |= ATTACHED | COMPLETE;
5828 	njnewblk->jn_oldfrags = jnewblk->jn_oldfrags;
5829 	cancel_jnewblk(jnewblk, wkhd);
5830 	WORKLIST_REMOVE(&jnewblk->jn_list);
5831 	free_jnewblk(jnewblk);
5832 	return (new);
5833 }
5834 
5835 /*
5836  * Replace an old allocdirect dependency with a newer one.
5837  */
5838 static void
5839 allocdirect_merge(adphead, newadp, oldadp)
5840 	struct allocdirectlst *adphead;	/* head of list holding allocdirects */
5841 	struct allocdirect *newadp;	/* allocdirect being added */
5842 	struct allocdirect *oldadp;	/* existing allocdirect being checked */
5843 {
5844 	struct worklist *wk;
5845 	struct freefrag *freefrag;
5846 
5847 	freefrag = NULL;
5848 	LOCK_OWNED(VFSTOUFS(newadp->ad_list.wk_mp));
5849 	if (newadp->ad_oldblkno != oldadp->ad_newblkno ||
5850 	    newadp->ad_oldsize != oldadp->ad_newsize ||
5851 	    newadp->ad_offset >= UFS_NDADDR)
5852 		panic("%s %jd != new %jd || old size %ld != new %ld",
5853 		    "allocdirect_merge: old blkno",
5854 		    (intmax_t)newadp->ad_oldblkno,
5855 		    (intmax_t)oldadp->ad_newblkno,
5856 		    newadp->ad_oldsize, oldadp->ad_newsize);
5857 	newadp->ad_oldblkno = oldadp->ad_oldblkno;
5858 	newadp->ad_oldsize = oldadp->ad_oldsize;
5859 	/*
5860 	 * If the old dependency had a fragment to free or had never
5861 	 * previously had a block allocated, then the new dependency
5862 	 * can immediately post its freefrag and adopt the old freefrag.
5863 	 * This action is done by swapping the freefrag dependencies.
5864 	 * The new dependency gains the old one's freefrag, and the
5865 	 * old one gets the new one and then immediately puts it on
5866 	 * the worklist when it is freed by free_newblk. It is
5867 	 * not possible to do this swap when the old dependency had a
5868 	 * non-zero size but no previous fragment to free. This condition
5869 	 * arises when the new block is an extension of the old block.
5870 	 * Here, the first part of the fragment allocated to the new
5871 	 * dependency is part of the block currently claimed on disk by
5872 	 * the old dependency, so cannot legitimately be freed until the
5873 	 * conditions for the new dependency are fulfilled.
5874 	 */
5875 	freefrag = newadp->ad_freefrag;
5876 	if (oldadp->ad_freefrag != NULL || oldadp->ad_oldblkno == 0) {
5877 		newadp->ad_freefrag = oldadp->ad_freefrag;
5878 		oldadp->ad_freefrag = freefrag;
5879 	}
5880 	/*
5881 	 * If we are tracking a new directory-block allocation,
5882 	 * move it from the old allocdirect to the new allocdirect.
5883 	 */
5884 	if ((wk = LIST_FIRST(&oldadp->ad_newdirblk)) != NULL) {
5885 		WORKLIST_REMOVE(wk);
5886 		if (!LIST_EMPTY(&oldadp->ad_newdirblk))
5887 			panic("allocdirect_merge: extra newdirblk");
5888 		WORKLIST_INSERT(&newadp->ad_newdirblk, wk);
5889 	}
5890 	TAILQ_REMOVE(adphead, oldadp, ad_next);
5891 	/*
5892 	 * We need to move any journal dependencies over to the freefrag
5893 	 * that releases this block if it exists.  Otherwise we are
5894 	 * extending an existing block and we'll wait until that is
5895 	 * complete to release the journal space and extend the
5896 	 * new journal to cover this old space as well.
5897 	 */
5898 	if (freefrag == NULL) {
5899 		if (oldadp->ad_newblkno != newadp->ad_newblkno)
5900 			panic("allocdirect_merge: %jd != %jd",
5901 			    oldadp->ad_newblkno, newadp->ad_newblkno);
5902 		newadp->ad_block.nb_jnewblk = (struct jnewblk *)
5903 		    jnewblk_merge(&newadp->ad_block.nb_jnewblk->jn_list,
5904 		    &oldadp->ad_block.nb_jnewblk->jn_list,
5905 		    &newadp->ad_block.nb_jwork);
5906 		oldadp->ad_block.nb_jnewblk = NULL;
5907 		cancel_newblk(&oldadp->ad_block, NULL,
5908 		    &newadp->ad_block.nb_jwork);
5909 	} else {
5910 		wk = (struct worklist *) cancel_newblk(&oldadp->ad_block,
5911 		    &freefrag->ff_list, &freefrag->ff_jwork);
5912 		freefrag->ff_jdep = jnewblk_merge(freefrag->ff_jdep, wk,
5913 		    &freefrag->ff_jwork);
5914 	}
5915 	free_newblk(&oldadp->ad_block);
5916 }
5917 
5918 /*
5919  * Allocate a jfreefrag structure to journal a single block free.
5920  */
5921 static struct jfreefrag *
5922 newjfreefrag(freefrag, ip, blkno, size, lbn)
5923 	struct freefrag *freefrag;
5924 	struct inode *ip;
5925 	ufs2_daddr_t blkno;
5926 	long size;
5927 	ufs_lbn_t lbn;
5928 {
5929 	struct jfreefrag *jfreefrag;
5930 	struct fs *fs;
5931 
5932 	fs = ITOFS(ip);
5933 	jfreefrag = malloc(sizeof(struct jfreefrag), M_JFREEFRAG,
5934 	    M_SOFTDEP_FLAGS);
5935 	workitem_alloc(&jfreefrag->fr_list, D_JFREEFRAG, ITOVFS(ip));
5936 	jfreefrag->fr_jsegdep = newjsegdep(&jfreefrag->fr_list);
5937 	jfreefrag->fr_state = ATTACHED | DEPCOMPLETE;
5938 	jfreefrag->fr_ino = ip->i_number;
5939 	jfreefrag->fr_lbn = lbn;
5940 	jfreefrag->fr_blkno = blkno;
5941 	jfreefrag->fr_frags = numfrags(fs, size);
5942 	jfreefrag->fr_freefrag = freefrag;
5943 
5944 	return (jfreefrag);
5945 }
5946 
5947 /*
5948  * Allocate a new freefrag structure.
5949  */
5950 static struct freefrag *
5951 newfreefrag(ip, blkno, size, lbn, key)
5952 	struct inode *ip;
5953 	ufs2_daddr_t blkno;
5954 	long size;
5955 	ufs_lbn_t lbn;
5956 	u_long key;
5957 {
5958 	struct freefrag *freefrag;
5959 	struct ufsmount *ump;
5960 	struct fs *fs;
5961 
5962 	CTR4(KTR_SUJ, "newfreefrag: ino %d blkno %jd size %ld lbn %jd",
5963 	    ip->i_number, blkno, size, lbn);
5964 	ump = ITOUMP(ip);
5965 	fs = ump->um_fs;
5966 	if (fragnum(fs, blkno) + numfrags(fs, size) > fs->fs_frag)
5967 		panic("newfreefrag: frag size");
5968 	freefrag = malloc(sizeof(struct freefrag),
5969 	    M_FREEFRAG, M_SOFTDEP_FLAGS);
5970 	workitem_alloc(&freefrag->ff_list, D_FREEFRAG, UFSTOVFS(ump));
5971 	freefrag->ff_state = ATTACHED;
5972 	LIST_INIT(&freefrag->ff_jwork);
5973 	freefrag->ff_inum = ip->i_number;
5974 	freefrag->ff_vtype = ITOV(ip)->v_type;
5975 	freefrag->ff_blkno = blkno;
5976 	freefrag->ff_fragsize = size;
5977 	freefrag->ff_key = key;
5978 
5979 	if (MOUNTEDSUJ(UFSTOVFS(ump))) {
5980 		freefrag->ff_jdep = (struct worklist *)
5981 		    newjfreefrag(freefrag, ip, blkno, size, lbn);
5982 	} else {
5983 		freefrag->ff_state |= DEPCOMPLETE;
5984 		freefrag->ff_jdep = NULL;
5985 	}
5986 
5987 	return (freefrag);
5988 }
5989 
5990 /*
5991  * This workitem de-allocates fragments that were replaced during
5992  * file block allocation.
5993  */
5994 static void
5995 handle_workitem_freefrag(freefrag)
5996 	struct freefrag *freefrag;
5997 {
5998 	struct ufsmount *ump = VFSTOUFS(freefrag->ff_list.wk_mp);
5999 	struct workhead wkhd;
6000 
6001 	CTR3(KTR_SUJ,
6002 	    "handle_workitem_freefrag: ino %d blkno %jd size %ld",
6003 	    freefrag->ff_inum, freefrag->ff_blkno, freefrag->ff_fragsize);
6004 	/*
6005 	 * It would be illegal to add new completion items to the
6006 	 * freefrag after it was schedule to be done so it must be
6007 	 * safe to modify the list head here.
6008 	 */
6009 	LIST_INIT(&wkhd);
6010 	ACQUIRE_LOCK(ump);
6011 	LIST_SWAP(&freefrag->ff_jwork, &wkhd, worklist, wk_list);
6012 	/*
6013 	 * If the journal has not been written we must cancel it here.
6014 	 */
6015 	if (freefrag->ff_jdep) {
6016 		if (freefrag->ff_jdep->wk_type != D_JNEWBLK)
6017 			panic("handle_workitem_freefrag: Unexpected type %d\n",
6018 			    freefrag->ff_jdep->wk_type);
6019 		cancel_jnewblk(WK_JNEWBLK(freefrag->ff_jdep), &wkhd);
6020 	}
6021 	FREE_LOCK(ump);
6022 	ffs_blkfree(ump, ump->um_fs, ump->um_devvp, freefrag->ff_blkno,
6023 	   freefrag->ff_fragsize, freefrag->ff_inum, freefrag->ff_vtype,
6024 	   &wkhd, freefrag->ff_key);
6025 	ACQUIRE_LOCK(ump);
6026 	WORKITEM_FREE(freefrag, D_FREEFRAG);
6027 	FREE_LOCK(ump);
6028 }
6029 
6030 /*
6031  * Set up a dependency structure for an external attributes data block.
6032  * This routine follows much of the structure of softdep_setup_allocdirect.
6033  * See the description of softdep_setup_allocdirect above for details.
6034  */
6035 void
6036 softdep_setup_allocext(ip, off, newblkno, oldblkno, newsize, oldsize, bp)
6037 	struct inode *ip;
6038 	ufs_lbn_t off;
6039 	ufs2_daddr_t newblkno;
6040 	ufs2_daddr_t oldblkno;
6041 	long newsize;
6042 	long oldsize;
6043 	struct buf *bp;
6044 {
6045 	struct allocdirect *adp, *oldadp;
6046 	struct allocdirectlst *adphead;
6047 	struct freefrag *freefrag;
6048 	struct inodedep *inodedep;
6049 	struct jnewblk *jnewblk;
6050 	struct newblk *newblk;
6051 	struct mount *mp;
6052 	struct ufsmount *ump;
6053 	ufs_lbn_t lbn;
6054 
6055 	mp = ITOVFS(ip);
6056 	ump = VFSTOUFS(mp);
6057 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6058 	    ("softdep_setup_allocext called on non-softdep filesystem"));
6059 	KASSERT(off < UFS_NXADDR,
6060 	    ("softdep_setup_allocext: lbn %lld > UFS_NXADDR", (long long)off));
6061 
6062 	lbn = bp->b_lblkno;
6063 	if (oldblkno && oldblkno != newblkno)
6064 		/*
6065 		 * The usual case is that a smaller fragment that
6066 		 * was just allocated has been replaced with a bigger
6067 		 * fragment or a full-size block. If it is marked as
6068 		 * B_DELWRI, the current contents have not been written
6069 		 * to disk. It is possible that the block was written
6070 		 * earlier, but very uncommon. If the block has never
6071 		 * been written, there is no need to send a BIO_DELETE
6072 		 * for it when it is freed. The gain from avoiding the
6073 		 * TRIMs for the common case of unwritten blocks far
6074 		 * exceeds the cost of the write amplification for the
6075 		 * uncommon case of failing to send a TRIM for a block
6076 		 * that had been written.
6077 		 */
6078 		freefrag = newfreefrag(ip, oldblkno, oldsize, lbn,
6079 		    (bp->b_flags & B_DELWRI) != 0 ? NOTRIM_KEY : SINGLETON_KEY);
6080 	else
6081 		freefrag = NULL;
6082 
6083 	ACQUIRE_LOCK(ump);
6084 	if (newblk_lookup(mp, newblkno, 0, &newblk) == 0)
6085 		panic("softdep_setup_allocext: lost block");
6086 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6087 	    ("softdep_setup_allocext: newblk already initialized"));
6088 	/*
6089 	 * Convert the newblk to an allocdirect.
6090 	 */
6091 	WORKITEM_REASSIGN(newblk, D_ALLOCDIRECT);
6092 	adp = (struct allocdirect *)newblk;
6093 	newblk->nb_freefrag = freefrag;
6094 	adp->ad_offset = off;
6095 	adp->ad_oldblkno = oldblkno;
6096 	adp->ad_newsize = newsize;
6097 	adp->ad_oldsize = oldsize;
6098 	adp->ad_state |=  EXTDATA;
6099 
6100 	/*
6101 	 * Finish initializing the journal.
6102 	 */
6103 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6104 		jnewblk->jn_ino = ip->i_number;
6105 		jnewblk->jn_lbn = lbn;
6106 		add_to_journal(&jnewblk->jn_list);
6107 	}
6108 	if (freefrag && freefrag->ff_jdep != NULL &&
6109 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6110 		add_to_journal(freefrag->ff_jdep);
6111 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6112 	adp->ad_inodedep = inodedep;
6113 
6114 	WORKLIST_INSERT(&bp->b_dep, &newblk->nb_list);
6115 	/*
6116 	 * The list of allocdirects must be kept in sorted and ascending
6117 	 * order so that the rollback routines can quickly determine the
6118 	 * first uncommitted block (the size of the file stored on disk
6119 	 * ends at the end of the lowest committed fragment, or if there
6120 	 * are no fragments, at the end of the highest committed block).
6121 	 * Since files generally grow, the typical case is that the new
6122 	 * block is to be added at the end of the list. We speed this
6123 	 * special case by checking against the last allocdirect in the
6124 	 * list before laboriously traversing the list looking for the
6125 	 * insertion point.
6126 	 */
6127 	adphead = &inodedep->id_newextupdt;
6128 	oldadp = TAILQ_LAST(adphead, allocdirectlst);
6129 	if (oldadp == NULL || oldadp->ad_offset <= off) {
6130 		/* insert at end of list */
6131 		TAILQ_INSERT_TAIL(adphead, adp, ad_next);
6132 		if (oldadp != NULL && oldadp->ad_offset == off)
6133 			allocdirect_merge(adphead, adp, oldadp);
6134 		FREE_LOCK(ump);
6135 		return;
6136 	}
6137 	TAILQ_FOREACH(oldadp, adphead, ad_next) {
6138 		if (oldadp->ad_offset >= off)
6139 			break;
6140 	}
6141 	if (oldadp == NULL)
6142 		panic("softdep_setup_allocext: lost entry");
6143 	/* insert in middle of list */
6144 	TAILQ_INSERT_BEFORE(oldadp, adp, ad_next);
6145 	if (oldadp->ad_offset == off)
6146 		allocdirect_merge(adphead, adp, oldadp);
6147 	FREE_LOCK(ump);
6148 }
6149 
6150 /*
6151  * Indirect block allocation dependencies.
6152  *
6153  * The same dependencies that exist for a direct block also exist when
6154  * a new block is allocated and pointed to by an entry in a block of
6155  * indirect pointers. The undo/redo states described above are also
6156  * used here. Because an indirect block contains many pointers that
6157  * may have dependencies, a second copy of the entire in-memory indirect
6158  * block is kept. The buffer cache copy is always completely up-to-date.
6159  * The second copy, which is used only as a source for disk writes,
6160  * contains only the safe pointers (i.e., those that have no remaining
6161  * update dependencies). The second copy is freed when all pointers
6162  * are safe. The cache is not allowed to replace indirect blocks with
6163  * pending update dependencies. If a buffer containing an indirect
6164  * block with dependencies is written, these routines will mark it
6165  * dirty again. It can only be successfully written once all the
6166  * dependencies are removed. The ffs_fsync routine in conjunction with
6167  * softdep_sync_metadata work together to get all the dependencies
6168  * removed so that a file can be successfully written to disk. Three
6169  * procedures are used when setting up indirect block pointer
6170  * dependencies. The division is necessary because of the organization
6171  * of the "balloc" routine and because of the distinction between file
6172  * pages and file metadata blocks.
6173  */
6174 
6175 /*
6176  * Allocate a new allocindir structure.
6177  */
6178 static struct allocindir *
6179 newallocindir(ip, ptrno, newblkno, oldblkno, lbn)
6180 	struct inode *ip;	/* inode for file being extended */
6181 	int ptrno;		/* offset of pointer in indirect block */
6182 	ufs2_daddr_t newblkno;	/* disk block number being added */
6183 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6184 	ufs_lbn_t lbn;
6185 {
6186 	struct newblk *newblk;
6187 	struct allocindir *aip;
6188 	struct freefrag *freefrag;
6189 	struct jnewblk *jnewblk;
6190 
6191 	if (oldblkno)
6192 		freefrag = newfreefrag(ip, oldblkno, ITOFS(ip)->fs_bsize, lbn,
6193 		    SINGLETON_KEY);
6194 	else
6195 		freefrag = NULL;
6196 	ACQUIRE_LOCK(ITOUMP(ip));
6197 	if (newblk_lookup(ITOVFS(ip), newblkno, 0, &newblk) == 0)
6198 		panic("new_allocindir: lost block");
6199 	KASSERT(newblk->nb_list.wk_type == D_NEWBLK,
6200 	    ("newallocindir: newblk already initialized"));
6201 	WORKITEM_REASSIGN(newblk, D_ALLOCINDIR);
6202 	newblk->nb_freefrag = freefrag;
6203 	aip = (struct allocindir *)newblk;
6204 	aip->ai_offset = ptrno;
6205 	aip->ai_oldblkno = oldblkno;
6206 	aip->ai_lbn = lbn;
6207 	if ((jnewblk = newblk->nb_jnewblk) != NULL) {
6208 		jnewblk->jn_ino = ip->i_number;
6209 		jnewblk->jn_lbn = lbn;
6210 		add_to_journal(&jnewblk->jn_list);
6211 	}
6212 	if (freefrag && freefrag->ff_jdep != NULL &&
6213 	    freefrag->ff_jdep->wk_type == D_JFREEFRAG)
6214 		add_to_journal(freefrag->ff_jdep);
6215 	return (aip);
6216 }
6217 
6218 /*
6219  * Called just before setting an indirect block pointer
6220  * to a newly allocated file page.
6221  */
6222 void
6223 softdep_setup_allocindir_page(ip, lbn, bp, ptrno, newblkno, oldblkno, nbp)
6224 	struct inode *ip;	/* inode for file being extended */
6225 	ufs_lbn_t lbn;		/* allocated block number within file */
6226 	struct buf *bp;		/* buffer with indirect blk referencing page */
6227 	int ptrno;		/* offset of pointer in indirect block */
6228 	ufs2_daddr_t newblkno;	/* disk block number being added */
6229 	ufs2_daddr_t oldblkno;	/* previous block number, 0 if none */
6230 	struct buf *nbp;	/* buffer holding allocated page */
6231 {
6232 	struct inodedep *inodedep;
6233 	struct freefrag *freefrag;
6234 	struct allocindir *aip;
6235 	struct pagedep *pagedep;
6236 	struct mount *mp;
6237 	struct ufsmount *ump;
6238 
6239 	mp = ITOVFS(ip);
6240 	ump = VFSTOUFS(mp);
6241 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6242 	    ("softdep_setup_allocindir_page called on non-softdep filesystem"));
6243 	KASSERT(lbn == nbp->b_lblkno,
6244 	    ("softdep_setup_allocindir_page: lbn %jd != lblkno %jd",
6245 	    lbn, bp->b_lblkno));
6246 	CTR4(KTR_SUJ,
6247 	    "softdep_setup_allocindir_page: ino %d blkno %jd oldblkno %jd "
6248 	    "lbn %jd", ip->i_number, newblkno, oldblkno, lbn);
6249 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_page");
6250 	aip = newallocindir(ip, ptrno, newblkno, oldblkno, lbn);
6251 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6252 	/*
6253 	 * If we are allocating a directory page, then we must
6254 	 * allocate an associated pagedep to track additions and
6255 	 * deletions.
6256 	 */
6257 	if ((ip->i_mode & IFMT) == IFDIR)
6258 		pagedep_lookup(mp, nbp, ip->i_number, lbn, DEPALLOC, &pagedep);
6259 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6260 	freefrag = setup_allocindir_phase2(bp, ip, inodedep, aip, lbn);
6261 	FREE_LOCK(ump);
6262 	if (freefrag)
6263 		handle_workitem_freefrag(freefrag);
6264 }
6265 
6266 /*
6267  * Called just before setting an indirect block pointer to a
6268  * newly allocated indirect block.
6269  */
6270 void
6271 softdep_setup_allocindir_meta(nbp, ip, bp, ptrno, newblkno)
6272 	struct buf *nbp;	/* newly allocated indirect block */
6273 	struct inode *ip;	/* inode for file being extended */
6274 	struct buf *bp;		/* indirect block referencing allocated block */
6275 	int ptrno;		/* offset of pointer in indirect block */
6276 	ufs2_daddr_t newblkno;	/* disk block number being added */
6277 {
6278 	struct inodedep *inodedep;
6279 	struct allocindir *aip;
6280 	struct ufsmount *ump;
6281 	ufs_lbn_t lbn;
6282 
6283 	ump = ITOUMP(ip);
6284 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
6285 	    ("softdep_setup_allocindir_meta called on non-softdep filesystem"));
6286 	CTR3(KTR_SUJ,
6287 	    "softdep_setup_allocindir_meta: ino %d blkno %jd ptrno %d",
6288 	    ip->i_number, newblkno, ptrno);
6289 	lbn = nbp->b_lblkno;
6290 	ASSERT_VOP_LOCKED(ITOV(ip), "softdep_setup_allocindir_meta");
6291 	aip = newallocindir(ip, ptrno, newblkno, 0, lbn);
6292 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
6293 	WORKLIST_INSERT(&nbp->b_dep, &aip->ai_block.nb_list);
6294 	if (setup_allocindir_phase2(bp, ip, inodedep, aip, lbn))
6295 		panic("softdep_setup_allocindir_meta: Block already existed");
6296 	FREE_LOCK(ump);
6297 }
6298 
6299 static void
6300 indirdep_complete(indirdep)
6301 	struct indirdep *indirdep;
6302 {
6303 	struct allocindir *aip;
6304 
6305 	LIST_REMOVE(indirdep, ir_next);
6306 	indirdep->ir_state |= DEPCOMPLETE;
6307 
6308 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL) {
6309 		LIST_REMOVE(aip, ai_next);
6310 		free_newblk(&aip->ai_block);
6311 	}
6312 	/*
6313 	 * If this indirdep is not attached to a buf it was simply waiting
6314 	 * on completion to clear completehd.  free_indirdep() asserts
6315 	 * that nothing is dangling.
6316 	 */
6317 	if ((indirdep->ir_state & ONWORKLIST) == 0)
6318 		free_indirdep(indirdep);
6319 }
6320 
6321 static struct indirdep *
6322 indirdep_lookup(mp, ip, bp)
6323 	struct mount *mp;
6324 	struct inode *ip;
6325 	struct buf *bp;
6326 {
6327 	struct indirdep *indirdep, *newindirdep;
6328 	struct newblk *newblk;
6329 	struct ufsmount *ump;
6330 	struct worklist *wk;
6331 	struct fs *fs;
6332 	ufs2_daddr_t blkno;
6333 
6334 	ump = VFSTOUFS(mp);
6335 	LOCK_OWNED(ump);
6336 	indirdep = NULL;
6337 	newindirdep = NULL;
6338 	fs = ump->um_fs;
6339 	for (;;) {
6340 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
6341 			if (wk->wk_type != D_INDIRDEP)
6342 				continue;
6343 			indirdep = WK_INDIRDEP(wk);
6344 			break;
6345 		}
6346 		/* Found on the buffer worklist, no new structure to free. */
6347 		if (indirdep != NULL && newindirdep == NULL)
6348 			return (indirdep);
6349 		if (indirdep != NULL && newindirdep != NULL)
6350 			panic("indirdep_lookup: simultaneous create");
6351 		/* None found on the buffer and a new structure is ready. */
6352 		if (indirdep == NULL && newindirdep != NULL)
6353 			break;
6354 		/* None found and no new structure available. */
6355 		FREE_LOCK(ump);
6356 		newindirdep = malloc(sizeof(struct indirdep),
6357 		    M_INDIRDEP, M_SOFTDEP_FLAGS);
6358 		workitem_alloc(&newindirdep->ir_list, D_INDIRDEP, mp);
6359 		newindirdep->ir_state = ATTACHED;
6360 		if (I_IS_UFS1(ip))
6361 			newindirdep->ir_state |= UFS1FMT;
6362 		TAILQ_INIT(&newindirdep->ir_trunc);
6363 		newindirdep->ir_saveddata = NULL;
6364 		LIST_INIT(&newindirdep->ir_deplisthd);
6365 		LIST_INIT(&newindirdep->ir_donehd);
6366 		LIST_INIT(&newindirdep->ir_writehd);
6367 		LIST_INIT(&newindirdep->ir_completehd);
6368 		if (bp->b_blkno == bp->b_lblkno) {
6369 			ufs_bmaparray(bp->b_vp, bp->b_lblkno, &blkno, bp,
6370 			    NULL, NULL);
6371 			bp->b_blkno = blkno;
6372 		}
6373 		newindirdep->ir_freeblks = NULL;
6374 		newindirdep->ir_savebp =
6375 		    getblk(ump->um_devvp, bp->b_blkno, bp->b_bcount, 0, 0, 0);
6376 		newindirdep->ir_bp = bp;
6377 		BUF_KERNPROC(newindirdep->ir_savebp);
6378 		bcopy(bp->b_data, newindirdep->ir_savebp->b_data, bp->b_bcount);
6379 		ACQUIRE_LOCK(ump);
6380 	}
6381 	indirdep = newindirdep;
6382 	WORKLIST_INSERT(&bp->b_dep, &indirdep->ir_list);
6383 	/*
6384 	 * If the block is not yet allocated we don't set DEPCOMPLETE so
6385 	 * that we don't free dependencies until the pointers are valid.
6386 	 * This could search b_dep for D_ALLOCDIRECT/D_ALLOCINDIR rather
6387 	 * than using the hash.
6388 	 */
6389 	if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk))
6390 		LIST_INSERT_HEAD(&newblk->nb_indirdeps, indirdep, ir_next);
6391 	else
6392 		indirdep->ir_state |= DEPCOMPLETE;
6393 	return (indirdep);
6394 }
6395 
6396 /*
6397  * Called to finish the allocation of the "aip" allocated
6398  * by one of the two routines above.
6399  */
6400 static struct freefrag *
6401 setup_allocindir_phase2(bp, ip, inodedep, aip, lbn)
6402 	struct buf *bp;		/* in-memory copy of the indirect block */
6403 	struct inode *ip;	/* inode for file being extended */
6404 	struct inodedep *inodedep; /* Inodedep for ip */
6405 	struct allocindir *aip;	/* allocindir allocated by the above routines */
6406 	ufs_lbn_t lbn;		/* Logical block number for this block. */
6407 {
6408 	struct fs *fs;
6409 	struct indirdep *indirdep;
6410 	struct allocindir *oldaip;
6411 	struct freefrag *freefrag;
6412 	struct mount *mp;
6413 	struct ufsmount *ump;
6414 
6415 	mp = ITOVFS(ip);
6416 	ump = VFSTOUFS(mp);
6417 	LOCK_OWNED(ump);
6418 	fs = ump->um_fs;
6419 	if (bp->b_lblkno >= 0)
6420 		panic("setup_allocindir_phase2: not indir blk");
6421 	KASSERT(aip->ai_offset >= 0 && aip->ai_offset < NINDIR(fs),
6422 	    ("setup_allocindir_phase2: Bad offset %d", aip->ai_offset));
6423 	indirdep = indirdep_lookup(mp, ip, bp);
6424 	KASSERT(indirdep->ir_savebp != NULL,
6425 	    ("setup_allocindir_phase2 NULL ir_savebp"));
6426 	aip->ai_indirdep = indirdep;
6427 	/*
6428 	 * Check for an unwritten dependency for this indirect offset.  If
6429 	 * there is, merge the old dependency into the new one.  This happens
6430 	 * as a result of reallocblk only.
6431 	 */
6432 	freefrag = NULL;
6433 	if (aip->ai_oldblkno != 0) {
6434 		LIST_FOREACH(oldaip, &indirdep->ir_deplisthd, ai_next) {
6435 			if (oldaip->ai_offset == aip->ai_offset) {
6436 				freefrag = allocindir_merge(aip, oldaip);
6437 				goto done;
6438 			}
6439 		}
6440 		LIST_FOREACH(oldaip, &indirdep->ir_donehd, ai_next) {
6441 			if (oldaip->ai_offset == aip->ai_offset) {
6442 				freefrag = allocindir_merge(aip, oldaip);
6443 				goto done;
6444 			}
6445 		}
6446 	}
6447 done:
6448 	LIST_INSERT_HEAD(&indirdep->ir_deplisthd, aip, ai_next);
6449 	return (freefrag);
6450 }
6451 
6452 /*
6453  * Merge two allocindirs which refer to the same block.  Move newblock
6454  * dependencies and setup the freefrags appropriately.
6455  */
6456 static struct freefrag *
6457 allocindir_merge(aip, oldaip)
6458 	struct allocindir *aip;
6459 	struct allocindir *oldaip;
6460 {
6461 	struct freefrag *freefrag;
6462 	struct worklist *wk;
6463 
6464 	if (oldaip->ai_newblkno != aip->ai_oldblkno)
6465 		panic("allocindir_merge: blkno");
6466 	aip->ai_oldblkno = oldaip->ai_oldblkno;
6467 	freefrag = aip->ai_freefrag;
6468 	aip->ai_freefrag = oldaip->ai_freefrag;
6469 	oldaip->ai_freefrag = NULL;
6470 	KASSERT(freefrag != NULL, ("setup_allocindir_phase2: No freefrag"));
6471 	/*
6472 	 * If we are tracking a new directory-block allocation,
6473 	 * move it from the old allocindir to the new allocindir.
6474 	 */
6475 	if ((wk = LIST_FIRST(&oldaip->ai_newdirblk)) != NULL) {
6476 		WORKLIST_REMOVE(wk);
6477 		if (!LIST_EMPTY(&oldaip->ai_newdirblk))
6478 			panic("allocindir_merge: extra newdirblk");
6479 		WORKLIST_INSERT(&aip->ai_newdirblk, wk);
6480 	}
6481 	/*
6482 	 * We can skip journaling for this freefrag and just complete
6483 	 * any pending journal work for the allocindir that is being
6484 	 * removed after the freefrag completes.
6485 	 */
6486 	if (freefrag->ff_jdep)
6487 		cancel_jfreefrag(WK_JFREEFRAG(freefrag->ff_jdep));
6488 	LIST_REMOVE(oldaip, ai_next);
6489 	freefrag->ff_jdep = (struct worklist *)cancel_newblk(&oldaip->ai_block,
6490 	    &freefrag->ff_list, &freefrag->ff_jwork);
6491 	free_newblk(&oldaip->ai_block);
6492 
6493 	return (freefrag);
6494 }
6495 
6496 static inline void
6497 setup_freedirect(freeblks, ip, i, needj)
6498 	struct freeblks *freeblks;
6499 	struct inode *ip;
6500 	int i;
6501 	int needj;
6502 {
6503 	struct ufsmount *ump;
6504 	ufs2_daddr_t blkno;
6505 	int frags;
6506 
6507 	blkno = DIP(ip, i_db[i]);
6508 	if (blkno == 0)
6509 		return;
6510 	DIP_SET(ip, i_db[i], 0);
6511 	ump = ITOUMP(ip);
6512 	frags = sblksize(ump->um_fs, ip->i_size, i);
6513 	frags = numfrags(ump->um_fs, frags);
6514 	newfreework(ump, freeblks, NULL, i, blkno, frags, 0, needj);
6515 }
6516 
6517 static inline void
6518 setup_freeext(freeblks, ip, i, needj)
6519 	struct freeblks *freeblks;
6520 	struct inode *ip;
6521 	int i;
6522 	int needj;
6523 {
6524 	struct ufsmount *ump;
6525 	ufs2_daddr_t blkno;
6526 	int frags;
6527 
6528 	blkno = ip->i_din2->di_extb[i];
6529 	if (blkno == 0)
6530 		return;
6531 	ip->i_din2->di_extb[i] = 0;
6532 	ump = ITOUMP(ip);
6533 	frags = sblksize(ump->um_fs, ip->i_din2->di_extsize, i);
6534 	frags = numfrags(ump->um_fs, frags);
6535 	newfreework(ump, freeblks, NULL, -1 - i, blkno, frags, 0, needj);
6536 }
6537 
6538 static inline void
6539 setup_freeindir(freeblks, ip, i, lbn, needj)
6540 	struct freeblks *freeblks;
6541 	struct inode *ip;
6542 	int i;
6543 	ufs_lbn_t lbn;
6544 	int needj;
6545 {
6546 	struct ufsmount *ump;
6547 	ufs2_daddr_t blkno;
6548 
6549 	blkno = DIP(ip, i_ib[i]);
6550 	if (blkno == 0)
6551 		return;
6552 	DIP_SET(ip, i_ib[i], 0);
6553 	ump = ITOUMP(ip);
6554 	newfreework(ump, freeblks, NULL, lbn, blkno, ump->um_fs->fs_frag,
6555 	    0, needj);
6556 }
6557 
6558 static inline struct freeblks *
6559 newfreeblks(mp, ip)
6560 	struct mount *mp;
6561 	struct inode *ip;
6562 {
6563 	struct freeblks *freeblks;
6564 
6565 	freeblks = malloc(sizeof(struct freeblks),
6566 		M_FREEBLKS, M_SOFTDEP_FLAGS|M_ZERO);
6567 	workitem_alloc(&freeblks->fb_list, D_FREEBLKS, mp);
6568 	LIST_INIT(&freeblks->fb_jblkdephd);
6569 	LIST_INIT(&freeblks->fb_jwork);
6570 	freeblks->fb_ref = 0;
6571 	freeblks->fb_cgwait = 0;
6572 	freeblks->fb_state = ATTACHED;
6573 	freeblks->fb_uid = ip->i_uid;
6574 	freeblks->fb_inum = ip->i_number;
6575 	freeblks->fb_vtype = ITOV(ip)->v_type;
6576 	freeblks->fb_modrev = DIP(ip, i_modrev);
6577 	freeblks->fb_devvp = ITODEVVP(ip);
6578 	freeblks->fb_chkcnt = 0;
6579 	freeblks->fb_len = 0;
6580 
6581 	return (freeblks);
6582 }
6583 
6584 static void
6585 trunc_indirdep(indirdep, freeblks, bp, off)
6586 	struct indirdep *indirdep;
6587 	struct freeblks *freeblks;
6588 	struct buf *bp;
6589 	int off;
6590 {
6591 	struct allocindir *aip, *aipn;
6592 
6593 	/*
6594 	 * The first set of allocindirs won't be in savedbp.
6595 	 */
6596 	LIST_FOREACH_SAFE(aip, &indirdep->ir_deplisthd, ai_next, aipn)
6597 		if (aip->ai_offset > off)
6598 			cancel_allocindir(aip, bp, freeblks, 1);
6599 	LIST_FOREACH_SAFE(aip, &indirdep->ir_donehd, ai_next, aipn)
6600 		if (aip->ai_offset > off)
6601 			cancel_allocindir(aip, bp, freeblks, 1);
6602 	/*
6603 	 * These will exist in savedbp.
6604 	 */
6605 	LIST_FOREACH_SAFE(aip, &indirdep->ir_writehd, ai_next, aipn)
6606 		if (aip->ai_offset > off)
6607 			cancel_allocindir(aip, NULL, freeblks, 0);
6608 	LIST_FOREACH_SAFE(aip, &indirdep->ir_completehd, ai_next, aipn)
6609 		if (aip->ai_offset > off)
6610 			cancel_allocindir(aip, NULL, freeblks, 0);
6611 }
6612 
6613 /*
6614  * Follow the chain of indirects down to lastlbn creating a freework
6615  * structure for each.  This will be used to start indir_trunc() at
6616  * the right offset and create the journal records for the parrtial
6617  * truncation.  A second step will handle the truncated dependencies.
6618  */
6619 static int
6620 setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno)
6621 	struct freeblks *freeblks;
6622 	struct inode *ip;
6623 	ufs_lbn_t lbn;
6624 	ufs_lbn_t lastlbn;
6625 	ufs2_daddr_t blkno;
6626 {
6627 	struct indirdep *indirdep;
6628 	struct indirdep *indirn;
6629 	struct freework *freework;
6630 	struct newblk *newblk;
6631 	struct mount *mp;
6632 	struct ufsmount *ump;
6633 	struct buf *bp;
6634 	uint8_t *start;
6635 	uint8_t *end;
6636 	ufs_lbn_t lbnadd;
6637 	int level;
6638 	int error;
6639 	int off;
6640 
6641 	freework = NULL;
6642 	if (blkno == 0)
6643 		return (0);
6644 	mp = freeblks->fb_list.wk_mp;
6645 	ump = VFSTOUFS(mp);
6646 	/*
6647 	 * Here, calls to VOP_BMAP() will fail.  However, we already have
6648 	 * the on-disk address, so we just pass it to bread() instead of
6649 	 * having bread() attempt to calculate it using VOP_BMAP().
6650 	 */
6651 	error = ffs_breadz(ump, ITOV(ip), lbn, blkptrtodb(ump, blkno),
6652 	    (int)mp->mnt_stat.f_iosize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
6653 	if (error)
6654 		return (error);
6655 	level = lbn_level(lbn);
6656 	lbnadd = lbn_offset(ump->um_fs, level);
6657 	/*
6658 	 * Compute the offset of the last block we want to keep.  Store
6659 	 * in the freework the first block we want to completely free.
6660 	 */
6661 	off = (lastlbn - -(lbn + level)) / lbnadd;
6662 	if (off + 1 == NINDIR(ump->um_fs))
6663 		goto nowork;
6664 	freework = newfreework(ump, freeblks, NULL, lbn, blkno, 0, off + 1, 0);
6665 	/*
6666 	 * Link the freework into the indirdep.  This will prevent any new
6667 	 * allocations from proceeding until we are finished with the
6668 	 * truncate and the block is written.
6669 	 */
6670 	ACQUIRE_LOCK(ump);
6671 	indirdep = indirdep_lookup(mp, ip, bp);
6672 	if (indirdep->ir_freeblks)
6673 		panic("setup_trunc_indir: indirdep already truncated.");
6674 	TAILQ_INSERT_TAIL(&indirdep->ir_trunc, freework, fw_next);
6675 	freework->fw_indir = indirdep;
6676 	/*
6677 	 * Cancel any allocindirs that will not make it to disk.
6678 	 * We have to do this for all copies of the indirdep that
6679 	 * live on this newblk.
6680 	 */
6681 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
6682 		if (newblk_lookup(mp, dbtofsb(ump->um_fs, bp->b_blkno), 0,
6683 		    &newblk) == 0)
6684 			panic("setup_trunc_indir: lost block");
6685 		LIST_FOREACH(indirn, &newblk->nb_indirdeps, ir_next)
6686 			trunc_indirdep(indirn, freeblks, bp, off);
6687 	} else
6688 		trunc_indirdep(indirdep, freeblks, bp, off);
6689 	FREE_LOCK(ump);
6690 	/*
6691 	 * Creation is protected by the buf lock. The saveddata is only
6692 	 * needed if a full truncation follows a partial truncation but it
6693 	 * is difficult to allocate in that case so we fetch it anyway.
6694 	 */
6695 	if (indirdep->ir_saveddata == NULL)
6696 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
6697 		    M_SOFTDEP_FLAGS);
6698 nowork:
6699 	/* Fetch the blkno of the child and the zero start offset. */
6700 	if (I_IS_UFS1(ip)) {
6701 		blkno = ((ufs1_daddr_t *)bp->b_data)[off];
6702 		start = (uint8_t *)&((ufs1_daddr_t *)bp->b_data)[off+1];
6703 	} else {
6704 		blkno = ((ufs2_daddr_t *)bp->b_data)[off];
6705 		start = (uint8_t *)&((ufs2_daddr_t *)bp->b_data)[off+1];
6706 	}
6707 	if (freework) {
6708 		/* Zero the truncated pointers. */
6709 		end = bp->b_data + bp->b_bcount;
6710 		bzero(start, end - start);
6711 		bdwrite(bp);
6712 	} else
6713 		bqrelse(bp);
6714 	if (level == 0)
6715 		return (0);
6716 	lbn++; /* adjust level */
6717 	lbn -= (off * lbnadd);
6718 	return setup_trunc_indir(freeblks, ip, lbn, lastlbn, blkno);
6719 }
6720 
6721 /*
6722  * Complete the partial truncation of an indirect block setup by
6723  * setup_trunc_indir().  This zeros the truncated pointers in the saved
6724  * copy and writes them to disk before the freeblks is allowed to complete.
6725  */
6726 static void
6727 complete_trunc_indir(freework)
6728 	struct freework *freework;
6729 {
6730 	struct freework *fwn;
6731 	struct indirdep *indirdep;
6732 	struct ufsmount *ump;
6733 	struct buf *bp;
6734 	uintptr_t start;
6735 	int count;
6736 
6737 	ump = VFSTOUFS(freework->fw_list.wk_mp);
6738 	LOCK_OWNED(ump);
6739 	indirdep = freework->fw_indir;
6740 	for (;;) {
6741 		bp = indirdep->ir_bp;
6742 		/* See if the block was discarded. */
6743 		if (bp == NULL)
6744 			break;
6745 		/* Inline part of getdirtybuf().  We dont want bremfree. */
6746 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) == 0)
6747 			break;
6748 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
6749 		    LOCK_PTR(ump)) == 0)
6750 			BUF_UNLOCK(bp);
6751 		ACQUIRE_LOCK(ump);
6752 	}
6753 	freework->fw_state |= DEPCOMPLETE;
6754 	TAILQ_REMOVE(&indirdep->ir_trunc, freework, fw_next);
6755 	/*
6756 	 * Zero the pointers in the saved copy.
6757 	 */
6758 	if (indirdep->ir_state & UFS1FMT)
6759 		start = sizeof(ufs1_daddr_t);
6760 	else
6761 		start = sizeof(ufs2_daddr_t);
6762 	start *= freework->fw_start;
6763 	count = indirdep->ir_savebp->b_bcount - start;
6764 	start += (uintptr_t)indirdep->ir_savebp->b_data;
6765 	bzero((char *)start, count);
6766 	/*
6767 	 * We need to start the next truncation in the list if it has not
6768 	 * been started yet.
6769 	 */
6770 	fwn = TAILQ_FIRST(&indirdep->ir_trunc);
6771 	if (fwn != NULL) {
6772 		if (fwn->fw_freeblks == indirdep->ir_freeblks)
6773 			TAILQ_REMOVE(&indirdep->ir_trunc, fwn, fw_next);
6774 		if ((fwn->fw_state & ONWORKLIST) == 0)
6775 			freework_enqueue(fwn);
6776 	}
6777 	/*
6778 	 * If bp is NULL the block was fully truncated, restore
6779 	 * the saved block list otherwise free it if it is no
6780 	 * longer needed.
6781 	 */
6782 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
6783 		if (bp == NULL)
6784 			bcopy(indirdep->ir_saveddata,
6785 			    indirdep->ir_savebp->b_data,
6786 			    indirdep->ir_savebp->b_bcount);
6787 		free(indirdep->ir_saveddata, M_INDIRDEP);
6788 		indirdep->ir_saveddata = NULL;
6789 	}
6790 	/*
6791 	 * When bp is NULL there is a full truncation pending.  We
6792 	 * must wait for this full truncation to be journaled before
6793 	 * we can release this freework because the disk pointers will
6794 	 * never be written as zero.
6795 	 */
6796 	if (bp == NULL)  {
6797 		if (LIST_EMPTY(&indirdep->ir_freeblks->fb_jblkdephd))
6798 			handle_written_freework(freework);
6799 		else
6800 			WORKLIST_INSERT(&indirdep->ir_freeblks->fb_freeworkhd,
6801 			   &freework->fw_list);
6802 		if (fwn == NULL) {
6803 			freework->fw_indir = (void *)0x0000deadbeef0000;
6804 			bp = indirdep->ir_savebp;
6805 			indirdep->ir_savebp = NULL;
6806 			free_indirdep(indirdep);
6807 			FREE_LOCK(ump);
6808 			brelse(bp);
6809 			ACQUIRE_LOCK(ump);
6810 		}
6811 	} else {
6812 		/* Complete when the real copy is written. */
6813 		WORKLIST_INSERT(&bp->b_dep, &freework->fw_list);
6814 		BUF_UNLOCK(bp);
6815 	}
6816 }
6817 
6818 /*
6819  * Calculate the number of blocks we are going to release where datablocks
6820  * is the current total and length is the new file size.
6821  */
6822 static ufs2_daddr_t
6823 blkcount(fs, datablocks, length)
6824 	struct fs *fs;
6825 	ufs2_daddr_t datablocks;
6826 	off_t length;
6827 {
6828 	off_t totblks, numblks;
6829 
6830 	totblks = 0;
6831 	numblks = howmany(length, fs->fs_bsize);
6832 	if (numblks <= UFS_NDADDR) {
6833 		totblks = howmany(length, fs->fs_fsize);
6834 		goto out;
6835 	}
6836         totblks = blkstofrags(fs, numblks);
6837 	numblks -= UFS_NDADDR;
6838 	/*
6839 	 * Count all single, then double, then triple indirects required.
6840 	 * Subtracting one indirects worth of blocks for each pass
6841 	 * acknowledges one of each pointed to by the inode.
6842 	 */
6843 	for (;;) {
6844 		totblks += blkstofrags(fs, howmany(numblks, NINDIR(fs)));
6845 		numblks -= NINDIR(fs);
6846 		if (numblks <= 0)
6847 			break;
6848 		numblks = howmany(numblks, NINDIR(fs));
6849 	}
6850 out:
6851 	totblks = fsbtodb(fs, totblks);
6852 	/*
6853 	 * Handle sparse files.  We can't reclaim more blocks than the inode
6854 	 * references.  We will correct it later in handle_complete_freeblks()
6855 	 * when we know the real count.
6856 	 */
6857 	if (totblks > datablocks)
6858 		return (0);
6859 	return (datablocks - totblks);
6860 }
6861 
6862 /*
6863  * Handle freeblocks for journaled softupdate filesystems.
6864  *
6865  * Contrary to normal softupdates, we must preserve the block pointers in
6866  * indirects until their subordinates are free.  This is to avoid journaling
6867  * every block that is freed which may consume more space than the journal
6868  * itself.  The recovery program will see the free block journals at the
6869  * base of the truncated area and traverse them to reclaim space.  The
6870  * pointers in the inode may be cleared immediately after the journal
6871  * records are written because each direct and indirect pointer in the
6872  * inode is recorded in a journal.  This permits full truncation to proceed
6873  * asynchronously.  The write order is journal -> inode -> cgs -> indirects.
6874  *
6875  * The algorithm is as follows:
6876  * 1) Traverse the in-memory state and create journal entries to release
6877  *    the relevant blocks and full indirect trees.
6878  * 2) Traverse the indirect block chain adding partial truncation freework
6879  *    records to indirects in the path to lastlbn.  The freework will
6880  *    prevent new allocation dependencies from being satisfied in this
6881  *    indirect until the truncation completes.
6882  * 3) Read and lock the inode block, performing an update with the new size
6883  *    and pointers.  This prevents truncated data from becoming valid on
6884  *    disk through step 4.
6885  * 4) Reap unsatisfied dependencies that are beyond the truncated area,
6886  *    eliminate journal work for those records that do not require it.
6887  * 5) Schedule the journal records to be written followed by the inode block.
6888  * 6) Allocate any necessary frags for the end of file.
6889  * 7) Zero any partially truncated blocks.
6890  *
6891  * From this truncation proceeds asynchronously using the freework and
6892  * indir_trunc machinery.  The file will not be extended again into a
6893  * partially truncated indirect block until all work is completed but
6894  * the normal dependency mechanism ensures that it is rolled back/forward
6895  * as appropriate.  Further truncation may occur without delay and is
6896  * serialized in indir_trunc().
6897  */
6898 void
6899 softdep_journal_freeblocks(ip, cred, length, flags)
6900 	struct inode *ip;	/* The inode whose length is to be reduced */
6901 	struct ucred *cred;
6902 	off_t length;		/* The new length for the file */
6903 	int flags;		/* IO_EXT and/or IO_NORMAL */
6904 {
6905 	struct freeblks *freeblks, *fbn;
6906 	struct worklist *wk, *wkn;
6907 	struct inodedep *inodedep;
6908 	struct jblkdep *jblkdep;
6909 	struct allocdirect *adp, *adpn;
6910 	struct ufsmount *ump;
6911 	struct fs *fs;
6912 	struct buf *bp;
6913 	struct vnode *vp;
6914 	struct mount *mp;
6915 	daddr_t dbn;
6916 	ufs2_daddr_t extblocks, datablocks;
6917 	ufs_lbn_t tmpval, lbn, lastlbn;
6918 	int frags, lastoff, iboff, allocblock, needj, error, i;
6919 
6920 	ump = ITOUMP(ip);
6921 	mp = UFSTOVFS(ump);
6922 	fs = ump->um_fs;
6923 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
6924 	    ("softdep_journal_freeblocks called on non-softdep filesystem"));
6925 	vp = ITOV(ip);
6926 	needj = 1;
6927 	iboff = -1;
6928 	allocblock = 0;
6929 	extblocks = 0;
6930 	datablocks = 0;
6931 	frags = 0;
6932 	freeblks = newfreeblks(mp, ip);
6933 	ACQUIRE_LOCK(ump);
6934 	/*
6935 	 * If we're truncating a removed file that will never be written
6936 	 * we don't need to journal the block frees.  The canceled journals
6937 	 * for the allocations will suffice.
6938 	 */
6939 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
6940 	if ((inodedep->id_state & (UNLINKED | DEPCOMPLETE)) == UNLINKED &&
6941 	    length == 0)
6942 		needj = 0;
6943 	CTR3(KTR_SUJ, "softdep_journal_freeblks: ip %d length %ld needj %d",
6944 	    ip->i_number, length, needj);
6945 	FREE_LOCK(ump);
6946 	/*
6947 	 * Calculate the lbn that we are truncating to.  This results in -1
6948 	 * if we're truncating the 0 bytes.  So it is the last lbn we want
6949 	 * to keep, not the first lbn we want to truncate.
6950 	 */
6951 	lastlbn = lblkno(fs, length + fs->fs_bsize - 1) - 1;
6952 	lastoff = blkoff(fs, length);
6953 	/*
6954 	 * Compute frags we are keeping in lastlbn.  0 means all.
6955 	 */
6956 	if (lastlbn >= 0 && lastlbn < UFS_NDADDR) {
6957 		frags = fragroundup(fs, lastoff);
6958 		/* adp offset of last valid allocdirect. */
6959 		iboff = lastlbn;
6960 	} else if (lastlbn > 0)
6961 		iboff = UFS_NDADDR;
6962 	if (fs->fs_magic == FS_UFS2_MAGIC)
6963 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
6964 	/*
6965 	 * Handle normal data blocks and indirects.  This section saves
6966 	 * values used after the inode update to complete frag and indirect
6967 	 * truncation.
6968 	 */
6969 	if ((flags & IO_NORMAL) != 0) {
6970 		/*
6971 		 * Handle truncation of whole direct and indirect blocks.
6972 		 */
6973 		for (i = iboff + 1; i < UFS_NDADDR; i++)
6974 			setup_freedirect(freeblks, ip, i, needj);
6975 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
6976 		    i < UFS_NIADDR;
6977 		    i++, lbn += tmpval, tmpval *= NINDIR(fs)) {
6978 			/* Release a whole indirect tree. */
6979 			if (lbn > lastlbn) {
6980 				setup_freeindir(freeblks, ip, i, -lbn -i,
6981 				    needj);
6982 				continue;
6983 			}
6984 			iboff = i + UFS_NDADDR;
6985 			/*
6986 			 * Traverse partially truncated indirect tree.
6987 			 */
6988 			if (lbn <= lastlbn && lbn + tmpval - 1 > lastlbn)
6989 				setup_trunc_indir(freeblks, ip, -lbn - i,
6990 				    lastlbn, DIP(ip, i_ib[i]));
6991 		}
6992 		/*
6993 		 * Handle partial truncation to a frag boundary.
6994 		 */
6995 		if (frags) {
6996 			ufs2_daddr_t blkno;
6997 			long oldfrags;
6998 
6999 			oldfrags = blksize(fs, ip, lastlbn);
7000 			blkno = DIP(ip, i_db[lastlbn]);
7001 			if (blkno && oldfrags != frags) {
7002 				oldfrags -= frags;
7003 				oldfrags = numfrags(fs, oldfrags);
7004 				blkno += numfrags(fs, frags);
7005 				newfreework(ump, freeblks, NULL, lastlbn,
7006 				    blkno, oldfrags, 0, needj);
7007 				if (needj)
7008 					adjust_newfreework(freeblks,
7009 					    numfrags(fs, frags));
7010 			} else if (blkno == 0)
7011 				allocblock = 1;
7012 		}
7013 		/*
7014 		 * Add a journal record for partial truncate if we are
7015 		 * handling indirect blocks.  Non-indirects need no extra
7016 		 * journaling.
7017 		 */
7018 		if (length != 0 && lastlbn >= UFS_NDADDR) {
7019 			UFS_INODE_SET_FLAG(ip, IN_TRUNCATED);
7020 			newjtrunc(freeblks, length, 0);
7021 		}
7022 		ip->i_size = length;
7023 		DIP_SET(ip, i_size, ip->i_size);
7024 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7025 		datablocks = DIP(ip, i_blocks) - extblocks;
7026 		if (length != 0)
7027 			datablocks = blkcount(fs, datablocks, length);
7028 		freeblks->fb_len = length;
7029 	}
7030 	if ((flags & IO_EXT) != 0) {
7031 		for (i = 0; i < UFS_NXADDR; i++)
7032 			setup_freeext(freeblks, ip, i, needj);
7033 		ip->i_din2->di_extsize = 0;
7034 		datablocks += extblocks;
7035 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7036 	}
7037 #ifdef QUOTA
7038 	/* Reference the quotas in case the block count is wrong in the end. */
7039 	quotaref(vp, freeblks->fb_quota);
7040 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7041 #endif
7042 	freeblks->fb_chkcnt = -datablocks;
7043 	UFS_LOCK(ump);
7044 	fs->fs_pendingblocks += datablocks;
7045 	UFS_UNLOCK(ump);
7046 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7047 	/*
7048 	 * Handle truncation of incomplete alloc direct dependencies.  We
7049 	 * hold the inode block locked to prevent incomplete dependencies
7050 	 * from reaching the disk while we are eliminating those that
7051 	 * have been truncated.  This is a partially inlined ffs_update().
7052 	 */
7053 	ufs_itimes(vp);
7054 	ip->i_flag &= ~(IN_LAZYACCESS | IN_LAZYMOD | IN_MODIFIED);
7055 	dbn = fsbtodb(fs, ino_to_fsba(fs, ip->i_number));
7056 	error = ffs_breadz(ump, ump->um_devvp, dbn, dbn, (int)fs->fs_bsize,
7057 	    NULL, NULL, 0, cred, 0, NULL, &bp);
7058 	if (error) {
7059 		softdep_error("softdep_journal_freeblocks", error);
7060 		return;
7061 	}
7062 	if (bp->b_bufsize == fs->fs_bsize)
7063 		bp->b_flags |= B_CLUSTEROK;
7064 	softdep_update_inodeblock(ip, bp, 0);
7065 	if (ump->um_fstype == UFS1) {
7066 		*((struct ufs1_dinode *)bp->b_data +
7067 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din1;
7068 	} else {
7069 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7070 		*((struct ufs2_dinode *)bp->b_data +
7071 		    ino_to_fsbo(fs, ip->i_number)) = *ip->i_din2;
7072 	}
7073 	ACQUIRE_LOCK(ump);
7074 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7075 	if ((inodedep->id_state & IOSTARTED) != 0)
7076 		panic("softdep_setup_freeblocks: inode busy");
7077 	/*
7078 	 * Add the freeblks structure to the list of operations that
7079 	 * must await the zero'ed inode being written to disk. If we
7080 	 * still have a bitmap dependency (needj), then the inode
7081 	 * has never been written to disk, so we can process the
7082 	 * freeblks below once we have deleted the dependencies.
7083 	 */
7084 	if (needj)
7085 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7086 	else
7087 		freeblks->fb_state |= COMPLETE;
7088 	if ((flags & IO_NORMAL) != 0) {
7089 		TAILQ_FOREACH_SAFE(adp, &inodedep->id_inoupdt, ad_next, adpn) {
7090 			if (adp->ad_offset > iboff)
7091 				cancel_allocdirect(&inodedep->id_inoupdt, adp,
7092 				    freeblks);
7093 			/*
7094 			 * Truncate the allocdirect.  We could eliminate
7095 			 * or modify journal records as well.
7096 			 */
7097 			else if (adp->ad_offset == iboff && frags)
7098 				adp->ad_newsize = frags;
7099 		}
7100 	}
7101 	if ((flags & IO_EXT) != 0)
7102 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7103 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7104 			    freeblks);
7105 	/*
7106 	 * Scan the bufwait list for newblock dependencies that will never
7107 	 * make it to disk.
7108 	 */
7109 	LIST_FOREACH_SAFE(wk, &inodedep->id_bufwait, wk_list, wkn) {
7110 		if (wk->wk_type != D_ALLOCDIRECT)
7111 			continue;
7112 		adp = WK_ALLOCDIRECT(wk);
7113 		if (((flags & IO_NORMAL) != 0 && (adp->ad_offset > iboff)) ||
7114 		    ((flags & IO_EXT) != 0 && (adp->ad_state & EXTDATA))) {
7115 			cancel_jfreeblk(freeblks, adp->ad_newblkno);
7116 			cancel_newblk(WK_NEWBLK(wk), NULL, &freeblks->fb_jwork);
7117 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7118 		}
7119 	}
7120 	/*
7121 	 * Add journal work.
7122 	 */
7123 	LIST_FOREACH(jblkdep, &freeblks->fb_jblkdephd, jb_deps)
7124 		add_to_journal(&jblkdep->jb_list);
7125 	FREE_LOCK(ump);
7126 	bdwrite(bp);
7127 	/*
7128 	 * Truncate dependency structures beyond length.
7129 	 */
7130 	trunc_dependencies(ip, freeblks, lastlbn, frags, flags);
7131 	/*
7132 	 * This is only set when we need to allocate a fragment because
7133 	 * none existed at the end of a frag-sized file.  It handles only
7134 	 * allocating a new, zero filled block.
7135 	 */
7136 	if (allocblock) {
7137 		ip->i_size = length - lastoff;
7138 		DIP_SET(ip, i_size, ip->i_size);
7139 		error = UFS_BALLOC(vp, length - 1, 1, cred, BA_CLRBUF, &bp);
7140 		if (error != 0) {
7141 			softdep_error("softdep_journal_freeblks", error);
7142 			return;
7143 		}
7144 		ip->i_size = length;
7145 		DIP_SET(ip, i_size, length);
7146 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_UPDATE);
7147 		allocbuf(bp, frags);
7148 		ffs_update(vp, 0);
7149 		bawrite(bp);
7150 	} else if (lastoff != 0 && vp->v_type != VDIR) {
7151 		int size;
7152 
7153 		/*
7154 		 * Zero the end of a truncated frag or block.
7155 		 */
7156 		size = sblksize(fs, length, lastlbn);
7157 		error = bread(vp, lastlbn, size, cred, &bp);
7158 		if (error == 0) {
7159 			bzero((char *)bp->b_data + lastoff, size - lastoff);
7160 			bawrite(bp);
7161 		} else if (!ffs_fsfail_cleanup(ump, error)) {
7162 			softdep_error("softdep_journal_freeblks", error);
7163 			return;
7164 		}
7165 	}
7166 	ACQUIRE_LOCK(ump);
7167 	inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7168 	TAILQ_INSERT_TAIL(&inodedep->id_freeblklst, freeblks, fb_next);
7169 	freeblks->fb_state |= DEPCOMPLETE | ONDEPLIST;
7170 	/*
7171 	 * We zero earlier truncations so they don't erroneously
7172 	 * update i_blocks.
7173 	 */
7174 	if (freeblks->fb_len == 0 && (flags & IO_NORMAL) != 0)
7175 		TAILQ_FOREACH(fbn, &inodedep->id_freeblklst, fb_next)
7176 			fbn->fb_len = 0;
7177 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE &&
7178 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
7179 		freeblks->fb_state |= INPROGRESS;
7180 	else
7181 		freeblks = NULL;
7182 	FREE_LOCK(ump);
7183 	if (freeblks)
7184 		handle_workitem_freeblocks(freeblks, 0);
7185 	trunc_pages(ip, length, extblocks, flags);
7186 
7187 }
7188 
7189 /*
7190  * Flush a JOP_SYNC to the journal.
7191  */
7192 void
7193 softdep_journal_fsync(ip)
7194 	struct inode *ip;
7195 {
7196 	struct jfsync *jfsync;
7197 	struct ufsmount *ump;
7198 
7199 	ump = ITOUMP(ip);
7200 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7201 	    ("softdep_journal_fsync called on non-softdep filesystem"));
7202 	if ((ip->i_flag & IN_TRUNCATED) == 0)
7203 		return;
7204 	ip->i_flag &= ~IN_TRUNCATED;
7205 	jfsync = malloc(sizeof(*jfsync), M_JFSYNC, M_SOFTDEP_FLAGS | M_ZERO);
7206 	workitem_alloc(&jfsync->jfs_list, D_JFSYNC, UFSTOVFS(ump));
7207 	jfsync->jfs_size = ip->i_size;
7208 	jfsync->jfs_ino = ip->i_number;
7209 	ACQUIRE_LOCK(ump);
7210 	add_to_journal(&jfsync->jfs_list);
7211 	jwait(&jfsync->jfs_list, MNT_WAIT);
7212 	FREE_LOCK(ump);
7213 }
7214 
7215 /*
7216  * Block de-allocation dependencies.
7217  *
7218  * When blocks are de-allocated, the on-disk pointers must be nullified before
7219  * the blocks are made available for use by other files.  (The true
7220  * requirement is that old pointers must be nullified before new on-disk
7221  * pointers are set.  We chose this slightly more stringent requirement to
7222  * reduce complexity.) Our implementation handles this dependency by updating
7223  * the inode (or indirect block) appropriately but delaying the actual block
7224  * de-allocation (i.e., freemap and free space count manipulation) until
7225  * after the updated versions reach stable storage.  After the disk is
7226  * updated, the blocks can be safely de-allocated whenever it is convenient.
7227  * This implementation handles only the common case of reducing a file's
7228  * length to zero. Other cases are handled by the conventional synchronous
7229  * write approach.
7230  *
7231  * The ffs implementation with which we worked double-checks
7232  * the state of the block pointers and file size as it reduces
7233  * a file's length.  Some of this code is replicated here in our
7234  * soft updates implementation.  The freeblks->fb_chkcnt field is
7235  * used to transfer a part of this information to the procedure
7236  * that eventually de-allocates the blocks.
7237  *
7238  * This routine should be called from the routine that shortens
7239  * a file's length, before the inode's size or block pointers
7240  * are modified. It will save the block pointer information for
7241  * later release and zero the inode so that the calling routine
7242  * can release it.
7243  */
7244 void
7245 softdep_setup_freeblocks(ip, length, flags)
7246 	struct inode *ip;	/* The inode whose length is to be reduced */
7247 	off_t length;		/* The new length for the file */
7248 	int flags;		/* IO_EXT and/or IO_NORMAL */
7249 {
7250 	struct ufs1_dinode *dp1;
7251 	struct ufs2_dinode *dp2;
7252 	struct freeblks *freeblks;
7253 	struct inodedep *inodedep;
7254 	struct allocdirect *adp;
7255 	struct ufsmount *ump;
7256 	struct buf *bp;
7257 	struct fs *fs;
7258 	ufs2_daddr_t extblocks, datablocks;
7259 	struct mount *mp;
7260 	int i, delay, error;
7261 	ufs_lbn_t tmpval;
7262 	ufs_lbn_t lbn;
7263 
7264 	ump = ITOUMP(ip);
7265 	mp = UFSTOVFS(ump);
7266 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
7267 	    ("softdep_setup_freeblocks called on non-softdep filesystem"));
7268 	CTR2(KTR_SUJ, "softdep_setup_freeblks: ip %d length %ld",
7269 	    ip->i_number, length);
7270 	KASSERT(length == 0, ("softdep_setup_freeblocks: non-zero length"));
7271 	fs = ump->um_fs;
7272 	if ((error = bread(ump->um_devvp,
7273 	    fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
7274 	    (int)fs->fs_bsize, NOCRED, &bp)) != 0) {
7275 		if (!ffs_fsfail_cleanup(ump, error))
7276 			softdep_error("softdep_setup_freeblocks", error);
7277 		return;
7278 	}
7279 	freeblks = newfreeblks(mp, ip);
7280 	extblocks = 0;
7281 	datablocks = 0;
7282 	if (fs->fs_magic == FS_UFS2_MAGIC)
7283 		extblocks = btodb(fragroundup(fs, ip->i_din2->di_extsize));
7284 	if ((flags & IO_NORMAL) != 0) {
7285 		for (i = 0; i < UFS_NDADDR; i++)
7286 			setup_freedirect(freeblks, ip, i, 0);
7287 		for (i = 0, tmpval = NINDIR(fs), lbn = UFS_NDADDR;
7288 		    i < UFS_NIADDR;
7289 		    i++, lbn += tmpval, tmpval *= NINDIR(fs))
7290 			setup_freeindir(freeblks, ip, i, -lbn -i, 0);
7291 		ip->i_size = 0;
7292 		DIP_SET(ip, i_size, 0);
7293 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7294 		datablocks = DIP(ip, i_blocks) - extblocks;
7295 	}
7296 	if ((flags & IO_EXT) != 0) {
7297 		for (i = 0; i < UFS_NXADDR; i++)
7298 			setup_freeext(freeblks, ip, i, 0);
7299 		ip->i_din2->di_extsize = 0;
7300 		datablocks += extblocks;
7301 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE);
7302 	}
7303 #ifdef QUOTA
7304 	/* Reference the quotas in case the block count is wrong in the end. */
7305 	quotaref(ITOV(ip), freeblks->fb_quota);
7306 	(void) chkdq(ip, -datablocks, NOCRED, FORCE);
7307 #endif
7308 	freeblks->fb_chkcnt = -datablocks;
7309 	UFS_LOCK(ump);
7310 	fs->fs_pendingblocks += datablocks;
7311 	UFS_UNLOCK(ump);
7312 	DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - datablocks);
7313 	/*
7314 	 * Push the zero'ed inode to its disk buffer so that we are free
7315 	 * to delete its dependencies below. Once the dependencies are gone
7316 	 * the buffer can be safely released.
7317 	 */
7318 	if (ump->um_fstype == UFS1) {
7319 		dp1 = ((struct ufs1_dinode *)bp->b_data +
7320 		    ino_to_fsbo(fs, ip->i_number));
7321 		ip->i_din1->di_freelink = dp1->di_freelink;
7322 		*dp1 = *ip->i_din1;
7323 	} else {
7324 		dp2 = ((struct ufs2_dinode *)bp->b_data +
7325 		    ino_to_fsbo(fs, ip->i_number));
7326 		ip->i_din2->di_freelink = dp2->di_freelink;
7327 		ffs_update_dinode_ckhash(fs, ip->i_din2);
7328 		*dp2 = *ip->i_din2;
7329 	}
7330 	/*
7331 	 * Find and eliminate any inode dependencies.
7332 	 */
7333 	ACQUIRE_LOCK(ump);
7334 	(void) inodedep_lookup(mp, ip->i_number, DEPALLOC, &inodedep);
7335 	if ((inodedep->id_state & IOSTARTED) != 0)
7336 		panic("softdep_setup_freeblocks: inode busy");
7337 	/*
7338 	 * Add the freeblks structure to the list of operations that
7339 	 * must await the zero'ed inode being written to disk. If we
7340 	 * still have a bitmap dependency (delay == 0), then the inode
7341 	 * has never been written to disk, so we can process the
7342 	 * freeblks below once we have deleted the dependencies.
7343 	 */
7344 	delay = (inodedep->id_state & DEPCOMPLETE);
7345 	if (delay)
7346 		WORKLIST_INSERT(&bp->b_dep, &freeblks->fb_list);
7347 	else
7348 		freeblks->fb_state |= COMPLETE;
7349 	/*
7350 	 * Because the file length has been truncated to zero, any
7351 	 * pending block allocation dependency structures associated
7352 	 * with this inode are obsolete and can simply be de-allocated.
7353 	 * We must first merge the two dependency lists to get rid of
7354 	 * any duplicate freefrag structures, then purge the merged list.
7355 	 * If we still have a bitmap dependency, then the inode has never
7356 	 * been written to disk, so we can free any fragments without delay.
7357 	 */
7358 	if (flags & IO_NORMAL) {
7359 		merge_inode_lists(&inodedep->id_newinoupdt,
7360 		    &inodedep->id_inoupdt);
7361 		while ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
7362 			cancel_allocdirect(&inodedep->id_inoupdt, adp,
7363 			    freeblks);
7364 	}
7365 	if (flags & IO_EXT) {
7366 		merge_inode_lists(&inodedep->id_newextupdt,
7367 		    &inodedep->id_extupdt);
7368 		while ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
7369 			cancel_allocdirect(&inodedep->id_extupdt, adp,
7370 			    freeblks);
7371 	}
7372 	FREE_LOCK(ump);
7373 	bdwrite(bp);
7374 	trunc_dependencies(ip, freeblks, -1, 0, flags);
7375 	ACQUIRE_LOCK(ump);
7376 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
7377 		(void) free_inodedep(inodedep);
7378 	freeblks->fb_state |= DEPCOMPLETE;
7379 	/*
7380 	 * If the inode with zeroed block pointers is now on disk
7381 	 * we can start freeing blocks.
7382 	 */
7383 	if ((freeblks->fb_state & ALLCOMPLETE) == ALLCOMPLETE)
7384 		freeblks->fb_state |= INPROGRESS;
7385 	else
7386 		freeblks = NULL;
7387 	FREE_LOCK(ump);
7388 	if (freeblks)
7389 		handle_workitem_freeblocks(freeblks, 0);
7390 	trunc_pages(ip, length, extblocks, flags);
7391 }
7392 
7393 /*
7394  * Eliminate pages from the page cache that back parts of this inode and
7395  * adjust the vnode pager's idea of our size.  This prevents stale data
7396  * from hanging around in the page cache.
7397  */
7398 static void
7399 trunc_pages(ip, length, extblocks, flags)
7400 	struct inode *ip;
7401 	off_t length;
7402 	ufs2_daddr_t extblocks;
7403 	int flags;
7404 {
7405 	struct vnode *vp;
7406 	struct fs *fs;
7407 	ufs_lbn_t lbn;
7408 	off_t end, extend;
7409 
7410 	vp = ITOV(ip);
7411 	fs = ITOFS(ip);
7412 	extend = OFF_TO_IDX(lblktosize(fs, -extblocks));
7413 	if ((flags & IO_EXT) != 0)
7414 		vn_pages_remove(vp, extend, 0);
7415 	if ((flags & IO_NORMAL) == 0)
7416 		return;
7417 	BO_LOCK(&vp->v_bufobj);
7418 	drain_output(vp);
7419 	BO_UNLOCK(&vp->v_bufobj);
7420 	/*
7421 	 * The vnode pager eliminates file pages we eliminate indirects
7422 	 * below.
7423 	 */
7424 	vnode_pager_setsize(vp, length);
7425 	/*
7426 	 * Calculate the end based on the last indirect we want to keep.  If
7427 	 * the block extends into indirects we can just use the negative of
7428 	 * its lbn.  Doubles and triples exist at lower numbers so we must
7429 	 * be careful not to remove those, if they exist.  double and triple
7430 	 * indirect lbns do not overlap with others so it is not important
7431 	 * to verify how many levels are required.
7432 	 */
7433 	lbn = lblkno(fs, length);
7434 	if (lbn >= UFS_NDADDR) {
7435 		/* Calculate the virtual lbn of the triple indirect. */
7436 		lbn = -lbn - (UFS_NIADDR - 1);
7437 		end = OFF_TO_IDX(lblktosize(fs, lbn));
7438 	} else
7439 		end = extend;
7440 	vn_pages_remove(vp, OFF_TO_IDX(OFF_MAX), end);
7441 }
7442 
7443 /*
7444  * See if the buf bp is in the range eliminated by truncation.
7445  */
7446 static int
7447 trunc_check_buf(bp, blkoffp, lastlbn, lastoff, flags)
7448 	struct buf *bp;
7449 	int *blkoffp;
7450 	ufs_lbn_t lastlbn;
7451 	int lastoff;
7452 	int flags;
7453 {
7454 	ufs_lbn_t lbn;
7455 
7456 	*blkoffp = 0;
7457 	/* Only match ext/normal blocks as appropriate. */
7458 	if (((flags & IO_EXT) == 0 && (bp->b_xflags & BX_ALTDATA)) ||
7459 	    ((flags & IO_NORMAL) == 0 && (bp->b_xflags & BX_ALTDATA) == 0))
7460 		return (0);
7461 	/* ALTDATA is always a full truncation. */
7462 	if ((bp->b_xflags & BX_ALTDATA) != 0)
7463 		return (1);
7464 	/* -1 is full truncation. */
7465 	if (lastlbn == -1)
7466 		return (1);
7467 	/*
7468 	 * If this is a partial truncate we only want those
7469 	 * blocks and indirect blocks that cover the range
7470 	 * we're after.
7471 	 */
7472 	lbn = bp->b_lblkno;
7473 	if (lbn < 0)
7474 		lbn = -(lbn + lbn_level(lbn));
7475 	if (lbn < lastlbn)
7476 		return (0);
7477 	/* Here we only truncate lblkno if it's partial. */
7478 	if (lbn == lastlbn) {
7479 		if (lastoff == 0)
7480 			return (0);
7481 		*blkoffp = lastoff;
7482 	}
7483 	return (1);
7484 }
7485 
7486 /*
7487  * Eliminate any dependencies that exist in memory beyond lblkno:off
7488  */
7489 static void
7490 trunc_dependencies(ip, freeblks, lastlbn, lastoff, flags)
7491 	struct inode *ip;
7492 	struct freeblks *freeblks;
7493 	ufs_lbn_t lastlbn;
7494 	int lastoff;
7495 	int flags;
7496 {
7497 	struct bufobj *bo;
7498 	struct vnode *vp;
7499 	struct buf *bp;
7500 	int blkoff;
7501 
7502 	/*
7503 	 * We must wait for any I/O in progress to finish so that
7504 	 * all potential buffers on the dirty list will be visible.
7505 	 * Once they are all there, walk the list and get rid of
7506 	 * any dependencies.
7507 	 */
7508 	vp = ITOV(ip);
7509 	bo = &vp->v_bufobj;
7510 	BO_LOCK(bo);
7511 	drain_output(vp);
7512 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs)
7513 		bp->b_vflags &= ~BV_SCANNED;
7514 restart:
7515 	TAILQ_FOREACH(bp, &bo->bo_dirty.bv_hd, b_bobufs) {
7516 		if (bp->b_vflags & BV_SCANNED)
7517 			continue;
7518 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7519 			bp->b_vflags |= BV_SCANNED;
7520 			continue;
7521 		}
7522 		KASSERT(bp->b_bufobj == bo, ("Wrong object in buffer"));
7523 		if ((bp = getdirtybuf(bp, BO_LOCKPTR(bo), MNT_WAIT)) == NULL)
7524 			goto restart;
7525 		BO_UNLOCK(bo);
7526 		if (deallocate_dependencies(bp, freeblks, blkoff))
7527 			bqrelse(bp);
7528 		else
7529 			brelse(bp);
7530 		BO_LOCK(bo);
7531 		goto restart;
7532 	}
7533 	/*
7534 	 * Now do the work of vtruncbuf while also matching indirect blocks.
7535 	 */
7536 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs)
7537 		bp->b_vflags &= ~BV_SCANNED;
7538 cleanrestart:
7539 	TAILQ_FOREACH(bp, &bo->bo_clean.bv_hd, b_bobufs) {
7540 		if (bp->b_vflags & BV_SCANNED)
7541 			continue;
7542 		if (!trunc_check_buf(bp, &blkoff, lastlbn, lastoff, flags)) {
7543 			bp->b_vflags |= BV_SCANNED;
7544 			continue;
7545 		}
7546 		if (BUF_LOCK(bp,
7547 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
7548 		    BO_LOCKPTR(bo)) == ENOLCK) {
7549 			BO_LOCK(bo);
7550 			goto cleanrestart;
7551 		}
7552 		bp->b_vflags |= BV_SCANNED;
7553 		bremfree(bp);
7554 		if (blkoff != 0) {
7555 			allocbuf(bp, blkoff);
7556 			bqrelse(bp);
7557 		} else {
7558 			bp->b_flags |= B_INVAL | B_NOCACHE | B_RELBUF;
7559 			brelse(bp);
7560 		}
7561 		BO_LOCK(bo);
7562 		goto cleanrestart;
7563 	}
7564 	drain_output(vp);
7565 	BO_UNLOCK(bo);
7566 }
7567 
7568 static int
7569 cancel_pagedep(pagedep, freeblks, blkoff)
7570 	struct pagedep *pagedep;
7571 	struct freeblks *freeblks;
7572 	int blkoff;
7573 {
7574 	struct jremref *jremref;
7575 	struct jmvref *jmvref;
7576 	struct dirrem *dirrem, *tmp;
7577 	int i;
7578 
7579 	/*
7580 	 * Copy any directory remove dependencies to the list
7581 	 * to be processed after the freeblks proceeds.  If
7582 	 * directory entry never made it to disk they
7583 	 * can be dumped directly onto the work list.
7584 	 */
7585 	LIST_FOREACH_SAFE(dirrem, &pagedep->pd_dirremhd, dm_next, tmp) {
7586 		/* Skip this directory removal if it is intended to remain. */
7587 		if (dirrem->dm_offset < blkoff)
7588 			continue;
7589 		/*
7590 		 * If there are any dirrems we wait for the journal write
7591 		 * to complete and then restart the buf scan as the lock
7592 		 * has been dropped.
7593 		 */
7594 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL) {
7595 			jwait(&jremref->jr_list, MNT_WAIT);
7596 			return (ERESTART);
7597 		}
7598 		LIST_REMOVE(dirrem, dm_next);
7599 		dirrem->dm_dirinum = pagedep->pd_ino;
7600 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &dirrem->dm_list);
7601 	}
7602 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL) {
7603 		jwait(&jmvref->jm_list, MNT_WAIT);
7604 		return (ERESTART);
7605 	}
7606 	/*
7607 	 * When we're partially truncating a pagedep we just want to flush
7608 	 * journal entries and return.  There can not be any adds in the
7609 	 * truncated portion of the directory and newblk must remain if
7610 	 * part of the block remains.
7611 	 */
7612 	if (blkoff != 0) {
7613 		struct diradd *dap;
7614 
7615 		LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
7616 			if (dap->da_offset > blkoff)
7617 				panic("cancel_pagedep: diradd %p off %d > %d",
7618 				    dap, dap->da_offset, blkoff);
7619 		for (i = 0; i < DAHASHSZ; i++)
7620 			LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist)
7621 				if (dap->da_offset > blkoff)
7622 					panic("cancel_pagedep: diradd %p off %d > %d",
7623 					    dap, dap->da_offset, blkoff);
7624 		return (0);
7625 	}
7626 	/*
7627 	 * There should be no directory add dependencies present
7628 	 * as the directory could not be truncated until all
7629 	 * children were removed.
7630 	 */
7631 	KASSERT(LIST_FIRST(&pagedep->pd_pendinghd) == NULL,
7632 	    ("deallocate_dependencies: pendinghd != NULL"));
7633 	for (i = 0; i < DAHASHSZ; i++)
7634 		KASSERT(LIST_FIRST(&pagedep->pd_diraddhd[i]) == NULL,
7635 		    ("deallocate_dependencies: diraddhd != NULL"));
7636 	if ((pagedep->pd_state & NEWBLOCK) != 0)
7637 		free_newdirblk(pagedep->pd_newdirblk);
7638 	if (free_pagedep(pagedep) == 0)
7639 		panic("Failed to free pagedep %p", pagedep);
7640 	return (0);
7641 }
7642 
7643 /*
7644  * Reclaim any dependency structures from a buffer that is about to
7645  * be reallocated to a new vnode. The buffer must be locked, thus,
7646  * no I/O completion operations can occur while we are manipulating
7647  * its associated dependencies. The mutex is held so that other I/O's
7648  * associated with related dependencies do not occur.
7649  */
7650 static int
7651 deallocate_dependencies(bp, freeblks, off)
7652 	struct buf *bp;
7653 	struct freeblks *freeblks;
7654 	int off;
7655 {
7656 	struct indirdep *indirdep;
7657 	struct pagedep *pagedep;
7658 	struct worklist *wk, *wkn;
7659 	struct ufsmount *ump;
7660 
7661 	ump = softdep_bp_to_mp(bp);
7662 	if (ump == NULL)
7663 		goto done;
7664 	ACQUIRE_LOCK(ump);
7665 	LIST_FOREACH_SAFE(wk, &bp->b_dep, wk_list, wkn) {
7666 		switch (wk->wk_type) {
7667 		case D_INDIRDEP:
7668 			indirdep = WK_INDIRDEP(wk);
7669 			if (bp->b_lblkno >= 0 ||
7670 			    bp->b_blkno != indirdep->ir_savebp->b_lblkno)
7671 				panic("deallocate_dependencies: not indir");
7672 			cancel_indirdep(indirdep, bp, freeblks);
7673 			continue;
7674 
7675 		case D_PAGEDEP:
7676 			pagedep = WK_PAGEDEP(wk);
7677 			if (cancel_pagedep(pagedep, freeblks, off)) {
7678 				FREE_LOCK(ump);
7679 				return (ERESTART);
7680 			}
7681 			continue;
7682 
7683 		case D_ALLOCINDIR:
7684 			/*
7685 			 * Simply remove the allocindir, we'll find it via
7686 			 * the indirdep where we can clear pointers if
7687 			 * needed.
7688 			 */
7689 			WORKLIST_REMOVE(wk);
7690 			continue;
7691 
7692 		case D_FREEWORK:
7693 			/*
7694 			 * A truncation is waiting for the zero'd pointers
7695 			 * to be written.  It can be freed when the freeblks
7696 			 * is journaled.
7697 			 */
7698 			WORKLIST_REMOVE(wk);
7699 			wk->wk_state |= ONDEPLIST;
7700 			WORKLIST_INSERT(&freeblks->fb_freeworkhd, wk);
7701 			break;
7702 
7703 		case D_ALLOCDIRECT:
7704 			if (off != 0)
7705 				continue;
7706 			/* FALLTHROUGH */
7707 		default:
7708 			panic("deallocate_dependencies: Unexpected type %s",
7709 			    TYPENAME(wk->wk_type));
7710 			/* NOTREACHED */
7711 		}
7712 	}
7713 	FREE_LOCK(ump);
7714 done:
7715 	/*
7716 	 * Don't throw away this buf, we were partially truncating and
7717 	 * some deps may always remain.
7718 	 */
7719 	if (off) {
7720 		allocbuf(bp, off);
7721 		bp->b_vflags |= BV_SCANNED;
7722 		return (EBUSY);
7723 	}
7724 	bp->b_flags |= B_INVAL | B_NOCACHE;
7725 
7726 	return (0);
7727 }
7728 
7729 /*
7730  * An allocdirect is being canceled due to a truncate.  We must make sure
7731  * the journal entry is released in concert with the blkfree that releases
7732  * the storage.  Completed journal entries must not be released until the
7733  * space is no longer pointed to by the inode or in the bitmap.
7734  */
7735 static void
7736 cancel_allocdirect(adphead, adp, freeblks)
7737 	struct allocdirectlst *adphead;
7738 	struct allocdirect *adp;
7739 	struct freeblks *freeblks;
7740 {
7741 	struct freework *freework;
7742 	struct newblk *newblk;
7743 	struct worklist *wk;
7744 
7745 	TAILQ_REMOVE(adphead, adp, ad_next);
7746 	newblk = (struct newblk *)adp;
7747 	freework = NULL;
7748 	/*
7749 	 * Find the correct freework structure.
7750 	 */
7751 	LIST_FOREACH(wk, &freeblks->fb_freeworkhd, wk_list) {
7752 		if (wk->wk_type != D_FREEWORK)
7753 			continue;
7754 		freework = WK_FREEWORK(wk);
7755 		if (freework->fw_blkno == newblk->nb_newblkno)
7756 			break;
7757 	}
7758 	if (freework == NULL)
7759 		panic("cancel_allocdirect: Freework not found");
7760 	/*
7761 	 * If a newblk exists at all we still have the journal entry that
7762 	 * initiated the allocation so we do not need to journal the free.
7763 	 */
7764 	cancel_jfreeblk(freeblks, freework->fw_blkno);
7765 	/*
7766 	 * If the journal hasn't been written the jnewblk must be passed
7767 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
7768 	 * this by linking the journal dependency into the freework to be
7769 	 * freed when freework_freeblock() is called.  If the journal has
7770 	 * been written we can simply reclaim the journal space when the
7771 	 * freeblks work is complete.
7772 	 */
7773 	freework->fw_jnewblk = cancel_newblk(newblk, &freework->fw_list,
7774 	    &freeblks->fb_jwork);
7775 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
7776 }
7777 
7778 /*
7779  * Cancel a new block allocation.  May be an indirect or direct block.  We
7780  * remove it from various lists and return any journal record that needs to
7781  * be resolved by the caller.
7782  *
7783  * A special consideration is made for indirects which were never pointed
7784  * at on disk and will never be found once this block is released.
7785  */
7786 static struct jnewblk *
7787 cancel_newblk(newblk, wk, wkhd)
7788 	struct newblk *newblk;
7789 	struct worklist *wk;
7790 	struct workhead *wkhd;
7791 {
7792 	struct jnewblk *jnewblk;
7793 
7794 	CTR1(KTR_SUJ, "cancel_newblk: blkno %jd", newblk->nb_newblkno);
7795 
7796 	newblk->nb_state |= GOINGAWAY;
7797 	/*
7798 	 * Previously we traversed the completedhd on each indirdep
7799 	 * attached to this newblk to cancel them and gather journal
7800 	 * work.  Since we need only the oldest journal segment and
7801 	 * the lowest point on the tree will always have the oldest
7802 	 * journal segment we are free to release the segments
7803 	 * of any subordinates and may leave the indirdep list to
7804 	 * indirdep_complete() when this newblk is freed.
7805 	 */
7806 	if (newblk->nb_state & ONDEPLIST) {
7807 		newblk->nb_state &= ~ONDEPLIST;
7808 		LIST_REMOVE(newblk, nb_deps);
7809 	}
7810 	if (newblk->nb_state & ONWORKLIST)
7811 		WORKLIST_REMOVE(&newblk->nb_list);
7812 	/*
7813 	 * If the journal entry hasn't been written we save a pointer to
7814 	 * the dependency that frees it until it is written or the
7815 	 * superseding operation completes.
7816 	 */
7817 	jnewblk = newblk->nb_jnewblk;
7818 	if (jnewblk != NULL && wk != NULL) {
7819 		newblk->nb_jnewblk = NULL;
7820 		jnewblk->jn_dep = wk;
7821 	}
7822 	if (!LIST_EMPTY(&newblk->nb_jwork))
7823 		jwork_move(wkhd, &newblk->nb_jwork);
7824 	/*
7825 	 * When truncating we must free the newdirblk early to remove
7826 	 * the pagedep from the hash before returning.
7827 	 */
7828 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7829 		free_newdirblk(WK_NEWDIRBLK(wk));
7830 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7831 		panic("cancel_newblk: extra newdirblk");
7832 
7833 	return (jnewblk);
7834 }
7835 
7836 /*
7837  * Schedule the freefrag associated with a newblk to be released once
7838  * the pointers are written and the previous block is no longer needed.
7839  */
7840 static void
7841 newblk_freefrag(newblk)
7842 	struct newblk *newblk;
7843 {
7844 	struct freefrag *freefrag;
7845 
7846 	if (newblk->nb_freefrag == NULL)
7847 		return;
7848 	freefrag = newblk->nb_freefrag;
7849 	newblk->nb_freefrag = NULL;
7850 	freefrag->ff_state |= COMPLETE;
7851 	if ((freefrag->ff_state & ALLCOMPLETE) == ALLCOMPLETE)
7852 		add_to_worklist(&freefrag->ff_list, 0);
7853 }
7854 
7855 /*
7856  * Free a newblk. Generate a new freefrag work request if appropriate.
7857  * This must be called after the inode pointer and any direct block pointers
7858  * are valid or fully removed via truncate or frag extension.
7859  */
7860 static void
7861 free_newblk(newblk)
7862 	struct newblk *newblk;
7863 {
7864 	struct indirdep *indirdep;
7865 	struct worklist *wk;
7866 
7867 	KASSERT(newblk->nb_jnewblk == NULL,
7868 	    ("free_newblk: jnewblk %p still attached", newblk->nb_jnewblk));
7869 	KASSERT(newblk->nb_list.wk_type != D_NEWBLK,
7870 	    ("free_newblk: unclaimed newblk"));
7871 	LOCK_OWNED(VFSTOUFS(newblk->nb_list.wk_mp));
7872 	newblk_freefrag(newblk);
7873 	if (newblk->nb_state & ONDEPLIST)
7874 		LIST_REMOVE(newblk, nb_deps);
7875 	if (newblk->nb_state & ONWORKLIST)
7876 		WORKLIST_REMOVE(&newblk->nb_list);
7877 	LIST_REMOVE(newblk, nb_hash);
7878 	if ((wk = LIST_FIRST(&newblk->nb_newdirblk)) != NULL)
7879 		free_newdirblk(WK_NEWDIRBLK(wk));
7880 	if (!LIST_EMPTY(&newblk->nb_newdirblk))
7881 		panic("free_newblk: extra newdirblk");
7882 	while ((indirdep = LIST_FIRST(&newblk->nb_indirdeps)) != NULL)
7883 		indirdep_complete(indirdep);
7884 	handle_jwork(&newblk->nb_jwork);
7885 	WORKITEM_FREE(newblk, D_NEWBLK);
7886 }
7887 
7888 /*
7889  * Free a newdirblk. Clear the NEWBLOCK flag on its associated pagedep.
7890  */
7891 static void
7892 free_newdirblk(newdirblk)
7893 	struct newdirblk *newdirblk;
7894 {
7895 	struct pagedep *pagedep;
7896 	struct diradd *dap;
7897 	struct worklist *wk;
7898 
7899 	LOCK_OWNED(VFSTOUFS(newdirblk->db_list.wk_mp));
7900 	WORKLIST_REMOVE(&newdirblk->db_list);
7901 	/*
7902 	 * If the pagedep is still linked onto the directory buffer
7903 	 * dependency chain, then some of the entries on the
7904 	 * pd_pendinghd list may not be committed to disk yet. In
7905 	 * this case, we will simply clear the NEWBLOCK flag and
7906 	 * let the pd_pendinghd list be processed when the pagedep
7907 	 * is next written. If the pagedep is no longer on the buffer
7908 	 * dependency chain, then all the entries on the pd_pending
7909 	 * list are committed to disk and we can free them here.
7910 	 */
7911 	pagedep = newdirblk->db_pagedep;
7912 	pagedep->pd_state &= ~NEWBLOCK;
7913 	if ((pagedep->pd_state & ONWORKLIST) == 0) {
7914 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
7915 			free_diradd(dap, NULL);
7916 		/*
7917 		 * If no dependencies remain, the pagedep will be freed.
7918 		 */
7919 		free_pagedep(pagedep);
7920 	}
7921 	/* Should only ever be one item in the list. */
7922 	while ((wk = LIST_FIRST(&newdirblk->db_mkdir)) != NULL) {
7923 		WORKLIST_REMOVE(wk);
7924 		handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
7925 	}
7926 	WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
7927 }
7928 
7929 /*
7930  * Prepare an inode to be freed. The actual free operation is not
7931  * done until the zero'ed inode has been written to disk.
7932  */
7933 void
7934 softdep_freefile(pvp, ino, mode)
7935 	struct vnode *pvp;
7936 	ino_t ino;
7937 	int mode;
7938 {
7939 	struct inode *ip = VTOI(pvp);
7940 	struct inodedep *inodedep;
7941 	struct freefile *freefile;
7942 	struct freeblks *freeblks;
7943 	struct ufsmount *ump;
7944 
7945 	ump = ITOUMP(ip);
7946 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
7947 	    ("softdep_freefile called on non-softdep filesystem"));
7948 	/*
7949 	 * This sets up the inode de-allocation dependency.
7950 	 */
7951 	freefile = malloc(sizeof(struct freefile),
7952 		M_FREEFILE, M_SOFTDEP_FLAGS);
7953 	workitem_alloc(&freefile->fx_list, D_FREEFILE, pvp->v_mount);
7954 	freefile->fx_mode = mode;
7955 	freefile->fx_oldinum = ino;
7956 	freefile->fx_devvp = ump->um_devvp;
7957 	LIST_INIT(&freefile->fx_jwork);
7958 	UFS_LOCK(ump);
7959 	ump->um_fs->fs_pendinginodes += 1;
7960 	UFS_UNLOCK(ump);
7961 
7962 	/*
7963 	 * If the inodedep does not exist, then the zero'ed inode has
7964 	 * been written to disk. If the allocated inode has never been
7965 	 * written to disk, then the on-disk inode is zero'ed. In either
7966 	 * case we can free the file immediately.  If the journal was
7967 	 * canceled before being written the inode will never make it to
7968 	 * disk and we must send the canceled journal entrys to
7969 	 * ffs_freefile() to be cleared in conjunction with the bitmap.
7970 	 * Any blocks waiting on the inode to write can be safely freed
7971 	 * here as it will never been written.
7972 	 */
7973 	ACQUIRE_LOCK(ump);
7974 	inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
7975 	if (inodedep) {
7976 		/*
7977 		 * Clear out freeblks that no longer need to reference
7978 		 * this inode.
7979 		 */
7980 		while ((freeblks =
7981 		    TAILQ_FIRST(&inodedep->id_freeblklst)) != NULL) {
7982 			TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks,
7983 			    fb_next);
7984 			freeblks->fb_state &= ~ONDEPLIST;
7985 		}
7986 		/*
7987 		 * Remove this inode from the unlinked list.
7988 		 */
7989 		if (inodedep->id_state & UNLINKED) {
7990 			/*
7991 			 * Save the journal work to be freed with the bitmap
7992 			 * before we clear UNLINKED.  Otherwise it can be lost
7993 			 * if the inode block is written.
7994 			 */
7995 			handle_bufwait(inodedep, &freefile->fx_jwork);
7996 			clear_unlinked_inodedep(inodedep);
7997 			/*
7998 			 * Re-acquire inodedep as we've dropped the
7999 			 * per-filesystem lock in clear_unlinked_inodedep().
8000 			 */
8001 			inodedep_lookup(pvp->v_mount, ino, 0, &inodedep);
8002 		}
8003 	}
8004 	if (inodedep == NULL || check_inode_unwritten(inodedep)) {
8005 		FREE_LOCK(ump);
8006 		handle_workitem_freefile(freefile);
8007 		return;
8008 	}
8009 	if ((inodedep->id_state & DEPCOMPLETE) == 0)
8010 		inodedep->id_state |= GOINGAWAY;
8011 	WORKLIST_INSERT(&inodedep->id_inowait, &freefile->fx_list);
8012 	FREE_LOCK(ump);
8013 	if (ip->i_number == ino)
8014 		UFS_INODE_SET_FLAG(ip, IN_MODIFIED);
8015 }
8016 
8017 /*
8018  * Check to see if an inode has never been written to disk. If
8019  * so free the inodedep and return success, otherwise return failure.
8020  *
8021  * If we still have a bitmap dependency, then the inode has never
8022  * been written to disk. Drop the dependency as it is no longer
8023  * necessary since the inode is being deallocated. We set the
8024  * ALLCOMPLETE flags since the bitmap now properly shows that the
8025  * inode is not allocated. Even if the inode is actively being
8026  * written, it has been rolled back to its zero'ed state, so we
8027  * are ensured that a zero inode is what is on the disk. For short
8028  * lived files, this change will usually result in removing all the
8029  * dependencies from the inode so that it can be freed immediately.
8030  */
8031 static int
8032 check_inode_unwritten(inodedep)
8033 	struct inodedep *inodedep;
8034 {
8035 
8036 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8037 
8038 	if ((inodedep->id_state & (DEPCOMPLETE | UNLINKED)) != 0 ||
8039 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8040 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8041 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8042 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8043 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8044 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8045 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8046 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8047 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8048 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8049 	    inodedep->id_mkdiradd != NULL ||
8050 	    inodedep->id_nlinkdelta != 0)
8051 		return (0);
8052 	/*
8053 	 * Another process might be in initiate_write_inodeblock_ufs[12]
8054 	 * trying to allocate memory without holding "Softdep Lock".
8055 	 */
8056 	if ((inodedep->id_state & IOSTARTED) != 0 &&
8057 	    inodedep->id_savedino1 == NULL)
8058 		return (0);
8059 
8060 	if (inodedep->id_state & ONDEPLIST)
8061 		LIST_REMOVE(inodedep, id_deps);
8062 	inodedep->id_state &= ~ONDEPLIST;
8063 	inodedep->id_state |= ALLCOMPLETE;
8064 	inodedep->id_bmsafemap = NULL;
8065 	if (inodedep->id_state & ONWORKLIST)
8066 		WORKLIST_REMOVE(&inodedep->id_list);
8067 	if (inodedep->id_savedino1 != NULL) {
8068 		free(inodedep->id_savedino1, M_SAVEDINO);
8069 		inodedep->id_savedino1 = NULL;
8070 	}
8071 	if (free_inodedep(inodedep) == 0)
8072 		panic("check_inode_unwritten: busy inode");
8073 	return (1);
8074 }
8075 
8076 static int
8077 check_inodedep_free(inodedep)
8078 	struct inodedep *inodedep;
8079 {
8080 
8081 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8082 	if ((inodedep->id_state & ALLCOMPLETE) != ALLCOMPLETE ||
8083 	    !LIST_EMPTY(&inodedep->id_dirremhd) ||
8084 	    !LIST_EMPTY(&inodedep->id_pendinghd) ||
8085 	    !LIST_EMPTY(&inodedep->id_bufwait) ||
8086 	    !LIST_EMPTY(&inodedep->id_inowait) ||
8087 	    !TAILQ_EMPTY(&inodedep->id_inoreflst) ||
8088 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
8089 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt) ||
8090 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
8091 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
8092 	    !TAILQ_EMPTY(&inodedep->id_freeblklst) ||
8093 	    inodedep->id_mkdiradd != NULL ||
8094 	    inodedep->id_nlinkdelta != 0 ||
8095 	    inodedep->id_savedino1 != NULL)
8096 		return (0);
8097 	return (1);
8098 }
8099 
8100 /*
8101  * Try to free an inodedep structure. Return 1 if it could be freed.
8102  */
8103 static int
8104 free_inodedep(inodedep)
8105 	struct inodedep *inodedep;
8106 {
8107 
8108 	LOCK_OWNED(VFSTOUFS(inodedep->id_list.wk_mp));
8109 	if ((inodedep->id_state & (ONWORKLIST | UNLINKED)) != 0 ||
8110 	    !check_inodedep_free(inodedep))
8111 		return (0);
8112 	if (inodedep->id_state & ONDEPLIST)
8113 		LIST_REMOVE(inodedep, id_deps);
8114 	LIST_REMOVE(inodedep, id_hash);
8115 	WORKITEM_FREE(inodedep, D_INODEDEP);
8116 	return (1);
8117 }
8118 
8119 /*
8120  * Free the block referenced by a freework structure.  The parent freeblks
8121  * structure is released and completed when the final cg bitmap reaches
8122  * the disk.  This routine may be freeing a jnewblk which never made it to
8123  * disk in which case we do not have to wait as the operation is undone
8124  * in memory immediately.
8125  */
8126 static void
8127 freework_freeblock(freework, key)
8128 	struct freework *freework;
8129 	u_long key;
8130 {
8131 	struct freeblks *freeblks;
8132 	struct jnewblk *jnewblk;
8133 	struct ufsmount *ump;
8134 	struct workhead wkhd;
8135 	struct fs *fs;
8136 	int bsize;
8137 	int needj;
8138 
8139 	ump = VFSTOUFS(freework->fw_list.wk_mp);
8140 	LOCK_OWNED(ump);
8141 	/*
8142 	 * Handle partial truncate separately.
8143 	 */
8144 	if (freework->fw_indir) {
8145 		complete_trunc_indir(freework);
8146 		return;
8147 	}
8148 	freeblks = freework->fw_freeblks;
8149 	fs = ump->um_fs;
8150 	needj = MOUNTEDSUJ(freeblks->fb_list.wk_mp) != 0;
8151 	bsize = lfragtosize(fs, freework->fw_frags);
8152 	LIST_INIT(&wkhd);
8153 	/*
8154 	 * DEPCOMPLETE is cleared in indirblk_insert() if the block lives
8155 	 * on the indirblk hashtable and prevents premature freeing.
8156 	 */
8157 	freework->fw_state |= DEPCOMPLETE;
8158 	/*
8159 	 * SUJ needs to wait for the segment referencing freed indirect
8160 	 * blocks to expire so that we know the checker will not confuse
8161 	 * a re-allocated indirect block with its old contents.
8162 	 */
8163 	if (needj && freework->fw_lbn <= -UFS_NDADDR)
8164 		indirblk_insert(freework);
8165 	/*
8166 	 * If we are canceling an existing jnewblk pass it to the free
8167 	 * routine, otherwise pass the freeblk which will ultimately
8168 	 * release the freeblks.  If we're not journaling, we can just
8169 	 * free the freeblks immediately.
8170 	 */
8171 	jnewblk = freework->fw_jnewblk;
8172 	if (jnewblk != NULL) {
8173 		cancel_jnewblk(jnewblk, &wkhd);
8174 		needj = 0;
8175 	} else if (needj) {
8176 		freework->fw_state |= DELAYEDFREE;
8177 		freeblks->fb_cgwait++;
8178 		WORKLIST_INSERT(&wkhd, &freework->fw_list);
8179 	}
8180 	FREE_LOCK(ump);
8181 	freeblks_free(ump, freeblks, btodb(bsize));
8182 	CTR4(KTR_SUJ,
8183 	    "freework_freeblock: ino %jd blkno %jd lbn %jd size %d",
8184 	    freeblks->fb_inum, freework->fw_blkno, freework->fw_lbn, bsize);
8185 	ffs_blkfree(ump, fs, freeblks->fb_devvp, freework->fw_blkno, bsize,
8186 	    freeblks->fb_inum, freeblks->fb_vtype, &wkhd, key);
8187 	ACQUIRE_LOCK(ump);
8188 	/*
8189 	 * The jnewblk will be discarded and the bits in the map never
8190 	 * made it to disk.  We can immediately free the freeblk.
8191 	 */
8192 	if (needj == 0)
8193 		handle_written_freework(freework);
8194 }
8195 
8196 /*
8197  * We enqueue freework items that need processing back on the freeblks and
8198  * add the freeblks to the worklist.  This makes it easier to find all work
8199  * required to flush a truncation in process_truncates().
8200  */
8201 static void
8202 freework_enqueue(freework)
8203 	struct freework *freework;
8204 {
8205 	struct freeblks *freeblks;
8206 
8207 	freeblks = freework->fw_freeblks;
8208 	if ((freework->fw_state & INPROGRESS) == 0)
8209 		WORKLIST_INSERT(&freeblks->fb_freeworkhd, &freework->fw_list);
8210 	if ((freeblks->fb_state &
8211 	    (ONWORKLIST | INPROGRESS | ALLCOMPLETE)) == ALLCOMPLETE &&
8212 	    LIST_EMPTY(&freeblks->fb_jblkdephd))
8213 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8214 }
8215 
8216 /*
8217  * Start, continue, or finish the process of freeing an indirect block tree.
8218  * The free operation may be paused at any point with fw_off containing the
8219  * offset to restart from.  This enables us to implement some flow control
8220  * for large truncates which may fan out and generate a huge number of
8221  * dependencies.
8222  */
8223 static void
8224 handle_workitem_indirblk(freework)
8225 	struct freework *freework;
8226 {
8227 	struct freeblks *freeblks;
8228 	struct ufsmount *ump;
8229 	struct fs *fs;
8230 
8231 	freeblks = freework->fw_freeblks;
8232 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8233 	fs = ump->um_fs;
8234 	if (freework->fw_state & DEPCOMPLETE) {
8235 		handle_written_freework(freework);
8236 		return;
8237 	}
8238 	if (freework->fw_off == NINDIR(fs)) {
8239 		freework_freeblock(freework, SINGLETON_KEY);
8240 		return;
8241 	}
8242 	freework->fw_state |= INPROGRESS;
8243 	FREE_LOCK(ump);
8244 	indir_trunc(freework, fsbtodb(fs, freework->fw_blkno),
8245 	    freework->fw_lbn);
8246 	ACQUIRE_LOCK(ump);
8247 }
8248 
8249 /*
8250  * Called when a freework structure attached to a cg buf is written.  The
8251  * ref on either the parent or the freeblks structure is released and
8252  * the freeblks is added back to the worklist if there is more work to do.
8253  */
8254 static void
8255 handle_written_freework(freework)
8256 	struct freework *freework;
8257 {
8258 	struct freeblks *freeblks;
8259 	struct freework *parent;
8260 
8261 	freeblks = freework->fw_freeblks;
8262 	parent = freework->fw_parent;
8263 	if (freework->fw_state & DELAYEDFREE)
8264 		freeblks->fb_cgwait--;
8265 	freework->fw_state |= COMPLETE;
8266 	if ((freework->fw_state & ALLCOMPLETE) == ALLCOMPLETE)
8267 		WORKITEM_FREE(freework, D_FREEWORK);
8268 	if (parent) {
8269 		if (--parent->fw_ref == 0)
8270 			freework_enqueue(parent);
8271 		return;
8272 	}
8273 	if (--freeblks->fb_ref != 0)
8274 		return;
8275 	if ((freeblks->fb_state & (ALLCOMPLETE | ONWORKLIST | INPROGRESS)) ==
8276 	    ALLCOMPLETE && LIST_EMPTY(&freeblks->fb_jblkdephd))
8277 		add_to_worklist(&freeblks->fb_list, WK_NODELAY);
8278 }
8279 
8280 /*
8281  * This workitem routine performs the block de-allocation.
8282  * The workitem is added to the pending list after the updated
8283  * inode block has been written to disk.  As mentioned above,
8284  * checks regarding the number of blocks de-allocated (compared
8285  * to the number of blocks allocated for the file) are also
8286  * performed in this function.
8287  */
8288 static int
8289 handle_workitem_freeblocks(freeblks, flags)
8290 	struct freeblks *freeblks;
8291 	int flags;
8292 {
8293 	struct freework *freework;
8294 	struct newblk *newblk;
8295 	struct allocindir *aip;
8296 	struct ufsmount *ump;
8297 	struct worklist *wk;
8298 	u_long key;
8299 
8300 	KASSERT(LIST_EMPTY(&freeblks->fb_jblkdephd),
8301 	    ("handle_workitem_freeblocks: Journal entries not written."));
8302 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8303 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8304 	ACQUIRE_LOCK(ump);
8305 	while ((wk = LIST_FIRST(&freeblks->fb_freeworkhd)) != NULL) {
8306 		WORKLIST_REMOVE(wk);
8307 		switch (wk->wk_type) {
8308 		case D_DIRREM:
8309 			wk->wk_state |= COMPLETE;
8310 			add_to_worklist(wk, 0);
8311 			continue;
8312 
8313 		case D_ALLOCDIRECT:
8314 			free_newblk(WK_NEWBLK(wk));
8315 			continue;
8316 
8317 		case D_ALLOCINDIR:
8318 			aip = WK_ALLOCINDIR(wk);
8319 			freework = NULL;
8320 			if (aip->ai_state & DELAYEDFREE) {
8321 				FREE_LOCK(ump);
8322 				freework = newfreework(ump, freeblks, NULL,
8323 				    aip->ai_lbn, aip->ai_newblkno,
8324 				    ump->um_fs->fs_frag, 0, 0);
8325 				ACQUIRE_LOCK(ump);
8326 			}
8327 			newblk = WK_NEWBLK(wk);
8328 			if (newblk->nb_jnewblk) {
8329 				freework->fw_jnewblk = newblk->nb_jnewblk;
8330 				newblk->nb_jnewblk->jn_dep = &freework->fw_list;
8331 				newblk->nb_jnewblk = NULL;
8332 			}
8333 			free_newblk(newblk);
8334 			continue;
8335 
8336 		case D_FREEWORK:
8337 			freework = WK_FREEWORK(wk);
8338 			if (freework->fw_lbn <= -UFS_NDADDR)
8339 				handle_workitem_indirblk(freework);
8340 			else
8341 				freework_freeblock(freework, key);
8342 			continue;
8343 		default:
8344 			panic("handle_workitem_freeblocks: Unknown type %s",
8345 			    TYPENAME(wk->wk_type));
8346 		}
8347 	}
8348 	if (freeblks->fb_ref != 0) {
8349 		freeblks->fb_state &= ~INPROGRESS;
8350 		wake_worklist(&freeblks->fb_list);
8351 		freeblks = NULL;
8352 	}
8353 	FREE_LOCK(ump);
8354 	ffs_blkrelease_finish(ump, key);
8355 	if (freeblks)
8356 		return handle_complete_freeblocks(freeblks, flags);
8357 	return (0);
8358 }
8359 
8360 /*
8361  * Handle completion of block free via truncate.  This allows fs_pending
8362  * to track the actual free block count more closely than if we only updated
8363  * it at the end.  We must be careful to handle cases where the block count
8364  * on free was incorrect.
8365  */
8366 static void
8367 freeblks_free(ump, freeblks, blocks)
8368 	struct ufsmount *ump;
8369 	struct freeblks *freeblks;
8370 	int blocks;
8371 {
8372 	struct fs *fs;
8373 	ufs2_daddr_t remain;
8374 
8375 	UFS_LOCK(ump);
8376 	remain = -freeblks->fb_chkcnt;
8377 	freeblks->fb_chkcnt += blocks;
8378 	if (remain > 0) {
8379 		if (remain < blocks)
8380 			blocks = remain;
8381 		fs = ump->um_fs;
8382 		fs->fs_pendingblocks -= blocks;
8383 	}
8384 	UFS_UNLOCK(ump);
8385 }
8386 
8387 /*
8388  * Once all of the freework workitems are complete we can retire the
8389  * freeblocks dependency and any journal work awaiting completion.  This
8390  * can not be called until all other dependencies are stable on disk.
8391  */
8392 static int
8393 handle_complete_freeblocks(freeblks, flags)
8394 	struct freeblks *freeblks;
8395 	int flags;
8396 {
8397 	struct inodedep *inodedep;
8398 	struct inode *ip;
8399 	struct vnode *vp;
8400 	struct fs *fs;
8401 	struct ufsmount *ump;
8402 	ufs2_daddr_t spare;
8403 
8404 	ump = VFSTOUFS(freeblks->fb_list.wk_mp);
8405 	fs = ump->um_fs;
8406 	flags = LK_EXCLUSIVE | flags;
8407 	spare = freeblks->fb_chkcnt;
8408 
8409 	/*
8410 	 * If we did not release the expected number of blocks we may have
8411 	 * to adjust the inode block count here.  Only do so if it wasn't
8412 	 * a truncation to zero and the modrev still matches.
8413 	 */
8414 	if (spare && freeblks->fb_len != 0) {
8415 		if (ffs_vgetf(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8416 		    flags, &vp, FFSV_FORCEINSMQ) != 0)
8417 			return (EBUSY);
8418 		ip = VTOI(vp);
8419 		if (ip->i_mode == 0) {
8420 			vgone(vp);
8421 		} else if (DIP(ip, i_modrev) == freeblks->fb_modrev) {
8422 			DIP_SET(ip, i_blocks, DIP(ip, i_blocks) - spare);
8423 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
8424 			/*
8425 			 * We must wait so this happens before the
8426 			 * journal is reclaimed.
8427 			 */
8428 			ffs_update(vp, 1);
8429 		}
8430 		vput(vp);
8431 	}
8432 	if (spare < 0) {
8433 		UFS_LOCK(ump);
8434 		fs->fs_pendingblocks += spare;
8435 		UFS_UNLOCK(ump);
8436 	}
8437 #ifdef QUOTA
8438 	/* Handle spare. */
8439 	if (spare)
8440 		quotaadj(freeblks->fb_quota, ump, -spare);
8441 	quotarele(freeblks->fb_quota);
8442 #endif
8443 	ACQUIRE_LOCK(ump);
8444 	if (freeblks->fb_state & ONDEPLIST) {
8445 		inodedep_lookup(freeblks->fb_list.wk_mp, freeblks->fb_inum,
8446 		    0, &inodedep);
8447 		TAILQ_REMOVE(&inodedep->id_freeblklst, freeblks, fb_next);
8448 		freeblks->fb_state &= ~ONDEPLIST;
8449 		if (TAILQ_EMPTY(&inodedep->id_freeblklst))
8450 			free_inodedep(inodedep);
8451 	}
8452 	/*
8453 	 * All of the freeblock deps must be complete prior to this call
8454 	 * so it's now safe to complete earlier outstanding journal entries.
8455 	 */
8456 	handle_jwork(&freeblks->fb_jwork);
8457 	WORKITEM_FREE(freeblks, D_FREEBLKS);
8458 	FREE_LOCK(ump);
8459 	return (0);
8460 }
8461 
8462 /*
8463  * Release blocks associated with the freeblks and stored in the indirect
8464  * block dbn. If level is greater than SINGLE, the block is an indirect block
8465  * and recursive calls to indirtrunc must be used to cleanse other indirect
8466  * blocks.
8467  *
8468  * This handles partial and complete truncation of blocks.  Partial is noted
8469  * with goingaway == 0.  In this case the freework is completed after the
8470  * zero'd indirects are written to disk.  For full truncation the freework
8471  * is completed after the block is freed.
8472  */
8473 static void
8474 indir_trunc(freework, dbn, lbn)
8475 	struct freework *freework;
8476 	ufs2_daddr_t dbn;
8477 	ufs_lbn_t lbn;
8478 {
8479 	struct freework *nfreework;
8480 	struct workhead wkhd;
8481 	struct freeblks *freeblks;
8482 	struct buf *bp;
8483 	struct fs *fs;
8484 	struct indirdep *indirdep;
8485 	struct mount *mp;
8486 	struct ufsmount *ump;
8487 	ufs1_daddr_t *bap1;
8488 	ufs2_daddr_t nb, nnb, *bap2;
8489 	ufs_lbn_t lbnadd, nlbn;
8490 	u_long key;
8491 	int nblocks, ufs1fmt, freedblocks;
8492 	int goingaway, freedeps, needj, level, cnt, i, error;
8493 
8494 	freeblks = freework->fw_freeblks;
8495 	mp = freeblks->fb_list.wk_mp;
8496 	ump = VFSTOUFS(mp);
8497 	fs = ump->um_fs;
8498 	/*
8499 	 * Get buffer of block pointers to be freed.  There are three cases:
8500 	 *
8501 	 * 1) Partial truncate caches the indirdep pointer in the freework
8502 	 *    which provides us a back copy to the save bp which holds the
8503 	 *    pointers we want to clear.  When this completes the zero
8504 	 *    pointers are written to the real copy.
8505 	 * 2) The indirect is being completely truncated, cancel_indirdep()
8506 	 *    eliminated the real copy and placed the indirdep on the saved
8507 	 *    copy.  The indirdep and buf are discarded when this completes.
8508 	 * 3) The indirect was not in memory, we read a copy off of the disk
8509 	 *    using the devvp and drop and invalidate the buffer when we're
8510 	 *    done.
8511 	 */
8512 	goingaway = 1;
8513 	indirdep = NULL;
8514 	if (freework->fw_indir != NULL) {
8515 		goingaway = 0;
8516 		indirdep = freework->fw_indir;
8517 		bp = indirdep->ir_savebp;
8518 		if (bp == NULL || bp->b_blkno != dbn)
8519 			panic("indir_trunc: Bad saved buf %p blkno %jd",
8520 			    bp, (intmax_t)dbn);
8521 	} else if ((bp = incore(&freeblks->fb_devvp->v_bufobj, dbn)) != NULL) {
8522 		/*
8523 		 * The lock prevents the buf dep list from changing and
8524 	 	 * indirects on devvp should only ever have one dependency.
8525 		 */
8526 		indirdep = WK_INDIRDEP(LIST_FIRST(&bp->b_dep));
8527 		if (indirdep == NULL || (indirdep->ir_state & GOINGAWAY) == 0)
8528 			panic("indir_trunc: Bad indirdep %p from buf %p",
8529 			    indirdep, bp);
8530 	} else {
8531 		error = ffs_breadz(ump, freeblks->fb_devvp, dbn, dbn,
8532 		    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL, &bp);
8533 		if (error)
8534 			return;
8535 	}
8536 	ACQUIRE_LOCK(ump);
8537 	/* Protects against a race with complete_trunc_indir(). */
8538 	freework->fw_state &= ~INPROGRESS;
8539 	/*
8540 	 * If we have an indirdep we need to enforce the truncation order
8541 	 * and discard it when it is complete.
8542 	 */
8543 	if (indirdep) {
8544 		if (freework != TAILQ_FIRST(&indirdep->ir_trunc) &&
8545 		    !TAILQ_EMPTY(&indirdep->ir_trunc)) {
8546 			/*
8547 			 * Add the complete truncate to the list on the
8548 			 * indirdep to enforce in-order processing.
8549 			 */
8550 			if (freework->fw_indir == NULL)
8551 				TAILQ_INSERT_TAIL(&indirdep->ir_trunc,
8552 				    freework, fw_next);
8553 			FREE_LOCK(ump);
8554 			return;
8555 		}
8556 		/*
8557 		 * If we're goingaway, free the indirdep.  Otherwise it will
8558 		 * linger until the write completes.
8559 		 */
8560 		if (goingaway) {
8561 			KASSERT(indirdep->ir_savebp == bp,
8562 			    ("indir_trunc: losing ir_savebp %p",
8563 			    indirdep->ir_savebp));
8564 			indirdep->ir_savebp = NULL;
8565 			free_indirdep(indirdep);
8566 		}
8567 	}
8568 	FREE_LOCK(ump);
8569 	/* Initialize pointers depending on block size. */
8570 	if (ump->um_fstype == UFS1) {
8571 		bap1 = (ufs1_daddr_t *)bp->b_data;
8572 		nb = bap1[freework->fw_off];
8573 		ufs1fmt = 1;
8574 		bap2 = NULL;
8575 	} else {
8576 		bap2 = (ufs2_daddr_t *)bp->b_data;
8577 		nb = bap2[freework->fw_off];
8578 		ufs1fmt = 0;
8579 		bap1 = NULL;
8580 	}
8581 	level = lbn_level(lbn);
8582 	needj = MOUNTEDSUJ(UFSTOVFS(ump)) != 0;
8583 	lbnadd = lbn_offset(fs, level);
8584 	nblocks = btodb(fs->fs_bsize);
8585 	nfreework = freework;
8586 	freedeps = 0;
8587 	cnt = 0;
8588 	/*
8589 	 * Reclaim blocks.  Traverses into nested indirect levels and
8590 	 * arranges for the current level to be freed when subordinates
8591 	 * are free when journaling.
8592 	 */
8593 	key = ffs_blkrelease_start(ump, freeblks->fb_devvp, freeblks->fb_inum);
8594 	for (i = freework->fw_off; i < NINDIR(fs); i++, nb = nnb) {
8595 		if (UFS_CHECK_BLKNO(mp, freeblks->fb_inum, nb,
8596 		    fs->fs_bsize) != 0)
8597 			nb = 0;
8598 		if (i != NINDIR(fs) - 1) {
8599 			if (ufs1fmt)
8600 				nnb = bap1[i+1];
8601 			else
8602 				nnb = bap2[i+1];
8603 		} else
8604 			nnb = 0;
8605 		if (nb == 0)
8606 			continue;
8607 		cnt++;
8608 		if (level != 0) {
8609 			nlbn = (lbn + 1) - (i * lbnadd);
8610 			if (needj != 0) {
8611 				nfreework = newfreework(ump, freeblks, freework,
8612 				    nlbn, nb, fs->fs_frag, 0, 0);
8613 				freedeps++;
8614 			}
8615 			indir_trunc(nfreework, fsbtodb(fs, nb), nlbn);
8616 		} else {
8617 			struct freedep *freedep;
8618 
8619 			/*
8620 			 * Attempt to aggregate freedep dependencies for
8621 			 * all blocks being released to the same CG.
8622 			 */
8623 			LIST_INIT(&wkhd);
8624 			if (needj != 0 &&
8625 			    (nnb == 0 || (dtog(fs, nb) != dtog(fs, nnb)))) {
8626 				freedep = newfreedep(freework);
8627 				WORKLIST_INSERT_UNLOCKED(&wkhd,
8628 				    &freedep->fd_list);
8629 				freedeps++;
8630 			}
8631 			CTR3(KTR_SUJ,
8632 			    "indir_trunc: ino %jd blkno %jd size %d",
8633 			    freeblks->fb_inum, nb, fs->fs_bsize);
8634 			ffs_blkfree(ump, fs, freeblks->fb_devvp, nb,
8635 			    fs->fs_bsize, freeblks->fb_inum,
8636 			    freeblks->fb_vtype, &wkhd, key);
8637 		}
8638 	}
8639 	ffs_blkrelease_finish(ump, key);
8640 	if (goingaway) {
8641 		bp->b_flags |= B_INVAL | B_NOCACHE;
8642 		brelse(bp);
8643 	}
8644 	freedblocks = 0;
8645 	if (level == 0)
8646 		freedblocks = (nblocks * cnt);
8647 	if (needj == 0)
8648 		freedblocks += nblocks;
8649 	freeblks_free(ump, freeblks, freedblocks);
8650 	/*
8651 	 * If we are journaling set up the ref counts and offset so this
8652 	 * indirect can be completed when its children are free.
8653 	 */
8654 	if (needj) {
8655 		ACQUIRE_LOCK(ump);
8656 		freework->fw_off = i;
8657 		freework->fw_ref += freedeps;
8658 		freework->fw_ref -= NINDIR(fs) + 1;
8659 		if (level == 0)
8660 			freeblks->fb_cgwait += freedeps;
8661 		if (freework->fw_ref == 0)
8662 			freework_freeblock(freework, SINGLETON_KEY);
8663 		FREE_LOCK(ump);
8664 		return;
8665 	}
8666 	/*
8667 	 * If we're not journaling we can free the indirect now.
8668 	 */
8669 	dbn = dbtofsb(fs, dbn);
8670 	CTR3(KTR_SUJ,
8671 	    "indir_trunc 2: ino %jd blkno %jd size %d",
8672 	    freeblks->fb_inum, dbn, fs->fs_bsize);
8673 	ffs_blkfree(ump, fs, freeblks->fb_devvp, dbn, fs->fs_bsize,
8674 	    freeblks->fb_inum, freeblks->fb_vtype, NULL, SINGLETON_KEY);
8675 	/* Non SUJ softdep does single-threaded truncations. */
8676 	if (freework->fw_blkno == dbn) {
8677 		freework->fw_state |= ALLCOMPLETE;
8678 		ACQUIRE_LOCK(ump);
8679 		handle_written_freework(freework);
8680 		FREE_LOCK(ump);
8681 	}
8682 	return;
8683 }
8684 
8685 /*
8686  * Cancel an allocindir when it is removed via truncation.  When bp is not
8687  * NULL the indirect never appeared on disk and is scheduled to be freed
8688  * independently of the indir so we can more easily track journal work.
8689  */
8690 static void
8691 cancel_allocindir(aip, bp, freeblks, trunc)
8692 	struct allocindir *aip;
8693 	struct buf *bp;
8694 	struct freeblks *freeblks;
8695 	int trunc;
8696 {
8697 	struct indirdep *indirdep;
8698 	struct freefrag *freefrag;
8699 	struct newblk *newblk;
8700 
8701 	newblk = (struct newblk *)aip;
8702 	LIST_REMOVE(aip, ai_next);
8703 	/*
8704 	 * We must eliminate the pointer in bp if it must be freed on its
8705 	 * own due to partial truncate or pending journal work.
8706 	 */
8707 	if (bp && (trunc || newblk->nb_jnewblk)) {
8708 		/*
8709 		 * Clear the pointer and mark the aip to be freed
8710 		 * directly if it never existed on disk.
8711 		 */
8712 		aip->ai_state |= DELAYEDFREE;
8713 		indirdep = aip->ai_indirdep;
8714 		if (indirdep->ir_state & UFS1FMT)
8715 			((ufs1_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8716 		else
8717 			((ufs2_daddr_t *)bp->b_data)[aip->ai_offset] = 0;
8718 	}
8719 	/*
8720 	 * When truncating the previous pointer will be freed via
8721 	 * savedbp.  Eliminate the freefrag which would dup free.
8722 	 */
8723 	if (trunc && (freefrag = newblk->nb_freefrag) != NULL) {
8724 		newblk->nb_freefrag = NULL;
8725 		if (freefrag->ff_jdep)
8726 			cancel_jfreefrag(
8727 			    WK_JFREEFRAG(freefrag->ff_jdep));
8728 		jwork_move(&freeblks->fb_jwork, &freefrag->ff_jwork);
8729 		WORKITEM_FREE(freefrag, D_FREEFRAG);
8730 	}
8731 	/*
8732 	 * If the journal hasn't been written the jnewblk must be passed
8733 	 * to the call to ffs_blkfree that reclaims the space.  We accomplish
8734 	 * this by leaving the journal dependency on the newblk to be freed
8735 	 * when a freework is created in handle_workitem_freeblocks().
8736 	 */
8737 	cancel_newblk(newblk, NULL, &freeblks->fb_jwork);
8738 	WORKLIST_INSERT(&freeblks->fb_freeworkhd, &newblk->nb_list);
8739 }
8740 
8741 /*
8742  * Create the mkdir dependencies for . and .. in a new directory.  Link them
8743  * in to a newdirblk so any subsequent additions are tracked properly.  The
8744  * caller is responsible for adding the mkdir1 dependency to the journal
8745  * and updating id_mkdiradd.  This function returns with the per-filesystem
8746  * lock held.
8747  */
8748 static struct mkdir *
8749 setup_newdir(dap, newinum, dinum, newdirbp, mkdirp)
8750 	struct diradd *dap;
8751 	ino_t newinum;
8752 	ino_t dinum;
8753 	struct buf *newdirbp;
8754 	struct mkdir **mkdirp;
8755 {
8756 	struct newblk *newblk;
8757 	struct pagedep *pagedep;
8758 	struct inodedep *inodedep;
8759 	struct newdirblk *newdirblk;
8760 	struct mkdir *mkdir1, *mkdir2;
8761 	struct worklist *wk;
8762 	struct jaddref *jaddref;
8763 	struct ufsmount *ump;
8764 	struct mount *mp;
8765 
8766 	mp = dap->da_list.wk_mp;
8767 	ump = VFSTOUFS(mp);
8768 	newdirblk = malloc(sizeof(struct newdirblk), M_NEWDIRBLK,
8769 	    M_SOFTDEP_FLAGS);
8770 	workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8771 	LIST_INIT(&newdirblk->db_mkdir);
8772 	mkdir1 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8773 	workitem_alloc(&mkdir1->md_list, D_MKDIR, mp);
8774 	mkdir1->md_state = ATTACHED | MKDIR_BODY;
8775 	mkdir1->md_diradd = dap;
8776 	mkdir1->md_jaddref = NULL;
8777 	mkdir2 = malloc(sizeof(struct mkdir), M_MKDIR, M_SOFTDEP_FLAGS);
8778 	workitem_alloc(&mkdir2->md_list, D_MKDIR, mp);
8779 	mkdir2->md_state = ATTACHED | MKDIR_PARENT;
8780 	mkdir2->md_diradd = dap;
8781 	mkdir2->md_jaddref = NULL;
8782 	if (MOUNTEDSUJ(mp) == 0) {
8783 		mkdir1->md_state |= DEPCOMPLETE;
8784 		mkdir2->md_state |= DEPCOMPLETE;
8785 	}
8786 	/*
8787 	 * Dependency on "." and ".." being written to disk.
8788 	 */
8789 	mkdir1->md_buf = newdirbp;
8790 	ACQUIRE_LOCK(VFSTOUFS(mp));
8791 	LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir1, md_mkdirs);
8792 	/*
8793 	 * We must link the pagedep, allocdirect, and newdirblk for
8794 	 * the initial file page so the pointer to the new directory
8795 	 * is not written until the directory contents are live and
8796 	 * any subsequent additions are not marked live until the
8797 	 * block is reachable via the inode.
8798 	 */
8799 	if (pagedep_lookup(mp, newdirbp, newinum, 0, 0, &pagedep) == 0)
8800 		panic("setup_newdir: lost pagedep");
8801 	LIST_FOREACH(wk, &newdirbp->b_dep, wk_list)
8802 		if (wk->wk_type == D_ALLOCDIRECT)
8803 			break;
8804 	if (wk == NULL)
8805 		panic("setup_newdir: lost allocdirect");
8806 	if (pagedep->pd_state & NEWBLOCK)
8807 		panic("setup_newdir: NEWBLOCK already set");
8808 	newblk = WK_NEWBLK(wk);
8809 	pagedep->pd_state |= NEWBLOCK;
8810 	pagedep->pd_newdirblk = newdirblk;
8811 	newdirblk->db_pagedep = pagedep;
8812 	WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
8813 	WORKLIST_INSERT(&newdirblk->db_mkdir, &mkdir1->md_list);
8814 	/*
8815 	 * Look up the inodedep for the parent directory so that we
8816 	 * can link mkdir2 into the pending dotdot jaddref or
8817 	 * the inode write if there is none.  If the inode is
8818 	 * ALLCOMPLETE and no jaddref is present all dependencies have
8819 	 * been satisfied and mkdir2 can be freed.
8820 	 */
8821 	inodedep_lookup(mp, dinum, 0, &inodedep);
8822 	if (MOUNTEDSUJ(mp)) {
8823 		if (inodedep == NULL)
8824 			panic("setup_newdir: Lost parent.");
8825 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8826 		    inoreflst);
8827 		KASSERT(jaddref != NULL && jaddref->ja_parent == newinum &&
8828 		    (jaddref->ja_state & MKDIR_PARENT),
8829 		    ("setup_newdir: bad dotdot jaddref %p", jaddref));
8830 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8831 		mkdir2->md_jaddref = jaddref;
8832 		jaddref->ja_mkdir = mkdir2;
8833 	} else if (inodedep == NULL ||
8834 	    (inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
8835 		dap->da_state &= ~MKDIR_PARENT;
8836 		WORKITEM_FREE(mkdir2, D_MKDIR);
8837 		mkdir2 = NULL;
8838 	} else {
8839 		LIST_INSERT_HEAD(&ump->softdep_mkdirlisthd, mkdir2, md_mkdirs);
8840 		WORKLIST_INSERT(&inodedep->id_bufwait, &mkdir2->md_list);
8841 	}
8842 	*mkdirp = mkdir2;
8843 
8844 	return (mkdir1);
8845 }
8846 
8847 /*
8848  * Directory entry addition dependencies.
8849  *
8850  * When adding a new directory entry, the inode (with its incremented link
8851  * count) must be written to disk before the directory entry's pointer to it.
8852  * Also, if the inode is newly allocated, the corresponding freemap must be
8853  * updated (on disk) before the directory entry's pointer. These requirements
8854  * are met via undo/redo on the directory entry's pointer, which consists
8855  * simply of the inode number.
8856  *
8857  * As directory entries are added and deleted, the free space within a
8858  * directory block can become fragmented.  The ufs filesystem will compact
8859  * a fragmented directory block to make space for a new entry. When this
8860  * occurs, the offsets of previously added entries change. Any "diradd"
8861  * dependency structures corresponding to these entries must be updated with
8862  * the new offsets.
8863  */
8864 
8865 /*
8866  * This routine is called after the in-memory inode's link
8867  * count has been incremented, but before the directory entry's
8868  * pointer to the inode has been set.
8869  */
8870 int
8871 softdep_setup_directory_add(bp, dp, diroffset, newinum, newdirbp, isnewblk)
8872 	struct buf *bp;		/* buffer containing directory block */
8873 	struct inode *dp;	/* inode for directory */
8874 	off_t diroffset;	/* offset of new entry in directory */
8875 	ino_t newinum;		/* inode referenced by new directory entry */
8876 	struct buf *newdirbp;	/* non-NULL => contents of new mkdir */
8877 	int isnewblk;		/* entry is in a newly allocated block */
8878 {
8879 	int offset;		/* offset of new entry within directory block */
8880 	ufs_lbn_t lbn;		/* block in directory containing new entry */
8881 	struct fs *fs;
8882 	struct diradd *dap;
8883 	struct newblk *newblk;
8884 	struct pagedep *pagedep;
8885 	struct inodedep *inodedep;
8886 	struct newdirblk *newdirblk;
8887 	struct mkdir *mkdir1, *mkdir2;
8888 	struct jaddref *jaddref;
8889 	struct ufsmount *ump;
8890 	struct mount *mp;
8891 	int isindir;
8892 
8893 	mp = ITOVFS(dp);
8894 	ump = VFSTOUFS(mp);
8895 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
8896 	    ("softdep_setup_directory_add called on non-softdep filesystem"));
8897 	/*
8898 	 * Whiteouts have no dependencies.
8899 	 */
8900 	if (newinum == UFS_WINO) {
8901 		if (newdirbp != NULL)
8902 			bdwrite(newdirbp);
8903 		return (0);
8904 	}
8905 	jaddref = NULL;
8906 	mkdir1 = mkdir2 = NULL;
8907 	fs = ump->um_fs;
8908 	lbn = lblkno(fs, diroffset);
8909 	offset = blkoff(fs, diroffset);
8910 	dap = malloc(sizeof(struct diradd), M_DIRADD,
8911 		M_SOFTDEP_FLAGS|M_ZERO);
8912 	workitem_alloc(&dap->da_list, D_DIRADD, mp);
8913 	dap->da_offset = offset;
8914 	dap->da_newinum = newinum;
8915 	dap->da_state = ATTACHED;
8916 	LIST_INIT(&dap->da_jwork);
8917 	isindir = bp->b_lblkno >= UFS_NDADDR;
8918 	newdirblk = NULL;
8919 	if (isnewblk &&
8920 	    (isindir ? blkoff(fs, diroffset) : fragoff(fs, diroffset)) == 0) {
8921 		newdirblk = malloc(sizeof(struct newdirblk),
8922 		    M_NEWDIRBLK, M_SOFTDEP_FLAGS);
8923 		workitem_alloc(&newdirblk->db_list, D_NEWDIRBLK, mp);
8924 		LIST_INIT(&newdirblk->db_mkdir);
8925 	}
8926 	/*
8927 	 * If we're creating a new directory setup the dependencies and set
8928 	 * the dap state to wait for them.  Otherwise it's COMPLETE and
8929 	 * we can move on.
8930 	 */
8931 	if (newdirbp == NULL) {
8932 		dap->da_state |= DEPCOMPLETE;
8933 		ACQUIRE_LOCK(ump);
8934 	} else {
8935 		dap->da_state |= MKDIR_BODY | MKDIR_PARENT;
8936 		mkdir1 = setup_newdir(dap, newinum, dp->i_number, newdirbp,
8937 		    &mkdir2);
8938 	}
8939 	/*
8940 	 * Link into parent directory pagedep to await its being written.
8941 	 */
8942 	pagedep_lookup(mp, bp, dp->i_number, lbn, DEPALLOC, &pagedep);
8943 #ifdef INVARIANTS
8944 	if (diradd_lookup(pagedep, offset) != NULL)
8945 		panic("softdep_setup_directory_add: %p already at off %d\n",
8946 		    diradd_lookup(pagedep, offset), offset);
8947 #endif
8948 	dap->da_pagedep = pagedep;
8949 	LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)], dap,
8950 	    da_pdlist);
8951 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
8952 	/*
8953 	 * If we're journaling, link the diradd into the jaddref so it
8954 	 * may be completed after the journal entry is written.  Otherwise,
8955 	 * link the diradd into its inodedep.  If the inode is not yet
8956 	 * written place it on the bufwait list, otherwise do the post-inode
8957 	 * write processing to put it on the id_pendinghd list.
8958 	 */
8959 	if (MOUNTEDSUJ(mp)) {
8960 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
8961 		    inoreflst);
8962 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
8963 		    ("softdep_setup_directory_add: bad jaddref %p", jaddref));
8964 		jaddref->ja_diroff = diroffset;
8965 		jaddref->ja_diradd = dap;
8966 		add_to_journal(&jaddref->ja_list);
8967 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE)
8968 		diradd_inode_written(dap, inodedep);
8969 	else
8970 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
8971 	/*
8972 	 * Add the journal entries for . and .. links now that the primary
8973 	 * link is written.
8974 	 */
8975 	if (mkdir1 != NULL && MOUNTEDSUJ(mp)) {
8976 		jaddref = (struct jaddref *)TAILQ_PREV(&jaddref->ja_ref,
8977 		    inoreflst, if_deps);
8978 		KASSERT(jaddref != NULL &&
8979 		    jaddref->ja_ino == jaddref->ja_parent &&
8980 		    (jaddref->ja_state & MKDIR_BODY),
8981 		    ("softdep_setup_directory_add: bad dot jaddref %p",
8982 		    jaddref));
8983 		mkdir1->md_jaddref = jaddref;
8984 		jaddref->ja_mkdir = mkdir1;
8985 		/*
8986 		 * It is important that the dotdot journal entry
8987 		 * is added prior to the dot entry since dot writes
8988 		 * both the dot and dotdot links.  These both must
8989 		 * be added after the primary link for the journal
8990 		 * to remain consistent.
8991 		 */
8992 		add_to_journal(&mkdir2->md_jaddref->ja_list);
8993 		add_to_journal(&jaddref->ja_list);
8994 	}
8995 	/*
8996 	 * If we are adding a new directory remember this diradd so that if
8997 	 * we rename it we can keep the dot and dotdot dependencies.  If
8998 	 * we are adding a new name for an inode that has a mkdiradd we
8999 	 * must be in rename and we have to move the dot and dotdot
9000 	 * dependencies to this new name.  The old name is being orphaned
9001 	 * soon.
9002 	 */
9003 	if (mkdir1 != NULL) {
9004 		if (inodedep->id_mkdiradd != NULL)
9005 			panic("softdep_setup_directory_add: Existing mkdir");
9006 		inodedep->id_mkdiradd = dap;
9007 	} else if (inodedep->id_mkdiradd)
9008 		merge_diradd(inodedep, dap);
9009 	if (newdirblk != NULL) {
9010 		/*
9011 		 * There is nothing to do if we are already tracking
9012 		 * this block.
9013 		 */
9014 		if ((pagedep->pd_state & NEWBLOCK) != 0) {
9015 			WORKITEM_FREE(newdirblk, D_NEWDIRBLK);
9016 			FREE_LOCK(ump);
9017 			return (0);
9018 		}
9019 		if (newblk_lookup(mp, dbtofsb(fs, bp->b_blkno), 0, &newblk)
9020 		    == 0)
9021 			panic("softdep_setup_directory_add: lost entry");
9022 		WORKLIST_INSERT(&newblk->nb_newdirblk, &newdirblk->db_list);
9023 		pagedep->pd_state |= NEWBLOCK;
9024 		pagedep->pd_newdirblk = newdirblk;
9025 		newdirblk->db_pagedep = pagedep;
9026 		FREE_LOCK(ump);
9027 		/*
9028 		 * If we extended into an indirect signal direnter to sync.
9029 		 */
9030 		if (isindir)
9031 			return (1);
9032 		return (0);
9033 	}
9034 	FREE_LOCK(ump);
9035 	return (0);
9036 }
9037 
9038 /*
9039  * This procedure is called to change the offset of a directory
9040  * entry when compacting a directory block which must be owned
9041  * exclusively by the caller. Note that the actual entry movement
9042  * must be done in this procedure to ensure that no I/O completions
9043  * occur while the move is in progress.
9044  */
9045 void
9046 softdep_change_directoryentry_offset(bp, dp, base, oldloc, newloc, entrysize)
9047 	struct buf *bp;		/* Buffer holding directory block. */
9048 	struct inode *dp;	/* inode for directory */
9049 	caddr_t base;		/* address of dp->i_offset */
9050 	caddr_t oldloc;		/* address of old directory location */
9051 	caddr_t newloc;		/* address of new directory location */
9052 	int entrysize;		/* size of directory entry */
9053 {
9054 	int offset, oldoffset, newoffset;
9055 	struct pagedep *pagedep;
9056 	struct jmvref *jmvref;
9057 	struct diradd *dap;
9058 	struct direct *de;
9059 	struct mount *mp;
9060 	struct ufsmount *ump;
9061 	ufs_lbn_t lbn;
9062 	int flags;
9063 
9064 	mp = ITOVFS(dp);
9065 	ump = VFSTOUFS(mp);
9066 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9067 	    ("softdep_change_directoryentry_offset called on "
9068 	     "non-softdep filesystem"));
9069 	de = (struct direct *)oldloc;
9070 	jmvref = NULL;
9071 	flags = 0;
9072 	/*
9073 	 * Moves are always journaled as it would be too complex to
9074 	 * determine if any affected adds or removes are present in the
9075 	 * journal.
9076 	 */
9077 	if (MOUNTEDSUJ(mp)) {
9078 		flags = DEPALLOC;
9079 		jmvref = newjmvref(dp, de->d_ino,
9080 		    I_OFFSET(dp) + (oldloc - base),
9081 		    I_OFFSET(dp) + (newloc - base));
9082 	}
9083 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9084 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9085 	oldoffset = offset + (oldloc - base);
9086 	newoffset = offset + (newloc - base);
9087 	ACQUIRE_LOCK(ump);
9088 	if (pagedep_lookup(mp, bp, dp->i_number, lbn, flags, &pagedep) == 0)
9089 		goto done;
9090 	dap = diradd_lookup(pagedep, oldoffset);
9091 	if (dap) {
9092 		dap->da_offset = newoffset;
9093 		newoffset = DIRADDHASH(newoffset);
9094 		oldoffset = DIRADDHASH(oldoffset);
9095 		if ((dap->da_state & ALLCOMPLETE) != ALLCOMPLETE &&
9096 		    newoffset != oldoffset) {
9097 			LIST_REMOVE(dap, da_pdlist);
9098 			LIST_INSERT_HEAD(&pagedep->pd_diraddhd[newoffset],
9099 			    dap, da_pdlist);
9100 		}
9101 	}
9102 done:
9103 	if (jmvref) {
9104 		jmvref->jm_pagedep = pagedep;
9105 		LIST_INSERT_HEAD(&pagedep->pd_jmvrefhd, jmvref, jm_deps);
9106 		add_to_journal(&jmvref->jm_list);
9107 	}
9108 	bcopy(oldloc, newloc, entrysize);
9109 	FREE_LOCK(ump);
9110 }
9111 
9112 /*
9113  * Move the mkdir dependencies and journal work from one diradd to another
9114  * when renaming a directory.  The new name must depend on the mkdir deps
9115  * completing as the old name did.  Directories can only have one valid link
9116  * at a time so one must be canonical.
9117  */
9118 static void
9119 merge_diradd(inodedep, newdap)
9120 	struct inodedep *inodedep;
9121 	struct diradd *newdap;
9122 {
9123 	struct diradd *olddap;
9124 	struct mkdir *mkdir, *nextmd;
9125 	struct ufsmount *ump;
9126 	short state;
9127 
9128 	olddap = inodedep->id_mkdiradd;
9129 	inodedep->id_mkdiradd = newdap;
9130 	if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9131 		newdap->da_state &= ~DEPCOMPLETE;
9132 		ump = VFSTOUFS(inodedep->id_list.wk_mp);
9133 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9134 		     mkdir = nextmd) {
9135 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9136 			if (mkdir->md_diradd != olddap)
9137 				continue;
9138 			mkdir->md_diradd = newdap;
9139 			state = mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY);
9140 			newdap->da_state |= state;
9141 			olddap->da_state &= ~state;
9142 			if ((olddap->da_state &
9143 			    (MKDIR_PARENT | MKDIR_BODY)) == 0)
9144 				break;
9145 		}
9146 		if ((olddap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9147 			panic("merge_diradd: unfound ref");
9148 	}
9149 	/*
9150 	 * Any mkdir related journal items are not safe to be freed until
9151 	 * the new name is stable.
9152 	 */
9153 	jwork_move(&newdap->da_jwork, &olddap->da_jwork);
9154 	olddap->da_state |= DEPCOMPLETE;
9155 	complete_diradd(olddap);
9156 }
9157 
9158 /*
9159  * Move the diradd to the pending list when all diradd dependencies are
9160  * complete.
9161  */
9162 static void
9163 complete_diradd(dap)
9164 	struct diradd *dap;
9165 {
9166 	struct pagedep *pagedep;
9167 
9168 	if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
9169 		if (dap->da_state & DIRCHG)
9170 			pagedep = dap->da_previous->dm_pagedep;
9171 		else
9172 			pagedep = dap->da_pagedep;
9173 		LIST_REMOVE(dap, da_pdlist);
9174 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9175 	}
9176 }
9177 
9178 /*
9179  * Cancel a diradd when a dirrem overlaps with it.  We must cancel the journal
9180  * add entries and conditonally journal the remove.
9181  */
9182 static void
9183 cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref)
9184 	struct diradd *dap;
9185 	struct dirrem *dirrem;
9186 	struct jremref *jremref;
9187 	struct jremref *dotremref;
9188 	struct jremref *dotdotremref;
9189 {
9190 	struct inodedep *inodedep;
9191 	struct jaddref *jaddref;
9192 	struct inoref *inoref;
9193 	struct ufsmount *ump;
9194 	struct mkdir *mkdir;
9195 
9196 	/*
9197 	 * If no remove references were allocated we're on a non-journaled
9198 	 * filesystem and can skip the cancel step.
9199 	 */
9200 	if (jremref == NULL) {
9201 		free_diradd(dap, NULL);
9202 		return;
9203 	}
9204 	/*
9205 	 * Cancel the primary name an free it if it does not require
9206 	 * journaling.
9207 	 */
9208 	if (inodedep_lookup(dap->da_list.wk_mp, dap->da_newinum,
9209 	    0, &inodedep) != 0) {
9210 		/* Abort the addref that reference this diradd.  */
9211 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
9212 			if (inoref->if_list.wk_type != D_JADDREF)
9213 				continue;
9214 			jaddref = (struct jaddref *)inoref;
9215 			if (jaddref->ja_diradd != dap)
9216 				continue;
9217 			if (cancel_jaddref(jaddref, inodedep,
9218 			    &dirrem->dm_jwork) == 0) {
9219 				free_jremref(jremref);
9220 				jremref = NULL;
9221 			}
9222 			break;
9223 		}
9224 	}
9225 	/*
9226 	 * Cancel subordinate names and free them if they do not require
9227 	 * journaling.
9228 	 */
9229 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9230 		ump = VFSTOUFS(dap->da_list.wk_mp);
9231 		LIST_FOREACH(mkdir, &ump->softdep_mkdirlisthd, md_mkdirs) {
9232 			if (mkdir->md_diradd != dap)
9233 				continue;
9234 			if ((jaddref = mkdir->md_jaddref) == NULL)
9235 				continue;
9236 			mkdir->md_jaddref = NULL;
9237 			if (mkdir->md_state & MKDIR_PARENT) {
9238 				if (cancel_jaddref(jaddref, NULL,
9239 				    &dirrem->dm_jwork) == 0) {
9240 					free_jremref(dotdotremref);
9241 					dotdotremref = NULL;
9242 				}
9243 			} else {
9244 				if (cancel_jaddref(jaddref, inodedep,
9245 				    &dirrem->dm_jwork) == 0) {
9246 					free_jremref(dotremref);
9247 					dotremref = NULL;
9248 				}
9249 			}
9250 		}
9251 	}
9252 
9253 	if (jremref)
9254 		journal_jremref(dirrem, jremref, inodedep);
9255 	if (dotremref)
9256 		journal_jremref(dirrem, dotremref, inodedep);
9257 	if (dotdotremref)
9258 		journal_jremref(dirrem, dotdotremref, NULL);
9259 	jwork_move(&dirrem->dm_jwork, &dap->da_jwork);
9260 	free_diradd(dap, &dirrem->dm_jwork);
9261 }
9262 
9263 /*
9264  * Free a diradd dependency structure.
9265  */
9266 static void
9267 free_diradd(dap, wkhd)
9268 	struct diradd *dap;
9269 	struct workhead *wkhd;
9270 {
9271 	struct dirrem *dirrem;
9272 	struct pagedep *pagedep;
9273 	struct inodedep *inodedep;
9274 	struct mkdir *mkdir, *nextmd;
9275 	struct ufsmount *ump;
9276 
9277 	ump = VFSTOUFS(dap->da_list.wk_mp);
9278 	LOCK_OWNED(ump);
9279 	LIST_REMOVE(dap, da_pdlist);
9280 	if (dap->da_state & ONWORKLIST)
9281 		WORKLIST_REMOVE(&dap->da_list);
9282 	if ((dap->da_state & DIRCHG) == 0) {
9283 		pagedep = dap->da_pagedep;
9284 	} else {
9285 		dirrem = dap->da_previous;
9286 		pagedep = dirrem->dm_pagedep;
9287 		dirrem->dm_dirinum = pagedep->pd_ino;
9288 		dirrem->dm_state |= COMPLETE;
9289 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9290 			add_to_worklist(&dirrem->dm_list, 0);
9291 	}
9292 	if (inodedep_lookup(pagedep->pd_list.wk_mp, dap->da_newinum,
9293 	    0, &inodedep) != 0)
9294 		if (inodedep->id_mkdiradd == dap)
9295 			inodedep->id_mkdiradd = NULL;
9296 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0) {
9297 		for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9298 		     mkdir = nextmd) {
9299 			nextmd = LIST_NEXT(mkdir, md_mkdirs);
9300 			if (mkdir->md_diradd != dap)
9301 				continue;
9302 			dap->da_state &=
9303 			    ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
9304 			LIST_REMOVE(mkdir, md_mkdirs);
9305 			if (mkdir->md_state & ONWORKLIST)
9306 				WORKLIST_REMOVE(&mkdir->md_list);
9307 			if (mkdir->md_jaddref != NULL)
9308 				panic("free_diradd: Unexpected jaddref");
9309 			WORKITEM_FREE(mkdir, D_MKDIR);
9310 			if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0)
9311 				break;
9312 		}
9313 		if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) != 0)
9314 			panic("free_diradd: unfound ref");
9315 	}
9316 	if (inodedep)
9317 		free_inodedep(inodedep);
9318 	/*
9319 	 * Free any journal segments waiting for the directory write.
9320 	 */
9321 	handle_jwork(&dap->da_jwork);
9322 	WORKITEM_FREE(dap, D_DIRADD);
9323 }
9324 
9325 /*
9326  * Directory entry removal dependencies.
9327  *
9328  * When removing a directory entry, the entry's inode pointer must be
9329  * zero'ed on disk before the corresponding inode's link count is decremented
9330  * (possibly freeing the inode for re-use). This dependency is handled by
9331  * updating the directory entry but delaying the inode count reduction until
9332  * after the directory block has been written to disk. After this point, the
9333  * inode count can be decremented whenever it is convenient.
9334  */
9335 
9336 /*
9337  * This routine should be called immediately after removing
9338  * a directory entry.  The inode's link count should not be
9339  * decremented by the calling procedure -- the soft updates
9340  * code will do this task when it is safe.
9341  */
9342 void
9343 softdep_setup_remove(bp, dp, ip, isrmdir)
9344 	struct buf *bp;		/* buffer containing directory block */
9345 	struct inode *dp;	/* inode for the directory being modified */
9346 	struct inode *ip;	/* inode for directory entry being removed */
9347 	int isrmdir;		/* indicates if doing RMDIR */
9348 {
9349 	struct dirrem *dirrem, *prevdirrem;
9350 	struct inodedep *inodedep;
9351 	struct ufsmount *ump;
9352 	int direct;
9353 
9354 	ump = ITOUMP(ip);
9355 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9356 	    ("softdep_setup_remove called on non-softdep filesystem"));
9357 	/*
9358 	 * Allocate a new dirrem if appropriate and ACQUIRE_LOCK.  We want
9359 	 * newdirrem() to setup the full directory remove which requires
9360 	 * isrmdir > 1.
9361 	 */
9362 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9363 	/*
9364 	 * Add the dirrem to the inodedep's pending remove list for quick
9365 	 * discovery later.
9366 	 */
9367 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0)
9368 		panic("softdep_setup_remove: Lost inodedep.");
9369 	KASSERT((inodedep->id_state & UNLINKED) == 0, ("inode unlinked"));
9370 	dirrem->dm_state |= ONDEPLIST;
9371 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9372 
9373 	/*
9374 	 * If the COMPLETE flag is clear, then there were no active
9375 	 * entries and we want to roll back to a zeroed entry until
9376 	 * the new inode is committed to disk. If the COMPLETE flag is
9377 	 * set then we have deleted an entry that never made it to
9378 	 * disk. If the entry we deleted resulted from a name change,
9379 	 * then the old name still resides on disk. We cannot delete
9380 	 * its inode (returned to us in prevdirrem) until the zeroed
9381 	 * directory entry gets to disk. The new inode has never been
9382 	 * referenced on the disk, so can be deleted immediately.
9383 	 */
9384 	if ((dirrem->dm_state & COMPLETE) == 0) {
9385 		LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd, dirrem,
9386 		    dm_next);
9387 		FREE_LOCK(ump);
9388 	} else {
9389 		if (prevdirrem != NULL)
9390 			LIST_INSERT_HEAD(&dirrem->dm_pagedep->pd_dirremhd,
9391 			    prevdirrem, dm_next);
9392 		dirrem->dm_dirinum = dirrem->dm_pagedep->pd_ino;
9393 		direct = LIST_EMPTY(&dirrem->dm_jremrefhd);
9394 		FREE_LOCK(ump);
9395 		if (direct)
9396 			handle_workitem_remove(dirrem, 0);
9397 	}
9398 }
9399 
9400 /*
9401  * Check for an entry matching 'offset' on both the pd_dirraddhd list and the
9402  * pd_pendinghd list of a pagedep.
9403  */
9404 static struct diradd *
9405 diradd_lookup(pagedep, offset)
9406 	struct pagedep *pagedep;
9407 	int offset;
9408 {
9409 	struct diradd *dap;
9410 
9411 	LIST_FOREACH(dap, &pagedep->pd_diraddhd[DIRADDHASH(offset)], da_pdlist)
9412 		if (dap->da_offset == offset)
9413 			return (dap);
9414 	LIST_FOREACH(dap, &pagedep->pd_pendinghd, da_pdlist)
9415 		if (dap->da_offset == offset)
9416 			return (dap);
9417 	return (NULL);
9418 }
9419 
9420 /*
9421  * Search for a .. diradd dependency in a directory that is being removed.
9422  * If the directory was renamed to a new parent we have a diradd rather
9423  * than a mkdir for the .. entry.  We need to cancel it now before
9424  * it is found in truncate().
9425  */
9426 static struct jremref *
9427 cancel_diradd_dotdot(ip, dirrem, jremref)
9428 	struct inode *ip;
9429 	struct dirrem *dirrem;
9430 	struct jremref *jremref;
9431 {
9432 	struct pagedep *pagedep;
9433 	struct diradd *dap;
9434 	struct worklist *wk;
9435 
9436 	if (pagedep_lookup(ITOVFS(ip), NULL, ip->i_number, 0, 0, &pagedep) == 0)
9437 		return (jremref);
9438 	dap = diradd_lookup(pagedep, DOTDOT_OFFSET);
9439 	if (dap == NULL)
9440 		return (jremref);
9441 	cancel_diradd(dap, dirrem, jremref, NULL, NULL);
9442 	/*
9443 	 * Mark any journal work as belonging to the parent so it is freed
9444 	 * with the .. reference.
9445 	 */
9446 	LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9447 		wk->wk_state |= MKDIR_PARENT;
9448 	return (NULL);
9449 }
9450 
9451 /*
9452  * Cancel the MKDIR_PARENT mkdir component of a diradd when we're going to
9453  * replace it with a dirrem/diradd pair as a result of re-parenting a
9454  * directory.  This ensures that we don't simultaneously have a mkdir and
9455  * a diradd for the same .. entry.
9456  */
9457 static struct jremref *
9458 cancel_mkdir_dotdot(ip, dirrem, jremref)
9459 	struct inode *ip;
9460 	struct dirrem *dirrem;
9461 	struct jremref *jremref;
9462 {
9463 	struct inodedep *inodedep;
9464 	struct jaddref *jaddref;
9465 	struct ufsmount *ump;
9466 	struct mkdir *mkdir;
9467 	struct diradd *dap;
9468 	struct mount *mp;
9469 
9470 	mp = ITOVFS(ip);
9471 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9472 		return (jremref);
9473 	dap = inodedep->id_mkdiradd;
9474 	if (dap == NULL || (dap->da_state & MKDIR_PARENT) == 0)
9475 		return (jremref);
9476 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
9477 	for (mkdir = LIST_FIRST(&ump->softdep_mkdirlisthd); mkdir;
9478 	    mkdir = LIST_NEXT(mkdir, md_mkdirs))
9479 		if (mkdir->md_diradd == dap && mkdir->md_state & MKDIR_PARENT)
9480 			break;
9481 	if (mkdir == NULL)
9482 		panic("cancel_mkdir_dotdot: Unable to find mkdir\n");
9483 	if ((jaddref = mkdir->md_jaddref) != NULL) {
9484 		mkdir->md_jaddref = NULL;
9485 		jaddref->ja_state &= ~MKDIR_PARENT;
9486 		if (inodedep_lookup(mp, jaddref->ja_ino, 0, &inodedep) == 0)
9487 			panic("cancel_mkdir_dotdot: Lost parent inodedep");
9488 		if (cancel_jaddref(jaddref, inodedep, &dirrem->dm_jwork)) {
9489 			journal_jremref(dirrem, jremref, inodedep);
9490 			jremref = NULL;
9491 		}
9492 	}
9493 	if (mkdir->md_state & ONWORKLIST)
9494 		WORKLIST_REMOVE(&mkdir->md_list);
9495 	mkdir->md_state |= ALLCOMPLETE;
9496 	complete_mkdir(mkdir);
9497 	return (jremref);
9498 }
9499 
9500 static void
9501 journal_jremref(dirrem, jremref, inodedep)
9502 	struct dirrem *dirrem;
9503 	struct jremref *jremref;
9504 	struct inodedep *inodedep;
9505 {
9506 
9507 	if (inodedep == NULL)
9508 		if (inodedep_lookup(jremref->jr_list.wk_mp,
9509 		    jremref->jr_ref.if_ino, 0, &inodedep) == 0)
9510 			panic("journal_jremref: Lost inodedep");
9511 	LIST_INSERT_HEAD(&dirrem->dm_jremrefhd, jremref, jr_deps);
9512 	TAILQ_INSERT_TAIL(&inodedep->id_inoreflst, &jremref->jr_ref, if_deps);
9513 	add_to_journal(&jremref->jr_list);
9514 }
9515 
9516 static void
9517 dirrem_journal(dirrem, jremref, dotremref, dotdotremref)
9518 	struct dirrem *dirrem;
9519 	struct jremref *jremref;
9520 	struct jremref *dotremref;
9521 	struct jremref *dotdotremref;
9522 {
9523 	struct inodedep *inodedep;
9524 
9525 	if (inodedep_lookup(jremref->jr_list.wk_mp, jremref->jr_ref.if_ino, 0,
9526 	    &inodedep) == 0)
9527 		panic("dirrem_journal: Lost inodedep");
9528 	journal_jremref(dirrem, jremref, inodedep);
9529 	if (dotremref)
9530 		journal_jremref(dirrem, dotremref, inodedep);
9531 	if (dotdotremref)
9532 		journal_jremref(dirrem, dotdotremref, NULL);
9533 }
9534 
9535 /*
9536  * Allocate a new dirrem if appropriate and return it along with
9537  * its associated pagedep. Called without a lock, returns with lock.
9538  */
9539 static struct dirrem *
9540 newdirrem(bp, dp, ip, isrmdir, prevdirremp)
9541 	struct buf *bp;		/* buffer containing directory block */
9542 	struct inode *dp;	/* inode for the directory being modified */
9543 	struct inode *ip;	/* inode for directory entry being removed */
9544 	int isrmdir;		/* indicates if doing RMDIR */
9545 	struct dirrem **prevdirremp; /* previously referenced inode, if any */
9546 {
9547 	int offset;
9548 	ufs_lbn_t lbn;
9549 	struct diradd *dap;
9550 	struct dirrem *dirrem;
9551 	struct pagedep *pagedep;
9552 	struct jremref *jremref;
9553 	struct jremref *dotremref;
9554 	struct jremref *dotdotremref;
9555 	struct vnode *dvp;
9556 	struct ufsmount *ump;
9557 
9558 	/*
9559 	 * Whiteouts have no deletion dependencies.
9560 	 */
9561 	if (ip == NULL)
9562 		panic("newdirrem: whiteout");
9563 	dvp = ITOV(dp);
9564 	ump = ITOUMP(dp);
9565 
9566 	/*
9567 	 * If the system is over its limit and our filesystem is
9568 	 * responsible for more than our share of that usage and
9569 	 * we are not a snapshot, request some inodedep cleanup.
9570 	 * Limiting the number of dirrem structures will also limit
9571 	 * the number of freefile and freeblks structures.
9572 	 */
9573 	ACQUIRE_LOCK(ump);
9574 	if (!IS_SNAPSHOT(ip) && softdep_excess_items(ump, D_DIRREM))
9575 		schedule_cleanup(UFSTOVFS(ump));
9576 	else
9577 		FREE_LOCK(ump);
9578 	dirrem = malloc(sizeof(struct dirrem), M_DIRREM, M_SOFTDEP_FLAGS |
9579 	    M_ZERO);
9580 	workitem_alloc(&dirrem->dm_list, D_DIRREM, dvp->v_mount);
9581 	LIST_INIT(&dirrem->dm_jremrefhd);
9582 	LIST_INIT(&dirrem->dm_jwork);
9583 	dirrem->dm_state = isrmdir ? RMDIR : 0;
9584 	dirrem->dm_oldinum = ip->i_number;
9585 	*prevdirremp = NULL;
9586 	/*
9587 	 * Allocate remove reference structures to track journal write
9588 	 * dependencies.  We will always have one for the link and
9589 	 * when doing directories we will always have one more for dot.
9590 	 * When renaming a directory we skip the dotdot link change so
9591 	 * this is not needed.
9592 	 */
9593 	jremref = dotremref = dotdotremref = NULL;
9594 	if (DOINGSUJ(dvp)) {
9595 		if (isrmdir) {
9596 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9597 			    ip->i_effnlink + 2);
9598 			dotremref = newjremref(dirrem, ip, ip, DOT_OFFSET,
9599 			    ip->i_effnlink + 1);
9600 			dotdotremref = newjremref(dirrem, ip, dp, DOTDOT_OFFSET,
9601 			    dp->i_effnlink + 1);
9602 			dotdotremref->jr_state |= MKDIR_PARENT;
9603 		} else
9604 			jremref = newjremref(dirrem, dp, ip, I_OFFSET(dp),
9605 			    ip->i_effnlink + 1);
9606 	}
9607 	ACQUIRE_LOCK(ump);
9608 	lbn = lblkno(ump->um_fs, I_OFFSET(dp));
9609 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9610 	pagedep_lookup(UFSTOVFS(ump), bp, dp->i_number, lbn, DEPALLOC,
9611 	    &pagedep);
9612 	dirrem->dm_pagedep = pagedep;
9613 	dirrem->dm_offset = offset;
9614 	/*
9615 	 * If we're renaming a .. link to a new directory, cancel any
9616 	 * existing MKDIR_PARENT mkdir.  If it has already been canceled
9617 	 * the jremref is preserved for any potential diradd in this
9618 	 * location.  This can not coincide with a rmdir.
9619 	 */
9620 	if (I_OFFSET(dp) == DOTDOT_OFFSET) {
9621 		if (isrmdir)
9622 			panic("newdirrem: .. directory change during remove?");
9623 		jremref = cancel_mkdir_dotdot(dp, dirrem, jremref);
9624 	}
9625 	/*
9626 	 * If we're removing a directory search for the .. dependency now and
9627 	 * cancel it.  Any pending journal work will be added to the dirrem
9628 	 * to be completed when the workitem remove completes.
9629 	 */
9630 	if (isrmdir)
9631 		dotdotremref = cancel_diradd_dotdot(ip, dirrem, dotdotremref);
9632 	/*
9633 	 * Check for a diradd dependency for the same directory entry.
9634 	 * If present, then both dependencies become obsolete and can
9635 	 * be de-allocated.
9636 	 */
9637 	dap = diradd_lookup(pagedep, offset);
9638 	if (dap == NULL) {
9639 		/*
9640 		 * Link the jremref structures into the dirrem so they are
9641 		 * written prior to the pagedep.
9642 		 */
9643 		if (jremref)
9644 			dirrem_journal(dirrem, jremref, dotremref,
9645 			    dotdotremref);
9646 		return (dirrem);
9647 	}
9648 	/*
9649 	 * Must be ATTACHED at this point.
9650 	 */
9651 	if ((dap->da_state & ATTACHED) == 0)
9652 		panic("newdirrem: not ATTACHED");
9653 	if (dap->da_newinum != ip->i_number)
9654 		panic("newdirrem: inum %ju should be %ju",
9655 		    (uintmax_t)ip->i_number, (uintmax_t)dap->da_newinum);
9656 	/*
9657 	 * If we are deleting a changed name that never made it to disk,
9658 	 * then return the dirrem describing the previous inode (which
9659 	 * represents the inode currently referenced from this entry on disk).
9660 	 */
9661 	if ((dap->da_state & DIRCHG) != 0) {
9662 		*prevdirremp = dap->da_previous;
9663 		dap->da_state &= ~DIRCHG;
9664 		dap->da_pagedep = pagedep;
9665 	}
9666 	/*
9667 	 * We are deleting an entry that never made it to disk.
9668 	 * Mark it COMPLETE so we can delete its inode immediately.
9669 	 */
9670 	dirrem->dm_state |= COMPLETE;
9671 	cancel_diradd(dap, dirrem, jremref, dotremref, dotdotremref);
9672 #ifdef INVARIANTS
9673 	if (isrmdir == 0) {
9674 		struct worklist *wk;
9675 
9676 		LIST_FOREACH(wk, &dirrem->dm_jwork, wk_list)
9677 			if (wk->wk_state & (MKDIR_BODY | MKDIR_PARENT))
9678 				panic("bad wk %p (0x%X)\n", wk, wk->wk_state);
9679 	}
9680 #endif
9681 
9682 	return (dirrem);
9683 }
9684 
9685 /*
9686  * Directory entry change dependencies.
9687  *
9688  * Changing an existing directory entry requires that an add operation
9689  * be completed first followed by a deletion. The semantics for the addition
9690  * are identical to the description of adding a new entry above except
9691  * that the rollback is to the old inode number rather than zero. Once
9692  * the addition dependency is completed, the removal is done as described
9693  * in the removal routine above.
9694  */
9695 
9696 /*
9697  * This routine should be called immediately after changing
9698  * a directory entry.  The inode's link count should not be
9699  * decremented by the calling procedure -- the soft updates
9700  * code will perform this task when it is safe.
9701  */
9702 void
9703 softdep_setup_directory_change(bp, dp, ip, newinum, isrmdir)
9704 	struct buf *bp;		/* buffer containing directory block */
9705 	struct inode *dp;	/* inode for the directory being modified */
9706 	struct inode *ip;	/* inode for directory entry being removed */
9707 	ino_t newinum;		/* new inode number for changed entry */
9708 	int isrmdir;		/* indicates if doing RMDIR */
9709 {
9710 	int offset;
9711 	struct diradd *dap = NULL;
9712 	struct dirrem *dirrem, *prevdirrem;
9713 	struct pagedep *pagedep;
9714 	struct inodedep *inodedep;
9715 	struct jaddref *jaddref;
9716 	struct mount *mp;
9717 	struct ufsmount *ump;
9718 
9719 	mp = ITOVFS(dp);
9720 	ump = VFSTOUFS(mp);
9721 	offset = blkoff(ump->um_fs, I_OFFSET(dp));
9722 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
9723 	   ("softdep_setup_directory_change called on non-softdep filesystem"));
9724 
9725 	/*
9726 	 * Whiteouts do not need diradd dependencies.
9727 	 */
9728 	if (newinum != UFS_WINO) {
9729 		dap = malloc(sizeof(struct diradd),
9730 		    M_DIRADD, M_SOFTDEP_FLAGS|M_ZERO);
9731 		workitem_alloc(&dap->da_list, D_DIRADD, mp);
9732 		dap->da_state = DIRCHG | ATTACHED | DEPCOMPLETE;
9733 		dap->da_offset = offset;
9734 		dap->da_newinum = newinum;
9735 		LIST_INIT(&dap->da_jwork);
9736 	}
9737 
9738 	/*
9739 	 * Allocate a new dirrem and ACQUIRE_LOCK.
9740 	 */
9741 	dirrem = newdirrem(bp, dp, ip, isrmdir, &prevdirrem);
9742 	pagedep = dirrem->dm_pagedep;
9743 	/*
9744 	 * The possible values for isrmdir:
9745 	 *	0 - non-directory file rename
9746 	 *	1 - directory rename within same directory
9747 	 *   inum - directory rename to new directory of given inode number
9748 	 * When renaming to a new directory, we are both deleting and
9749 	 * creating a new directory entry, so the link count on the new
9750 	 * directory should not change. Thus we do not need the followup
9751 	 * dirrem which is usually done in handle_workitem_remove. We set
9752 	 * the DIRCHG flag to tell handle_workitem_remove to skip the
9753 	 * followup dirrem.
9754 	 */
9755 	if (isrmdir > 1)
9756 		dirrem->dm_state |= DIRCHG;
9757 
9758 	/*
9759 	 * Whiteouts have no additional dependencies,
9760 	 * so just put the dirrem on the correct list.
9761 	 */
9762 	if (newinum == UFS_WINO) {
9763 		if ((dirrem->dm_state & COMPLETE) == 0) {
9764 			LIST_INSERT_HEAD(&pagedep->pd_dirremhd, dirrem,
9765 			    dm_next);
9766 		} else {
9767 			dirrem->dm_dirinum = pagedep->pd_ino;
9768 			if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9769 				add_to_worklist(&dirrem->dm_list, 0);
9770 		}
9771 		FREE_LOCK(ump);
9772 		return;
9773 	}
9774 	/*
9775 	 * Add the dirrem to the inodedep's pending remove list for quick
9776 	 * discovery later.  A valid nlinkdelta ensures that this lookup
9777 	 * will not fail.
9778 	 */
9779 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
9780 		panic("softdep_setup_directory_change: Lost inodedep.");
9781 	dirrem->dm_state |= ONDEPLIST;
9782 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
9783 
9784 	/*
9785 	 * If the COMPLETE flag is clear, then there were no active
9786 	 * entries and we want to roll back to the previous inode until
9787 	 * the new inode is committed to disk. If the COMPLETE flag is
9788 	 * set, then we have deleted an entry that never made it to disk.
9789 	 * If the entry we deleted resulted from a name change, then the old
9790 	 * inode reference still resides on disk. Any rollback that we do
9791 	 * needs to be to that old inode (returned to us in prevdirrem). If
9792 	 * the entry we deleted resulted from a create, then there is
9793 	 * no entry on the disk, so we want to roll back to zero rather
9794 	 * than the uncommitted inode. In either of the COMPLETE cases we
9795 	 * want to immediately free the unwritten and unreferenced inode.
9796 	 */
9797 	if ((dirrem->dm_state & COMPLETE) == 0) {
9798 		dap->da_previous = dirrem;
9799 	} else {
9800 		if (prevdirrem != NULL) {
9801 			dap->da_previous = prevdirrem;
9802 		} else {
9803 			dap->da_state &= ~DIRCHG;
9804 			dap->da_pagedep = pagedep;
9805 		}
9806 		dirrem->dm_dirinum = pagedep->pd_ino;
9807 		if (LIST_EMPTY(&dirrem->dm_jremrefhd))
9808 			add_to_worklist(&dirrem->dm_list, 0);
9809 	}
9810 	/*
9811 	 * Lookup the jaddref for this journal entry.  We must finish
9812 	 * initializing it and make the diradd write dependent on it.
9813 	 * If we're not journaling, put it on the id_bufwait list if the
9814 	 * inode is not yet written. If it is written, do the post-inode
9815 	 * write processing to put it on the id_pendinghd list.
9816 	 */
9817 	inodedep_lookup(mp, newinum, DEPALLOC, &inodedep);
9818 	if (MOUNTEDSUJ(mp)) {
9819 		jaddref = (struct jaddref *)TAILQ_LAST(&inodedep->id_inoreflst,
9820 		    inoreflst);
9821 		KASSERT(jaddref != NULL && jaddref->ja_parent == dp->i_number,
9822 		    ("softdep_setup_directory_change: bad jaddref %p",
9823 		    jaddref));
9824 		jaddref->ja_diroff = I_OFFSET(dp);
9825 		jaddref->ja_diradd = dap;
9826 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9827 		    dap, da_pdlist);
9828 		add_to_journal(&jaddref->ja_list);
9829 	} else if ((inodedep->id_state & ALLCOMPLETE) == ALLCOMPLETE) {
9830 		dap->da_state |= COMPLETE;
9831 		LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap, da_pdlist);
9832 		WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
9833 	} else {
9834 		LIST_INSERT_HEAD(&pagedep->pd_diraddhd[DIRADDHASH(offset)],
9835 		    dap, da_pdlist);
9836 		WORKLIST_INSERT(&inodedep->id_bufwait, &dap->da_list);
9837 	}
9838 	/*
9839 	 * If we're making a new name for a directory that has not been
9840 	 * committed when need to move the dot and dotdot references to
9841 	 * this new name.
9842 	 */
9843 	if (inodedep->id_mkdiradd && I_OFFSET(dp) != DOTDOT_OFFSET)
9844 		merge_diradd(inodedep, dap);
9845 	FREE_LOCK(ump);
9846 }
9847 
9848 /*
9849  * Called whenever the link count on an inode is changed.
9850  * It creates an inode dependency so that the new reference(s)
9851  * to the inode cannot be committed to disk until the updated
9852  * inode has been written.
9853  */
9854 void
9855 softdep_change_linkcnt(ip)
9856 	struct inode *ip;	/* the inode with the increased link count */
9857 {
9858 	struct inodedep *inodedep;
9859 	struct ufsmount *ump;
9860 
9861 	ump = ITOUMP(ip);
9862 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9863 	    ("softdep_change_linkcnt called on non-softdep filesystem"));
9864 	ACQUIRE_LOCK(ump);
9865 	inodedep_lookup(UFSTOVFS(ump), ip->i_number, DEPALLOC, &inodedep);
9866 	if (ip->i_nlink < ip->i_effnlink)
9867 		panic("softdep_change_linkcnt: bad delta");
9868 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
9869 	FREE_LOCK(ump);
9870 }
9871 
9872 /*
9873  * Attach a sbdep dependency to the superblock buf so that we can keep
9874  * track of the head of the linked list of referenced but unlinked inodes.
9875  */
9876 void
9877 softdep_setup_sbupdate(ump, fs, bp)
9878 	struct ufsmount *ump;
9879 	struct fs *fs;
9880 	struct buf *bp;
9881 {
9882 	struct sbdep *sbdep;
9883 	struct worklist *wk;
9884 
9885 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
9886 	    ("softdep_setup_sbupdate called on non-softdep filesystem"));
9887 	LIST_FOREACH(wk, &bp->b_dep, wk_list)
9888 		if (wk->wk_type == D_SBDEP)
9889 			break;
9890 	if (wk != NULL)
9891 		return;
9892 	sbdep = malloc(sizeof(struct sbdep), M_SBDEP, M_SOFTDEP_FLAGS);
9893 	workitem_alloc(&sbdep->sb_list, D_SBDEP, UFSTOVFS(ump));
9894 	sbdep->sb_fs = fs;
9895 	sbdep->sb_ump = ump;
9896 	ACQUIRE_LOCK(ump);
9897 	WORKLIST_INSERT(&bp->b_dep, &sbdep->sb_list);
9898 	FREE_LOCK(ump);
9899 }
9900 
9901 /*
9902  * Return the first unlinked inodedep which is ready to be the head of the
9903  * list.  The inodedep and all those after it must have valid next pointers.
9904  */
9905 static struct inodedep *
9906 first_unlinked_inodedep(ump)
9907 	struct ufsmount *ump;
9908 {
9909 	struct inodedep *inodedep;
9910 	struct inodedep *idp;
9911 
9912 	LOCK_OWNED(ump);
9913 	for (inodedep = TAILQ_LAST(&ump->softdep_unlinked, inodedeplst);
9914 	    inodedep; inodedep = idp) {
9915 		if ((inodedep->id_state & UNLINKNEXT) == 0)
9916 			return (NULL);
9917 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
9918 		if (idp == NULL || (idp->id_state & UNLINKNEXT) == 0)
9919 			break;
9920 		if ((inodedep->id_state & UNLINKPREV) == 0)
9921 			break;
9922 	}
9923 	return (inodedep);
9924 }
9925 
9926 /*
9927  * Set the sujfree unlinked head pointer prior to writing a superblock.
9928  */
9929 static void
9930 initiate_write_sbdep(sbdep)
9931 	struct sbdep *sbdep;
9932 {
9933 	struct inodedep *inodedep;
9934 	struct fs *bpfs;
9935 	struct fs *fs;
9936 
9937 	bpfs = sbdep->sb_fs;
9938 	fs = sbdep->sb_ump->um_fs;
9939 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9940 	if (inodedep) {
9941 		fs->fs_sujfree = inodedep->id_ino;
9942 		inodedep->id_state |= UNLINKPREV;
9943 	} else
9944 		fs->fs_sujfree = 0;
9945 	bpfs->fs_sujfree = fs->fs_sujfree;
9946 	/*
9947 	 * Because we have made changes to the superblock, we need to
9948 	 * recompute its check-hash.
9949 	 */
9950 	bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
9951 }
9952 
9953 /*
9954  * After a superblock is written determine whether it must be written again
9955  * due to a changing unlinked list head.
9956  */
9957 static int
9958 handle_written_sbdep(sbdep, bp)
9959 	struct sbdep *sbdep;
9960 	struct buf *bp;
9961 {
9962 	struct inodedep *inodedep;
9963 	struct fs *fs;
9964 
9965 	LOCK_OWNED(sbdep->sb_ump);
9966 	fs = sbdep->sb_fs;
9967 	/*
9968 	 * If the superblock doesn't match the in-memory list start over.
9969 	 */
9970 	inodedep = first_unlinked_inodedep(sbdep->sb_ump);
9971 	if ((inodedep && fs->fs_sujfree != inodedep->id_ino) ||
9972 	    (inodedep == NULL && fs->fs_sujfree != 0)) {
9973 		bdirty(bp);
9974 		return (1);
9975 	}
9976 	WORKITEM_FREE(sbdep, D_SBDEP);
9977 	if (fs->fs_sujfree == 0)
9978 		return (0);
9979 	/*
9980 	 * Now that we have a record of this inode in stable store allow it
9981 	 * to be written to free up pending work.  Inodes may see a lot of
9982 	 * write activity after they are unlinked which we must not hold up.
9983 	 */
9984 	for (; inodedep != NULL; inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
9985 		if ((inodedep->id_state & UNLINKLINKS) != UNLINKLINKS)
9986 			panic("handle_written_sbdep: Bad inodedep %p (0x%X)",
9987 			    inodedep, inodedep->id_state);
9988 		if (inodedep->id_state & UNLINKONLIST)
9989 			break;
9990 		inodedep->id_state |= DEPCOMPLETE | UNLINKONLIST;
9991 	}
9992 
9993 	return (0);
9994 }
9995 
9996 /*
9997  * Mark an inodedep as unlinked and insert it into the in-memory unlinked list.
9998  */
9999 static void
10000 unlinked_inodedep(mp, inodedep)
10001 	struct mount *mp;
10002 	struct inodedep *inodedep;
10003 {
10004 	struct ufsmount *ump;
10005 
10006 	ump = VFSTOUFS(mp);
10007 	LOCK_OWNED(ump);
10008 	if (MOUNTEDSUJ(mp) == 0)
10009 		return;
10010 	ump->um_fs->fs_fmod = 1;
10011 	if (inodedep->id_state & UNLINKED)
10012 		panic("unlinked_inodedep: %p already unlinked\n", inodedep);
10013 	inodedep->id_state |= UNLINKED;
10014 	TAILQ_INSERT_HEAD(&ump->softdep_unlinked, inodedep, id_unlinked);
10015 }
10016 
10017 /*
10018  * Remove an inodedep from the unlinked inodedep list.  This may require
10019  * disk writes if the inode has made it that far.
10020  */
10021 static void
10022 clear_unlinked_inodedep(inodedep)
10023 	struct inodedep *inodedep;
10024 {
10025 	struct ufs2_dinode *dip;
10026 	struct ufsmount *ump;
10027 	struct inodedep *idp;
10028 	struct inodedep *idn;
10029 	struct fs *fs, *bpfs;
10030 	struct buf *bp;
10031 	daddr_t dbn;
10032 	ino_t ino;
10033 	ino_t nino;
10034 	ino_t pino;
10035 	int error;
10036 
10037 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10038 	fs = ump->um_fs;
10039 	ino = inodedep->id_ino;
10040 	error = 0;
10041 	for (;;) {
10042 		LOCK_OWNED(ump);
10043 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10044 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10045 		    inodedep));
10046 		/*
10047 		 * If nothing has yet been written simply remove us from
10048 		 * the in memory list and return.  This is the most common
10049 		 * case where handle_workitem_remove() loses the final
10050 		 * reference.
10051 		 */
10052 		if ((inodedep->id_state & UNLINKLINKS) == 0)
10053 			break;
10054 		/*
10055 		 * If we have a NEXT pointer and no PREV pointer we can simply
10056 		 * clear NEXT's PREV and remove ourselves from the list.  Be
10057 		 * careful not to clear PREV if the superblock points at
10058 		 * next as well.
10059 		 */
10060 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10061 		if ((inodedep->id_state & UNLINKLINKS) == UNLINKNEXT) {
10062 			if (idn && fs->fs_sujfree != idn->id_ino)
10063 				idn->id_state &= ~UNLINKPREV;
10064 			break;
10065 		}
10066 		/*
10067 		 * Here we have an inodedep which is actually linked into
10068 		 * the list.  We must remove it by forcing a write to the
10069 		 * link before us, whether it be the superblock or an inode.
10070 		 * Unfortunately the list may change while we're waiting
10071 		 * on the buf lock for either resource so we must loop until
10072 		 * we lock the right one.  If both the superblock and an
10073 		 * inode point to this inode we must clear the inode first
10074 		 * followed by the superblock.
10075 		 */
10076 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10077 		pino = 0;
10078 		if (idp && (idp->id_state & UNLINKNEXT))
10079 			pino = idp->id_ino;
10080 		FREE_LOCK(ump);
10081 		if (pino == 0) {
10082 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10083 			    (int)fs->fs_sbsize, 0, 0, 0);
10084 		} else {
10085 			dbn = fsbtodb(fs, ino_to_fsba(fs, pino));
10086 			error = ffs_breadz(ump, ump->um_devvp, dbn, dbn,
10087 			    (int)fs->fs_bsize, NULL, NULL, 0, NOCRED, 0, NULL,
10088 			    &bp);
10089 		}
10090 		ACQUIRE_LOCK(ump);
10091 		if (error)
10092 			break;
10093 		/* If the list has changed restart the loop. */
10094 		idp = TAILQ_PREV(inodedep, inodedeplst, id_unlinked);
10095 		nino = 0;
10096 		if (idp && (idp->id_state & UNLINKNEXT))
10097 			nino = idp->id_ino;
10098 		if (nino != pino ||
10099 		    (inodedep->id_state & UNLINKPREV) != UNLINKPREV) {
10100 			FREE_LOCK(ump);
10101 			brelse(bp);
10102 			ACQUIRE_LOCK(ump);
10103 			continue;
10104 		}
10105 		nino = 0;
10106 		idn = TAILQ_NEXT(inodedep, id_unlinked);
10107 		if (idn)
10108 			nino = idn->id_ino;
10109 		/*
10110 		 * Remove us from the in memory list.  After this we cannot
10111 		 * access the inodedep.
10112 		 */
10113 		KASSERT((inodedep->id_state & UNLINKED) != 0,
10114 		    ("clear_unlinked_inodedep: inodedep %p not unlinked",
10115 		    inodedep));
10116 		inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10117 		TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10118 		FREE_LOCK(ump);
10119 		/*
10120 		 * The predecessor's next pointer is manually updated here
10121 		 * so that the NEXT flag is never cleared for an element
10122 		 * that is in the list.
10123 		 */
10124 		if (pino == 0) {
10125 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10126 			bpfs = (struct fs *)bp->b_data;
10127 			ffs_oldfscompat_write(bpfs, ump);
10128 			softdep_setup_sbupdate(ump, bpfs, bp);
10129 			/*
10130 			 * Because we may have made changes to the superblock,
10131 			 * we need to recompute its check-hash.
10132 			 */
10133 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10134 		} else if (fs->fs_magic == FS_UFS1_MAGIC) {
10135 			((struct ufs1_dinode *)bp->b_data +
10136 			    ino_to_fsbo(fs, pino))->di_freelink = nino;
10137 		} else {
10138 			dip = (struct ufs2_dinode *)bp->b_data +
10139 			    ino_to_fsbo(fs, pino);
10140 			dip->di_freelink = nino;
10141 			ffs_update_dinode_ckhash(fs, dip);
10142 		}
10143 		/*
10144 		 * If the bwrite fails we have no recourse to recover.  The
10145 		 * filesystem is corrupted already.
10146 		 */
10147 		bwrite(bp);
10148 		ACQUIRE_LOCK(ump);
10149 		/*
10150 		 * If the superblock pointer still needs to be cleared force
10151 		 * a write here.
10152 		 */
10153 		if (fs->fs_sujfree == ino) {
10154 			FREE_LOCK(ump);
10155 			bp = getblk(ump->um_devvp, btodb(fs->fs_sblockloc),
10156 			    (int)fs->fs_sbsize, 0, 0, 0);
10157 			bcopy((caddr_t)fs, bp->b_data, (u_int)fs->fs_sbsize);
10158 			bpfs = (struct fs *)bp->b_data;
10159 			ffs_oldfscompat_write(bpfs, ump);
10160 			softdep_setup_sbupdate(ump, bpfs, bp);
10161 			/*
10162 			 * Because we may have made changes to the superblock,
10163 			 * we need to recompute its check-hash.
10164 			 */
10165 			bpfs->fs_ckhash = ffs_calc_sbhash(bpfs);
10166 			bwrite(bp);
10167 			ACQUIRE_LOCK(ump);
10168 		}
10169 
10170 		if (fs->fs_sujfree != ino)
10171 			return;
10172 		panic("clear_unlinked_inodedep: Failed to clear free head");
10173 	}
10174 	if (inodedep->id_ino == fs->fs_sujfree)
10175 		panic("clear_unlinked_inodedep: Freeing head of free list");
10176 	inodedep->id_state &= ~(UNLINKED | UNLINKLINKS | UNLINKONLIST);
10177 	TAILQ_REMOVE(&ump->softdep_unlinked, inodedep, id_unlinked);
10178 	return;
10179 }
10180 
10181 /*
10182  * This workitem decrements the inode's link count.
10183  * If the link count reaches zero, the file is removed.
10184  */
10185 static int
10186 handle_workitem_remove(dirrem, flags)
10187 	struct dirrem *dirrem;
10188 	int flags;
10189 {
10190 	struct inodedep *inodedep;
10191 	struct workhead dotdotwk;
10192 	struct worklist *wk;
10193 	struct ufsmount *ump;
10194 	struct mount *mp;
10195 	struct vnode *vp;
10196 	struct inode *ip;
10197 	ino_t oldinum;
10198 
10199 	if (dirrem->dm_state & ONWORKLIST)
10200 		panic("handle_workitem_remove: dirrem %p still on worklist",
10201 		    dirrem);
10202 	oldinum = dirrem->dm_oldinum;
10203 	mp = dirrem->dm_list.wk_mp;
10204 	ump = VFSTOUFS(mp);
10205 	flags |= LK_EXCLUSIVE;
10206 	if (ffs_vgetf(mp, oldinum, flags, &vp, FFSV_FORCEINSMQ) != 0)
10207 		return (EBUSY);
10208 	ip = VTOI(vp);
10209 	MPASS(ip->i_mode != 0);
10210 	ACQUIRE_LOCK(ump);
10211 	if ((inodedep_lookup(mp, oldinum, 0, &inodedep)) == 0)
10212 		panic("handle_workitem_remove: lost inodedep");
10213 	if (dirrem->dm_state & ONDEPLIST)
10214 		LIST_REMOVE(dirrem, dm_inonext);
10215 	KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
10216 	    ("handle_workitem_remove:  Journal entries not written."));
10217 
10218 	/*
10219 	 * Move all dependencies waiting on the remove to complete
10220 	 * from the dirrem to the inode inowait list to be completed
10221 	 * after the inode has been updated and written to disk.
10222 	 *
10223 	 * Any marked MKDIR_PARENT are saved to be completed when the
10224 	 * dotdot ref is removed unless DIRCHG is specified.  For
10225 	 * directory change operations there will be no further
10226 	 * directory writes and the jsegdeps need to be moved along
10227 	 * with the rest to be completed when the inode is free or
10228 	 * stable in the inode free list.
10229 	 */
10230 	LIST_INIT(&dotdotwk);
10231 	while ((wk = LIST_FIRST(&dirrem->dm_jwork)) != NULL) {
10232 		WORKLIST_REMOVE(wk);
10233 		if ((dirrem->dm_state & DIRCHG) == 0 &&
10234 		    wk->wk_state & MKDIR_PARENT) {
10235 			wk->wk_state &= ~MKDIR_PARENT;
10236 			WORKLIST_INSERT(&dotdotwk, wk);
10237 			continue;
10238 		}
10239 		WORKLIST_INSERT(&inodedep->id_inowait, wk);
10240 	}
10241 	LIST_SWAP(&dirrem->dm_jwork, &dotdotwk, worklist, wk_list);
10242 	/*
10243 	 * Normal file deletion.
10244 	 */
10245 	if ((dirrem->dm_state & RMDIR) == 0) {
10246 		ip->i_nlink--;
10247 		KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: file ino "
10248 		    "%ju negative i_nlink %d", (intmax_t)ip->i_number,
10249 		    ip->i_nlink));
10250 		DIP_SET(ip, i_nlink, ip->i_nlink);
10251 		UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10252 		if (ip->i_nlink < ip->i_effnlink)
10253 			panic("handle_workitem_remove: bad file delta");
10254 		if (ip->i_nlink == 0)
10255 			unlinked_inodedep(mp, inodedep);
10256 		inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10257 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10258 		    ("handle_workitem_remove: worklist not empty. %s",
10259 		    TYPENAME(LIST_FIRST(&dirrem->dm_jwork)->wk_type)));
10260 		WORKITEM_FREE(dirrem, D_DIRREM);
10261 		FREE_LOCK(ump);
10262 		goto out;
10263 	}
10264 	/*
10265 	 * Directory deletion. Decrement reference count for both the
10266 	 * just deleted parent directory entry and the reference for ".".
10267 	 * Arrange to have the reference count on the parent decremented
10268 	 * to account for the loss of "..".
10269 	 */
10270 	ip->i_nlink -= 2;
10271 	KASSERT(ip->i_nlink >= 0, ("handle_workitem_remove: directory ino "
10272 	    "%ju negative i_nlink %d", (intmax_t)ip->i_number, ip->i_nlink));
10273 	DIP_SET(ip, i_nlink, ip->i_nlink);
10274 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10275 	if (ip->i_nlink < ip->i_effnlink)
10276 		panic("handle_workitem_remove: bad dir delta");
10277 	if (ip->i_nlink == 0)
10278 		unlinked_inodedep(mp, inodedep);
10279 	inodedep->id_nlinkdelta = ip->i_nlink - ip->i_effnlink;
10280 	/*
10281 	 * Rename a directory to a new parent. Since, we are both deleting
10282 	 * and creating a new directory entry, the link count on the new
10283 	 * directory should not change. Thus we skip the followup dirrem.
10284 	 */
10285 	if (dirrem->dm_state & DIRCHG) {
10286 		KASSERT(LIST_EMPTY(&dirrem->dm_jwork),
10287 		    ("handle_workitem_remove: DIRCHG and worklist not empty."));
10288 		WORKITEM_FREE(dirrem, D_DIRREM);
10289 		FREE_LOCK(ump);
10290 		goto out;
10291 	}
10292 	dirrem->dm_state = ONDEPLIST;
10293 	dirrem->dm_oldinum = dirrem->dm_dirinum;
10294 	/*
10295 	 * Place the dirrem on the parent's diremhd list.
10296 	 */
10297 	if (inodedep_lookup(mp, dirrem->dm_oldinum, 0, &inodedep) == 0)
10298 		panic("handle_workitem_remove: lost dir inodedep");
10299 	LIST_INSERT_HEAD(&inodedep->id_dirremhd, dirrem, dm_inonext);
10300 	/*
10301 	 * If the allocated inode has never been written to disk, then
10302 	 * the on-disk inode is zero'ed and we can remove the file
10303 	 * immediately.  When journaling if the inode has been marked
10304 	 * unlinked and not DEPCOMPLETE we know it can never be written.
10305 	 */
10306 	inodedep_lookup(mp, oldinum, 0, &inodedep);
10307 	if (inodedep == NULL ||
10308 	    (inodedep->id_state & (DEPCOMPLETE | UNLINKED)) == UNLINKED ||
10309 	    check_inode_unwritten(inodedep)) {
10310 		FREE_LOCK(ump);
10311 		vput(vp);
10312 		return handle_workitem_remove(dirrem, flags);
10313 	}
10314 	WORKLIST_INSERT(&inodedep->id_inowait, &dirrem->dm_list);
10315 	FREE_LOCK(ump);
10316 	UFS_INODE_SET_FLAG(ip, IN_CHANGE);
10317 out:
10318 	ffs_update(vp, 0);
10319 	vput(vp);
10320 	return (0);
10321 }
10322 
10323 /*
10324  * Inode de-allocation dependencies.
10325  *
10326  * When an inode's link count is reduced to zero, it can be de-allocated. We
10327  * found it convenient to postpone de-allocation until after the inode is
10328  * written to disk with its new link count (zero).  At this point, all of the
10329  * on-disk inode's block pointers are nullified and, with careful dependency
10330  * list ordering, all dependencies related to the inode will be satisfied and
10331  * the corresponding dependency structures de-allocated.  So, if/when the
10332  * inode is reused, there will be no mixing of old dependencies with new
10333  * ones.  This artificial dependency is set up by the block de-allocation
10334  * procedure above (softdep_setup_freeblocks) and completed by the
10335  * following procedure.
10336  */
10337 static void
10338 handle_workitem_freefile(freefile)
10339 	struct freefile *freefile;
10340 {
10341 	struct workhead wkhd;
10342 	struct fs *fs;
10343 	struct ufsmount *ump;
10344 	int error;
10345 #ifdef INVARIANTS
10346 	struct inodedep *idp;
10347 #endif
10348 
10349 	ump = VFSTOUFS(freefile->fx_list.wk_mp);
10350 	fs = ump->um_fs;
10351 #ifdef INVARIANTS
10352 	ACQUIRE_LOCK(ump);
10353 	error = inodedep_lookup(UFSTOVFS(ump), freefile->fx_oldinum, 0, &idp);
10354 	FREE_LOCK(ump);
10355 	if (error)
10356 		panic("handle_workitem_freefile: inodedep %p survived", idp);
10357 #endif
10358 	UFS_LOCK(ump);
10359 	fs->fs_pendinginodes -= 1;
10360 	UFS_UNLOCK(ump);
10361 	LIST_INIT(&wkhd);
10362 	LIST_SWAP(&freefile->fx_jwork, &wkhd, worklist, wk_list);
10363 	if ((error = ffs_freefile(ump, fs, freefile->fx_devvp,
10364 	    freefile->fx_oldinum, freefile->fx_mode, &wkhd)) != 0)
10365 		softdep_error("handle_workitem_freefile", error);
10366 	ACQUIRE_LOCK(ump);
10367 	WORKITEM_FREE(freefile, D_FREEFILE);
10368 	FREE_LOCK(ump);
10369 }
10370 
10371 /*
10372  * Helper function which unlinks marker element from work list and returns
10373  * the next element on the list.
10374  */
10375 static __inline struct worklist *
10376 markernext(struct worklist *marker)
10377 {
10378 	struct worklist *next;
10379 
10380 	next = LIST_NEXT(marker, wk_list);
10381 	LIST_REMOVE(marker, wk_list);
10382 	return next;
10383 }
10384 
10385 /*
10386  * Disk writes.
10387  *
10388  * The dependency structures constructed above are most actively used when file
10389  * system blocks are written to disk.  No constraints are placed on when a
10390  * block can be written, but unsatisfied update dependencies are made safe by
10391  * modifying (or replacing) the source memory for the duration of the disk
10392  * write.  When the disk write completes, the memory block is again brought
10393  * up-to-date.
10394  *
10395  * In-core inode structure reclamation.
10396  *
10397  * Because there are a finite number of "in-core" inode structures, they are
10398  * reused regularly.  By transferring all inode-related dependencies to the
10399  * in-memory inode block and indexing them separately (via "inodedep"s), we
10400  * can allow "in-core" inode structures to be reused at any time and avoid
10401  * any increase in contention.
10402  *
10403  * Called just before entering the device driver to initiate a new disk I/O.
10404  * The buffer must be locked, thus, no I/O completion operations can occur
10405  * while we are manipulating its associated dependencies.
10406  */
10407 static void
10408 softdep_disk_io_initiation(bp)
10409 	struct buf *bp;		/* structure describing disk write to occur */
10410 {
10411 	struct worklist *wk;
10412 	struct worklist marker;
10413 	struct inodedep *inodedep;
10414 	struct freeblks *freeblks;
10415 	struct jblkdep *jblkdep;
10416 	struct newblk *newblk;
10417 	struct ufsmount *ump;
10418 
10419 	/*
10420 	 * We only care about write operations. There should never
10421 	 * be dependencies for reads.
10422 	 */
10423 	if (bp->b_iocmd != BIO_WRITE)
10424 		panic("softdep_disk_io_initiation: not write");
10425 
10426 	if (bp->b_vflags & BV_BKGRDINPROG)
10427 		panic("softdep_disk_io_initiation: Writing buffer with "
10428 		    "background write in progress: %p", bp);
10429 
10430 	ump = softdep_bp_to_mp(bp);
10431 	if (ump == NULL)
10432 		return;
10433 
10434 	marker.wk_type = D_LAST + 1;	/* Not a normal workitem */
10435 	PHOLD(curproc);			/* Don't swap out kernel stack */
10436 	ACQUIRE_LOCK(ump);
10437 	/*
10438 	 * Do any necessary pre-I/O processing.
10439 	 */
10440 	for (wk = LIST_FIRST(&bp->b_dep); wk != NULL;
10441 	     wk = markernext(&marker)) {
10442 		LIST_INSERT_AFTER(wk, &marker, wk_list);
10443 		switch (wk->wk_type) {
10444 		case D_PAGEDEP:
10445 			initiate_write_filepage(WK_PAGEDEP(wk), bp);
10446 			continue;
10447 
10448 		case D_INODEDEP:
10449 			inodedep = WK_INODEDEP(wk);
10450 			if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC)
10451 				initiate_write_inodeblock_ufs1(inodedep, bp);
10452 			else
10453 				initiate_write_inodeblock_ufs2(inodedep, bp);
10454 			continue;
10455 
10456 		case D_INDIRDEP:
10457 			initiate_write_indirdep(WK_INDIRDEP(wk), bp);
10458 			continue;
10459 
10460 		case D_BMSAFEMAP:
10461 			initiate_write_bmsafemap(WK_BMSAFEMAP(wk), bp);
10462 			continue;
10463 
10464 		case D_JSEG:
10465 			WK_JSEG(wk)->js_buf = NULL;
10466 			continue;
10467 
10468 		case D_FREEBLKS:
10469 			freeblks = WK_FREEBLKS(wk);
10470 			jblkdep = LIST_FIRST(&freeblks->fb_jblkdephd);
10471 			/*
10472 			 * We have to wait for the freeblks to be journaled
10473 			 * before we can write an inodeblock with updated
10474 			 * pointers.  Be careful to arrange the marker so
10475 			 * we revisit the freeblks if it's not removed by
10476 			 * the first jwait().
10477 			 */
10478 			if (jblkdep != NULL) {
10479 				LIST_REMOVE(&marker, wk_list);
10480 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10481 				jwait(&jblkdep->jb_list, MNT_WAIT);
10482 			}
10483 			continue;
10484 		case D_ALLOCDIRECT:
10485 		case D_ALLOCINDIR:
10486 			/*
10487 			 * We have to wait for the jnewblk to be journaled
10488 			 * before we can write to a block if the contents
10489 			 * may be confused with an earlier file's indirect
10490 			 * at recovery time.  Handle the marker as described
10491 			 * above.
10492 			 */
10493 			newblk = WK_NEWBLK(wk);
10494 			if (newblk->nb_jnewblk != NULL &&
10495 			    indirblk_lookup(newblk->nb_list.wk_mp,
10496 			    newblk->nb_newblkno)) {
10497 				LIST_REMOVE(&marker, wk_list);
10498 				LIST_INSERT_BEFORE(wk, &marker, wk_list);
10499 				jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
10500 			}
10501 			continue;
10502 
10503 		case D_SBDEP:
10504 			initiate_write_sbdep(WK_SBDEP(wk));
10505 			continue;
10506 
10507 		case D_MKDIR:
10508 		case D_FREEWORK:
10509 		case D_FREEDEP:
10510 		case D_JSEGDEP:
10511 			continue;
10512 
10513 		default:
10514 			panic("handle_disk_io_initiation: Unexpected type %s",
10515 			    TYPENAME(wk->wk_type));
10516 			/* NOTREACHED */
10517 		}
10518 	}
10519 	FREE_LOCK(ump);
10520 	PRELE(curproc);			/* Allow swapout of kernel stack */
10521 }
10522 
10523 /*
10524  * Called from within the procedure above to deal with unsatisfied
10525  * allocation dependencies in a directory. The buffer must be locked,
10526  * thus, no I/O completion operations can occur while we are
10527  * manipulating its associated dependencies.
10528  */
10529 static void
10530 initiate_write_filepage(pagedep, bp)
10531 	struct pagedep *pagedep;
10532 	struct buf *bp;
10533 {
10534 	struct jremref *jremref;
10535 	struct jmvref *jmvref;
10536 	struct dirrem *dirrem;
10537 	struct diradd *dap;
10538 	struct direct *ep;
10539 	int i;
10540 
10541 	if (pagedep->pd_state & IOSTARTED) {
10542 		/*
10543 		 * This can only happen if there is a driver that does not
10544 		 * understand chaining. Here biodone will reissue the call
10545 		 * to strategy for the incomplete buffers.
10546 		 */
10547 		printf("initiate_write_filepage: already started\n");
10548 		return;
10549 	}
10550 	pagedep->pd_state |= IOSTARTED;
10551 	/*
10552 	 * Wait for all journal remove dependencies to hit the disk.
10553 	 * We can not allow any potentially conflicting directory adds
10554 	 * to be visible before removes and rollback is too difficult.
10555 	 * The per-filesystem lock may be dropped and re-acquired, however
10556 	 * we hold the buf locked so the dependency can not go away.
10557 	 */
10558 	LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next)
10559 		while ((jremref = LIST_FIRST(&dirrem->dm_jremrefhd)) != NULL)
10560 			jwait(&jremref->jr_list, MNT_WAIT);
10561 	while ((jmvref = LIST_FIRST(&pagedep->pd_jmvrefhd)) != NULL)
10562 		jwait(&jmvref->jm_list, MNT_WAIT);
10563 	for (i = 0; i < DAHASHSZ; i++) {
10564 		LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
10565 			ep = (struct direct *)
10566 			    ((char *)bp->b_data + dap->da_offset);
10567 			if (ep->d_ino != dap->da_newinum)
10568 				panic("%s: dir inum %ju != new %ju",
10569 				    "initiate_write_filepage",
10570 				    (uintmax_t)ep->d_ino,
10571 				    (uintmax_t)dap->da_newinum);
10572 			if (dap->da_state & DIRCHG)
10573 				ep->d_ino = dap->da_previous->dm_oldinum;
10574 			else
10575 				ep->d_ino = 0;
10576 			dap->da_state &= ~ATTACHED;
10577 			dap->da_state |= UNDONE;
10578 		}
10579 	}
10580 }
10581 
10582 /*
10583  * Version of initiate_write_inodeblock that handles UFS1 dinodes.
10584  * Note that any bug fixes made to this routine must be done in the
10585  * version found below.
10586  *
10587  * Called from within the procedure above to deal with unsatisfied
10588  * allocation dependencies in an inodeblock. The buffer must be
10589  * locked, thus, no I/O completion operations can occur while we
10590  * are manipulating its associated dependencies.
10591  */
10592 static void
10593 initiate_write_inodeblock_ufs1(inodedep, bp)
10594 	struct inodedep *inodedep;
10595 	struct buf *bp;			/* The inode block */
10596 {
10597 	struct allocdirect *adp, *lastadp;
10598 	struct ufs1_dinode *dp;
10599 	struct ufs1_dinode *sip;
10600 	struct inoref *inoref;
10601 	struct ufsmount *ump;
10602 	struct fs *fs;
10603 	ufs_lbn_t i;
10604 #ifdef INVARIANTS
10605 	ufs_lbn_t prevlbn = 0;
10606 #endif
10607 	int deplist;
10608 
10609 	if (inodedep->id_state & IOSTARTED)
10610 		panic("initiate_write_inodeblock_ufs1: already started");
10611 	inodedep->id_state |= IOSTARTED;
10612 	fs = inodedep->id_fs;
10613 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10614 	LOCK_OWNED(ump);
10615 	dp = (struct ufs1_dinode *)bp->b_data +
10616 	    ino_to_fsbo(fs, inodedep->id_ino);
10617 
10618 	/*
10619 	 * If we're on the unlinked list but have not yet written our
10620 	 * next pointer initialize it here.
10621 	 */
10622 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10623 		struct inodedep *inon;
10624 
10625 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10626 		dp->di_freelink = inon ? inon->id_ino : 0;
10627 	}
10628 	/*
10629 	 * If the bitmap is not yet written, then the allocated
10630 	 * inode cannot be written to disk.
10631 	 */
10632 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10633 		if (inodedep->id_savedino1 != NULL)
10634 			panic("initiate_write_inodeblock_ufs1: I/O underway");
10635 		FREE_LOCK(ump);
10636 		sip = malloc(sizeof(struct ufs1_dinode),
10637 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10638 		ACQUIRE_LOCK(ump);
10639 		inodedep->id_savedino1 = sip;
10640 		*inodedep->id_savedino1 = *dp;
10641 		bzero((caddr_t)dp, sizeof(struct ufs1_dinode));
10642 		dp->di_gen = inodedep->id_savedino1->di_gen;
10643 		dp->di_freelink = inodedep->id_savedino1->di_freelink;
10644 		return;
10645 	}
10646 	/*
10647 	 * If no dependencies, then there is nothing to roll back.
10648 	 */
10649 	inodedep->id_savedsize = dp->di_size;
10650 	inodedep->id_savedextsize = 0;
10651 	inodedep->id_savednlink = dp->di_nlink;
10652 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10653 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10654 		return;
10655 	/*
10656 	 * Revert the link count to that of the first unwritten journal entry.
10657 	 */
10658 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10659 	if (inoref)
10660 		dp->di_nlink = inoref->if_nlink;
10661 	/*
10662 	 * Set the dependencies to busy.
10663 	 */
10664 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10665 	     adp = TAILQ_NEXT(adp, ad_next)) {
10666 #ifdef INVARIANTS
10667 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10668 			panic("softdep_write_inodeblock: lbn order");
10669 		prevlbn = adp->ad_offset;
10670 		if (adp->ad_offset < UFS_NDADDR &&
10671 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10672 			panic("initiate_write_inodeblock_ufs1: "
10673 			    "direct pointer #%jd mismatch %d != %jd",
10674 			    (intmax_t)adp->ad_offset,
10675 			    dp->di_db[adp->ad_offset],
10676 			    (intmax_t)adp->ad_newblkno);
10677 		if (adp->ad_offset >= UFS_NDADDR &&
10678 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10679 			panic("initiate_write_inodeblock_ufs1: "
10680 			    "indirect pointer #%jd mismatch %d != %jd",
10681 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10682 			    dp->di_ib[adp->ad_offset - UFS_NDADDR],
10683 			    (intmax_t)adp->ad_newblkno);
10684 		deplist |= 1 << adp->ad_offset;
10685 		if ((adp->ad_state & ATTACHED) == 0)
10686 			panic("initiate_write_inodeblock_ufs1: "
10687 			    "Unknown state 0x%x", adp->ad_state);
10688 #endif /* INVARIANTS */
10689 		adp->ad_state &= ~ATTACHED;
10690 		adp->ad_state |= UNDONE;
10691 	}
10692 	/*
10693 	 * The on-disk inode cannot claim to be any larger than the last
10694 	 * fragment that has been written. Otherwise, the on-disk inode
10695 	 * might have fragments that were not the last block in the file
10696 	 * which would corrupt the filesystem.
10697 	 */
10698 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10699 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10700 		if (adp->ad_offset >= UFS_NDADDR)
10701 			break;
10702 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10703 		/* keep going until hitting a rollback to a frag */
10704 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10705 			continue;
10706 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10707 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10708 #ifdef INVARIANTS
10709 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10710 				panic("initiate_write_inodeblock_ufs1: "
10711 				    "lost dep1");
10712 #endif /* INVARIANTS */
10713 			dp->di_db[i] = 0;
10714 		}
10715 		for (i = 0; i < UFS_NIADDR; i++) {
10716 #ifdef INVARIANTS
10717 			if (dp->di_ib[i] != 0 &&
10718 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10719 				panic("initiate_write_inodeblock_ufs1: "
10720 				    "lost dep2");
10721 #endif /* INVARIANTS */
10722 			dp->di_ib[i] = 0;
10723 		}
10724 		return;
10725 	}
10726 	/*
10727 	 * If we have zero'ed out the last allocated block of the file,
10728 	 * roll back the size to the last currently allocated block.
10729 	 * We know that this last allocated block is a full-sized as
10730 	 * we already checked for fragments in the loop above.
10731 	 */
10732 	if (lastadp != NULL &&
10733 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10734 		for (i = lastadp->ad_offset; i >= 0; i--)
10735 			if (dp->di_db[i] != 0)
10736 				break;
10737 		dp->di_size = (i + 1) * fs->fs_bsize;
10738 	}
10739 	/*
10740 	 * The only dependencies are for indirect blocks.
10741 	 *
10742 	 * The file size for indirect block additions is not guaranteed.
10743 	 * Such a guarantee would be non-trivial to achieve. The conventional
10744 	 * synchronous write implementation also does not make this guarantee.
10745 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10746 	 * can be over-estimated without destroying integrity when the file
10747 	 * moves into the indirect blocks (i.e., is large). If we want to
10748 	 * postpone fsck, we are stuck with this argument.
10749 	 */
10750 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10751 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10752 }
10753 
10754 /*
10755  * Version of initiate_write_inodeblock that handles UFS2 dinodes.
10756  * Note that any bug fixes made to this routine must be done in the
10757  * version found above.
10758  *
10759  * Called from within the procedure above to deal with unsatisfied
10760  * allocation dependencies in an inodeblock. The buffer must be
10761  * locked, thus, no I/O completion operations can occur while we
10762  * are manipulating its associated dependencies.
10763  */
10764 static void
10765 initiate_write_inodeblock_ufs2(inodedep, bp)
10766 	struct inodedep *inodedep;
10767 	struct buf *bp;			/* The inode block */
10768 {
10769 	struct allocdirect *adp, *lastadp;
10770 	struct ufs2_dinode *dp;
10771 	struct ufs2_dinode *sip;
10772 	struct inoref *inoref;
10773 	struct ufsmount *ump;
10774 	struct fs *fs;
10775 	ufs_lbn_t i;
10776 #ifdef INVARIANTS
10777 	ufs_lbn_t prevlbn = 0;
10778 #endif
10779 	int deplist;
10780 
10781 	if (inodedep->id_state & IOSTARTED)
10782 		panic("initiate_write_inodeblock_ufs2: already started");
10783 	inodedep->id_state |= IOSTARTED;
10784 	fs = inodedep->id_fs;
10785 	ump = VFSTOUFS(inodedep->id_list.wk_mp);
10786 	LOCK_OWNED(ump);
10787 	dp = (struct ufs2_dinode *)bp->b_data +
10788 	    ino_to_fsbo(fs, inodedep->id_ino);
10789 
10790 	/*
10791 	 * If we're on the unlinked list but have not yet written our
10792 	 * next pointer initialize it here.
10793 	 */
10794 	if ((inodedep->id_state & (UNLINKED | UNLINKNEXT)) == UNLINKED) {
10795 		struct inodedep *inon;
10796 
10797 		inon = TAILQ_NEXT(inodedep, id_unlinked);
10798 		dp->di_freelink = inon ? inon->id_ino : 0;
10799 		ffs_update_dinode_ckhash(fs, dp);
10800 	}
10801 	/*
10802 	 * If the bitmap is not yet written, then the allocated
10803 	 * inode cannot be written to disk.
10804 	 */
10805 	if ((inodedep->id_state & DEPCOMPLETE) == 0) {
10806 		if (inodedep->id_savedino2 != NULL)
10807 			panic("initiate_write_inodeblock_ufs2: I/O underway");
10808 		FREE_LOCK(ump);
10809 		sip = malloc(sizeof(struct ufs2_dinode),
10810 		    M_SAVEDINO, M_SOFTDEP_FLAGS);
10811 		ACQUIRE_LOCK(ump);
10812 		inodedep->id_savedino2 = sip;
10813 		*inodedep->id_savedino2 = *dp;
10814 		bzero((caddr_t)dp, sizeof(struct ufs2_dinode));
10815 		dp->di_gen = inodedep->id_savedino2->di_gen;
10816 		dp->di_freelink = inodedep->id_savedino2->di_freelink;
10817 		return;
10818 	}
10819 	/*
10820 	 * If no dependencies, then there is nothing to roll back.
10821 	 */
10822 	inodedep->id_savedsize = dp->di_size;
10823 	inodedep->id_savedextsize = dp->di_extsize;
10824 	inodedep->id_savednlink = dp->di_nlink;
10825 	if (TAILQ_EMPTY(&inodedep->id_inoupdt) &&
10826 	    TAILQ_EMPTY(&inodedep->id_extupdt) &&
10827 	    TAILQ_EMPTY(&inodedep->id_inoreflst))
10828 		return;
10829 	/*
10830 	 * Revert the link count to that of the first unwritten journal entry.
10831 	 */
10832 	inoref = TAILQ_FIRST(&inodedep->id_inoreflst);
10833 	if (inoref)
10834 		dp->di_nlink = inoref->if_nlink;
10835 
10836 	/*
10837 	 * Set the ext data dependencies to busy.
10838 	 */
10839 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10840 	     adp = TAILQ_NEXT(adp, ad_next)) {
10841 #ifdef INVARIANTS
10842 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10843 			panic("initiate_write_inodeblock_ufs2: lbn order");
10844 		prevlbn = adp->ad_offset;
10845 		if (dp->di_extb[adp->ad_offset] != adp->ad_newblkno)
10846 			panic("initiate_write_inodeblock_ufs2: "
10847 			    "ext pointer #%jd mismatch %jd != %jd",
10848 			    (intmax_t)adp->ad_offset,
10849 			    (intmax_t)dp->di_extb[adp->ad_offset],
10850 			    (intmax_t)adp->ad_newblkno);
10851 		deplist |= 1 << adp->ad_offset;
10852 		if ((adp->ad_state & ATTACHED) == 0)
10853 			panic("initiate_write_inodeblock_ufs2: Unknown "
10854 			    "state 0x%x", adp->ad_state);
10855 #endif /* INVARIANTS */
10856 		adp->ad_state &= ~ATTACHED;
10857 		adp->ad_state |= UNDONE;
10858 	}
10859 	/*
10860 	 * The on-disk inode cannot claim to be any larger than the last
10861 	 * fragment that has been written. Otherwise, the on-disk inode
10862 	 * might have fragments that were not the last block in the ext
10863 	 * data which would corrupt the filesystem.
10864 	 */
10865 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_extupdt); adp;
10866 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10867 		dp->di_extb[adp->ad_offset] = adp->ad_oldblkno;
10868 		/* keep going until hitting a rollback to a frag */
10869 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10870 			continue;
10871 		dp->di_extsize = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10872 		for (i = adp->ad_offset + 1; i < UFS_NXADDR; i++) {
10873 #ifdef INVARIANTS
10874 			if (dp->di_extb[i] != 0 && (deplist & (1 << i)) == 0)
10875 				panic("initiate_write_inodeblock_ufs2: "
10876 				    "lost dep1");
10877 #endif /* INVARIANTS */
10878 			dp->di_extb[i] = 0;
10879 		}
10880 		lastadp = NULL;
10881 		break;
10882 	}
10883 	/*
10884 	 * If we have zero'ed out the last allocated block of the ext
10885 	 * data, roll back the size to the last currently allocated block.
10886 	 * We know that this last allocated block is a full-sized as
10887 	 * we already checked for fragments in the loop above.
10888 	 */
10889 	if (lastadp != NULL &&
10890 	    dp->di_extsize <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10891 		for (i = lastadp->ad_offset; i >= 0; i--)
10892 			if (dp->di_extb[i] != 0)
10893 				break;
10894 		dp->di_extsize = (i + 1) * fs->fs_bsize;
10895 	}
10896 	/*
10897 	 * Set the file data dependencies to busy.
10898 	 */
10899 	for (deplist = 0, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10900 	     adp = TAILQ_NEXT(adp, ad_next)) {
10901 #ifdef INVARIANTS
10902 		if (deplist != 0 && prevlbn >= adp->ad_offset)
10903 			panic("softdep_write_inodeblock: lbn order");
10904 		if ((adp->ad_state & ATTACHED) == 0)
10905 			panic("inodedep %p and adp %p not attached", inodedep, adp);
10906 		prevlbn = adp->ad_offset;
10907 		if (!ffs_fsfail_cleanup(ump, 0) &&
10908 		    adp->ad_offset < UFS_NDADDR &&
10909 		    dp->di_db[adp->ad_offset] != adp->ad_newblkno)
10910 			panic("initiate_write_inodeblock_ufs2: "
10911 			    "direct pointer #%jd mismatch %jd != %jd",
10912 			    (intmax_t)adp->ad_offset,
10913 			    (intmax_t)dp->di_db[adp->ad_offset],
10914 			    (intmax_t)adp->ad_newblkno);
10915 		if (!ffs_fsfail_cleanup(ump, 0) &&
10916 		    adp->ad_offset >= UFS_NDADDR &&
10917 		    dp->di_ib[adp->ad_offset - UFS_NDADDR] != adp->ad_newblkno)
10918 			panic("initiate_write_inodeblock_ufs2: "
10919 			    "indirect pointer #%jd mismatch %jd != %jd",
10920 			    (intmax_t)adp->ad_offset - UFS_NDADDR,
10921 			    (intmax_t)dp->di_ib[adp->ad_offset - UFS_NDADDR],
10922 			    (intmax_t)adp->ad_newblkno);
10923 		deplist |= 1 << adp->ad_offset;
10924 		if ((adp->ad_state & ATTACHED) == 0)
10925 			panic("initiate_write_inodeblock_ufs2: Unknown "
10926 			     "state 0x%x", adp->ad_state);
10927 #endif /* INVARIANTS */
10928 		adp->ad_state &= ~ATTACHED;
10929 		adp->ad_state |= UNDONE;
10930 	}
10931 	/*
10932 	 * The on-disk inode cannot claim to be any larger than the last
10933 	 * fragment that has been written. Otherwise, the on-disk inode
10934 	 * might have fragments that were not the last block in the file
10935 	 * which would corrupt the filesystem.
10936 	 */
10937 	for (lastadp = NULL, adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp;
10938 	     lastadp = adp, adp = TAILQ_NEXT(adp, ad_next)) {
10939 		if (adp->ad_offset >= UFS_NDADDR)
10940 			break;
10941 		dp->di_db[adp->ad_offset] = adp->ad_oldblkno;
10942 		/* keep going until hitting a rollback to a frag */
10943 		if (adp->ad_oldsize == 0 || adp->ad_oldsize == fs->fs_bsize)
10944 			continue;
10945 		dp->di_size = fs->fs_bsize * adp->ad_offset + adp->ad_oldsize;
10946 		for (i = adp->ad_offset + 1; i < UFS_NDADDR; i++) {
10947 #ifdef INVARIANTS
10948 			if (dp->di_db[i] != 0 && (deplist & (1 << i)) == 0)
10949 				panic("initiate_write_inodeblock_ufs2: "
10950 				    "lost dep2");
10951 #endif /* INVARIANTS */
10952 			dp->di_db[i] = 0;
10953 		}
10954 		for (i = 0; i < UFS_NIADDR; i++) {
10955 #ifdef INVARIANTS
10956 			if (dp->di_ib[i] != 0 &&
10957 			    (deplist & ((1 << UFS_NDADDR) << i)) == 0)
10958 				panic("initiate_write_inodeblock_ufs2: "
10959 				    "lost dep3");
10960 #endif /* INVARIANTS */
10961 			dp->di_ib[i] = 0;
10962 		}
10963 		ffs_update_dinode_ckhash(fs, dp);
10964 		return;
10965 	}
10966 	/*
10967 	 * If we have zero'ed out the last allocated block of the file,
10968 	 * roll back the size to the last currently allocated block.
10969 	 * We know that this last allocated block is a full-sized as
10970 	 * we already checked for fragments in the loop above.
10971 	 */
10972 	if (lastadp != NULL &&
10973 	    dp->di_size <= (lastadp->ad_offset + 1) * fs->fs_bsize) {
10974 		for (i = lastadp->ad_offset; i >= 0; i--)
10975 			if (dp->di_db[i] != 0)
10976 				break;
10977 		dp->di_size = (i + 1) * fs->fs_bsize;
10978 	}
10979 	/*
10980 	 * The only dependencies are for indirect blocks.
10981 	 *
10982 	 * The file size for indirect block additions is not guaranteed.
10983 	 * Such a guarantee would be non-trivial to achieve. The conventional
10984 	 * synchronous write implementation also does not make this guarantee.
10985 	 * Fsck should catch and fix discrepancies. Arguably, the file size
10986 	 * can be over-estimated without destroying integrity when the file
10987 	 * moves into the indirect blocks (i.e., is large). If we want to
10988 	 * postpone fsck, we are stuck with this argument.
10989 	 */
10990 	for (; adp; adp = TAILQ_NEXT(adp, ad_next))
10991 		dp->di_ib[adp->ad_offset - UFS_NDADDR] = 0;
10992 	ffs_update_dinode_ckhash(fs, dp);
10993 }
10994 
10995 /*
10996  * Cancel an indirdep as a result of truncation.  Release all of the
10997  * children allocindirs and place their journal work on the appropriate
10998  * list.
10999  */
11000 static void
11001 cancel_indirdep(indirdep, bp, freeblks)
11002 	struct indirdep *indirdep;
11003 	struct buf *bp;
11004 	struct freeblks *freeblks;
11005 {
11006 	struct allocindir *aip;
11007 
11008 	/*
11009 	 * None of the indirect pointers will ever be visible,
11010 	 * so they can simply be tossed. GOINGAWAY ensures
11011 	 * that allocated pointers will be saved in the buffer
11012 	 * cache until they are freed. Note that they will
11013 	 * only be able to be found by their physical address
11014 	 * since the inode mapping the logical address will
11015 	 * be gone. The save buffer used for the safe copy
11016 	 * was allocated in setup_allocindir_phase2 using
11017 	 * the physical address so it could be used for this
11018 	 * purpose. Hence we swap the safe copy with the real
11019 	 * copy, allowing the safe copy to be freed and holding
11020 	 * on to the real copy for later use in indir_trunc.
11021 	 */
11022 	if (indirdep->ir_state & GOINGAWAY)
11023 		panic("cancel_indirdep: already gone");
11024 	if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
11025 		indirdep->ir_state |= DEPCOMPLETE;
11026 		LIST_REMOVE(indirdep, ir_next);
11027 	}
11028 	indirdep->ir_state |= GOINGAWAY;
11029 	/*
11030 	 * Pass in bp for blocks still have journal writes
11031 	 * pending so we can cancel them on their own.
11032 	 */
11033 	while ((aip = LIST_FIRST(&indirdep->ir_deplisthd)) != NULL)
11034 		cancel_allocindir(aip, bp, freeblks, 0);
11035 	while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL)
11036 		cancel_allocindir(aip, NULL, freeblks, 0);
11037 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL)
11038 		cancel_allocindir(aip, NULL, freeblks, 0);
11039 	while ((aip = LIST_FIRST(&indirdep->ir_completehd)) != NULL)
11040 		cancel_allocindir(aip, NULL, freeblks, 0);
11041 	/*
11042 	 * If there are pending partial truncations we need to keep the
11043 	 * old block copy around until they complete.  This is because
11044 	 * the current b_data is not a perfect superset of the available
11045 	 * blocks.
11046 	 */
11047 	if (TAILQ_EMPTY(&indirdep->ir_trunc))
11048 		bcopy(bp->b_data, indirdep->ir_savebp->b_data, bp->b_bcount);
11049 	else
11050 		bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11051 	WORKLIST_REMOVE(&indirdep->ir_list);
11052 	WORKLIST_INSERT(&indirdep->ir_savebp->b_dep, &indirdep->ir_list);
11053 	indirdep->ir_bp = NULL;
11054 	indirdep->ir_freeblks = freeblks;
11055 }
11056 
11057 /*
11058  * Free an indirdep once it no longer has new pointers to track.
11059  */
11060 static void
11061 free_indirdep(indirdep)
11062 	struct indirdep *indirdep;
11063 {
11064 
11065 	KASSERT(TAILQ_EMPTY(&indirdep->ir_trunc),
11066 	    ("free_indirdep: Indir trunc list not empty."));
11067 	KASSERT(LIST_EMPTY(&indirdep->ir_completehd),
11068 	    ("free_indirdep: Complete head not empty."));
11069 	KASSERT(LIST_EMPTY(&indirdep->ir_writehd),
11070 	    ("free_indirdep: write head not empty."));
11071 	KASSERT(LIST_EMPTY(&indirdep->ir_donehd),
11072 	    ("free_indirdep: done head not empty."));
11073 	KASSERT(LIST_EMPTY(&indirdep->ir_deplisthd),
11074 	    ("free_indirdep: deplist head not empty."));
11075 	KASSERT((indirdep->ir_state & DEPCOMPLETE),
11076 	    ("free_indirdep: %p still on newblk list.", indirdep));
11077 	KASSERT(indirdep->ir_saveddata == NULL,
11078 	    ("free_indirdep: %p still has saved data.", indirdep));
11079 	KASSERT(indirdep->ir_savebp == NULL,
11080 	    ("free_indirdep: %p still has savebp buffer.", indirdep));
11081 	if (indirdep->ir_state & ONWORKLIST)
11082 		WORKLIST_REMOVE(&indirdep->ir_list);
11083 	WORKITEM_FREE(indirdep, D_INDIRDEP);
11084 }
11085 
11086 /*
11087  * Called before a write to an indirdep.  This routine is responsible for
11088  * rolling back pointers to a safe state which includes only those
11089  * allocindirs which have been completed.
11090  */
11091 static void
11092 initiate_write_indirdep(indirdep, bp)
11093 	struct indirdep *indirdep;
11094 	struct buf *bp;
11095 {
11096 	struct ufsmount *ump;
11097 
11098 	indirdep->ir_state |= IOSTARTED;
11099 	if (indirdep->ir_state & GOINGAWAY)
11100 		panic("disk_io_initiation: indirdep gone");
11101 	/*
11102 	 * If there are no remaining dependencies, this will be writing
11103 	 * the real pointers.
11104 	 */
11105 	if (LIST_EMPTY(&indirdep->ir_deplisthd) &&
11106 	    TAILQ_EMPTY(&indirdep->ir_trunc))
11107 		return;
11108 	/*
11109 	 * Replace up-to-date version with safe version.
11110 	 */
11111 	if (indirdep->ir_saveddata == NULL) {
11112 		ump = VFSTOUFS(indirdep->ir_list.wk_mp);
11113 		LOCK_OWNED(ump);
11114 		FREE_LOCK(ump);
11115 		indirdep->ir_saveddata = malloc(bp->b_bcount, M_INDIRDEP,
11116 		    M_SOFTDEP_FLAGS);
11117 		ACQUIRE_LOCK(ump);
11118 	}
11119 	indirdep->ir_state &= ~ATTACHED;
11120 	indirdep->ir_state |= UNDONE;
11121 	bcopy(bp->b_data, indirdep->ir_saveddata, bp->b_bcount);
11122 	bcopy(indirdep->ir_savebp->b_data, bp->b_data,
11123 	    bp->b_bcount);
11124 }
11125 
11126 /*
11127  * Called when an inode has been cleared in a cg bitmap.  This finally
11128  * eliminates any canceled jaddrefs
11129  */
11130 void
11131 softdep_setup_inofree(mp, bp, ino, wkhd)
11132 	struct mount *mp;
11133 	struct buf *bp;
11134 	ino_t ino;
11135 	struct workhead *wkhd;
11136 {
11137 	struct worklist *wk, *wkn;
11138 	struct inodedep *inodedep;
11139 	struct ufsmount *ump;
11140 	uint8_t *inosused;
11141 	struct cg *cgp;
11142 	struct fs *fs;
11143 
11144 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
11145 	    ("softdep_setup_inofree called on non-softdep filesystem"));
11146 	ump = VFSTOUFS(mp);
11147 	ACQUIRE_LOCK(ump);
11148 	if (!ffs_fsfail_cleanup(ump, 0)) {
11149 		fs = ump->um_fs;
11150 		cgp = (struct cg *)bp->b_data;
11151 		inosused = cg_inosused(cgp);
11152 		if (isset(inosused, ino % fs->fs_ipg))
11153 			panic("softdep_setup_inofree: inode %ju not freed.",
11154 			    (uintmax_t)ino);
11155 	}
11156 	if (inodedep_lookup(mp, ino, 0, &inodedep))
11157 		panic("softdep_setup_inofree: ino %ju has existing inodedep %p",
11158 		    (uintmax_t)ino, inodedep);
11159 	if (wkhd) {
11160 		LIST_FOREACH_SAFE(wk, wkhd, wk_list, wkn) {
11161 			if (wk->wk_type != D_JADDREF)
11162 				continue;
11163 			WORKLIST_REMOVE(wk);
11164 			/*
11165 			 * We can free immediately even if the jaddref
11166 			 * isn't attached in a background write as now
11167 			 * the bitmaps are reconciled.
11168 			 */
11169 			wk->wk_state |= COMPLETE | ATTACHED;
11170 			free_jaddref(WK_JADDREF(wk));
11171 		}
11172 		jwork_move(&bp->b_dep, wkhd);
11173 	}
11174 	FREE_LOCK(ump);
11175 }
11176 
11177 /*
11178  * Called via ffs_blkfree() after a set of frags has been cleared from a cg
11179  * map.  Any dependencies waiting for the write to clear are added to the
11180  * buf's list and any jnewblks that are being canceled are discarded
11181  * immediately.
11182  */
11183 void
11184 softdep_setup_blkfree(mp, bp, blkno, frags, wkhd)
11185 	struct mount *mp;
11186 	struct buf *bp;
11187 	ufs2_daddr_t blkno;
11188 	int frags;
11189 	struct workhead *wkhd;
11190 {
11191 	struct bmsafemap *bmsafemap;
11192 	struct jnewblk *jnewblk;
11193 	struct ufsmount *ump;
11194 	struct worklist *wk;
11195 	struct fs *fs;
11196 #ifdef INVARIANTS
11197 	uint8_t *blksfree;
11198 	struct cg *cgp;
11199 	ufs2_daddr_t jstart;
11200 	ufs2_daddr_t jend;
11201 	ufs2_daddr_t end;
11202 	long bno;
11203 	int i;
11204 #endif
11205 
11206 	CTR3(KTR_SUJ,
11207 	    "softdep_setup_blkfree: blkno %jd frags %d wk head %p",
11208 	    blkno, frags, wkhd);
11209 
11210 	ump = VFSTOUFS(mp);
11211 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
11212 	    ("softdep_setup_blkfree called on non-softdep filesystem"));
11213 	ACQUIRE_LOCK(ump);
11214 	/* Lookup the bmsafemap so we track when it is dirty. */
11215 	fs = ump->um_fs;
11216 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11217 	/*
11218 	 * Detach any jnewblks which have been canceled.  They must linger
11219 	 * until the bitmap is cleared again by ffs_blkfree() to prevent
11220 	 * an unjournaled allocation from hitting the disk.
11221 	 */
11222 	if (wkhd) {
11223 		while ((wk = LIST_FIRST(wkhd)) != NULL) {
11224 			CTR2(KTR_SUJ,
11225 			    "softdep_setup_blkfree: blkno %jd wk type %d",
11226 			    blkno, wk->wk_type);
11227 			WORKLIST_REMOVE(wk);
11228 			if (wk->wk_type != D_JNEWBLK) {
11229 				WORKLIST_INSERT(&bmsafemap->sm_freehd, wk);
11230 				continue;
11231 			}
11232 			jnewblk = WK_JNEWBLK(wk);
11233 			KASSERT(jnewblk->jn_state & GOINGAWAY,
11234 			    ("softdep_setup_blkfree: jnewblk not canceled."));
11235 #ifdef INVARIANTS
11236 			/*
11237 			 * Assert that this block is free in the bitmap
11238 			 * before we discard the jnewblk.
11239 			 */
11240 			cgp = (struct cg *)bp->b_data;
11241 			blksfree = cg_blksfree(cgp);
11242 			bno = dtogd(fs, jnewblk->jn_blkno);
11243 			for (i = jnewblk->jn_oldfrags;
11244 			    i < jnewblk->jn_frags; i++) {
11245 				if (isset(blksfree, bno + i))
11246 					continue;
11247 				panic("softdep_setup_blkfree: not free");
11248 			}
11249 #endif
11250 			/*
11251 			 * Even if it's not attached we can free immediately
11252 			 * as the new bitmap is correct.
11253 			 */
11254 			wk->wk_state |= COMPLETE | ATTACHED;
11255 			free_jnewblk(jnewblk);
11256 		}
11257 	}
11258 
11259 #ifdef INVARIANTS
11260 	/*
11261 	 * Assert that we are not freeing a block which has an outstanding
11262 	 * allocation dependency.
11263 	 */
11264 	fs = VFSTOUFS(mp)->um_fs;
11265 	bmsafemap = bmsafemap_lookup(mp, bp, dtog(fs, blkno), NULL);
11266 	end = blkno + frags;
11267 	LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11268 		/*
11269 		 * Don't match against blocks that will be freed when the
11270 		 * background write is done.
11271 		 */
11272 		if ((jnewblk->jn_state & (ATTACHED | COMPLETE | DEPCOMPLETE)) ==
11273 		    (COMPLETE | DEPCOMPLETE))
11274 			continue;
11275 		jstart = jnewblk->jn_blkno + jnewblk->jn_oldfrags;
11276 		jend = jnewblk->jn_blkno + jnewblk->jn_frags;
11277 		if ((blkno >= jstart && blkno < jend) ||
11278 		    (end > jstart && end <= jend)) {
11279 			printf("state 0x%X %jd - %d %d dep %p\n",
11280 			    jnewblk->jn_state, jnewblk->jn_blkno,
11281 			    jnewblk->jn_oldfrags, jnewblk->jn_frags,
11282 			    jnewblk->jn_dep);
11283 			panic("softdep_setup_blkfree: "
11284 			    "%jd-%jd(%d) overlaps with %jd-%jd",
11285 			    blkno, end, frags, jstart, jend);
11286 		}
11287 	}
11288 #endif
11289 	FREE_LOCK(ump);
11290 }
11291 
11292 /*
11293  * Revert a block allocation when the journal record that describes it
11294  * is not yet written.
11295  */
11296 static int
11297 jnewblk_rollback(jnewblk, fs, cgp, blksfree)
11298 	struct jnewblk *jnewblk;
11299 	struct fs *fs;
11300 	struct cg *cgp;
11301 	uint8_t *blksfree;
11302 {
11303 	ufs1_daddr_t fragno;
11304 	long cgbno, bbase;
11305 	int frags, blk;
11306 	int i;
11307 
11308 	frags = 0;
11309 	cgbno = dtogd(fs, jnewblk->jn_blkno);
11310 	/*
11311 	 * We have to test which frags need to be rolled back.  We may
11312 	 * be operating on a stale copy when doing background writes.
11313 	 */
11314 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++)
11315 		if (isclr(blksfree, cgbno + i))
11316 			frags++;
11317 	if (frags == 0)
11318 		return (0);
11319 	/*
11320 	 * This is mostly ffs_blkfree() sans some validation and
11321 	 * superblock updates.
11322 	 */
11323 	if (frags == fs->fs_frag) {
11324 		fragno = fragstoblks(fs, cgbno);
11325 		ffs_setblock(fs, blksfree, fragno);
11326 		ffs_clusteracct(fs, cgp, fragno, 1);
11327 		cgp->cg_cs.cs_nbfree++;
11328 	} else {
11329 		cgbno += jnewblk->jn_oldfrags;
11330 		bbase = cgbno - fragnum(fs, cgbno);
11331 		/* Decrement the old frags.  */
11332 		blk = blkmap(fs, blksfree, bbase);
11333 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
11334 		/* Deallocate the fragment */
11335 		for (i = 0; i < frags; i++)
11336 			setbit(blksfree, cgbno + i);
11337 		cgp->cg_cs.cs_nffree += frags;
11338 		/* Add back in counts associated with the new frags */
11339 		blk = blkmap(fs, blksfree, bbase);
11340 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
11341 		/* If a complete block has been reassembled, account for it. */
11342 		fragno = fragstoblks(fs, bbase);
11343 		if (ffs_isblock(fs, blksfree, fragno)) {
11344 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
11345 			ffs_clusteracct(fs, cgp, fragno, 1);
11346 			cgp->cg_cs.cs_nbfree++;
11347 		}
11348 	}
11349 	stat_jnewblk++;
11350 	jnewblk->jn_state &= ~ATTACHED;
11351 	jnewblk->jn_state |= UNDONE;
11352 
11353 	return (frags);
11354 }
11355 
11356 static void
11357 initiate_write_bmsafemap(bmsafemap, bp)
11358 	struct bmsafemap *bmsafemap;
11359 	struct buf *bp;			/* The cg block. */
11360 {
11361 	struct jaddref *jaddref;
11362 	struct jnewblk *jnewblk;
11363 	uint8_t *inosused;
11364 	uint8_t *blksfree;
11365 	struct cg *cgp;
11366 	struct fs *fs;
11367 	ino_t ino;
11368 
11369 	/*
11370 	 * If this is a background write, we did this at the time that
11371 	 * the copy was made, so do not need to do it again.
11372 	 */
11373 	if (bmsafemap->sm_state & IOSTARTED)
11374 		return;
11375 	bmsafemap->sm_state |= IOSTARTED;
11376 	/*
11377 	 * Clear any inode allocations which are pending journal writes.
11378 	 */
11379 	if (LIST_FIRST(&bmsafemap->sm_jaddrefhd) != NULL) {
11380 		cgp = (struct cg *)bp->b_data;
11381 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11382 		inosused = cg_inosused(cgp);
11383 		LIST_FOREACH(jaddref, &bmsafemap->sm_jaddrefhd, ja_bmdeps) {
11384 			ino = jaddref->ja_ino % fs->fs_ipg;
11385 			if (isset(inosused, ino)) {
11386 				if ((jaddref->ja_mode & IFMT) == IFDIR)
11387 					cgp->cg_cs.cs_ndir--;
11388 				cgp->cg_cs.cs_nifree++;
11389 				clrbit(inosused, ino);
11390 				jaddref->ja_state &= ~ATTACHED;
11391 				jaddref->ja_state |= UNDONE;
11392 				stat_jaddref++;
11393 			} else
11394 				panic("initiate_write_bmsafemap: inode %ju "
11395 				    "marked free", (uintmax_t)jaddref->ja_ino);
11396 		}
11397 	}
11398 	/*
11399 	 * Clear any block allocations which are pending journal writes.
11400 	 */
11401 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
11402 		cgp = (struct cg *)bp->b_data;
11403 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
11404 		blksfree = cg_blksfree(cgp);
11405 		LIST_FOREACH(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps) {
11406 			if (jnewblk_rollback(jnewblk, fs, cgp, blksfree))
11407 				continue;
11408 			panic("initiate_write_bmsafemap: block %jd "
11409 			    "marked free", jnewblk->jn_blkno);
11410 		}
11411 	}
11412 	/*
11413 	 * Move allocation lists to the written lists so they can be
11414 	 * cleared once the block write is complete.
11415 	 */
11416 	LIST_SWAP(&bmsafemap->sm_inodedephd, &bmsafemap->sm_inodedepwr,
11417 	    inodedep, id_deps);
11418 	LIST_SWAP(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
11419 	    newblk, nb_deps);
11420 	LIST_SWAP(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr, worklist,
11421 	    wk_list);
11422 }
11423 
11424 void
11425 softdep_handle_error(struct buf *bp)
11426 {
11427 	struct ufsmount *ump;
11428 
11429 	ump = softdep_bp_to_mp(bp);
11430 	if (ump == NULL)
11431 		return;
11432 
11433 	if (ffs_fsfail_cleanup(ump, bp->b_error)) {
11434 		/*
11435 		 * No future writes will succeed, so the on-disk image is safe.
11436 		 * Pretend that this write succeeded so that the softdep state
11437 		 * will be cleaned up naturally.
11438 		 */
11439 		bp->b_ioflags &= ~BIO_ERROR;
11440 		bp->b_error = 0;
11441 	}
11442 }
11443 
11444 /*
11445  * This routine is called during the completion interrupt
11446  * service routine for a disk write (from the procedure called
11447  * by the device driver to inform the filesystem caches of
11448  * a request completion).  It should be called early in this
11449  * procedure, before the block is made available to other
11450  * processes or other routines are called.
11451  *
11452  */
11453 static void
11454 softdep_disk_write_complete(bp)
11455 	struct buf *bp;		/* describes the completed disk write */
11456 {
11457 	struct worklist *wk;
11458 	struct worklist *owk;
11459 	struct ufsmount *ump;
11460 	struct workhead reattach;
11461 	struct freeblks *freeblks;
11462 	struct buf *sbp;
11463 
11464 	ump = softdep_bp_to_mp(bp);
11465 	KASSERT(LIST_EMPTY(&bp->b_dep) || ump != NULL,
11466 	    ("softdep_disk_write_complete: softdep_bp_to_mp returned NULL "
11467 	     "with outstanding dependencies for buffer %p", bp));
11468 	if (ump == NULL)
11469 		return;
11470 	if ((bp->b_ioflags & BIO_ERROR) != 0)
11471 		softdep_handle_error(bp);
11472 	/*
11473 	 * If an error occurred while doing the write, then the data
11474 	 * has not hit the disk and the dependencies cannot be processed.
11475 	 * But we do have to go through and roll forward any dependencies
11476 	 * that were rolled back before the disk write.
11477 	 */
11478 	sbp = NULL;
11479 	ACQUIRE_LOCK(ump);
11480 	if ((bp->b_ioflags & BIO_ERROR) != 0 && (bp->b_flags & B_INVAL) == 0) {
11481 		LIST_FOREACH(wk, &bp->b_dep, wk_list) {
11482 			switch (wk->wk_type) {
11483 			case D_PAGEDEP:
11484 				handle_written_filepage(WK_PAGEDEP(wk), bp, 0);
11485 				continue;
11486 
11487 			case D_INODEDEP:
11488 				handle_written_inodeblock(WK_INODEDEP(wk),
11489 				    bp, 0);
11490 				continue;
11491 
11492 			case D_BMSAFEMAP:
11493 				handle_written_bmsafemap(WK_BMSAFEMAP(wk),
11494 				    bp, 0);
11495 				continue;
11496 
11497 			case D_INDIRDEP:
11498 				handle_written_indirdep(WK_INDIRDEP(wk),
11499 				    bp, &sbp, 0);
11500 				continue;
11501 			default:
11502 				/* nothing to roll forward */
11503 				continue;
11504 			}
11505 		}
11506 		FREE_LOCK(ump);
11507 		if (sbp)
11508 			brelse(sbp);
11509 		return;
11510 	}
11511 	LIST_INIT(&reattach);
11512 
11513 	/*
11514 	 * Ump SU lock must not be released anywhere in this code segment.
11515 	 */
11516 	owk = NULL;
11517 	while ((wk = LIST_FIRST(&bp->b_dep)) != NULL) {
11518 		WORKLIST_REMOVE(wk);
11519 		atomic_add_long(&dep_write[wk->wk_type], 1);
11520 		if (wk == owk)
11521 			panic("duplicate worklist: %p\n", wk);
11522 		owk = wk;
11523 		switch (wk->wk_type) {
11524 		case D_PAGEDEP:
11525 			if (handle_written_filepage(WK_PAGEDEP(wk), bp,
11526 			    WRITESUCCEEDED))
11527 				WORKLIST_INSERT(&reattach, wk);
11528 			continue;
11529 
11530 		case D_INODEDEP:
11531 			if (handle_written_inodeblock(WK_INODEDEP(wk), bp,
11532 			    WRITESUCCEEDED))
11533 				WORKLIST_INSERT(&reattach, wk);
11534 			continue;
11535 
11536 		case D_BMSAFEMAP:
11537 			if (handle_written_bmsafemap(WK_BMSAFEMAP(wk), bp,
11538 			    WRITESUCCEEDED))
11539 				WORKLIST_INSERT(&reattach, wk);
11540 			continue;
11541 
11542 		case D_MKDIR:
11543 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_BODY);
11544 			continue;
11545 
11546 		case D_ALLOCDIRECT:
11547 			wk->wk_state |= COMPLETE;
11548 			handle_allocdirect_partdone(WK_ALLOCDIRECT(wk), NULL);
11549 			continue;
11550 
11551 		case D_ALLOCINDIR:
11552 			wk->wk_state |= COMPLETE;
11553 			handle_allocindir_partdone(WK_ALLOCINDIR(wk));
11554 			continue;
11555 
11556 		case D_INDIRDEP:
11557 			if (handle_written_indirdep(WK_INDIRDEP(wk), bp, &sbp,
11558 			    WRITESUCCEEDED))
11559 				WORKLIST_INSERT(&reattach, wk);
11560 			continue;
11561 
11562 		case D_FREEBLKS:
11563 			wk->wk_state |= COMPLETE;
11564 			freeblks = WK_FREEBLKS(wk);
11565 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE &&
11566 			    LIST_EMPTY(&freeblks->fb_jblkdephd))
11567 				add_to_worklist(wk, WK_NODELAY);
11568 			continue;
11569 
11570 		case D_FREEWORK:
11571 			handle_written_freework(WK_FREEWORK(wk));
11572 			break;
11573 
11574 		case D_JSEGDEP:
11575 			free_jsegdep(WK_JSEGDEP(wk));
11576 			continue;
11577 
11578 		case D_JSEG:
11579 			handle_written_jseg(WK_JSEG(wk), bp);
11580 			continue;
11581 
11582 		case D_SBDEP:
11583 			if (handle_written_sbdep(WK_SBDEP(wk), bp))
11584 				WORKLIST_INSERT(&reattach, wk);
11585 			continue;
11586 
11587 		case D_FREEDEP:
11588 			free_freedep(WK_FREEDEP(wk));
11589 			continue;
11590 
11591 		default:
11592 			panic("handle_disk_write_complete: Unknown type %s",
11593 			    TYPENAME(wk->wk_type));
11594 			/* NOTREACHED */
11595 		}
11596 	}
11597 	/*
11598 	 * Reattach any requests that must be redone.
11599 	 */
11600 	while ((wk = LIST_FIRST(&reattach)) != NULL) {
11601 		WORKLIST_REMOVE(wk);
11602 		WORKLIST_INSERT(&bp->b_dep, wk);
11603 	}
11604 	FREE_LOCK(ump);
11605 	if (sbp)
11606 		brelse(sbp);
11607 }
11608 
11609 /*
11610  * Called from within softdep_disk_write_complete above.
11611  */
11612 static void
11613 handle_allocdirect_partdone(adp, wkhd)
11614 	struct allocdirect *adp;	/* the completed allocdirect */
11615 	struct workhead *wkhd;		/* Work to do when inode is writtne. */
11616 {
11617 	struct allocdirectlst *listhead;
11618 	struct allocdirect *listadp;
11619 	struct inodedep *inodedep;
11620 	long bsize;
11621 
11622 	LOCK_OWNED(VFSTOUFS(adp->ad_block.nb_list.wk_mp));
11623 	if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11624 		return;
11625 	/*
11626 	 * The on-disk inode cannot claim to be any larger than the last
11627 	 * fragment that has been written. Otherwise, the on-disk inode
11628 	 * might have fragments that were not the last block in the file
11629 	 * which would corrupt the filesystem. Thus, we cannot free any
11630 	 * allocdirects after one whose ad_oldblkno claims a fragment as
11631 	 * these blocks must be rolled back to zero before writing the inode.
11632 	 * We check the currently active set of allocdirects in id_inoupdt
11633 	 * or id_extupdt as appropriate.
11634 	 */
11635 	inodedep = adp->ad_inodedep;
11636 	bsize = inodedep->id_fs->fs_bsize;
11637 	if (adp->ad_state & EXTDATA)
11638 		listhead = &inodedep->id_extupdt;
11639 	else
11640 		listhead = &inodedep->id_inoupdt;
11641 	TAILQ_FOREACH(listadp, listhead, ad_next) {
11642 		/* found our block */
11643 		if (listadp == adp)
11644 			break;
11645 		/* continue if ad_oldlbn is not a fragment */
11646 		if (listadp->ad_oldsize == 0 ||
11647 		    listadp->ad_oldsize == bsize)
11648 			continue;
11649 		/* hit a fragment */
11650 		return;
11651 	}
11652 	/*
11653 	 * If we have reached the end of the current list without
11654 	 * finding the just finished dependency, then it must be
11655 	 * on the future dependency list. Future dependencies cannot
11656 	 * be freed until they are moved to the current list.
11657 	 */
11658 	if (listadp == NULL) {
11659 #ifdef INVARIANTS
11660 		if (adp->ad_state & EXTDATA)
11661 			listhead = &inodedep->id_newextupdt;
11662 		else
11663 			listhead = &inodedep->id_newinoupdt;
11664 		TAILQ_FOREACH(listadp, listhead, ad_next)
11665 			/* found our block */
11666 			if (listadp == adp)
11667 				break;
11668 		if (listadp == NULL)
11669 			panic("handle_allocdirect_partdone: lost dep");
11670 #endif /* INVARIANTS */
11671 		return;
11672 	}
11673 	/*
11674 	 * If we have found the just finished dependency, then queue
11675 	 * it along with anything that follows it that is complete.
11676 	 * Since the pointer has not yet been written in the inode
11677 	 * as the dependency prevents it, place the allocdirect on the
11678 	 * bufwait list where it will be freed once the pointer is
11679 	 * valid.
11680 	 */
11681 	if (wkhd == NULL)
11682 		wkhd = &inodedep->id_bufwait;
11683 	for (; adp; adp = listadp) {
11684 		listadp = TAILQ_NEXT(adp, ad_next);
11685 		if ((adp->ad_state & ALLCOMPLETE) != ALLCOMPLETE)
11686 			return;
11687 		TAILQ_REMOVE(listhead, adp, ad_next);
11688 		WORKLIST_INSERT(wkhd, &adp->ad_block.nb_list);
11689 	}
11690 }
11691 
11692 /*
11693  * Called from within softdep_disk_write_complete above.  This routine
11694  * completes successfully written allocindirs.
11695  */
11696 static void
11697 handle_allocindir_partdone(aip)
11698 	struct allocindir *aip;		/* the completed allocindir */
11699 {
11700 	struct indirdep *indirdep;
11701 
11702 	if ((aip->ai_state & ALLCOMPLETE) != ALLCOMPLETE)
11703 		return;
11704 	indirdep = aip->ai_indirdep;
11705 	LIST_REMOVE(aip, ai_next);
11706 	/*
11707 	 * Don't set a pointer while the buffer is undergoing IO or while
11708 	 * we have active truncations.
11709 	 */
11710 	if (indirdep->ir_state & UNDONE || !TAILQ_EMPTY(&indirdep->ir_trunc)) {
11711 		LIST_INSERT_HEAD(&indirdep->ir_donehd, aip, ai_next);
11712 		return;
11713 	}
11714 	if (indirdep->ir_state & UFS1FMT)
11715 		((ufs1_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11716 		    aip->ai_newblkno;
11717 	else
11718 		((ufs2_daddr_t *)indirdep->ir_savebp->b_data)[aip->ai_offset] =
11719 		    aip->ai_newblkno;
11720 	/*
11721 	 * Await the pointer write before freeing the allocindir.
11722 	 */
11723 	LIST_INSERT_HEAD(&indirdep->ir_writehd, aip, ai_next);
11724 }
11725 
11726 /*
11727  * Release segments held on a jwork list.
11728  */
11729 static void
11730 handle_jwork(wkhd)
11731 	struct workhead *wkhd;
11732 {
11733 	struct worklist *wk;
11734 
11735 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
11736 		WORKLIST_REMOVE(wk);
11737 		switch (wk->wk_type) {
11738 		case D_JSEGDEP:
11739 			free_jsegdep(WK_JSEGDEP(wk));
11740 			continue;
11741 		case D_FREEDEP:
11742 			free_freedep(WK_FREEDEP(wk));
11743 			continue;
11744 		case D_FREEFRAG:
11745 			rele_jseg(WK_JSEG(WK_FREEFRAG(wk)->ff_jdep));
11746 			WORKITEM_FREE(wk, D_FREEFRAG);
11747 			continue;
11748 		case D_FREEWORK:
11749 			handle_written_freework(WK_FREEWORK(wk));
11750 			continue;
11751 		default:
11752 			panic("handle_jwork: Unknown type %s\n",
11753 			    TYPENAME(wk->wk_type));
11754 		}
11755 	}
11756 }
11757 
11758 /*
11759  * Handle the bufwait list on an inode when it is safe to release items
11760  * held there.  This normally happens after an inode block is written but
11761  * may be delayed and handled later if there are pending journal items that
11762  * are not yet safe to be released.
11763  */
11764 static struct freefile *
11765 handle_bufwait(inodedep, refhd)
11766 	struct inodedep *inodedep;
11767 	struct workhead *refhd;
11768 {
11769 	struct jaddref *jaddref;
11770 	struct freefile *freefile;
11771 	struct worklist *wk;
11772 
11773 	freefile = NULL;
11774 	while ((wk = LIST_FIRST(&inodedep->id_bufwait)) != NULL) {
11775 		WORKLIST_REMOVE(wk);
11776 		switch (wk->wk_type) {
11777 		case D_FREEFILE:
11778 			/*
11779 			 * We defer adding freefile to the worklist
11780 			 * until all other additions have been made to
11781 			 * ensure that it will be done after all the
11782 			 * old blocks have been freed.
11783 			 */
11784 			if (freefile != NULL)
11785 				panic("handle_bufwait: freefile");
11786 			freefile = WK_FREEFILE(wk);
11787 			continue;
11788 
11789 		case D_MKDIR:
11790 			handle_written_mkdir(WK_MKDIR(wk), MKDIR_PARENT);
11791 			continue;
11792 
11793 		case D_DIRADD:
11794 			diradd_inode_written(WK_DIRADD(wk), inodedep);
11795 			continue;
11796 
11797 		case D_FREEFRAG:
11798 			wk->wk_state |= COMPLETE;
11799 			if ((wk->wk_state & ALLCOMPLETE) == ALLCOMPLETE)
11800 				add_to_worklist(wk, 0);
11801 			continue;
11802 
11803 		case D_DIRREM:
11804 			wk->wk_state |= COMPLETE;
11805 			add_to_worklist(wk, 0);
11806 			continue;
11807 
11808 		case D_ALLOCDIRECT:
11809 		case D_ALLOCINDIR:
11810 			free_newblk(WK_NEWBLK(wk));
11811 			continue;
11812 
11813 		case D_JNEWBLK:
11814 			wk->wk_state |= COMPLETE;
11815 			free_jnewblk(WK_JNEWBLK(wk));
11816 			continue;
11817 
11818 		/*
11819 		 * Save freed journal segments and add references on
11820 		 * the supplied list which will delay their release
11821 		 * until the cg bitmap is cleared on disk.
11822 		 */
11823 		case D_JSEGDEP:
11824 			if (refhd == NULL)
11825 				free_jsegdep(WK_JSEGDEP(wk));
11826 			else
11827 				WORKLIST_INSERT(refhd, wk);
11828 			continue;
11829 
11830 		case D_JADDREF:
11831 			jaddref = WK_JADDREF(wk);
11832 			TAILQ_REMOVE(&inodedep->id_inoreflst, &jaddref->ja_ref,
11833 			    if_deps);
11834 			/*
11835 			 * Transfer any jaddrefs to the list to be freed with
11836 			 * the bitmap if we're handling a removed file.
11837 			 */
11838 			if (refhd == NULL) {
11839 				wk->wk_state |= COMPLETE;
11840 				free_jaddref(jaddref);
11841 			} else
11842 				WORKLIST_INSERT(refhd, wk);
11843 			continue;
11844 
11845 		default:
11846 			panic("handle_bufwait: Unknown type %p(%s)",
11847 			    wk, TYPENAME(wk->wk_type));
11848 			/* NOTREACHED */
11849 		}
11850 	}
11851 	return (freefile);
11852 }
11853 /*
11854  * Called from within softdep_disk_write_complete above to restore
11855  * in-memory inode block contents to their most up-to-date state. Note
11856  * that this routine is always called from interrupt level with further
11857  * interrupts from this device blocked.
11858  *
11859  * If the write did not succeed, we will do all the roll-forward
11860  * operations, but we will not take the actions that will allow its
11861  * dependencies to be processed.
11862  */
11863 static int
11864 handle_written_inodeblock(inodedep, bp, flags)
11865 	struct inodedep *inodedep;
11866 	struct buf *bp;		/* buffer containing the inode block */
11867 	int flags;
11868 {
11869 	struct freefile *freefile;
11870 	struct allocdirect *adp, *nextadp;
11871 	struct ufs1_dinode *dp1 = NULL;
11872 	struct ufs2_dinode *dp2 = NULL;
11873 	struct workhead wkhd;
11874 	int hadchanges, fstype;
11875 	ino_t freelink;
11876 
11877 	LIST_INIT(&wkhd);
11878 	hadchanges = 0;
11879 	freefile = NULL;
11880 	if ((inodedep->id_state & IOSTARTED) == 0)
11881 		panic("handle_written_inodeblock: not started");
11882 	inodedep->id_state &= ~IOSTARTED;
11883 	if (inodedep->id_fs->fs_magic == FS_UFS1_MAGIC) {
11884 		fstype = UFS1;
11885 		dp1 = (struct ufs1_dinode *)bp->b_data +
11886 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11887 		freelink = dp1->di_freelink;
11888 	} else {
11889 		fstype = UFS2;
11890 		dp2 = (struct ufs2_dinode *)bp->b_data +
11891 		    ino_to_fsbo(inodedep->id_fs, inodedep->id_ino);
11892 		freelink = dp2->di_freelink;
11893 	}
11894 	/*
11895 	 * Leave this inodeblock dirty until it's in the list.
11896 	 */
11897 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) == UNLINKED &&
11898 	    (flags & WRITESUCCEEDED)) {
11899 		struct inodedep *inon;
11900 
11901 		inon = TAILQ_NEXT(inodedep, id_unlinked);
11902 		if ((inon == NULL && freelink == 0) ||
11903 		    (inon && inon->id_ino == freelink)) {
11904 			if (inon)
11905 				inon->id_state |= UNLINKPREV;
11906 			inodedep->id_state |= UNLINKNEXT;
11907 		}
11908 		hadchanges = 1;
11909 	}
11910 	/*
11911 	 * If we had to rollback the inode allocation because of
11912 	 * bitmaps being incomplete, then simply restore it.
11913 	 * Keep the block dirty so that it will not be reclaimed until
11914 	 * all associated dependencies have been cleared and the
11915 	 * corresponding updates written to disk.
11916 	 */
11917 	if (inodedep->id_savedino1 != NULL) {
11918 		hadchanges = 1;
11919 		if (fstype == UFS1)
11920 			*dp1 = *inodedep->id_savedino1;
11921 		else
11922 			*dp2 = *inodedep->id_savedino2;
11923 		free(inodedep->id_savedino1, M_SAVEDINO);
11924 		inodedep->id_savedino1 = NULL;
11925 		if ((bp->b_flags & B_DELWRI) == 0)
11926 			stat_inode_bitmap++;
11927 		bdirty(bp);
11928 		/*
11929 		 * If the inode is clear here and GOINGAWAY it will never
11930 		 * be written.  Process the bufwait and clear any pending
11931 		 * work which may include the freefile.
11932 		 */
11933 		if (inodedep->id_state & GOINGAWAY)
11934 			goto bufwait;
11935 		return (1);
11936 	}
11937 	if (flags & WRITESUCCEEDED)
11938 		inodedep->id_state |= COMPLETE;
11939 	/*
11940 	 * Roll forward anything that had to be rolled back before
11941 	 * the inode could be updated.
11942 	 */
11943 	for (adp = TAILQ_FIRST(&inodedep->id_inoupdt); adp; adp = nextadp) {
11944 		nextadp = TAILQ_NEXT(adp, ad_next);
11945 		if (adp->ad_state & ATTACHED)
11946 			panic("handle_written_inodeblock: new entry");
11947 		if (fstype == UFS1) {
11948 			if (adp->ad_offset < UFS_NDADDR) {
11949 				if (dp1->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11950 					panic("%s %s #%jd mismatch %d != %jd",
11951 					    "handle_written_inodeblock:",
11952 					    "direct pointer",
11953 					    (intmax_t)adp->ad_offset,
11954 					    dp1->di_db[adp->ad_offset],
11955 					    (intmax_t)adp->ad_oldblkno);
11956 				dp1->di_db[adp->ad_offset] = adp->ad_newblkno;
11957 			} else {
11958 				if (dp1->di_ib[adp->ad_offset - UFS_NDADDR] !=
11959 				    0)
11960 					panic("%s: %s #%jd allocated as %d",
11961 					    "handle_written_inodeblock",
11962 					    "indirect pointer",
11963 					    (intmax_t)adp->ad_offset -
11964 					    UFS_NDADDR,
11965 					    dp1->di_ib[adp->ad_offset -
11966 					    UFS_NDADDR]);
11967 				dp1->di_ib[adp->ad_offset - UFS_NDADDR] =
11968 				    adp->ad_newblkno;
11969 			}
11970 		} else {
11971 			if (adp->ad_offset < UFS_NDADDR) {
11972 				if (dp2->di_db[adp->ad_offset]!=adp->ad_oldblkno)
11973 					panic("%s: %s #%jd %s %jd != %jd",
11974 					    "handle_written_inodeblock",
11975 					    "direct pointer",
11976 					    (intmax_t)adp->ad_offset, "mismatch",
11977 					    (intmax_t)dp2->di_db[adp->ad_offset],
11978 					    (intmax_t)adp->ad_oldblkno);
11979 				dp2->di_db[adp->ad_offset] = adp->ad_newblkno;
11980 			} else {
11981 				if (dp2->di_ib[adp->ad_offset - UFS_NDADDR] !=
11982 				    0)
11983 					panic("%s: %s #%jd allocated as %jd",
11984 					    "handle_written_inodeblock",
11985 					    "indirect pointer",
11986 					    (intmax_t)adp->ad_offset -
11987 					    UFS_NDADDR,
11988 					    (intmax_t)
11989 					    dp2->di_ib[adp->ad_offset -
11990 					    UFS_NDADDR]);
11991 				dp2->di_ib[adp->ad_offset - UFS_NDADDR] =
11992 				    adp->ad_newblkno;
11993 			}
11994 		}
11995 		adp->ad_state &= ~UNDONE;
11996 		adp->ad_state |= ATTACHED;
11997 		hadchanges = 1;
11998 	}
11999 	for (adp = TAILQ_FIRST(&inodedep->id_extupdt); adp; adp = nextadp) {
12000 		nextadp = TAILQ_NEXT(adp, ad_next);
12001 		if (adp->ad_state & ATTACHED)
12002 			panic("handle_written_inodeblock: new entry");
12003 		if (dp2->di_extb[adp->ad_offset] != adp->ad_oldblkno)
12004 			panic("%s: direct pointers #%jd %s %jd != %jd",
12005 			    "handle_written_inodeblock",
12006 			    (intmax_t)adp->ad_offset, "mismatch",
12007 			    (intmax_t)dp2->di_extb[adp->ad_offset],
12008 			    (intmax_t)adp->ad_oldblkno);
12009 		dp2->di_extb[adp->ad_offset] = adp->ad_newblkno;
12010 		adp->ad_state &= ~UNDONE;
12011 		adp->ad_state |= ATTACHED;
12012 		hadchanges = 1;
12013 	}
12014 	if (hadchanges && (bp->b_flags & B_DELWRI) == 0)
12015 		stat_direct_blk_ptrs++;
12016 	/*
12017 	 * Reset the file size to its most up-to-date value.
12018 	 */
12019 	if (inodedep->id_savedsize == -1 || inodedep->id_savedextsize == -1)
12020 		panic("handle_written_inodeblock: bad size");
12021 	if (inodedep->id_savednlink > UFS_LINK_MAX)
12022 		panic("handle_written_inodeblock: Invalid link count "
12023 		    "%jd for inodedep %p", (uintmax_t)inodedep->id_savednlink,
12024 		    inodedep);
12025 	if (fstype == UFS1) {
12026 		if (dp1->di_nlink != inodedep->id_savednlink) {
12027 			dp1->di_nlink = inodedep->id_savednlink;
12028 			hadchanges = 1;
12029 		}
12030 		if (dp1->di_size != inodedep->id_savedsize) {
12031 			dp1->di_size = inodedep->id_savedsize;
12032 			hadchanges = 1;
12033 		}
12034 	} else {
12035 		if (dp2->di_nlink != inodedep->id_savednlink) {
12036 			dp2->di_nlink = inodedep->id_savednlink;
12037 			hadchanges = 1;
12038 		}
12039 		if (dp2->di_size != inodedep->id_savedsize) {
12040 			dp2->di_size = inodedep->id_savedsize;
12041 			hadchanges = 1;
12042 		}
12043 		if (dp2->di_extsize != inodedep->id_savedextsize) {
12044 			dp2->di_extsize = inodedep->id_savedextsize;
12045 			hadchanges = 1;
12046 		}
12047 	}
12048 	inodedep->id_savedsize = -1;
12049 	inodedep->id_savedextsize = -1;
12050 	inodedep->id_savednlink = -1;
12051 	/*
12052 	 * If there were any rollbacks in the inode block, then it must be
12053 	 * marked dirty so that its will eventually get written back in
12054 	 * its correct form.
12055 	 */
12056 	if (hadchanges) {
12057 		if (fstype == UFS2)
12058 			ffs_update_dinode_ckhash(inodedep->id_fs, dp2);
12059 		bdirty(bp);
12060 	}
12061 bufwait:
12062 	/*
12063 	 * If the write did not succeed, we have done all the roll-forward
12064 	 * operations, but we cannot take the actions that will allow its
12065 	 * dependencies to be processed.
12066 	 */
12067 	if ((flags & WRITESUCCEEDED) == 0)
12068 		return (hadchanges);
12069 	/*
12070 	 * Process any allocdirects that completed during the update.
12071 	 */
12072 	if ((adp = TAILQ_FIRST(&inodedep->id_inoupdt)) != NULL)
12073 		handle_allocdirect_partdone(adp, &wkhd);
12074 	if ((adp = TAILQ_FIRST(&inodedep->id_extupdt)) != NULL)
12075 		handle_allocdirect_partdone(adp, &wkhd);
12076 	/*
12077 	 * Process deallocations that were held pending until the
12078 	 * inode had been written to disk. Freeing of the inode
12079 	 * is delayed until after all blocks have been freed to
12080 	 * avoid creation of new <vfsid, inum, lbn> triples
12081 	 * before the old ones have been deleted.  Completely
12082 	 * unlinked inodes are not processed until the unlinked
12083 	 * inode list is written or the last reference is removed.
12084 	 */
12085 	if ((inodedep->id_state & (UNLINKED | UNLINKONLIST)) != UNLINKED) {
12086 		freefile = handle_bufwait(inodedep, NULL);
12087 		if (freefile && !LIST_EMPTY(&wkhd)) {
12088 			WORKLIST_INSERT(&wkhd, &freefile->fx_list);
12089 			freefile = NULL;
12090 		}
12091 	}
12092 	/*
12093 	 * Move rolled forward dependency completions to the bufwait list
12094 	 * now that those that were already written have been processed.
12095 	 */
12096 	if (!LIST_EMPTY(&wkhd) && hadchanges == 0)
12097 		panic("handle_written_inodeblock: bufwait but no changes");
12098 	jwork_move(&inodedep->id_bufwait, &wkhd);
12099 
12100 	if (freefile != NULL) {
12101 		/*
12102 		 * If the inode is goingaway it was never written.  Fake up
12103 		 * the state here so free_inodedep() can succeed.
12104 		 */
12105 		if (inodedep->id_state & GOINGAWAY)
12106 			inodedep->id_state |= COMPLETE | DEPCOMPLETE;
12107 		if (free_inodedep(inodedep) == 0)
12108 			panic("handle_written_inodeblock: live inodedep %p",
12109 			    inodedep);
12110 		add_to_worklist(&freefile->fx_list, 0);
12111 		return (0);
12112 	}
12113 
12114 	/*
12115 	 * If no outstanding dependencies, free it.
12116 	 */
12117 	if (free_inodedep(inodedep) ||
12118 	    (TAILQ_FIRST(&inodedep->id_inoreflst) == 0 &&
12119 	     TAILQ_FIRST(&inodedep->id_inoupdt) == 0 &&
12120 	     TAILQ_FIRST(&inodedep->id_extupdt) == 0 &&
12121 	     LIST_FIRST(&inodedep->id_bufwait) == 0))
12122 		return (0);
12123 	return (hadchanges);
12124 }
12125 
12126 /*
12127  * Perform needed roll-forwards and kick off any dependencies that
12128  * can now be processed.
12129  *
12130  * If the write did not succeed, we will do all the roll-forward
12131  * operations, but we will not take the actions that will allow its
12132  * dependencies to be processed.
12133  */
12134 static int
12135 handle_written_indirdep(indirdep, bp, bpp, flags)
12136 	struct indirdep *indirdep;
12137 	struct buf *bp;
12138 	struct buf **bpp;
12139 	int flags;
12140 {
12141 	struct allocindir *aip;
12142 	struct buf *sbp;
12143 	int chgs;
12144 
12145 	if (indirdep->ir_state & GOINGAWAY)
12146 		panic("handle_written_indirdep: indirdep gone");
12147 	if ((indirdep->ir_state & IOSTARTED) == 0)
12148 		panic("handle_written_indirdep: IO not started");
12149 	chgs = 0;
12150 	/*
12151 	 * If there were rollbacks revert them here.
12152 	 */
12153 	if (indirdep->ir_saveddata) {
12154 		bcopy(indirdep->ir_saveddata, bp->b_data, bp->b_bcount);
12155 		if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12156 			free(indirdep->ir_saveddata, M_INDIRDEP);
12157 			indirdep->ir_saveddata = NULL;
12158 		}
12159 		chgs = 1;
12160 	}
12161 	indirdep->ir_state &= ~(UNDONE | IOSTARTED);
12162 	indirdep->ir_state |= ATTACHED;
12163 	/*
12164 	 * If the write did not succeed, we have done all the roll-forward
12165 	 * operations, but we cannot take the actions that will allow its
12166 	 * dependencies to be processed.
12167 	 */
12168 	if ((flags & WRITESUCCEEDED) == 0) {
12169 		stat_indir_blk_ptrs++;
12170 		bdirty(bp);
12171 		return (1);
12172 	}
12173 	/*
12174 	 * Move allocindirs with written pointers to the completehd if
12175 	 * the indirdep's pointer is not yet written.  Otherwise
12176 	 * free them here.
12177 	 */
12178 	while ((aip = LIST_FIRST(&indirdep->ir_writehd)) != NULL) {
12179 		LIST_REMOVE(aip, ai_next);
12180 		if ((indirdep->ir_state & DEPCOMPLETE) == 0) {
12181 			LIST_INSERT_HEAD(&indirdep->ir_completehd, aip,
12182 			    ai_next);
12183 			newblk_freefrag(&aip->ai_block);
12184 			continue;
12185 		}
12186 		free_newblk(&aip->ai_block);
12187 	}
12188 	/*
12189 	 * Move allocindirs that have finished dependency processing from
12190 	 * the done list to the write list after updating the pointers.
12191 	 */
12192 	if (TAILQ_EMPTY(&indirdep->ir_trunc)) {
12193 		while ((aip = LIST_FIRST(&indirdep->ir_donehd)) != NULL) {
12194 			handle_allocindir_partdone(aip);
12195 			if (aip == LIST_FIRST(&indirdep->ir_donehd))
12196 				panic("disk_write_complete: not gone");
12197 			chgs = 1;
12198 		}
12199 	}
12200 	/*
12201 	 * Preserve the indirdep if there were any changes or if it is not
12202 	 * yet valid on disk.
12203 	 */
12204 	if (chgs) {
12205 		stat_indir_blk_ptrs++;
12206 		bdirty(bp);
12207 		return (1);
12208 	}
12209 	/*
12210 	 * If there were no changes we can discard the savedbp and detach
12211 	 * ourselves from the buf.  We are only carrying completed pointers
12212 	 * in this case.
12213 	 */
12214 	sbp = indirdep->ir_savebp;
12215 	sbp->b_flags |= B_INVAL | B_NOCACHE;
12216 	indirdep->ir_savebp = NULL;
12217 	indirdep->ir_bp = NULL;
12218 	if (*bpp != NULL)
12219 		panic("handle_written_indirdep: bp already exists.");
12220 	*bpp = sbp;
12221 	/*
12222 	 * The indirdep may not be freed until its parent points at it.
12223 	 */
12224 	if (indirdep->ir_state & DEPCOMPLETE)
12225 		free_indirdep(indirdep);
12226 
12227 	return (0);
12228 }
12229 
12230 /*
12231  * Process a diradd entry after its dependent inode has been written.
12232  */
12233 static void
12234 diradd_inode_written(dap, inodedep)
12235 	struct diradd *dap;
12236 	struct inodedep *inodedep;
12237 {
12238 
12239 	LOCK_OWNED(VFSTOUFS(dap->da_list.wk_mp));
12240 	dap->da_state |= COMPLETE;
12241 	complete_diradd(dap);
12242 	WORKLIST_INSERT(&inodedep->id_pendinghd, &dap->da_list);
12243 }
12244 
12245 /*
12246  * Returns true if the bmsafemap will have rollbacks when written.  Must only
12247  * be called with the per-filesystem lock and the buf lock on the cg held.
12248  */
12249 static int
12250 bmsafemap_backgroundwrite(bmsafemap, bp)
12251 	struct bmsafemap *bmsafemap;
12252 	struct buf *bp;
12253 {
12254 	int dirty;
12255 
12256 	LOCK_OWNED(VFSTOUFS(bmsafemap->sm_list.wk_mp));
12257 	dirty = !LIST_EMPTY(&bmsafemap->sm_jaddrefhd) |
12258 	    !LIST_EMPTY(&bmsafemap->sm_jnewblkhd);
12259 	/*
12260 	 * If we're initiating a background write we need to process the
12261 	 * rollbacks as they exist now, not as they exist when IO starts.
12262 	 * No other consumers will look at the contents of the shadowed
12263 	 * buf so this is safe to do here.
12264 	 */
12265 	if (bp->b_xflags & BX_BKGRDMARKER)
12266 		initiate_write_bmsafemap(bmsafemap, bp);
12267 
12268 	return (dirty);
12269 }
12270 
12271 /*
12272  * Re-apply an allocation when a cg write is complete.
12273  */
12274 static int
12275 jnewblk_rollforward(jnewblk, fs, cgp, blksfree)
12276 	struct jnewblk *jnewblk;
12277 	struct fs *fs;
12278 	struct cg *cgp;
12279 	uint8_t *blksfree;
12280 {
12281 	ufs1_daddr_t fragno;
12282 	ufs2_daddr_t blkno;
12283 	long cgbno, bbase;
12284 	int frags, blk;
12285 	int i;
12286 
12287 	frags = 0;
12288 	cgbno = dtogd(fs, jnewblk->jn_blkno);
12289 	for (i = jnewblk->jn_oldfrags; i < jnewblk->jn_frags; i++) {
12290 		if (isclr(blksfree, cgbno + i))
12291 			panic("jnewblk_rollforward: re-allocated fragment");
12292 		frags++;
12293 	}
12294 	if (frags == fs->fs_frag) {
12295 		blkno = fragstoblks(fs, cgbno);
12296 		ffs_clrblock(fs, blksfree, (long)blkno);
12297 		ffs_clusteracct(fs, cgp, blkno, -1);
12298 		cgp->cg_cs.cs_nbfree--;
12299 	} else {
12300 		bbase = cgbno - fragnum(fs, cgbno);
12301 		cgbno += jnewblk->jn_oldfrags;
12302                 /* If a complete block had been reassembled, account for it. */
12303 		fragno = fragstoblks(fs, bbase);
12304 		if (ffs_isblock(fs, blksfree, fragno)) {
12305 			cgp->cg_cs.cs_nffree += fs->fs_frag;
12306 			ffs_clusteracct(fs, cgp, fragno, -1);
12307 			cgp->cg_cs.cs_nbfree--;
12308 		}
12309 		/* Decrement the old frags.  */
12310 		blk = blkmap(fs, blksfree, bbase);
12311 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
12312 		/* Allocate the fragment */
12313 		for (i = 0; i < frags; i++)
12314 			clrbit(blksfree, cgbno + i);
12315 		cgp->cg_cs.cs_nffree -= frags;
12316 		/* Add back in counts associated with the new frags */
12317 		blk = blkmap(fs, blksfree, bbase);
12318 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
12319 	}
12320 	return (frags);
12321 }
12322 
12323 /*
12324  * Complete a write to a bmsafemap structure.  Roll forward any bitmap
12325  * changes if it's not a background write.  Set all written dependencies
12326  * to DEPCOMPLETE and free the structure if possible.
12327  *
12328  * If the write did not succeed, we will do all the roll-forward
12329  * operations, but we will not take the actions that will allow its
12330  * dependencies to be processed.
12331  */
12332 static int
12333 handle_written_bmsafemap(bmsafemap, bp, flags)
12334 	struct bmsafemap *bmsafemap;
12335 	struct buf *bp;
12336 	int flags;
12337 {
12338 	struct newblk *newblk;
12339 	struct inodedep *inodedep;
12340 	struct jaddref *jaddref, *jatmp;
12341 	struct jnewblk *jnewblk, *jntmp;
12342 	struct ufsmount *ump;
12343 	uint8_t *inosused;
12344 	uint8_t *blksfree;
12345 	struct cg *cgp;
12346 	struct fs *fs;
12347 	ino_t ino;
12348 	int foreground;
12349 	int chgs;
12350 
12351 	if ((bmsafemap->sm_state & IOSTARTED) == 0)
12352 		panic("handle_written_bmsafemap: Not started\n");
12353 	ump = VFSTOUFS(bmsafemap->sm_list.wk_mp);
12354 	chgs = 0;
12355 	bmsafemap->sm_state &= ~IOSTARTED;
12356 	foreground = (bp->b_xflags & BX_BKGRDMARKER) == 0;
12357 	/*
12358 	 * If write was successful, release journal work that was waiting
12359 	 * on the write. Otherwise move the work back.
12360 	 */
12361 	if (flags & WRITESUCCEEDED)
12362 		handle_jwork(&bmsafemap->sm_freewr);
12363 	else
12364 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12365 		    worklist, wk_list);
12366 
12367 	/*
12368 	 * Restore unwritten inode allocation pending jaddref writes.
12369 	 */
12370 	if (!LIST_EMPTY(&bmsafemap->sm_jaddrefhd)) {
12371 		cgp = (struct cg *)bp->b_data;
12372 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12373 		inosused = cg_inosused(cgp);
12374 		LIST_FOREACH_SAFE(jaddref, &bmsafemap->sm_jaddrefhd,
12375 		    ja_bmdeps, jatmp) {
12376 			if ((jaddref->ja_state & UNDONE) == 0)
12377 				continue;
12378 			ino = jaddref->ja_ino % fs->fs_ipg;
12379 			if (isset(inosused, ino))
12380 				panic("handle_written_bmsafemap: "
12381 				    "re-allocated inode");
12382 			/* Do the roll-forward only if it's a real copy. */
12383 			if (foreground) {
12384 				if ((jaddref->ja_mode & IFMT) == IFDIR)
12385 					cgp->cg_cs.cs_ndir++;
12386 				cgp->cg_cs.cs_nifree--;
12387 				setbit(inosused, ino);
12388 				chgs = 1;
12389 			}
12390 			jaddref->ja_state &= ~UNDONE;
12391 			jaddref->ja_state |= ATTACHED;
12392 			free_jaddref(jaddref);
12393 		}
12394 	}
12395 	/*
12396 	 * Restore any block allocations which are pending journal writes.
12397 	 */
12398 	if (LIST_FIRST(&bmsafemap->sm_jnewblkhd) != NULL) {
12399 		cgp = (struct cg *)bp->b_data;
12400 		fs = VFSTOUFS(bmsafemap->sm_list.wk_mp)->um_fs;
12401 		blksfree = cg_blksfree(cgp);
12402 		LIST_FOREACH_SAFE(jnewblk, &bmsafemap->sm_jnewblkhd, jn_deps,
12403 		    jntmp) {
12404 			if ((jnewblk->jn_state & UNDONE) == 0)
12405 				continue;
12406 			/* Do the roll-forward only if it's a real copy. */
12407 			if (foreground &&
12408 			    jnewblk_rollforward(jnewblk, fs, cgp, blksfree))
12409 				chgs = 1;
12410 			jnewblk->jn_state &= ~(UNDONE | NEWBLOCK);
12411 			jnewblk->jn_state |= ATTACHED;
12412 			free_jnewblk(jnewblk);
12413 		}
12414 	}
12415 	/*
12416 	 * If the write did not succeed, we have done all the roll-forward
12417 	 * operations, but we cannot take the actions that will allow its
12418 	 * dependencies to be processed.
12419 	 */
12420 	if ((flags & WRITESUCCEEDED) == 0) {
12421 		LIST_CONCAT(&bmsafemap->sm_newblkhd, &bmsafemap->sm_newblkwr,
12422 		    newblk, nb_deps);
12423 		LIST_CONCAT(&bmsafemap->sm_freehd, &bmsafemap->sm_freewr,
12424 		    worklist, wk_list);
12425 		if (foreground)
12426 			bdirty(bp);
12427 		return (1);
12428 	}
12429 	while ((newblk = LIST_FIRST(&bmsafemap->sm_newblkwr))) {
12430 		newblk->nb_state |= DEPCOMPLETE;
12431 		newblk->nb_state &= ~ONDEPLIST;
12432 		newblk->nb_bmsafemap = NULL;
12433 		LIST_REMOVE(newblk, nb_deps);
12434 		if (newblk->nb_list.wk_type == D_ALLOCDIRECT)
12435 			handle_allocdirect_partdone(
12436 			    WK_ALLOCDIRECT(&newblk->nb_list), NULL);
12437 		else if (newblk->nb_list.wk_type == D_ALLOCINDIR)
12438 			handle_allocindir_partdone(
12439 			    WK_ALLOCINDIR(&newblk->nb_list));
12440 		else if (newblk->nb_list.wk_type != D_NEWBLK)
12441 			panic("handle_written_bmsafemap: Unexpected type: %s",
12442 			    TYPENAME(newblk->nb_list.wk_type));
12443 	}
12444 	while ((inodedep = LIST_FIRST(&bmsafemap->sm_inodedepwr)) != NULL) {
12445 		inodedep->id_state |= DEPCOMPLETE;
12446 		inodedep->id_state &= ~ONDEPLIST;
12447 		LIST_REMOVE(inodedep, id_deps);
12448 		inodedep->id_bmsafemap = NULL;
12449 	}
12450 	LIST_REMOVE(bmsafemap, sm_next);
12451 	if (chgs == 0 && LIST_EMPTY(&bmsafemap->sm_jaddrefhd) &&
12452 	    LIST_EMPTY(&bmsafemap->sm_jnewblkhd) &&
12453 	    LIST_EMPTY(&bmsafemap->sm_newblkhd) &&
12454 	    LIST_EMPTY(&bmsafemap->sm_inodedephd) &&
12455 	    LIST_EMPTY(&bmsafemap->sm_freehd)) {
12456 		LIST_REMOVE(bmsafemap, sm_hash);
12457 		WORKITEM_FREE(bmsafemap, D_BMSAFEMAP);
12458 		return (0);
12459 	}
12460 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, bmsafemap, sm_next);
12461 	if (foreground)
12462 		bdirty(bp);
12463 	return (1);
12464 }
12465 
12466 /*
12467  * Try to free a mkdir dependency.
12468  */
12469 static void
12470 complete_mkdir(mkdir)
12471 	struct mkdir *mkdir;
12472 {
12473 	struct diradd *dap;
12474 
12475 	if ((mkdir->md_state & ALLCOMPLETE) != ALLCOMPLETE)
12476 		return;
12477 	LIST_REMOVE(mkdir, md_mkdirs);
12478 	dap = mkdir->md_diradd;
12479 	dap->da_state &= ~(mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY));
12480 	if ((dap->da_state & (MKDIR_PARENT | MKDIR_BODY)) == 0) {
12481 		dap->da_state |= DEPCOMPLETE;
12482 		complete_diradd(dap);
12483 	}
12484 	WORKITEM_FREE(mkdir, D_MKDIR);
12485 }
12486 
12487 /*
12488  * Handle the completion of a mkdir dependency.
12489  */
12490 static void
12491 handle_written_mkdir(mkdir, type)
12492 	struct mkdir *mkdir;
12493 	int type;
12494 {
12495 
12496 	if ((mkdir->md_state & (MKDIR_PARENT | MKDIR_BODY)) != type)
12497 		panic("handle_written_mkdir: bad type");
12498 	mkdir->md_state |= COMPLETE;
12499 	complete_mkdir(mkdir);
12500 }
12501 
12502 static int
12503 free_pagedep(pagedep)
12504 	struct pagedep *pagedep;
12505 {
12506 	int i;
12507 
12508 	if (pagedep->pd_state & NEWBLOCK)
12509 		return (0);
12510 	if (!LIST_EMPTY(&pagedep->pd_dirremhd))
12511 		return (0);
12512 	for (i = 0; i < DAHASHSZ; i++)
12513 		if (!LIST_EMPTY(&pagedep->pd_diraddhd[i]))
12514 			return (0);
12515 	if (!LIST_EMPTY(&pagedep->pd_pendinghd))
12516 		return (0);
12517 	if (!LIST_EMPTY(&pagedep->pd_jmvrefhd))
12518 		return (0);
12519 	if (pagedep->pd_state & ONWORKLIST)
12520 		WORKLIST_REMOVE(&pagedep->pd_list);
12521 	LIST_REMOVE(pagedep, pd_hash);
12522 	WORKITEM_FREE(pagedep, D_PAGEDEP);
12523 
12524 	return (1);
12525 }
12526 
12527 /*
12528  * Called from within softdep_disk_write_complete above.
12529  * A write operation was just completed. Removed inodes can
12530  * now be freed and associated block pointers may be committed.
12531  * Note that this routine is always called from interrupt level
12532  * with further interrupts from this device blocked.
12533  *
12534  * If the write did not succeed, we will do all the roll-forward
12535  * operations, but we will not take the actions that will allow its
12536  * dependencies to be processed.
12537  */
12538 static int
12539 handle_written_filepage(pagedep, bp, flags)
12540 	struct pagedep *pagedep;
12541 	struct buf *bp;		/* buffer containing the written page */
12542 	int flags;
12543 {
12544 	struct dirrem *dirrem;
12545 	struct diradd *dap, *nextdap;
12546 	struct direct *ep;
12547 	int i, chgs;
12548 
12549 	if ((pagedep->pd_state & IOSTARTED) == 0)
12550 		panic("handle_written_filepage: not started");
12551 	pagedep->pd_state &= ~IOSTARTED;
12552 	if ((flags & WRITESUCCEEDED) == 0)
12553 		goto rollforward;
12554 	/*
12555 	 * Process any directory removals that have been committed.
12556 	 */
12557 	while ((dirrem = LIST_FIRST(&pagedep->pd_dirremhd)) != NULL) {
12558 		LIST_REMOVE(dirrem, dm_next);
12559 		dirrem->dm_state |= COMPLETE;
12560 		dirrem->dm_dirinum = pagedep->pd_ino;
12561 		KASSERT(LIST_EMPTY(&dirrem->dm_jremrefhd),
12562 		    ("handle_written_filepage: Journal entries not written."));
12563 		add_to_worklist(&dirrem->dm_list, 0);
12564 	}
12565 	/*
12566 	 * Free any directory additions that have been committed.
12567 	 * If it is a newly allocated block, we have to wait until
12568 	 * the on-disk directory inode claims the new block.
12569 	 */
12570 	if ((pagedep->pd_state & NEWBLOCK) == 0)
12571 		while ((dap = LIST_FIRST(&pagedep->pd_pendinghd)) != NULL)
12572 			free_diradd(dap, NULL);
12573 rollforward:
12574 	/*
12575 	 * Uncommitted directory entries must be restored.
12576 	 */
12577 	for (chgs = 0, i = 0; i < DAHASHSZ; i++) {
12578 		for (dap = LIST_FIRST(&pagedep->pd_diraddhd[i]); dap;
12579 		     dap = nextdap) {
12580 			nextdap = LIST_NEXT(dap, da_pdlist);
12581 			if (dap->da_state & ATTACHED)
12582 				panic("handle_written_filepage: attached");
12583 			ep = (struct direct *)
12584 			    ((char *)bp->b_data + dap->da_offset);
12585 			ep->d_ino = dap->da_newinum;
12586 			dap->da_state &= ~UNDONE;
12587 			dap->da_state |= ATTACHED;
12588 			chgs = 1;
12589 			/*
12590 			 * If the inode referenced by the directory has
12591 			 * been written out, then the dependency can be
12592 			 * moved to the pending list.
12593 			 */
12594 			if ((dap->da_state & ALLCOMPLETE) == ALLCOMPLETE) {
12595 				LIST_REMOVE(dap, da_pdlist);
12596 				LIST_INSERT_HEAD(&pagedep->pd_pendinghd, dap,
12597 				    da_pdlist);
12598 			}
12599 		}
12600 	}
12601 	/*
12602 	 * If there were any rollbacks in the directory, then it must be
12603 	 * marked dirty so that its will eventually get written back in
12604 	 * its correct form.
12605 	 */
12606 	if (chgs || (flags & WRITESUCCEEDED) == 0) {
12607 		if ((bp->b_flags & B_DELWRI) == 0)
12608 			stat_dir_entry++;
12609 		bdirty(bp);
12610 		return (1);
12611 	}
12612 	/*
12613 	 * If we are not waiting for a new directory block to be
12614 	 * claimed by its inode, then the pagedep will be freed.
12615 	 * Otherwise it will remain to track any new entries on
12616 	 * the page in case they are fsync'ed.
12617 	 */
12618 	free_pagedep(pagedep);
12619 	return (0);
12620 }
12621 
12622 /*
12623  * Writing back in-core inode structures.
12624  *
12625  * The filesystem only accesses an inode's contents when it occupies an
12626  * "in-core" inode structure.  These "in-core" structures are separate from
12627  * the page frames used to cache inode blocks.  Only the latter are
12628  * transferred to/from the disk.  So, when the updated contents of the
12629  * "in-core" inode structure are copied to the corresponding in-memory inode
12630  * block, the dependencies are also transferred.  The following procedure is
12631  * called when copying a dirty "in-core" inode to a cached inode block.
12632  */
12633 
12634 /*
12635  * Called when an inode is loaded from disk. If the effective link count
12636  * differed from the actual link count when it was last flushed, then we
12637  * need to ensure that the correct effective link count is put back.
12638  */
12639 void
12640 softdep_load_inodeblock(ip)
12641 	struct inode *ip;	/* the "in_core" copy of the inode */
12642 {
12643 	struct inodedep *inodedep;
12644 	struct ufsmount *ump;
12645 
12646 	ump = ITOUMP(ip);
12647 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
12648 	    ("softdep_load_inodeblock called on non-softdep filesystem"));
12649 	/*
12650 	 * Check for alternate nlink count.
12651 	 */
12652 	ip->i_effnlink = ip->i_nlink;
12653 	ACQUIRE_LOCK(ump);
12654 	if (inodedep_lookup(UFSTOVFS(ump), ip->i_number, 0, &inodedep) == 0) {
12655 		FREE_LOCK(ump);
12656 		return;
12657 	}
12658 	if (ip->i_nlink != inodedep->id_nlinkwrote &&
12659 	    inodedep->id_nlinkwrote != -1) {
12660 		KASSERT(ip->i_nlink == 0 &&
12661 		    (ump->um_flags & UM_FSFAIL_CLEANUP) != 0,
12662 		    ("read bad i_nlink value"));
12663 		ip->i_effnlink = ip->i_nlink = inodedep->id_nlinkwrote;
12664 	}
12665 	ip->i_effnlink -= inodedep->id_nlinkdelta;
12666 	KASSERT(ip->i_effnlink >= 0,
12667 	    ("softdep_load_inodeblock: negative i_effnlink"));
12668 	FREE_LOCK(ump);
12669 }
12670 
12671 /*
12672  * This routine is called just before the "in-core" inode
12673  * information is to be copied to the in-memory inode block.
12674  * Recall that an inode block contains several inodes. If
12675  * the force flag is set, then the dependencies will be
12676  * cleared so that the update can always be made. Note that
12677  * the buffer is locked when this routine is called, so we
12678  * will never be in the middle of writing the inode block
12679  * to disk.
12680  */
12681 void
12682 softdep_update_inodeblock(ip, bp, waitfor)
12683 	struct inode *ip;	/* the "in_core" copy of the inode */
12684 	struct buf *bp;		/* the buffer containing the inode block */
12685 	int waitfor;		/* nonzero => update must be allowed */
12686 {
12687 	struct inodedep *inodedep;
12688 	struct inoref *inoref;
12689 	struct ufsmount *ump;
12690 	struct worklist *wk;
12691 	struct mount *mp;
12692 	struct buf *ibp;
12693 	struct fs *fs;
12694 	int error;
12695 
12696 	ump = ITOUMP(ip);
12697 	mp = UFSTOVFS(ump);
12698 	KASSERT(MOUNTEDSOFTDEP(mp) != 0,
12699 	    ("softdep_update_inodeblock called on non-softdep filesystem"));
12700 	fs = ump->um_fs;
12701 	/*
12702 	 * Preserve the freelink that is on disk.  clear_unlinked_inodedep()
12703 	 * does not have access to the in-core ip so must write directly into
12704 	 * the inode block buffer when setting freelink.
12705 	 */
12706 	if (fs->fs_magic == FS_UFS1_MAGIC)
12707 		DIP_SET(ip, i_freelink, ((struct ufs1_dinode *)bp->b_data +
12708 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12709 	else
12710 		DIP_SET(ip, i_freelink, ((struct ufs2_dinode *)bp->b_data +
12711 		    ino_to_fsbo(fs, ip->i_number))->di_freelink);
12712 	/*
12713 	 * If the effective link count is not equal to the actual link
12714 	 * count, then we must track the difference in an inodedep while
12715 	 * the inode is (potentially) tossed out of the cache. Otherwise,
12716 	 * if there is no existing inodedep, then there are no dependencies
12717 	 * to track.
12718 	 */
12719 	ACQUIRE_LOCK(ump);
12720 again:
12721 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12722 		FREE_LOCK(ump);
12723 		if (ip->i_effnlink != ip->i_nlink)
12724 			panic("softdep_update_inodeblock: bad link count");
12725 		return;
12726 	}
12727 	KASSERT(ip->i_nlink >= inodedep->id_nlinkdelta,
12728 	    ("softdep_update_inodeblock inconsistent ip %p i_nlink %d "
12729 	    "inodedep %p id_nlinkdelta %jd",
12730 	    ip, ip->i_nlink, inodedep, (intmax_t)inodedep->id_nlinkdelta));
12731 	inodedep->id_nlinkwrote = ip->i_nlink;
12732 	if (inodedep->id_nlinkdelta != ip->i_nlink - ip->i_effnlink)
12733 		panic("softdep_update_inodeblock: bad delta");
12734 	/*
12735 	 * If we're flushing all dependencies we must also move any waiting
12736 	 * for journal writes onto the bufwait list prior to I/O.
12737 	 */
12738 	if (waitfor) {
12739 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12740 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12741 			    == DEPCOMPLETE) {
12742 				jwait(&inoref->if_list, MNT_WAIT);
12743 				goto again;
12744 			}
12745 		}
12746 	}
12747 	/*
12748 	 * Changes have been initiated. Anything depending on these
12749 	 * changes cannot occur until this inode has been written.
12750 	 */
12751 	inodedep->id_state &= ~COMPLETE;
12752 	if ((inodedep->id_state & ONWORKLIST) == 0)
12753 		WORKLIST_INSERT(&bp->b_dep, &inodedep->id_list);
12754 	/*
12755 	 * Any new dependencies associated with the incore inode must
12756 	 * now be moved to the list associated with the buffer holding
12757 	 * the in-memory copy of the inode. Once merged process any
12758 	 * allocdirects that are completed by the merger.
12759 	 */
12760 	merge_inode_lists(&inodedep->id_newinoupdt, &inodedep->id_inoupdt);
12761 	if (!TAILQ_EMPTY(&inodedep->id_inoupdt))
12762 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_inoupdt),
12763 		    NULL);
12764 	merge_inode_lists(&inodedep->id_newextupdt, &inodedep->id_extupdt);
12765 	if (!TAILQ_EMPTY(&inodedep->id_extupdt))
12766 		handle_allocdirect_partdone(TAILQ_FIRST(&inodedep->id_extupdt),
12767 		    NULL);
12768 	/*
12769 	 * Now that the inode has been pushed into the buffer, the
12770 	 * operations dependent on the inode being written to disk
12771 	 * can be moved to the id_bufwait so that they will be
12772 	 * processed when the buffer I/O completes.
12773 	 */
12774 	while ((wk = LIST_FIRST(&inodedep->id_inowait)) != NULL) {
12775 		WORKLIST_REMOVE(wk);
12776 		WORKLIST_INSERT(&inodedep->id_bufwait, wk);
12777 	}
12778 	/*
12779 	 * Newly allocated inodes cannot be written until the bitmap
12780 	 * that allocates them have been written (indicated by
12781 	 * DEPCOMPLETE being set in id_state). If we are doing a
12782 	 * forced sync (e.g., an fsync on a file), we force the bitmap
12783 	 * to be written so that the update can be done.
12784 	 */
12785 	if (waitfor == 0) {
12786 		FREE_LOCK(ump);
12787 		return;
12788 	}
12789 retry:
12790 	if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) != 0) {
12791 		FREE_LOCK(ump);
12792 		return;
12793 	}
12794 	ibp = inodedep->id_bmsafemap->sm_buf;
12795 	ibp = getdirtybuf(ibp, LOCK_PTR(ump), MNT_WAIT);
12796 	if (ibp == NULL) {
12797 		/*
12798 		 * If ibp came back as NULL, the dependency could have been
12799 		 * freed while we slept.  Look it up again, and check to see
12800 		 * that it has completed.
12801 		 */
12802 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0)
12803 			goto retry;
12804 		FREE_LOCK(ump);
12805 		return;
12806 	}
12807 	FREE_LOCK(ump);
12808 	if ((error = bwrite(ibp)) != 0)
12809 		softdep_error("softdep_update_inodeblock: bwrite", error);
12810 }
12811 
12812 /*
12813  * Merge the a new inode dependency list (such as id_newinoupdt) into an
12814  * old inode dependency list (such as id_inoupdt).
12815  */
12816 static void
12817 merge_inode_lists(newlisthead, oldlisthead)
12818 	struct allocdirectlst *newlisthead;
12819 	struct allocdirectlst *oldlisthead;
12820 {
12821 	struct allocdirect *listadp, *newadp;
12822 
12823 	newadp = TAILQ_FIRST(newlisthead);
12824 	if (newadp != NULL)
12825 		LOCK_OWNED(VFSTOUFS(newadp->ad_block.nb_list.wk_mp));
12826 	for (listadp = TAILQ_FIRST(oldlisthead); listadp && newadp;) {
12827 		if (listadp->ad_offset < newadp->ad_offset) {
12828 			listadp = TAILQ_NEXT(listadp, ad_next);
12829 			continue;
12830 		}
12831 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12832 		TAILQ_INSERT_BEFORE(listadp, newadp, ad_next);
12833 		if (listadp->ad_offset == newadp->ad_offset) {
12834 			allocdirect_merge(oldlisthead, newadp,
12835 			    listadp);
12836 			listadp = newadp;
12837 		}
12838 		newadp = TAILQ_FIRST(newlisthead);
12839 	}
12840 	while ((newadp = TAILQ_FIRST(newlisthead)) != NULL) {
12841 		TAILQ_REMOVE(newlisthead, newadp, ad_next);
12842 		TAILQ_INSERT_TAIL(oldlisthead, newadp, ad_next);
12843 	}
12844 }
12845 
12846 /*
12847  * If we are doing an fsync, then we must ensure that any directory
12848  * entries for the inode have been written after the inode gets to disk.
12849  */
12850 int
12851 softdep_fsync(vp)
12852 	struct vnode *vp;	/* the "in_core" copy of the inode */
12853 {
12854 	struct inodedep *inodedep;
12855 	struct pagedep *pagedep;
12856 	struct inoref *inoref;
12857 	struct ufsmount *ump;
12858 	struct worklist *wk;
12859 	struct diradd *dap;
12860 	struct mount *mp;
12861 	struct vnode *pvp;
12862 	struct inode *ip;
12863 	struct buf *bp;
12864 	struct fs *fs;
12865 	struct thread *td = curthread;
12866 	int error, flushparent, pagedep_new_block;
12867 	ino_t parentino;
12868 	ufs_lbn_t lbn;
12869 
12870 	ip = VTOI(vp);
12871 	mp = vp->v_mount;
12872 	ump = VFSTOUFS(mp);
12873 	fs = ump->um_fs;
12874 	if (MOUNTEDSOFTDEP(mp) == 0)
12875 		return (0);
12876 	ACQUIRE_LOCK(ump);
12877 restart:
12878 	if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0) {
12879 		FREE_LOCK(ump);
12880 		return (0);
12881 	}
12882 	TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
12883 		if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
12884 		    == DEPCOMPLETE) {
12885 			jwait(&inoref->if_list, MNT_WAIT);
12886 			goto restart;
12887 		}
12888 	}
12889 	if (!LIST_EMPTY(&inodedep->id_inowait) ||
12890 	    !TAILQ_EMPTY(&inodedep->id_extupdt) ||
12891 	    !TAILQ_EMPTY(&inodedep->id_newextupdt) ||
12892 	    !TAILQ_EMPTY(&inodedep->id_inoupdt) ||
12893 	    !TAILQ_EMPTY(&inodedep->id_newinoupdt))
12894 		panic("softdep_fsync: pending ops %p", inodedep);
12895 	for (error = 0, flushparent = 0; ; ) {
12896 		if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) == NULL)
12897 			break;
12898 		if (wk->wk_type != D_DIRADD)
12899 			panic("softdep_fsync: Unexpected type %s",
12900 			    TYPENAME(wk->wk_type));
12901 		dap = WK_DIRADD(wk);
12902 		/*
12903 		 * Flush our parent if this directory entry has a MKDIR_PARENT
12904 		 * dependency or is contained in a newly allocated block.
12905 		 */
12906 		if (dap->da_state & DIRCHG)
12907 			pagedep = dap->da_previous->dm_pagedep;
12908 		else
12909 			pagedep = dap->da_pagedep;
12910 		parentino = pagedep->pd_ino;
12911 		lbn = pagedep->pd_lbn;
12912 		if ((dap->da_state & (MKDIR_BODY | COMPLETE)) != COMPLETE)
12913 			panic("softdep_fsync: dirty");
12914 		if ((dap->da_state & MKDIR_PARENT) ||
12915 		    (pagedep->pd_state & NEWBLOCK))
12916 			flushparent = 1;
12917 		else
12918 			flushparent = 0;
12919 		/*
12920 		 * If we are being fsync'ed as part of vgone'ing this vnode,
12921 		 * then we will not be able to release and recover the
12922 		 * vnode below, so we just have to give up on writing its
12923 		 * directory entry out. It will eventually be written, just
12924 		 * not now, but then the user was not asking to have it
12925 		 * written, so we are not breaking any promises.
12926 		 */
12927 		if (VN_IS_DOOMED(vp))
12928 			break;
12929 		/*
12930 		 * We prevent deadlock by always fetching inodes from the
12931 		 * root, moving down the directory tree. Thus, when fetching
12932 		 * our parent directory, we first try to get the lock. If
12933 		 * that fails, we must unlock ourselves before requesting
12934 		 * the lock on our parent. See the comment in ufs_lookup
12935 		 * for details on possible races.
12936 		 */
12937 		FREE_LOCK(ump);
12938 		error = get_parent_vp(vp, mp, parentino, NULL, NULL, NULL,
12939 		    &pvp);
12940 		if (error == ERELOOKUP)
12941 			error = 0;
12942 		if (error != 0)
12943 			return (error);
12944 		/*
12945 		 * All MKDIR_PARENT dependencies and all the NEWBLOCK pagedeps
12946 		 * that are contained in direct blocks will be resolved by
12947 		 * doing a ffs_update. Pagedeps contained in indirect blocks
12948 		 * may require a complete sync'ing of the directory. So, we
12949 		 * try the cheap and fast ffs_update first, and if that fails,
12950 		 * then we do the slower ffs_syncvnode of the directory.
12951 		 */
12952 		if (flushparent) {
12953 			int locked;
12954 
12955 			if ((error = ffs_update(pvp, 1)) != 0) {
12956 				vput(pvp);
12957 				return (error);
12958 			}
12959 			ACQUIRE_LOCK(ump);
12960 			locked = 1;
12961 			if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) != 0) {
12962 				if ((wk = LIST_FIRST(&inodedep->id_pendinghd)) != NULL) {
12963 					if (wk->wk_type != D_DIRADD)
12964 						panic("softdep_fsync: Unexpected type %s",
12965 						      TYPENAME(wk->wk_type));
12966 					dap = WK_DIRADD(wk);
12967 					if (dap->da_state & DIRCHG)
12968 						pagedep = dap->da_previous->dm_pagedep;
12969 					else
12970 						pagedep = dap->da_pagedep;
12971 					pagedep_new_block = pagedep->pd_state & NEWBLOCK;
12972 					FREE_LOCK(ump);
12973 					locked = 0;
12974 					if (pagedep_new_block && (error =
12975 					    ffs_syncvnode(pvp, MNT_WAIT, 0))) {
12976 						vput(pvp);
12977 						return (error);
12978 					}
12979 				}
12980 			}
12981 			if (locked)
12982 				FREE_LOCK(ump);
12983 		}
12984 		/*
12985 		 * Flush directory page containing the inode's name.
12986 		 */
12987 		error = bread(pvp, lbn, blksize(fs, VTOI(pvp), lbn), td->td_ucred,
12988 		    &bp);
12989 		if (error == 0)
12990 			error = bwrite(bp);
12991 		else
12992 			brelse(bp);
12993 		vput(pvp);
12994 		if (!ffs_fsfail_cleanup(ump, error))
12995 			return (error);
12996 		ACQUIRE_LOCK(ump);
12997 		if (inodedep_lookup(mp, ip->i_number, 0, &inodedep) == 0)
12998 			break;
12999 	}
13000 	FREE_LOCK(ump);
13001 	return (0);
13002 }
13003 
13004 /*
13005  * Flush all the dirty bitmaps associated with the block device
13006  * before flushing the rest of the dirty blocks so as to reduce
13007  * the number of dependencies that will have to be rolled back.
13008  *
13009  * XXX Unused?
13010  */
13011 void
13012 softdep_fsync_mountdev(vp)
13013 	struct vnode *vp;
13014 {
13015 	struct buf *bp, *nbp;
13016 	struct worklist *wk;
13017 	struct bufobj *bo;
13018 
13019 	if (!vn_isdisk(vp))
13020 		panic("softdep_fsync_mountdev: vnode not a disk");
13021 	bo = &vp->v_bufobj;
13022 restart:
13023 	BO_LOCK(bo);
13024 	TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
13025 		/*
13026 		 * If it is already scheduled, skip to the next buffer.
13027 		 */
13028 		if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL))
13029 			continue;
13030 
13031 		if ((bp->b_flags & B_DELWRI) == 0)
13032 			panic("softdep_fsync_mountdev: not dirty");
13033 		/*
13034 		 * We are only interested in bitmaps with outstanding
13035 		 * dependencies.
13036 		 */
13037 		if ((wk = LIST_FIRST(&bp->b_dep)) == NULL ||
13038 		    wk->wk_type != D_BMSAFEMAP ||
13039 		    (bp->b_vflags & BV_BKGRDINPROG)) {
13040 			BUF_UNLOCK(bp);
13041 			continue;
13042 		}
13043 		BO_UNLOCK(bo);
13044 		bremfree(bp);
13045 		(void) bawrite(bp);
13046 		goto restart;
13047 	}
13048 	drain_output(vp);
13049 	BO_UNLOCK(bo);
13050 }
13051 
13052 /*
13053  * Sync all cylinder groups that were dirty at the time this function is
13054  * called.  Newly dirtied cgs will be inserted before the sentinel.  This
13055  * is used to flush freedep activity that may be holding up writes to a
13056  * indirect block.
13057  */
13058 static int
13059 sync_cgs(mp, waitfor)
13060 	struct mount *mp;
13061 	int waitfor;
13062 {
13063 	struct bmsafemap *bmsafemap;
13064 	struct bmsafemap *sentinel;
13065 	struct ufsmount *ump;
13066 	struct buf *bp;
13067 	int error;
13068 
13069 	sentinel = malloc(sizeof(*sentinel), M_BMSAFEMAP, M_ZERO | M_WAITOK);
13070 	sentinel->sm_cg = -1;
13071 	ump = VFSTOUFS(mp);
13072 	error = 0;
13073 	ACQUIRE_LOCK(ump);
13074 	LIST_INSERT_HEAD(&ump->softdep_dirtycg, sentinel, sm_next);
13075 	for (bmsafemap = LIST_NEXT(sentinel, sm_next); bmsafemap != NULL;
13076 	    bmsafemap = LIST_NEXT(sentinel, sm_next)) {
13077 		/* Skip sentinels and cgs with no work to release. */
13078 		if (bmsafemap->sm_cg == -1 ||
13079 		    (LIST_EMPTY(&bmsafemap->sm_freehd) &&
13080 		    LIST_EMPTY(&bmsafemap->sm_freewr))) {
13081 			LIST_REMOVE(sentinel, sm_next);
13082 			LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13083 			continue;
13084 		}
13085 		/*
13086 		 * If we don't get the lock and we're waiting try again, if
13087 		 * not move on to the next buf and try to sync it.
13088 		 */
13089 		bp = getdirtybuf(bmsafemap->sm_buf, LOCK_PTR(ump), waitfor);
13090 		if (bp == NULL && waitfor == MNT_WAIT)
13091 			continue;
13092 		LIST_REMOVE(sentinel, sm_next);
13093 		LIST_INSERT_AFTER(bmsafemap, sentinel, sm_next);
13094 		if (bp == NULL)
13095 			continue;
13096 		FREE_LOCK(ump);
13097 		if (waitfor == MNT_NOWAIT)
13098 			bawrite(bp);
13099 		else
13100 			error = bwrite(bp);
13101 		ACQUIRE_LOCK(ump);
13102 		if (error)
13103 			break;
13104 	}
13105 	LIST_REMOVE(sentinel, sm_next);
13106 	FREE_LOCK(ump);
13107 	free(sentinel, M_BMSAFEMAP);
13108 	return (error);
13109 }
13110 
13111 /*
13112  * This routine is called when we are trying to synchronously flush a
13113  * file. This routine must eliminate any filesystem metadata dependencies
13114  * so that the syncing routine can succeed.
13115  */
13116 int
13117 softdep_sync_metadata(struct vnode *vp)
13118 {
13119 	struct inode *ip;
13120 	int error;
13121 
13122 	ip = VTOI(vp);
13123 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13124 	    ("softdep_sync_metadata called on non-softdep filesystem"));
13125 	/*
13126 	 * Ensure that any direct block dependencies have been cleared,
13127 	 * truncations are started, and inode references are journaled.
13128 	 */
13129 	ACQUIRE_LOCK(VFSTOUFS(vp->v_mount));
13130 	/*
13131 	 * Write all journal records to prevent rollbacks on devvp.
13132 	 */
13133 	if (vp->v_type == VCHR)
13134 		softdep_flushjournal(vp->v_mount);
13135 	error = flush_inodedep_deps(vp, vp->v_mount, ip->i_number);
13136 	/*
13137 	 * Ensure that all truncates are written so we won't find deps on
13138 	 * indirect blocks.
13139 	 */
13140 	process_truncates(vp);
13141 	FREE_LOCK(VFSTOUFS(vp->v_mount));
13142 
13143 	return (error);
13144 }
13145 
13146 /*
13147  * This routine is called when we are attempting to sync a buf with
13148  * dependencies.  If waitfor is MNT_NOWAIT it attempts to schedule any
13149  * other IO it can but returns EBUSY if the buffer is not yet able to
13150  * be written.  Dependencies which will not cause rollbacks will always
13151  * return 0.
13152  */
13153 int
13154 softdep_sync_buf(struct vnode *vp, struct buf *bp, int waitfor)
13155 {
13156 	struct indirdep *indirdep;
13157 	struct pagedep *pagedep;
13158 	struct allocindir *aip;
13159 	struct newblk *newblk;
13160 	struct ufsmount *ump;
13161 	struct buf *nbp;
13162 	struct worklist *wk;
13163 	int i, error;
13164 
13165 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13166 	    ("softdep_sync_buf called on non-softdep filesystem"));
13167 	/*
13168 	 * For VCHR we just don't want to force flush any dependencies that
13169 	 * will cause rollbacks.
13170 	 */
13171 	if (vp->v_type == VCHR) {
13172 		if (waitfor == MNT_NOWAIT && softdep_count_dependencies(bp, 0))
13173 			return (EBUSY);
13174 		return (0);
13175 	}
13176 	ump = VFSTOUFS(vp->v_mount);
13177 	ACQUIRE_LOCK(ump);
13178 	/*
13179 	 * As we hold the buffer locked, none of its dependencies
13180 	 * will disappear.
13181 	 */
13182 	error = 0;
13183 top:
13184 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
13185 		switch (wk->wk_type) {
13186 		case D_ALLOCDIRECT:
13187 		case D_ALLOCINDIR:
13188 			newblk = WK_NEWBLK(wk);
13189 			if (newblk->nb_jnewblk != NULL) {
13190 				if (waitfor == MNT_NOWAIT) {
13191 					error = EBUSY;
13192 					goto out_unlock;
13193 				}
13194 				jwait(&newblk->nb_jnewblk->jn_list, waitfor);
13195 				goto top;
13196 			}
13197 			if (newblk->nb_state & DEPCOMPLETE ||
13198 			    waitfor == MNT_NOWAIT)
13199 				continue;
13200 			nbp = newblk->nb_bmsafemap->sm_buf;
13201 			nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13202 			if (nbp == NULL)
13203 				goto top;
13204 			FREE_LOCK(ump);
13205 			if ((error = bwrite(nbp)) != 0)
13206 				goto out;
13207 			ACQUIRE_LOCK(ump);
13208 			continue;
13209 
13210 		case D_INDIRDEP:
13211 			indirdep = WK_INDIRDEP(wk);
13212 			if (waitfor == MNT_NOWAIT) {
13213 				if (!TAILQ_EMPTY(&indirdep->ir_trunc) ||
13214 				    !LIST_EMPTY(&indirdep->ir_deplisthd)) {
13215 					error = EBUSY;
13216 					goto out_unlock;
13217 				}
13218 			}
13219 			if (!TAILQ_EMPTY(&indirdep->ir_trunc))
13220 				panic("softdep_sync_buf: truncation pending.");
13221 		restart:
13222 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
13223 				newblk = (struct newblk *)aip;
13224 				if (newblk->nb_jnewblk != NULL) {
13225 					jwait(&newblk->nb_jnewblk->jn_list,
13226 					    waitfor);
13227 					goto restart;
13228 				}
13229 				if (newblk->nb_state & DEPCOMPLETE)
13230 					continue;
13231 				nbp = newblk->nb_bmsafemap->sm_buf;
13232 				nbp = getdirtybuf(nbp, LOCK_PTR(ump), waitfor);
13233 				if (nbp == NULL)
13234 					goto restart;
13235 				FREE_LOCK(ump);
13236 				if ((error = bwrite(nbp)) != 0)
13237 					goto out;
13238 				ACQUIRE_LOCK(ump);
13239 				goto restart;
13240 			}
13241 			continue;
13242 
13243 		case D_PAGEDEP:
13244 			/*
13245 			 * Only flush directory entries in synchronous passes.
13246 			 */
13247 			if (waitfor != MNT_WAIT) {
13248 				error = EBUSY;
13249 				goto out_unlock;
13250 			}
13251 			/*
13252 			 * While syncing snapshots, we must allow recursive
13253 			 * lookups.
13254 			 */
13255 			BUF_AREC(bp);
13256 			/*
13257 			 * We are trying to sync a directory that may
13258 			 * have dependencies on both its own metadata
13259 			 * and/or dependencies on the inodes of any
13260 			 * recently allocated files. We walk its diradd
13261 			 * lists pushing out the associated inode.
13262 			 */
13263 			pagedep = WK_PAGEDEP(wk);
13264 			for (i = 0; i < DAHASHSZ; i++) {
13265 				if (LIST_FIRST(&pagedep->pd_diraddhd[i]) == 0)
13266 					continue;
13267 				error = flush_pagedep_deps(vp, wk->wk_mp,
13268 				    &pagedep->pd_diraddhd[i], bp);
13269 				if (error != 0) {
13270 					if (error != ERELOOKUP)
13271 						BUF_NOREC(bp);
13272 					goto out_unlock;
13273 				}
13274 			}
13275 			BUF_NOREC(bp);
13276 			continue;
13277 
13278 		case D_FREEWORK:
13279 		case D_FREEDEP:
13280 		case D_JSEGDEP:
13281 		case D_JNEWBLK:
13282 			continue;
13283 
13284 		default:
13285 			panic("softdep_sync_buf: Unknown type %s",
13286 			    TYPENAME(wk->wk_type));
13287 			/* NOTREACHED */
13288 		}
13289 	}
13290 out_unlock:
13291 	FREE_LOCK(ump);
13292 out:
13293 	return (error);
13294 }
13295 
13296 /*
13297  * Flush the dependencies associated with an inodedep.
13298  */
13299 static int
13300 flush_inodedep_deps(vp, mp, ino)
13301 	struct vnode *vp;
13302 	struct mount *mp;
13303 	ino_t ino;
13304 {
13305 	struct inodedep *inodedep;
13306 	struct inoref *inoref;
13307 	struct ufsmount *ump;
13308 	int error, waitfor;
13309 
13310 	/*
13311 	 * This work is done in two passes. The first pass grabs most
13312 	 * of the buffers and begins asynchronously writing them. The
13313 	 * only way to wait for these asynchronous writes is to sleep
13314 	 * on the filesystem vnode which may stay busy for a long time
13315 	 * if the filesystem is active. So, instead, we make a second
13316 	 * pass over the dependencies blocking on each write. In the
13317 	 * usual case we will be blocking against a write that we
13318 	 * initiated, so when it is done the dependency will have been
13319 	 * resolved. Thus the second pass is expected to end quickly.
13320 	 * We give a brief window at the top of the loop to allow
13321 	 * any pending I/O to complete.
13322 	 */
13323 	ump = VFSTOUFS(mp);
13324 	LOCK_OWNED(ump);
13325 	for (error = 0, waitfor = MNT_NOWAIT; ; ) {
13326 		if (error)
13327 			return (error);
13328 		FREE_LOCK(ump);
13329 		ACQUIRE_LOCK(ump);
13330 restart:
13331 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
13332 			return (0);
13333 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13334 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13335 			    == DEPCOMPLETE) {
13336 				jwait(&inoref->if_list, MNT_WAIT);
13337 				goto restart;
13338 			}
13339 		}
13340 		if (flush_deplist(&inodedep->id_inoupdt, waitfor, &error) ||
13341 		    flush_deplist(&inodedep->id_newinoupdt, waitfor, &error) ||
13342 		    flush_deplist(&inodedep->id_extupdt, waitfor, &error) ||
13343 		    flush_deplist(&inodedep->id_newextupdt, waitfor, &error))
13344 			continue;
13345 		/*
13346 		 * If pass2, we are done, otherwise do pass 2.
13347 		 */
13348 		if (waitfor == MNT_WAIT)
13349 			break;
13350 		waitfor = MNT_WAIT;
13351 	}
13352 	/*
13353 	 * Try freeing inodedep in case all dependencies have been removed.
13354 	 */
13355 	if (inodedep_lookup(mp, ino, 0, &inodedep) != 0)
13356 		(void) free_inodedep(inodedep);
13357 	return (0);
13358 }
13359 
13360 /*
13361  * Flush an inode dependency list.
13362  */
13363 static int
13364 flush_deplist(listhead, waitfor, errorp)
13365 	struct allocdirectlst *listhead;
13366 	int waitfor;
13367 	int *errorp;
13368 {
13369 	struct allocdirect *adp;
13370 	struct newblk *newblk;
13371 	struct ufsmount *ump;
13372 	struct buf *bp;
13373 
13374 	if ((adp = TAILQ_FIRST(listhead)) == NULL)
13375 		return (0);
13376 	ump = VFSTOUFS(adp->ad_list.wk_mp);
13377 	LOCK_OWNED(ump);
13378 	TAILQ_FOREACH(adp, listhead, ad_next) {
13379 		newblk = (struct newblk *)adp;
13380 		if (newblk->nb_jnewblk != NULL) {
13381 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13382 			return (1);
13383 		}
13384 		if (newblk->nb_state & DEPCOMPLETE)
13385 			continue;
13386 		bp = newblk->nb_bmsafemap->sm_buf;
13387 		bp = getdirtybuf(bp, LOCK_PTR(ump), waitfor);
13388 		if (bp == NULL) {
13389 			if (waitfor == MNT_NOWAIT)
13390 				continue;
13391 			return (1);
13392 		}
13393 		FREE_LOCK(ump);
13394 		if (waitfor == MNT_NOWAIT)
13395 			bawrite(bp);
13396 		else
13397 			*errorp = bwrite(bp);
13398 		ACQUIRE_LOCK(ump);
13399 		return (1);
13400 	}
13401 	return (0);
13402 }
13403 
13404 /*
13405  * Flush dependencies associated with an allocdirect block.
13406  */
13407 static int
13408 flush_newblk_dep(vp, mp, lbn)
13409 	struct vnode *vp;
13410 	struct mount *mp;
13411 	ufs_lbn_t lbn;
13412 {
13413 	struct newblk *newblk;
13414 	struct ufsmount *ump;
13415 	struct bufobj *bo;
13416 	struct inode *ip;
13417 	struct buf *bp;
13418 	ufs2_daddr_t blkno;
13419 	int error;
13420 
13421 	error = 0;
13422 	bo = &vp->v_bufobj;
13423 	ip = VTOI(vp);
13424 	blkno = DIP(ip, i_db[lbn]);
13425 	if (blkno == 0)
13426 		panic("flush_newblk_dep: Missing block");
13427 	ump = VFSTOUFS(mp);
13428 	ACQUIRE_LOCK(ump);
13429 	/*
13430 	 * Loop until all dependencies related to this block are satisfied.
13431 	 * We must be careful to restart after each sleep in case a write
13432 	 * completes some part of this process for us.
13433 	 */
13434 	for (;;) {
13435 		if (newblk_lookup(mp, blkno, 0, &newblk) == 0) {
13436 			FREE_LOCK(ump);
13437 			break;
13438 		}
13439 		if (newblk->nb_list.wk_type != D_ALLOCDIRECT)
13440 			panic("flush_newblk_dep: Bad newblk %p", newblk);
13441 		/*
13442 		 * Flush the journal.
13443 		 */
13444 		if (newblk->nb_jnewblk != NULL) {
13445 			jwait(&newblk->nb_jnewblk->jn_list, MNT_WAIT);
13446 			continue;
13447 		}
13448 		/*
13449 		 * Write the bitmap dependency.
13450 		 */
13451 		if ((newblk->nb_state & DEPCOMPLETE) == 0) {
13452 			bp = newblk->nb_bmsafemap->sm_buf;
13453 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13454 			if (bp == NULL)
13455 				continue;
13456 			FREE_LOCK(ump);
13457 			error = bwrite(bp);
13458 			if (error)
13459 				break;
13460 			ACQUIRE_LOCK(ump);
13461 			continue;
13462 		}
13463 		/*
13464 		 * Write the buffer.
13465 		 */
13466 		FREE_LOCK(ump);
13467 		BO_LOCK(bo);
13468 		bp = gbincore(bo, lbn);
13469 		if (bp != NULL) {
13470 			error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_SLEEPFAIL |
13471 			    LK_INTERLOCK, BO_LOCKPTR(bo));
13472 			if (error == ENOLCK) {
13473 				ACQUIRE_LOCK(ump);
13474 				error = 0;
13475 				continue; /* Slept, retry */
13476 			}
13477 			if (error != 0)
13478 				break;	/* Failed */
13479 			if (bp->b_flags & B_DELWRI) {
13480 				bremfree(bp);
13481 				error = bwrite(bp);
13482 				if (error)
13483 					break;
13484 			} else
13485 				BUF_UNLOCK(bp);
13486 		} else
13487 			BO_UNLOCK(bo);
13488 		/*
13489 		 * We have to wait for the direct pointers to
13490 		 * point at the newdirblk before the dependency
13491 		 * will go away.
13492 		 */
13493 		error = ffs_update(vp, 1);
13494 		if (error)
13495 			break;
13496 		ACQUIRE_LOCK(ump);
13497 	}
13498 	return (error);
13499 }
13500 
13501 /*
13502  * Eliminate a pagedep dependency by flushing out all its diradd dependencies.
13503  */
13504 static int
13505 flush_pagedep_deps(pvp, mp, diraddhdp, locked_bp)
13506 	struct vnode *pvp;
13507 	struct mount *mp;
13508 	struct diraddhd *diraddhdp;
13509 	struct buf *locked_bp;
13510 {
13511 	struct inodedep *inodedep;
13512 	struct inoref *inoref;
13513 	struct ufsmount *ump;
13514 	struct diradd *dap;
13515 	struct vnode *vp;
13516 	int error = 0;
13517 	struct buf *bp;
13518 	ino_t inum;
13519 	struct diraddhd unfinished;
13520 
13521 	LIST_INIT(&unfinished);
13522 	ump = VFSTOUFS(mp);
13523 	LOCK_OWNED(ump);
13524 restart:
13525 	while ((dap = LIST_FIRST(diraddhdp)) != NULL) {
13526 		/*
13527 		 * Flush ourselves if this directory entry
13528 		 * has a MKDIR_PARENT dependency.
13529 		 */
13530 		if (dap->da_state & MKDIR_PARENT) {
13531 			FREE_LOCK(ump);
13532 			if ((error = ffs_update(pvp, 1)) != 0)
13533 				break;
13534 			ACQUIRE_LOCK(ump);
13535 			/*
13536 			 * If that cleared dependencies, go on to next.
13537 			 */
13538 			if (dap != LIST_FIRST(diraddhdp))
13539 				continue;
13540 			/*
13541 			 * All MKDIR_PARENT dependencies and all the
13542 			 * NEWBLOCK pagedeps that are contained in direct
13543 			 * blocks were resolved by doing above ffs_update.
13544 			 * Pagedeps contained in indirect blocks may
13545 			 * require a complete sync'ing of the directory.
13546 			 * We are in the midst of doing a complete sync,
13547 			 * so if they are not resolved in this pass we
13548 			 * defer them for now as they will be sync'ed by
13549 			 * our caller shortly.
13550 			 */
13551 			LIST_REMOVE(dap, da_pdlist);
13552 			LIST_INSERT_HEAD(&unfinished, dap, da_pdlist);
13553 			continue;
13554 		}
13555 		/*
13556 		 * A newly allocated directory must have its "." and
13557 		 * ".." entries written out before its name can be
13558 		 * committed in its parent.
13559 		 */
13560 		inum = dap->da_newinum;
13561 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13562 			panic("flush_pagedep_deps: lost inode1");
13563 		/*
13564 		 * Wait for any pending journal adds to complete so we don't
13565 		 * cause rollbacks while syncing.
13566 		 */
13567 		TAILQ_FOREACH(inoref, &inodedep->id_inoreflst, if_deps) {
13568 			if ((inoref->if_state & (DEPCOMPLETE | GOINGAWAY))
13569 			    == DEPCOMPLETE) {
13570 				jwait(&inoref->if_list, MNT_WAIT);
13571 				goto restart;
13572 			}
13573 		}
13574 		if (dap->da_state & MKDIR_BODY) {
13575 			FREE_LOCK(ump);
13576 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13577 			    diraddhdp, &unfinished, &vp);
13578 			if (error != 0)
13579 				break;
13580 			error = flush_newblk_dep(vp, mp, 0);
13581 			/*
13582 			 * If we still have the dependency we might need to
13583 			 * update the vnode to sync the new link count to
13584 			 * disk.
13585 			 */
13586 			if (error == 0 && dap == LIST_FIRST(diraddhdp))
13587 				error = ffs_update(vp, 1);
13588 			vput(vp);
13589 			if (error != 0)
13590 				break;
13591 			ACQUIRE_LOCK(ump);
13592 			/*
13593 			 * If that cleared dependencies, go on to next.
13594 			 */
13595 			if (dap != LIST_FIRST(diraddhdp))
13596 				continue;
13597 			if (dap->da_state & MKDIR_BODY) {
13598 				inodedep_lookup(UFSTOVFS(ump), inum, 0,
13599 				    &inodedep);
13600 				panic("flush_pagedep_deps: MKDIR_BODY "
13601 				    "inodedep %p dap %p vp %p",
13602 				    inodedep, dap, vp);
13603 			}
13604 		}
13605 		/*
13606 		 * Flush the inode on which the directory entry depends.
13607 		 * Having accounted for MKDIR_PARENT and MKDIR_BODY above,
13608 		 * the only remaining dependency is that the updated inode
13609 		 * count must get pushed to disk. The inode has already
13610 		 * been pushed into its inode buffer (via VOP_UPDATE) at
13611 		 * the time of the reference count change. So we need only
13612 		 * locate that buffer, ensure that there will be no rollback
13613 		 * caused by a bitmap dependency, then write the inode buffer.
13614 		 */
13615 retry:
13616 		if (inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep) == 0)
13617 			panic("flush_pagedep_deps: lost inode");
13618 		/*
13619 		 * If the inode still has bitmap dependencies,
13620 		 * push them to disk.
13621 		 */
13622 		if ((inodedep->id_state & (DEPCOMPLETE | GOINGAWAY)) == 0) {
13623 			bp = inodedep->id_bmsafemap->sm_buf;
13624 			bp = getdirtybuf(bp, LOCK_PTR(ump), MNT_WAIT);
13625 			if (bp == NULL)
13626 				goto retry;
13627 			FREE_LOCK(ump);
13628 			if ((error = bwrite(bp)) != 0)
13629 				break;
13630 			ACQUIRE_LOCK(ump);
13631 			if (dap != LIST_FIRST(diraddhdp))
13632 				continue;
13633 		}
13634 		/*
13635 		 * If the inode is still sitting in a buffer waiting
13636 		 * to be written or waiting for the link count to be
13637 		 * adjusted update it here to flush it to disk.
13638 		 */
13639 		if (dap == LIST_FIRST(diraddhdp)) {
13640 			FREE_LOCK(ump);
13641 			error = get_parent_vp(pvp, mp, inum, locked_bp,
13642 			    diraddhdp, &unfinished, &vp);
13643 			if (error != 0)
13644 				break;
13645 			error = ffs_update(vp, 1);
13646 			vput(vp);
13647 			if (error)
13648 				break;
13649 			ACQUIRE_LOCK(ump);
13650 		}
13651 		/*
13652 		 * If we have failed to get rid of all the dependencies
13653 		 * then something is seriously wrong.
13654 		 */
13655 		if (dap == LIST_FIRST(diraddhdp)) {
13656 			inodedep_lookup(UFSTOVFS(ump), inum, 0, &inodedep);
13657 			panic("flush_pagedep_deps: failed to flush "
13658 			    "inodedep %p ino %ju dap %p",
13659 			    inodedep, (uintmax_t)inum, dap);
13660 		}
13661 	}
13662 	if (error)
13663 		ACQUIRE_LOCK(ump);
13664 	while ((dap = LIST_FIRST(&unfinished)) != NULL) {
13665 		LIST_REMOVE(dap, da_pdlist);
13666 		LIST_INSERT_HEAD(diraddhdp, dap, da_pdlist);
13667 	}
13668 	return (error);
13669 }
13670 
13671 /*
13672  * A large burst of file addition or deletion activity can drive the
13673  * memory load excessively high. First attempt to slow things down
13674  * using the techniques below. If that fails, this routine requests
13675  * the offending operations to fall back to running synchronously
13676  * until the memory load returns to a reasonable level.
13677  */
13678 int
13679 softdep_slowdown(vp)
13680 	struct vnode *vp;
13681 {
13682 	struct ufsmount *ump;
13683 	int jlow;
13684 	int max_softdeps_hard;
13685 
13686 	KASSERT(MOUNTEDSOFTDEP(vp->v_mount) != 0,
13687 	    ("softdep_slowdown called on non-softdep filesystem"));
13688 	ump = VFSTOUFS(vp->v_mount);
13689 	ACQUIRE_LOCK(ump);
13690 	jlow = 0;
13691 	/*
13692 	 * Check for journal space if needed.
13693 	 */
13694 	if (DOINGSUJ(vp)) {
13695 		if (journal_space(ump, 0) == 0)
13696 			jlow = 1;
13697 	}
13698 	/*
13699 	 * If the system is under its limits and our filesystem is
13700 	 * not responsible for more than our share of the usage and
13701 	 * we are not low on journal space, then no need to slow down.
13702 	 */
13703 	max_softdeps_hard = max_softdeps * 11 / 10;
13704 	if (dep_current[D_DIRREM] < max_softdeps_hard / 2 &&
13705 	    dep_current[D_INODEDEP] < max_softdeps_hard &&
13706 	    dep_current[D_INDIRDEP] < max_softdeps_hard / 1000 &&
13707 	    dep_current[D_FREEBLKS] < max_softdeps_hard && jlow == 0 &&
13708 	    ump->softdep_curdeps[D_DIRREM] <
13709 	    (max_softdeps_hard / 2) / stat_flush_threads &&
13710 	    ump->softdep_curdeps[D_INODEDEP] <
13711 	    max_softdeps_hard / stat_flush_threads &&
13712 	    ump->softdep_curdeps[D_INDIRDEP] <
13713 	    (max_softdeps_hard / 1000) / stat_flush_threads &&
13714 	    ump->softdep_curdeps[D_FREEBLKS] <
13715 	    max_softdeps_hard / stat_flush_threads) {
13716 		FREE_LOCK(ump);
13717   		return (0);
13718 	}
13719 	/*
13720 	 * If the journal is low or our filesystem is over its limit
13721 	 * then speedup the cleanup.
13722 	 */
13723 	if (ump->softdep_curdeps[D_INDIRDEP] <
13724 	    (max_softdeps_hard / 1000) / stat_flush_threads || jlow)
13725 		softdep_speedup(ump);
13726 	stat_sync_limit_hit += 1;
13727 	FREE_LOCK(ump);
13728 	/*
13729 	 * We only slow down the rate at which new dependencies are
13730 	 * generated if we are not using journaling. With journaling,
13731 	 * the cleanup should always be sufficient to keep things
13732 	 * under control.
13733 	 */
13734 	if (DOINGSUJ(vp))
13735 		return (0);
13736 	return (1);
13737 }
13738 
13739 /*
13740  * Called by the allocation routines when they are about to fail
13741  * in the hope that we can free up the requested resource (inodes
13742  * or disk space).
13743  *
13744  * First check to see if the work list has anything on it. If it has,
13745  * clean up entries until we successfully free the requested resource.
13746  * Because this process holds inodes locked, we cannot handle any remove
13747  * requests that might block on a locked inode as that could lead to
13748  * deadlock. If the worklist yields none of the requested resource,
13749  * start syncing out vnodes to free up the needed space.
13750  */
13751 int
13752 softdep_request_cleanup(fs, vp, cred, resource)
13753 	struct fs *fs;
13754 	struct vnode *vp;
13755 	struct ucred *cred;
13756 	int resource;
13757 {
13758 	struct ufsmount *ump;
13759 	struct mount *mp;
13760 	long starttime;
13761 	ufs2_daddr_t needed;
13762 	int error, failed_vnode;
13763 
13764 	/*
13765 	 * If we are being called because of a process doing a
13766 	 * copy-on-write, then it is not safe to process any
13767 	 * worklist items as we will recurse into the copyonwrite
13768 	 * routine.  This will result in an incoherent snapshot.
13769 	 * If the vnode that we hold is a snapshot, we must avoid
13770 	 * handling other resources that could cause deadlock.
13771 	 */
13772 	if ((curthread->td_pflags & TDP_COWINPROGRESS) || IS_SNAPSHOT(VTOI(vp)))
13773 		return (0);
13774 
13775 	if (resource == FLUSH_BLOCKS_WAIT)
13776 		stat_cleanup_blkrequests += 1;
13777 	else
13778 		stat_cleanup_inorequests += 1;
13779 
13780 	mp = vp->v_mount;
13781 	ump = VFSTOUFS(mp);
13782 	mtx_assert(UFS_MTX(ump), MA_OWNED);
13783 	UFS_UNLOCK(ump);
13784 	error = ffs_update(vp, 1);
13785 	if (error != 0 || MOUNTEDSOFTDEP(mp) == 0) {
13786 		UFS_LOCK(ump);
13787 		return (0);
13788 	}
13789 	/*
13790 	 * If we are in need of resources, start by cleaning up
13791 	 * any block removals associated with our inode.
13792 	 */
13793 	ACQUIRE_LOCK(ump);
13794 	process_removes(vp);
13795 	process_truncates(vp);
13796 	FREE_LOCK(ump);
13797 	/*
13798 	 * Now clean up at least as many resources as we will need.
13799 	 *
13800 	 * When requested to clean up inodes, the number that are needed
13801 	 * is set by the number of simultaneous writers (mnt_writeopcount)
13802 	 * plus a bit of slop (2) in case some more writers show up while
13803 	 * we are cleaning.
13804 	 *
13805 	 * When requested to free up space, the amount of space that
13806 	 * we need is enough blocks to allocate a full-sized segment
13807 	 * (fs_contigsumsize). The number of such segments that will
13808 	 * be needed is set by the number of simultaneous writers
13809 	 * (mnt_writeopcount) plus a bit of slop (2) in case some more
13810 	 * writers show up while we are cleaning.
13811 	 *
13812 	 * Additionally, if we are unpriviledged and allocating space,
13813 	 * we need to ensure that we clean up enough blocks to get the
13814 	 * needed number of blocks over the threshold of the minimum
13815 	 * number of blocks required to be kept free by the filesystem
13816 	 * (fs_minfree).
13817 	 */
13818 	if (resource == FLUSH_INODES_WAIT) {
13819 		needed = vfs_mount_fetch_counter(vp->v_mount,
13820 		    MNT_COUNT_WRITEOPCOUNT) + 2;
13821 	} else if (resource == FLUSH_BLOCKS_WAIT) {
13822 		needed = (vfs_mount_fetch_counter(vp->v_mount,
13823 		    MNT_COUNT_WRITEOPCOUNT) + 2) * fs->fs_contigsumsize;
13824 		if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE))
13825 			needed += fragstoblks(fs,
13826 			    roundup((fs->fs_dsize * fs->fs_minfree / 100) -
13827 			    fs->fs_cstotal.cs_nffree, fs->fs_frag));
13828 	} else {
13829 		printf("softdep_request_cleanup: Unknown resource type %d\n",
13830 		    resource);
13831 		UFS_LOCK(ump);
13832 		return (0);
13833 	}
13834 	starttime = time_second;
13835 retry:
13836 	if (resource == FLUSH_BLOCKS_WAIT &&
13837 	    fs->fs_cstotal.cs_nbfree <= needed)
13838 		softdep_send_speedup(ump, needed * fs->fs_bsize,
13839 		    BIO_SPEEDUP_TRIM);
13840 	if ((resource == FLUSH_BLOCKS_WAIT && ump->softdep_on_worklist > 0 &&
13841 	    fs->fs_cstotal.cs_nbfree <= needed) ||
13842 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13843 	    fs->fs_cstotal.cs_nifree <= needed)) {
13844 		ACQUIRE_LOCK(ump);
13845 		if (ump->softdep_on_worklist > 0 &&
13846 		    process_worklist_item(UFSTOVFS(ump),
13847 		    ump->softdep_on_worklist, LK_NOWAIT) != 0)
13848 			stat_worklist_push += 1;
13849 		FREE_LOCK(ump);
13850 	}
13851 	/*
13852 	 * If we still need resources and there are no more worklist
13853 	 * entries to process to obtain them, we have to start flushing
13854 	 * the dirty vnodes to force the release of additional requests
13855 	 * to the worklist that we can then process to reap addition
13856 	 * resources. We walk the vnodes associated with the mount point
13857 	 * until we get the needed worklist requests that we can reap.
13858 	 *
13859 	 * If there are several threads all needing to clean the same
13860 	 * mount point, only one is allowed to walk the mount list.
13861 	 * When several threads all try to walk the same mount list,
13862 	 * they end up competing with each other and often end up in
13863 	 * livelock. This approach ensures that forward progress is
13864 	 * made at the cost of occational ENOSPC errors being returned
13865 	 * that might otherwise have been avoided.
13866 	 */
13867 	error = 1;
13868 	if ((resource == FLUSH_BLOCKS_WAIT &&
13869 	     fs->fs_cstotal.cs_nbfree <= needed) ||
13870 	    (resource == FLUSH_INODES_WAIT && fs->fs_pendinginodes > 0 &&
13871 	     fs->fs_cstotal.cs_nifree <= needed)) {
13872 		ACQUIRE_LOCK(ump);
13873 		if ((ump->um_softdep->sd_flags & FLUSH_RC_ACTIVE) == 0) {
13874 			ump->um_softdep->sd_flags |= FLUSH_RC_ACTIVE;
13875 			FREE_LOCK(ump);
13876 			failed_vnode = softdep_request_cleanup_flush(mp, ump);
13877 			ACQUIRE_LOCK(ump);
13878 			ump->um_softdep->sd_flags &= ~FLUSH_RC_ACTIVE;
13879 			FREE_LOCK(ump);
13880 			if (ump->softdep_on_worklist > 0) {
13881 				stat_cleanup_retries += 1;
13882 				if (!failed_vnode)
13883 					goto retry;
13884 			}
13885 		} else {
13886 			FREE_LOCK(ump);
13887 			error = 0;
13888 		}
13889 		stat_cleanup_failures += 1;
13890 	}
13891 	if (time_second - starttime > stat_cleanup_high_delay)
13892 		stat_cleanup_high_delay = time_second - starttime;
13893 	UFS_LOCK(ump);
13894 	return (error);
13895 }
13896 
13897 /*
13898  * Scan the vnodes for the specified mount point flushing out any
13899  * vnodes that can be locked without waiting. Finally, try to flush
13900  * the device associated with the mount point if it can be locked
13901  * without waiting.
13902  *
13903  * We return 0 if we were able to lock every vnode in our scan.
13904  * If we had to skip one or more vnodes, we return 1.
13905  */
13906 static int
13907 softdep_request_cleanup_flush(mp, ump)
13908 	struct mount *mp;
13909 	struct ufsmount *ump;
13910 {
13911 	struct thread *td;
13912 	struct vnode *lvp, *mvp;
13913 	int failed_vnode;
13914 
13915 	failed_vnode = 0;
13916 	td = curthread;
13917 	MNT_VNODE_FOREACH_ALL(lvp, mp, mvp) {
13918 		if (TAILQ_FIRST(&lvp->v_bufobj.bo_dirty.bv_hd) == 0) {
13919 			VI_UNLOCK(lvp);
13920 			continue;
13921 		}
13922 		if (vget(lvp, LK_EXCLUSIVE | LK_INTERLOCK | LK_NOWAIT) != 0) {
13923 			failed_vnode = 1;
13924 			continue;
13925 		}
13926 		if (lvp->v_vflag & VV_NOSYNC) {	/* unlinked */
13927 			vput(lvp);
13928 			continue;
13929 		}
13930 		(void) ffs_syncvnode(lvp, MNT_NOWAIT, 0);
13931 		vput(lvp);
13932 	}
13933 	lvp = ump->um_devvp;
13934 	if (vn_lock(lvp, LK_EXCLUSIVE | LK_NOWAIT) == 0) {
13935 		VOP_FSYNC(lvp, MNT_NOWAIT, td);
13936 		VOP_UNLOCK(lvp);
13937 	}
13938 	return (failed_vnode);
13939 }
13940 
13941 static bool
13942 softdep_excess_items(struct ufsmount *ump, int item)
13943 {
13944 
13945 	KASSERT(item >= 0 && item < D_LAST, ("item %d", item));
13946 	return (dep_current[item] > max_softdeps &&
13947 	    ump->softdep_curdeps[item] > max_softdeps /
13948 	    stat_flush_threads);
13949 }
13950 
13951 static void
13952 schedule_cleanup(struct mount *mp)
13953 {
13954 	struct ufsmount *ump;
13955 	struct thread *td;
13956 
13957 	ump = VFSTOUFS(mp);
13958 	LOCK_OWNED(ump);
13959 	FREE_LOCK(ump);
13960 	td = curthread;
13961 	if ((td->td_pflags & TDP_KTHREAD) != 0 &&
13962 	    (td->td_proc->p_flag2 & P2_AST_SU) == 0) {
13963 		/*
13964 		 * No ast is delivered to kernel threads, so nobody
13965 		 * would deref the mp.  Some kernel threads
13966 		 * explicitely check for AST, e.g. NFS daemon does
13967 		 * this in the serving loop.
13968 		 */
13969 		return;
13970 	}
13971 	if (td->td_su != NULL)
13972 		vfs_rel(td->td_su);
13973 	vfs_ref(mp);
13974 	td->td_su = mp;
13975 	thread_lock(td);
13976 	td->td_flags |= TDF_ASTPENDING;
13977 	thread_unlock(td);
13978 }
13979 
13980 static void
13981 softdep_ast_cleanup_proc(struct thread *td)
13982 {
13983 	struct mount *mp;
13984 	struct ufsmount *ump;
13985 	int error;
13986 	bool req;
13987 
13988 	while ((mp = td->td_su) != NULL) {
13989 		td->td_su = NULL;
13990 		error = vfs_busy(mp, MBF_NOWAIT);
13991 		vfs_rel(mp);
13992 		if (error != 0)
13993 			return;
13994 		if (ffs_own_mount(mp) && MOUNTEDSOFTDEP(mp)) {
13995 			ump = VFSTOUFS(mp);
13996 			for (;;) {
13997 				req = false;
13998 				ACQUIRE_LOCK(ump);
13999 				if (softdep_excess_items(ump, D_INODEDEP)) {
14000 					req = true;
14001 					request_cleanup(mp, FLUSH_INODES);
14002 				}
14003 				if (softdep_excess_items(ump, D_DIRREM)) {
14004 					req = true;
14005 					request_cleanup(mp, FLUSH_BLOCKS);
14006 				}
14007 				FREE_LOCK(ump);
14008 				if (softdep_excess_items(ump, D_NEWBLK) ||
14009 				    softdep_excess_items(ump, D_ALLOCDIRECT) ||
14010 				    softdep_excess_items(ump, D_ALLOCINDIR)) {
14011 					error = vn_start_write(NULL, &mp,
14012 					    V_WAIT);
14013 					if (error == 0) {
14014 						req = true;
14015 						VFS_SYNC(mp, MNT_WAIT);
14016 						vn_finished_write(mp);
14017 					}
14018 				}
14019 				if ((td->td_pflags & TDP_KTHREAD) != 0 || !req)
14020 					break;
14021 			}
14022 		}
14023 		vfs_unbusy(mp);
14024 	}
14025 	if ((mp = td->td_su) != NULL) {
14026 		td->td_su = NULL;
14027 		vfs_rel(mp);
14028 	}
14029 }
14030 
14031 /*
14032  * If memory utilization has gotten too high, deliberately slow things
14033  * down and speed up the I/O processing.
14034  */
14035 static int
14036 request_cleanup(mp, resource)
14037 	struct mount *mp;
14038 	int resource;
14039 {
14040 	struct thread *td = curthread;
14041 	struct ufsmount *ump;
14042 
14043 	ump = VFSTOUFS(mp);
14044 	LOCK_OWNED(ump);
14045 	/*
14046 	 * We never hold up the filesystem syncer or buf daemon.
14047 	 */
14048 	if (td->td_pflags & (TDP_SOFTDEP|TDP_NORUNNINGBUF))
14049 		return (0);
14050 	/*
14051 	 * First check to see if the work list has gotten backlogged.
14052 	 * If it has, co-opt this process to help clean up two entries.
14053 	 * Because this process may hold inodes locked, we cannot
14054 	 * handle any remove requests that might block on a locked
14055 	 * inode as that could lead to deadlock.  We set TDP_SOFTDEP
14056 	 * to avoid recursively processing the worklist.
14057 	 */
14058 	if (ump->softdep_on_worklist > max_softdeps / 10) {
14059 		td->td_pflags |= TDP_SOFTDEP;
14060 		process_worklist_item(mp, 2, LK_NOWAIT);
14061 		td->td_pflags &= ~TDP_SOFTDEP;
14062 		stat_worklist_push += 2;
14063 		return(1);
14064 	}
14065 	/*
14066 	 * Next, we attempt to speed up the syncer process. If that
14067 	 * is successful, then we allow the process to continue.
14068 	 */
14069 	if (softdep_speedup(ump) &&
14070 	    resource != FLUSH_BLOCKS_WAIT &&
14071 	    resource != FLUSH_INODES_WAIT)
14072 		return(0);
14073 	/*
14074 	 * If we are resource constrained on inode dependencies, try
14075 	 * flushing some dirty inodes. Otherwise, we are constrained
14076 	 * by file deletions, so try accelerating flushes of directories
14077 	 * with removal dependencies. We would like to do the cleanup
14078 	 * here, but we probably hold an inode locked at this point and
14079 	 * that might deadlock against one that we try to clean. So,
14080 	 * the best that we can do is request the syncer daemon to do
14081 	 * the cleanup for us.
14082 	 */
14083 	switch (resource) {
14084 	case FLUSH_INODES:
14085 	case FLUSH_INODES_WAIT:
14086 		ACQUIRE_GBLLOCK(&lk);
14087 		stat_ino_limit_push += 1;
14088 		req_clear_inodedeps += 1;
14089 		FREE_GBLLOCK(&lk);
14090 		stat_countp = &stat_ino_limit_hit;
14091 		break;
14092 
14093 	case FLUSH_BLOCKS:
14094 	case FLUSH_BLOCKS_WAIT:
14095 		ACQUIRE_GBLLOCK(&lk);
14096 		stat_blk_limit_push += 1;
14097 		req_clear_remove += 1;
14098 		FREE_GBLLOCK(&lk);
14099 		stat_countp = &stat_blk_limit_hit;
14100 		break;
14101 
14102 	default:
14103 		panic("request_cleanup: unknown type");
14104 	}
14105 	/*
14106 	 * Hopefully the syncer daemon will catch up and awaken us.
14107 	 * We wait at most tickdelay before proceeding in any case.
14108 	 */
14109 	ACQUIRE_GBLLOCK(&lk);
14110 	FREE_LOCK(ump);
14111 	proc_waiting += 1;
14112 	if (callout_pending(&softdep_callout) == FALSE)
14113 		callout_reset(&softdep_callout, tickdelay > 2 ? tickdelay : 2,
14114 		    pause_timer, 0);
14115 
14116 	if ((td->td_pflags & TDP_KTHREAD) == 0)
14117 		msleep((caddr_t)&proc_waiting, &lk, PPAUSE, "softupdate", 0);
14118 	proc_waiting -= 1;
14119 	FREE_GBLLOCK(&lk);
14120 	ACQUIRE_LOCK(ump);
14121 	return (1);
14122 }
14123 
14124 /*
14125  * Awaken processes pausing in request_cleanup and clear proc_waiting
14126  * to indicate that there is no longer a timer running. Pause_timer
14127  * will be called with the global softdep mutex (&lk) locked.
14128  */
14129 static void
14130 pause_timer(arg)
14131 	void *arg;
14132 {
14133 
14134 	GBLLOCK_OWNED(&lk);
14135 	/*
14136 	 * The callout_ API has acquired mtx and will hold it around this
14137 	 * function call.
14138 	 */
14139 	*stat_countp += proc_waiting;
14140 	wakeup(&proc_waiting);
14141 }
14142 
14143 /*
14144  * If requested, try removing inode or removal dependencies.
14145  */
14146 static void
14147 check_clear_deps(mp)
14148 	struct mount *mp;
14149 {
14150 	struct ufsmount *ump;
14151 	bool suj_susp;
14152 
14153 	/*
14154 	 * Tell the lower layers that any TRIM or WRITE transactions that have
14155 	 * been delayed for performance reasons should proceed to help alleviate
14156 	 * the shortage faster. The race between checking req_* and the softdep
14157 	 * mutex (lk) is fine since this is an advisory operation that at most
14158 	 * causes deferred work to be done sooner.
14159 	 */
14160 	ump = VFSTOUFS(mp);
14161 	suj_susp = MOUNTEDSUJ(mp) && ump->softdep_jblocks->jb_suspended;
14162 	if (req_clear_remove || req_clear_inodedeps || suj_susp) {
14163 		FREE_LOCK(ump);
14164 		softdep_send_speedup(ump, 0, BIO_SPEEDUP_TRIM | BIO_SPEEDUP_WRITE);
14165 		ACQUIRE_LOCK(ump);
14166 	}
14167 
14168 	/*
14169 	 * If we are suspended, it may be because of our using
14170 	 * too many inodedeps, so help clear them out.
14171 	 */
14172 	if (suj_susp)
14173 		clear_inodedeps(mp);
14174 
14175 	/*
14176 	 * General requests for cleanup of backed up dependencies
14177 	 */
14178 	ACQUIRE_GBLLOCK(&lk);
14179 	if (req_clear_inodedeps) {
14180 		req_clear_inodedeps -= 1;
14181 		FREE_GBLLOCK(&lk);
14182 		clear_inodedeps(mp);
14183 		ACQUIRE_GBLLOCK(&lk);
14184 		wakeup(&proc_waiting);
14185 	}
14186 	if (req_clear_remove) {
14187 		req_clear_remove -= 1;
14188 		FREE_GBLLOCK(&lk);
14189 		clear_remove(mp);
14190 		ACQUIRE_GBLLOCK(&lk);
14191 		wakeup(&proc_waiting);
14192 	}
14193 	FREE_GBLLOCK(&lk);
14194 }
14195 
14196 /*
14197  * Flush out a directory with at least one removal dependency in an effort to
14198  * reduce the number of dirrem, freefile, and freeblks dependency structures.
14199  */
14200 static void
14201 clear_remove(mp)
14202 	struct mount *mp;
14203 {
14204 	struct pagedep_hashhead *pagedephd;
14205 	struct pagedep *pagedep;
14206 	struct ufsmount *ump;
14207 	struct vnode *vp;
14208 	struct bufobj *bo;
14209 	int error, cnt;
14210 	ino_t ino;
14211 
14212 	ump = VFSTOUFS(mp);
14213 	LOCK_OWNED(ump);
14214 
14215 	for (cnt = 0; cnt <= ump->pagedep_hash_size; cnt++) {
14216 		pagedephd = &ump->pagedep_hashtbl[ump->pagedep_nextclean++];
14217 		if (ump->pagedep_nextclean > ump->pagedep_hash_size)
14218 			ump->pagedep_nextclean = 0;
14219 		LIST_FOREACH(pagedep, pagedephd, pd_hash) {
14220 			if (LIST_EMPTY(&pagedep->pd_dirremhd))
14221 				continue;
14222 			ino = pagedep->pd_ino;
14223 			if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14224 				continue;
14225 			FREE_LOCK(ump);
14226 
14227 			/*
14228 			 * Let unmount clear deps
14229 			 */
14230 			error = vfs_busy(mp, MBF_NOWAIT);
14231 			if (error != 0)
14232 				goto finish_write;
14233 			error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14234 			     FFSV_FORCEINSMQ);
14235 			vfs_unbusy(mp);
14236 			if (error != 0) {
14237 				softdep_error("clear_remove: vget", error);
14238 				goto finish_write;
14239 			}
14240 			MPASS(VTOI(vp)->i_mode != 0);
14241 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14242 				softdep_error("clear_remove: fsync", error);
14243 			bo = &vp->v_bufobj;
14244 			BO_LOCK(bo);
14245 			drain_output(vp);
14246 			BO_UNLOCK(bo);
14247 			vput(vp);
14248 		finish_write:
14249 			vn_finished_write(mp);
14250 			ACQUIRE_LOCK(ump);
14251 			return;
14252 		}
14253 	}
14254 }
14255 
14256 /*
14257  * Clear out a block of dirty inodes in an effort to reduce
14258  * the number of inodedep dependency structures.
14259  */
14260 static void
14261 clear_inodedeps(mp)
14262 	struct mount *mp;
14263 {
14264 	struct inodedep_hashhead *inodedephd;
14265 	struct inodedep *inodedep;
14266 	struct ufsmount *ump;
14267 	struct vnode *vp;
14268 	struct fs *fs;
14269 	int error, cnt;
14270 	ino_t firstino, lastino, ino;
14271 
14272 	ump = VFSTOUFS(mp);
14273 	fs = ump->um_fs;
14274 	LOCK_OWNED(ump);
14275 	/*
14276 	 * Pick a random inode dependency to be cleared.
14277 	 * We will then gather up all the inodes in its block
14278 	 * that have dependencies and flush them out.
14279 	 */
14280 	for (cnt = 0; cnt <= ump->inodedep_hash_size; cnt++) {
14281 		inodedephd = &ump->inodedep_hashtbl[ump->inodedep_nextclean++];
14282 		if (ump->inodedep_nextclean > ump->inodedep_hash_size)
14283 			ump->inodedep_nextclean = 0;
14284 		if ((inodedep = LIST_FIRST(inodedephd)) != NULL)
14285 			break;
14286 	}
14287 	if (inodedep == NULL)
14288 		return;
14289 	/*
14290 	 * Find the last inode in the block with dependencies.
14291 	 */
14292 	firstino = rounddown2(inodedep->id_ino, INOPB(fs));
14293 	for (lastino = firstino + INOPB(fs) - 1; lastino > firstino; lastino--)
14294 		if (inodedep_lookup(mp, lastino, 0, &inodedep) != 0)
14295 			break;
14296 	/*
14297 	 * Asynchronously push all but the last inode with dependencies.
14298 	 * Synchronously push the last inode with dependencies to ensure
14299 	 * that the inode block gets written to free up the inodedeps.
14300 	 */
14301 	for (ino = firstino; ino <= lastino; ino++) {
14302 		if (inodedep_lookup(mp, ino, 0, &inodedep) == 0)
14303 			continue;
14304 		if (vn_start_write(NULL, &mp, V_NOWAIT) != 0)
14305 			continue;
14306 		FREE_LOCK(ump);
14307 		error = vfs_busy(mp, MBF_NOWAIT); /* Let unmount clear deps */
14308 		if (error != 0) {
14309 			vn_finished_write(mp);
14310 			ACQUIRE_LOCK(ump);
14311 			return;
14312 		}
14313 		if ((error = ffs_vgetf(mp, ino, LK_EXCLUSIVE, &vp,
14314 		    FFSV_FORCEINSMQ)) != 0) {
14315 			softdep_error("clear_inodedeps: vget", error);
14316 			vfs_unbusy(mp);
14317 			vn_finished_write(mp);
14318 			ACQUIRE_LOCK(ump);
14319 			return;
14320 		}
14321 		vfs_unbusy(mp);
14322 		if (VTOI(vp)->i_mode == 0) {
14323 			vgone(vp);
14324 		} else if (ino == lastino) {
14325 			do {
14326 				error = ffs_syncvnode(vp, MNT_WAIT, 0);
14327 			} while (error == ERELOOKUP);
14328 			if (error != 0)
14329 				softdep_error("clear_inodedeps: fsync1", error);
14330 		} else {
14331 			if ((error = ffs_syncvnode(vp, MNT_NOWAIT, 0)))
14332 				softdep_error("clear_inodedeps: fsync2", error);
14333 			BO_LOCK(&vp->v_bufobj);
14334 			drain_output(vp);
14335 			BO_UNLOCK(&vp->v_bufobj);
14336 		}
14337 		vput(vp);
14338 		vn_finished_write(mp);
14339 		ACQUIRE_LOCK(ump);
14340 	}
14341 }
14342 
14343 void
14344 softdep_buf_append(bp, wkhd)
14345 	struct buf *bp;
14346 	struct workhead *wkhd;
14347 {
14348 	struct worklist *wk;
14349 	struct ufsmount *ump;
14350 
14351 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14352 		return;
14353 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14354 	    ("softdep_buf_append called on non-softdep filesystem"));
14355 	ump = VFSTOUFS(wk->wk_mp);
14356 	ACQUIRE_LOCK(ump);
14357 	while ((wk = LIST_FIRST(wkhd)) != NULL) {
14358 		WORKLIST_REMOVE(wk);
14359 		WORKLIST_INSERT(&bp->b_dep, wk);
14360 	}
14361 	FREE_LOCK(ump);
14362 
14363 }
14364 
14365 void
14366 softdep_inode_append(ip, cred, wkhd)
14367 	struct inode *ip;
14368 	struct ucred *cred;
14369 	struct workhead *wkhd;
14370 {
14371 	struct buf *bp;
14372 	struct fs *fs;
14373 	struct ufsmount *ump;
14374 	int error;
14375 
14376 	ump = ITOUMP(ip);
14377 	KASSERT(MOUNTEDSOFTDEP(UFSTOVFS(ump)) != 0,
14378 	    ("softdep_inode_append called on non-softdep filesystem"));
14379 	fs = ump->um_fs;
14380 	error = bread(ump->um_devvp, fsbtodb(fs, ino_to_fsba(fs, ip->i_number)),
14381 	    (int)fs->fs_bsize, cred, &bp);
14382 	if (error) {
14383 		bqrelse(bp);
14384 		softdep_freework(wkhd);
14385 		return;
14386 	}
14387 	softdep_buf_append(bp, wkhd);
14388 	bqrelse(bp);
14389 }
14390 
14391 void
14392 softdep_freework(wkhd)
14393 	struct workhead *wkhd;
14394 {
14395 	struct worklist *wk;
14396 	struct ufsmount *ump;
14397 
14398 	if ((wk = LIST_FIRST(wkhd)) == NULL)
14399 		return;
14400 	KASSERT(MOUNTEDSOFTDEP(wk->wk_mp) != 0,
14401 	    ("softdep_freework called on non-softdep filesystem"));
14402 	ump = VFSTOUFS(wk->wk_mp);
14403 	ACQUIRE_LOCK(ump);
14404 	handle_jwork(wkhd);
14405 	FREE_LOCK(ump);
14406 }
14407 
14408 static struct ufsmount *
14409 softdep_bp_to_mp(bp)
14410 	struct buf *bp;
14411 {
14412 	struct mount *mp;
14413 	struct vnode *vp;
14414 
14415 	if (LIST_EMPTY(&bp->b_dep))
14416 		return (NULL);
14417 	vp = bp->b_vp;
14418 	KASSERT(vp != NULL,
14419 	    ("%s, buffer with dependencies lacks vnode", __func__));
14420 
14421 	/*
14422 	 * The ump mount point is stable after we get a correct
14423 	 * pointer, since bp is locked and this prevents unmount from
14424 	 * proceeding.  But to get to it, we cannot dereference bp->b_dep
14425 	 * head wk_mp, because we do not yet own SU ump lock and
14426 	 * workitem might be freed while dereferenced.
14427 	 */
14428 retry:
14429 	switch (vp->v_type) {
14430 	case VCHR:
14431 		VI_LOCK(vp);
14432 		mp = vp->v_type == VCHR ? vp->v_rdev->si_mountpt : NULL;
14433 		VI_UNLOCK(vp);
14434 		if (mp == NULL)
14435 			goto retry;
14436 		break;
14437 	case VREG:
14438 	case VDIR:
14439 	case VLNK:
14440 	case VFIFO:
14441 	case VSOCK:
14442 		mp = vp->v_mount;
14443 		break;
14444 	case VBLK:
14445 		vn_printf(vp, "softdep_bp_to_mp: unexpected block device\n");
14446 		/* FALLTHROUGH */
14447 	case VNON:
14448 	case VBAD:
14449 	case VMARKER:
14450 		mp = NULL;
14451 		break;
14452 	default:
14453 		vn_printf(vp, "unknown vnode type");
14454 		mp = NULL;
14455 		break;
14456 	}
14457 	return (VFSTOUFS(mp));
14458 }
14459 
14460 /*
14461  * Function to determine if the buffer has outstanding dependencies
14462  * that will cause a roll-back if the buffer is written. If wantcount
14463  * is set, return number of dependencies, otherwise just yes or no.
14464  */
14465 static int
14466 softdep_count_dependencies(bp, wantcount)
14467 	struct buf *bp;
14468 	int wantcount;
14469 {
14470 	struct worklist *wk;
14471 	struct ufsmount *ump;
14472 	struct bmsafemap *bmsafemap;
14473 	struct freework *freework;
14474 	struct inodedep *inodedep;
14475 	struct indirdep *indirdep;
14476 	struct freeblks *freeblks;
14477 	struct allocindir *aip;
14478 	struct pagedep *pagedep;
14479 	struct dirrem *dirrem;
14480 	struct newblk *newblk;
14481 	struct mkdir *mkdir;
14482 	struct diradd *dap;
14483 	int i, retval;
14484 
14485 	ump = softdep_bp_to_mp(bp);
14486 	if (ump == NULL)
14487 		return (0);
14488 	retval = 0;
14489 	ACQUIRE_LOCK(ump);
14490 	LIST_FOREACH(wk, &bp->b_dep, wk_list) {
14491 		switch (wk->wk_type) {
14492 		case D_INODEDEP:
14493 			inodedep = WK_INODEDEP(wk);
14494 			if ((inodedep->id_state & DEPCOMPLETE) == 0) {
14495 				/* bitmap allocation dependency */
14496 				retval += 1;
14497 				if (!wantcount)
14498 					goto out;
14499 			}
14500 			if (TAILQ_FIRST(&inodedep->id_inoupdt)) {
14501 				/* direct block pointer dependency */
14502 				retval += 1;
14503 				if (!wantcount)
14504 					goto out;
14505 			}
14506 			if (TAILQ_FIRST(&inodedep->id_extupdt)) {
14507 				/* direct block pointer dependency */
14508 				retval += 1;
14509 				if (!wantcount)
14510 					goto out;
14511 			}
14512 			if (TAILQ_FIRST(&inodedep->id_inoreflst)) {
14513 				/* Add reference dependency. */
14514 				retval += 1;
14515 				if (!wantcount)
14516 					goto out;
14517 			}
14518 			continue;
14519 
14520 		case D_INDIRDEP:
14521 			indirdep = WK_INDIRDEP(wk);
14522 
14523 			TAILQ_FOREACH(freework, &indirdep->ir_trunc, fw_next) {
14524 				/* indirect truncation dependency */
14525 				retval += 1;
14526 				if (!wantcount)
14527 					goto out;
14528 			}
14529 
14530 			LIST_FOREACH(aip, &indirdep->ir_deplisthd, ai_next) {
14531 				/* indirect block pointer dependency */
14532 				retval += 1;
14533 				if (!wantcount)
14534 					goto out;
14535 			}
14536 			continue;
14537 
14538 		case D_PAGEDEP:
14539 			pagedep = WK_PAGEDEP(wk);
14540 			LIST_FOREACH(dirrem, &pagedep->pd_dirremhd, dm_next) {
14541 				if (LIST_FIRST(&dirrem->dm_jremrefhd)) {
14542 					/* Journal remove ref dependency. */
14543 					retval += 1;
14544 					if (!wantcount)
14545 						goto out;
14546 				}
14547 			}
14548 			for (i = 0; i < DAHASHSZ; i++) {
14549 				LIST_FOREACH(dap, &pagedep->pd_diraddhd[i], da_pdlist) {
14550 					/* directory entry dependency */
14551 					retval += 1;
14552 					if (!wantcount)
14553 						goto out;
14554 				}
14555 			}
14556 			continue;
14557 
14558 		case D_BMSAFEMAP:
14559 			bmsafemap = WK_BMSAFEMAP(wk);
14560 			if (LIST_FIRST(&bmsafemap->sm_jaddrefhd)) {
14561 				/* Add reference dependency. */
14562 				retval += 1;
14563 				if (!wantcount)
14564 					goto out;
14565 			}
14566 			if (LIST_FIRST(&bmsafemap->sm_jnewblkhd)) {
14567 				/* Allocate block dependency. */
14568 				retval += 1;
14569 				if (!wantcount)
14570 					goto out;
14571 			}
14572 			continue;
14573 
14574 		case D_FREEBLKS:
14575 			freeblks = WK_FREEBLKS(wk);
14576 			if (LIST_FIRST(&freeblks->fb_jblkdephd)) {
14577 				/* Freeblk journal dependency. */
14578 				retval += 1;
14579 				if (!wantcount)
14580 					goto out;
14581 			}
14582 			continue;
14583 
14584 		case D_ALLOCDIRECT:
14585 		case D_ALLOCINDIR:
14586 			newblk = WK_NEWBLK(wk);
14587 			if (newblk->nb_jnewblk) {
14588 				/* Journal allocate dependency. */
14589 				retval += 1;
14590 				if (!wantcount)
14591 					goto out;
14592 			}
14593 			continue;
14594 
14595 		case D_MKDIR:
14596 			mkdir = WK_MKDIR(wk);
14597 			if (mkdir->md_jaddref) {
14598 				/* Journal reference dependency. */
14599 				retval += 1;
14600 				if (!wantcount)
14601 					goto out;
14602 			}
14603 			continue;
14604 
14605 		case D_FREEWORK:
14606 		case D_FREEDEP:
14607 		case D_JSEGDEP:
14608 		case D_JSEG:
14609 		case D_SBDEP:
14610 			/* never a dependency on these blocks */
14611 			continue;
14612 
14613 		default:
14614 			panic("softdep_count_dependencies: Unexpected type %s",
14615 			    TYPENAME(wk->wk_type));
14616 			/* NOTREACHED */
14617 		}
14618 	}
14619 out:
14620 	FREE_LOCK(ump);
14621 	return (retval);
14622 }
14623 
14624 /*
14625  * Acquire exclusive access to a buffer.
14626  * Must be called with a locked mtx parameter.
14627  * Return acquired buffer or NULL on failure.
14628  */
14629 static struct buf *
14630 getdirtybuf(bp, lock, waitfor)
14631 	struct buf *bp;
14632 	struct rwlock *lock;
14633 	int waitfor;
14634 {
14635 	int error;
14636 
14637 	if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT, NULL) != 0) {
14638 		if (waitfor != MNT_WAIT)
14639 			return (NULL);
14640 		error = BUF_LOCK(bp,
14641 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, lock);
14642 		/*
14643 		 * Even if we successfully acquire bp here, we have dropped
14644 		 * lock, which may violates our guarantee.
14645 		 */
14646 		if (error == 0)
14647 			BUF_UNLOCK(bp);
14648 		else if (error != ENOLCK)
14649 			panic("getdirtybuf: inconsistent lock: %d", error);
14650 		rw_wlock(lock);
14651 		return (NULL);
14652 	}
14653 	if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14654 		if (lock != BO_LOCKPTR(bp->b_bufobj) && waitfor == MNT_WAIT) {
14655 			rw_wunlock(lock);
14656 			BO_LOCK(bp->b_bufobj);
14657 			BUF_UNLOCK(bp);
14658 			if ((bp->b_vflags & BV_BKGRDINPROG) != 0) {
14659 				bp->b_vflags |= BV_BKGRDWAIT;
14660 				msleep(&bp->b_xflags, BO_LOCKPTR(bp->b_bufobj),
14661 				       PRIBIO | PDROP, "getbuf", 0);
14662 			} else
14663 				BO_UNLOCK(bp->b_bufobj);
14664 			rw_wlock(lock);
14665 			return (NULL);
14666 		}
14667 		BUF_UNLOCK(bp);
14668 		if (waitfor != MNT_WAIT)
14669 			return (NULL);
14670 #ifdef DEBUG_VFS_LOCKS
14671 		if (bp->b_vp->v_type != VCHR)
14672 			ASSERT_BO_WLOCKED(bp->b_bufobj);
14673 #endif
14674 		bp->b_vflags |= BV_BKGRDWAIT;
14675 		rw_sleep(&bp->b_xflags, lock, PRIBIO, "getbuf", 0);
14676 		return (NULL);
14677 	}
14678 	if ((bp->b_flags & B_DELWRI) == 0) {
14679 		BUF_UNLOCK(bp);
14680 		return (NULL);
14681 	}
14682 	bremfree(bp);
14683 	return (bp);
14684 }
14685 
14686 /*
14687  * Check if it is safe to suspend the file system now.  On entry,
14688  * the vnode interlock for devvp should be held.  Return 0 with
14689  * the mount interlock held if the file system can be suspended now,
14690  * otherwise return EAGAIN with the mount interlock held.
14691  */
14692 int
14693 softdep_check_suspend(struct mount *mp,
14694 		      struct vnode *devvp,
14695 		      int softdep_depcnt,
14696 		      int softdep_accdepcnt,
14697 		      int secondary_writes,
14698 		      int secondary_accwrites)
14699 {
14700 	struct bufobj *bo;
14701 	struct ufsmount *ump;
14702 	struct inodedep *inodedep;
14703 	int error, unlinked;
14704 
14705 	bo = &devvp->v_bufobj;
14706 	ASSERT_BO_WLOCKED(bo);
14707 
14708 	/*
14709 	 * If we are not running with soft updates, then we need only
14710 	 * deal with secondary writes as we try to suspend.
14711 	 */
14712 	if (MOUNTEDSOFTDEP(mp) == 0) {
14713 		MNT_ILOCK(mp);
14714 		while (mp->mnt_secondary_writes != 0) {
14715 			BO_UNLOCK(bo);
14716 			msleep(&mp->mnt_secondary_writes, MNT_MTX(mp),
14717 			    (PUSER - 1) | PDROP, "secwr", 0);
14718 			BO_LOCK(bo);
14719 			MNT_ILOCK(mp);
14720 		}
14721 
14722 		/*
14723 		 * Reasons for needing more work before suspend:
14724 		 * - Dirty buffers on devvp.
14725 		 * - Secondary writes occurred after start of vnode sync loop
14726 		 */
14727 		error = 0;
14728 		if (bo->bo_numoutput > 0 ||
14729 		    bo->bo_dirty.bv_cnt > 0 ||
14730 		    secondary_writes != 0 ||
14731 		    mp->mnt_secondary_writes != 0 ||
14732 		    secondary_accwrites != mp->mnt_secondary_accwrites)
14733 			error = EAGAIN;
14734 		BO_UNLOCK(bo);
14735 		return (error);
14736 	}
14737 
14738 	/*
14739 	 * If we are running with soft updates, then we need to coordinate
14740 	 * with them as we try to suspend.
14741 	 */
14742 	ump = VFSTOUFS(mp);
14743 	for (;;) {
14744 		if (!TRY_ACQUIRE_LOCK(ump)) {
14745 			BO_UNLOCK(bo);
14746 			ACQUIRE_LOCK(ump);
14747 			FREE_LOCK(ump);
14748 			BO_LOCK(bo);
14749 			continue;
14750 		}
14751 		MNT_ILOCK(mp);
14752 		if (mp->mnt_secondary_writes != 0) {
14753 			FREE_LOCK(ump);
14754 			BO_UNLOCK(bo);
14755 			msleep(&mp->mnt_secondary_writes,
14756 			       MNT_MTX(mp),
14757 			       (PUSER - 1) | PDROP, "secwr", 0);
14758 			BO_LOCK(bo);
14759 			continue;
14760 		}
14761 		break;
14762 	}
14763 
14764 	unlinked = 0;
14765 	if (MOUNTEDSUJ(mp)) {
14766 		for (inodedep = TAILQ_FIRST(&ump->softdep_unlinked);
14767 		    inodedep != NULL;
14768 		    inodedep = TAILQ_NEXT(inodedep, id_unlinked)) {
14769 			if ((inodedep->id_state & (UNLINKED | UNLINKLINKS |
14770 			    UNLINKONLIST)) != (UNLINKED | UNLINKLINKS |
14771 			    UNLINKONLIST) ||
14772 			    !check_inodedep_free(inodedep))
14773 				continue;
14774 			unlinked++;
14775 		}
14776 	}
14777 
14778 	/*
14779 	 * Reasons for needing more work before suspend:
14780 	 * - Dirty buffers on devvp.
14781 	 * - Softdep activity occurred after start of vnode sync loop
14782 	 * - Secondary writes occurred after start of vnode sync loop
14783 	 */
14784 	error = 0;
14785 	if (bo->bo_numoutput > 0 ||
14786 	    bo->bo_dirty.bv_cnt > 0 ||
14787 	    softdep_depcnt != unlinked ||
14788 	    ump->softdep_deps != unlinked ||
14789 	    softdep_accdepcnt != ump->softdep_accdeps ||
14790 	    secondary_writes != 0 ||
14791 	    mp->mnt_secondary_writes != 0 ||
14792 	    secondary_accwrites != mp->mnt_secondary_accwrites)
14793 		error = EAGAIN;
14794 	FREE_LOCK(ump);
14795 	BO_UNLOCK(bo);
14796 	return (error);
14797 }
14798 
14799 /*
14800  * Get the number of dependency structures for the file system, both
14801  * the current number and the total number allocated.  These will
14802  * later be used to detect that softdep processing has occurred.
14803  */
14804 void
14805 softdep_get_depcounts(struct mount *mp,
14806 		      int *softdep_depsp,
14807 		      int *softdep_accdepsp)
14808 {
14809 	struct ufsmount *ump;
14810 
14811 	if (MOUNTEDSOFTDEP(mp) == 0) {
14812 		*softdep_depsp = 0;
14813 		*softdep_accdepsp = 0;
14814 		return;
14815 	}
14816 	ump = VFSTOUFS(mp);
14817 	ACQUIRE_LOCK(ump);
14818 	*softdep_depsp = ump->softdep_deps;
14819 	*softdep_accdepsp = ump->softdep_accdeps;
14820 	FREE_LOCK(ump);
14821 }
14822 
14823 /*
14824  * Wait for pending output on a vnode to complete.
14825  */
14826 static void
14827 drain_output(vp)
14828 	struct vnode *vp;
14829 {
14830 
14831 	ASSERT_VOP_LOCKED(vp, "drain_output");
14832 	(void)bufobj_wwait(&vp->v_bufobj, 0, 0);
14833 }
14834 
14835 /*
14836  * Called whenever a buffer that is being invalidated or reallocated
14837  * contains dependencies. This should only happen if an I/O error has
14838  * occurred. The routine is called with the buffer locked.
14839  */
14840 static void
14841 softdep_deallocate_dependencies(bp)
14842 	struct buf *bp;
14843 {
14844 
14845 	if ((bp->b_ioflags & BIO_ERROR) == 0)
14846 		panic("softdep_deallocate_dependencies: dangling deps");
14847 	if (bp->b_vp != NULL && bp->b_vp->v_mount != NULL)
14848 		softdep_error(bp->b_vp->v_mount->mnt_stat.f_mntonname, bp->b_error);
14849 	else
14850 		printf("softdep_deallocate_dependencies: "
14851 		    "got error %d while accessing filesystem\n", bp->b_error);
14852 	if (bp->b_error != ENXIO)
14853 		panic("softdep_deallocate_dependencies: unrecovered I/O error");
14854 }
14855 
14856 /*
14857  * Function to handle asynchronous write errors in the filesystem.
14858  */
14859 static void
14860 softdep_error(func, error)
14861 	char *func;
14862 	int error;
14863 {
14864 
14865 	/* XXX should do something better! */
14866 	printf("%s: got error %d while accessing filesystem\n", func, error);
14867 }
14868 
14869 #ifdef DDB
14870 
14871 /* exported to ffs_vfsops.c */
14872 extern void db_print_ffs(struct ufsmount *ump);
14873 void
14874 db_print_ffs(struct ufsmount *ump)
14875 {
14876 	db_printf("mp %p (%s) devvp %p\n", ump->um_mountp,
14877 	    ump->um_mountp->mnt_stat.f_mntonname, ump->um_devvp);
14878 	db_printf("    fs %p su_wl %d su_deps %d su_req %d\n",
14879 	    ump->um_fs, ump->softdep_on_worklist,
14880 	    ump->softdep_deps, ump->softdep_req);
14881 }
14882 
14883 static void
14884 worklist_print(struct worklist *wk, int verbose)
14885 {
14886 
14887 	if (!verbose) {
14888 		db_printf("%s: %p state 0x%b\n", TYPENAME(wk->wk_type), wk,
14889 		    (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS);
14890 		return;
14891 	}
14892 	db_printf("worklist: %p type %s state 0x%b next %p\n    ", wk,
14893 	    TYPENAME(wk->wk_type), (u_int)wk->wk_state, PRINT_SOFTDEP_FLAGS,
14894 	    LIST_NEXT(wk, wk_list));
14895 	db_print_ffs(VFSTOUFS(wk->wk_mp));
14896 }
14897 
14898 static void
14899 inodedep_print(struct inodedep *inodedep, int verbose)
14900 {
14901 
14902 	worklist_print(&inodedep->id_list, 0);
14903 	db_printf("    fs %p ino %jd inoblk %jd delta %jd nlink %jd\n",
14904 	    inodedep->id_fs,
14905 	    (intmax_t)inodedep->id_ino,
14906 	    (intmax_t)fsbtodb(inodedep->id_fs,
14907 	        ino_to_fsba(inodedep->id_fs, inodedep->id_ino)),
14908 	    (intmax_t)inodedep->id_nlinkdelta,
14909 	    (intmax_t)inodedep->id_savednlink);
14910 
14911 	if (verbose == 0)
14912 		return;
14913 
14914 	db_printf("    bmsafemap %p, mkdiradd %p, inoreflst %p\n",
14915 	    inodedep->id_bmsafemap,
14916 	    inodedep->id_mkdiradd,
14917 	    TAILQ_FIRST(&inodedep->id_inoreflst));
14918 	db_printf("    dirremhd %p, pendinghd %p, bufwait %p\n",
14919 	    LIST_FIRST(&inodedep->id_dirremhd),
14920 	    LIST_FIRST(&inodedep->id_pendinghd),
14921 	    LIST_FIRST(&inodedep->id_bufwait));
14922 	db_printf("    inowait %p, inoupdt %p, newinoupdt %p\n",
14923 	    LIST_FIRST(&inodedep->id_inowait),
14924 	    TAILQ_FIRST(&inodedep->id_inoupdt),
14925 	    TAILQ_FIRST(&inodedep->id_newinoupdt));
14926 	db_printf("    extupdt %p, newextupdt %p, freeblklst %p\n",
14927 	    TAILQ_FIRST(&inodedep->id_extupdt),
14928 	    TAILQ_FIRST(&inodedep->id_newextupdt),
14929 	    TAILQ_FIRST(&inodedep->id_freeblklst));
14930 	db_printf("    saveino %p, savedsize %jd, savedextsize %jd\n",
14931 	    inodedep->id_savedino1,
14932 	    (intmax_t)inodedep->id_savedsize,
14933 	    (intmax_t)inodedep->id_savedextsize);
14934 }
14935 
14936 static void
14937 newblk_print(struct newblk *nbp)
14938 {
14939 
14940 	worklist_print(&nbp->nb_list, 0);
14941 	db_printf("    newblkno %jd\n", (intmax_t)nbp->nb_newblkno);
14942 	db_printf("    jnewblk %p, bmsafemap %p, freefrag %p\n",
14943 	    &nbp->nb_jnewblk,
14944 	    &nbp->nb_bmsafemap,
14945 	    &nbp->nb_freefrag);
14946 	db_printf("    indirdeps %p, newdirblk %p, jwork %p\n",
14947 	    LIST_FIRST(&nbp->nb_indirdeps),
14948 	    LIST_FIRST(&nbp->nb_newdirblk),
14949 	    LIST_FIRST(&nbp->nb_jwork));
14950 }
14951 
14952 static void
14953 allocdirect_print(struct allocdirect *adp)
14954 {
14955 
14956 	newblk_print(&adp->ad_block);
14957 	db_printf("    oldblkno %jd, oldsize %ld, newsize %ld\n",
14958 	    adp->ad_oldblkno, adp->ad_oldsize, adp->ad_newsize);
14959 	db_printf("    offset %d, inodedep %p\n",
14960 	    adp->ad_offset, adp->ad_inodedep);
14961 }
14962 
14963 static void
14964 allocindir_print(struct allocindir *aip)
14965 {
14966 
14967 	newblk_print(&aip->ai_block);
14968 	db_printf("    oldblkno %jd, lbn %jd\n",
14969 	    (intmax_t)aip->ai_oldblkno, (intmax_t)aip->ai_lbn);
14970 	db_printf("    offset %d, indirdep %p\n",
14971 	    aip->ai_offset, aip->ai_indirdep);
14972 }
14973 
14974 static void
14975 mkdir_print(struct mkdir *mkdir)
14976 {
14977 
14978 	worklist_print(&mkdir->md_list, 0);
14979 	db_printf("    diradd %p, jaddref %p, buf %p\n",
14980 		mkdir->md_diradd, mkdir->md_jaddref, mkdir->md_buf);
14981 }
14982 
14983 DB_SHOW_COMMAND(sd_inodedep, db_show_sd_inodedep)
14984 {
14985 
14986 	if (have_addr == 0) {
14987 		db_printf("inodedep address required\n");
14988 		return;
14989 	}
14990 	inodedep_print((struct inodedep*)addr, 1);
14991 }
14992 
14993 DB_SHOW_COMMAND(sd_allinodedeps, db_show_sd_allinodedeps)
14994 {
14995 	struct inodedep_hashhead *inodedephd;
14996 	struct inodedep *inodedep;
14997 	struct ufsmount *ump;
14998 	int cnt;
14999 
15000 	if (have_addr == 0) {
15001 		db_printf("ufsmount address required\n");
15002 		return;
15003 	}
15004 	ump = (struct ufsmount *)addr;
15005 	for (cnt = 0; cnt < ump->inodedep_hash_size; cnt++) {
15006 		inodedephd = &ump->inodedep_hashtbl[cnt];
15007 		LIST_FOREACH(inodedep, inodedephd, id_hash) {
15008 			inodedep_print(inodedep, 0);
15009 		}
15010 	}
15011 }
15012 
15013 DB_SHOW_COMMAND(sd_worklist, db_show_sd_worklist)
15014 {
15015 
15016 	if (have_addr == 0) {
15017 		db_printf("worklist address required\n");
15018 		return;
15019 	}
15020 	worklist_print((struct worklist *)addr, 1);
15021 }
15022 
15023 DB_SHOW_COMMAND(sd_workhead, db_show_sd_workhead)
15024 {
15025 	struct worklist *wk;
15026 	struct workhead *wkhd;
15027 
15028 	if (have_addr == 0) {
15029 		db_printf("worklist address required "
15030 		    "(for example value in bp->b_dep)\n");
15031 		return;
15032 	}
15033 	/*
15034 	 * We often do not have the address of the worklist head but
15035 	 * instead a pointer to its first entry (e.g., we have the
15036 	 * contents of bp->b_dep rather than &bp->b_dep). But the back
15037 	 * pointer of bp->b_dep will point at the head of the list, so
15038 	 * we cheat and use that instead. If we are in the middle of
15039 	 * a list we will still get the same result, so nothing
15040 	 * unexpected will result.
15041 	 */
15042 	wk = (struct worklist *)addr;
15043 	if (wk == NULL)
15044 		return;
15045 	wkhd = (struct workhead *)wk->wk_list.le_prev;
15046 	LIST_FOREACH(wk, wkhd, wk_list) {
15047 		switch(wk->wk_type) {
15048 		case D_INODEDEP:
15049 			inodedep_print(WK_INODEDEP(wk), 0);
15050 			continue;
15051 		case D_ALLOCDIRECT:
15052 			allocdirect_print(WK_ALLOCDIRECT(wk));
15053 			continue;
15054 		case D_ALLOCINDIR:
15055 			allocindir_print(WK_ALLOCINDIR(wk));
15056 			continue;
15057 		case D_MKDIR:
15058 			mkdir_print(WK_MKDIR(wk));
15059 			continue;
15060 		default:
15061 			worklist_print(wk, 0);
15062 			continue;
15063 		}
15064 	}
15065 }
15066 
15067 DB_SHOW_COMMAND(sd_mkdir, db_show_sd_mkdir)
15068 {
15069 	if (have_addr == 0) {
15070 		db_printf("mkdir address required\n");
15071 		return;
15072 	}
15073 	mkdir_print((struct mkdir *)addr);
15074 }
15075 
15076 DB_SHOW_COMMAND(sd_mkdir_list, db_show_sd_mkdir_list)
15077 {
15078 	struct mkdirlist *mkdirlisthd;
15079 	struct mkdir *mkdir;
15080 
15081 	if (have_addr == 0) {
15082 		db_printf("mkdir listhead address required\n");
15083 		return;
15084 	}
15085 	mkdirlisthd = (struct mkdirlist *)addr;
15086 	LIST_FOREACH(mkdir, mkdirlisthd, md_mkdirs) {
15087 		mkdir_print(mkdir);
15088 		if (mkdir->md_diradd != NULL) {
15089 			db_printf("    ");
15090 			worklist_print(&mkdir->md_diradd->da_list, 0);
15091 		}
15092 		if (mkdir->md_jaddref != NULL) {
15093 			db_printf("    ");
15094 			worklist_print(&mkdir->md_jaddref->ja_list, 0);
15095 		}
15096 	}
15097 }
15098 
15099 DB_SHOW_COMMAND(sd_allocdirect, db_show_sd_allocdirect)
15100 {
15101 	if (have_addr == 0) {
15102 		db_printf("allocdirect address required\n");
15103 		return;
15104 	}
15105 	allocdirect_print((struct allocdirect *)addr);
15106 }
15107 
15108 DB_SHOW_COMMAND(sd_allocindir, db_show_sd_allocindir)
15109 {
15110 	if (have_addr == 0) {
15111 		db_printf("allocindir address required\n");
15112 		return;
15113 	}
15114 	allocindir_print((struct allocindir *)addr);
15115 }
15116 
15117 #endif /* DDB */
15118 
15119 #endif /* SOFTUPDATES */
15120